infra-kit 0.21.0 → 0.22.1

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 ym,e as Ar,f as Pm,g as Tt,h as Ms,i as xm,j as Tm,k as Cm,l as $m,m as Am,n as Om,o as Im,p as Dm,s as qa,t as Mm,u as Se}from"./chunk-LPGKGTVI.js";import{a as xp,b as Ie,c as Tp,d as Na,e as Cp,f as $p,g as Ap,h as Op,i as Dn,j as Ip,k as Dp,l as Np,m as _p,n as Mp,o as Nn,p as jp,q as Fp,r as Lp,s as Bp,t as _a,u as Ps,v as Rt,w as Up,x as xs,y as Vp}from"./chunk-XES5EOEE.js";import{a as oe,b as G,c as Pt,d as jn,e as Ba,f as Is,g as Ds,h as Ua,i as Fn,j as zt,k as Va,l as Ns,m as dm,n as Ln,o as Bn,p as Ga,q as Ja,r as Ka,s as km,u as Ha}from"./chunk-7A4LVTRJ.js";import{b as In,c as Ss,d as Da,e as bp,f as Es,g as Rp,i as Sp,k as Ep,m as ye,o as Pp}from"./chunk-AWFGP6GY.js";import{a as hm}from"./chunk-TVG47UHG.js";import{A as Vn,C as za,G as Xa,H as Za,a as k,b as E,c as bm,d as Rm,e as Xt,f as Sm,g as Zt,h as Em,i as Nm,j as Un,k as Ct,l as Or,m as Ye,n as js,o as $t,p as _m,q as Fs,r as jm,s as Fm,t as ze,x as Ya}from"./chunk-XSFASMOH.js";import{a as h,b as dt,c as pm,d as mm,e as I,f as _s,g as L,i as xt,j as Je,k as vm,l as Wa,m as wm}from"./chunk-HB3BDJFE.js";import{$ as La,A as Yp,B as zp,C as Xp,D as $s,E as As,F as De,G as _n,H as $r,I as Os,J as Zp,K as Qp,L as em,M as ja,N as Fa,O as tm,P as d,Q as Ne,R as z,S as v,T as Ge,U as rm,V as nm,W as om,X as im,Y as am,Z as St,_ as cm,a as Yt,aa as lm,b as $,ba as um,c as Wp,ca as H,d as _,da as W,e as ve,ea as Mn,f as J,fa as Et,g as Ts,ga as C,h as Gp,i as f,j as Jp,k as Cs,l as K,m as me,n as we,o as Kp,p as Ma,q as ne,r as Y,s as Tr,t as Hp,u as qe,v as fe,w as P,x as Re,y as Cr,z as qp}from"./chunk-PSC73DBX.js";import{a as sm}from"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-X7KY6GP5.js";import{a as Sr,b as ys,c as vs,d as On,e as hp,f as Er,g as ws,h as ks,i as yp,j as bs,k as Rs,l as vp,m as wp,n as ut,o as Pr,p as bt,q as ue,r as kp,s as xr}from"./chunk-I23MDR4X.js";import{a as fm,b as gm}from"./chunk-QWVLAZ6N.js";import M_,{Separator as sk}from"@inquirer/select";import{existsSync as j_,realpathSync as F_}from"node:fs";import{homedir as L_}from"node:os";import Oe from"node:process";import{fileURLToPath as ak}from"node:url";import $f from"node:process";import{z as je}from"zod";import Km from"node:fs";import Nr from"node:path";import{packageConfigSchema as Um}from"@slip-stream-kit/config/internal";import Vm from"node:fs/promises";import Ls from"node:path";import{pathToFileURL as hk}from"node:url";import{z as Wm}from"zod";import Lm from"node:path";var Wn=["frontend","backend","lib","e2e","mobile"],uk={ui:"frontend",api:"backend",tests:"e2e"},dk="mobile-app",pk=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],mk=(e,t)=>{let r=Lm.relative(t,e).split(Lm.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=uk[o];if(s)return s}return r.at(-1)===dk?"mobile":null},fk=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of pk)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Gn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??mk(e,t)??fk(r)??"lib";var At={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Bm=2e3,Qa={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Bm}} 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"},Jn={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"]},Kn=(e,t=At)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import gk from"node:fs/promises";var Ee=async e=>{try{return await gk.access(e),!0}catch{return!1}};var se="infra-kit.config.ts",Qt=async e=>{try{let t=await Vm.readFile(Ls.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},ec=async e=>{let t=await Vm.stat(e),o=(await import(`${hk(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${se} at ${e} has no default export`);return typeof o=="function"?await o():o},er=async e=>{let t=Ls.join(e,se);if(await Ee(t))try{let n=(await ec(t))?.type;return Wn.find(o=>o===n)}catch{return}},Hn=async(e,t=At)=>{let r=Ls.join(e,se);if(!await Ee(r))throw new Error(`${se} not found at ${r}`);let n=await ec(r),o=Um.safeParse(n);if(!o.success)throw new Error(`Invalid ${se} at ${r}: ${Wm.prettifyError(o.error)}`);return Kn(o.data,t)},Ir=async e=>{let t=Ls.join(e,se);if(!await Ee(t))return;let r=Um.safeParse(await ec(t));if(!r.success)throw new Error(`Invalid ${se} at ${t}: ${Wm.prettifyError(r.error)}`);return r.data};import Gm from"node:fs/promises";import Bs from"node:path";import yk from"yaml";var vk="pnpm-workspace.yaml",wk=async e=>(await Gm.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Bs.join(e,r.name)),kk=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await wk(n));continue}let o=Bs.join(n,t);await Ee(o)&&r.push(o)}return r},bk=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await kk(r,n);return r},Pe=async e=>{let t=await Gm.readFile(Bs.join(e,vk),"utf-8"),n=((yk.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await bk(e,s);for(let a of i)await Ee(Bs.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import qn from"node:path";var Yn=async e=>{let t=qn.resolve(e);for(;t!==qn.dirname(t);){if(await Ee(qn.join(t,"package.json")))return t;t=qn.dirname(t)}if(await Ee(qn.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var Xe=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Ot=(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}`:"")},tc=(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},Jm=(e,t,r)=>`${e}
2
+ import{c as ym,e as Or,f as Pm,g as Tt,h as Ms,i as xm,j as Tm,k as Cm,l as $m,m as Am,n as Om,o as Im,p as Dm,s as qa,t as Mm,u as Se}from"./chunk-7Y6W67EX.js";import{a as xp,b as Ie,c as Tp,d as Na,e as Cp,f as $p,g as Ap,h as Op,i as Dn,j as Ip,k as Dp,l as Np,m as _p,n as Mp,o as Nn,p as jp,q as Fp,r as Lp,s as Bp,t as _a,u as Ps,v as Rt,w as Up,x as xs,y as Vp}from"./chunk-XES5EOEE.js";import{a as oe,b as G,c as Pt,d as jn,e as Ba,f as Is,g as Ds,h as Ua,i as Fn,j as Xt,k as Va,l as Ns,m as dm,n as Ln,o as Bn,p as Ga,q as Ja,r as Ka,s as km,u as Ha}from"./chunk-7A4LVTRJ.js";import{b as In,c as Ss,d as Da,e as bp,f as Es,g as Rp,i as Sp,k as Ep,m as ye,o as Pp}from"./chunk-AWFGP6GY.js";import{a as hm}from"./chunk-TVG47UHG.js";import{A as Vn,C as za,G as Xa,H as Za,a as k,b as E,c as bm,d as Rm,e as Zt,f as Sm,g as Qt,h as Em,i as Nm,j as Un,k as Ct,l as Ir,m as Ye,n as js,o as $t,p as _m,q as Fs,r as jm,s as Fm,t as ze,x as Ya}from"./chunk-HNEK3XXI.js";import{a as h,b as dt,c as pm,d as mm,e as I,f as _s,g as L,i as xt,j as Je,k as vm,l as Wa,m as wm}from"./chunk-YUSKMGVU.js";import{$ as La,A as Yp,B as zp,C as Xp,D as $s,E as As,F as De,G as _n,H as Ar,I as Os,J as Zp,K as Qp,L as em,M as ja,N as Fa,O as tm,P as d,Q as Ne,R as X,S as v,T as Ge,U as rm,V as nm,W as om,X as im,Y as am,Z as St,_ as cm,a as zt,aa as lm,b as $,ba as um,c as Wp,ca as q,d as _,da as W,e as ve,ea as Mn,f as K,fa as Et,g as Ts,ga as C,h as Gp,i as f,j as Jp,k as Cs,l as H,m as pe,n as we,o as Kp,p as Ma,q as ne,r as z,s as Cr,t as Hp,u as qe,v as me,w as P,x as Re,y as $r,z as qp}from"./chunk-NVPU3RG2.js";import{a as sm}from"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-T5KOUOJY.js";import{a as Er,b as ys,c as vs,d as On,e as hp,f as Pr,g as ws,h as ks,i as yp,j as bs,k as Rs,l as vp,m as wp,n as ut,o as xr,p as bt,q as le,r as kp,s as Tr}from"./chunk-I23MDR4X.js";import{a as fm,b as gm}from"./chunk-QWVLAZ6N.js";import U_,{Separator as sk}from"@inquirer/select";import{existsSync as V_,realpathSync as W_}from"node:fs";import{homedir as G_}from"node:os";import Oe from"node:process";import{fileURLToPath as ak}from"node:url";import Af from"node:process";import{z as je}from"zod";import Hm from"node:fs";import Nr from"node:path";import{packageConfigSchema as Um}from"@slip-stream-kit/config/internal";import Vm from"node:fs/promises";import Ls from"node:path";import{pathToFileURL as hk}from"node:url";import{z as Wm}from"zod";import Lm from"node:path";var Wn=["frontend","backend","lib","e2e","mobile"],uk={ui:"frontend",api:"backend",tests:"e2e"},dk="mobile-app",pk=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],mk=(e,t)=>{let r=Lm.relative(t,e).split(Lm.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=uk[o];if(s)return s}return r.at(-1)===dk?"mobile":null},fk=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of pk)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Gn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??mk(e,t)??fk(r)??"lib";var At={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Bm=2e3,Qa={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Bm}} 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"},Jn={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"]},Kn=(e,t=At)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import gk from"node:fs/promises";var Ee=async e=>{try{return await gk.access(e),!0}catch{return!1}};var se="infra-kit.config.ts",er=async e=>{try{let t=await Vm.readFile(Ls.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},ec=async e=>{let t=await Vm.stat(e),o=(await import(`${hk(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${se} at ${e} has no default export`);return typeof o=="function"?await o():o},tr=async e=>{let t=Ls.join(e,se);if(await Ee(t))try{let n=(await ec(t))?.type;return Wn.find(o=>o===n)}catch{return}},Gm=e=>e,Hn=async(e,t=At)=>{let r=Ls.join(e,se);if(!await Ee(r))throw new Error(`${se} not found at ${r}`);let n=await ec(r),o=Um.safeParse(n);if(!o.success)throw new Error(`Invalid ${se} at ${r}: ${Wm.prettifyError(o.error)}`);return Kn(Gm(o.data),t)},Ot=async e=>{let t=Ls.join(e,se);if(!await Ee(t))return;let r=Um.safeParse(await ec(t));if(!r.success)throw new Error(`Invalid ${se} at ${t}: ${Wm.prettifyError(r.error)}`);return Gm(r.data)};import Jm from"node:fs/promises";import Bs from"node:path";import yk from"yaml";var vk="pnpm-workspace.yaml",wk=async e=>(await Jm.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Bs.join(e,r.name)),kk=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await wk(n));continue}let o=Bs.join(n,t);await Ee(o)&&r.push(o)}return r},bk=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await kk(r,n);return r},Pe=async e=>{let t=await Jm.readFile(Bs.join(e,vk),"utf-8"),n=((yk.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await bk(e,s);for(let a of i)await Ee(Bs.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import qn from"node:path";var Yn=async e=>{let t=qn.resolve(e);for(;t!==qn.dirname(t);){if(await Ee(qn.join(t,"package.json")))return t;t=qn.dirname(t)}if(await Ee(qn.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var Xe=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},It=(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}`:"")},tc=(e,t)=>{let r=e.indexOf(t);if(r===-1)return null;let o=e.slice(r+t.length).match(/^([^\s>]+)/);return o?o[1]:null},Km=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,Dr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Jm(r,t,n),i=Xe(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),u=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(u)}let c=(i?Ot(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,Dr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Km(r,t,n),i=Xe(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),u=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(u)}let c=(i?It(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var _e="<!-- infra-kit:begin -->",Ze="<!-- infra-kit:end -->",rc="<!-- infra-kit:version ",Qe="<!-- infra-kit:package:begin -->",pt="<!-- infra-kit:package:end -->",tr="<!-- infra-kit:package:version ";var Rk=e=>{let t=e.indexOf(Qe)+Qe.length;return e.slice(t,e.indexOf(pt))},Sk=e=>{let t=e.indexOf(tr);if(t===-1)return null;let r=e.slice(t+tr.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Wn.find(n=>n===r)??null},rr=e=>{if(e===null)return{state:"missing"};if(!Xe(e,Qe,pt))return e.includes(Qe)||e.includes(pt)?{state:"malformed"}:Xe(e,_e,Ze)?{state:"foreign-block"}:{state:"no-block"};let t=Rk(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=tc(t,tr),o=Sk(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Ek from"node:fs";var nr=e=>{try{return Ek.readFileSync(e,"utf-8")}catch{return null}};var Hm="pnpm-workspace.yaml",Pk="CLAUDE.md",oc=e=>{let t=Nr.resolve(e);for(;t!==Nr.dirname(t);){if(Km.existsSync(Nr.join(t,Hm)))return t;t=Nr.dirname(t)}return Km.existsSync(Nr.join(t,Hm))?t:null},nc=new Map,Us=()=>{nc.clear()},xk=async e=>{let t;try{t=await Pe(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Nr.join(r,Pk),o=nr(n);if(o!==null&&rr(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},_r=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=nc.get(e);if(t)return t;let r=await xk(e);return nc.set(e,r),r};import or from"node:fs";import It from"node:path";var qm=`---
8
+ `};var _e="<!-- infra-kit:begin -->",Ze="<!-- infra-kit:end -->",rc="<!-- infra-kit:version ",Qe="<!-- infra-kit:package:begin -->",pt="<!-- infra-kit:package:end -->",rr="<!-- infra-kit:package:version ";var Rk=e=>{let t=e.indexOf(Qe)+Qe.length;return e.slice(t,e.indexOf(pt))},Sk=e=>{let t=e.indexOf(rr);if(t===-1)return null;let r=e.slice(t+rr.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Wn.find(n=>n===r)??null},nr=e=>{if(e===null)return{state:"missing"};if(!Xe(e,Qe,pt))return e.includes(Qe)||e.includes(pt)?{state:"malformed"}:Xe(e,_e,Ze)?{state:"foreign-block"}:{state:"no-block"};let t=Rk(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=tc(t,rr),o=Sk(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Ek from"node:fs";var or=e=>{try{return Ek.readFileSync(e,"utf-8")}catch{return null}};var qm="pnpm-workspace.yaml",Pk="CLAUDE.md",oc=e=>{let t=Nr.resolve(e);for(;t!==Nr.dirname(t);){if(Hm.existsSync(Nr.join(t,qm)))return t;t=Nr.dirname(t)}return Hm.existsSync(Nr.join(t,qm))?t:null},nc=new Map,Us=()=>{nc.clear()},xk=async e=>{let t;try{t=await Pe(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Nr.join(r,Pk),o=or(n);if(o!==null&&nr(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},_r=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=nc.get(e);if(t)return t;let r=await xk(e);return nc.set(e,r),r};import sr from"node:fs";import Dt from"node:path";var Ym=`---
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 Ym=`# {{packageName}}
77
+ `;var zm=`# {{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 zm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{checksBullet}}\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the shared CI job exports. Pass them to `use.httpCredentials`; never invent a per-app name (`E2E_CLIENT_BASIC_AUTH_*`) or fall back to one. `infra-kit audit` fails the package otherwise.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- `playwright.config.ts` takes `baseURL`, `ignoreHTTPSErrors` and `webServer` from `infraKitE2e()` (`@slip-stream-kit/config/playwright`). Every run is local by default \u2014 this worktree's dev server, reused or started for the run \u2014 and cloud only with `INFRA_KIT_E2E=cloud` (`infra-kit e2e --cloud`) or on CI, against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test, or skip it with a linked issue once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var Xm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{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 Zm=`# {{packageName}}
98
+ `;var Xm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{checksBullet}}\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the shared CI job exports. Pass them to `use.httpCredentials`; never invent a per-app name (`E2E_CLIENT_BASIC_AUTH_*`) or fall back to one. `infra-kit audit` fails the package otherwise.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- `playwright.config.ts` takes `baseURL`, `ignoreHTTPSErrors` and `webServer` from `infraKitE2e()` (`@slip-stream-kit/config/playwright`). Every run is local by default \u2014 this worktree's dev server, reused or started for the run \u2014 and cloud only with `INFRA_KIT_E2E=cloud` (`infra-kit e2e --cloud`) or on CI, against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL. The one exception is a suite that must run against a production build it serves itself: it declares `e2e: { server: 'static' }` in `infra-kit.config.ts` and sets `baseURL` and `webServer` itself.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test, or skip it with a linked issue once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var Zm="# {{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 Qm=`# {{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 Qm=`# {{packageName}}
119
+ `;var ef=`# {{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,41 +138,42 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
138
138
  - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
139
139
  - The web build feeds the native shell, so a device run needs a rebuild first.
140
140
  - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
141
- `;var ef="# 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 Mr={"root/body":ef.trimEnd(),"package/frontend":Xm.trimEnd(),"package/backend":Ym.trimEnd(),"package/lib":Zm.trimEnd(),"package/e2e":zm.trimEnd(),"package/mobile":Qm.trimEnd(),"design/skeleton":qm.trimEnd()};var sc=/\{\{(\w+)\}\}/g,Nk=/^- \{\{(\w+)\}\}$/,_k=e=>new Set([...e.matchAll(sc)].map(t=>t[1])),Mk=(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(", ")}`)},jk=(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(", ")}`)},Fk=(e,t)=>e.filter(r=>{let n=Nk.exec(r);return n===null||t[n[1]]!==""}),Lk=(e,t)=>{for(let r of e)for(let n of r.matchAll(sc)){let o=t[n[1]];if(o!==void 0&&o.includes(`
141
+ `;var tf="# 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 Mr={"root/body":tf.trimEnd(),"package/frontend":Zm.trimEnd(),"package/backend":zm.trimEnd(),"package/lib":Qm.trimEnd(),"package/e2e":Xm.trimEnd(),"package/mobile":ef.trimEnd(),"design/skeleton":Ym.trimEnd()};var sc=/\{\{(\w+)\}\}/g,Nk=/^- \{\{(\w+)\}\}$/,_k=e=>new Set([...e.matchAll(sc)].map(t=>t[1])),Mk=(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(", ")}`)},jk=(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(", ")}`)},Fk=(e,t)=>e.filter(r=>{let n=Nk.exec(r);return n===null||t[n[1]]!==""}),Lk=(e,t)=>{for(let r of e)for(let n of r.matchAll(sc)){let o=t[n[1]];if(o!==void 0&&o.includes(`
142
142
  `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},jr=(e,t)=>{let r=_k(e);jk(r,t),Mk(r,t);let n=Fk(e.split(`
143
143
  `),t);return Lk(n,t),n.join(`
144
144
  `).replace(sc,(o,s)=>t[s])};var Bk="name: TODO",ic=e=>{let t=jr(Mr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(Bk,()=>r)}
145
- `};var Uk=(e,t)=>`${tr}${e} ${t} -->`,Vk="`README.md` \u2014 what this package is and how to run it.",ac="docs/e2e-playwright.md",Wk=`\`${ac}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Gk=["ts-check","eslint-check","test"],Jk="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.",Kk="Run `pnpm run build` before a dependent package can see a change.",tf=(e,t)=>e?.includes(t)??!0,Hk=e=>{let t=Gk.filter(r=>tf(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},cc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=jr(Mr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?Vk:"",checksBullet:Hk(a),...r==="e2e"?{e2eDocBullet:i?Wk:""}:{},...r==="lib"?{surfaceBullet:c?Jk:"",buildBullet:tf(a,"build")?Kk:""}:{}});return[Uk(t,r),"",l].join(`
146
- `)};var qk=e=>`${rc}${e} -->`,lc=e=>{let t=jr(Mr["root/body"],{});return[qk(e),"",t].join(`
147
- `)};import Fr from"node:fs";import Yk from"node:path";var Vs=e=>{let t;try{t=Fr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},zn=(e,t)=>{let r=Xn(e,t);return r!=="unchanged"&&(Fr.mkdirSync(Yk.dirname(e),{recursive:!0}),Fr.writeFileSync(e,t,"utf-8")),r},Xn=(e,t)=>{Vs(e);let r=Fr.existsSync(e)?Fr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},uc=(e,t,r)=>{let n=Fr.readFileSync(e,"utf-8");if(!Xe(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},rf=(e,t,r)=>Xe(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,dc=(e,t,r,n)=>{let o=rf(e,r,n),s=rf(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 Gs="<!-- infra-kit:import:begin -->",Js="<!-- infra-kit:import:end -->",zk="AGENTS.md",nf="CLAUDE.md",Xk="README.md",pc="DESIGN.md",Zk=["frontend","mobile"],Qk=e=>or.existsSync(e)?or.readFileSync(e,"utf-8"):null,mc=(e,t)=>{try{return or.readdirSync(e).includes(t)}catch{return!1}},Ws=(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},of=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=Qk(e),a=i===null?"":o?.(i)??i,c=Dr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return Xn(e,c);let l=zn(e,c);return uc(e,r,n),i!==null&&dc(a,c,r,n),l},eb=(e,t)=>{if(!or.existsSync(e))return"unchanged";Vs(e);let r=or.readFileSync(e,"utf-8"),n=Ot(r,_e,Ze);return n===null?"unchanged":n.trim()===""?(t||or.rmSync(e),"removed"):t?Xn(e,n):zn(e,n)},tb=(e,t,r)=>of({filePath:e,dryRun:r,body:lc(t),startMarker:_e,endMarker:Ze,prepare:n=>Ot(n,Gs,Js)??n}),Zn=async(e,{version:t,dryRun:r=!1})=>{let n=It.join(e,nf),o=It.join(e,zk),s=[];try{s.push({path:n,action:tb(n,t,r)})}catch(i){s.push(Ws(n,i))}try{s.push({path:o,action:eb(o,r)})}catch(i){s.push(Ws(o,i))}return s},rb=(e,t,r,n)=>{if(!Zk.includes(r)||mc(e,pc))return null;let o=It.join(e,pc),s=ic(t);try{return{path:o,action:n?Xn(o,s):zn(o,s),type:r}}catch(i){return Ws(o,i,r)}},Qn=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=It.join(e,nf),a=await Qt(e),c=a.name??It.basename(e),l=Gn({packageDir:e,repoRoot:t,pkgJson:a,declaredType:o}),u=cc({version:r,type:l,packageName:c,relDir:It.relative(t,e).split(It.sep).join("/"),hasReadme:mc(e,Xk),hasDesign:mc(e,pc),hasE2eDoc:or.existsSync(It.join(t,ac)),scripts:Object.keys(a.scripts??{}),hasPublicSurface:a.exports!==void 0||a.bin!==void 0}),p=[];try{p.push({path:i,action:of({filePath:i,body:u,startMarker:Qe,endMarker:pt,dryRun:s}),type:l})}catch(m){p.push(Ws(i,m,l))}if(n){let m=rb(e,c,l,s);m&&p.push(m)}return p};import Sb from"node:path";import sf from"node:path";var fc="agent-guidance",eo="CLAUDE.md",nb="\u2014 run: infra-kit audit --fix",ob={missing:`${eo} missing`,"no-block":`${eo} has no infra-kit block (expected ${Qe} \u2026 ${pt})`,malformed:`${eo} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${eo} carries the ROOT infra-kit block (${_e}); a package needs the package block`},sb=e=>e.adopted?` (workspace adopted: ${sf.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",gc=(e,t)=>{let r=rr(nr(sf.join(e,eo)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:fc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${ob[r.state]} ${nb}`,o=r.state==="missing"?`${n}${sb(t)}`:n;return t.adopted?{name:fc,status:"fail",message:o}:{name:fc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import ib from"node:path";var hc=async(e,t=At)=>{try{let r=await Hn(e,t);return{check:{name:se,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:se,status:"fail",message:r.message},rules:null}}},af="infra-kit.json",ab=async e=>await Ee(ib.join(e,se))?{name:se,status:"fail",message:'retired at the repo root \u2014 root audit rules live in infra-kit.json "audit". Run `infra-kit audit --fix --root` to move them and delete the file'}:null,yc=async(e,t=Jn)=>{let r=await ab(e),n=r?[r]:[];try{let{audit:o={}}=await W();return{checks:[{name:af,status:"pass",message:"present and valid"},...n],rules:Kn(o,t)}}catch(o){return{checks:[{name:af,status:"fail",message:o.message},...n],rules:null}}};import Ks from"node:fs/promises";import Lr from"node:path";import{$ as cb}from"zx";var to="playwright.config.ts",lb=[{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')"}],cf=e=>Object.entries(Qa).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"}}),lf=async e=>{let t=Lr.join(e,to),r=await Ks.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${to}`,status:"fail",message:`missing ${to}`}]:lb.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${to} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},ub=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,db=/\.[cm]?[jt]sx?$/u,vc=async(e,t)=>(await Ks.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&db.test(n.name)).map(n=>Lr.join(n.parentPath,n.name)),pb=async e=>{let t=await vc(Lr.join(e,"src"),!0);for(let r of[Lr.join(e,to),...t]){let n=await Ks.readFile(r,"utf-8").catch(()=>"");if(ub.test(n))return!0}return!1},uf=async e=>{let t="e2e-auth:gitignored";if(!await pb(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await cb({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}`}},wc="E2E__BASIC_AUTH_USERNAME",kc="E2E__BASIC_AUTH_PASSWORD",mb=/\bE2E_\w*BASIC_AUTH_\w+/gu,fb=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,gb=/\/\*[\s\S]*?\*\//gu,hb=/(^|[^:])\/\/[^\n]*/gu,yb=e=>/USER(?:NAME)?$/u.test(e)?wc:kc,vb=e=>e.replace(gb,"").replace(hb,"$1"),df=async e=>{let t="e2e-env:basic-auth",r=[...await vc(e,!1),...await vc(Lr.join(e,"src"),!0)],n=[];for(let o of r){let s=await Ks.readFile(o,"utf-8").catch(()=>""),i=new Set([...vb(s).matchAll(mb)].map(a=>a[0]).filter(a=>fb.test(a)&&a!==wc&&a!==kc));for(let a of i)n.push(`${a} \u2192 ${yb(a)} (${Lr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${wc} / ${kc}`}:{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("; ")}`}},bc=async(e,t)=>[...cf(t),...await lf(e),await uf(e),await df(e)];import wb from"node:fs/promises";import kb from"node:path";var Rc=async(e,t)=>Promise.all(t.map(async r=>{let n=await wb.stat(kb.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 Sc=(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 bb from"node:fs/promises";import Rb from"node:path";var Br="turbo.json",Ec=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await bb.readFile(Rb.join(e,Br),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Br,status:"fail",message:`cannot read/parse ${Br}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Br,status:"fail",message:`no "tasks" object defined in ${Br}`}]: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 ${Br}`}})};var Eb=async(e,t)=>{let{check:r,rules:n}=await hc(e,t);return{checks:[r],rules:n}},Pb={adopted:!1,workspaceRoot:null},xb=async(e,t,r)=>Gn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await er(e)}),Pc=async(e,t=At,r={})=>{let n=await Qt(e),o=n.name??Sb.basename(e),{checks:s,rules:i}=r.isRoot?await yc(e,t):await Eb(e,t);r.isRoot||s.push(gc(e,r.adoption??Pb)),i&&(s.push(...Sc(n.scripts??{},i.requiredScripts)),s.push(...await Rc(e,i.requiredFiles)),s.push(...await Ec(e,i.turboTasks))),!r.isRoot&&await xb(e,n,r.repoRoot)==="e2e"&&s.push(...await bc(e,n.scripts??{}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var xc=["plugin","marketplace","add",Pt],Tc=["plugin","install",G,"--scope","project"],pf=(e,t)=>zt({projectPath:e,home:t}).kind==="installed",Hs=e=>((e??"").split(`
148
- `).find(r=>r.trim().length>0)??"").trim(),Tb=(e,t)=>{if(Fn(t))return null;d.debug({msg:`Running: ${jn} ${xc.join(" ")}`});let r=e({args:xc});return r.ok?null:{step:"marketplace",error:Hs(r.output)}},Cb=(e,t)=>{d.debug({msg:`Running: ${jn} ${Ds.join(" ")}`});let r=e({args:Ds});if(!r.ok)return{status:"update-failed",error:Hs(r.output)};d.debug({msg:`Running: ${jn} ${Is.join(" ")}`});let n=e({args:Is,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:Hs(n.output)}},Cc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Ua;if(!n({args:Ba}).ok)return{status:"claude-missing"};if(pf(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Cb(n,t);let o=Tb(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${jn} ${Tc.join(" ")}`});let s=n({args:Tc,cwd:t});return s.ok?pf(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:Hs(s.output)}};import $b from"node:fs";import Ab from"node:path";var Me=".mcp.json",et="mcpServers",Ob="infra-kit",Ib=["mcp"],Db="/infra-kit/dist/mcp.js",$c=" ",sr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mf=e=>{if(!sr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Ob&&r[0]===Ib[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Db)):!1},ff=e=>/\n([ \t]+)"/.exec(e)?.[1]??$c,Ac=e=>{try{return{kind:"raw",raw:$b.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Oc=e=>{try{return JSON.parse(e)}catch{return}},Ic=e=>e instanceof Error?e.message:String(e),Ur=e=>{let t=Ac(Ab.join(e,Me));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Oc(t.raw);if(!sr(r)||!sr(r[et]))return{kind:"unparseable"};let n=r[et];if(oe in n)return{kind:"stale"};let o=Object.keys(n).find(s=>mf(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import qs from"node:fs";import Nb from"node:path";var mt=`claude plugin install ${G} --scope project`,Vr=`claude plugin marketplace update ${oe} && claude plugin update ${G} --scope project`,Dc=`claude plugin marketplace add ${Pt}`,yf=" ",vf=()=>({source:{source:"github",repo:Pt}}),_b=()=>({extraKnownMarketplaces:{[oe]:vf()},enabledPlugins:{[G]:!0}}),wf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Mb=e=>/\n([ \t]+)"/.exec(e)?.[1]??yf,gf=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!wf(o)||r in o?null:(o[r]=n,`${t}.${r}`)},hf=e=>[gf(e,"extraKnownMarketplaces",oe,vf()),gf(e,"enabledPlugins",G,!0)].filter(r=>r!==null),jb=e=>{try{return qs.readFileSync(e,"utf-8")}catch{return null}},Fb=e=>(qs.mkdirSync(Nb.dirname(e),{recursive:!0}),qs.writeFileSync(e,`${JSON.stringify(_b(),null,yf)}
149
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${oe}`,`enabledPlugins.${G}`]}),Nc=(e,{write:t=!0}={})=>{let r=jb(e);if(r===null)return t?Fb(e):{status:"withheld",path:e,added:hf({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!wf(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${G}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=hf(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=Mb(r),i=r.endsWith(`
145
+ `};var Uk=(e,t)=>`${rr}${e} ${t} -->`,Vk="`README.md` \u2014 what this package is and how to run it.",ac="docs/e2e-playwright.md",Wk=`\`${ac}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Gk=["ts-check","eslint-check","test"],Jk="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.",Kk="Run `pnpm run build` before a dependent package can see a change.",rf=(e,t)=>e?.includes(t)??!0,Hk=e=>{let t=Gk.filter(r=>rf(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},cc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=jr(Mr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?Vk:"",checksBullet:Hk(a),...r==="e2e"?{e2eDocBullet:i?Wk:""}:{},...r==="lib"?{surfaceBullet:c?Jk:"",buildBullet:rf(a,"build")?Kk:""}:{}});return[Uk(t,r),"",l,""].join(`
146
+ `)};var qk=e=>`${rc}${e} -->`,lc=e=>{let t=jr(Mr["root/body"],{});return[qk(e),"",t,""].join(`
147
+ `)};import Fr from"node:fs";import Yk from"node:path";var Vs=e=>{let t;try{t=Fr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},zn=(e,t)=>{let r=Xn(e,t);return r!=="unchanged"&&(Fr.mkdirSync(Yk.dirname(e),{recursive:!0}),Fr.writeFileSync(e,t,"utf-8")),r},Xn=(e,t)=>{Vs(e);let r=Fr.existsSync(e)?Fr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},uc=(e,t,r)=>{let n=Fr.readFileSync(e,"utf-8");if(!Xe(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},nf=(e,t,r)=>Xe(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,dc=(e,t,r,n)=>{let o=nf(e,r,n),s=nf(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 Gs="<!-- infra-kit:import:begin -->",Js="<!-- infra-kit:import:end -->",zk="AGENTS.md",of="CLAUDE.md",Xk="README.md",pc="DESIGN.md",Zk=["frontend","mobile"],Qk=e=>sr.existsSync(e)?sr.readFileSync(e,"utf-8"):null,mc=(e,t)=>{try{return sr.readdirSync(e).includes(t)}catch{return!1}},Ws=(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},sf=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=Qk(e),a=i===null?"":o?.(i)??i,c=Dr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return Xn(e,c);let l=zn(e,c);return uc(e,r,n),i!==null&&dc(a,c,r,n),l},eb=(e,t)=>{if(!sr.existsSync(e))return"unchanged";Vs(e);let r=sr.readFileSync(e,"utf-8"),n=It(r,_e,Ze);return n===null?"unchanged":n.trim()===""?(t||sr.rmSync(e),"removed"):t?Xn(e,n):zn(e,n)},tb=(e,t,r)=>sf({filePath:e,dryRun:r,body:lc(t),startMarker:_e,endMarker:Ze,prepare:n=>It(n,Gs,Js)??n}),Zn=async(e,{version:t,dryRun:r=!1})=>{let n=Dt.join(e,of),o=Dt.join(e,zk),s=[];try{s.push({path:n,action:tb(n,t,r)})}catch(i){s.push(Ws(n,i))}try{s.push({path:o,action:eb(o,r)})}catch(i){s.push(Ws(o,i))}return s},rb=(e,t,r,n)=>{if(!Zk.includes(r)||mc(e,pc))return null;let o=Dt.join(e,pc),s=ic(t);try{return{path:o,action:n?Xn(o,s):zn(o,s),type:r}}catch(i){return Ws(o,i,r)}},Qn=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Dt.join(e,of),a=await er(e),c=a.name??Dt.basename(e),l=Gn({packageDir:e,repoRoot:t,pkgJson:a,declaredType:o}),u=cc({version:r,type:l,packageName:c,relDir:Dt.relative(t,e).split(Dt.sep).join("/"),hasReadme:mc(e,Xk),hasDesign:mc(e,pc),hasE2eDoc:sr.existsSync(Dt.join(t,ac)),scripts:Object.keys(a.scripts??{}),hasPublicSurface:a.exports!==void 0||a.bin!==void 0}),p=[];try{p.push({path:i,action:sf({filePath:i,body:u,startMarker:Qe,endMarker:pt,dryRun:s}),type:l})}catch(m){p.push(Ws(i,m,l))}if(n){let m=rb(e,c,l,s);m&&p.push(m)}return p};import Eb from"node:path";import af from"node:path";var fc="agent-guidance",eo="CLAUDE.md",nb="\u2014 run: infra-kit audit --fix",ob={missing:`${eo} missing`,"no-block":`${eo} has no infra-kit block (expected ${Qe} \u2026 ${pt})`,malformed:`${eo} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${eo} carries the ROOT infra-kit block (${_e}); a package needs the package block`},sb=e=>e.adopted?` (workspace adopted: ${af.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",gc=(e,t)=>{let r=nr(or(af.join(e,eo)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:fc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${ob[r.state]} ${nb}`,o=r.state==="missing"?`${n}${sb(t)}`:n;return t.adopted?{name:fc,status:"fail",message:o}:{name:fc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import ib from"node:path";var hc=async(e,t=At)=>{try{let r=await Hn(e,t);return{check:{name:se,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:se,status:"fail",message:r.message},rules:null}}},cf="infra-kit.json",ab=async e=>await Ee(ib.join(e,se))?{name:se,status:"fail",message:'retired at the repo root \u2014 root audit rules live in infra-kit.json "audit". Run `infra-kit audit --fix --root` to move them and delete the file'}:null,yc=async(e,t=Jn)=>{let r=await ab(e),n=r?[r]:[];try{let{audit:o={}}=await W();return{checks:[{name:cf,status:"pass",message:"present and valid"},...n],rules:Kn(o,t)}}catch(o){return{checks:[{name:cf,status:"fail",message:o.message},...n],rules:null}}};import Ks from"node:fs/promises";import Lr from"node:path";import{$ as cb}from"zx";var to="playwright.config.ts",lb=[{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')"}],lf=e=>Object.entries(Qa).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"}}),ub="infra-kit-e2e",uf=async(e,t={})=>{let r=Lr.join(e,to),n=await Ks.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${to}`,status:"fail",message:`missing ${to}`}]:lb.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===ub?{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:`${to} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},db=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,pb=/\.[cm]?[jt]sx?$/u,vc=async(e,t)=>(await Ks.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&pb.test(n.name)).map(n=>Lr.join(n.parentPath,n.name)),mb=async e=>{let t=await vc(Lr.join(e,"src"),!0);for(let r of[Lr.join(e,to),...t]){let n=await Ks.readFile(r,"utf-8").catch(()=>"");if(db.test(n))return!0}return!1},df=async e=>{let t="e2e-auth:gitignored";if(!await mb(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await cb({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}`}},wc="E2E__BASIC_AUTH_USERNAME",kc="E2E__BASIC_AUTH_PASSWORD",fb=/\bE2E_\w*BASIC_AUTH_\w+/gu,gb=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,hb=/\/\*[\s\S]*?\*\//gu,yb=/(^|[^:])\/\/[^\n]*/gu,vb=e=>/USER(?:NAME)?$/u.test(e)?wc:kc,wb=e=>e.replace(hb,"").replace(yb,"$1"),pf=async e=>{let t="e2e-env:basic-auth",r=[...await vc(e,!1),...await vc(Lr.join(e,"src"),!0)],n=[];for(let o of r){let s=await Ks.readFile(o,"utf-8").catch(()=>""),i=new Set([...wb(s).matchAll(fb)].map(a=>a[0]).filter(a=>gb.test(a)&&a!==wc&&a!==kc));for(let a of i)n.push(`${a} \u2192 ${vb(a)} (${Lr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${wc} / ${kc}`}:{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("; ")}`}},bc=async(e,t,r={})=>[...lf(t),...await uf(e,r),await df(e),await pf(e)];import kb from"node:fs/promises";import bb from"node:path";var Rc=async(e,t)=>Promise.all(t.map(async r=>{let n=await kb.stat(bb.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 Sc=(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 Rb from"node:fs/promises";import Sb from"node:path";var Br="turbo.json",Ec=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await Rb.readFile(Sb.join(e,Br),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Br,status:"fail",message:`cannot read/parse ${Br}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Br,status:"fail",message:`no "tasks" object defined in ${Br}`}]: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 ${Br}`}})};var Pb=async(e,t)=>{let{check:r,rules:n}=await hc(e,t);return{checks:[r],rules:n}},xb={adopted:!1,workspaceRoot:null},Tb=async(e,t,r)=>Gn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await tr(e)}),Cb=async e=>(await Ot(e).catch(()=>{}))?.e2e?.server==="static",Pc=async(e,t=At,r={})=>{let n=await er(e),o=n.name??Eb.basename(e),{checks:s,rules:i}=r.isRoot?await yc(e,t):await Pb(e,t);r.isRoot||s.push(gc(e,r.adoption??xb)),i&&(s.push(...Sc(n.scripts??{},i.requiredScripts)),s.push(...await Rc(e,i.requiredFiles)),s.push(...await Ec(e,i.turboTasks))),!r.isRoot&&await Tb(e,n,r.repoRoot)==="e2e"&&s.push(...await bc(e,n.scripts??{},{staticServer:await Cb(e)}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var xc=["plugin","marketplace","add",Pt],Tc=["plugin","install",G,"--scope","project"],mf=(e,t)=>Xt({projectPath:e,home:t}).kind==="installed",Hs=e=>((e??"").split(`
148
+ `).find(r=>r.trim().length>0)??"").trim(),$b=(e,t)=>{if(Fn(t))return null;d.debug({msg:`Running: ${jn} ${xc.join(" ")}`});let r=e({args:xc});return r.ok?null:{step:"marketplace",error:Hs(r.output)}},Ab=(e,t)=>{d.debug({msg:`Running: ${jn} ${Ds.join(" ")}`});let r=e({args:Ds});if(!r.ok)return{status:"update-failed",error:Hs(r.output)};d.debug({msg:`Running: ${jn} ${Is.join(" ")}`});let n=e({args:Is,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:Hs(n.output)}},Cc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Ua;if(!n({args:Ba}).ok)return{status:"claude-missing"};if(mf(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Ab(n,t);let o=$b(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${jn} ${Tc.join(" ")}`});let s=n({args:Tc,cwd:t});return s.ok?mf(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:Hs(s.output)}};import Ob from"node:fs";import Ib from"node:path";var Me=".mcp.json",et="mcpServers",Db="infra-kit",Nb=["mcp"],_b="/infra-kit/dist/mcp.js",$c=" ",ir=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ff=e=>{if(!ir(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Db&&r[0]===Nb[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(_b)):!1},gf=e=>/\n([ \t]+)"/.exec(e)?.[1]??$c,Ac=e=>{try{return{kind:"raw",raw:Ob.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Oc=e=>{try{return JSON.parse(e)}catch{return}},Ic=e=>e instanceof Error?e.message:String(e),Ur=e=>{let t=Ac(Ib.join(e,Me));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Oc(t.raw);if(!ir(r)||!ir(r[et]))return{kind:"unparseable"};let n=r[et];if(oe in n)return{kind:"stale"};let o=Object.keys(n).find(s=>ff(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import qs from"node:fs";import Mb from"node:path";var mt=`claude plugin install ${G} --scope project`,Vr=`claude plugin marketplace update ${oe} && claude plugin update ${G} --scope project`,Dc=`claude plugin marketplace add ${Pt}`,vf=" ",wf=()=>({source:{source:"github",repo:Pt}}),jb=()=>({extraKnownMarketplaces:{[oe]:wf()},enabledPlugins:{[G]:!0}}),kf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fb=e=>/\n([ \t]+)"/.exec(e)?.[1]??vf,hf=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!kf(o)||r in o?null:(o[r]=n,`${t}.${r}`)},yf=e=>[hf(e,"extraKnownMarketplaces",oe,wf()),hf(e,"enabledPlugins",G,!0)].filter(r=>r!==null),Lb=e=>{try{return qs.readFileSync(e,"utf-8")}catch{return null}},Bb=e=>(qs.mkdirSync(Mb.dirname(e),{recursive:!0}),qs.writeFileSync(e,`${JSON.stringify(jb(),null,vf)}
149
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${oe}`,`enabledPlugins.${G}`]}),Nc=(e,{write:t=!0}={})=>{let r=Lb(e);if(r===null)return t?Bb(e):{status:"withheld",path:e,added:yf({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!kf(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${G}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=yf(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=Fb(r),i=r.endsWith(`
150
150
  `)?`
151
- `:"";return qs.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};import Ub from"node:path";import Vb from"node:process";import _c from"node:fs/promises";import kf from"node:path";var Lb="infra-kit.json",bf=["requiredScripts","requiredFiles","turbo"],ro=(e,t)=>[{path:e,action:"failed",message:t}],Bb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rf=async e=>{let t=kf.join(e,se),r=kf.join(e,Lb),n;try{n=await Ir(e)}catch(c){return ro(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!bf.includes(c));if(s.length>0)return ro(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(bf.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await _c.stat(r),l=await _c.readFile(r,"utf8"),u=JSON.parse(l);if(!Bb(u))return ro(r,"is not a JSON object");if("audit"in u)return ro(r,`already has an "audit" block \u2014 merge ${se}'s rules into it by hand, then delete ${se}`);await nm({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return ro(r,c.message)}try{await _c.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var Wb=["unchanged","created"],Gb=["unchanged","created","updated","removed","failed"],Sf=async(e,t,r)=>{let n=await er(e);return Qn(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},Jb=async(e,t)=>{if(e.root)return[...await Rf(t),...await Zn(t,{version:U.version})];if(e.all){let n=[];for(let o of await Pe(t))n.push(...await Sf(o,t,e.design));return n}let r=await Yn(e.cwd??Vb.cwd());return Sf(r,t,e.design)},Kb=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 ${Gb.filter(n=>Wb.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},Hb=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Ub.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(Kb(e))},qb=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Ef=async(e,t)=>{let r=await P();Us();let n=await _r(t),o=await Jb(e,r);Hb(o,r),Us();let s=await _r(t),i=!e.all&&!e.root;return{fixed:o.map(qb),adoptionFlipped:i&&!n.adopted&&s.adopted}};import xf from"node:fs";import Tf from"node:path";var Mc="ik-mcp",Pf=(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:Mc,args:r}};var Ys="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Yb=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),jc=e=>sr(e)&&e.command===Mc,zb=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Xb=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Pf(i,a),l=e[i];if(l!==void 0&&!jc(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 ${Ys}, or drop mcp.${i} from infra-kit.json`});continue}if(jc(l)&&l.type===c.type&&Yb(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=zb(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: ${Ys}`:`"${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: ${Ys}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!jc(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}},Zb=(e,t,r)=>{let n=r===null?$c:ff(r),o=r===null||r.endsWith(`
151
+ `:"";return qs.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};import Wb from"node:path";import Gb from"node:process";import _c from"node:fs/promises";import bf from"node:path";var Ub="infra-kit.json",Rf=["requiredScripts","requiredFiles","turbo"],ro=(e,t)=>[{path:e,action:"failed",message:t}],Vb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sf=async e=>{let t=bf.join(e,se),r=bf.join(e,Ub),n;try{n=await Ot(e)}catch(c){return ro(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Rf.includes(c));if(s.length>0)return ro(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Rf.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await _c.stat(r),l=await _c.readFile(r,"utf8"),u=JSON.parse(l);if(!Vb(u))return ro(r,"is not a JSON object");if("audit"in u)return ro(r,`already has an "audit" block \u2014 merge ${se}'s rules into it by hand, then delete ${se}`);await nm({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return ro(r,c.message)}try{await _c.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var Jb=["unchanged","created"],Kb=["unchanged","created","updated","removed","failed"],Ef=async(e,t,r)=>{let n=await tr(e);return Qn(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},Hb=async(e,t)=>{if(e.root)return[...await Sf(t),...await Zn(t,{version:U.version})];if(e.all){let n=[];for(let o of await Pe(t))n.push(...await Ef(o,t,e.design));return n}let r=await Yn(e.cwd??Gb.cwd());return Ef(r,t,e.design)},qb=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 ${Kb.filter(n=>Jb.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},Yb=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Wb.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(qb(e))},zb=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Pf=async(e,t)=>{let r=await P();Us();let n=await _r(t),o=await Hb(e,r);Yb(o,r),Us();let s=await _r(t),i=!e.all&&!e.root;return{fixed:o.map(zb),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Tf from"node:fs";import Cf from"node:path";var Mc="ik-mcp",xf=(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:Mc,args:r}};var Ys="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Xb=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),jc=e=>ir(e)&&e.command===Mc,Zb=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Qb=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=xf(i,a),l=e[i];if(l!==void 0&&!jc(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 ${Ys}, or drop mcp.${i} from infra-kit.json`});continue}if(jc(l)&&l.type===c.type&&Xb(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Zb(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: ${Ys}`:`"${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: ${Ys}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!jc(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}},eR=(e,t,r)=>{let n=r===null?$c:gf(r),o=r===null||r.endsWith(`
152
152
  `)?`
153
- `:"";try{return xf.mkdirSync(Tf.dirname(e),{recursive:!0}),xf.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${Ic(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},no=({projectRoot:e,proxies:t,write:r})=>{let n=Tf.join(e,Me),o=Ac(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${Ic(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Oc(s);if(!sr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ys}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[et];if(a!==void 0&&!sr(a))return d.warn(`${n} has a "${et}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Xb(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Zb(n,{...i,[et]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Cf=async(e,t)=>{let r;try{r=(await W()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=no({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:o.length===0}};var Qb="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",eR=async e=>e.root?[{dir:await P(),baseline:Jn,isRoot:!0}]:e.all?(await Pe(await P())).map(r=>({dir:r})):[{dir:await Yn(e.cwd??$f.cwd())}],tR=async e=>e.root||e.all?await P():e.cwd??$f.cwd(),rR=async()=>{try{return await P()}catch{return}},nR=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,d.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return d.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},oR=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Ef(e,t);return n&&d.info(Qb),r},sR=e=>{if(Ur(e).kind!=="stale")return null;let t=`${Me} still registers "${oe}" \u2014 delete this key: the plugin no longer serves an MCP server and the entry spawns a retired subcommand that exits immediately (Claude Code lists it as failed). Delete the "${oe}" entry by hand in a PR, keeping its siblings`;return d.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},zs=async(e={})=>{let t=oc(await tR(e)),r=e.fix?await oR(e,t):void 0,n=await eR(e),o=await _r(t),s=await rR(),i=[];for(let l of n)i.push(await Pc(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await Cf(n[0].dir,e.fix===!0);l&&i.push(l);let u=sR(n[0].dir);u&&i.push(u)}let c={allPassed:nR(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},iR={all:je.boolean().optional().describe("Audit every non-vendor workspace package"),root:je.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},aR={allPassed:je.boolean().describe("Whether every audited package passed all checks"),packages:je.array(je.object({name:je.string(),passed:je.boolean(),checks:je.array(je.object({name:je.string(),status:je.enum(["pass","fail"]),message:je.string()}))})).describe("Per-package check results")},Fc=E({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:iR,outputSchema:aR,handler:e=>zs({all:e.all,root:e.root})});import{z as Dt}from"zod";import Lc from"node:fs/promises";import cR from"node:path";var Wr=()=>Object.keys(am.shape),lR=new Set(["protectedEnvs"]),oo={project:"per-project override",global:"user-global override"},Xs=(e,t)=>{if(ve()&&lR.has(e))throw new C({status:"refused",agentMode:_.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!Wr().includes(e)){if(e.includes(".")){let r=e.split(".")[0]??e;throw new Error(`Nested keys are not supported: override layers merge per top-level key, so "${e}" would replace the whole "${r}" section. Set "${r}" to its full JSON value instead, or use \`infra-kit config edit\`.`)}throw new Error(`Unknown config key "${e}". Top-level keys: ${Wr().join(", ")}.`)}},Af=e=>{try{return JSON.parse(e)}catch{return e}},uR=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dR=async e=>{let t;try{t=await Lc.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${v(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!uR(r))throw new Error(`${v(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},pR=async(e,t)=>{t===null?await Lc.rm(e,{force:!0}):bt(e,t,420),Mn()},Zs=async(e,t,r)=>{let n=await H(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await dR(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Lc.mkdir(cR.dirname(o),{recursive:!0}),bt(o,`${JSON.stringify(c,null,2)}
154
- `,420),Mn();try{await W({autoMigrate:"off"})}catch(l){throw await pR(o,s),new Error(`${l.message}
155
- ${v(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Bc=async({key:e,value:t,global:r})=>{Xs(e,"config-set");let n=r?"global":"project",o=Af(t),{file:s,previous:i}=await Zs(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${oo[n]} (${v(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}};var Qs=async({key:e}={})=>{let[t,r]=await Promise.all([W(),H()]),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(!Wr().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Wr().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},mR={config:Dt.record(Dt.string(),Dt.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:Dt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Dt.string().optional().describe("The top-level key asked for, when one was."),value:Dt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Dt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Uc=E({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config-set` / `config-unset` (top-level keys) or `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{key:Dt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:mR,handler:e=>Qs(e)});import wR from"node:fs";import{z as ie}from"zod";import io from"node:fs";import Gr from"node:path";import fR from"node:process";var gR=Gr.join(".infra-kit","dev-context"),hR=".infra-kit",Of=(e,t)=>{let r=Gr.resolve(e);for(;;){let n=Gr.join(r,t);if(io.existsSync(n))return n;let o=Gr.dirname(r);if(o===r)return;r=o}},yR=e=>{let t=Of(e,gR);if(t)return t;let r=Of(e,hR);return r?Gr.join(r,"dev-context"):void 0},Vc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,so=e=>typeof e=="string"?e:"",vR=(e,t,r)=>{let n=Gr.join(e,t);try{let o=io.statSync(n),s=JSON.parse(io.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:Vc(i.port),alias:so(i.alias),origin:so(i.origin),release:so(i.release),env:so(i.env),pid:Vc(i.pid),writtenAt:Vc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},ao=(e=fR.cwd())=>{let t=Date.now(),r=yR(e);if(!r||!io.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=io.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>vR(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 ei=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Dn,n=ao(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),g=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(wR.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",g=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${g}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},kR={active:ie.boolean().describe("True when at least one dev-context fragment exists on disk (an infra-kit dev session has apps registered). False means no active dev session was found \u2014 this is a clean result, NOT an error."),contextDir:ie.string().nullable().describe("The RESOLVED dev-context fragment directory \u2014 found by searching UPWARD from the working directory. This is where the read looked, NOT proof anything is there: when no fragment directory exists the resolver derives one from an up-tree `.infra-kit`, so this can name a path (even under $HOME) that was never written to. Check contextDirExists before drawing any conclusion from it. Null when no `.infra-kit` anchor exists up-tree at all."),contextDirExists:ie.boolean().describe('Whether contextDir actually exists on disk. False with a non-null contextDir means the path was DERIVED, not read \u2014 the usual state in a repo where `infra-kit dev` has never run. Distinguishes "looked and found nothing" from "had nowhere to look".'),apps:ie.array(ie.object({app:ie.string().describe("App folder name (the fragment filename without .json)."),package:ie.string().describe("The app package name the vite helper reads to decide a local route."),port:ie.number().describe("The actual bound port the dev server is listening on."),pid:ie.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ie.string().describe("Registered portless hostname for the app."),origin:ie.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ie.string().describe("Release slug the runner recorded for this worktree."),env:ie.string().nullable().describe("INFRA_KIT_ENV the dev session runs with \u2014 where its UIs proxy cloud routes. Null when none was loaded, or the fragment predates the field."),writtenAt:ie.string().nullable().describe("ISO 8601 time the runner self-reported writing the fragment (writer clock \u2014 may be wrong; prefer fragmentMtime). Null when the fragment did not record it."),fragmentMtime:ie.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ie.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ie.boolean().describe("Whether a TCP connection to the app port succeeds RIGHT NOW (a real engine liveness probe, not an inference). A fresh fragment with live:false is a crashed or killed dev server whose fragment was not cleaned up.")})).describe("One entry per dev-context fragment on disk, sorted by app name. Empty when no dev session is active.")},Wc=E({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:kR,handler:()=>ei()});import{spawnSync as Oh}from"node:child_process";import ee from"node:fs";import Ih from"node:os";import pe from"node:path";import it from"node:process";import{z as ge}from"zod";import{execFileSync as bR}from"node:child_process";var If=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},RR=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],SR=e=>RR.some(t=>t.test(e)),ER="/bin/ps",PR=()=>bR(ER,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
156
- `),Df=(e=PR)=>{try{return e().some(SR)}catch{return!0}};import{Chalk as xR}from"chalk";import Gc from"node:process";var Jc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},TR=new Set(["warn","fail"]),CR=24,Jr=" ",Nf=" ",$R=(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:[""]},_f=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},AR=e=>{let t=new xR({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)}},Mf=(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),OR=(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=Mf(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}},IR=(e,t,r,n)=>{let o=OR(_f(e.rows),e.rows.length,t,r),s=Math.max(1,n-Jr.length-e.label.length-o.plainWidth);return`${Jr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},DR=(e,t,r,n,o)=>{let s=TR.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=Nf.length+i+1+t+2,p=Math.max(CR,o-u),[m,...g]=$R(e.message,p),y=" ".repeat(u),b=x=>s?x:r.dim(x);return[`${Nf}${c(n[e.status])} ${l} ${b(m??"")}`.trimEnd(),...g.map(x=>`${y}${b(x)}`),...(e.notes??[]).map(x=>`${y}${x}`.trimEnd())]},NR=(e,t,r,n,o)=>{let s=_f(t),i=n.rule.repeat(Math.max(12,Math.min(o-Jr.length,56))),a=Mf(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[`${Jr}${r.dim(i)}`,`${Jr}${c}${l.join("")}`]},Kc=(e,t={})=>{let r=t.width??80,n=AR(t.color??!1),o=t.unicode??!0?Jc.unicode:Jc.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,"",`${Jr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[IR(u,n,o,r),...u.rows.flatMap(p=>DR(p,c,n,o,r)),""]);return[a,"",...l,...NR(e,i,n,o,r)]},_R=new Set(["","0","false","none"]),MR=["LC_ALL","LC_CTYPE","LANG"],jR=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!_R.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,FR=(e,t)=>{if(t)return!1;let r=MR.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Hc=(e={})=>{let t=e.env??Gc.env,r=e.stream??Gc.stderr;return{color:jR(t,r),unicode:FR(t,e.ascii??!1),width:r.columns??80}},tt=(e,t={})=>{(t.write??(n=>{Gc.stderr.write(n)}))(`${Kc(e,Hc(t)).join(`
153
+ `:"";try{return Tf.mkdirSync(Cf.dirname(e),{recursive:!0}),Tf.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${Ic(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},no=({projectRoot:e,proxies:t,write:r})=>{let n=Cf.join(e,Me),o=Ac(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${Ic(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Oc(s);if(!ir(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ys}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[et];if(a!==void 0&&!ir(a))return d.warn(`${n} has a "${et}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Qb(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=eR(n,{...i,[et]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var $f=async(e,t)=>{let r;try{r=(await W()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=no({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:o.length===0}};var tR="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",rR=async e=>e.root?[{dir:await P(),baseline:Jn,isRoot:!0}]:e.all?(await Pe(await P())).map(r=>({dir:r})):[{dir:await Yn(e.cwd??Af.cwd())}],nR=async e=>e.root||e.all?await P():e.cwd??Af.cwd(),oR=async()=>{try{return await P()}catch{return}},sR=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,d.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return d.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},iR=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Pf(e,t);return n&&d.info(tR),r},aR=e=>{if(Ur(e).kind!=="stale")return null;let t=`${Me} still registers "${oe}" \u2014 delete this key: the plugin no longer serves an MCP server and the entry spawns a retired subcommand that exits immediately (Claude Code lists it as failed). Delete the "${oe}" entry by hand in a PR, keeping its siblings`;return d.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},zs=async(e={})=>{let t=oc(await nR(e)),r=e.fix?await iR(e,t):void 0,n=await rR(e),o=await _r(t),s=await oR(),i=[];for(let l of n)i.push(await Pc(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await $f(n[0].dir,e.fix===!0);l&&i.push(l);let u=aR(n[0].dir);u&&i.push(u)}let c={allPassed:sR(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},cR={all:je.boolean().optional().describe("Audit every non-vendor workspace package"),root:je.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},lR={allPassed:je.boolean().describe("Whether every audited package passed all checks"),packages:je.array(je.object({name:je.string(),passed:je.boolean(),checks:je.array(je.object({name:je.string(),status:je.enum(["pass","fail"]),message:je.string()}))})).describe("Per-package check results")},Fc=E({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:cR,outputSchema:lR,handler:e=>zs({all:e.all,root:e.root})});import{z as Nt}from"zod";import Lc from"node:fs/promises";import uR from"node:path";var Wr=()=>Object.keys(am.shape),dR=new Set(["protectedEnvs"]),oo={project:"per-project override",global:"user-global override"},Xs=(e,t)=>{if(ve()&&dR.has(e))throw new C({status:"refused",agentMode:_.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!Wr().includes(e)){if(e.includes(".")){let r=e.split(".")[0]??e;throw new Error(`Nested keys are not supported: override layers merge per top-level key, so "${e}" would replace the whole "${r}" section. Set "${r}" to its full JSON value instead, or use \`infra-kit config edit\`.`)}throw new Error(`Unknown config key "${e}". Top-level keys: ${Wr().join(", ")}.`)}},Of=e=>{try{return JSON.parse(e)}catch{return e}},pR=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mR=async e=>{let t;try{t=await Lc.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${v(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!pR(r))throw new Error(`${v(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},fR=async(e,t)=>{t===null?await Lc.rm(e,{force:!0}):bt(e,t,420),Mn()},Zs=async(e,t,r)=>{let n=await q(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await mR(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Lc.mkdir(uR.dirname(o),{recursive:!0}),bt(o,`${JSON.stringify(c,null,2)}
154
+ `,420),Mn();try{await W({autoMigrate:"off"})}catch(l){throw await fR(o,s),new Error(`${l.message}
155
+ ${v(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},Bc=async({key:e,value:t,global:r})=>{Xs(e,"config-set");let n=r?"global":"project",o=Of(t),{file:s,previous:i}=await Zs(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${oo[n]} (${v(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}};var Qs=async({key:e}={})=>{let[t,r]=await Promise.all([W(),q()]),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(!Wr().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Wr().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},gR={config:Nt.record(Nt.string(),Nt.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:Nt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Nt.string().optional().describe("The top-level key asked for, when one was."),value:Nt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Nt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Uc=E({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config-set` / `config-unset` (top-level keys) or `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{key:Nt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:gR,handler:e=>Qs(e)});import bR from"node:fs";import{z as ie}from"zod";import io from"node:fs";import Gr from"node:path";import hR from"node:process";var yR=Gr.join(".infra-kit","dev-context"),vR=".infra-kit",If=(e,t)=>{let r=Gr.resolve(e);for(;;){let n=Gr.join(r,t);if(io.existsSync(n))return n;let o=Gr.dirname(r);if(o===r)return;r=o}},wR=e=>{let t=If(e,yR);if(t)return t;let r=If(e,vR);return r?Gr.join(r,"dev-context"):void 0},Vc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,so=e=>typeof e=="string"?e:"",kR=(e,t,r)=>{let n=Gr.join(e,t);try{let o=io.statSync(n),s=JSON.parse(io.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:Vc(i.port),alias:so(i.alias),origin:so(i.origin),release:so(i.release),env:so(i.env),pid:Vc(i.pid),writtenAt:Vc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},ao=(e=hR.cwd())=>{let t=Date.now(),r=wR(e);if(!r||!io.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=io.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>kR(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 ei=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Dn,n=ao(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),g=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(bR.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",g=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${g}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},RR={active:ie.boolean().describe("True when at least one dev-context fragment exists on disk (an infra-kit dev session has apps registered). False means no active dev session was found \u2014 this is a clean result, NOT an error."),contextDir:ie.string().nullable().describe("The RESOLVED dev-context fragment directory \u2014 found by searching UPWARD from the working directory. This is where the read looked, NOT proof anything is there: when no fragment directory exists the resolver derives one from an up-tree `.infra-kit`, so this can name a path (even under $HOME) that was never written to. Check contextDirExists before drawing any conclusion from it. Null when no `.infra-kit` anchor exists up-tree at all."),contextDirExists:ie.boolean().describe('Whether contextDir actually exists on disk. False with a non-null contextDir means the path was DERIVED, not read \u2014 the usual state in a repo where `infra-kit dev` has never run. Distinguishes "looked and found nothing" from "had nowhere to look".'),apps:ie.array(ie.object({app:ie.string().describe("App folder name (the fragment filename without .json)."),package:ie.string().describe("The app package name the vite helper reads to decide a local route."),port:ie.number().describe("The actual bound port the dev server is listening on."),pid:ie.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ie.string().describe("Registered portless hostname for the app."),origin:ie.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ie.string().describe("Release slug the runner recorded for this worktree."),env:ie.string().nullable().describe("INFRA_KIT_ENV the dev session runs with \u2014 where its UIs proxy cloud routes. Null when none was loaded, or the fragment predates the field."),writtenAt:ie.string().nullable().describe("ISO 8601 time the runner self-reported writing the fragment (writer clock \u2014 may be wrong; prefer fragmentMtime). Null when the fragment did not record it."),fragmentMtime:ie.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ie.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ie.boolean().describe("Whether a TCP connection to the app port succeeds RIGHT NOW (a real engine liveness probe, not an inference). A fresh fragment with live:false is a crashed or killed dev server whose fragment was not cleaned up.")})).describe("One entry per dev-context fragment on disk, sorted by app name. Empty when no dev session is active.")},Wc=E({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:RR,handler:()=>ei()});import{spawnSync as Oh}from"node:child_process";import te from"node:fs";import Ih from"node:os";import de from"node:path";import it from"node:process";import{z as fe}from"zod";import{execFileSync as SR}from"node:child_process";var Df=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},ER=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],PR=e=>ER.some(t=>t.test(e)),xR="/bin/ps",TR=()=>SR(xR,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
156
+ `),Nf=(e=TR)=>{try{return e().some(PR)}catch{return!0}};import{Chalk as CR}from"chalk";import Gc from"node:process";var Jc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},$R=new Set(["warn","fail"]),AR=24,Jr=" ",_f=" ",OR=(e,t)=>{let r=e.split(/\s+/).filter(s=>s.length>0),n=[],o="";for(let s of r)o.length===0?o=s:`${o} ${s}`.length<=t?o=`${o} ${s}`:(n.push(o),o=s);return o.length>0&&n.push(o),n.length>0?n:[""]},Mf=e=>{let t={ok:0,changed:0,skipped:0,manual:0,warn:0,fail:0};for(let r of e)t[r.status]+=1;return t},IR=e=>{let t=new CR({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)}},jf=(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),DR=(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=jf(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}},NR=(e,t,r,n)=>{let o=DR(Mf(e.rows),e.rows.length,t,r),s=Math.max(1,n-Jr.length-e.label.length-o.plainWidth);return`${Jr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},_R=(e,t,r,n,o)=>{let s=$R.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=_f.length+i+1+t+2,p=Math.max(AR,o-u),[m,...g]=OR(e.message,p),y=" ".repeat(u),b=x=>s?x:r.dim(x);return[`${_f}${c(n[e.status])} ${l} ${b(m??"")}`.trimEnd(),...g.map(x=>`${y}${b(x)}`),...(e.notes??[]).map(x=>`${y}${x}`.trimEnd())]},MR=(e,t,r,n,o)=>{let s=Mf(t),i=n.rule.repeat(Math.max(12,Math.min(o-Jr.length,56))),a=jf(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[`${Jr}${r.dim(i)}`,`${Jr}${c}${l.join("")}`]},Kc=(e,t={})=>{let r=t.width??80,n=IR(t.color??!1),o=t.unicode??!0?Jc.unicode:Jc.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,"",`${Jr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[NR(u,n,o,r),...u.rows.flatMap(p=>_R(p,c,n,o,r)),""]);return[a,"",...l,...MR(e,i,n,o,r)]},jR=new Set(["","0","false","none"]),FR=["LC_ALL","LC_CTYPE","LANG"],LR=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!jR.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,BR=(e,t)=>{if(t)return!1;let r=FR.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Hc=(e={})=>{let t=e.env??Gc.env,r=e.stream??Gc.stderr;return{color:LR(t,r),unicode:BR(t,e.ascii??!1),width:r.columns??80}},tt=(e,t={})=>{(t.write??(n=>{Gc.stderr.write(n)}))(`${Kc(e,Hc(t)).join(`
157
157
  `)}
158
- `)};var LR="Tools & CLIs",BR="Shell & integration",UR="Project config",VR="Doppler env tokens",WR="Dev proxy (portless)",GR="Claude Code plugin",JR=`portless serving TLS on :${St}`,qc=[[LR,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[BR,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[UR,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[VR,["tokens.json present","env tokens configured","tokens.json perms"]],[WR,["portless installed","portless node","portless service target",JR,"portless CA chain valid","portless CA trusted","portless routes"]],[GR,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],jf="Other",KR=qc.map(([e])=>e),HR=new Map(qc.flatMap(([e,t])=>t.map(r=>[r,e]))),f0=qc.flatMap(([,e])=>e),Yc=new Set(["portless routes","tokens.json perms"]),qR=e=>{let t=new Map;for(let n of e){let o=HR.get(n.name)??jf,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...KR,jf].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var YR=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ne(e)}},zR=e=>{let t=e.filter(r=>r.status==="fail"&&Yc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:qR(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:YR(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var zc=(e,t={})=>{tt(zR(e),t)};var XR=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),ZR=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>XR(t[1])),QR=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:ZR(t[1])},eS=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},tS=e=>{let t=e.split(`
159
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:eS(t.slice(10))},Ff=(e,t)=>{try{return e==="darwin"?QR(t):e==="linux"?tS(t):null}catch{return null}};import{Buffer as og}from"node:buffer";import Te from"node:fs/promises";import nt from"node:path";import sg from"node:process";import{$ as di}from"zx";import rS from"node:process";var co=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Lf=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(J())throw new C({status:"argument_required",argument:e,agentMode:_.source},2,t);if(!rS.stdin.isTTY)throw new f(void 0,t)},Nt=async e=>{Lf("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new co;return r},_t=async(e,t)=>{Lf("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new co;return n};import{$ as Kf}from"zx";import{$ as P0}from"zx";import{$ as Hr}from"zx";import{$ as Bf}from"zx";var Xc=async e=>{let{operation:t}=e;try{await Bf({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await Bf({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},oS=4,Kr=async e=>{let{operation:t}=e,r=await qp();if(r.length===0)return;d.error(`working tree has uncommitted changes:
158
+ `)};var UR="Tools & CLIs",VR="Shell & integration",WR="Project config",GR="Doppler env tokens",JR="Dev proxy (portless)",KR="Claude Code plugin",HR=`portless serving TLS on :${St}`,qc=[[UR,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[VR,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[WR,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[GR,["tokens.json present","env tokens configured","tokens.json perms"]],[JR,["portless installed","portless node","portless service target",HR,"portless CA chain valid","portless CA trusted","portless routes"]],[KR,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],Ff="Other",qR=qc.map(([e])=>e),YR=new Map(qc.flatMap(([e,t])=>t.map(r=>[r,e]))),w0=qc.flatMap(([,e])=>e),Yc=new Set(["portless routes","tokens.json perms"]),zR=e=>{let t=new Map;for(let n of e){let o=YR.get(n.name)??Ff,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...qR,Ff].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var XR=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ne(e)}},ZR=e=>{let t=e.filter(r=>r.status==="fail"&&Yc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:zR(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:XR(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var zc=(e,t={})=>{tt(ZR(e),t)};var QR=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),eS=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>QR(t[1])),tS=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:eS(t[1])},rS=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},nS=e=>{let t=e.split(`
159
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:rS(t.slice(10))},Lf=(e,t)=>{try{return e==="darwin"?tS(t):e==="linux"?nS(t):null}catch{return null}};import{Buffer as og}from"node:buffer";import Te from"node:fs/promises";import nt from"node:path";import sg from"node:process";import{$ as di}from"zx";import oS from"node:process";var co=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Bf=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(K())throw new C({status:"argument_required",argument:e,agentMode:_.source},2,t);if(!oS.stdin.isTTY)throw new f(void 0,t)},_t=async e=>{Bf("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new co;return r},Mt=async(e,t)=>{Bf("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new co;return n};import{$ as Hf}from"zx";import{$ as A0}from"zx";import{$ as Hr}from"zx";import{$ as Uf}from"zx";var Xc=async e=>{let{operation:t}=e;try{await Uf({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await Uf({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},iS=4,Kr=async e=>{let{operation:t}=e,r=await qp();if(r.length===0)return;d.error(`working tree has uncommitted changes:
160
160
  ${r.join(`
161
- `)}`);let n=r.slice(0,oS),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},lo=async e=>{let{operation:t,base:r}=e;if(await Cr()===r)return;let n=(await qe(await P())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},xe=async e=>{let{operation:t}=e;if(await zp())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await Kr({operation:t})};var sS=e=>e.map(t=>({pr:t,id:K(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Hp(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),uo=200,Uf=(e,t)=>{e.length<uo||d.warn({source:t,limit:uo},`\u26A0\uFE0F ${t} returned ${uo} PRs \u2014 the page is full, so older release PRs may be missing`)},iS=async()=>{let[e,t]=await Promise.all([Hr`gh pr list --limit ${uo} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Hr`gh pr list --limit ${uo} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Uf(r,"release PR discovery (base dev)"),Uf(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)}))},po="find open release PRs",Vf=async()=>{try{let e=await iS();if(e.length===0)throw new f(void 0,{operation:po,remediation:"open a release PR first, or check you are in the right repo"});return sS(e)}catch(e){throw e instanceof f?e:(d.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},ti=async()=>(await Vf()).map(t=>t.headRefName),aS=e=>{let t=mo(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Zc(e.title)!==t;return(r||e.dualBase)&&d.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await Vf()).map(aS),ri=async e=>{let{branch:t,body:r}=e;try{await Hr({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}},cS=async(e,t)=>{let r=Hr({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=Kp(t,n),a=rt(n),c=Hr({quiet:!0}),l=we(t),u=fo(r,o);try{await Kr({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await cS(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Hr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Qc}from"zx";var qr=async e=>{let t=await Qc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},el=async e=>{let t=await Qc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},tl=async e=>{try{let t=await Qc`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import ho from"node:process";var lS="x-seraph-loginreason",uS="AUTHENTICATED_FAILED",dS=(e,t=160)=>{let r=e.split(`
162
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Gf=(e,t)=>t===uS||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Wf=(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}`,Yr=class extends Error{status;kind;body;context;constructor(t){let r=Gf(t.status,t.seraphLoginReason),n=dS(t.body);super(n===""?`${t.context}: ${Wf(r,t.status)}`:`${t.context}: ${Wf(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},go=e=>e instanceof Yr,Jf=e=>e.headers.get(lS);var zr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Yr({status:e.status,seraphLoginReason:Jf(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},ir=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,rl=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 zr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Xr=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 zr(a,"Failed to get Jira project versions"),await a.json()},ft=async(e,t)=>(await Xr(t)).find(o=>o.name===e)||null,Zr=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await zr(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}},nl=async(e,t)=>{let{versionName:r}=e,n=await ft(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Zr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Qr=async()=>{let e=ho.env.JIRA_BASE_URL,t=ho.env.JIRA_TOKEN||ho.env.JIRA_API_TOKEN,r=ho.env.JIRA_PROJECT_ID,n=ho.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
163
- `);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},gt=async()=>{try{return await Qr()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var oi=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 zr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},ol=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 zr(c,"Failed to remove Jira version")};var Hf="dev",qf={regular:"dev",hotfix:"main"},rt=e=>qf[e],mo=e=>{let t=Object.entries(qf).find(([,r])=>r===e);return t?t[0]:null},fo=(e,t)=>(t??"").trim()!==""?`${e}
161
+ `)}`);let n=r.slice(0,iS),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},lo=async e=>{let{operation:t,base:r}=e;if(await $r()===r)return;let n=(await qe(await P())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},xe=async e=>{let{operation:t}=e;if(await zp())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await Kr({operation:t})};var aS=e=>e.map(t=>({pr:t,id:H(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Hp(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),uo=200,Vf=(e,t)=>{e.length<uo||d.warn({source:t,limit:uo},`\u26A0\uFE0F ${t} returned ${uo} PRs \u2014 the page is full, so older release PRs may be missing`)},cS=async()=>{let[e,t]=await Promise.all([Hr`gh pr list --limit ${uo} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Hr`gh pr list --limit ${uo} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Vf(r,"release PR discovery (base dev)"),Vf(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)}))},po="find open release PRs",Wf=async()=>{try{let e=await cS();if(e.length===0)throw new f(void 0,{operation:po,remediation:"open a release PR first, or check you are in the right repo"});return aS(e)}catch(e){throw e instanceof f?e:(d.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},ti=async()=>(await Wf()).map(t=>t.headRefName),lS=e=>{let t=mo(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Zc(e.title)!==t;return(r||e.dualBase)&&d.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await Wf()).map(lS),ri=async e=>{let{branch:t,body:r}=e;try{await Hr({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}},uS=async(e,t)=>{let r=Hr({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=Kp(t,n),a=rt(n),c=Hr({quiet:!0}),l=we(t),u=fo(r,o);try{await Kr({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await uS(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Hr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Qc}from"zx";var qr=async e=>{let t=await Qc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},el=async e=>{let t=await Qc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},tl=async e=>{try{let t=await Qc`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import ho from"node:process";var dS="x-seraph-loginreason",pS="AUTHENTICATED_FAILED",mS=(e,t=160)=>{let r=e.split(`
162
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Jf=(e,t)=>t===pS||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Gf=(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}`,Yr=class extends Error{status;kind;body;context;constructor(t){let r=Jf(t.status,t.seraphLoginReason),n=mS(t.body);super(n===""?`${t.context}: ${Gf(r,t.status)}`:`${t.context}: ${Gf(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},go=e=>e instanceof Yr,Kf=e=>e.headers.get(dS);var zr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Yr({status:e.status,seraphLoginReason:Kf(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},ar=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,rl=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 zr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Xr=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 zr(a,"Failed to get Jira project versions"),await a.json()},ft=async(e,t)=>(await Xr(t)).find(o=>o.name===e)||null,Zr=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await zr(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}},nl=async(e,t)=>{let{versionName:r}=e,n=await ft(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Zr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Qr=async()=>{let e=ho.env.JIRA_BASE_URL,t=ho.env.JIRA_TOKEN||ho.env.JIRA_API_TOKEN,r=ho.env.JIRA_PROJECT_ID,n=ho.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
163
+ `);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},gt=async()=>{try{return await Qr()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var oi=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 zr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},ol=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 zr(c,"Failed to remove Jira version")};var qf="dev",Yf={regular:"dev",hotfix:"main"},rt=e=>Yf[e],mo=e=>{let t=Object.entries(Yf).find(([,r])=>r===e);return t?t[0]:null},fo=(e,t)=>(t??"").trim()!==""?`${e}
164
164
 
165
165
  ${t}`:`${e}
166
- `,sl=async(e="regular")=>{let t=rt(e),r=Kf({quiet:!0});await r`git fetch origin`,await r`git switch ${t}`;try{await r`git pull --ff-only origin ${t}`}catch(n){let o=await Kf({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},pS=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await ft(t,r);if(!s)return(await rl({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await Zr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},il=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ne(t),c=await pS({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=ir(r,c),u=await ni({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:Y(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},si=async()=>{let e=new Map,t=await gt();if(!t)return e;try{let r=await Xr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){d.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},ae=async()=>{let e=await si();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},yo=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Zc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",ii=e=>e.flatMap(t=>{let r=K(t);return r?[{branch:t,id:r,label:Y(r)}]:[]}),ht=e=>{try{return we(me(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},vo=e=>{if(e===Hf)return Hf;let t=K(e);return t?Y(t):e},yt=e=>e.flatMap(t=>{let r=K(t);return r?[Y(r)]:[]}),mS=(e,t)=>t?t.get(e)||"regular":void 0,ce=e=>{let{branches:t,descriptions:r,types:n}=e;return ii(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ne(s)),type:mS(o,n)}))};import Yf from"node:fs/promises";import fS from"node:path";import{$ as al}from"zx";var B="pnpm-lock.yaml",gS=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Xf=async(e,t)=>{let r=fS.join(e,B),n=`${t}:${B}`;try{let o=await al({cwd:e,quiet:!0})`git show ${n}`;await Yf.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${B} to start from: ${zf(o)}`}}try{await al({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${B}: ${zf(o)}`}}return gS.test(await Yf.readFile(r,"utf8"))?{ok:!1,reason:`${B} still carries conflict markers after pnpm ran`}:(await al({cwd:e,quiet:!0})`git add -- ${B}`,{ok:!0})},zf=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as ar}from"zx";var cl="Merge remote-tracking branch 'origin/dev' into ",Zf=e=>String(e.stderr??e.message??e).trim(),hS=async e=>{try{return(await ar({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
167
- `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},yS=async(e,t)=>{let r=Zf(t),n=await hS(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await em(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Qf=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await De(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await vS({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},vS=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await De(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await _n(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await ja(r),await ar({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${cl}${n}`;await ar({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await ar({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 yS(r,i)}}finally{await Fa(r)}},eg=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),tg="pnpm install --frozen-lockfile",rg=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await ja(t),await ar({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await ar({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,Zf(a))}finally{await Fa(t)}return{kept:o,failed:s}},wo=async(e,t,r="origin/dev")=>{await ar({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await _n(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import ll from"node:process";var ai=new Set,ci=e=>(ai.add(e),()=>{ai.delete(e)}),wS=async()=>{for(let e of[...ai])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}ai.clear()},kS=["SIGINT","SIGTERM"],ng=async(e,t={})=>{let{register:r=(i,a)=>{ll.on(i,a)},unregister:n=(i,a)=>{ll.off(i,a)},exit:o=i=>{ll.exit(i)}}=t,s=new Map;for(let i of kS){let a=()=>{wS().then(()=>{o(ym(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var bS="pnpm install --frozen-lockfile --ignore-scripts",RS="pnpm install --frozen-lockfile",ig=64*1024,dg=4096,bo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-dg)},j=async(e,t)=>(await di({cwd:e,quiet:!0})`git ${t}`).stdout,ul=e=>e.split(`
166
+ `,sl=async(e="regular")=>{let t=rt(e),r=Hf({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 Hf({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},fS=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await ft(t,r);if(!s)return(await rl({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await Zr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},il=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ne(t),c=await fS({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=ar(r,c),u=await ni({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:z(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},si=async()=>{let e=new Map,t=await gt();if(!t)return e;try{let r=await Xr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){d.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},ae=async()=>{let e=await si();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},yo=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Zc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",ii=e=>e.flatMap(t=>{let r=H(t);return r?[{branch:t,id:r,label:z(r)}]:[]}),ht=e=>{try{return we(pe(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},vo=e=>{if(e===qf)return qf;let t=H(e);return t?z(t):e},yt=e=>e.flatMap(t=>{let r=H(t);return r?[z(r)]:[]}),gS=(e,t)=>t?t.get(e)||"regular":void 0,ce=e=>{let{branches:t,descriptions:r,types:n}=e;return ii(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ne(s)),type:gS(o,n)}))};import zf from"node:fs/promises";import hS from"node:path";import{$ as al}from"zx";var B="pnpm-lock.yaml",yS=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Zf=async(e,t)=>{let r=hS.join(e,B),n=`${t}:${B}`;try{let o=await al({cwd:e,quiet:!0})`git show ${n}`;await zf.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${B} to start from: ${Xf(o)}`}}try{await al({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${B}: ${Xf(o)}`}}return yS.test(await zf.readFile(r,"utf8"))?{ok:!1,reason:`${B} still carries conflict markers after pnpm ran`}:(await al({cwd:e,quiet:!0})`git add -- ${B}`,{ok:!0})},Xf=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as cr}from"zx";var cl="Merge remote-tracking branch 'origin/dev' into ",vS=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},wS=2048,kS=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-wS)).filter(s=>s.length>0).join(`
167
+ `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},bS=async e=>{try{return(await cr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
168
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},RS=async(e,t)=>{let r=vS(t),n=await bS(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await em(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Qf=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await De(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await SS({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},SS=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await De(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await _n(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await ja(r),await cr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${cl}${n}`;await cr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await cr({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:a===o?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:n,...await RS(r,i)}}finally{await Fa(r)}},eg=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),tg="pnpm install --frozen-lockfile",rg=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await ja(t),await cr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await cr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,kS(a))}finally{await Fa(t)}return{kept:o,failed:s}},wo=async(e,t,r="origin/dev")=>{await cr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await _n(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import ll from"node:process";var ai=new Set,ci=e=>(ai.add(e),()=>{ai.delete(e)}),ES=async()=>{for(let e of[...ai])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}ai.clear()},PS=["SIGINT","SIGTERM"],ng=async(e,t={})=>{let{register:r=(i,a)=>{ll.on(i,a)},unregister:n=(i,a)=>{ll.off(i,a)},exit:o=i=>{ll.exit(i)}}=t,s=new Map;for(let i of PS){let a=()=>{ES().then(()=>{o(ym(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var xS="pnpm install --frozen-lockfile --ignore-scripts",TS="pnpm install --frozen-lockfile",ig=64*1024,dg=4096,bo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-dg)},j=async(e,t)=>(await di({cwd:e,quiet:!0})`git ${t}`).stdout,ul=e=>e.split(`
168
169
  `).map(t=>t.trim()).filter(t=>t.length>0),pi=e=>e.split("\0").filter(t=>t.length>0),li=async(e,t)=>{try{return(await j(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},pg=async e=>nt.resolve(e,(await j(e,["rev-parse","--git-common-dir"])).trim()),dl=e=>e.then(()=>!0,()=>!1),ko=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),pl=e=>e?.length===1&&e[0]===B,mg=async e=>nt.join(await pg(e),"infra-kit","merge-dev-resolutions"),ml=async(e,t)=>nt.join(await mg(e),`${Zp(t)}.json`),fg=async e=>{try{return JSON.parse(await Te.readFile(e,"utf8"))}catch{return null}},tn=async(e,t)=>{let r=await ml(e,t.branch);await Te.mkdir(nt.dirname(r),{recursive:!0}),await Te.writeFile(r,`${JSON.stringify(t,null,2)}
169
- `)},gg=async e=>{let t=await mg(e),r=await Te.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>fg(nt.join(t,o))))).filter(o=>o!==null)},hg=async e=>Promise.all((await gg(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await dl(Te.stat(t.worktreePath))}))),ag=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),fl=async(e,t,r)=>{await j(e,["worktree","remove","--force",r]).catch(()=>Te.rm(r,{recursive:!0,force:!0})),await Te.rm(await ml(e,t),{force:!0}).catch(()=>{}),await j(e,["worktree","prune"]).catch(()=>{})},yg=async e=>pi(await j(e,["diff","--name-only","-z","--diff-filter=U"])),ui=async e=>pi(await j(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),SS=async(e,t)=>{let r=(await j(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await dl(Te.stat(nt.join(await pg(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(ul(await j(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},vg=e=>e.split("/").includes("node_modules"),mi=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=pi(await j(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await ES(e),...o].filter(a=>!r.has(a)),i=(await ui(e)).filter(a=>!n.has(a)&&!vg(a));return[...new Set([...s,...i,...await PS(e)])].sort()},ES=async e=>{let t=pi(await j(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},PS=async e=>(await j(e,["ls-files","-v"])).split(`
170
- `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),xS=async e=>{let t=`:(exclude)${B}`;try{return await j(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
171
- `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},TS=async(e,t)=>{let r=[];for(let n of t)(await dl(Te.lstat(nt.join(e,n)))||(await j(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await j(e,["--literal-pathspecs","add","-A","--",...r])},cg=async e=>(await j(e,["write-tree"])).trim(),wg=async e=>(await j(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),CS=e=>e?`${RS} && ${e}`:bS,$S=async(e,t)=>{try{return await di({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:bo(r)}}},kg=async(e,t)=>{let r=(await j(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await j(e,["diff","--cached","--stat",l,"--",B])).trim(),o=t.conflictPaths.includes(B)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await j(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${B}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let u=/^diff --git a\/(.*) b\//.exec(l)?.[1];return u&&i.has(u)?`# rerere (recorded resolution)
172
- ${l}`:l}).join(""),c=og.byteLength(a)>ig;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?og.from(a).subarray(0,ig).toString():a,resolutionDiffTruncated:c}},bg=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await AS(t,s,n));return o},AS=async(e,t,r)=>{let n=await fg(await ml(e,t));if(n)return{resolution:ag(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await De(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=Qp(e,t),i=()=>fl(e,t,s),a=ci(i);try{await j(e,["worktree","prune"]),await Te.mkdir(nt.dirname(s),{recursive:!0}),await j(e,["worktree","add","--detach",s,o]),await di({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${cl+t}`.catch(()=>{});let c=await yg(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await li(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await j(e,["--version"])).trim()})`};let u=await SS(s,c),p=pl(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:u,ignoredAtHandoff:await ui(s),lockfileOnly:p,cliVersion:U.version,createdAt:new Date().toISOString()};return await tn(e,m),{resolution:ag(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:bo(c)}}finally{a()}},Rg=async e=>{let{cwd:t,versions:r,all:n}=e,o=await gg(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=we(me(c)),u=o.find(p=>p.branch===l);if(!u)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return u});if(n||o.length===0)return o;let i=await _t(ce({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},OS=async(e,t)=>{let r=await Te.realpath(t).catch(()=>null);if(!r)return!1;let n=await qe(e);for(let o of n)if(await Te.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},en=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Sg=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 OS(e,n))return en(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await li(n,"HEAD"),i=await li(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?MS(e,t,o,r):IS(t,o,s,i)},IS=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return en(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 wg(o),i=n?null:await li(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 en(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await mi(o,e);return c.length>0?en(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(B),...await kg(o,e)}},lg=async(e,t)=>{let r=ul(await j(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},DS=async(e,t)=>{let r=t.worktreePath,n=await lg(r,B),o=t.lockfileBlob,s=await Xf(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[B]};let i=await lg(r,B);if(i!==null&&i!==o&&(t.lockfileBlob=i,await tn(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${B} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[B]}:{code:"out-of-scope-edit",detail:`${B} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[B]};let a=await mi(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},NS=async(e,t)=>{let r=t.worktreePath;await TS(r,t.conflictPaths.filter(i=>i!==B));let n=await mi(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await yg(r)).filter(i=>i!==B);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await xS(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${bo(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(B)?DS(e,t):null},_S=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 $S(o,n);if(!i.ok)return i;let a=(await ui(o)).filter(c=>!s.has(c)&&!vg(c)&&nt.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await tn(e,t),i},MS=async(e,t,r,n)=>{let o=t.worktreePath,s=await NS(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(B),a=await cg(o),c=await _S(e,t,a,CS(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return en(l,"verify-failed",c.reason??"the verify command failed");let u=await mi(o,t),p=ul(await j(o,["diff","--name-only"]));return u.length>0||p.length>0||await cg(o)!==a?en(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await tn(e,t)),{...l,...await kg(o,t)})},jS=12e4,FS=async(e,t=jS)=>{let r=di({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...sg.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&sg.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:bo(s)};let i=(await j(e,["rev-parse","--git-path","index.lock"])).trim();return await Te.rm(nt.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},LS={"verify-failed":"verify-failed","tree-changed":"tree-changed"},BS=e=>{let t=e.blocked;return{branch:e.branch,status:LS[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},US=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 FS(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await j(o,["rev-parse","HEAD"])).trim(),c=(await j(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await tn(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 wg(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}},VS=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 wo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${bo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await De(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await _n(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},WS=e=>{d.info(`
173
- \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}`)},Eg=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Rg({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),ko();if(i)return ug(t,a,o,s);let c=[];for(let m of a){let g=await Sg(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await tn(t,m)),c.push(g)}WS(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new C({status:"refused",plan:l,agentMode:_.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await L(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:GS(p)})}catch(m){if(!dt(m))throw m;return{...ko(),declined:!0}}return ug(t,a,o,p)},Pg=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},GS=e=>{let t=[],r=!1;for(let o of mm())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"]},JS=async(e,t,r,n)=>{let o=await Sg(e,t,r);if(o.blocked)return BS(o);let s=await US(e,o,t,n);if(!("sha"in s))return s;let i=await VS(e,t,s.sha);return i==="keep"?s:i},KS=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(`
174
- \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await Os(e,r),o=[];for(let s of t){let i=n.pushed||await $r(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(-dg)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
175
- `)[0]}}},ug=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await JS(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await KS(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 fl(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}},xg=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Rg({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),ko();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await L(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!dt(a))throw a;return{...ko(),declined:!0}}for(let a of s)await fl(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...ko(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import HS from"node:fs";import qS from"node:os";import YS from"node:path";var zS="infra-kit.json",XS="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)",ZS="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Ro=async()=>{let e;try{e=await P()}catch{return null}let t=e.trim();return t===""||t===qS.homedir()?null:t},Tg=async()=>{let e=await Ro();return e===null&&d.info(XS),e},QS=async()=>{let e=await Ro();return e===null?null:HS.existsSync(YS.join(e,zS))?e:(d.info(ZS),null)};var eE=async e=>{try{return await Pe(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Cg=async({dryRun:e=!1}={})=>{let t=await QS(),r=U.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await Zn(t,{version:r,dryRun:e})];for(let o of await eE(t)){let s=await er(o);n.push(...await Qn(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import de from"node:fs";import ki from"node:os";import Q from"node:path";import Pl from"node:process";import gl from"node:fs";import $g from"node:os";import Ag from"node:path";import tE from"node:process";import{z as gi}from"zod";var Og=e=>{try{return gl.readFileSync(e,"utf-8")}catch{return null}},rn="claude in chrome",rE="com.anthropic.claude_code_browser_extension",fi="run `/chrome` inside Claude Code to set up Claude in Chrome",nE={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},oE=e=>{try{return gl.accessSync(e,gl.constants.X_OK),!0}catch{return!1}},Ig=e=>{try{return JSON.parse(e)}catch{return null}},sE=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,So=(e={})=>{let t=e.platform??tE.platform,r=e.home??$g.homedir(),n=e.readText??Og,o=e.isExecutable??oE,s=nE[t];if(s===void 0)return{name:rn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=Ag.join(r,...s,`${rE}.json`),a=n(i);if(a===null)return{name:rn,status:"warn",message:`Chrome native host not registered \u2014 ${fi}`};let c=gi.object({path:gi.string().min(1)}).safeParse(Ig(a));if(!c.success)return{name:rn,status:"fail",message:`${v(i)} has no host path \u2014 ${fi} again`};let l=c.data.path;if(!o(l))return{name:rn,status:"fail",message:`Chrome native host ${v(l)} is missing or not executable \u2014 ${fi} again`};let u=sE.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:rn,status:"fail",message:`Chrome native host runs ${v(u)}, which no longer exists \u2014 ${fi} again`}:{name:rn,status:"pass",message:`Native host registered (${v(l)}); /infra-kit:doctor checks the live connection`}},hl=(e={})=>{let t=e.home??$g.homedir(),r=e.readText??Og,n=gi.object({claudeInChromeDefaultEnabled:gi.boolean().optional()}).safeParse(Ig(r(Ag.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import yi from"node:fs/promises";import iE from"node:path";import aE from"node:process";var Dg=` // "envManagement": { // required in layer 1; provider-tagged
170
+ `)},gg=async e=>{let t=await mg(e),r=await Te.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>fg(nt.join(t,o))))).filter(o=>o!==null)},hg=async e=>Promise.all((await gg(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await dl(Te.stat(t.worktreePath))}))),ag=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),fl=async(e,t,r)=>{await j(e,["worktree","remove","--force",r]).catch(()=>Te.rm(r,{recursive:!0,force:!0})),await Te.rm(await ml(e,t),{force:!0}).catch(()=>{}),await j(e,["worktree","prune"]).catch(()=>{})},yg=async e=>pi(await j(e,["diff","--name-only","-z","--diff-filter=U"])),ui=async e=>pi(await j(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),CS=async(e,t)=>{let r=(await j(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await dl(Te.stat(nt.join(await pg(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(ul(await j(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},vg=e=>e.split("/").includes("node_modules"),mi=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=pi(await j(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await $S(e),...o].filter(a=>!r.has(a)),i=(await ui(e)).filter(a=>!n.has(a)&&!vg(a));return[...new Set([...s,...i,...await AS(e)])].sort()},$S=async e=>{let t=pi(await j(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},AS=async e=>(await j(e,["ls-files","-v"])).split(`
171
+ `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),OS=async e=>{let t=`:(exclude)${B}`;try{return await j(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
172
+ `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},IS=async(e,t)=>{let r=[];for(let n of t)(await dl(Te.lstat(nt.join(e,n)))||(await j(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await j(e,["--literal-pathspecs","add","-A","--",...r])},cg=async e=>(await j(e,["write-tree"])).trim(),wg=async e=>(await j(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),DS=e=>e?`${TS} && ${e}`:xS,NS=async(e,t)=>{try{return await di({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:bo(r)}}},kg=async(e,t)=>{let r=(await j(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await j(e,["diff","--cached","--stat",l,"--",B])).trim(),o=t.conflictPaths.includes(B)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await j(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${B}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let u=/^diff --git a\/(.*) b\//.exec(l)?.[1];return u&&i.has(u)?`# rerere (recorded resolution)
173
+ ${l}`:l}).join(""),c=og.byteLength(a)>ig;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?og.from(a).subarray(0,ig).toString():a,resolutionDiffTruncated:c}},bg=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await _S(t,s,n));return o},_S=async(e,t,r)=>{let n=await fg(await ml(e,t));if(n)return{resolution:ag(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await De(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=Qp(e,t),i=()=>fl(e,t,s),a=ci(i);try{await j(e,["worktree","prune"]),await Te.mkdir(nt.dirname(s),{recursive:!0}),await j(e,["worktree","add","--detach",s,o]),await di({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${cl+t}`.catch(()=>{});let c=await yg(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await li(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await j(e,["--version"])).trim()})`};let u=await CS(s,c),p=pl(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:u,ignoredAtHandoff:await ui(s),lockfileOnly:p,cliVersion:U.version,createdAt:new Date().toISOString()};return await tn(e,m),{resolution:ag(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:bo(c)}}finally{a()}},Rg=async e=>{let{cwd:t,versions:r,all:n}=e,o=await gg(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=we(pe(c)),u=o.find(p=>p.branch===l);if(!u)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return u});if(n||o.length===0)return o;let i=await Mt(ce({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},MS=async(e,t)=>{let r=await Te.realpath(t).catch(()=>null);if(!r)return!1;let n=await qe(e);for(let o of n)if(await Te.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},en=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Sg=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 MS(e,n))return en(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await li(n,"HEAD"),i=await li(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?US(e,t,o,r):jS(t,o,s,i)},jS=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return en(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 wg(o),i=n?null:await li(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 en(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await mi(o,e);return c.length>0?en(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(B),...await kg(o,e)}},lg=async(e,t)=>{let r=ul(await j(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},FS=async(e,t)=>{let r=t.worktreePath,n=await lg(r,B),o=t.lockfileBlob,s=await Zf(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[B]};let i=await lg(r,B);if(i!==null&&i!==o&&(t.lockfileBlob=i,await tn(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${B} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[B]}:{code:"out-of-scope-edit",detail:`${B} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[B]};let a=await mi(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},LS=async(e,t)=>{let r=t.worktreePath;await IS(r,t.conflictPaths.filter(i=>i!==B));let n=await mi(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await yg(r)).filter(i=>i!==B);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await OS(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${bo(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(B)?FS(e,t):null},BS=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 NS(o,n),a=(await ui(o)).filter(c=>!s.has(c)&&!vg(c)&&nt.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await tn(e,t),i},US=async(e,t,r,n)=>{let o=t.worktreePath,s=await LS(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(B),a=await cg(o),c=await BS(e,t,a,DS(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return en(l,"verify-failed",c.reason??"the verify command failed");let u=await mi(o,t),p=ul(await j(o,["diff","--name-only"]));return u.length>0||p.length>0||await cg(o)!==a?en(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await tn(e,t)),{...l,...await kg(o,t)})},VS=12e4,WS=async(e,t=VS)=>{let r=di({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...sg.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&sg.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:bo(s)};let i=(await j(e,["rev-parse","--git-path","index.lock"])).trim();return await Te.rm(nt.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},GS={"verify-failed":"verify-failed","tree-changed":"tree-changed"},JS=e=>{let t=e.blocked;return{branch:e.branch,status:GS[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},KS=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 WS(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await j(o,["rev-parse","HEAD"])).trim(),c=(await j(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await tn(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 wg(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}},HS=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 wo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${bo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await De(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await _n(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},qS=e=>{d.info(`
174
+ \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?d.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):d.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Eg=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Rg({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),ko();if(i)return ug(t,a,o,s);let c=[];for(let m of a){let g=await Sg(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await tn(t,m)),c.push(g)}qS(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new C({status:"refused",plan:l,agentMode:_.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await L(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:YS(p)})}catch(m){if(!dt(m))throw m;return{...ko(),declined:!0}}return ug(t,a,o,p)},Pg=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},YS=e=>{let t=[],r=!1;for(let o of mm())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"]},zS=async(e,t,r,n)=>{let o=await Sg(e,t,r);if(o.blocked)return JS(o);let s=await KS(e,o,t,n);if(!("sha"in s))return s;let i=await HS(e,t,s.sha);return i==="keep"?s:i},XS=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));d.info(`
175
+ \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await Os(e,r),o=[];for(let s of t){let i=n.pushed||await Ar(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(-dg)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
176
+ `)[0]}}},ug=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await zS(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await XS(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 fl(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}},xg=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Rg({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),ko();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await L(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!dt(a))throw a;return{...ko(),declined:!0}}for(let a of s)await fl(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...ko(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import ZS from"node:fs";import QS from"node:os";import eE from"node:path";var tE="infra-kit.json",rE="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)",nE="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Ro=async()=>{let e;try{e=await P()}catch{return null}let t=e.trim();return t===""||t===QS.homedir()?null:t},Tg=async()=>{let e=await Ro();return e===null&&d.info(rE),e},oE=async()=>{let e=await Ro();return e===null?null:ZS.existsSync(eE.join(e,tE))?e:(d.info(nE),null)};var sE=async e=>{try{return await Pe(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Cg=async({dryRun:e=!1}={})=>{let t=await oE(),r=U.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await Zn(t,{version:r,dryRun:e})];for(let o of await sE(t)){let s=await tr(o);n.push(...await Qn(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import ue from"node:fs";import ki from"node:os";import ee from"node:path";import Pl from"node:process";import gl from"node:fs";import $g from"node:os";import Ag from"node:path";import iE from"node:process";import{z as gi}from"zod";var Og=e=>{try{return gl.readFileSync(e,"utf-8")}catch{return null}},rn="claude in chrome",aE="com.anthropic.claude_code_browser_extension",fi="run `/chrome` inside Claude Code to set up Claude in Chrome",cE={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},lE=e=>{try{return gl.accessSync(e,gl.constants.X_OK),!0}catch{return!1}},Ig=e=>{try{return JSON.parse(e)}catch{return null}},uE=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,So=(e={})=>{let t=e.platform??iE.platform,r=e.home??$g.homedir(),n=e.readText??Og,o=e.isExecutable??lE,s=cE[t];if(s===void 0)return{name:rn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=Ag.join(r,...s,`${aE}.json`),a=n(i);if(a===null)return{name:rn,status:"warn",message:`Chrome native host not registered \u2014 ${fi}`};let c=gi.object({path:gi.string().min(1)}).safeParse(Ig(a));if(!c.success)return{name:rn,status:"fail",message:`${v(i)} has no host path \u2014 ${fi} again`};let l=c.data.path;if(!o(l))return{name:rn,status:"fail",message:`Chrome native host ${v(l)} is missing or not executable \u2014 ${fi} again`};let u=uE.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:rn,status:"fail",message:`Chrome native host runs ${v(u)}, which no longer exists \u2014 ${fi} again`}:{name:rn,status:"pass",message:`Native host registered (${v(l)}); /infra-kit:doctor checks the live connection`}},hl=(e={})=>{let t=e.home??$g.homedir(),r=e.readText??Og,n=gi.object({claudeInChromeDefaultEnabled:gi.boolean().optional()}).safeParse(Ig(r(Ag.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import yi from"node:fs/promises";import dE from"node:path";import pE from"node:process";var Dg=` // "envManagement": { // required in layer 1; provider-tagged
176
177
  // "provider": "doppler",
177
178
  // "config": { "name": "my-doppler-project" }
178
179
  // },
@@ -320,102 +321,102 @@ ${Dg}
320
321
  // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
321
322
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
322
323
  }
323
- `;var Ng=!1,cE=e=>e.replace(/\.json$/,".example.jsonc"),lE=async e=>{try{return await yi.readFile(e,"utf-8")}catch{return null}},nn=async e=>{let t=e.userProject,r=cE(t);await yi.mkdir(iE.dirname(t),{recursive:!0});let n=!await z(t);n&&await yi.writeFile(t,`{}
324
- `,"utf-8");let o=vl(e.projectName),s=await lE(r)!==o;return s&&await yi.writeFile(r,o,"utf-8"),n&&Mn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},on=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,kl=async()=>{if(aE.env.INFRA_KIT_NO_SEED||Ng)return;Ng=!0;let e;try{e=await H()}catch{return}if(await z(e.main))try{let t=await nn(e);t.createdConfig?d.info(on(t)):t.refreshedExample&&d.debug(`Refreshed ${v(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import{spawn as kE}from"node:child_process";import Wg from"node:fs";import ln from"node:process";import{fileURLToPath as Gg}from"node:url";import vi from"node:fs";import sn from"node:path";var _g="auto-setup.json",uE="auto-setup.log",dE="auto-setup.lock",Mg="auto-setup.notified",pE=3,mE=3600*1e3,fE=()=>sn.join(ut(),_g),an=()=>sn.join(ut(),uE),jg=()=>sn.join(ut(),dE),gE=()=>sn.join(ut(),Mg),hE=new Set(["ok","attention","failed"]),yE=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"&&hE.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},vE=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(yE)},cn=(e=t=>vi.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(fE()));return vE(t)?t:null}catch{return null}},Fg=e=>{let t=ut();vi.mkdirSync(t,{recursive:!0}),bt(sn.join(t,_g),JSON.stringify(e),384)},wE=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),Lg=(e=t=>vi.readFileSync(t,"utf8"))=>{try{let t=Number(e(gE()).trim());return Number.isFinite(t)?t:null}catch{return null}},Bg=e=>{let t=ut();vi.mkdirSync(t,{recursive:!0}),bt(sn.join(t,Mg),String(e),384)},Ug=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<mE?!1:e.version!==t?!0:wE(e)&&e.attempts<pE};var Vg=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],bl=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Vg.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Sp(o,s,i)?"local-install":null:"not-a-tty"};var bE=e=>{kE(ln.execPath,[e,"--parent-pid",String(ln.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},RE=()=>Gg(new URL("./update-check.js",import.meta.url)),SE=()=>Wg.realpathSync(Gg(new URL("./cli.js",import.meta.url))),EE=/^[\w@./+ -]+$/,PE=e=>EE.test(e),xE=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Ln(e.latestVersion,t)&&e.updateCommand.every(PE)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Es(e.updateCommand)}`)},TE=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${v(an())}, or run: infra-kit setup`),o(e.finishedMs)},Rl=(e,t={})=>{try{let r=t.argv??ln.argv,n=t.env??ln.env,o=t.isTty??!!ln.stdout.isTTY,s=t.cwd??ln.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??SE(),c=t.readCache??Bn,l=t.spawnChild??bE,u=t.fileExists??(y=>Wg.existsSync(y)),p=t.notify??(y=>{d.info(y)});if(bl({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:ye})!==null)return;let m=c();xE(m,e,p);try{TE((t.readAutoSetup??cn)(),e,(t.readNotified??Lg)(),p,t.writeNotified??Bg)}catch{}if(!Ga(m,i))return;let g=t.childPath??RE();if(!u(g))return;l(g)}catch{}};import st from"node:fs/promises";import ot from"node:path";import{pathToFileURL as AE}from"node:url";import OE from"yaml";import{z as pn}from"zod";import CE from"node:fs/promises";import Sl from"node:os";import El from"node:path";import{z as $E}from"zod";import{z as Eo}from"zod";var Jg="vendor.json",Kg=Eo.object({workspaceDir:Eo.string().min(1),source:Eo.string().min(1),targets:Eo.array(Eo.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var un=()=>El.join(Sl.homedir(),hp,Jg),dn=e=>{if(e==="~")return Sl.homedir();if(e.startsWith("~/"))return El.join(Sl.homedir(),e.slice(2));if(El.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},wi=async()=>{let e=un(),t;try{t=await CE.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:
324
+ `;var Ng=!1,mE=e=>e.replace(/\.json$/,".example.jsonc"),fE=async e=>{try{return await yi.readFile(e,"utf-8")}catch{return null}},nn=async e=>{let t=e.userProject,r=mE(t);await yi.mkdir(dE.dirname(t),{recursive:!0});let n=!await X(t);n&&await yi.writeFile(t,`{}
325
+ `,"utf-8");let o=vl(e.projectName),s=await fE(r)!==o;return s&&await yi.writeFile(r,o,"utf-8"),n&&Mn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},on=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,kl=async()=>{if(pE.env.INFRA_KIT_NO_SEED||Ng)return;Ng=!0;let e;try{e=await q()}catch{return}if(await X(e.main))try{let t=await nn(e);t.createdConfig?d.info(on(t)):t.refreshedExample&&d.debug(`Refreshed ${v(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import{spawn as PE}from"node:child_process";import Wg from"node:fs";import ln from"node:process";import{fileURLToPath as Gg}from"node:url";import vi from"node:fs";import sn from"node:path";var _g="auto-setup.json",gE="auto-setup.log",hE="auto-setup.lock",Mg="auto-setup.notified",yE=3,vE=3600*1e3,wE=()=>sn.join(ut(),_g),an=()=>sn.join(ut(),gE),jg=()=>sn.join(ut(),hE),kE=()=>sn.join(ut(),Mg),bE=new Set(["ok","attention","failed"]),RE=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"&&bE.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},SE=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(RE)},cn=(e=t=>vi.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(wE()));return SE(t)?t:null}catch{return null}},Fg=e=>{let t=ut();vi.mkdirSync(t,{recursive:!0}),bt(sn.join(t,_g),JSON.stringify(e),384)},EE=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),Lg=(e=t=>vi.readFileSync(t,"utf8"))=>{try{let t=Number(e(kE()).trim());return Number.isFinite(t)?t:null}catch{return null}},Bg=e=>{let t=ut();vi.mkdirSync(t,{recursive:!0}),bt(sn.join(t,Mg),String(e),384)},Ug=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<vE?!1:e.version!==t?!0:EE(e)&&e.attempts<yE};var Vg=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],bl=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Vg.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Sp(o,s,i)?"local-install":null:"not-a-tty"};var xE=e=>{PE(ln.execPath,[e,"--parent-pid",String(ln.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},TE=()=>Gg(new URL("./update-check.js",import.meta.url)),CE=()=>Wg.realpathSync(Gg(new URL("./cli.js",import.meta.url))),$E=/^[\w@./+ -]+$/,AE=e=>$E.test(e),OE=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Ln(e.latestVersion,t)&&e.updateCommand.every(AE)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Es(e.updateCommand)}`)},IE=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${v(an())}, or run: infra-kit setup`),o(e.finishedMs)},Rl=(e,t={})=>{try{let r=t.argv??ln.argv,n=t.env??ln.env,o=t.isTty??!!ln.stdout.isTTY,s=t.cwd??ln.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??CE(),c=t.readCache??Bn,l=t.spawnChild??xE,u=t.fileExists??(y=>Wg.existsSync(y)),p=t.notify??(y=>{d.info(y)});if(bl({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:ye})!==null)return;let m=c();OE(m,e,p);try{IE((t.readAutoSetup??cn)(),e,(t.readNotified??Lg)(),p,t.writeNotified??Bg)}catch{}if(!Ga(m,i))return;let g=t.childPath??TE();if(!u(g))return;l(g)}catch{}};import st from"node:fs/promises";import ot from"node:path";import{pathToFileURL as _E}from"node:url";import ME from"yaml";import{z as pn}from"zod";import DE from"node:fs/promises";import Sl from"node:os";import El from"node:path";import{z as NE}from"zod";import{z as Eo}from"zod";var Jg="vendor.json",Kg=Eo.object({workspaceDir:Eo.string().min(1),source:Eo.string().min(1),targets:Eo.array(Eo.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var un=()=>El.join(Sl.homedir(),hp,Jg),dn=e=>{if(e==="~")return Sl.homedir();if(e.startsWith("~/"))return El.join(Sl.homedir(),e.slice(2));if(El.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},wi=async()=>{let e=un(),t;try{t=await DE.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:
325
326
 
326
327
  {
327
328
  "workspaceDir": "~/projects",
328
329
  "source": "my-starter",
329
330
  "targets": ["my-repo"]
330
331
  }
331
- `)}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=Kg.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${$E.prettifyError(n.error)}`);return n.data};var Hg=e=>e.replace(/\.json$/,".yml"),qg=async()=>{let e;try{e=await H()}catch{return}let t={label:"infra-kit.json",yml:Hg(e.main),json:e.main,schema:cm},r=[...Ge.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:ot.join(ot.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:La},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Hg(e.userProject),json:e.userProject,schema:La}],n=0;for(let o of r){let[s,i]=await Promise.all([z(o.yml),z(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${v(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await st.readFile(o.yml,"utf-8"),c=OE.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 invalid config: ${pn.prettifyError(l.error)}`);continue}await st.mkdir(ot.dirname(o.json),{recursive:!0}),await st.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
332
- `,"utf-8"),await st.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${v(o.yml)} \u2192 ${v(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${a.message}`)}}}n>0&&Et()},Yg=async()=>{let e;try{e=await H()}catch{return}let t=ot.dirname(e.userGlobal),r=[{from:ot.join(t,"config.json"),to:e.userGlobal},{from:ot.join(t,"config.example.jsonc"),to:ot.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([z(o),z(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${v(o)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await st.mkdir(ot.dirname(s),{recursive:!0}),await st.rename(o,s),d.info(`\u2713 Renamed ${v(o)} \u2192 ${v(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${v(o)} \u2014 ${c.message}`)}}}n>0&&Et()},IE=pn.object({workspaceDir:pn.string().min(1),targets:pn.array(pn.string()).min(1)}).strict(),zg=async()=>{let e=un(),t=ot.dirname(e),r=ot.join(t,"vendor.config.ts"),[n,o]=await Promise.all([z(r),z(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${v(r)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await st.stat(r),c=(await import(`${AE(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=IE.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${v(r)} \u2014 invalid factory config: ${pn.prettifyError(p.error)}`);return}await st.mkdir(t,{recursive:!0}),await st.writeFile(e,`${JSON.stringify(p.data,null,2)}
333
- `,"utf-8"),await st.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${v(r)} \u2192 ${v(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${v(e)} directly to change them.`):d.info(`\u2713 Migrated ${v(r)} \u2192 ${v(e)}`)}catch(s){d.info(`\u26A0 Skipped ${v(r)} \u2014 ${s.message}`)}}},Xg=async()=>{let e=await DE(),t=0;for(let r of e)if(await z(r))try{let n=await om(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${v(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof rm?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${v(r)} \u2014 ${o}`)}t>0&&Et()},DE=async()=>{try{let e=await H();return Ge.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[um()]}};var cr="# -- infra-kit:begin --",Mt="# -- infra-kit:end --",NE=[["# region infra-kit","# endregion infra-kit"]],_E="# infra-kit shell functions",mn=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},fn="Run `source ~/.zshrc` or open a new terminal to activate.",ME={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Fe=async(e,t)=>{try{return await t()}catch(r){throw new mn(e,r)}},xl=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Fe("zshrc",()=>{r(LE())}),await Fe("zshenv",()=>{r(BE())}),await Fe("migrations",async()=>{await VE(),UE(),r(ME)}),await Fe("user-config",()=>{r(GE())});let n=await Fe("guidance",async()=>{let{entries:s,root:i}=await qE();return r(...s),i}),o=await Fe("plugin-pointer",async()=>Tg());return r(...zE(o,n)),await Fe("worktrees",async()=>{r(...await tP(o))}),await Fe("plugin-pointer",async()=>{await nP(o,r)}),await Fe("mcp-proxies",async()=>{r(...await sP(o))}),await Fe("project-config",async()=>{r(...await JE(o))}),await Fe("token-perms",async()=>{r(await FE())}),await Fe("chrome",()=>{r(jE())}),r(...WE()),t},jE=()=>{let e=So();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"}:hl()?{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"}},FE=async()=>{let e=await vm();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 Qg=e=>{let t=Q.dirname(e);return de.existsSync(Q.join(e,".git"))?e:t===e?null:Qg(t)},eh=(e,t,r,n)=>{if(!Ge.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=de.realpathSync(t)}catch{}return Qg(Q.dirname(o))===null?null:xo(e,ki.homedir(),o,["the infra-kit block updated"])},th=e=>de.existsSync(e)?de.readFileSync(e,"utf-8"):null,LE=()=>{let e=Q.join(ki.homedir(),".zshrc"),t=th(e),r=t===null?"":aP(t),n=Dr({content:r,body:oh(),startMarker:cr,endMarker:Mt,placement:"append-end"}),o=eh("zshrc",e,t,n);return o!==null?o:(de.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},BE=()=>{let e=Q.join(ki.homedir(),".zshenv"),t=th(e),r=Dr({content:t??"",body:Tl(),startMarker:cr,endMarker:Mt}),n=eh("zshenv",e,t,r);return n!==null?n:(de.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},UE=()=>{de.rmSync(Q.join(ut(),"projects"),{recursive:!0,force:!0})},VE=async()=>{await qg(),await Yg(),await Xg(),await zg()},WE=()=>{let e=Pl.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:fn,level:"info"}),t},GE=()=>{let e=Q.join(ki.homedir(),".infra-kit"),t=Q.join(e,"infra-kit.json");return de.mkdirSync(e,{recursive:!0}),de.writeFileSync(Q.join(e,"infra-kit.example.jsonc"),yl(),"utf-8"),de.writeFileSync(Q.join(e,"vendor.example.jsonc"),wl(),"utf-8"),de.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(de.writeFileSync(t,`{}
334
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},JE=async e=>{if(Pl.env.INFRA_KIT_NO_SEED)return[Po("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Po("skipped","not inside a git repository")];try{let t=await H();if(!de.existsSync(t.main))return[Po("skipped",`no project config at ${t.main}`)];let r=await nn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:on(r),level:"info"}]:[Po("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Po("warned",t instanceof Error?t.message:String(t))]}},Po=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),KE=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},HE=(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"},...KE(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},qE=async()=>{let{skipped:e,root:t,version:r,written:n}=await Cg({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:HE(r,n)}},bi=e=>`cd ${xp(e)} && infra-kit setup --skip-tools`,xo=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${bi(t)}`,level:"info"}),YE=(e,t)=>{let r=Q.relative(e,t.path);return t.status==="withheld"?xo("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"}},Zg=(e,t)=>{let r=Me;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?oe:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${et} from ${Q.join(e,Me)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: none wanted \u2014 the plugin is skills-only (${t.kind==="absent"?`${r} carries no "${oe}" key`:`no ${r}`})`,level:"info"}},zE=(e,t)=>e===null||t!==null?[]:[{step:"plugin-pointer",outcome:"warned",message:`No infra-kit.json at ${e} \u2014 setting up Claude Code there anyway: writing .claude/settings.json and installing the ${G} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],XE=()=>[Dc,mt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),ZE=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${U.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${U.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"};return e.stale?[r,{step:"plugin-pointer",outcome:"manual",message:Es(e.updateCommand),level:"info"}]:[r]},QE=(e,t)=>e.status==="skipped-cli-stale"?ZE(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${G} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${Vr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${G} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...XE()]:[{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: ${mt}`,level:"warn"}],rh={stale:!1},eP=async()=>{let e=Bn(),t=e===null?await Ka(Pl.env):e.latestVersion;return t===null||!Ha(t,U.version)?rh:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Rp(t)}},tP=async e=>{if(e===null)return[];let r=`${await Re(e)}${ue}`,n=Object.values(xr).filter(o=>!de.existsSync(Q.join(r,o)));for(let o of Object.values(xr))de.mkdirSync(Q.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"}]},rP=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${G} is installed; the update worker keeps it current`,level:"debug"}]:[xo("plugin-pointer",e,".claude/settings.json",[`the ${G} plugin installed`])],nP=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(YE(e,Nc(Q.join(e,".claude","settings.json"),{write:!Ge.withheld})));let r=zt({projectPath:e}).kind==="installed";if(Ge.withheld){t(...rP(e,r),Zg(e,Ur(e)));return}let n=r?await eP():rh;t(...QE(Cc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(Zg(e,Ur(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: ${mt}`,level:"warn"})}},nh=(e,t)=>{let r=Q.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},oP=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=nh(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,xo("mcp-proxies",e,Q.relative(e,t.path),s)]},sP=async e=>{if(e===null)return[];if(!de.existsSync(Q.join(e,"infra-kit.json")))return[{step:"mcp-proxies",outcome:"skipped",message:"no infra-kit.json \u2014 no ik-mcp entries to derive",level:"silent"}];let t;try{t=(await W()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
335
- `)[0]??n;return Ge.withheld?[xo("mcp-proxies",e,"infra-kit.json",[`a config fix or migration (${o})`])]:[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:Ge.withheld?oP(e,no({projectRoot:e,proxies:t,write:!1})):nh(e,no({projectRoot:e,proxies:t,write:!0}))},iP=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"),aP=e=>{let t=Ot(e,cr,Mt);if(t!==null)return t;for(let[a,c]of NE){let l=Ot(e,a,c);if(l!==null)return l}let r=e.indexOf(_E);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
336
- `),s=0;for(;s<o.length&&iP(o[s]);)s++;let i=o.slice(s).join(`
332
+ `)}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=Kg.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${NE.prettifyError(n.error)}`);return n.data};var Hg=e=>e.replace(/\.json$/,".yml"),qg=async()=>{let e;try{e=await q()}catch{return}let t={label:"infra-kit.json",yml:Hg(e.main),json:e.main,schema:cm},r=[...Ge.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:ot.join(ot.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:La},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Hg(e.userProject),json:e.userProject,schema:La}],n=0;for(let o of r){let[s,i]=await Promise.all([X(o.yml),X(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${v(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await st.readFile(o.yml,"utf-8"),c=ME.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 invalid config: ${pn.prettifyError(l.error)}`);continue}await st.mkdir(ot.dirname(o.json),{recursive:!0}),await st.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
333
+ `,"utf-8"),await st.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${v(o.yml)} \u2192 ${v(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${a.message}`)}}}n>0&&Et()},Yg=async()=>{let e;try{e=await q()}catch{return}let t=ot.dirname(e.userGlobal),r=[{from:ot.join(t,"config.json"),to:e.userGlobal},{from:ot.join(t,"config.example.jsonc"),to:ot.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([X(o),X(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${v(o)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await st.mkdir(ot.dirname(s),{recursive:!0}),await st.rename(o,s),d.info(`\u2713 Renamed ${v(o)} \u2192 ${v(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${v(o)} \u2014 ${c.message}`)}}}n>0&&Et()},jE=pn.object({workspaceDir:pn.string().min(1),targets:pn.array(pn.string()).min(1)}).strict(),zg=async()=>{let e=un(),t=ot.dirname(e),r=ot.join(t,"vendor.config.ts"),[n,o]=await Promise.all([X(r),X(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${v(r)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await st.stat(r),c=(await import(`${_E(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=jE.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${v(r)} \u2014 invalid factory config: ${pn.prettifyError(p.error)}`);return}await st.mkdir(t,{recursive:!0}),await st.writeFile(e,`${JSON.stringify(p.data,null,2)}
334
+ `,"utf-8"),await st.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${v(r)} \u2192 ${v(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${v(e)} directly to change them.`):d.info(`\u2713 Migrated ${v(r)} \u2192 ${v(e)}`)}catch(s){d.info(`\u26A0 Skipped ${v(r)} \u2014 ${s.message}`)}}},Xg=async()=>{let e=await FE(),t=0;for(let r of e)if(await X(r))try{let n=await om(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${v(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof rm?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${v(r)} \u2014 ${o}`)}t>0&&Et()},FE=async()=>{try{let e=await q();return Ge.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[um()]}};var lr="# -- infra-kit:begin --",jt="# -- infra-kit:end --",LE=[["# region infra-kit","# endregion infra-kit"]],BE="# infra-kit shell functions",mn=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},fn="Run `source ~/.zshrc` or open a new terminal to activate.",UE={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Fe=async(e,t)=>{try{return await t()}catch(r){throw new mn(e,r)}},xl=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Fe("zshrc",()=>{r(GE())}),await Fe("zshenv",()=>{r(JE())}),await Fe("migrations",async()=>{await HE(),KE(),r(UE)}),await Fe("user-config",()=>{r(YE())});let n=await Fe("guidance",async()=>{let{entries:s,root:i}=await QE();return r(...s),i}),o=await Fe("plugin-pointer",async()=>Tg());return r(...tP(o,n)),await Fe("worktrees",async()=>{r(...await iP(o))}),await Fe("plugin-pointer",async()=>{await cP(o,r)}),await Fe("mcp-proxies",async()=>{r(...await uP(o))}),await Fe("project-config",async()=>{r(...await zE(o))}),await Fe("token-perms",async()=>{r(await WE())}),await Fe("chrome",()=>{r(VE())}),r(...qE()),t},VE=()=>{let e=So();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"}:hl()?{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"}},WE=async()=>{let e=await vm();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 Qg=e=>{let t=ee.dirname(e);return ue.existsSync(ee.join(e,".git"))?e:t===e?null:Qg(t)},eh=(e,t,r,n)=>{if(!Ge.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=ue.realpathSync(t)}catch{}return Qg(ee.dirname(o))===null?null:xo(e,ki.homedir(),o,["the infra-kit block updated"])},th=e=>ue.existsSync(e)?ue.readFileSync(e,"utf-8"):null,GE=()=>{let e=ee.join(ki.homedir(),".zshrc"),t=th(e),r=t===null?"":pP(t),n=Dr({content:r,body:oh(),startMarker:lr,endMarker:jt,placement:"append-end"}),o=eh("zshrc",e,t,n);return o!==null?o:(ue.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},JE=()=>{let e=ee.join(ki.homedir(),".zshenv"),t=th(e),r=Dr({content:t??"",body:Tl(),startMarker:lr,endMarker:jt}),n=eh("zshenv",e,t,r);return n!==null?n:(ue.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},KE=()=>{ue.rmSync(ee.join(ut(),"projects"),{recursive:!0,force:!0})},HE=async()=>{await qg(),await Yg(),await Xg(),await zg()},qE=()=>{let e=Pl.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:fn,level:"info"}),t},YE=()=>{let e=ee.join(ki.homedir(),".infra-kit"),t=ee.join(e,"infra-kit.json");return ue.mkdirSync(e,{recursive:!0}),ue.writeFileSync(ee.join(e,"infra-kit.example.jsonc"),yl(),"utf-8"),ue.writeFileSync(ee.join(e,"vendor.example.jsonc"),wl(),"utf-8"),ue.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ue.writeFileSync(t,`{}
335
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},zE=async e=>{if(Pl.env.INFRA_KIT_NO_SEED)return[Po("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Po("skipped","not inside a git repository")];try{let t=await q();if(!ue.existsSync(t.main))return[Po("skipped",`no project config at ${t.main}`)];let r=await nn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:on(r),level:"info"}]:[Po("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Po("warned",t instanceof Error?t.message:String(t))]}},Po=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),XE=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},ZE=(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"},...XE(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},QE=async()=>{let{skipped:e,root:t,version:r,written:n}=await Cg({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:ZE(r,n)}},bi=e=>`cd ${xp(e)} && infra-kit setup --skip-tools`,xo=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${bi(t)}`,level:"info"}),eP=(e,t)=>{let r=ee.relative(e,t.path);return t.status==="withheld"?xo("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"}},Zg=(e,t)=>{let r=Me;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?oe:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${et} from ${ee.join(e,Me)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: none wanted \u2014 the plugin is skills-only (${t.kind==="absent"?`${r} carries no "${oe}" key`:`no ${r}`})`,level:"info"}},tP=(e,t)=>e===null||t!==null?[]:[{step:"plugin-pointer",outcome:"warned",message:`No infra-kit.json at ${e} \u2014 setting up Claude Code there anyway: writing .claude/settings.json and installing the ${G} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],rP=()=>[Dc,mt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),nP=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${U.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${U.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"};return e.stale?[r,{step:"plugin-pointer",outcome:"manual",message:Es(e.updateCommand),level:"info"}]:[r]},oP=(e,t)=>e.status==="skipped-cli-stale"?nP(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${G} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${Vr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${G} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...rP()]:[{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: ${mt}`,level:"warn"}],rh={stale:!1},sP=async()=>{let e=Bn(),t=e===null?await Ka(Pl.env):e.latestVersion;return t===null||!Ha(t,U.version)?rh:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Rp(t)}},iP=async e=>{if(e===null)return[];let r=`${await Re(e)}${le}`,n=Object.values(Tr).filter(o=>!ue.existsSync(ee.join(r,o)));for(let o of Object.values(Tr))ue.mkdirSync(ee.join(r,o),{recursive:!0});return n.length===0?[{step:"worktrees",outcome:"unchanged",message:`Worktree directories already present at ${r}`,level:"info"}]:[{step:"worktrees",outcome:"written",message:`Created worktree directories at ${r} (${n.join(", ")})`,level:"info"}]},aP=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${G} is installed; the update worker keeps it current`,level:"debug"}]:[xo("plugin-pointer",e,".claude/settings.json",[`the ${G} plugin installed`])],cP=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(eP(e,Nc(ee.join(e,".claude","settings.json"),{write:!Ge.withheld})));let r=Xt({projectPath:e}).kind==="installed";if(Ge.withheld){t(...aP(e,r),Zg(e,Ur(e)));return}let n=r?await sP():rh;t(...oP(Cc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(Zg(e,Ur(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: ${mt}`,level:"warn"})}},nh=(e,t)=>{let r=ee.relative(e,t.path);if(t.status!=="ok"&&t.status!=="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${r} could not be read as JSON \u2014 ik-mcp entries not synced`,level:"warn"}];if(t.status==="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${r} could not be written \u2014 ik-mcp entries not synced`,level:"warn"}];let n=[];for(let o of t.entries)o.status==="written"?n.push({step:"mcp-proxies",outcome:"written",message:` updated ${r} \u2014 ik-mcp "${o.name}"`,level:"info"}):(o.status==="conflict"||o.status==="stale")&&n.push({step:"mcp-proxies",outcome:"warned",message:` ${o.message}`,level:"warn"});return n},lP=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=nh(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,xo("mcp-proxies",e,ee.relative(e,t.path),s)]},uP=async e=>{if(e===null)return[];if(!ue.existsSync(ee.join(e,"infra-kit.json")))return[{step:"mcp-proxies",outcome:"skipped",message:"no infra-kit.json \u2014 no ik-mcp entries to derive",level:"silent"}];let t;try{t=(await W()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
336
+ `)[0]??n;return Ge.withheld?[xo("mcp-proxies",e,"infra-kit.json",[`a config fix or migration (${o})`])]:[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:Ge.withheld?lP(e,no({projectRoot:e,proxies:t,write:!1})):nh(e,no({projectRoot:e,proxies:t,write:!0}))},dP=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"),pP=e=>{let t=It(e,lr,jt);if(t!==null)return t;for(let[a,c]of LE){let l=It(e,a,c);if(l!==null)return l}let r=e.indexOf(BE);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
337
+ `),s=0;for(;s<o.length&&dP(o[s]);)s++;let i=o.slice(s).join(`
337
338
  `);return n+(i?`
338
339
  ${i}`:"")},oh=()=>{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(`
339
- `)},sh=()=>`${cr}
340
+ `)},sh=()=>`${lr}
340
341
  ${oh()}
341
- ${Mt}`,Tl=()=>["# 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(`
342
- `),Cl=()=>`${cr}
342
+ ${jt}`,Tl=()=>["# 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(`
343
+ `),Cl=()=>`${lr}
343
344
  ${Tl()}
344
- ${Mt}`;import cP from"node:fs/promises";var To=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await cP.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}}},Co=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import uP from"node:fs";import dP from"node:os";import ih from"node:path";import pP from"node:process";import{$ as lP}from"zx";var gn=()=>lP({quiet:!0});var mP=()=>[ih.join(dP.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],fP=async e=>{try{return(await gn()`command -v ${e}`).stdout.trim()||null}catch{return null}},$o=()=>({runCommand:async e=>{let t=await gn()`${e}`;return{stdout:`${t.stdout}
345
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await fP(e);return t!==null?t:mP().map(r=>ih.join(r,e)).find(r=>uP.existsSync(r))??null},realpath:ye,platform:pP.platform});var jt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),hn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,yn=["darwin","linux"],Pi=e=>t=>Da(t,e)?"homebrew":"unknown",xi=(e,t)=>r=>r===null?null:t(e(r),r),Al=e=>xi(Pi(e.kegName),t=>t==="homebrew"?jt(["brew","upgrade",e.brewFormula]):null),ah=e=>Ss(e,"Homebrew")||Ss(e,"homebrew")?"homebrew":"unknown",gP={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:hn,platforms:yn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:ah,updateFor:xi(ah,e=>e==="homebrew"?jt(["brew","update"]):null)},$l={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},uh="https://awscli.amazonaws.com/v2/install.sh",dh={steps:[["/bin/bash","-c",`curl -fsSL ${uh} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},hP="/usr/local/aws-cli",yP=e=>In(hP,e,ye)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${uh} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:dh,ch=e=>Da(e,$l.kegName)?"homebrew":Ss(e,"aws-cli")?"script":"unknown",vP={id:"aws",binName:"aws",...$l,probeArgv:["aws","--version"],versionFrom:hn,platforms:yn,prerequisites:[],bootstrapInstall:dh,identify:ch,updateFor:xi(ch,(e,t)=>e==="homebrew"?jt(["brew","upgrade",$l.brewFormula]):e==="script"?yP(t):null)},Ri={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},wP={id:"git",binName:"git",...Ri,probeArgv:["git","--version"],versionFrom:hn,platforms:yn,prerequisites:["brew"],bootstrapInstall:jt(["brew","install",Ri.brewInstallSpec]),identify:Pi(Ri.kegName),updateFor:Al(Ri)},Si={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},kP={id:"gh",binName:"gh",...Si,probeArgv:["gh","--version"],versionFrom:hn,platforms:yn,prerequisites:["brew"],bootstrapInstall:jt(["brew","install",Si.brewInstallSpec]),identify:Pi(Si.kegName),updateFor:Al(Si)},Ei={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},bP={id:"doppler",binName:"doppler",...Ei,probeArgv:["doppler","--version"],versionFrom:hn,platforms:yn,prerequisites:["brew"],bootstrapInstall:jt(["brew","install","gnupg"],["brew","install",Ei.brewInstallSpec]),identify:Pi(Ei.kegName),updateFor:Al(Ei)},Ao="portless",lh=e=>bp(e,Ao)===null?"unknown":"npm",RP={id:"portless",binName:Ao,npmPackage:Ao,probeArgv:["portless","--version"],versionFrom:hn,platforms:[...yn,"win32"],prerequisites:[],bootstrapInstall:jt(["npm","install","-g",Ao]),identify:lh,updateFor:xi(lh,e=>e==="npm"?jt(["npm","install","-g",`${Ao}@latest`]):null)},Ol={brew:gP,git:wP,aws:vP,gh:kP,doppler:bP,portless:RP},lr=Object.keys(Ol),Le=e=>Ol[e],Il=(e,t)=>e.platforms.includes(t),Dl=e=>{let t=[],r=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!r.has(o)){r.add(o);for(let i of Le(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var ph=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),mh=async(e,t)=>{try{return await e(t)}catch{return null}},SP=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},fh=async(e,t)=>{if(!Il(e,t.platform))return ph(e.id);let r=await mh(t.runCommand,e.probeArgv),n=await SP(t,e.binName);if(r==null&&n==null)return ph(e.id);let o=r??(n==null?null:await mh(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)}},Oo=async(e,t)=>Promise.all(e.map(r=>fh(Le(r),t)));import{$ as $P}from"zx";import{z as gh}from"zod";var hh=/^\d{4}-\d{2}-\d{2}$/,Io=e=>{if(!hh.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},yh=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,vn=class extends Error{constructor(t){super(yh(t)),this.name="InvalidReleaseDateError"}},ur=e=>{let t=e.trim();if(!Io(t))throw new vn(t);return t},Do=e=>{let t=e.trim();return t===""||Io(t)?!0:yh(t)},Nl=gh.string().refine(Io,{message:"Expected a calendar date in yyyy-mm-dd form."}),_l=gh.string().refine(e=>e===""||Io(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Ft=e=>e.slice(1).split(".").map(Number),wn=e=>[...e].sort((t,r)=>{let[n,o,s]=Ft(t),[i,a,c]=Ft(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var wh="next",EP=/^v?(\d+)\.(\d+)\.(\d+)$/,PP=e=>e.replace(/^.*release\//,""),Ml=e=>{let t=PP(e.trim()),r=EP.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},vh=e=>`${e[0]}.${e[1]}.${e[2]}`,jl=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Ml(o);if(!s)continue;let i=vh(s);n.has(i)||(n.add(i),r.push(s))}return wn(r.map(o=>vh(o))).map(o=>Ft(`v${o}`))},dr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Fl=(e,t)=>{if(e.length===0)throw new dr;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`},kn=(e,t)=>{try{return Fl(e,t)}catch(r){if(r instanceof dr)return null;throw r}},Ll=e=>e.trim().toLowerCase()===wh,Ci=e=>Ll(e)||Ml(e)!==null?{version:e}:{name:e},xP=e=>e==="regular"||e==="hotfix",kh=e=>"name"in e,TP=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:ur(n)}},Bl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=TP(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(!xP(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return Ti({...Ci(n),type:s},{description:i,releaseDate:o})},Ul=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},Ti=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},CP=e=>{let t=e.name.trim();return Cs(t),Ti({id:{kind:"name",name:t,raw:t},type:e.type},e)},Vl=(e,t)=>{let r=[...t];return e.map(n=>{if(kh(n))return CP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Ll(o)){let a=Fl(r,n.type);return r.push(Ft(`v${a}`)),Ti({id:me(a),type:n.type},n)}let s=Ml(o);if(!s)throw new Error(`Invalid version "${o}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return r.push(s),Ti({id:me(i),type:n.type},n)})},Wl=e=>e.some(t=>!kh(t)&&Ll(t.version));var AP=e=>e.split(`
346
- `).map(t=>{let r=t.indexOf(" ");return r===-1?null:K(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),OP=async()=>{let e=await $P({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return AP(e.stdout)},IP=async()=>{let e=await gt();return e?(await Xr(e)).map(r=>r.name):[]},No=async()=>{let[e,t]=await Promise.allSettled([OP(),IP()]);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"),jl({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import DP from"node:fs";import NP from"node:path";var Gl=[".claude/settings.json",".claude/settings.local.json"],_P=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],MP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),jP=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},FP=(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(MP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},LP=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},BP=()=>pr.filter(e=>e.mutating),UP=e=>{let t=jP(e);return t===null?[]:BP().filter(r=>_P.some(n=>LP(r).some(o=>FP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},VP=(e,t)=>{let r;try{r=DP.readFileSync(NP.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}},bh=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Gl){let n=VP(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=UP(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var WP=e=>e.every(t=>t.status!=="fail"),GP=["brew","git","gh","doppler","aws"],JP=async e=>{let t=await Oo(GP,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},vt=async(e,t,r,n)=>{try{return await gn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},KP=async()=>{let e="orca installed",t=await Tt();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)"}},Dh=(e,t,r,n)=>{let o=pe.join(Ih.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ee.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ee.readFileSync(o,"utf-8"),a=i.indexOf(cr),c=i.indexOf(Mt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Mt.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`}},HP=()=>Dh("zshrc init block",".zshrc","shell",sh()),qP=()=>Dh("zshenv session block",".zshenv","session-env",Cl()),YP=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await P(),r=pe.join(t,"pnpm-workspace.yaml");if(!ee.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ee.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},zP=async()=>{try{return Et(),{config:await W(),error:null}}catch(e){return{config:null,error:e}}},XP=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)"}},ZP=384,Jl=448,QP=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(", "),ex=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}}})),tx=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Je,o=t.resolveToken??Em;if(!e.config)return{name:r,status:"skip",message:"infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await ex(await Fs(),o);return{name:r,status:"pass",message:QP(s)}},rx=()=>it.env[Zt]||void 0,nx=async(e={})=>{let t="tokens.json present",r=e.readStore??Je,n=e.storePath??xt;if((e.readEnvToken??rx)())return{name:t,status:"skip",message:`${Zt} is set; that channel takes precedence over the store`};let s;try{s=v(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${Zt} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},_o=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},ox=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??xt,o=t.statPath??sx,s=t.chmodPath??ee.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(_o(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=pe.dirname(i),c=pe.dirname(a),l=pe.dirname(c),p=[{target:l,expected:Jl,actual:_o(l,o)},{target:c,expected:Jl,actual:_o(c,o)},{target:a,expected:Jl,actual:_o(a,o)},{target:i,expected:ZP,actual:_o(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(g=>`${v(g.target)} is ${Rh(g.actual)}, expected ${Rh(g.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 g of p)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},Rh=e=>`0${e.toString(8).padStart(3,"0")}`,sx=e=>{try{return ee.statSync(e)}catch{return null}},ix=async()=>{let e="user override path";try{let t=await H(),r=ee.existsSync(t.userProject),n=await To(t.userProject,r),o=r?Co(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${v(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},ax=async()=>{let e="legacy user-global config",t;try{t=await H()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=pe.join(pe.dirname(t.userGlobal),"config.json");return ee.existsSync(r)?ee.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${v(r)} \u2014 ${v(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${v(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Sh=/^\d+\.\d+\.\d+$/,cx=(e,t)=>e===t||!Sh.test(e)||!Sh.test(t)?!1:wn([`v${e}`,`v${t}`])[0]===`v${e}`,lx=async(e,t)=>{let r;try{r=await Pe(e)}catch{return[]}let n=[];for(let o of r){let s=rr(nr(pe.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&cx(s.version,t)&&n.push(s.version)}return n},ux=async(e,t)=>{let r=await lx(e,t);if(r.length===0)return"";let n=wn(r.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${r.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${t}) \u2014 run: infra-kit audit --fix --all`},dx=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await H()).main}catch{return e}if(!ee.existsSync(t))return e;let r=pe.dirname(t),n=pe.join(r,"CLAUDE.md"),o=ee.existsSync(n)?ee.readFileSync(n,"utf-8"):"",s=Xe(o,_e,Ze),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await ux(r,U.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},px=async()=>{try{let e=(await H()).main;return ee.existsSync(e)?pe.dirname(e):null}catch{return null}},mx=e=>{let t=dm();return t===null||!Ln(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Vr}`},fx=e=>{let t=e.kind==="installed"?Ns(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${G} version ${t}${mx(t)}`}},Eh=3,Ph=(e,t)=>ye(e)===ye(t),gx=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(Ph(e.projectDir,e.gitRoot))return"";let r=In(e.gitRoot,ye(e.projectDir),ye)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${v(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return Ph(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${v(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},hx=(e,t)=>{let r="plugin installed",n=gx(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${G} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${G} is not installed. Run: ${mt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-Eh,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Eh).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${G} is installed for ${a} only, not this project. Run: ${mt}${n}`}},yx=()=>vt("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 vx=(e,...t)=>{try{return JSON.parse(ee.readFileSync(pe.join(e,...t),"utf-8"))}catch{return null}},wx=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=Ns(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=vx(r,Me),o=n!==null&&typeof n=="object"?n[et]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},xh=e=>`Plugin ${G} ${e===null?"(version unreadable)":e}`,kx=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: ${mt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${xh(e.version)} still carries an MCP server in its ${Me}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Vr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${xh(e.version)} is skills-only \u2014 no ${Me}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},bx=(e,t)=>{let r=zt(e===null?{}:{projectPath:e}),n=Fn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${oe} is known to Claude Code`:`Marketplace ${oe} is not registered. Run: claude plugin marketplace add ${Pt}`},hx(r,t),fx(r),kx(wx(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},Rx=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${v(an())}, or run: infra-kit setup`}},Sx=({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(", ")},Ex=e=>{let t="Agent mode",r=Ts(e),n=Sx(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})`}},Th=4,Px=e=>{let t=e.slice(0,Th).join(", "),r=e.length-Th;return r>0?`${t} +${r} more`:t},xx=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=bh(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"} (${Px(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 ${Gl.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`}},Tx=(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`},Cx=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 hg(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?v(i.worktreePath):"worktree missing";return`${i.branch} (${Tx(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`}},Nh=e=>Na(["trust"],{bin:e}),$x=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Ch="ERR_TLS_CERT_ALTNAME_INVALID",_h=()=>`portless serving TLS on :${St}`,Ax=async(e,t,r)=>{let n=_h();return await e(St,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${St}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${St}. Install it once (needs root): \`${Rt(t,r)}\`.`}},Ox=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(St,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(Ch)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Ch} 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=>$x.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${Nh(n)}\`, or reinstall: \`${Rt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},Ix=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${v(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Nh(r)}\` (no sudo needed).`}},Dx=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 \`${Na(["alias","--remove","<name>"],{bin:r})}\`.`}},Lt="portless service target",jo=e=>({name:Lt,status:"warn",message:e}),Mh=e=>e==="darwin"?$p:e==="linux"?Ap:null,Nx=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Cp}`:`sudo systemctl restart ${Op}`,_x="/bin/ps",Mx=e=>{try{let t=Oh(_x,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(t.status!==0)return null;let r=new Date(t.stdout.trim());return Number.isNaN(r.getTime())?null:r}catch{return null}},$h=e=>{try{return ee.readFileSync(e,"utf-8")}catch{return null}},jx=e=>{try{return ee.statSync(e).mtime}catch{return null}},Fx=2e3,Lx=e=>{try{let t=Oh(e,["-p","process.version"],{encoding:"utf-8",timeout:Fx}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},Bx=(e,t)=>({platform:e.platform??it.platform,readServiceFile:e.readServiceFile??$h,readFile:e.readFile??$h,exists:e.exists??ee.existsSync,realpath:e.realpath??ye,mtime:e.mtime??jx,execPath:e.execPath??it.execPath,home:e.home??Ih.homedir(),cwd:e.cwd??it.cwd(),repoRoot:e.repoRoot??Ro,stateDir:(e.stateDir??Dp)(),processStartTime:e.processStartTime??Mx,version:e.version??it.version,arch:e.arch??it.arch,nodeVersionOf:e.nodeVersionOf??Lx,isGlobal:e.isGlobal??xs().node.isGlobal,nodeFs:e.nodeFs??ee,stableNode:null,stableNodeSidecar:null,bin:t}),Fo="portless node",mr="~/.infra-kit/node",Mo=e=>({row:{name:Fo,status:"fail",message:e},stableNode:null,sidecar:null}),Ah=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},Ux=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,Vx=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,Wx=e=>{let t=Fp(e.home),r=Ah(e.nodeFs.lstatSync,t);if(r===void 0)return Mo(`${mr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Mo(`${mr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Lp(e.home,e.nodeFs);if(n===null)return Mo(`${mr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Ah(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 Mo(`${mr} is Node ${n.version} (${n.method} of ${v(n.source)}); infra-kit runs ${e.version} at ${v(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!Vx(c,e))return Mo(`${mr} does not run as Node ${e.version} (${Ux(c)}). Re-run through the current Node: \`${Rt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Fo,status:"pass",message:`${mr} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},Gx=e=>{if(Mh(e.platform)===null)return{row:{name:Fo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=Wx(e);return e.isGlobal()?t:{...t,row:{name:Fo,status:"skip",message:`not a global install; the global infra-kit keeps ${mr} current`}}},jh=(e,t)=>{let r=Bx(e,t),n=Gx(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},Jx=(e,t)=>{let r=t.readFile(pe.join(e,"package.json"));try{let n=r===null?null:ge.object({version:ge.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},Kx=e=>{let t=Number.parseInt(e.readFile(pe.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},Hx=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},qx=(e,t,r)=>{let n=Kx(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(Hx(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(pe.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},Yx=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:In(await t.repoRoot()??r,e,t.realpath)},fr=e=>({state:"drifted",row:e}),zx=async(e,t,r)=>{let n=Rt(r.bin,r);if(!r.exists(e))return fr({name:Lt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=pe.join(_a(r.home),"dist","cli.js");if(t!==o)return fr(jo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Ps(r.home,r.exists)===null)return fr({name:Lt,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=r.realpath(_a(r.home));if(await Yx(s,r))return fr({name:Lt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=Xx(e,n,r);if(i!==null)return i;let a=Jx(s,r),c=qx(s,a,r);return c!==null?{state:"converged",row:jo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${Nx(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Lt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},Xx=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:fr(jo(`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:fr(jo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Fh=async e=>{let t=Mh(e.platform);if(t===null)return{state:"absent",row:{name:Lt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Lt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Ff(e.platform,r)??[];return n===void 0||o===void 0?fr(jo(`could not parse ${t} \u2014 re-run \`${Rt(e.bin,e)}\` to rewrite it.`)):zx(n,o,e)},Lh=async(e,t)=>{let{seams:r}=jh(e,t);return{state:(await Fh(r)).state,stableNode:r.stableNode}},Zx=()=>[Fo,Lt,_h(),"portless CA chain valid","portless CA trusted","portless routes"],Qx=async(e={})=>{let t=e.resolveBin??Tp,r=e.isProxyServing??Ip,n=e.handshake??Mp,o=e.caTrusted??_p,s=e.routes??Nn,i=e.isListening??Dn,a=(e.caPath??Np)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...Zx().map(b=>({name:b,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=jh(e,c),m=s(),g=await Ax(r,c,u),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await Ox(n,m,a,c,u);return[l,p,(await Fh(u)).row,g,y,Ix(o(),a,c),await Dx(m,i,c)]},eT=async(e={})=>{let t="portless routes",r=e.routes??Nn,n=e.isListening??Dn,o=e.devSessionRunning??Df,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}=If(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??jp().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},$i=async(e={})=>{let t=await zP(),r=JP(e.probeDeps??$o()),n=async(m,g)=>{let[y,b]=await Promise.all([g,r]),w=b.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",vt("brew installed",Le("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",vt("git installed",Le("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",vt("gh installed",Le("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),vt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",vt("doppler installed",Le("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",vt("aws installed",Le("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),vt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),vt("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"),KP(),Promise.resolve(HP()),Promise.resolve(qP()),YP(),Promise.resolve(XP(t)),nx(),tx(t),ox(e.fix??!1),ix(),ax()]),s=await Qx(e.portlessDeps);if(e.fix){let m=await eT(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await px(),a=await Ro(),c={projectDir:it.env.CLAUDE_PROJECT_DIR||null,cwd:it.cwd(),gitRoot:a},l=[await yx(),...bx(i,c),So(),Ex({env:it.env,stdinIsTTY:it.stdin.isTTY===!0,flag:_.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:xx(a)],u=[...o,await Cx(a),...s,...await dx(),...l,Rx(cn(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Yc.has(m.name),detail:m.detail})),allPassed:WP(u),cliVersion:U.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},Kl=E({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:ge.array(ge.object({name:ge.string().describe("Name of the check"),status:ge.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:ge.string().describe("Details about the check result"),fixable:ge.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ge.object({manager:ge.string().describe("Which package manager owns this install, read from its resolved path"),version:ge.string().nullable().describe("The version the tool reported, or null"),present:ge.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ge.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:ge.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:ge.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>$i()});import{E2E_MODE_ENV as TT}from"@slip-stream-kit/config/internal";import eu from"node:fs";import CT from"node:os";import Bo from"node:path";import Ii from"node:process";import{z as R}from"zod";var at=(e,t,r)=>new C({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as tT,loadDev as rT,readAppAliasName as nT,readCloudOrigin as oT,readLocalContext as Uh}from"@slip-stream-kit/config/internal";import Bh from"node:fs";import gr from"node:path";import Ai from"node:process";import{z as Hl}from"zod";var sT=async e=>{let t=gr.join(e,"apps"),r=Bh.existsSync(t)?Bh.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=gr.join(t,o,"tests"),i=await Ir(s);i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},iT=(e,t)=>{let[r,n]=gr.relative(e,t).split(gr.sep);return r==="apps"&&n?n:void 0},aT=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(iT(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new C({status:"argument_required",argument:a,choices:Hl.toJSONSchema(Hl.object({app:Hl.enum(i)})),agentMode:_.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},cT=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}})),lT=e=>ao(e).apps.find(t=>t.env!=="")?.env??null,ql=async(e,t={})=>{let r=t.cwd??Ai.cwd(),n=t.projectRoot??await P(),o=(t.env??Ai.env)[Er]||null,s=t.healthProbe??qa,i=aT(await sT(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=gr.join(n,"apps",c,l),p=(await Qt(u)).name,m=(await Ir(u))?.deployedUrlEnv??null;if(!p)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${gr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let g=Mm(u),y=nT(p,u),b=`${y}.localhost`,w=`https://${b}`,x=0;if(l==="ui")x=(t.listRoutes??Nn)().find(T=>T.name===b||T.name===y)?.port??0;else{let T=Uh(u).info.get(p);x=T?.port??0,w=T?.origin??w}let D=x>0&&await s({tag:a,port:x,kind:l})==="ok",N=D?lT(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:g,env:o,servedEnv:N,localUrl:w,served:D}},Vh=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}},Yl=async(e,t={})=>{let r=t.healthProbe??qa,n=Uh(e.targetDir),o=e.kind==="ui"?await rT(e.targetDir):void 0,s=o?.proxy?tT({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:oT(e.deployedUrlEnv??void 0,t.env??Ai.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Vh(e),mode:"local",baseUrl:e.localUrl,routes:await cT(s,i,r)}},zl=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw at("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${gr.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??Ai.env)[n];if(!r||!s){let i=s?Er:n;throw at("env_not_loaded",{missing:i},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${Er}, and ${i} is not set`})}return{...Vh(e),mode:"cloud",baseUrl:s,routes:[]}};import uT from"node:fs";import dT from"node:path";import{stripVTControlCharacters as pT}from"node:util";import{z as A}from"zod";var Wh=2e3,Gh="--reporter=line,json",Jh=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Kh=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Xl=A.object({message:A.string().optional()}),Hh=A.object({type:A.string()}),mT=A.object({status:A.string(),retry:A.number(),error:Xl.optional(),errors:A.array(Xl).optional(),annotations:A.array(Hh).optional(),attachments:A.array(A.object({name:A.string(),path:A.string().optional()})).optional()}),fT=A.object({projectName:A.string(),status:A.string(),expectedStatus:A.string().optional(),annotations:A.array(Hh).optional(),results:A.array(mT)}),gT=A.object({title:A.string(),file:A.string(),line:A.number().optional(),tests:A.array(fT)}),qh=A.lazy(()=>A.object({title:A.string(),specs:A.array(gT).optional(),suites:A.array(qh).optional()})),hT=A.object({config:A.object({rootDir:A.string().optional()}).optional(),suites:A.array(qh),errors:A.array(Xl).optional(),stats:A.object({expected:A.number(),unexpected:A.number(),flaky:A.number(),skipped:A.number()})}),Yh=e=>{let t=pT(e);return t.length>Wh?`${t.slice(0,Wh)}\u2026`:t},yT=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Yh(t)},vT=e=>e.status==="unexpected"||e.status==="flaky",wT=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},kT=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),bT=(e,t)=>{let r=e.filter(vT),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?yT(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},RT=e=>{let t=hT.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 g=new Set(m.flatMap(w=>[...kT(w)])),y=m.some(w=>w.expectedStatus==="failed");if(!y&&!g.has("fixme")&&!g.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};y&&(b.fail+=1),g.has("fixme")?b.fixme+=1:g.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let g of p.specs??[]){let y=r?.rootDir?dT.resolve(r.rootDir,g.file):g.file,b=[...m,g.title].join(" \u203A ");l(y,g.tests);for(let[w,x]of wT(g.tests)){let D=bT(x,{title:b,file:y,line:g.line??null,project:w});D&&(D.runs>1&&D.failedRuns<D.runs&&(c+=1),i.push(D))}}for(let g of p.suites??[])u(g,[...m,g.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?[]:[Yh(p.message)])}},zh=e=>{try{return RT(JSON.parse(uT.readFileSync(e,"utf8")))}catch{return null}};import Lo from"node:fs";import Zh from"node:path";import Oi from"node:process";var ST=e=>Zh.join(e,"node_modules",".cache","infra-kit-e2e.lock"),ET=e=>{try{return Oi.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Xh=e=>{try{return Lo.writeFileSync(e,String(Oi.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},Zl=e=>{try{let t=Number.parseInt(Lo.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},Qh=e=>{let t=ST(e);if(Lo.mkdirSync(Zh.dirname(t),{recursive:!0}),!Xh(t)){let r=Zl(t);if(r!==null&&r!==Oi.pid&&ET(r))return{holder:r};if(Lo.rmSync(t,{force:!0}),!Xh(t))return{holder:Zl(t)??0}}return{release:()=>{Zl(t)===Oi.pid&&Lo.rmSync(t,{force:!0})}}};import{spawn as PT}from"node:child_process";import xT from"node:os";import Ql from"node:process";var ey=(e,t,r)=>new Promise((n,o)=>{let s=PT(e,t,r),i=Ql.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Ql.off(l,a)};for(let l of i)Ql.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+xT.constants.signals[u]:1))})});var $T=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],AT=e=>$T.some(t=>{try{return eu.readFileSync(Bo.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),tu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,OT=(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(`
347
- `)},IT=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw at("dead_local_routes",{routes:r},{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},DT=async(e,t)=>{if(e.env===null||!Nm(e.env))return;let r=await(t.protectedEnvAccess??Ye)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?at("protected_env",{env:e.env,humanMayRun:!0},{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):at("protected_env",{env:e.env,humanMayRun:!1},{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},NT=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw at("served_env_mismatch",{servedEnv:e.servedEnv,env:e.env},{operation:`run ${e.app} e2e against the local dev server`,remediation:`load the same env (\`infra-kit env-load -c ${e.servedEnv}\`), or restart \`infra-kit dev\` under "${e.env??"none"}"`,stderrExcerpt:`the dev server serving ${e.target} runs with env "${e.servedEnv}", this shell with "${e.env??"none"}"`})},_T=async(e,t)=>{if(e.served){NT(e);let p=await Yl(e,t);return IT(p),p}if(!AT(e.testsDir))throw at("no_dev_server",{devCommand:tu(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${tu(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:[]}},MT=(e,t,r)=>ey("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Ii.env,...r,[TT]:e.mode},stdio:["inherit",Yt.enabled||J()?2:"inherit","inherit"]}),jT=(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:Bo.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=Bo.join(e.testsDir,"test-results",`ik-e2e-${n}-${Ii.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},FT=e=>{if(e.mode==="cloud")return()=>{};let t=Qh(e.testsDir);if("holder"in t)throw at("run_in_progress",{pid:t.holder},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${t.holder}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (pid ${t.holder}) is using its dev server`});return t.release},Di=async(e,t={})=>{let r=await ql(e.app,t),n=e.cloud?zl(r,t):await _T(r,t);d.info(OT(n,r.served)),n.mode==="cloud"&&await DT(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?tu(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return nu({...o,ran:!1,exitCode:null,...ru});n.mode==="cloud"&&await L(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=FT(n);try{return await LT(o,t.runPlaywright??MT)}finally{s()}},LT=async(e,t)=>{if(!J()||Kh(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(Ii.exitCode=i),nu({...e,ran:!0,exitCode:i,...ru,report:J()?"caller-reporter":"off"})}let{args:r,outputDir:n}=jT(e,e.playwrightArgs),o=eu.mkdtempSync(Bo.join(CT.tmpdir(),"ik-e2e-report-")),s=Bo.join(o,"report.json");try{let i=await t(e,[Gh,...r],Jh(s));i!==0&&(Ii.exitCode=i);let a=zh(s);return nu({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...ru,report:"unavailable"},outputDir:n})}finally{eu.rmSync(o,{recursive:!0,force:!0})}},ru={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},nu=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),BT={app:R.string(),testsDir:R.string(),target:R.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:R.string(),mode:R.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:R.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:R.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:R.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:R.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:R.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:R.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:R.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:R.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:R.array(R.object({path:R.string(),packageName:R.string(),source:R.enum(["local","cloud"]),target:R.string().nullable(),live:R.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:R.array(R.string()),ran:R.boolean().describe("False for --dry-run."),exitCode:R.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:R.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:R.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:R.object({expected:R.number(),unexpected:R.number(),flaky:R.number(),skipped:R.number(),repeatFlaky:R.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:R.array(R.object({title:R.string().describe("Describe path and test title, joined with \u203A."),file:R.string(),line:R.number().nullable(),project:R.string(),status:R.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:R.number().describe("The retry index of the failed attempt reported here."),runs:R.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:R.number().describe("How many of those runs failed."),error:R.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:R.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:R.array(R.object({file:R.string(),fail:R.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:R.number().describe("test.fixme \u2014 skipped as unfinished."),skip:R.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:R.array(R.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},ou=E({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:R.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:R.boolean().optional(),yes:R.boolean().optional(),cloud:R.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:R.array(R.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:BT,handler:e=>Di(e)});import Ni from"node:fs";import su from"node:path";import{z as Uo}from"zod";var UT=e=>[...e.map(t=>`unset ${t}`),`unset ${Er}`,`unset ${ws}`,`unset ${ks}`,`unset ${yp}`,`unset ${bs}`],_i=async()=>{let e=Pr(),t=su.join(e,Sr);if(!Ni.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Rs(t),n=UT(r),o=su.resolve(e,ys);Ni.mkdirSync(e,{recursive:!0,mode:448}),bt(o,`${n.join(`
345
+ ${jt}`;import mP from"node:fs/promises";var To=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await mP.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}}},Co=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import gP from"node:fs";import hP from"node:os";import ih from"node:path";import yP from"node:process";import{$ as fP}from"zx";var gn=()=>fP({quiet:!0});var vP=()=>[ih.join(hP.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],wP=async e=>{try{return(await gn()`command -v ${e}`).stdout.trim()||null}catch{return null}},$o=()=>({runCommand:async e=>{let t=await gn()`${e}`;return{stdout:`${t.stdout}
346
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await wP(e);return t!==null?t:vP().map(r=>ih.join(r,e)).find(r=>gP.existsSync(r))??null},realpath:ye,platform:yP.platform});var Ft=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),hn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,yn=["darwin","linux"],Pi=e=>t=>Da(t,e)?"homebrew":"unknown",xi=(e,t)=>r=>r===null?null:t(e(r),r),Al=e=>xi(Pi(e.kegName),t=>t==="homebrew"?Ft(["brew","upgrade",e.brewFormula]):null),ah=e=>Ss(e,"Homebrew")||Ss(e,"homebrew")?"homebrew":"unknown",kP={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:hn,platforms:yn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:ah,updateFor:xi(ah,e=>e==="homebrew"?Ft(["brew","update"]):null)},$l={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},uh="https://awscli.amazonaws.com/v2/install.sh",dh={steps:[["/bin/bash","-c",`curl -fsSL ${uh} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},bP="/usr/local/aws-cli",RP=e=>In(bP,e,ye)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${uh} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:dh,ch=e=>Da(e,$l.kegName)?"homebrew":Ss(e,"aws-cli")?"script":"unknown",SP={id:"aws",binName:"aws",...$l,probeArgv:["aws","--version"],versionFrom:hn,platforms:yn,prerequisites:[],bootstrapInstall:dh,identify:ch,updateFor:xi(ch,(e,t)=>e==="homebrew"?Ft(["brew","upgrade",$l.brewFormula]):e==="script"?RP(t):null)},Ri={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},EP={id:"git",binName:"git",...Ri,probeArgv:["git","--version"],versionFrom:hn,platforms:yn,prerequisites:["brew"],bootstrapInstall:Ft(["brew","install",Ri.brewInstallSpec]),identify:Pi(Ri.kegName),updateFor:Al(Ri)},Si={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},PP={id:"gh",binName:"gh",...Si,probeArgv:["gh","--version"],versionFrom:hn,platforms:yn,prerequisites:["brew"],bootstrapInstall:Ft(["brew","install",Si.brewInstallSpec]),identify:Pi(Si.kegName),updateFor:Al(Si)},Ei={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},xP={id:"doppler",binName:"doppler",...Ei,probeArgv:["doppler","--version"],versionFrom:hn,platforms:yn,prerequisites:["brew"],bootstrapInstall:Ft(["brew","install","gnupg"],["brew","install",Ei.brewInstallSpec]),identify:Pi(Ei.kegName),updateFor:Al(Ei)},Ao="portless",lh=e=>bp(e,Ao)===null?"unknown":"npm",TP={id:"portless",binName:Ao,npmPackage:Ao,probeArgv:["portless","--version"],versionFrom:hn,platforms:[...yn,"win32"],prerequisites:[],bootstrapInstall:Ft(["npm","install","-g",Ao]),identify:lh,updateFor:xi(lh,e=>e==="npm"?Ft(["npm","install","-g",`${Ao}@latest`]):null)},Ol={brew:kP,git:EP,aws:SP,gh:PP,doppler:xP,portless:TP},ur=Object.keys(Ol),Le=e=>Ol[e],Il=(e,t)=>e.platforms.includes(t),Dl=e=>{let t=[],r=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!r.has(o)){r.add(o);for(let i of Le(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var ph=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),mh=async(e,t)=>{try{return await e(t)}catch{return null}},CP=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},fh=async(e,t)=>{if(!Il(e,t.platform))return ph(e.id);let r=await mh(t.runCommand,e.probeArgv),n=await CP(t,e.binName);if(r==null&&n==null)return ph(e.id);let o=r??(n==null?null:await mh(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)}},Oo=async(e,t)=>Promise.all(e.map(r=>fh(Le(r),t)));import{$ as NP}from"zx";import{z as gh}from"zod";var hh=/^\d{4}-\d{2}-\d{2}$/,Io=e=>{if(!hh.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},yh=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,vn=class extends Error{constructor(t){super(yh(t)),this.name="InvalidReleaseDateError"}},dr=e=>{let t=e.trim();if(!Io(t))throw new vn(t);return t},Do=e=>{let t=e.trim();return t===""||Io(t)?!0:yh(t)},Nl=gh.string().refine(Io,{message:"Expected a calendar date in yyyy-mm-dd form."}),_l=gh.string().refine(e=>e===""||Io(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Lt=e=>e.slice(1).split(".").map(Number),wn=e=>[...e].sort((t,r)=>{let[n,o,s]=Lt(t),[i,a,c]=Lt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var wh="next",$P=/^v?(\d+)\.(\d+)\.(\d+)$/,AP=e=>e.replace(/^.*release\//,""),Ml=e=>{let t=AP(e.trim()),r=$P.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},vh=e=>`${e[0]}.${e[1]}.${e[2]}`,jl=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Ml(o);if(!s)continue;let i=vh(s);n.has(i)||(n.add(i),r.push(s))}return wn(r.map(o=>vh(o))).map(o=>Lt(`v${o}`))},pr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Fl=(e,t)=>{if(e.length===0)throw new pr;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},kn=(e,t)=>{try{return Fl(e,t)}catch(r){if(r instanceof pr)return null;throw r}},Ll=e=>e.trim().toLowerCase()===wh,Ci=e=>Ll(e)||Ml(e)!==null?{version:e}:{name:e},OP=e=>e==="regular"||e==="hotfix",kh=e=>"name"in e,IP=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:dr(n)}},Bl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=IP(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(!OP(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return Ti({...Ci(n),type:s},{description:i,releaseDate:o})},Ul=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},Ti=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},DP=e=>{let t=e.name.trim();return Cs(t),Ti({id:{kind:"name",name:t,raw:t},type:e.type},e)},Vl=(e,t)=>{let r=[...t];return e.map(n=>{if(kh(n))return DP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Ll(o)){let a=Fl(r,n.type);return r.push(Lt(`v${a}`)),Ti({id:pe(a),type:n.type},n)}let s=Ml(o);if(!s)throw new Error(`Invalid version "${o}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return r.push(s),Ti({id:pe(i),type:n.type},n)})},Wl=e=>e.some(t=>!kh(t)&&Ll(t.version));var _P=e=>e.split(`
347
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:H(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),MP=async()=>{let e=await NP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return _P(e.stdout)},jP=async()=>{let e=await gt();return e?(await Xr(e)).map(r=>r.name):[]},No=async()=>{let[e,t]=await Promise.allSettled([MP(),jP()]);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"),jl({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import FP from"node:fs";import LP from"node:path";var Gl=[".claude/settings.json",".claude/settings.local.json"],BP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],UP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),VP=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},WP=(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(UP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},GP=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},JP=()=>mr.filter(e=>e.mutating),KP=e=>{let t=VP(e);return t===null?[]:JP().filter(r=>BP.some(n=>GP(r).some(o=>WP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},HP=(e,t)=>{let r;try{r=FP.readFileSync(LP.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}},bh=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Gl){let n=HP(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=KP(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var qP=e=>e.every(t=>t.status!=="fail"),YP=["brew","git","gh","doppler","aws"],zP=async e=>{let t=await Oo(YP,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},vt=async(e,t,r,n)=>{try{return await gn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},XP=async()=>{let e="orca installed",t=await Tt();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)"}},Dh=(e,t,r,n)=>{let o=de.join(Ih.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!te.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=te.readFileSync(o,"utf-8"),a=i.indexOf(lr),c=i.indexOf(jt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+jt.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`}},ZP=()=>Dh("zshrc init block",".zshrc","shell",sh()),QP=()=>Dh("zshenv session block",".zshenv","session-env",Cl()),ex=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await P(),r=de.join(t,"pnpm-workspace.yaml");if(!te.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=te.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},tx=async()=>{try{return Et(),{config:await W(),error:null}}catch(e){return{config:null,error:e}}},rx=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)"}},nx=384,Jl=448,ox=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(", "),sx=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}}})),ix=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Je,o=t.resolveToken??Em;if(!e.config)return{name:r,status:"skip",message:"infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await sx(await Fs(),o);return{name:r,status:"pass",message:ox(s)}},ax=()=>it.env[Qt]||void 0,cx=async(e={})=>{let t="tokens.json present",r=e.readStore??Je,n=e.storePath??xt;if((e.readEnvToken??ax)())return{name:t,status:"skip",message:`${Qt} is set; that channel takes precedence over the store`};let s;try{s=v(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${Qt} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},_o=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},lx=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??xt,o=t.statPath??ux,s=t.chmodPath??te.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(_o(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=de.dirname(i),c=de.dirname(a),l=de.dirname(c),p=[{target:l,expected:Jl,actual:_o(l,o)},{target:c,expected:Jl,actual:_o(c,o)},{target:a,expected:Jl,actual:_o(a,o)},{target:i,expected:nx,actual:_o(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(g=>`${v(g.target)} is ${Rh(g.actual)}, expected ${Rh(g.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 g of p)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},Rh=e=>`0${e.toString(8).padStart(3,"0")}`,ux=e=>{try{return te.statSync(e)}catch{return null}},dx=async()=>{let e="user override path";try{let t=await q(),r=te.existsSync(t.userProject),n=await To(t.userProject,r),o=r?Co(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${v(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},px=async()=>{let e="legacy user-global config",t;try{t=await q()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=de.join(de.dirname(t.userGlobal),"config.json");return te.existsSync(r)?te.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${v(r)} \u2014 ${v(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${v(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Sh=/^\d+\.\d+\.\d+$/,mx=(e,t)=>e===t||!Sh.test(e)||!Sh.test(t)?!1:wn([`v${e}`,`v${t}`])[0]===`v${e}`,fx=async(e,t)=>{let r;try{r=await Pe(e)}catch{return[]}let n=[];for(let o of r){let s=nr(or(de.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&mx(s.version,t)&&n.push(s.version)}return n},gx=async(e,t)=>{let r=await fx(e,t);if(r.length===0)return"";let n=wn(r.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${r.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${t}) \u2014 run: infra-kit audit --fix --all`},hx=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await q()).main}catch{return e}if(!te.existsSync(t))return e;let r=de.dirname(t),n=de.join(r,"CLAUDE.md"),o=te.existsSync(n)?te.readFileSync(n,"utf-8"):"",s=Xe(o,_e,Ze),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await gx(r,U.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},yx=async()=>{try{let e=(await q()).main;return te.existsSync(e)?de.dirname(e):null}catch{return null}},vx=e=>{let t=dm();return t===null||!Ln(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Vr}`},wx=e=>{let t=e.kind==="installed"?Ns(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${G} version ${t}${vx(t)}`}},Eh=3,Ph=(e,t)=>ye(e)===ye(t),kx=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(Ph(e.projectDir,e.gitRoot))return"";let r=In(e.gitRoot,ye(e.projectDir),ye)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${v(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return Ph(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${v(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},bx=(e,t)=>{let r="plugin installed",n=kx(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${G} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${G} is not installed. Run: ${mt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-Eh,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Eh).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${G} is installed for ${a} only, not this project. Run: ${mt}${n}`}},Rx=()=>vt("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 Sx=(e,...t)=>{try{return JSON.parse(te.readFileSync(de.join(e,...t),"utf-8"))}catch{return null}},Ex=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=Ns(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=Sx(r,Me),o=n!==null&&typeof n=="object"?n[et]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},xh=e=>`Plugin ${G} ${e===null?"(version unreadable)":e}`,Px=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: ${mt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${xh(e.version)} still carries an MCP server in its ${Me}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Vr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${xh(e.version)} is skills-only \u2014 no ${Me}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},xx=(e,t)=>{let r=Xt(e===null?{}:{projectPath:e}),n=Fn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${oe} is known to Claude Code`:`Marketplace ${oe} is not registered. Run: claude plugin marketplace add ${Pt}`},bx(r,t),wx(r),Px(Ex(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},Tx=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${v(an())}, or run: infra-kit setup`}},Cx=({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(", ")},$x=e=>{let t="Agent mode",r=Ts(e),n=Cx(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})`}},Th=4,Ax=e=>{let t=e.slice(0,Th).join(", "),r=e.length-Th;return r>0?`${t} +${r} more`:t},Ox=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=bh(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"} (${Ax(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 ${Gl.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`}},Ix=(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`},Dx=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 hg(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?v(i.worktreePath):"worktree missing";return`${i.branch} (${Ix(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`}},Nh=e=>Na(["trust"],{bin:e}),Nx=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Ch="ERR_TLS_CERT_ALTNAME_INVALID",_h=()=>`portless serving TLS on :${St}`,_x=async(e,t,r)=>{let n=_h();return await e(St,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${St}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${St}. Install it once (needs root): \`${Rt(t,r)}\`.`}},Mx=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(St,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(Ch)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Ch} 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=>Nx.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${Nh(n)}\`, or reinstall: \`${Rt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},jx=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${v(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Nh(r)}\` (no sudo needed).`}},Fx=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 \`${Na(["alias","--remove","<name>"],{bin:r})}\`.`}},Bt="portless service target",jo=e=>({name:Bt,status:"warn",message:e}),Mh=e=>e==="darwin"?$p:e==="linux"?Ap:null,Lx=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Cp}`:`sudo systemctl restart ${Op}`,Bx="/bin/ps",Ux=e=>{try{let t=Oh(Bx,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(t.status!==0)return null;let r=new Date(t.stdout.trim());return Number.isNaN(r.getTime())?null:r}catch{return null}},$h=e=>{try{return te.readFileSync(e,"utf-8")}catch{return null}},Vx=e=>{try{return te.statSync(e).mtime}catch{return null}},Wx=2e3,Gx=e=>{try{let t=Oh(e,["-p","process.version"],{encoding:"utf-8",timeout:Wx}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},Jx=(e,t)=>({platform:e.platform??it.platform,readServiceFile:e.readServiceFile??$h,readFile:e.readFile??$h,exists:e.exists??te.existsSync,realpath:e.realpath??ye,mtime:e.mtime??Vx,execPath:e.execPath??it.execPath,home:e.home??Ih.homedir(),cwd:e.cwd??it.cwd(),repoRoot:e.repoRoot??Ro,stateDir:(e.stateDir??Dp)(),processStartTime:e.processStartTime??Ux,version:e.version??it.version,arch:e.arch??it.arch,nodeVersionOf:e.nodeVersionOf??Gx,isGlobal:e.isGlobal??xs().node.isGlobal,nodeFs:e.nodeFs??te,stableNode:null,stableNodeSidecar:null,bin:t}),Fo="portless node",fr="~/.infra-kit/node",Mo=e=>({row:{name:Fo,status:"fail",message:e},stableNode:null,sidecar:null}),Ah=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},Kx=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,Hx=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,qx=e=>{let t=Fp(e.home),r=Ah(e.nodeFs.lstatSync,t);if(r===void 0)return Mo(`${fr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Mo(`${fr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Lp(e.home,e.nodeFs);if(n===null)return Mo(`${fr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Ah(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 Mo(`${fr} is Node ${n.version} (${n.method} of ${v(n.source)}); infra-kit runs ${e.version} at ${v(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!Hx(c,e))return Mo(`${fr} does not run as Node ${e.version} (${Kx(c)}). Re-run through the current Node: \`${Rt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Fo,status:"pass",message:`${fr} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},Yx=e=>{if(Mh(e.platform)===null)return{row:{name:Fo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=qx(e);return e.isGlobal()?t:{...t,row:{name:Fo,status:"skip",message:`not a global install; the global infra-kit keeps ${fr} current`}}},jh=(e,t)=>{let r=Jx(e,t),n=Yx(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},zx=(e,t)=>{let r=t.readFile(de.join(e,"package.json"));try{let n=r===null?null:fe.object({version:fe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},Xx=e=>{let t=Number.parseInt(e.readFile(de.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},Zx=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},Qx=(e,t,r)=>{let n=Xx(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(Zx(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(de.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},eT=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:In(await t.repoRoot()??r,e,t.realpath)},gr=e=>({state:"drifted",row:e}),tT=async(e,t,r)=>{let n=Rt(r.bin,r);if(!r.exists(e))return gr({name:Bt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=de.join(_a(r.home),"dist","cli.js");if(t!==o)return gr(jo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Ps(r.home,r.exists)===null)return gr({name:Bt,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(_a(r.home));if(await eT(s,r))return gr({name:Bt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=rT(e,n,r);if(i!==null)return i;let a=zx(s,r),c=Qx(s,a,r);return c!==null?{state:"converged",row:jo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${Lx(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Bt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},rT=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:gr(jo(`The service runs \`${e}\`, a path its package manager will remove. Re-run once to switch it to the stable node: \`${t}\``)):r.realpath(e)===r.realpath(r.execPath)?null:gr(jo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Fh=async e=>{let t=Mh(e.platform);if(t===null)return{state:"absent",row:{name:Bt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Bt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Lf(e.platform,r)??[];return n===void 0||o===void 0?gr(jo(`could not parse ${t} \u2014 re-run \`${Rt(e.bin,e)}\` to rewrite it.`)):tT(n,o,e)},Lh=async(e,t)=>{let{seams:r}=jh(e,t);return{state:(await Fh(r)).state,stableNode:r.stableNode}},nT=()=>[Fo,Bt,_h(),"portless CA chain valid","portless CA trusted","portless routes"],oT=async(e={})=>{let t=e.resolveBin??Tp,r=e.isProxyServing??Ip,n=e.handshake??Mp,o=e.caTrusted??_p,s=e.routes??Nn,i=e.isListening??Dn,a=(e.caPath??Np)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...nT().map(b=>({name:b,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=jh(e,c),m=s(),g=await _x(r,c,u),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await Mx(n,m,a,c,u);return[l,p,(await Fh(u)).row,g,y,jx(o(),a,c),await Fx(m,i,c)]},sT=async(e={})=>{let t="portless routes",r=e.routes??Nn,n=e.isListening??Dn,o=e.devSessionRunning??Nf,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}=Df(i,o());if(c.length>0)return{name:t,status:"fail",message:`${c.length} route(s) look stale (${c.join(", ")}), but a dev session is running \u2014 a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. Stop dev and re-run \`infra-kit doctor --fix\`.`};if(a.length===0)return{name:t,status:"pass",message:`${s.length} portless route(s), all live`};let l=e.removeAlias??jp().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},$i=async(e={})=>{let t=await tx(),r=zP(e.probeDeps??$o()),n=async(m,g)=>{let[y,b]=await Promise.all([g,r]),w=b.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",vt("brew installed",Le("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",vt("git installed",Le("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",vt("gh installed",Le("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),vt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",vt("doppler installed",Le("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",vt("aws installed",Le("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),vt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),vt("typescript-language-server installed",["typescript-language-server","--version"],"typescript-language-server is installed","typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing"),XP(),Promise.resolve(ZP()),Promise.resolve(QP()),ex(),Promise.resolve(rx(t)),cx(),ix(t),lx(e.fix??!1),dx(),px()]),s=await oT(e.portlessDeps);if(e.fix){let m=await sT(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await yx(),a=await Ro(),c={projectDir:it.env.CLAUDE_PROJECT_DIR||null,cwd:it.cwd(),gitRoot:a},l=[await Rx(),...xx(i,c),So(),$x({env:it.env,stdinIsTTY:it.stdin.isTTY===!0,flag:_.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:Ox(a)],u=[...o,await Dx(a),...s,...await hx(),...l,Tx(cn(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Yc.has(m.name),detail:m.detail})),allPassed:qP(u),cliVersion:U.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},Kl=E({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:fe.array(fe.object({name:fe.string().describe("Name of the check"),status:fe.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:fe.string().describe("Details about the check result"),fixable:fe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:fe.object({manager:fe.string().describe("Which package manager owns this install, read from its resolved path"),version:fe.string().nullable().describe("The version the tool reported, or null"),present:fe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:fe.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:fe.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:fe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>$i()});import{E2E_MODE_ENV as IT}from"@slip-stream-kit/config/internal";import eu from"node:fs";import DT from"node:os";import Bo from"node:path";import Ii from"node:process";import{z as R}from"zod";var at=(e,t,r)=>new C({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as iT,loadDev as aT,readAppAliasName as cT,readCloudOrigin as lT,readLocalContext as Uh}from"@slip-stream-kit/config/internal";import Bh from"node:fs";import hr from"node:path";import Ai from"node:process";import{z as Hl}from"zod";var uT=async e=>{let t=hr.join(e,"apps"),r=Bh.existsSync(t)?Bh.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=hr.join(t,o,"tests"),a=(await Ot(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},dT=(e,t)=>{let[r,n]=hr.relative(e,t).split(hr.sep);return r==="apps"&&n?n:void 0},pT=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(dT(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new C({status:"argument_required",argument:a,choices:Hl.toJSONSchema(Hl.object({app:Hl.enum(i)})),agentMode:_.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},mT=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}})),fT=e=>ao(e).apps.find(t=>t.env!=="")?.env??null,ql=async(e,t={})=>{let r=t.cwd??Ai.cwd(),n=t.projectRoot??await P(),o=(t.env??Ai.env)[Pr]||null,s=t.healthProbe??qa,i=pT(await uT(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=hr.join(n,"apps",c,l),p=(await er(u)).name,m=(await Ot(u))?.deployedUrlEnv??null;if(!p)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${hr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let g=Mm(u),y=cT(p,u),b=`${y}.localhost`,w=`https://${b}`,x=0;if(l==="ui")x=(t.listRoutes??Nn)().find(T=>T.name===b||T.name===y)?.port??0;else{let T=Uh(u).info.get(p);x=T?.port??0,w=T?.origin??w}let D=x>0&&await s({tag:a,port:x,kind:l})==="ok",N=D?fT(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:g,env:o,servedEnv:N,localUrl:w,served:D}},Vh=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}},Yl=async(e,t={})=>{let r=t.healthProbe??qa,n=Uh(e.targetDir),o=e.kind==="ui"?await aT(e.targetDir):void 0,s=o?.proxy?iT({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:lT(e.deployedUrlEnv??void 0,t.env??Ai.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Vh(e),mode:"local",baseUrl:e.localUrl,routes:await mT(s,i,r)}},zl=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw at("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${hr.join(e.targetDir,"infra-kit.config.ts")} and keep the URL per environment in Doppler`,stderrExcerpt:`${o} names no variable holding its deployed URL`});let s=(t.env??Ai.env)[n];if(!r||!s){let i=s?Pr:n;throw at("env_not_loaded",{missing:i},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${Pr}, and ${i} is not set`})}return{...Vh(e),mode:"cloud",baseUrl:s,routes:[]}};import gT from"node:fs";import hT from"node:path";import{stripVTControlCharacters as yT}from"node:util";import{z as A}from"zod";var Wh=2e3,Gh="--reporter=line,json",Jh=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Kh=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Xl=A.object({message:A.string().optional()}),Hh=A.object({type:A.string()}),vT=A.object({status:A.string(),retry:A.number(),error:Xl.optional(),errors:A.array(Xl).optional(),annotations:A.array(Hh).optional(),attachments:A.array(A.object({name:A.string(),path:A.string().optional()})).optional()}),wT=A.object({projectName:A.string(),status:A.string(),expectedStatus:A.string().optional(),annotations:A.array(Hh).optional(),results:A.array(vT)}),kT=A.object({title:A.string(),file:A.string(),line:A.number().optional(),tests:A.array(wT)}),qh=A.lazy(()=>A.object({title:A.string(),specs:A.array(kT).optional(),suites:A.array(qh).optional()})),bT=A.object({config:A.object({rootDir:A.string().optional()}).optional(),suites:A.array(qh),errors:A.array(Xl).optional(),stats:A.object({expected:A.number(),unexpected:A.number(),flaky:A.number(),skipped:A.number()})}),Yh=e=>{let t=yT(e);return t.length>Wh?`${t.slice(0,Wh)}\u2026`:t},RT=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Yh(t)},ST=e=>e.status==="unexpected"||e.status==="flaky",ET=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},PT=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),xT=(e,t)=>{let r=e.filter(ST),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?RT(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},TT=e=>{let t=bT.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 g=new Set(m.flatMap(w=>[...PT(w)])),y=m.some(w=>w.expectedStatus==="failed");if(!y&&!g.has("fixme")&&!g.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};y&&(b.fail+=1),g.has("fixme")?b.fixme+=1:g.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let g of p.specs??[]){let y=r?.rootDir?hT.resolve(r.rootDir,g.file):g.file,b=[...m,g.title].join(" \u203A ");l(y,g.tests);for(let[w,x]of ET(g.tests)){let D=xT(x,{title:b,file:y,line:g.line??null,project:w});D&&(D.runs>1&&D.failedRuns<D.runs&&(c+=1),i.push(D))}}for(let g of p.suites??[])u(g,[...m,g.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?[]:[Yh(p.message)])}},zh=e=>{try{return TT(JSON.parse(gT.readFileSync(e,"utf8")))}catch{return null}};import Lo from"node:fs";import Zh from"node:path";import Oi from"node:process";var CT=e=>Zh.join(e,"node_modules",".cache","infra-kit-e2e.lock"),$T=e=>{try{return Oi.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Xh=e=>{try{return Lo.writeFileSync(e,String(Oi.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},Zl=e=>{try{let t=Number.parseInt(Lo.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},Qh=e=>{let t=CT(e);if(Lo.mkdirSync(Zh.dirname(t),{recursive:!0}),!Xh(t)){let r=Zl(t);if(r!==null&&r!==Oi.pid&&$T(r))return{holder:r};if(Lo.rmSync(t,{force:!0}),!Xh(t))return{holder:Zl(t)??0}}return{release:()=>{Zl(t)===Oi.pid&&Lo.rmSync(t,{force:!0})}}};import{spawn as AT}from"node:child_process";import OT from"node:os";import Ql from"node:process";var ey=(e,t,r)=>new Promise((n,o)=>{let s=AT(e,t,r),i=Ql.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Ql.off(l,a)};for(let l of i)Ql.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+OT.constants.signals[u]:1))})});var NT=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],_T=e=>NT.some(t=>{try{return eu.readFileSync(Bo.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),tu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,MT=(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(`
348
+ `)},jT=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw at("dead_local_routes",{routes:r},{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},FT=async(e,t)=>{if(e.env===null||!Nm(e.env))return;let r=await(t.protectedEnvAccess??Ye)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?at("protected_env",{env:e.env,humanMayRun:!0},{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):at("protected_env",{env:e.env,humanMayRun:!1},{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},LT=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw at("served_env_mismatch",{servedEnv:e.servedEnv,env:e.env},{operation:`run ${e.app} e2e against the local dev server`,remediation:`load the same env (\`infra-kit env-load -c ${e.servedEnv}\`), or restart \`infra-kit dev\` under "${e.env??"none"}"`,stderrExcerpt:`the dev server serving ${e.target} runs with env "${e.servedEnv}", this shell with "${e.env??"none"}"`})},BT=async(e,t)=>{if(e.served){LT(e);let p=await Yl(e,t);return jT(p),p}if(!_T(e.testsDir))throw at("no_dev_server",{devCommand:tu(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${tu(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:[]}},UT=(e,t,r)=>ey("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Ii.env,...r,[IT]:e.mode},stdio:["inherit",zt.enabled||K()?2:"inherit","inherit"]}),VT=(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:Bo.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=Bo.join(e.testsDir,"test-results",`ik-e2e-${n}-${Ii.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},WT=e=>{if(e.mode==="cloud")return()=>{};let t=Qh(e.testsDir);if("holder"in t)throw at("run_in_progress",{pid:t.holder},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${t.holder}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (pid ${t.holder}) is using its dev server`});return t.release},Di=async(e,t={})=>{let r=await ql(e.app,t),n=e.cloud?zl(r,t):await BT(r,t);d.info(MT(n,r.served)),n.mode==="cloud"&&await FT(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?tu(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return nu({...o,ran:!1,exitCode:null,...ru});n.mode==="cloud"&&await L(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=WT(n);try{return await GT(o,t.runPlaywright??UT)}finally{s()}},GT=async(e,t)=>{if(!K()||Kh(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(Ii.exitCode=i),nu({...e,ran:!0,exitCode:i,...ru,report:K()?"caller-reporter":"off"})}let{args:r,outputDir:n}=VT(e,e.playwrightArgs),o=eu.mkdtempSync(Bo.join(DT.tmpdir(),"ik-e2e-report-")),s=Bo.join(o,"report.json");try{let i=await t(e,[Gh,...r],Jh(s));i!==0&&(Ii.exitCode=i);let a=zh(s);return nu({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...ru,report:"unavailable"},outputDir:n})}finally{eu.rmSync(o,{recursive:!0,force:!0})}},ru={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},nu=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),JT={app:R.string(),testsDir:R.string(),target:R.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:R.string(),mode:R.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:R.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:R.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:R.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:R.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:R.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:R.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:R.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:R.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:R.array(R.object({path:R.string(),packageName:R.string(),source:R.enum(["local","cloud"]),target:R.string().nullable(),live:R.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:R.array(R.string()),ran:R.boolean().describe("False for --dry-run."),exitCode:R.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:R.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:R.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:R.object({expected:R.number(),unexpected:R.number(),flaky:R.number(),skipped:R.number(),repeatFlaky:R.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:R.array(R.object({title:R.string().describe("Describe path and test title, joined with \u203A."),file:R.string(),line:R.number().nullable(),project:R.string(),status:R.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:R.number().describe("The retry index of the failed attempt reported here."),runs:R.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:R.number().describe("How many of those runs failed."),error:R.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:R.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:R.array(R.object({file:R.string(),fail:R.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:R.number().describe("test.fixme \u2014 skipped as unfinished."),skip:R.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:R.array(R.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},ou=E({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:R.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:R.boolean().optional(),yes:R.boolean().optional(),cloud:R.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:R.array(R.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:JT,handler:e=>Di(e)});import Ni from"node:fs";import su from"node:path";import{z as Uo}from"zod";var KT=e=>[...e.map(t=>`unset ${t}`),`unset ${Pr}`,`unset ${ws}`,`unset ${ks}`,`unset ${yp}`,`unset ${bs}`],_i=async()=>{let e=xr(),t=su.join(e,Er);if(!Ni.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Rs(t),n=KT(r),o=su.resolve(e,ys);Ni.mkdirSync(e,{recursive:!0,mode:448}),bt(o,`${n.join(`
348
349
  `)}
349
- `,384),Ni.rmSync(t,{force:!0}),Ni.rmSync(su.join(e,vs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},iu=E({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Uo.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Uo.string().describe("Path to the file that must be sourced to apply"),variableCount:Uo.number().describe("Number of variables cleared"),unsetStatements:Uo.array(Uo.string()).describe("Unset statements generated")},handler:()=>_i()});import VT from"node:path";import Vo from"node:process";import{z as bn}from"zod";var Mi=async()=>{d.info("Environment session status:");let e=Pr(),t=Vo.env[On],r=VT.join(e,Sr),n=0,o=0,s=Vo.env[ws]??null,i=Vo.env[ks]??null,a=Vo.env[bs]??null;if(s){let l=Rs(r);l.length>0&&(o=l.length,n=l.filter(p=>p in Vo.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})
350
+ `,384),Ni.rmSync(t,{force:!0}),Ni.rmSync(su.join(e,vs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},iu=E({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Uo.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Uo.string().describe("Path to the file that must be sourced to apply"),variableCount:Uo.number().describe("Number of variables cleared"),unsetStatements:Uo.array(Uo.string()).describe("Unset statements generated")},handler:()=>_i()});import HT from"node:path";import Vo from"node:process";import{z as bn}from"zod";var Mi=async()=>{d.info("Environment session status:");let e=xr(),t=Vo.env[On],r=HT.join(e,Er),n=0,o=0,s=Vo.env[ws]??null,i=Vo.env[ks]??null,a=Vo.env[bs]??null;if(s){let l=Rs(r);l.length>0&&(o=l.length,n=l.filter(p=>p in Vo.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})
350
351
  `),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
351
- `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},au=E({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, and how many variables are cached. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:bn.string().describe("Current terminal session ID"),sessionLoadedCount:bn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:bn.number().describe("Total number of cached var names"),sessionConfig:bn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:bn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:bn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Mi});import WT from"node:process";import{z as Bt}from"zod";var ty="****",ke=e=>typeof e!="string"||e.length<8?ty:`${ty}${e.slice(-4)}`;var ry=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Zt}`:"store",redactedToken:ke(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),GT=["ENV","SOURCE","TOKEN","PRESENT"],ny=(e,t)=>{let r=[...GT,...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())},ji=async({check:e}={})=>{let t=await Fs(),r=await Je(),n=WT.env[Zt],o=ry(t,r?.envs??{},n);if(e){let a=await Xt();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await Sm({childEnv:Vn(l),project:a,config:c.env});c.status=u.outcome}}for(let a of ny(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
352
- No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},cu=E({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:Bt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Bt.array(Bt.object({env:Bt.string().describe("Environment / Doppler config name"),source:Bt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Bt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Bt.boolean().describe("Whether a token is configured for this environment"),status:Bt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ji});import{z as S}from"zod";import{$ as JT}from"zx";var KT=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),HT=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,qT=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(", ")},uu=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),lu=new Set(["up-to-date","fast-forward","merged"]),YT=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=we(me(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},zT={"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"},sy=e=>{let t=zT[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},XT=(e,t)=>{d.info(`
353
- \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${sy(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},ZT=(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`},QT=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=K(i.branch);return a?[[ne(a),sy(i)]]:[]}));return _t(ce({branches:r,descriptions:s}),{required:!0})},eC=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let b of y)d.info(`\u2139\uFE0F ${b} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await wo(t,eg(i));a(c.nowUpToDate);let l=c.kept,u=new Map;if(s&&l.length>0){d.info(`
352
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},au=E({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, and how many variables are cached. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:bn.string().describe("Current terminal session ID"),sessionLoadedCount:bn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:bn.number().describe("Total number of cached var names"),sessionConfig:bn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:bn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:bn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Mi});import qT from"node:process";import{z as Ut}from"zod";var ty="****",ke=e=>typeof e!="string"||e.length<8?ty:`${ty}${e.slice(-4)}`;var ry=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Qt}`:"store",redactedToken:ke(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),YT=["ENV","SOURCE","TOKEN","PRESENT"],ny=(e,t)=>{let r=[...YT,...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())},ji=async({check:e}={})=>{let t=await Fs(),r=await Je(),n=qT.env[Qt],o=ry(t,r?.envs??{},n);if(e){let a=await Zt();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await Sm({childEnv:Vn(l),project:a,config:c.env});c.status=u.outcome}}for(let a of ny(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
353
+ No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},cu=E({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:Ut.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Ut.array(Ut.object({env:Ut.string().describe("Environment / Doppler config name"),source:Ut.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Ut.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Ut.boolean().describe("Whether a token is configured for this environment"),status:Ut.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ji});import{z as S}from"zod";import{$ as zT}from"zx";var XT=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),ZT=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,QT=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(", ")},uu=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),lu=new Set(["up-to-date","fast-forward","merged"]),eC=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=we(pe(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},tC={"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"},sy=e=>{let t=tC[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},rC=(e,t)=>{d.info(`
354
+ \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${sy(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},nC=(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`},oC=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=H(i.branch);return a?[[ne(a),sy(i)]]:[]}));return Mt(ce({branches:r,descriptions:s}),{required:!0})},sC=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let b of y)d.info(`\u2139\uFE0F ${b} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await wo(t,eg(i));a(c.nowUpToDate);let l=c.kept,u=new Map;if(s&&l.length>0){d.info(`
354
355
  \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await rg({worktreePath:r,refs:l,command:s});u=y.failed;for(let[w,x]of y.failed)d.info(`\u2717 ${w} failed verification \u2014 not pushing it. ${x.split(`
355
356
  `)[0]??""}`);let b=await wo(t,y.kept);a(b.nowUpToDate),l=b.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};d.info(`
356
- \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await Os(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await $r(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:p.stderr?.split(`
357
- `)[0],observedLanded:g.map(y=>y.branch)}},tC=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},oy=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
358
- `)[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=>!lu.has(i.status));return uu({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},rC=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Re();if(e.abort)return oy(await xg({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return oy(await Eg({cwd:s,versions:r,all:t,verify:i,trees:Pg(e.tree),confirmedCommand:o}))},Fi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;tC(e);let a=o===!0?tg:o||void 0;if(await Xc({operation:"merge dev into release branches"}),e.continue||e.abort)return rC(e);let c=[],l=[];for(let re of await F()){let qt=HT(re);qt?l.push({branch:re.branch,reason:qt}):c.push(re.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 (${qT(l)})`),h.print(),uu(KT(n,l));let u=await Re();try{await JT({cwd:u,quiet:!0})`git fetch origin --prune`}catch(re){throw new f(re,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:YT(r,c,l),m=await tm({cwd:u},async re=>{let qt=ci(re.remove);try{return await nC({cwd:u,worktree:re,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{qt()}}),{entries:g,selected:y,pushed:b,pushAborted:w,abortedBy:x,declined:D,verifyFailed:N,handOffs:T}=m,le=await qe(u).catch(()=>[]);return iC({entries:g,selected:y,pushed:b,pushAborted:w,abortedBy:x,declined:D,verifyFailed:N,handOffs:T,dryRun:n,worktrees:le,skipped:l})},nC=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p}=e,m=u?await De(t,"origin/dev"):null,g=await Qf({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(XT(g,s),c)return{...y,selected:n};let b=await QT({entries:g,toPlan:n,all:i,explicit:a!==void 0});b.length===o.length?h.addOption("--all",!0):h.addOption("--versions",b);let w=g.filter(T=>b.includes(T.branch)&&T.mergeSha).length;w>0&&d.info(`
359
- \u2139\uFE0F This will push ${w} branch(es), re-running CI on ${w} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await L(p,`Are you sure you want to merge dev into these branches: ${b.join(", ")}?`,{throwOnDecline:!0,plan:oC(g,b,s)})}catch(T){if(!dt(T))throw T;return{...y,selected:b,declined:!0}}p||h.addOption("--yes",!0);let x=await eC({cwd:t,worktreePath:r.path,entries:g,selected:b,verify:l}),D=g.filter(T=>b.includes(T.branch)&&T.status==="conflict").map(T=>T.branch),N=u&&m&&D.length>0?await bg({cwd:t,branches:D,devSha:m}):void 0;return{entries:g,selected:b,declined:!1,...x,handOffs:N}},oC=(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:pl(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),sC=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
357
+ \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await Os(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Ar(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:u,abortedBy:p.stderr?.split(`
358
+ `)[0],observedLanded:g.map(y=>y.branch)}},iC=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},oy=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
359
+ `)[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=>!lu.has(i.status));return uu({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},aC=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Re();if(e.abort)return oy(await xg({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return oy(await Eg({cwd:s,versions:r,all:t,verify:i,trees:Pg(e.tree),confirmedCommand:o}))},Fi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;iC(e);let a=o===!0?tg:o||void 0;if(await Xc({operation:"merge dev into release branches"}),e.continue||e.abort)return aC(e);let c=[],l=[];for(let J of await F()){let Yt=ZT(J);Yt?l.push({branch:J.branch,reason:Yt}):c.push(J.branch)}if(c.length===0)return d.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${QT(l)})`),h.print(),uu(XT(n,l));let u=await Re();try{await zT({cwd:u,quiet:!0})`git fetch origin --prune`}catch(J){throw new f(J,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:eC(r,c,l),m=await tm({cwd:u},async J=>{let Yt=ci(J.remove);try{return await cC({cwd:u,worktree:J,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{Yt()}}),{entries:g,selected:y,pushed:b,pushAborted:w,abortedBy:x,declined:D,verifyFailed:N,handOffs:T}=m,he=await qe(u).catch(()=>[]);return dC({entries:g,selected:y,pushed:b,pushAborted:w,abortedBy:x,declined:D,verifyFailed:N,handOffs:T,dryRun:n,worktrees:he,skipped:l})},cC=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p}=e,m=u?await De(t,"origin/dev"):null,g=await Qf({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(rC(g,s),c)return{...y,selected:n};let b=await oC({entries:g,toPlan:n,all:i,explicit:a!==void 0});b.length===o.length?h.addOption("--all",!0):h.addOption("--versions",b);let w=g.filter(T=>b.includes(T.branch)&&T.mergeSha).length;w>0&&d.info(`
360
+ \u2139\uFE0F This will push ${w} branch(es), re-running CI on ${w} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await L(p,`Are you sure you want to merge dev into these branches: ${b.join(", ")}?`,{throwOnDecline:!0,plan:lC(g,b,s)})}catch(T){if(!dt(T))throw T;return{...y,selected:b,declined:!0}}p||h.addOption("--yes",!0);let x=await sC({cwd:t,worktreePath:r.path,entries:g,selected:b,verify:l}),D=g.filter(T=>b.includes(T.branch)&&T.status==="conflict").map(T=>T.branch),N=u&&m&&D.length>0?await bg({cwd:t,branches:D,devSha:m}):void 0;return{entries:g,selected:b,declined:!1,...x,handOffs:N}},lC=(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:pl(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),uC=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
360
361
  `:`# ${e.branch} \u2014 ${e.status}
361
- ${ZT(e.branch,t)}
362
- `,iC=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p}=e,m=new Set(n?t.filter(w=>r.includes(w.branch)&&w.mergeSha&&!l?.has(w.branch)).map(w=>w.branch):[]),g=t.filter(w=>r.includes(w.branch)).map(w=>{let x=!!w.mergeSha,D=e.verifyFailed?.get(w.branch),N=o&&x?"push-aborted":w.status,T=D?"verify-failed":N,le=u?.get(w.branch);return{branch:w.branch,status:T,mergeSha:w.mergeSha,conflictPaths:w.conflictPaths,pushed:m.has(w.branch),reason:D??le?.reason??w.reason,...le?.resolution?{resolution:le.resolution}:{}}}),y=g.filter(w=>!lu.has(w.status));for(let w of g){let x=t.find(D=>D.branch===w.branch);d.info({branch:w.branch,status:w.status,mergeSha:w.mergeSha,conflictCount:w.conflictPaths?.length??0,durationMs:x?.durationMs,pushed:w.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
362
+ ${nC(e.branch,t)}
363
+ `,dC=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p}=e,m=new Set(n?t.filter(w=>r.includes(w.branch)&&w.mergeSha&&!l?.has(w.branch)).map(w=>w.branch):[]),g=t.filter(w=>r.includes(w.branch)).map(w=>{let x=!!w.mergeSha,D=l?.has(w.branch)??!1,N=l?.get(w.branch),T=o&&x?"push-aborted":w.status,he=D?"verify-failed":T,J=u?.get(w.branch);return{branch:w.branch,status:he,mergeSha:w.mergeSha,conflictPaths:w.conflictPaths,pushed:m.has(w.branch),reason:N??J?.reason??w.reason,...J?.resolution?{resolution:J.resolution}:{}}}),y=g.filter(w=>!lu.has(w.status));for(let w of g){let x=t.find(D=>D.branch===w.branch);d.info({branch:w.branch,status:w.status,mergeSha:w.mergeSha,conflictCount:w.conflictPaths?.length??0,durationMs:x?.durationMs,pushed:w.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
363
364
  Operation cancelled \u2014 nothing was pushed.
364
365
  `:`
365
366
  \u{1F50D} Dry run \u2014 nothing was pushed.
366
367
  `);else if(y.length>0){d.info(`
367
368
  \u26A0\uFE0F ${y.length} branch(es) did not merge.
368
- `);for(let w of y)d.info(sC(w,c))}else d.info(`\u2705 All merges completed successfully!
369
- `);h.print();let b=a||i;return uu({successfulMerges:b?0:g.filter(w=>lu.has(w.status)).length,failedMerges:b?0:y.length,failedBranches:b?[]:y.map(w=>w.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(w=>b?{...w,pushed:!1}:w),skipped:p})},du=E({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:S.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:S.union([S.string(),S.array(S.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:S.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:S.union([S.boolean(),S.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:S.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:S.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:S.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:S.union([S.string(),S.array(S.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:S.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:S.number().describe("Number of branches that reached their desired state"),failedMerges:S.number().describe("Number of branches that did not"),failedBranches:S.array(S.string()).describe("List of branches that did not merge"),totalBranches:S.number().describe("Total number of branches processed"),dryRun:S.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:S.object({attempted:S.boolean(),aborted:S.boolean(),abortedBy:S.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:S.array(S.object({branch:S.string(),status:S.string(),mergeSha:S.string().optional(),conflictPaths:S.array(S.string()).optional(),pushed:S.boolean(),reason:S.string().optional(),resolution:S.object({worktreePath:S.string(),baseSha:S.string(),devSha:S.string(),conflictPaths:S.array(S.string()),lockfileOnly:S.boolean(),rererePreResolved:S.array(S.string()),state:S.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:S.object({code:S.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:S.array(S.string()).optional(),detail:S.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:S.array(S.object({branch:S.string(),reason:S.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:Fi});import{z as Ho}from"zod";import{$ as Be}from"zx";var iy=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},hr=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=iy(t.stderr,500);o&&(r.stderr=o);let s=iy(t.stdout,200);return s&&(r.stdout=s),r};var Wo=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 Go=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=k(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw ve()?new C({status:"partial_failure",...n},1,s):new f(void 0,s)};import Li from"node:fs/promises";import{$ as mu}from"zx";var aC=new Set([".omc",".DS_Store"]),cC=new Set(["state","sessions"]),lC=2e3,uy="check 'git worktree list' for the path; uncommitted changes block removal",uC=e=>new Promise(t=>{setTimeout(t,e)}),pu=e=>typeof e=="object"&&e!==null?e.code:void 0,ay=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},cy=async e=>{try{return ay(await Li.realpath(e))}catch{return ay(e)}},dC=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await qe(t),o=await cy(r);for(let s of n)if(await cy(s.path)===o)return!0;return!1}catch{return!0}},pC=async e=>{let t;try{t=await Li.readdir(e)}catch(n){return{kind:pu(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>aC.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Li.readdir(`${e}/.omc`)).every(s=>cC.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:pu(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},ly=async e=>{try{return await Li.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return pu(t)==="ENOTEMPTY"?"busy":"failed"}},mC=async e=>{let{worktreePath:t,sleep:r}=e,n=await ly(t);return n!=="busy"?n==="removed":(await r(lC),await ly(t)==="removed")},Jo=(e,t,r)=>{let n=new f(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}},fC=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await dC({projectRoot:n,worktreePath:r}))return Jo(t,o,uy);let i=await pC(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 mC({worktreePath:r,sleep:s})?Jo(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"})},gC=async e=>{try{return(await mu`git -C ${e} status --porcelain`).stdout.split(`
370
- `).filter(r=>r.trim().length>0)}catch{return[]}},hC=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await gC(i);if(a.length>0)return Jo(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),uy);let c=await Tm(i,o);if(!c.closed&&"error"in c)return Jo(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await mu`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return fC({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},yr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=uC}=e,i=t.length>0?await Tt():"unreachable",a=await Promise.all(t.map(l=>hC({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 mu`git worktree prune`,c};var Ko=async(e,t)=>{if(!(await fe("release")).includes(e))return[];let n=await P(),o=`${n}${ue}`,{removed:s,failed:i}=await yr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Rn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:hr(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},yC=async e=>{let t=Ma(e),r=await Be`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},dy=async()=>{let e=await Be`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},vC=async e=>{let t=ht(e),r=await el(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await qr(t);if(!n)throw d.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=mo(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},wC=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await ae(),o=await Nt(ce({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},kC=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=rt(r),s=await tl(n);if(s.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await Rn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin --delete-branch`})},bC=async e=>{let t=Y(e),r=Ma(e),n=await dy();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 Rn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await Be`gh pr edit ${s} --title ${r}`})),s}await Rn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await Be`gh pr create --base main --head dev --title ${r} --body ""`});let o=await dy();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},RC=async e=>{let t=Y(e);if(await yC(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await bC(e);await Rn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin`})},SC=async()=>{Be.quiet=!1,await Rn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await Be`gh workflow run deploy-all.yml --ref main -f environment=prod`}),Be.quiet=!0},EC=async()=>{await Rn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await Be`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},PC=async e=>{try{await $s(e)}catch(t){d.warn({err:hr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await As(e)}catch(t){d.warn({err:hr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},xC=async e=>{let t=await gt();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await nl({versionName:r},t)}catch(r){let n=go(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:hr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Bi=async e=>{let{version:t,confirmedCommand:r}=e;await xe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await vC(t):await wC(),i=K(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=Y(i);if(h.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ve())throw new C({status:"refused",agentMode:_.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await L(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),Be.quiet=!0;let l=`${await P()}${ue}`;await Ko(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await kC({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await RC(i),await SC(),await EC(),await PC(n),Be.quiet=!1,await xC(i),d.info(`Successfully delivered ${n} to production!`),h.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},fu=E({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:Ho.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:Ho.string().describe("The release branch that was delivered"),version:Ho.string().describe("The version that was delivered"),type:Ho.enum(["regular","hotfix"]).describe("Release type"),success:Ho.boolean().describe("Whether the delivery was successful")},handler:Bi});import{z as wt}from"zod";import{$ as Eu}from"zx";import{z as zo}from"zod";import py from"node:fs/promises";import gu from"node:path";var my=".github/workflows",TC=/script_name:\s*(?<service>[a-z0-9-]+)/,CC=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,$C=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,hu=async e=>{let t=gu.resolve(e,my),r;try{r=await py.readdir(t)}catch{return new Map}return fy(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},qo=async(e,t)=>fy(gu.resolve(e,my),[t]),fy=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await py.readFile(gu.resolve(e,n),"utf-8")}catch{continue}AC(o,r)}return r},AC=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=TC.exec(r)?.groups?.service??CC.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll($C)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},yu=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import OC from"node:fs/promises";import IC from"node:path";import DC from"yaml";var NC=".github/workflows",_C="skip_terraform_deploy",Yo=async(e,t)=>{let r=IC.resolve(e,NC,t),n;try{n=DC.parse(await OC.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!==_C).map(([i])=>i)};var gy="dev",vu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hy=(e,t)=>e[t]===void 0,yy=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},wu=async e=>{try{return await e}catch{return[]}},MC=async()=>{let e=await F();return yt(e.map(t=>t.branch))},jC=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},vr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await wu(MC());if(l.length===0)return null;let u=yy(c,"version");return zo.enum([...new Set([...l,gy])]).optional().describe(`Which release to deploy from. "${gy}" 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=Ct(await wu($t(t)),await Ye());if(l.length===0)return null;let u=l.filter(Un),p=l.filter(g=>!Un(g)),m=yy(c,"env");return zo.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await P(),l=await wu(Yo(c,t));if(l.length===0)return null;let u=await qo(c,t);return zo.array(zo.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${jC(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=>vu(c)?r.some(l=>hy(c,l)):!1,buildRequestedSchema:async c=>{let l=vu(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")&&hy(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):zo.object(u)},toArgs:(c,l)=>{let u={...vu(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 FC from"@inquirer/select";var Sn=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return I(r=>FC({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import LC from"@inquirer/confirm";var Xo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;J()&&_s(o,{branch:r,env:n}),h.setInteractive();let s=await I(i=>LC({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import BC from"@inquirer/select";import UC from"node:process";var ku=()=>!J()&&UC.stdin.isTTY===!0,VC={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},bu=async()=>I(e=>BC({message:"\u{1F680} Where should this deploy run?",choices:Ut.filter(t=>t!=="local").map(t=>({name:t,value:t,description:VC[t]}))},e),{whenHeadless:"refuse"});var Ut=["ci","local"],WC={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},vy=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Ut.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw J()?new C({status:"argument_required",argument:"from",agentMode:_.source},2,r):new f(void 0,r)}let t=Ut.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Ut.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Ru=(e,t)=>{let n=WC[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Su=async e=>e||!ku()?vy(e):bu();var Zo=async e=>{if(e)return e==="dev"?"dev":ht(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await ae();return Nt([{value:"dev",label:"dev"},...ce({branches:r,descriptions:o,types:n})])};var wy="deploy-all.yml",ky=vr({workflowFile:wy,fields:["version","env"],toolName:"gh-release-deploy-all"}),Ui=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await ze({provider:ky,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await Zo(t),i=vo(s);h.addOption("--version",i);let a=await Ye(),c=Ct(await $t(wy),a),l="";r?l=r:(h.setInteractive(),l=await Sn(c,"launch deploy-all workflow")),h.addOption("--env",l),Or(l,"launch deploy-all workflow",a),js({env:l,branch:s});let u=n??!1;if(u&&h.addOption("--skip-terraform",!0),!await Xo({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{Eu.quiet=!0,await Eu`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Eu.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Pu=E({name:"gh-release-deploy-all",formProvider:ky,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:wt.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:wt.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:wt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:wt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:wt.string().describe("The release branch that was deployed"),version:wt.string().describe("The version that was deployed"),environment:wt.string().describe("The environment deployed to"),skipTerraformDeploy:wt.boolean().describe("Whether terraform deployment was skipped"),success:wt.boolean().describe("Whether the deployment was successful")},handler:Ui});import GC from"@inquirer/checkbox";import{z as Ce}from"zod";import{$ as xu}from"zx";var wr="deploy-selected-services.yml",by=vr({workflowFile:wr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Vi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await ze({provider:by,params:e,operation:"launch deploy-selected workflow",argument:N=>N[0]??"version"});let i=await Zo(t),a=vo(i);h.addOption("--version",a);let c=await Ye(),l=Ct(await $t(wr),c),u="";r?u=r:(h.setInteractive(),u=await Sn(l,"launch deploy-selected workflow")),h.addOption("--env",u),Or(u,"launch deploy-selected workflow",c),js({env:u,branch:i});let p=await P(),m=await Yo(p,wr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${wr}`,stderrExcerpt:`no services found in .github/workflows/${wr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await I(N=>GC({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(T=>({name:T,value:T}))},N),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(N=>!m.includes(N));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let b=await qo(p,wr),w=g.filter(N=>{let T=b.get(N);return T!==void 0&&!T.includes(u)});if(w.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(N=>`${N} deploys only to: ${(b.get(N)??[]).join(", ")}`).join("; "),stderrExcerpt:`${wr} gates these services out of ${u}: ${w.join(", ")}`});let x=o??!1;x&&h.addOption("--skip-terraform",!0);let D=N=>{let T={releaseBranch:i,version:a,environment:u,services:g,skipTerraformDeploy:x,success:N};return{content:k(JSON.stringify(T,null,2)),structuredContent:T}};if(!await Xo({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),D(!1);try{xu.quiet=!0;let N=g.flatMap(le=>["-f",`${le}=true`]);return await xu`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${N} ${x?["-f","skip_terraform_deploy=true"]:[]}`,xu.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${g.join(", ")}`),h.print(),D(!0)}catch(N){throw d.error({error:N},"\u274C Error launching workflow"),new f(N,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Tu=E({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:by,description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:Ce.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:Ce.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:Ce.array(Ce.string()).optional().describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:Ce.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ce.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was deployed"),version:Ce.string().describe("The version that was deployed"),environment:Ce.string().describe("The environment deployed to"),services:Ce.array(Ce.string()).describe("The services that were deployed"),skipTerraformDeploy:Ce.boolean().describe("Whether terraform deployment was skipped"),success:Ce.boolean().describe("Whether the deployment was successful")},handler:Vi});import{z as Vt}from"zod";var Wi=async()=>{let t=(await F()).flatMap(i=>{let a=K(i.branch);return a?[{version:Y(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await si(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=yo(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:
369
+ `);for(let w of y)d.info(uC(w,c))}else d.info(`\u2705 All merges completed successfully!
370
+ `);h.print();let b=a||i;return uu({successfulMerges:b?0:g.filter(w=>lu.has(w.status)).length,failedMerges:b?0:y.length,failedBranches:b?[]:y.map(w=>w.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(w=>b?{...w,pushed:!1}:w),skipped:p})},du=E({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:S.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:S.union([S.string(),S.array(S.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:S.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:S.union([S.boolean(),S.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:S.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:S.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:S.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:S.union([S.string(),S.array(S.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:S.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:S.number().describe("Number of branches that reached their desired state"),failedMerges:S.number().describe("Number of branches that did not"),failedBranches:S.array(S.string()).describe("List of branches that did not merge"),totalBranches:S.number().describe("Total number of branches processed"),dryRun:S.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:S.object({attempted:S.boolean(),aborted:S.boolean(),abortedBy:S.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:S.array(S.object({branch:S.string(),status:S.string(),mergeSha:S.string().optional(),conflictPaths:S.array(S.string()).optional(),pushed:S.boolean(),reason:S.string().optional(),resolution:S.object({worktreePath:S.string(),baseSha:S.string(),devSha:S.string(),conflictPaths:S.array(S.string()),lockfileOnly:S.boolean(),rererePreResolved:S.array(S.string()),state:S.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:S.object({code:S.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:S.array(S.string()).optional(),detail:S.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:S.array(S.object({branch:S.string(),reason:S.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:Fi});import{z as Ho}from"zod";import{$ as Be}from"zx";var iy=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},yr=e=>{if(e===null||typeof e!="object")return{message:String(e)};let t=e,r={};e instanceof Error?(r.name=e.name,r.message=e.message):typeof t.message=="string"&&(r.message=t.message);let n=t.exitCode;(typeof n=="number"||n===null)&&(r.exitCode=n);let o=iy(t.stderr,500);o&&(r.stderr=o);let s=iy(t.stdout,200);return s&&(r.stdout=s),r};var Wo=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 Go=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=k(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw ve()?new C({status:"partial_failure",...n},1,s):new f(void 0,s)};import Li from"node:fs/promises";import{$ as mu}from"zx";var pC=new Set([".omc",".DS_Store"]),mC=new Set(["state","sessions"]),fC=2e3,uy="check 'git worktree list' for the path; uncommitted changes block removal",gC=e=>new Promise(t=>{setTimeout(t,e)}),pu=e=>typeof e=="object"&&e!==null?e.code:void 0,ay=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},cy=async e=>{try{return ay(await Li.realpath(e))}catch{return ay(e)}},hC=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await qe(t),o=await cy(r);for(let s of n)if(await cy(s.path)===o)return!0;return!1}catch{return!0}},yC=async e=>{let t;try{t=await Li.readdir(e)}catch(n){return{kind:pu(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>pC.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Li.readdir(`${e}/.omc`)).every(s=>mC.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:pu(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},ly=async e=>{try{return await Li.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return pu(t)==="ENOTEMPTY"?"busy":"failed"}},vC=async e=>{let{worktreePath:t,sleep:r}=e,n=await ly(t);return n!=="busy"?n==="removed":(await r(fC),await ly(t)==="removed")},Jo=(e,t,r)=>{let n=new f(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}},wC=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await hC({projectRoot:n,worktreePath:r}))return Jo(t,o,uy);let i=await yC(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 vC({worktreePath:r,sleep:s})?Jo(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"})},kC=async e=>{try{return(await mu`git -C ${e} status --porcelain`).stdout.split(`
371
+ `).filter(r=>r.trim().length>0)}catch{return[]}},bC=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await kC(i);if(a.length>0)return Jo(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),uy);let c=await Tm(i,o);if(!c.closed&&"error"in c)return Jo(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await mu`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return wC({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},vr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=gC}=e,i=t.length>0?await Tt():"unreachable",a=await Promise.all(t.map(l=>bC({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 mu`git worktree prune`,c};var Ko=async(e,t)=>{if(!(await me("release")).includes(e))return[];let n=await P(),o=`${n}${le}`,{removed:s,failed:i}=await vr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Rn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:yr(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},RC=async e=>{let t=Ma(e),r=await Be`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},dy=async()=>{let e=await Be`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},SC=async e=>{let t=ht(e),r=await el(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await qr(t);if(!n)throw d.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=mo(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},EC=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await ae(),o=await _t(ce({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},PC=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=rt(r),s=await tl(n);if(s.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await Rn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin --delete-branch`})},xC=async e=>{let t=z(e),r=Ma(e),n=await dy();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 Rn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await Be`gh pr edit ${s} --title ${r}`})),s}await Rn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await Be`gh pr create --base main --head dev --title ${r} --body ""`});let o=await dy();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},TC=async e=>{let t=z(e);if(await RC(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await xC(e);await Rn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin`})},CC=async()=>{Be.quiet=!1,await Rn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await Be`gh workflow run deploy-all.yml --ref main -f environment=prod`}),Be.quiet=!0},$C=async()=>{await Rn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await Be`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},AC=async e=>{try{await $s(e)}catch(t){d.warn({err:yr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await As(e)}catch(t){d.warn({err:yr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},OC=async e=>{let t=await gt();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await nl({versionName:r},t)}catch(r){let n=go(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:yr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Bi=async e=>{let{version:t,confirmedCommand:r}=e;await xe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await SC(t):await EC(),i=H(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=z(i);if(h.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ve())throw new C({status:"refused",agentMode:_.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await L(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),Be.quiet=!0;let l=`${await P()}${le}`;await Ko(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await PC({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await TC(i),await CC(),await $C(),await AC(n),Be.quiet=!1,await OC(i),d.info(`Successfully delivered ${n} to production!`),h.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},fu=E({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:Ho.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:Ho.string().describe("The release branch that was delivered"),version:Ho.string().describe("The version that was delivered"),type:Ho.enum(["regular","hotfix"]).describe("Release type"),success:Ho.boolean().describe("Whether the delivery was successful")},handler:Bi});import{z as wt}from"zod";import{$ as Eu}from"zx";import{z as zo}from"zod";import py from"node:fs/promises";import gu from"node:path";var my=".github/workflows",IC=/script_name:\s*(?<service>[a-z0-9-]+)/,DC=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,NC=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,hu=async e=>{let t=gu.resolve(e,my),r;try{r=await py.readdir(t)}catch{return new Map}return fy(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},qo=async(e,t)=>fy(gu.resolve(e,my),[t]),fy=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await py.readFile(gu.resolve(e,n),"utf-8")}catch{continue}_C(o,r)}return r},_C=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=IC.exec(r)?.groups?.service??DC.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(NC)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},yu=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import MC from"node:fs/promises";import jC from"node:path";import FC from"yaml";var LC=".github/workflows",BC="skip_terraform_deploy",Yo=async(e,t)=>{let r=jC.resolve(e,LC,t),n;try{n=FC.parse(await MC.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!==BC).map(([i])=>i)};var gy="dev",vu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hy=(e,t)=>e[t]===void 0,yy=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},wu=async e=>{try{return await e}catch{return[]}},UC=async()=>{let e=await F();return yt(e.map(t=>t.branch))},VC=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},wr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await wu(UC());if(l.length===0)return null;let u=yy(c,"version");return zo.enum([...new Set([...l,gy])]).optional().describe(`Which release to deploy from. "${gy}" 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=Ct(await wu($t(t)),await Ye());if(l.length===0)return null;let u=l.filter(Un),p=l.filter(g=>!Un(g)),m=yy(c,"env");return zo.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await P(),l=await wu(Yo(c,t));if(l.length===0)return null;let u=await qo(c,t);return zo.array(zo.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${VC(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=>vu(c)?r.some(l=>hy(c,l)):!1,buildRequestedSchema:async c=>{let l=vu(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")&&hy(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):zo.object(u)},toArgs:(c,l)=>{let u={...vu(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 WC from"@inquirer/select";var Sn=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return I(r=>WC({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import GC from"@inquirer/confirm";var Xo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;K()&&_s(o,{branch:r,env:n}),h.setInteractive();let s=await I(i=>GC({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import JC from"@inquirer/select";import KC from"node:process";var ku=()=>!K()&&KC.stdin.isTTY===!0,HC={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},bu=async()=>I(e=>JC({message:"\u{1F680} Where should this deploy run?",choices:Vt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:HC[t]}))},e),{whenHeadless:"refuse"});var Vt=["ci","local"],qC={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},vy=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Vt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw K()?new C({status:"argument_required",argument:"from",agentMode:_.source},2,r):new f(void 0,r)}let t=Vt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Vt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Ru=(e,t)=>{let n=qC[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Su=async e=>e||!ku()?vy(e):bu();var Zo=async e=>{if(e)return e==="dev"?"dev":ht(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await ae();return _t([{value:"dev",label:"dev"},...ce({branches:r,descriptions:o,types:n})])};var wy="deploy-all.yml",ky=wr({workflowFile:wy,fields:["version","env"],toolName:"gh-release-deploy-all"}),Ui=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await ze({provider:ky,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await Zo(t),i=vo(s);h.addOption("--version",i);let a=await Ye(),c=Ct(await $t(wy),a),l="";r?l=r:(h.setInteractive(),l=await Sn(c,"launch deploy-all workflow")),h.addOption("--env",l),Ir(l,"launch deploy-all workflow",a),js({env:l,branch:s});let u=n??!1;if(u&&h.addOption("--skip-terraform",!0),!await Xo({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{Eu.quiet=!0,await Eu`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Eu.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Pu=E({name:"gh-release-deploy-all",formProvider:ky,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:wt.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:wt.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:wt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:wt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:wt.string().describe("The release branch that was deployed"),version:wt.string().describe("The version that was deployed"),environment:wt.string().describe("The environment deployed to"),skipTerraformDeploy:wt.boolean().describe("Whether terraform deployment was skipped"),success:wt.boolean().describe("Whether the deployment was successful")},handler:Ui});import YC from"@inquirer/checkbox";import{z as Ce}from"zod";import{$ as xu}from"zx";var kr="deploy-selected-services.yml",by=wr({workflowFile:kr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Vi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await ze({provider:by,params:e,operation:"launch deploy-selected workflow",argument:N=>N[0]??"version"});let i=await Zo(t),a=vo(i);h.addOption("--version",a);let c=await Ye(),l=Ct(await $t(kr),c),u="";r?u=r:(h.setInteractive(),u=await Sn(l,"launch deploy-selected workflow")),h.addOption("--env",u),Ir(u,"launch deploy-selected workflow",c),js({env:u,branch:i});let p=await P(),m=await Yo(p,kr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${kr}`,stderrExcerpt:`no services found in .github/workflows/${kr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await I(N=>YC({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(T=>({name:T,value:T}))},N),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(N=>!m.includes(N));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let b=await qo(p,kr),w=g.filter(N=>{let T=b.get(N);return T!==void 0&&!T.includes(u)});if(w.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(N=>`${N} deploys only to: ${(b.get(N)??[]).join(", ")}`).join("; "),stderrExcerpt:`${kr} gates these services out of ${u}: ${w.join(", ")}`});let x=o??!1;x&&h.addOption("--skip-terraform",!0);let D=N=>{let T={releaseBranch:i,version:a,environment:u,services:g,skipTerraformDeploy:x,success:N};return{content:k(JSON.stringify(T,null,2)),structuredContent:T}};if(!await Xo({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),D(!1);try{xu.quiet=!0;let N=g.flatMap(he=>["-f",`${he}=true`]);return await xu`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${N} ${x?["-f","skip_terraform_deploy=true"]:[]}`,xu.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${g.join(", ")}`),h.print(),D(!0)}catch(N){throw d.error({error:N},"\u274C Error launching workflow"),new f(N,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Tu=E({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:by,description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:Ce.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:Ce.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:Ce.array(Ce.string()).optional().describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:Ce.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ce.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was deployed"),version:Ce.string().describe("The version that was deployed"),environment:Ce.string().describe("The environment deployed to"),services:Ce.array(Ce.string()).describe("The services that were deployed"),skipTerraformDeploy:Ce.boolean().describe("Whether terraform deployment was skipped"),success:Ce.boolean().describe("Whether the deployment was successful")},handler:Vi});import{z as Wt}from"zod";var Wi=async()=>{let t=(await F()).flatMap(i=>{let a=H(i.branch);return a?[{version:z(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await si(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=yo(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:
371
372
  `),d.info(`
372
373
  ${o.join(`
373
374
  `)}
374
- `);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Cu=E({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and the associated Jira fix version\u2019s description and planned release date. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:Vt.array(Vt.object({version:Vt.string().describe("Release version"),type:Vt.enum(["regular","hotfix"]).describe("Release type"),description:Vt.string().nullable().describe("Jira version description"),releaseDate:Vt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Vt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Vt.number().describe("Number of release branches")},handler:Wi});import JC from"node:process";var $u=e=>({...e}),Au=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=JC.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},Gi=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(`
375
- `)};import s$ from"@inquirer/checkbox";import i$ from"@inquirer/confirm";import a$ from"@inquirer/select";import{spawn as c$}from"node:child_process";import l$ from"node:process";import{z as q}from"zod";import{$ as es}from"zx";import{$ as Qo}from"zx";var KC=async e=>{let t=Qo.quiet;Qo.quiet=!0;try{let r=`/${e}/environment`,n=await Qo`aws sts get-caller-identity --query Account --output text`,o=await Qo`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Qo.quiet=t}},Ry=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},Sy=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},Ey=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Ou=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Or(t,`deploy to "${t}"`,i),Ey(t,s),Sy({env:t,isShared:n,isClean:o});let a=await KC(r);return Ry(t,a),{identity:a}};import Py from"node:fs/promises";import Ji from"node:path";var HC="devops/scripts",qC=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,YC=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,zC=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,XC=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Iu=async e=>{let t=Ji.resolve(e,HC),r;try{r=await Py.readdir(t)}catch{return[]}let n=await hu(e);return(await Promise.all(r.map(s=>({entry:s,match:qC.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ji.resolve(t,s),c=i?.groups?.service??"",l=QC(await ZC(a));return{name:c,scriptPath:a,allowedEnvs:yu(e$(l),n.get(c)),ssmPrefix:r$(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},ZC=async e=>{try{return await Py.readFile(e,"utf-8")}catch{return""}},QC=e=>e.split(`
376
- `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),e$=e=>{let t=e.reduce((n,{text:o})=>n??YC.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},t$=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},r$=e=>{for(let{line:t,text:r}of e){let n=XC.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=zC.exec(r)?.groups?.arg;if(o!==void 0&&t$(o))return{unparseable:{line:t,text:r.trim()}}}return null},n$=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ji.basename(r.scriptPath)]);return t},o$=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ji.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},xy=e=>{o$(e);let t=n$(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},Ki=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Du=(e,t)=>e.filter(r=>Ki(r,t));var _u="deploy-all.yml",Cy="/bin/sh",u$=async()=>{let e=es.quiet;es.quiet=!0;try{let t=await es`gh run list --workflow=${_u} --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}},d$=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await I(o=>s$({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},p$=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return J()&&_s(i,{env:t,services:n,accountId:o,shared:r}),r?I(a=>a$({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):I(a=>i$({message:i,default:!1},a),{whenHeadless:"refuse"})},m$=(e,t,r)=>new Promise((n,o)=>{let s=c$(Cy,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),f$=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 m$(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}},g$=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!Ki(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},Nu=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:$u(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},h$=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(),d$(r,o))},$y=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await P(),c=await Iu(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=xy(c);await ze({provider:Mu[t],params:e,operation:"deploy locally",argument:"env"});let u=await Ye(),p=Ct(await $t(_u),u),m=r??"";m||(h.setInteractive(),m=await Sn(p,"deploy locally")),h.addOption("--env",m);let g=Du(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await h$({selection:t,eligible:g,service:n,env:m}),b=g$({names:y,services:c,env:m});if(t==="selected")for(let Ia of y)h.addOption("--service",Ia);let w=Un(m),x=await Cr(),D=(await es`git rev-parse HEAD`.quiet()).stdout.trim(),N=await Yp(),T=Au({env:m,branch:x,sha:D,isClean:N});i&&d.info(`Deploy contract for ${m}:
377
- ${Gi(T)}`);let re=(await Ou({env:m,project:l,isShared:w,isClean:N,runningEnvs:await u$(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${re}) from this machine`,`Preflight parameter: /${l}/environment`,Gi(T),"Commands:",...b.map(Ia=>` ${Cy} ${Ia.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
378
- `)),Nu({env:m,accountId:re,names:y,built:T,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await p$({env:m,isShared:w,names:y,accountId:re}))return d.info("Deployment cancelled"),Nu({env:m,accountId:re,names:y,built:T,deployed:[],failed:[],dryRun:!1,success:!1});T.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${T.stripped.join(", ")}`);let{deployed:qt,failed:hs}=await f$({chosen:b,childEnv:T.childEnv,cwd:a,env:m});return hs.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${qt.join(", ")||"none"}], failed [${hs.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),l$.exitCode=1),h.print(),Nu({env:m,accountId:re,names:y,built:T,deployed:qt,failed:hs,dryRun:!1,success:hs.length===0})},Ay=async e=>$y(e,"all"),Oy=async e=>$y(e,"selected"),Iy='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.',Dy={env:q.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:q.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:q.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Ny={environment:q.string().describe("Environment deployed to"),accountId:q.string().describe("AWS account the deploy targeted"),services:q.array(q.string()).describe("Services requested"),deployed:q.array(q.string()).describe("Services that completed successfully"),failed:q.array(q.string()).describe("Services that failed"),contract:q.record(q.string(),q.string()).describe("Build contract passed to the scripts"),strippedVars:q.array(q.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:q.boolean().describe("Whether this was a dry run"),success:q.boolean().describe("Whether every requested service deployed")},Ty=e=>vr({workflowFile:_u,fields:["env"],toolName:e}),Mu={all:Ty("local-deploy-all"),selected:Ty("local-deploy-selected")},ju=E({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Iy}`,requiresHumanConfirm:!0,formProvider:Mu.all,inputSchema:Dy,outputSchema:Ny,handler:Ay}),Fu=E({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Iy}`,requiresHumanConfirm:!0,formProvider:Mu.selected,inputSchema:{...Dy,service:q.array(q.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Ny,handler:Oy});import w$ from"@inquirer/confirm";import Hi from"@inquirer/input";import Fy from"@inquirer/select";import Bu from"node:process";import{z as V}from"zod";import{z as ts}from"zod";var En=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var jy=2500,_y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),My=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,y$=async()=>{let e=await No();return{regular:kn(e,"regular"),hotfix:kn(e,"hotfix")}},v$=(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).`,Lu=(e={})=>{let t=e.hintBudgetMs??jy;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=>_y(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await En(y$(),t);return ts.object({type:ts.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:ts.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign" \u2014 no "@" here, the date has its own field. ${v$(r,t)}`),description:ts.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:ts.string().optional().describe("Optional. Planned production date, yyyy-mm-dd. Becomes the Jira fix version's release date; delivery overwrites it with the actual date. On the re-run it is passed as <token>@yyyy-mm-dd inside -r.")})},toArgs:(r,n)=>{let o=typeof r.release=="string"?r.release.trim():"";if(o==="")return null;let s=r.type==="hotfix"?"hotfix":"regular",i=My(r.description),a=My(r.releaseDate),c=Ci(o);return{..._y(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var k$='"1.2.5" or "next"',Uu=(e,t)=>{try{return Vl(e,t)}catch(r){throw r instanceof dr?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof Jp?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},b$=async(e,t)=>{let r=kn(e,t),n=r?` [${r}]`:"",o=(await I(i=>Hi({message:` Version (e.g. ${k$})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Bu.exit(1)),s},R$=async()=>{let e=(await I(t=>Hi({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Bu.exit(1));try{Cs(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Bu.exit(1)}return e},S$=async()=>(await I(e=>Hi({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Do},e),{whenHeadless:"refuse"})).trim(),E$=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await I(m=>Fy({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await I(m=>Fy({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 R$();l=Uu([{name:m,type:c}],[])[0]}else{let m=await b$(await n(),c);l=Uu([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Ft(`v${l.id.raw}`))}let u=(await I(m=>Hi({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await S$();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await I(m=>w$({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},P$=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 ")},Ly=e=>{for(let t of e)h.addOption("--release",Ul(t))},x$=async(e,t)=>{if(e&&e.length>0){let n=Wl(e)?await t():[],o=Uu(e,n);return Ly(o),o}if(ve())throw new C({status:"argument_required",argument:"release",agentMode:_.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await E$(t);return Ly(r),r},T$=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},C$=async(e,t)=>{let r=e.map(P$).join(`
375
+ `);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Cu=E({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and the associated Jira fix version\u2019s description and planned release date. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:Wt.array(Wt.object({version:Wt.string().describe("Release version"),type:Wt.enum(["regular","hotfix"]).describe("Release type"),description:Wt.string().nullable().describe("Jira version description"),releaseDate:Wt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Wt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Wt.number().describe("Number of release branches")},handler:Wi});import zC from"node:process";var $u=e=>({...e}),Au=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=zC.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},Gi=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(`
376
+ `)};import u$ from"@inquirer/checkbox";import d$ from"@inquirer/confirm";import p$ from"@inquirer/select";import{spawn as m$}from"node:child_process";import f$ from"node:process";import{z as Y}from"zod";import{$ as es}from"zx";import{$ as Qo}from"zx";var XC=async e=>{let t=Qo.quiet;Qo.quiet=!0;try{let r=`/${e}/environment`,n=await Qo`aws sts get-caller-identity --query Account --output text`,o=await Qo`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Qo.quiet=t}},Ry=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},Sy=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},Ey=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Ou=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Ir(t,`deploy to "${t}"`,i),Ey(t,s),Sy({env:t,isShared:n,isClean:o});let a=await XC(r);return Ry(t,a),{identity:a}};import Py from"node:fs/promises";import Ji from"node:path";var ZC="devops/scripts",QC=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,e$=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,t$=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,r$=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Iu=async e=>{let t=Ji.resolve(e,ZC),r;try{r=await Py.readdir(t)}catch{return[]}let n=await hu(e);return(await Promise.all(r.map(s=>({entry:s,match:QC.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ji.resolve(t,s),c=i?.groups?.service??"",l=o$(await n$(a));return{name:c,scriptPath:a,allowedEnvs:yu(s$(l),n.get(c)),ssmPrefix:a$(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},n$=async e=>{try{return await Py.readFile(e,"utf-8")}catch{return""}},o$=e=>e.split(`
377
+ `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),s$=e=>{let t=e.reduce((n,{text:o})=>n??e$.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},i$=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},a$=e=>{for(let{line:t,text:r}of e){let n=r$.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=t$.exec(r)?.groups?.arg;if(o!==void 0&&i$(o))return{unparseable:{line:t,text:r.trim()}}}return null},c$=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ji.basename(r.scriptPath)]);return t},l$=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ji.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},xy=e=>{l$(e);let t=c$(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},Ki=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Du=(e,t)=>e.filter(r=>Ki(r,t));var _u="deploy-all.yml",Cy="/bin/sh",g$=async()=>{let e=es.quiet;es.quiet=!0;try{let t=await es`gh run list --workflow=${_u} --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}},h$=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await I(o=>u$({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},y$=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return K()&&_s(i,{env:t,services:n,accountId:o,shared:r}),r?I(a=>p$({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):I(a=>d$({message:i,default:!1},a),{whenHeadless:"refuse"})},v$=(e,t,r)=>new Promise((n,o)=>{let s=m$(Cy,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),w$=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 v$(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}},k$=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!Ki(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},Nu=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:$u(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},b$=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(),h$(r,o))},$y=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await P(),c=await Iu(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=xy(c);await ze({provider:Mu[t],params:e,operation:"deploy locally",argument:"env"});let u=await Ye(),p=Ct(await $t(_u),u),m=r??"";m||(h.setInteractive(),m=await Sn(p,"deploy locally")),h.addOption("--env",m);let g=Du(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await b$({selection:t,eligible:g,service:n,env:m}),b=k$({names:y,services:c,env:m});if(t==="selected")for(let Ia of y)h.addOption("--service",Ia);let w=Un(m),x=await $r(),D=(await es`git rev-parse HEAD`.quiet()).stdout.trim(),N=await Yp(),T=Au({env:m,branch:x,sha:D,isClean:N});i&&d.info(`Deploy contract for ${m}:
378
+ ${Gi(T)}`);let J=(await Ou({env:m,project:l,isShared:w,isClean:N,runningEnvs:await g$(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${J}) from this machine`,`Preflight parameter: /${l}/environment`,Gi(T),"Commands:",...b.map(Ia=>` ${Cy} ${Ia.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
379
+ `)),Nu({env:m,accountId:J,names:y,built:T,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await y$({env:m,isShared:w,names:y,accountId:J}))return d.info("Deployment cancelled"),Nu({env:m,accountId:J,names:y,built:T,deployed:[],failed:[],dryRun:!1,success:!1});T.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${T.stripped.join(", ")}`);let{deployed:Yt,failed:hs}=await w$({chosen:b,childEnv:T.childEnv,cwd:a,env:m});return hs.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${Yt.join(", ")||"none"}], failed [${hs.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),f$.exitCode=1),h.print(),Nu({env:m,accountId:J,names:y,built:T,deployed:Yt,failed:hs,dryRun:!1,success:hs.length===0})},Ay=async e=>$y(e,"all"),Oy=async e=>$y(e,"selected"),Iy='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.',Dy={env:Y.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:Y.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:Y.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Ny={environment:Y.string().describe("Environment deployed to"),accountId:Y.string().describe("AWS account the deploy targeted"),services:Y.array(Y.string()).describe("Services requested"),deployed:Y.array(Y.string()).describe("Services that completed successfully"),failed:Y.array(Y.string()).describe("Services that failed"),contract:Y.record(Y.string(),Y.string()).describe("Build contract passed to the scripts"),strippedVars:Y.array(Y.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:Y.boolean().describe("Whether this was a dry run"),success:Y.boolean().describe("Whether every requested service deployed")},Ty=e=>wr({workflowFile:_u,fields:["env"],toolName:e}),Mu={all:Ty("local-deploy-all"),selected:Ty("local-deploy-selected")},ju=E({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Iy}`,requiresHumanConfirm:!0,formProvider:Mu.all,inputSchema:Dy,outputSchema:Ny,handler:Ay}),Fu=E({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Iy}`,requiresHumanConfirm:!0,formProvider:Mu.selected,inputSchema:{...Dy,service:Y.array(Y.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Ny,handler:Oy});import E$ from"@inquirer/confirm";import Hi from"@inquirer/input";import Fy from"@inquirer/select";import Bu from"node:process";import{z as V}from"zod";import{z as ts}from"zod";var En=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var jy=2500,_y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),My=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,R$=async()=>{let e=await No();return{regular:kn(e,"regular"),hotfix:kn(e,"hotfix")}},S$=(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).`,Lu=(e={})=>{let t=e.hintBudgetMs??jy;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=>_y(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await En(R$(),t);return ts.object({type:ts.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:ts.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign" \u2014 no "@" here, the date has its own field. ${S$(r,t)}`),description:ts.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:ts.string().optional().describe("Optional. Planned production date, yyyy-mm-dd. Becomes the Jira fix version's release date; delivery overwrites it with the actual date. On the re-run it is passed as <token>@yyyy-mm-dd inside -r.")})},toArgs:(r,n)=>{let o=typeof r.release=="string"?r.release.trim():"";if(o==="")return null;let s=r.type==="hotfix"?"hotfix":"regular",i=My(r.description),a=My(r.releaseDate),c=Ci(o);return{..._y(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var P$='"1.2.5" or "next"',Uu=(e,t)=>{try{return Vl(e,t)}catch(r){throw r instanceof pr?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof Jp?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},x$=async(e,t)=>{let r=kn(e,t),n=r?` [${r}]`:"",o=(await I(i=>Hi({message:` Version (e.g. ${P$})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Bu.exit(1)),s},T$=async()=>{let e=(await I(t=>Hi({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Bu.exit(1));try{Cs(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Bu.exit(1)}return e},C$=async()=>(await I(e=>Hi({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Do},e),{whenHeadless:"refuse"})).trim(),$$=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await I(m=>Fy({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await I(m=>Fy({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 T$();l=Uu([{name:m,type:c}],[])[0]}else{let m=await x$(await n(),c);l=Uu([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Lt(`v${l.id.raw}`))}let u=(await I(m=>Hi({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await C$();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await I(m=>E$({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},A$=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 ")},Ly=e=>{for(let t of e)h.addOption("--release",Ul(t))},O$=async(e,t)=>{if(e&&e.length>0){let n=Wl(e)?await t():[],o=Uu(e,n);return Ly(o),o}if(ve())throw new C({status:"argument_required",argument:"release",agentMode:_.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await $$(t);return Ly(r),r},I$=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},D$=async(e,t)=>{let r=e.map(A$).join(`
379
380
  - `);await L(t,`Create the following ${e.length} release(s)?
380
381
  - ${r}
381
- `),h.addOption("--yes",!0)},$$=async e=>{let{entry:t,jiraConfig:r}=e,n=Y(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Kr({operation:`create release ${o}`});let s=await sl(t.type),i=await il({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}
382
+ `),h.addOption("--yes",!0)},N$=async e=>{let{entry:t,jiraConfig:r}=e,n=z(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Kr({operation:`create release ${o}`});let s=await sl(t.type),i=await il({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}
382
383
  `),{result:i}}catch(s){let i=go(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return d.error(`\u274C ${a.message}
383
- `),{failure:{version:n,error:a.message}}}},A$=(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.`)},By=Lu(),qi=async e=>{let{releases:t,confirmedCommand:r}=e;await xe({operation:"create release"}),await ze({provider:By,params:e,operation:"create release",argument:"release"});let n=await Qr(),o=null,i=await x$(t,async()=>(o===null&&(o=await No()),o));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});T$(i),await lo({operation:"create release",base:rt(i[0].type)}),await C$(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await $$({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}A$(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Vu=E({name:"release-create",requiresHumanConfirm:!0,formProvider:By,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:V.array(V.object({version:V.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:V.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:V.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:V.string().optional().describe("Optional description for the Jira version."),releaseDate:Nl.optional().describe('Optional planned production date, yyyy-mm-dd. Written to the Jira fix version as its release date; "release deliver" overwrites it with the actual date. Rides in the CLI spec as "<token>@yyyy-mm-dd".')}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>{let t={...e.description?{description:e.description}:{},...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}};return e.name!==void 0?{name:e.name,type:e.type,...t}:{version:e.version,type:e.type,...t}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description. Optional over MCP: omit it to have the human fill one release from a form.').optional(),confirm:V.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:V.array(V.string()).describe("List of created release branch names"),successCount:V.number().describe("Number of releases created successfully"),failureCount:V.number().describe("Number of releases that failed"),releases:V.array(V.object({version:V.string().describe("Version number"),type:V.enum(["regular","hotfix"]).describe("Release type"),branchName:V.string().describe("Release branch name"),prUrl:V.string().describe("GitHub PR URL"),jiraVersionUrl:V.string().describe("Jira version URL"),releaseDate:V.string().nullable().describe("The release date the Jira fix version now carries (yyyy-mm-dd), or null when it has none")})).describe("Detailed information for each created release with URLs"),failedReleases:V.array(V.object({version:V.string().describe("Version number that failed"),error:V.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:qi});import Uy from"@inquirer/input";import{z as Ue}from"zod";var Vy=["description","releaseDate"],O$=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await ae(),o=await Nt(ce({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},I$=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},D$=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await I(o=>Uy({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},N$=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await I(o=>Uy({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Do},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:ur(n)},_$=e=>{if(e!==void 0)return e===""?null:e},M$=async e=>(h.setInteractive(),{description:await D$(e.description),releaseDate:await N$(e.releaseDate)}),Wu=e=>e??"(none)",j$=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Wu(t.releaseDate)} \u2192 ${Wu(r.releaseDate)}`,Yi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=_$(n),i=await Qr(),a;t?(a=ht(t),await I$(a)):(h.setInteractive(),a=(await O$()).branch);let c=K(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=Y(c);h.addOption("--version",l);let u=ne(c),p=await ft(u,i);if(!p)throw new f(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},g=r!==void 0||s!==void 0;if(!g&&J())throw new C({status:"argument_required",argument:"description",agentMode:_.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await M$(m),b=Vy.filter(le=>y[le]!==m[le]),w=b.includes("description"),x=b.includes("releaseDate"),D=ir(i,p),N=le=>{let re={version:l,branch:a,jiraVersionUrl:D,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:b,changed:le};return{content:k(JSON.stringify(re,null,2)),structuredContent:re}};if(b.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${Wu(m.releaseDate)}`),h.print(),N(!1);w&&h.addOption("--description",y.description),x&&h.addOption("--release-date",y.releaseDate??"");let T=b.map(le=>j$(le,m,y));return await L(o,`Update ${u}?
384
+ `),{failure:{version:n,error:a.message}}}},_$=(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.`)},By=Lu(),qi=async e=>{let{releases:t,confirmedCommand:r}=e;await xe({operation:"create release"}),await ze({provider:By,params:e,operation:"create release",argument:"release"});let n=await Qr(),o=null,i=await O$(t,async()=>(o===null&&(o=await No()),o));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});I$(i),await lo({operation:"create release",base:rt(i[0].type)}),await D$(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await N$({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}_$(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Vu=E({name:"release-create",requiresHumanConfirm:!0,formProvider:By,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:V.array(V.object({version:V.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:V.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:V.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:V.string().optional().describe("Optional description for the Jira version."),releaseDate:Nl.optional().describe('Optional planned production date, yyyy-mm-dd. Written to the Jira fix version as its release date; "release deliver" overwrites it with the actual date. Rides in the CLI spec as "<token>@yyyy-mm-dd".')}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>{let t={...e.description?{description:e.description}:{},...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}};return e.name!==void 0?{name:e.name,type:e.type,...t}:{version:e.version,type:e.type,...t}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description. Optional over MCP: omit it to have the human fill one release from a form.').optional(),confirm:V.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:V.array(V.string()).describe("List of created release branch names"),successCount:V.number().describe("Number of releases created successfully"),failureCount:V.number().describe("Number of releases that failed"),releases:V.array(V.object({version:V.string().describe("Version number"),type:V.enum(["regular","hotfix"]).describe("Release type"),branchName:V.string().describe("Release branch name"),prUrl:V.string().describe("GitHub PR URL"),jiraVersionUrl:V.string().describe("Jira version URL"),releaseDate:V.string().nullable().describe("The release date the Jira fix version now carries (yyyy-mm-dd), or null when it has none")})).describe("Detailed information for each created release with URLs"),failedReleases:V.array(V.object({version:V.string().describe("Version number that failed"),error:V.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:qi});import Uy from"@inquirer/input";import{z as Ue}from"zod";var Vy=["description","releaseDate"],M$=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await ae(),o=await _t(ce({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},j$=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},F$=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await I(o=>Uy({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},L$=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await I(o=>Uy({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Do},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:dr(n)},B$=e=>{if(e!==void 0)return e===""?null:e},U$=async e=>(h.setInteractive(),{description:await F$(e.description),releaseDate:await L$(e.releaseDate)}),Wu=e=>e??"(none)",V$=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Wu(t.releaseDate)} \u2192 ${Wu(r.releaseDate)}`,Yi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=B$(n),i=await Qr(),a;t?(a=ht(t),await j$(a)):(h.setInteractive(),a=(await M$()).branch);let c=H(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=z(c);h.addOption("--version",l);let u=ne(c),p=await ft(u,i);if(!p)throw new f(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},g=r!==void 0||s!==void 0;if(!g&&K())throw new C({status:"argument_required",argument:"description",agentMode:_.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await U$(m),b=Vy.filter(he=>y[he]!==m[he]),w=b.includes("description"),x=b.includes("releaseDate"),D=ar(i,p),N=he=>{let J={version:l,branch:a,jiraVersionUrl:D,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:b,changed:he};return{content:k(JSON.stringify(J,null,2)),structuredContent:J}};if(b.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${Wu(m.releaseDate)}`),h.print(),N(!1);w&&h.addOption("--description",y.description),x&&h.addOption("--release-date",y.releaseDate??"");let T=b.map(he=>V$(he,m,y));return await L(o,`Update ${u}?
384
385
  ${T.join(`
385
386
  `)}
386
387
  `),h.addOption("--yes",!0),await Zr({versionId:p.id,...w?{description:y.description}:{},...x?{releaseDate:y.releaseDate}:{}},i),w&&await ri({branch:a,body:fo(D,y.description)}),d.info(`\u2705 Updated ${b.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${D}`),d.info(`\u{1F517} PR branch: ${a}
387
- `),h.print(),N(!0)},Gu=E({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Ue.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ue.string().optional().describe("New description. Empty string clears the description."),releaseDate:_l.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ue.string().describe("Release version"),branch:Ue.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ue.string().describe("Jira fix version URL"),previousDescription:Ue.string().describe("The description before the update"),newDescription:Ue.string().describe("The description after the update"),previousReleaseDate:Ue.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ue.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ue.array(Ue.enum(Vy)).describe("The fields whose value actually changed"),changed:Ue.boolean().describe("Whether anything actually changed")},handler:Yi});import{z as te}from"zod";import{$ as Ku}from"zx";import{z as Wy}from"zod";var Ky=2500,zi="release-remove",Gy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),F$=e=>e.version===void 0||e.version==="",L$=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===po?{outcome:"empty"}:{outcome:"failed"}}},Jy=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${zi}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${zi}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${zi}`}),null),B$=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return ii(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ne(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},U$=(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): ${zi}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Ju=(e={})=>{let t=e.fetchBudgetMs??Ky;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=>Gy(r)&&F$(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([En(L$(),t),En(ae(),t)]);if(r===null||r.outcome!=="listed")return Jy(r,t);let o=B$(r.prs,n);return o.length===0?Jy({outcome:"empty"},t):Wy.object({version:Wy.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${U$(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:{...Gy(n)?n:{},version:r.version}}};var Hy=["worktree","pr","local-branch","remote-branch","jira"],zy={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"},kr="remove a release",Ke=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},qy=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new C({...e,agentMode:_.source},2,t)},V$=e=>{ve()&&(e.version||qy({status:"argument_required",argument:"version"},{operation:kr,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&&qy({status:"refused"},{operation:kr,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"}))},Xy=e=>{e.pr?.state==="MERGED"&&Ke({operation:`remove release ${e.label}`,remediation:`this release has shipped \u2014 removing it would delete the branch recording the merge and strip its Jira fix version from delivered work. To undo a delivery, revert the merge commit on ${e.baseBranch} and cut a new release.`,stderrExcerpt:`PR #${e.pr.number} for ${e.branch} is MERGED`})},W$=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ke({operation:`remove release ${e.label}`,remediation:"set JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL, or pass --skip-jira to tear down the branch and PR and leave any fix version alone",stderrExcerpt:"Jira is not configured, so a fix version for this release cannot be checked or removed"}),!e.jira))return;let{version:r,fixCount:n,affectsCount:o}=e.jira;(r.released||r.archived)&&Ke({operation:`remove Jira fix version "${r.name}"`,remediation:"un-release it in Jira first, or remove the release without it via --skip-jira",stderrExcerpt:`fix version "${r.name}" is already ${r.released?"released":"archived"}`}),!(n===0&&o===0)&&(e.moveIssuesTo||Ke({operation:`remove Jira fix version "${r.name}"`,remediation:"deleting it would clear both fields on those issues with no way to restore them \u2014 pass --move-issues-to <version> to reassign both, or clear the version from the issues in Jira first",stderrExcerpt:`${r.name} is set as fixVersion on ${n} issue(s) and as affectsVersion on ${o} issue(s)`}))},G$=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ke({operation:`remove release ${e.label}`,remediation:`nothing named "${e.label}" exists to remove \u2014 check the spelling against \`infra-kit release list\`. (A release this command already removed keeps a CLOSED PR, so a genuine re-run is not affected.)`,stderrExcerpt:"found no worktree, no PR (any state), no local or remote branch, and no Jira fix version"})},J$=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ke({operation:`remove release ${e.label}`,remediation:`commit or discard those changes (\`git -C ${e.worktreePath} stash -u\`), then re-run`,stderrExcerpt:`the worktree at ${e.worktreePath} has uncommitted changes: ${e.worktreeDirty.slice(0,4).join(", ")}`})},K$=async e=>(await Ku`git -C ${e} status --porcelain`).stdout.split(`
388
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),H$=async e=>{try{let{terminals:t}=await xm(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},q$=async e=>{let t=await Ms([e]);if(t!==null)throw d.warn({operation:kr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:kr,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`})},Y$=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await gt();if(!n)return r;let o=await ft(ne(e),n),s=t.moveIssuesTo?await z$(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await oi(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:ir(n,o)}}},z$=async(e,t)=>{let r=await ft(e,t);return r||Ke({operation:`reassign issues to Jira fix version "${e}"`,remediation:'name an existing fix version exactly as it appears in Jira (e.g. "v1.2.6")',stderrExcerpt:`no Jira fix version named "${e}"`})},X$=async(e,t)=>{let r=K(e);r||Ke({operation:`remove release ${e}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:`"${e}" is not a release branch`});let n=await P(),s=`${`${n}${ue}`}/${e}`,[i,a,c,l]=await Promise.all([fe("release"),qr(e),De(n,`refs/heads/${e}`),$r(n,e)]),u=i.includes(e);return u&&await q$(s),{...await Y$(r,t),branch:e,id:r,label:Y(r),baseBranch:a?.baseRefName??rt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await H$(s):0,worktreeDirty:u?await K$(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Yy=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}),Z$=(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}`},Q$=(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: ${Z$(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
389
- `)},Xi=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},eA=e=>typeof e=="string"?e:e.outcome;async function rs(e,t,r){try{let n=await r(),o=eA(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${zy[e]} \u2014 ${o}`),n}catch(n){throw new Xi(e,n)}}var tA=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,rA=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>tA(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 f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Hy.indexOf(r)+1} of ${Hy.length} (${zy[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},nA=async e=>(await Ko(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",oA=async e=>{let t=await qr(e.branch);if(Xy({...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 Ku`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},sA=async e=>(await Cr()===e.branch&&await Ku`git switch ${e.baseBranch}`,await $s(e.branch),await Xp(e.branch)?Ke({operation:`delete local branch ${e.branch}`,remediation:`delete it by hand with \`git branch -D ${e.branch}\`, then re-run to finish the removal`,stderrExcerpt:`${e.branch} still exists after the delete`}):e.localTipSha?"deleted":"absent"),iA=async e=>(await As(e.branch),e.remoteTipSha?"deleted":"absent"),aA=async(e,t,r)=>{let n=await oi(t.version.id,r);if(n.issuesFixedCount===t.fixCount&&n.issuesAffectedCount===t.affectsCount)return;let o=`re-run \`infra-kit release remove --version ${e.label}\``;Ke({operation:`remove Jira fix version "${t.version.name}"`,remediation:`the fix version was NOT removed and every other step is complete \u2014 ${o} so the guard re-evaluates the new counts`,stderrExcerpt:`issue counts changed since preflight: fixVersion ${t.fixCount} \u2192 ${n.issuesFixedCount}, affectsVersion ${t.affectsCount} \u2192 ${n.issuesAffectedCount}`})},cA=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await aA(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 ol({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),lA=(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}),uA=async(e,t,r)=>{let n=await rs("worktree",r,()=>nA(e)),o=await rs("pr",r,()=>oA(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,()=>sA(e)),i=await rs("remote-branch",r,()=>iA(e)),a=await rs("jira",r,()=>cA(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},dA=async(e,t)=>{let r=[];try{return lA(e,await uA(e,t,r))}catch(n){throw n instanceof Xi?rA({plan:e,step:n.step,done:r,cause:n.reason}):n}},pA=async e=>{if(e)return ht(e);h.setInteractive();let[t,r]=await Promise.all([ae(),F()]),n=r.map(s=>s.branch);n.length===0&&Ke({operation:"select a release to remove",remediation:"pass `--version <ref>` to remove a release that is already partially torn down",stderrExcerpt:"no open release PRs to pick from"});let o=new Map(r.map(s=>[s.branch,s.type]));try{return await Nt(ce({branches:n,descriptions:t,types:o}))}catch(s){throw Se(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},Zy=Ju(),Zi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await xe({operation:kr}),await W(),await ze({provider:Zy,params:e,operation:kr,argument:"version"}),V$(e);try{let s=await X$(await pA(r),e);d.debug({plan:Yy(s)},"release remove: resolved plan"),Xy(s),W$(s,e),G$(s),await lo({operation:`remove release ${s.label}`,base:s.baseBranch}),J$(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await L(t,Q$(s,!!o),{throwOnDecline:!0,plan:{...Yy(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await dA(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Se(s)||dt(s)||s instanceof f?s:(d.error({err:hr(s)},"\u274C Error removing release"),new f(s,{operation:kr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Hu=E({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:Zy,inputSchema:{version:te.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:te.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:te.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:te.string().describe("The release branch that was targeted"),version:te.string().describe('The release label (e.g. "1.2.5")'),baseBranch:te.string().describe("The branch HEAD was moved to before the local delete"),worktree:te.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:te.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:te.number().nullable().describe("The pull request number, or null when none exists"),localBranch:te.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:te.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:te.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:te.string().nullable().describe("The origin tip before deletion"),jira:te.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:te.object({id:te.string(),name:te.string(),url:te.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Zi});import{spawn as hA}from"node:child_process";import yA from"node:fs";import{homedir as vA}from"node:os";import ea from"node:process";import Qi from"node:fs";import Pn from"node:path";var mA=e=>{try{return Qi.statSync(e).isFile()?Qi.readFileSync(e,"utf8"):null}catch{return null}},fA=e=>{try{return Qi.realpathSync(e)}catch{return e}},gA=(e,t)=>{let o=t(Pn.join(e,".git"))?.split(`
390
- `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=Pn.resolve(e,o),i=`${Pn.sep}.git${Pn.sep}worktrees${Pn.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},Qy=(e={})=>{let t=e.listInstallations??Va,r=e.exists??Qi.existsSync,n=e.readGitFile??mA,o=e.realpath??fA,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=gA(i.projectPath,n);if(!r(Pn.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var wA=180*1e3,kA=900*1e3,bA=4*1024*1024,RA=2e3,SA=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=hA(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&&ea.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<bA&&(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)},RA).unref()})}),EA=({cwd:e,timeoutMs:t})=>SA({command:ea.execPath,args:[ea.argv[1]??"","setup","--unattended","--json"],cwd:e,env:km(ea.env),timeoutMs:t}),PA=e=>{yA.writeFileSync(an(),e,{mode:384})},xA=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}},TA=new RegExp("\x1B\\[[0-9;]*m","g"),CA=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(TA,"").split(`
391
- `).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},$A=(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}},ev=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":bi(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(wA,o)}),a=i.error===null?xA(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${CA(i)} \u2014 run: ${s}`]}:{root:e,...$A(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},AA=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}})},OA=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(`
388
+ `),h.print(),N(!0)},Gu=E({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Ue.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ue.string().optional().describe("New description. Empty string clears the description."),releaseDate:_l.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ue.string().describe("Release version"),branch:Ue.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ue.string().describe("Jira fix version URL"),previousDescription:Ue.string().describe("The description before the update"),newDescription:Ue.string().describe("The description after the update"),previousReleaseDate:Ue.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ue.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ue.array(Ue.enum(Vy)).describe("The fields whose value actually changed"),changed:Ue.boolean().describe("Whether anything actually changed")},handler:Yi});import{z as re}from"zod";import{$ as Ku}from"zx";import{z as Wy}from"zod";var Ky=2500,zi="release-remove",Gy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),W$=e=>e.version===void 0||e.version==="",G$=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===po?{outcome:"empty"}:{outcome:"failed"}}},Jy=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${zi}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${zi}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${zi}`}),null),J$=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return ii(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ne(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},K$=(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): ${zi}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Ju=(e={})=>{let t=e.fetchBudgetMs??Ky;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=>Gy(r)&&W$(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([En(G$(),t),En(ae(),t)]);if(r===null||r.outcome!=="listed")return Jy(r,t);let o=J$(r.prs,n);return o.length===0?Jy({outcome:"empty"},t):Wy.object({version:Wy.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${K$(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:{...Gy(n)?n:{},version:r.version}}};var Hy=["worktree","pr","local-branch","remote-branch","jira"],zy={worktree:"remove the worktree",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},br="remove a release",Ke=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},qy=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new C({...e,agentMode:_.source},2,t)},H$=e=>{ve()&&(e.version||qy({status:"argument_required",argument:"version"},{operation:br,remediation:"pass --version <ref> (a release version or name) on the re-run \u2014 `infra-kit release list --json` lists the candidates",stderrExcerpt:"release remove reached the handler without --version under agent mode"}),e.skipJira&&qy({status:"refused"},{operation:br,remediation:"drop --skip-jira \u2014 under agent mode the fix version is checked and removed with the release; to keep it, ask a human to run `infra-kit release remove --skip-jira` from their own terminal",stderrExcerpt:"--skip-jira is not permitted under agent mode: it would tear down the branch and PR and leave a live Jira fix version behind with nothing in the result pointing at it"}))},Xy=e=>{e.pr?.state==="MERGED"&&Ke({operation:`remove release ${e.label}`,remediation:`this release has shipped \u2014 removing it would delete the branch recording the merge and strip its Jira fix version from delivered work. To undo a delivery, revert the merge commit on ${e.baseBranch} and cut a new release.`,stderrExcerpt:`PR #${e.pr.number} for ${e.branch} is MERGED`})},q$=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ke({operation:`remove release ${e.label}`,remediation:"set JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL, or pass --skip-jira to tear down the branch and PR and leave any fix version alone",stderrExcerpt:"Jira is not configured, so a fix version for this release cannot be checked or removed"}),!e.jira))return;let{version:r,fixCount:n,affectsCount:o}=e.jira;(r.released||r.archived)&&Ke({operation:`remove Jira fix version "${r.name}"`,remediation:"un-release it in Jira first, or remove the release without it via --skip-jira",stderrExcerpt:`fix version "${r.name}" is already ${r.released?"released":"archived"}`}),!(n===0&&o===0)&&(e.moveIssuesTo||Ke({operation:`remove Jira fix version "${r.name}"`,remediation:"deleting it would clear both fields on those issues with no way to restore them \u2014 pass --move-issues-to <version> to reassign both, or clear the version from the issues in Jira first",stderrExcerpt:`${r.name} is set as fixVersion on ${n} issue(s) and as affectsVersion on ${o} issue(s)`}))},Y$=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ke({operation:`remove release ${e.label}`,remediation:`nothing named "${e.label}" exists to remove \u2014 check the spelling against \`infra-kit release list\`. (A release this command already removed keeps a CLOSED PR, so a genuine re-run is not affected.)`,stderrExcerpt:"found no worktree, no PR (any state), no local or remote branch, and no Jira fix version"})},z$=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ke({operation:`remove release ${e.label}`,remediation:`commit or discard those changes (\`git -C ${e.worktreePath} stash -u\`), then re-run`,stderrExcerpt:`the worktree at ${e.worktreePath} has uncommitted changes: ${e.worktreeDirty.slice(0,4).join(", ")}`})},X$=async e=>(await Ku`git -C ${e} status --porcelain`).stdout.split(`
389
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),Z$=async e=>{try{let{terminals:t}=await xm(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},Q$=async e=>{let t=await Ms([e]);if(t!==null)throw d.warn({operation:br},`\u26D4 this command runs inside an Orca terminal of ${t}`),new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:br,remediation:`re-run from a terminal that is not an Orca pane of ${t} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${t}, which the removal would close`})},eA=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await gt();if(!n)return r;let o=await ft(ne(e),n),s=t.moveIssuesTo?await tA(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await oi(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:ar(n,o)}}},tA=async(e,t)=>{let r=await ft(e,t);return r||Ke({operation:`reassign issues to Jira fix version "${e}"`,remediation:'name an existing fix version exactly as it appears in Jira (e.g. "v1.2.6")',stderrExcerpt:`no Jira fix version named "${e}"`})},rA=async(e,t)=>{let r=H(e);r||Ke({operation:`remove release ${e}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:`"${e}" is not a release branch`});let n=await P(),s=`${`${n}${le}`}/${e}`,[i,a,c,l]=await Promise.all([me("release"),qr(e),De(n,`refs/heads/${e}`),Ar(n,e)]),u=i.includes(e);return u&&await Q$(s),{...await eA(r,t),branch:e,id:r,label:z(r),baseBranch:a?.baseRefName??rt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await Z$(s):0,worktreeDirty:u?await X$(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Yy=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}),nA=(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}`},oA=(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: ${nA(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
390
+ `)},Xi=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},sA=e=>typeof e=="string"?e:e.outcome;async function rs(e,t,r){try{let n=await r(),o=sA(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${zy[e]} \u2014 ${o}`),n}catch(n){throw new Xi(e,n)}}var iA=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,aA=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>iA(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 f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Hy.indexOf(r)+1} of ${Hy.length} (${zy[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},cA=async e=>(await Ko(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",lA=async e=>{let t=await qr(e.branch);if(Xy({...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 Ku`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},uA=async e=>(await $r()===e.branch&&await Ku`git switch ${e.baseBranch}`,await $s(e.branch),await Xp(e.branch)?Ke({operation:`delete local branch ${e.branch}`,remediation:`delete it by hand with \`git branch -D ${e.branch}\`, then re-run to finish the removal`,stderrExcerpt:`${e.branch} still exists after the delete`}):e.localTipSha?"deleted":"absent"),dA=async e=>(await As(e.branch),e.remoteTipSha?"deleted":"absent"),pA=async(e,t,r)=>{let n=await oi(t.version.id,r);if(n.issuesFixedCount===t.fixCount&&n.issuesAffectedCount===t.affectsCount)return;let o=`re-run \`infra-kit release remove --version ${e.label}\``;Ke({operation:`remove Jira fix version "${t.version.name}"`,remediation:`the fix version was NOT removed and every other step is complete \u2014 ${o} so the guard re-evaluates the new counts`,stderrExcerpt:`issue counts changed since preflight: fixVersion ${t.fixCount} \u2192 ${n.issuesFixedCount}, affectsVersion ${t.affectsCount} \u2192 ${n.issuesAffectedCount}`})},mA=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await pA(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 ol({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),fA=(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}),gA=async(e,t,r)=>{let n=await rs("worktree",r,()=>cA(e)),o=await rs("pr",r,()=>lA(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,()=>uA(e)),i=await rs("remote-branch",r,()=>dA(e)),a=await rs("jira",r,()=>mA(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},hA=async(e,t)=>{let r=[];try{return fA(e,await gA(e,t,r))}catch(n){throw n instanceof Xi?aA({plan:e,step:n.step,done:r,cause:n.reason}):n}},yA=async e=>{if(e)return ht(e);h.setInteractive();let[t,r]=await Promise.all([ae(),F()]),n=r.map(s=>s.branch);n.length===0&&Ke({operation:"select a release to remove",remediation:"pass `--version <ref>` to remove a release that is already partially torn down",stderrExcerpt:"no open release PRs to pick from"});let o=new Map(r.map(s=>[s.branch,s.type]));try{return await _t(ce({branches:n,descriptions:t,types:o}))}catch(s){throw Se(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},Zy=Ju(),Zi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await xe({operation:br}),await W(),await ze({provider:Zy,params:e,operation:br,argument:"version"}),H$(e);try{let s=await rA(await yA(r),e);d.debug({plan:Yy(s)},"release remove: resolved plan"),Xy(s),q$(s,e),Y$(s),await lo({operation:`remove release ${s.label}`,base:s.baseBranch}),z$(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await L(t,oA(s,!!o),{throwOnDecline:!0,plan:{...Yy(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await hA(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Se(s)||dt(s)||s instanceof f?s:(d.error({err:yr(s)},"\u274C Error removing release"),new f(s,{operation:br,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Hu=E({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:Zy,inputSchema:{version:re.string().optional().describe('The release version or name to remove (e.g. "1.2.5" or "checkout-redesign"). Omit it to be offered the open release PRs.'),moveIssuesTo:re.string().optional().describe(`Optional. An EXISTING Jira fix version name (exactly as in Jira, e.g. "v1.2.6") to move this release's issues to before its fix version is removed \u2014 both fixVersion and affectsVersion. Pass it only after a refusal reported the issue counts, or when the human named the target; a name Jira does not know is refused in preflight before anything is touched.`),confirm:re.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:re.string().describe("The release branch that was targeted"),version:re.string().describe('The release label (e.g. "1.2.5")'),baseBranch:re.string().describe("The branch HEAD was moved to before the local delete"),worktree:re.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:re.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:re.number().nullable().describe("The pull request number, or null when none exists"),localBranch:re.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:re.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:re.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:re.string().nullable().describe("The origin tip before deletion"),jira:re.enum(["removed","absent","skipped"]).describe('"removed" when the fix version was deleted; "absent" when Jira knows none for this release (the resume path); "skipped" only on the CLI with --skip-jira'),jiraVersion:re.object({id:re.string(),name:re.string(),url:re.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Zi});import{spawn as bA}from"node:child_process";import RA from"node:fs";import{homedir as SA}from"node:os";import ea from"node:process";import Qi from"node:fs";import Pn from"node:path";var vA=e=>{try{return Qi.statSync(e).isFile()?Qi.readFileSync(e,"utf8"):null}catch{return null}},wA=e=>{try{return Qi.realpathSync(e)}catch{return e}},kA=(e,t)=>{let o=t(Pn.join(e,".git"))?.split(`
391
+ `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=Pn.resolve(e,o),i=`${Pn.sep}.git${Pn.sep}worktrees${Pn.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},Qy=(e={})=>{let t=e.listInstallations??Va,r=e.exists??Qi.existsSync,n=e.readGitFile??vA,o=e.realpath??wA,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=kA(i.projectPath,n);if(!r(Pn.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var EA=180*1e3,PA=900*1e3,xA=4*1024*1024,TA=2e3,CA=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=bA(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&&ea.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<xA&&(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)},TA).unref()})}),$A=({cwd:e,timeoutMs:t})=>CA({command:ea.execPath,args:[ea.argv[1]??"","setup","--unattended","--json"],cwd:e,env:km(ea.env),timeoutMs:t}),AA=e=>{RA.writeFileSync(an(),e,{mode:384})},OA=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}},IA=new RegExp("\x1B\\[[0-9;]*m","g"),DA=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(IA,"").split(`
392
+ `).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},NA=(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}},ev=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":bi(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(EA,o)}),a=i.error===null?OA(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${DA(i)} \u2014 run: ${s}`]}:{root:e,...NA(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},_A=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}})},MA=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(`
392
393
  `)}
393
- `},IA=e=>({version:e.version??U.version,home:e.home??vA(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Ja({lockPath:jg()})),readRecord:e.readRecord??cn,writeRecord:e.writeRecord??Fg,discoverProjects:e.discoverProjects??(()=>Qy()),runSetupChild:e.runSetupChild??EA,writeLog:e.writeLog??PA}),DA=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},NA=async e=>{let t=e.readRecord(),r=e.clock();if(!Ug(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+kA,s=await ev(null,e.home,e,o),i=DA(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 ev(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:AA(a)};e.writeRecord(c);try{e.writeLog(OA(c))}catch{}return"ran"},tv=async(e={})=>{try{let t=IA(e),r=t.acquireLock();if(r===null)return"already-running";try{return await NA(t)}finally{r()}}catch{return"not-due"}},qu=async(e={})=>{let t=await tv(e);return{content:k(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as FA}from"node:child_process";import{homedir as LA}from"node:os";import BA from"node:process";var _A=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},MA=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},jA=(e,t)=>{let r=_A(e);if(r===null)return[];let n=[];return t.present.includes(r)||n.push("manager-absent"),t.owner!==null&&t.owner!==r&&n.push("manager-mismatch"),n},ns=(e,t)=>{let r=[...MA(e),...jA(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},os=e=>e.steps.map(Ie);var UA=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],VA=e=>{let t={...Pp(e)};for(let r of UA)delete t[r];return t},Yu=(e,t,r={})=>{let n=r.spawnSync??FA,o=r.env??BA.env,s=(r.agentMode??ve)(),i=os(e),a=ns(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:JA({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??WA}):{ran:!1,commands:i,refusedBecause:a.reasons}},WA=e=>{d.info(e)},nv=64,GA=nv*1024*1024,JA=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=VA(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:GA,cwd:LA(),env:s}),l=XA(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},KA=5,HA=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,rv=e=>e==null?[]:String(e).split(`
394
- `).map(t=>t.trim()).filter(t=>t.length>0),qA=e=>{let t=rv(e.stderr),r=rv(e.stdout),n=[...t,...r].filter(s=>HA.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-KA).join(" / ")},YA="ENOBUFS",zA=e=>e.error?.code===YA,XA=e=>{if(zA(e))return`terminated after exceeding the ${nv} 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=qA(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var ZA=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},QA=e=>{let t=Le(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},eO=(e,t)=>{let r=QA(e),n={...t,owner:e.present?e.manager:null};if(r===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=ns(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:os(r),context:n}},ta=async(e=lr,t=$o())=>{let r=await Oo(lr,t),n={owner:null,present:ZA(r)},o=Dl(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>eO(s.get(a),n)),context:n}};var zu=(e,t)=>({...ss(e),action:"skipped",commands:e.commands,detail:t}),ss=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),ov=(e,t)=>e.action==="none"?zu(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?zu(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...ss(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},tO=(e,t)=>t.ran?t.ok?{...ss(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...ss(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...ss(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Xu=async e=>{let t=e.run??Yu,{plans:r}=await ta(e.ids,e.probeDeps),n=[];for(let o of r){let s=ov(o,e.mode);if(s!==null){n.push(s);continue}n.push(tO(o,t(o.recipe,o.context)))}return n},Zu=async(e,t)=>{let{plans:r}=await ta(e,t);return r.map(n=>ov(n,"converge")??zu(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import yO from"node:process";import{z as O}from"zod";var Qu={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},rO=Object.keys(Qu).sort((e,t)=>Qu[e]-Qu[t]),sv={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},iv=new Set(["manual","warn","fail"]),ed=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return Ne(e)}},nO=e=>e.reduce((t,r)=>sv[r]>sv[t]?r:t,"skipped"),cv=e=>e.message.trim(),oO=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 "),av=e=>e.message===fn,sO=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?cv(r):e.length>1?oO(e):t?"activate with the last line below":"see below"},iO=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>ed(i.outcome)),n=t.filter(i=>iv.has(ed(i.outcome))).map(cv),o=t.filter(i=>!iv.has(ed(i.outcome))&&!av(i)),s={name:e,status:nO(r),message:sO(o,t.some(av))};return n.length>0?{...s,notes:n}:s},aO=e=>({label:"Local setup",rows:rO.map(t=>iO(t,e.filter(r=>r.step===t)))}),cO=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return Ne(e.action)}},lO=(e,t)=>{let r=cO(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},uO=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>lO(r,t))}),dO=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return Ne(e)}},pO=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return Ne(e)}},mO=e=>{switch(e){case"created":return"linked ~/.infra-kit/portless to the running portless";case"repointed":return"re-pointed ~/.infra-kit/portless to the running portless";case"unchanged":return"already linked to the running portless";case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-unresolved":return"skipped \u2014 portless is not installed";case"failed":return"could not update the link \u2014 see the debug log";default:return Ne(e)}},fO=e=>{let t=e.method==="copy"?"copied":"linked";switch(e.outcome){case"created":return`${t} Node ${e.version} to ~/.infra-kit/node`;case"refreshed":return`re-${t} Node ${e.version} to ~/.infra-kit/node`;case"unchanged":return`~/.infra-kit/node is already Node ${e.version}`;case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-platform":return"skipped \u2014 no portless OS service on this platform";case"failed":return"could not write ~/.infra-kit/node \u2014 see the debug log";default:return Ne(e.outcome)}},gO=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return Ne(e)}},hO=e=>({label:"Portless service",rows:[{name:"link",status:dO(e.link),message:mO(e.link)},{name:"node",status:pO(e.node.outcome),message:fO(e.node)},gO(e.service,e.command)]}),lv=(e,t)=>[aO(e.init),uO(e.tools,t),hO(e.portless)],uv=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var vO=()=>{let{link:e,node:t}=xs();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},wO=async e=>{let t=Up(e.link).outcome,r=Bp(e.node),n=Ps(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 Lh(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Rt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},pv="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",mv="--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.",kO=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(pv);if(o&&(e.tools!==void 0||r))throw new Error(mv);return{ids:e.tools??t??lr,mode:r?"update":"converge",skipTools:o}},dv=(e,t)=>e instanceof mn?e.step:t.at(-1)?.step??"zshrc",bO=async()=>{let e=[];try{await xl(t=>{e.push(t)})}catch(t){e.push({step:dv(t,e),outcome:"failed",message:`The ${dv(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},RO=(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}`}))},SO=async(e,t)=>{try{return e.skipTools?await Zu(e.ids,t.probeDeps):await Xu({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return RO(e.ids,r)}},EO=e=>({step:e.step,outcome:e.outcome,message:e.message}),ra=async(e={})=>{let t=kO(e);Ge.withheld=e.unattended===!0;let r=await bO(),n=await SO(t,e),o=await wO(e.portlessDeps??vO()),s=lv({init:r,tools:n,portless:o},{skipTools:t.skipTools});tt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(fn),uv(s)&&(yO.exitCode=1);let i={init:r.map(EO),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},PO=O.object({step:O.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","token-perms","chrome","shell"]).describe("Which init step this reports on"),outcome:O.enum(["written","unchanged","skipped","manual","warned","failed"]).describe("What that step did: changed something, found nothing to change, did not run, left a command for a human to run (the message carries it), failed non-fatally, or threw and ended the init half (setup exits 1)"),message:O.string().describe("The same line a human running this would have read")}),xO=O.object({id:O.string().describe("Dependency id"),action:O.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:O.object({present:O.boolean(),onPath:O.boolean(),version:O.string().nullable(),manager:O.string()}).describe("The tool\u2019s state before this run"),commands:O.array(O.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:O.string().describe("Why, in one line")}),TO=O.object({link:O.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:O.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:O.enum(["absent","converged","drifted","skipped"]).describe("The installed portless system service against the link and node: not installed, already running through both, installed but pointing elsewhere, or not judged because portless is not installed"),command:O.string().nullable().describe("The sudo `service install` command a human has to run; present if and only if service is absent or drifted, null otherwise")}),CO={init:O.array(PO).describe("One entry per init step, in the order they ran"),tools:O.array(xO).describe("One result per requested dependency"),portlessService:TO.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:O.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:O.boolean().describe("Whether anything was installed or updated"),report:O.array(O.object({label:O.string().describe("Section heading"),rows:O.array(O.object({name:O.string().describe("Init step, tool id, or portless part"),status:O.enum(["ok","changed","skipped","manual","warn","fail"]).describe("ok: nothing to change; changed: changed something; skipped: did not run; manual: not run by the CLI, the notes hold the command a human runs; warn: advisory problem; fail: failed (setup exits 1)"),message:O.string().describe("The row message, as printed"),notes:O.array(O.string()).optional().describe("Lines printed under the row, verbatim: the manual commands, warnings and failures")}))})).describe("The exact rows of the table printed on stderr; setup exits 1 iff a row is fail"),allSucceeded:O.boolean().describe("Whether no tool failed (a refusal is not a failure)")},$O={tools:O.array(O.enum(lr)).optional().describe("Which tools to act on. Omit for all six."),mode:O.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:O.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},td=E({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, check the agent-instruction files (never rewritten here: drift is reported with the `audit --fix` command that refreshes them), register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:$O,outputSchema:CO,requiresHumanConfirm:!0,handler:e=>ra({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as gv}from"node:fs";import hv from"node:path";import BO from"node:process";import{z as kt}from"zod";import{createHash as AO}from"node:crypto";import{readFileSync as OO}from"node:fs";var br=e=>AO("sha256").update(OO(e)).digest("hex");import{readFileSync as jO,writeFileSync as FO}from"node:fs";import ia from"node:path";import{z as ct}from"zod";var X="vendor",IO=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),DO=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),NO=[".tsbuildinfo"],rd=e=>IO.has(e),nd=e=>DO.has(e)?!0:NO.some(t=>e.endsWith(t)),na=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>rd(o))||nd(r)};import{readdirSync as _O}from"node:fs";import od from"node:path";var MO=e=>e.split(od.sep).join("/"),oa=e=>{let t=[],r=n=>{for(let o of _O(n,{withFileTypes:!0})){let s=od.join(n,o.name);if(o.isDirectory()){if(rd(o.name))continue;r(s);continue}nd(o.name)||t.push(MO(od.relative(e,s)))}};return r(e),t.sort()};var Ve=".sync-manifest.json",sa=1,LO=ct.object({schemaVersion:ct.number().optional(),source:ct.string(),commit:ct.string(),syncedAt:ct.string(),fileCount:ct.number(),files:ct.record(ct.string(),ct.string())}),sd=e=>(e.schemaVersion??sa)>sa,fv=(e,t)=>{let r={},n=t?[...new Set(t)].sort():oa(e);for(let o of n)try{r[o]=br(ia.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},is=e=>{let t=ia.join(e,Ve),r;try{r=jO(t,"utf8")}catch{throw new Error(`Missing ${Ve} at ${t}`)}let n=LO.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ve} at ${t}: ${ct.prettifyError(n.error)}`);return n.data},id=(e,t,r)=>{let n=fv(e,r),o={schemaVersion:sa,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return FO(ia.join(e,Ve),`${JSON.stringify(o,null,2)}
395
- `),o},ad=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!na(c))),n=oa(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}br(ia.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 cd=30,ld=(e,t)=>{if(t.length!==0){d.info(`
396
- ${e} (${t.length}):`);for(let r of t.slice(0,cd))d.info(` ${r}`);t.length>cd&&d.info(` \u2026and ${t.length-cd} more`)}},aa=async(e={})=>{let t=e.cwd??await P(),r=hv.join(t,X),n={modified:[],added:[],removed:[],fileCount:0};if(!gv(r)){d.info(`\u2139\uFE0F No ${X}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}if(!gv(hv.join(r,Ve))){d.error(`\u274C Missing ${X}/${Ve}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let o=is(r);if(sd(o)){d.error(`\u274C ${X}/${Ve} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=ad(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${X}/ has drifted from ${X}/${Ve}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),ld("Modified",s),ld("Added (not in manifest)",i),ld("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${X}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},UO={status:kt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:kt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:kt.number(),modified:kt.array(kt.string()),added:kt.array(kt.string()),removed:kt.array(kt.string())},ud=E({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:UO,handler:()=>aa({cwd:BO.cwd()})});import yv from"node:process";import{z as as}from"zod";var vv=async e=>{try{return await e()}catch{return null}},ca=async()=>{let e=U.version;d.info(e);let t=await vv(P),r=t===null?null:await vv(()=>Re(t)),n={version:e,cwd:yv.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:yv.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},dd=E({name:"version",description:"Print the installed infra-kit CLI version and where this process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR)",inputSchema:{},outputSchema:{version:as.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:as.string().describe("The working directory of this process"),repoRoot:as.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:as.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:as.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:ca});import Ov from"@inquirer/confirm";import HO from"node:path";import{z as M}from"zod";import{$ as ls}from"zx";import VO from"@inquirer/input";import kv from"@inquirer/select";import{$ as Wt}from"zx";var cs="dev",WO="main",pd="feature/",bv=["new","local","remote"],la=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${pd}${t}`},Rv=async()=>{let e=await Wt({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},GO=2,md=async()=>{let e=await Wt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${cs}`;if(e.exitCode===0)return cs;if(e.exitCode!==GO)throw new f(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${cs} exists`});return await Rv()??cs},Sv=async e=>{let t=e?.trim();return t?t===cs||t===WO||t===await Rv()?t:we(me(t)):md()},Ev=async()=>I(e=>kv({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"}}),Pv=async()=>I(e=>VO({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>la(t)===pd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),xv=async(e,t)=>e.length===0?t:I(r=>kv({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),JO=async e=>{let t=await Wt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===pd||t.exitCode!==0)throw new f(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},wv=async e=>(await Wt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,KO=async e=>(await Wt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Tv=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(la))];for(let s of n)await JO(s);if(!await wv(r))throw new f(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await KO(s)?o.push({branch:s,base:r,source:"local"}):await wv(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Cv=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await Wt`git worktree add ${t} ${r}`:o==="remote"?await Wt`git worktree add --track -b ${r} ${t} origin/${r}`:await Wt`git worktree add --no-track -b ${r} ${t} origin/${n}`},$v=e=>e.source==="new"?` \u2022 ${e.branch}: new branch from origin/${e.base}`:` \u2022 ${e.branch}: existing ${e.source==="local"?"local":"remote"} branch (base not applied)`;var us="create worktrees",qO=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],fd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),ua=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await xe({operation:us}),YO(e);try{let o=await P(),s=`${o}${ue}`;await Av(`${s}/${xr.release}`),await Av(`${s}/${xr.feature}`);let i=await zO(e),a=i==="feature"?await ZO(e):await XO(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),h.print();let D={kind:i,createdWorktrees:[],count:0,features:[],...fd()};return{content:k(JSON.stringify(D,null,2)),structuredContent:D}}let c=await W(),l=await QO(r,c),u=await eI(n,c),p=await Re(o),m=HO.basename(p),g=u?await tI({explicit:n!==void 0,mainRepoRoot:p}):null;await L(t,rI(g,m,a.previewLines)),t||h.addOption("--yes",!0);let y=g?await nI(g,p):null,b=await cI(a.targets,s);if(lI(b),l)for(let D of b)await ls`github ${s}/${D}`,await ls`sleep 5`;let w=y?await sI({registration:y,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):fd();iI(w),h.print();let x={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(D=>b.includes(D.branch)),...w};return{content:k(JSON.stringify(x,null,2)),structuredContent:x}}catch(o){throw Se(o)||o instanceof C?o:(d.debug({err:o},"Error managing worktrees"),new f(o,{operation:us,remediation:o instanceof f&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},YO=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new f(void 0,{operation:us,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},zO=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Ev()),XO=async e=>{let{all:t,versions:r}=e,n=await fe("release"),o=[];if(r)o=r.split(",").map(a=>we(me(a.trim())));else{let a=await F(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{h.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await ae();o=await _t(ce({branches:c,descriptions:u,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",yt(o));let{branchesToCreate:s}=aI({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>ls`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},ZO=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await Pv()],n===void 0)){let l=(await F()).map(u=>u.branch);n=await xv(l,await md())}let o=await Sv(n),s=await Tv({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await fe("feature"),a=s.filter(l=>i.includes(l.branch)?(d.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:u=>Cv(l,u)})),features:a,previewLines:a.map($v)}},QO=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await I(o=>Ov({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},eI=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await I(o=>Ov({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},Iv=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"},tI=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Tt();if(n!=="ready"){let{reason:s,text:i}=Iv(n);if(t)throw d.warn({operation:us},`\u26D4 --orca was passed but ${i}`),new C({status:"refused",reason:s,agentMode:_.source},2,{operation:us,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 Cm(r);return{probe:n,registered:o.registered,visibility:o.visibility}},rI=(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(`
397
- `)},nI=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Iv(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await $m(t);return{kind:"ready",visibility:r}}catch(r){return d.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof Ar?r.code:void 0}}},oI=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,sI=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=fd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=lm(i),l=r.length===1&&t.visibility!=="hide",u=Om();for(let p of r){let m=`${n}/${p}`;try{let{layout:g}=await Im({cwd:m,title:Dm({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Am(o,m)?a.orcaOpened.push({branch:p,layout:g}):a.orcaHidden.push({branch:p,path:m,fix:oI(s)})}catch(g){d.warn({error:g,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),g instanceof Ar&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:g instanceof Ar?g.code:void 0})}}return a},iI=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}`)}},Av=async e=>{await ls`mkdir -p ${e}`},aI=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Tr(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},cI=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await ls({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new f(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},lI=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")},gd=E({name:"worktrees-add",description:`Create local git worktrees under the worktrees directory and run "pnpm install" in each: release worktrees for open release branches ("versions" / all=true), or feature worktrees ("feature", optional "base") \u2014 each name becomes a feature/<name> branch at <root>-worktrees/feature/<name>, cut from origin/<base> (default dev, or the default branch of a repo without dev; main; or any release branch) with no upstream, or checked out as-is when the branch already exists locally or on origin. Mutates the local filesystem. When invoked via MCP, pass "versions" (comma-separated), all=true, or "feature" \u2014 the branch picker and "open in Cursor / GitHub Desktop / Orca" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls. With "orca" true each created worktree gets an Orca terminal tab laid out per "worktrees.orca.layout"; the result reports orcaOpened, orcaSkipped (with a reason) and orcaHidden (a worktree Orca's sidebar hides, with the UI steps to reveal it). An unregistered repo is registered in Orca first (orca repo add).`,inputSchema:{feature:M.string().optional().describe('Comma-separated feature names (e.g. "checkout-v2" or "feature/checkout-v2"); each becomes a feature/<name> worktree. Cannot be combined with "versions" or "all".'),base:M.string().optional().describe(`Base for NEW feature branches: "dev" (default; the repo's default branch when it has no dev), "main", or a release ref ("1.4.0", "release/v1.4.0", "release/<name>"). Not applied to a feature branch that already exists. Implies a feature run.`),all:M.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:M.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:M.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:M.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:M.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:M.array(M.object({branch:M.string(),base:M.string(),source:M.enum(bv)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:M.array(M.string()).describe("List of created git worktree branches"),count:M.number().describe("Number of git worktrees created"),orcaOpened:M.array(M.object({branch:M.string(),layout:M.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:M.array(M.object({branch:M.string(),reason:M.enum(qO),code:M.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:M.array(M.object({branch:M.string(),path:M.string(),fix:M.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:ua});import{z as Gt}from"zod";var da=async()=>{await W();let[e,t]=await Promise.all([fe("release"),fe("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await uI(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
394
+ `},jA=e=>({version:e.version??U.version,home:e.home??SA(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Ja({lockPath:jg()})),readRecord:e.readRecord??cn,writeRecord:e.writeRecord??Fg,discoverProjects:e.discoverProjects??(()=>Qy()),runSetupChild:e.runSetupChild??$A,writeLog:e.writeLog??AA}),FA=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},LA=async e=>{let t=e.readRecord(),r=e.clock();if(!Ug(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+PA,s=await ev(null,e.home,e,o),i=FA(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 ev(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:_A(a)};e.writeRecord(c);try{e.writeLog(MA(c))}catch{}return"ran"},tv=async(e={})=>{try{let t=jA(e),r=t.acquireLock();if(r===null)return"already-running";try{return await LA(t)}finally{r()}}catch{return"not-due"}},qu=async(e={})=>{let t=await tv(e);return{content:k(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as WA}from"node:child_process";import{homedir as GA}from"node:os";import JA from"node:process";var BA=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},UA=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},VA=(e,t)=>{let r=BA(e);if(r===null)return[];let n=[];return t.present.includes(r)||n.push("manager-absent"),t.owner!==null&&t.owner!==r&&n.push("manager-mismatch"),n},ns=(e,t)=>{let r=[...UA(e),...VA(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},os=e=>e.steps.map(Ie);var KA=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],HA=e=>{let t={...Pp(e)};for(let r of KA)delete t[r];return t},Yu=(e,t,r={})=>{let n=r.spawnSync??WA,o=r.env??JA.env,s=(r.agentMode??ve)(),i=os(e),a=ns(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:zA({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??qA}):{ran:!1,commands:i,refusedBecause:a.reasons}},qA=e=>{d.info(e)},nv=64,YA=nv*1024*1024,zA=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=HA(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:YA,cwd:GA(),env:s}),l=rO(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},XA=5,ZA=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,rv=e=>e==null?[]:String(e).split(`
395
+ `).map(t=>t.trim()).filter(t=>t.length>0),QA=e=>{let t=rv(e.stderr),r=rv(e.stdout),n=[...t,...r].filter(s=>ZA.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-XA).join(" / ")},eO="ENOBUFS",tO=e=>e.error?.code===eO,rO=e=>{if(tO(e))return`terminated after exceeding the ${nv} 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=QA(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var nO=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},oO=e=>{let t=Le(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},sO=(e,t)=>{let r=oO(e),n={...t,owner:e.present?e.manager:null};if(r===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=ns(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:os(r),context:n}},ta=async(e=ur,t=$o())=>{let r=await Oo(ur,t),n={owner:null,present:nO(r)},o=Dl(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>sO(s.get(a),n)),context:n}};var zu=(e,t)=>({...ss(e),action:"skipped",commands:e.commands,detail:t}),ss=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),ov=(e,t)=>e.action==="none"?zu(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?zu(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...ss(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},iO=(e,t)=>t.ran?t.ok?{...ss(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...ss(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...ss(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Xu=async e=>{let t=e.run??Yu,{plans:r}=await ta(e.ids,e.probeDeps),n=[];for(let o of r){let s=ov(o,e.mode);if(s!==null){n.push(s);continue}n.push(iO(o,t(o.recipe,o.context)))}return n},Zu=async(e,t)=>{let{plans:r}=await ta(e,t);return r.map(n=>ov(n,"converge")??zu(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import RO from"node:process";import{z as O}from"zod";var Qu={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},aO=Object.keys(Qu).sort((e,t)=>Qu[e]-Qu[t]),sv={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},iv=new Set(["manual","warn","fail"]),ed=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return Ne(e)}},cO=e=>e.reduce((t,r)=>sv[r]>sv[t]?r:t,"skipped"),cv=e=>e.message.trim(),lO=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 "),av=e=>e.message===fn,uO=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?cv(r):e.length>1?lO(e):t?"activate with the last line below":"see below"},dO=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>ed(i.outcome)),n=t.filter(i=>iv.has(ed(i.outcome))).map(cv),o=t.filter(i=>!iv.has(ed(i.outcome))&&!av(i)),s={name:e,status:cO(r),message:uO(o,t.some(av))};return n.length>0?{...s,notes:n}:s},pO=e=>({label:"Local setup",rows:aO.map(t=>dO(t,e.filter(r=>r.step===t)))}),mO=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return Ne(e.action)}},fO=(e,t)=>{let r=mO(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},gO=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>fO(r,t))}),hO=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return Ne(e)}},yO=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return Ne(e)}},vO=e=>{switch(e){case"created":return"linked ~/.infra-kit/portless to the running portless";case"repointed":return"re-pointed ~/.infra-kit/portless to the running portless";case"unchanged":return"already linked to the running portless";case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-unresolved":return"skipped \u2014 portless is not installed";case"failed":return"could not update the link \u2014 see the debug log";default:return Ne(e)}},wO=e=>{let t=e.method==="copy"?"copied":"linked";switch(e.outcome){case"created":return`${t} Node ${e.version} to ~/.infra-kit/node`;case"refreshed":return`re-${t} Node ${e.version} to ~/.infra-kit/node`;case"unchanged":return`~/.infra-kit/node is already Node ${e.version}`;case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-platform":return"skipped \u2014 no portless OS service on this platform";case"failed":return"could not write ~/.infra-kit/node \u2014 see the debug log";default:return Ne(e.outcome)}},kO=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return Ne(e)}},bO=e=>({label:"Portless service",rows:[{name:"link",status:hO(e.link),message:vO(e.link)},{name:"node",status:yO(e.node.outcome),message:wO(e.node)},kO(e.service,e.command)]}),lv=(e,t)=>[pO(e.init),gO(e.tools,t),bO(e.portless)],uv=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var SO=()=>{let{link:e,node:t}=xs();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},EO=async e=>{let t=Up(e.link).outcome,r=Bp(e.node),n=Ps(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 Lh(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Rt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},pv="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",mv="--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.",PO=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(pv);if(o&&(e.tools!==void 0||r))throw new Error(mv);return{ids:e.tools??t??ur,mode:r?"update":"converge",skipTools:o}},dv=(e,t)=>e instanceof mn?e.step:t.at(-1)?.step??"zshrc",xO=async()=>{let e=[];try{await xl(t=>{e.push(t)})}catch(t){e.push({step:dv(t,e),outcome:"failed",message:`The ${dv(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},TO=(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}`}))},CO=async(e,t)=>{try{return e.skipTools?await Zu(e.ids,t.probeDeps):await Xu({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return TO(e.ids,r)}},$O=e=>({step:e.step,outcome:e.outcome,message:e.message}),ra=async(e={})=>{let t=PO(e);Ge.withheld=e.unattended===!0;let r=await xO(),n=await CO(t,e),o=await EO(e.portlessDeps??SO()),s=lv({init:r,tools:n,portless:o},{skipTools:t.skipTools});tt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(fn),uv(s)&&(RO.exitCode=1);let i={init:r.map($O),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},AO=O.object({step:O.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","token-perms","chrome","shell"]).describe("Which init step this reports on"),outcome:O.enum(["written","unchanged","skipped","manual","warned","failed"]).describe("What that step did: changed something, found nothing to change, did not run, left a command for a human to run (the message carries it), failed non-fatally, or threw and ended the init half (setup exits 1)"),message:O.string().describe("The same line a human running this would have read")}),OO=O.object({id:O.string().describe("Dependency id"),action:O.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:O.object({present:O.boolean(),onPath:O.boolean(),version:O.string().nullable(),manager:O.string()}).describe("The tool\u2019s state before this run"),commands:O.array(O.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:O.string().describe("Why, in one line")}),IO=O.object({link:O.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:O.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:O.enum(["absent","converged","drifted","skipped"]).describe("The installed portless system service against the link and node: not installed, already running through both, installed but pointing elsewhere, or not judged because portless is not installed"),command:O.string().nullable().describe("The sudo `service install` command a human has to run; present if and only if service is absent or drifted, null otherwise")}),DO={init:O.array(AO).describe("One entry per init step, in the order they ran"),tools:O.array(OO).describe("One result per requested dependency"),portlessService:IO.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:O.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:O.boolean().describe("Whether anything was installed or updated"),report:O.array(O.object({label:O.string().describe("Section heading"),rows:O.array(O.object({name:O.string().describe("Init step, tool id, or portless part"),status:O.enum(["ok","changed","skipped","manual","warn","fail"]).describe("ok: nothing to change; changed: changed something; skipped: did not run; manual: not run by the CLI, the notes hold the command a human runs; warn: advisory problem; fail: failed (setup exits 1)"),message:O.string().describe("The row message, as printed"),notes:O.array(O.string()).optional().describe("Lines printed under the row, verbatim: the manual commands, warnings and failures")}))})).describe("The exact rows of the table printed on stderr; setup exits 1 iff a row is fail"),allSucceeded:O.boolean().describe("Whether no tool failed (a refusal is not a failure)")},NO={tools:O.array(O.enum(ur)).optional().describe("Which tools to act on. Omit for all six."),mode:O.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:O.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},td=E({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, check the agent-instruction files (never rewritten here: drift is reported with the `audit --fix` command that refreshes them), register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:NO,outputSchema:DO,requiresHumanConfirm:!0,handler:e=>ra({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as gv}from"node:fs";import hv from"node:path";import JO from"node:process";import{z as kt}from"zod";import{createHash as _O}from"node:crypto";import{readFileSync as MO}from"node:fs";var Rr=e=>_O("sha256").update(MO(e)).digest("hex");import{readFileSync as VO,writeFileSync as WO}from"node:fs";import ia from"node:path";import{z as ct}from"zod";var Z="vendor",jO=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),FO=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),LO=[".tsbuildinfo"],rd=e=>jO.has(e),nd=e=>FO.has(e)?!0:LO.some(t=>e.endsWith(t)),na=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>rd(o))||nd(r)};import{readdirSync as BO}from"node:fs";import od from"node:path";var UO=e=>e.split(od.sep).join("/"),oa=e=>{let t=[],r=n=>{for(let o of BO(n,{withFileTypes:!0})){let s=od.join(n,o.name);if(o.isDirectory()){if(rd(o.name))continue;r(s);continue}nd(o.name)||t.push(UO(od.relative(e,s)))}};return r(e),t.sort()};var Ve=".sync-manifest.json",sa=1,GO=ct.object({schemaVersion:ct.number().optional(),source:ct.string(),commit:ct.string(),syncedAt:ct.string(),fileCount:ct.number(),files:ct.record(ct.string(),ct.string())}),sd=e=>(e.schemaVersion??sa)>sa,fv=(e,t)=>{let r={},n=t?[...new Set(t)].sort():oa(e);for(let o of n)try{r[o]=Rr(ia.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},is=e=>{let t=ia.join(e,Ve),r;try{r=VO(t,"utf8")}catch{throw new Error(`Missing ${Ve} at ${t}`)}let n=GO.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ve} at ${t}: ${ct.prettifyError(n.error)}`);return n.data},id=(e,t,r)=>{let n=fv(e,r),o={schemaVersion:sa,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return WO(ia.join(e,Ve),`${JSON.stringify(o,null,2)}
396
+ `),o},ad=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!na(c))),n=oa(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Rr(ia.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 cd=30,ld=(e,t)=>{if(t.length!==0){d.info(`
397
+ ${e} (${t.length}):`);for(let r of t.slice(0,cd))d.info(` ${r}`);t.length>cd&&d.info(` \u2026and ${t.length-cd} more`)}},aa=async(e={})=>{let t=e.cwd??await P(),r=hv.join(t,Z),n={modified:[],added:[],removed:[],fileCount:0};if(!gv(r)){d.info(`\u2139\uFE0F No ${Z}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}if(!gv(hv.join(r,Ve))){d.error(`\u274C Missing ${Z}/${Ve}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let o=is(r);if(sd(o)){d.error(`\u274C ${Z}/${Ve} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=ad(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${Z}/ has drifted from ${Z}/${Ve}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),ld("Modified",s),ld("Added (not in manifest)",i),ld("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${Z}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},KO={status:kt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:kt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:kt.number(),modified:kt.array(kt.string()),added:kt.array(kt.string()),removed:kt.array(kt.string())},ud=E({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:KO,handler:()=>aa({cwd:JO.cwd()})});import yv from"node:process";import{z as as}from"zod";var vv=async e=>{try{return await e()}catch{return null}},ca=async()=>{let e=U.version;d.info(e);let t=await vv(P),r=t===null?null:await vv(()=>Re(t)),n={version:e,cwd:yv.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:yv.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},dd=E({name:"version",description:"Print the installed infra-kit CLI version and where this process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR)",inputSchema:{},outputSchema:{version:as.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:as.string().describe("The working directory of this process"),repoRoot:as.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:as.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:as.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:ca});import Ov from"@inquirer/confirm";import ZO from"node:path";import{z as M}from"zod";import{$ as ls}from"zx";import HO from"@inquirer/input";import kv from"@inquirer/select";import{$ as Gt}from"zx";var cs="dev",qO="main",pd="feature/",bv=["new","local","remote"],la=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${pd}${t}`},Rv=async()=>{let e=await Gt({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},YO=2,md=async()=>{let e=await Gt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${cs}`;if(e.exitCode===0)return cs;if(e.exitCode!==YO)throw new f(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${cs} exists`});return await Rv()??cs},Sv=async e=>{let t=e?.trim();return t?t===cs||t===qO||t===await Rv()?t:we(pe(t)):md()},Ev=async()=>I(e=>kv({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"}}),Pv=async()=>I(e=>HO({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>la(t)===pd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),xv=async(e,t)=>e.length===0?t:I(r=>kv({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),zO=async e=>{let t=await Gt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===pd||t.exitCode!==0)throw new f(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},wv=async e=>(await Gt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,XO=async e=>(await Gt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Tv=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(la))];for(let s of n)await zO(s);if(!await wv(r))throw new f(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await XO(s)?o.push({branch:s,base:r,source:"local"}):await wv(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Cv=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await Gt`git worktree add ${t} ${r}`:o==="remote"?await Gt`git worktree add --track -b ${r} ${t} origin/${r}`:await Gt`git worktree add --no-track -b ${r} ${t} origin/${n}`},$v=e=>e.source==="new"?` \u2022 ${e.branch}: new branch from origin/${e.base}`:` \u2022 ${e.branch}: existing ${e.source==="local"?"local":"remote"} branch (base not applied)`;var us="create worktrees",QO=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],fd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),ua=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await xe({operation:us}),eI(e);try{let o=await P(),s=`${o}${le}`;await Av(`${s}/${Tr.release}`),await Av(`${s}/${Tr.feature}`);let i=await tI(e),a=i==="feature"?await nI(e):await rI(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),h.print();let D={kind:i,createdWorktrees:[],count:0,features:[],...fd()};return{content:k(JSON.stringify(D,null,2)),structuredContent:D}}let c=await W(),l=await oI(r,c),u=await sI(n,c),p=await Re(o),m=ZO.basename(p),g=u?await iI({explicit:n!==void 0,mainRepoRoot:p}):null;await L(t,aI(g,m,a.previewLines)),t||h.addOption("--yes",!0);let y=g?await cI(g,p):null,b=await mI(a.targets,s);if(fI(b),l)for(let D of b)await ls`github ${s}/${D}`,await ls`sleep 5`;let w=y?await uI({registration:y,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):fd();dI(w),h.print();let x={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(D=>b.includes(D.branch)),...w};return{content:k(JSON.stringify(x,null,2)),structuredContent:x}}catch(o){throw Se(o)||o instanceof C?o:(d.debug({err:o},"Error managing worktrees"),new f(o,{operation:us,remediation:o instanceof f&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},eI=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new f(void 0,{operation:us,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},tI=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Ev()),rI=async e=>{let{all:t,versions:r}=e,n=await me("release"),o=[];if(r)o=r.split(",").map(a=>we(pe(a.trim())));else{let a=await F(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{h.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await ae();o=await Mt(ce({branches:c,descriptions:u,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",yt(o));let{branchesToCreate:s}=pI({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>ls`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},nI=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await Pv()],n===void 0)){let l=(await F()).map(u=>u.branch);n=await xv(l,await md())}let o=await Sv(n),s=await Tv({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await me("feature"),a=s.filter(l=>i.includes(l.branch)?(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=>Cv(l,u)})),features:a,previewLines:a.map($v)}},oI=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await I(o=>Ov({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},sI=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await I(o=>Ov({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},Iv=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"},iI=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Tt();if(n!=="ready"){let{reason:s,text:i}=Iv(n);if(t)throw d.warn({operation:us},`\u26D4 --orca was passed but ${i}`),new C({status:"refused",reason:s,agentMode:_.source},2,{operation:us,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 Cm(r);return{probe:n,registered:o.registered,visibility:o.visibility}},aI=(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(`
398
+ `)},cI=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Iv(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await $m(t);return{kind:"ready",visibility:r}}catch(r){return d.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof Or?r.code:void 0}}},lI=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,uI=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=fd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=lm(i),l=r.length===1&&t.visibility!=="hide",u=Om();for(let p of r){let m=`${n}/${p}`;try{let{layout:g}=await Im({cwd:m,title:Dm({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Am(o,m)?a.orcaOpened.push({branch:p,layout:g}):a.orcaHidden.push({branch:p,path:m,fix:lI(s)})}catch(g){d.warn({error:g,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),g instanceof Or&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:g instanceof Or?g.code:void 0})}}return a},dI=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}`)}},Av=async e=>{await ls`mkdir -p ${e}`},pI=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Cr(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},mI=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await ls({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new f(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},fI=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")},gd=E({name:"worktrees-add",description:`Create local git worktrees under the worktrees directory and run "pnpm install" in each: release worktrees for open release branches ("versions" / all=true), or feature worktrees ("feature", optional "base") \u2014 each name becomes a feature/<name> branch at <root>-worktrees/feature/<name>, cut from origin/<base> (default dev, or the default branch of a repo without dev; main; or any release branch) with no upstream, or checked out as-is when the branch already exists locally or on origin. Mutates the local filesystem. When invoked via MCP, pass "versions" (comma-separated), all=true, or "feature" \u2014 the branch picker and "open in Cursor / GitHub Desktop / Orca" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls. With "orca" true each created worktree gets an Orca terminal tab laid out per "worktrees.orca.layout"; the result reports orcaOpened, orcaSkipped (with a reason) and orcaHidden (a worktree Orca's sidebar hides, with the UI steps to reveal it). An unregistered repo is registered in Orca first (orca repo add).`,inputSchema:{feature:M.string().optional().describe('Comma-separated feature names (e.g. "checkout-v2" or "feature/checkout-v2"); each becomes a feature/<name> worktree. Cannot be combined with "versions" or "all".'),base:M.string().optional().describe(`Base for NEW feature branches: "dev" (default; the repo's default branch when it has no dev), "main", or a release ref ("1.4.0", "release/v1.4.0", "release/<name>"). Not applied to a feature branch that already exists. Implies a feature run.`),all:M.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:M.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:M.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:M.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:M.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:M.array(M.object({branch:M.string(),base:M.string(),source:M.enum(bv)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:M.array(M.string()).describe("List of created git worktree branches"),count:M.number().describe("Number of git worktrees created"),orcaOpened:M.array(M.object({branch:M.string(),layout:M.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:M.array(M.object({branch:M.string(),reason:M.enum(QO),code:M.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:M.array(M.object({branch:M.string(),path:M.string(),fix:M.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:ua});import{z as Jt}from"zod";var da=async()=>{await W();let[e,t]=await Promise.all([me("release"),me("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await gI(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
398
399
 
399
- ${dI(r).join(`
400
+ ${hI(r).join(`
400
401
  `)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
401
402
 
402
403
  ${t.join(`
403
404
  `)}`),d.info(n.join(`
404
405
 
405
- `));let o={worktrees:r,count:r.length,features:t};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},uI=async e=>{let[t,r]=await Promise.all([F(),ae()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=K(o);if(!s)return[];let i=Y(s),a=n.get(o)||"regular",c=r.get(ne(s))||null;return[{version:i,type:a,description:c}]})},dI=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=yo(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},hd=E({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description, plus feature worktrees (feature/* branches). Read-only.",inputSchema:{},outputSchema:{worktrees:Gt.array(Gt.object({version:Gt.string().describe("Release version"),type:Gt.enum(["regular","hotfix"]).describe("Release type"),description:Gt.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:Gt.number().describe("Number of release worktrees"),features:Gt.array(Gt.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:da});import{z as We}from"zod";import pI from"node:fs/promises";import{$ as mI}from"zx";var Nv="remove this worktree",fI=2,gI=3,pa=async e=>{try{return await pI.realpath(e)}catch{return e}},Rr=(e,t)=>{throw new f(void 0,{operation:Nv,remediation:e,stderrExcerpt:t})},hI=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=yt([e]);return Tr(e)&&t?["--versions",t]:Rr("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`)},yI=async()=>{let e=await pa(await P()),t=await pa(await Re(e));e===t&&Rr("run --self from inside the worktree to remove, or name it with --feature / --versions","this is the main checkout, not a linked worktree");let r=null;for(let o of await qe(t))await pa(o.path)===e&&(r=o.branch);if(!r)return Rr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await pa(`${t}${ue}/${r}`);return n!==e&&Rr("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:hI(r)}},Dv=async e=>(await mI({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
406
- `).filter(r=>r.trim().length>0),vI=async e=>{let[t,r]=await Promise.all([Dv(e.worktreePath),Dv(e.mainRoot)]);t.length>0&&Rr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Rr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Tt();n!=="ready"&&Rr(`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},wI=async e=>{let t=Ie(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${fI}; ${t} && { sleep ${gI}; exit; }`;try{return(await Pm(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Ar?new f(n,{operation:Nv,remediation:`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},_v=async e=>{let t=await yI();await vI(t),h.addOption("--self",!0),await L(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||h.addOption("--yes",!0);let r=await wI(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),h.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:k(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var kI=e=>{if(ve()){if(e.all)throw new C({status:"refused",agentMode:_.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions&&!e.feature)throw new C({status:"argument_required",argument:"versions",agentMode:_.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},bI=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},RI=async(e,t)=>{let r=await Ms(t.map(n=>`${e}/${n}`));if(r!==null)throw new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},SI=e=>e?e.split(",").map(t=>we(me(t.trim()))):[],EI=e=>e?e.split(",").filter(t=>t.trim()!=="").map(la):[],PI=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",yt(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},ma=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new f(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return _v(t)}await xe({operation:"remove worktrees"}),await W(),kI({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([fe("release"),fe("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),h.print();let y={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(y,null,2)),structuredContent:y}}let l=await P(),u=`${l}${ue}`,p=[];if(r)p=c;else if(n||o)p=[...SI(n),...EI(o)];else{h.setInteractive();let[y,b]=await Promise.all([ae(),F()]),w=new Map(b.map(x=>[x.branch,x.type]));p=await _t([...ce({branches:i,descriptions:y,types:w}),...a.map(x=>({value:x,label:x,type:"feature"}))],{required:!0})}bI(p,c);let m=p.length===c.length;m?h.addOption("--all",!0):PI(p),await RI(u,p),await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let g=await yr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Wo(g),h.print(),Go({result:g,operation:"remove worktrees"})}catch(i){throw Se(i)||i instanceof f?i:(d.error({error:i},"\u274C Error managing worktrees"),new f(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},yd=E({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches ("versions") and/or feature branches ("feature"). Over MCP you MUST pass "versions" or "feature" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named target must be an active worktree, or the call errors without removing anything. What survives: the release and feature branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically. Every Orca terminal open in a removed worktree is closed first; a call made from an Orca terminal INSIDE one of the targets is refused (orca_caller_inside_target) before anything is removed \u2014 re-run it from a terminal that is not an Orca pane of that worktree.',requiresHumanConfirm:!0,inputSchema:{versions:We.string().optional().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). This or "feature" is required: each must name an active worktree, or the call errors before removing anything.'),feature:We.string().optional().describe('Comma-separated feature names to remove (e.g. "checkout-v2" or "feature/checkout-v2"). This or "versions" is required; each must name an active feature worktree.'),confirm:We.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:We.array(We.string()).describe("List of removed git worktree branches"),failedWorktrees:We.array(We.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:We.number().describe("Number of git worktrees removed"),handedOff:We.object({branch:We.string(),worktreePath:We.string(),terminal:We.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:ma});import{z as ds}from"zod";var fa=async e=>{let{confirmedCommand:t}=e;await xe({operation:"sync worktrees"}),await W();try{let r=await fe("release"),n=await P(),o=`${n}${ue}`,s=await ti();await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=xI({releasePRsList:s,currentWorktrees:r}),a=await yr({branches:i,worktreeDir:o,projectRoot:n});return Wo(a),h.print(),Go({result:a,operation:"sync worktrees"})}catch(r){throw Se(r)||r instanceof f?r:(d.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},xI=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Tr(s)).filter(s=>!t.includes(s))}},vd=E({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:ds.array(ds.string()).describe("List of removed worktree branches"),failedWorktrees:ds.array(ds.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ds.number().describe("Number of worktrees removed during sync")},handler:fa});var wd=[{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:Wc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:ou,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:du,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Cu,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Vu,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Gu,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Pu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Tu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:fu,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Hu,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:ju,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Fu,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:gd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:hd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:vd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:au,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Fm,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Za,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:iu,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:cu,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Uc,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:ud,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","sync"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:td,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Kl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Fc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:dd,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:"environment",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]}];var kd=e=>pr.filter(t=>t.menuGroup===e),bd=e=>pr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var TI=(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},Mv=e=>wd.flatMap(({key:t,label:r})=>kd(t).flatMap(n=>{let o=TI(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Rd from"node:process";var CI="MODULE_TYPELESS_PACKAGE_JSON",$I=(e,t)=>typeof e=="object"&&e!==null?e.code:t,jv=!1,Sd=()=>{if(jv)return;jv=!0;let e=Rd.emitWarning.bind(Rd);Rd.emitWarning=((t,...r)=>{$I(r[0],r[1])!==CI&&e(t,...r)})};import{Command as SN,InvalidArgumentError as EN,Option as Nw}from"commander";import{resolve as PN}from"node:path";import $e from"node:process";import{cd as xN}from"zx";import Fv from"node:process";import{$ as AI}from"zx";var Ed=async()=>{let e=await H(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await z(i.path)}))),r=t.at(-1)?.exists===!0,n=await To(e.userProject,r),o=r?Co(n):"";d.info(`Project name: ${e.projectName}
406
+ `));let o={worktrees:r,count:r.length,features:t};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},gI=async e=>{let[t,r]=await Promise.all([F(),ae()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=H(o);if(!s)return[];let i=z(s),a=n.get(o)||"regular",c=r.get(ne(s))||null;return[{version:i,type:a,description:c}]})},hI=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=yo(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},hd=E({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description, plus feature worktrees (feature/* branches). Read-only.",inputSchema:{},outputSchema:{worktrees:Jt.array(Jt.object({version:Jt.string().describe("Release version"),type:Jt.enum(["regular","hotfix"]).describe("Release type"),description:Jt.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:Jt.number().describe("Number of release worktrees"),features:Jt.array(Jt.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:da});import{z as We}from"zod";import yI from"node:fs/promises";import{$ as vI}from"zx";var Nv="remove this worktree",wI=2,kI=3,pa=async e=>{try{return await yI.realpath(e)}catch{return e}},Sr=(e,t)=>{throw new f(void 0,{operation:Nv,remediation:e,stderrExcerpt:t})},bI=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=yt([e]);return Cr(e)&&t?["--versions",t]:Sr("only feature/* and release worktrees created by `infra-kit worktrees add` can be removed with --self",`branch ${e} is neither a feature nor a release branch`)},RI=async()=>{let e=await pa(await P()),t=await pa(await Re(e));e===t&&Sr("run --self from inside the worktree to remove, or name it with --feature / --versions","this is the main checkout, not a linked worktree");let r=null;for(let o of await qe(t))await pa(o.path)===e&&(r=o.branch);if(!r)return Sr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await pa(`${t}${le}/${r}`);return n!==e&&Sr("remove it with `git worktree remove` from the main checkout",`${e} is not an infra-kit worktree (expected ${n})`),{worktreePath:e,mainRoot:t,branch:r,targetArgs:bI(r)}},Dv=async e=>(await vI({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
407
+ `).filter(r=>r.trim().length>0),SI=async e=>{let[t,r]=await Promise.all([Dv(e.worktreePath),Dv(e.mainRoot)]);t.length>0&&Sr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Sr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Tt();n!=="ready"&&Sr(`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},EI=async e=>{let t=Ie(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${wI}; ${t} && { sleep ${kI}; exit; }`;try{return(await Pm(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Or?new f(n,{operation:Nv,remediation:`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},_v=async e=>{let t=await RI();await SI(t),h.addOption("--self",!0),await L(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||h.addOption("--yes",!0);let r=await EI(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),h.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:k(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var PI=e=>{if(ve()){if(e.all)throw new C({status:"refused",agentMode:_.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions&&!e.feature)throw new C({status:"argument_required",argument:"versions",agentMode:_.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},xI=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},TI=async(e,t)=>{let r=await Ms(t.map(n=>`${e}/${n}`));if(r!==null)throw new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},CI=e=>e?e.split(",").map(t=>we(pe(t.trim()))):[],$I=e=>e?e.split(",").filter(t=>t.trim()!=="").map(la):[],AI=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",yt(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},ma=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new f(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return _v(t)}await xe({operation:"remove worktrees"}),await W(),PI({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([me("release"),me("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),h.print();let y={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(y,null,2)),structuredContent:y}}let l=await P(),u=`${l}${le}`,p=[];if(r)p=c;else if(n||o)p=[...CI(n),...$I(o)];else{h.setInteractive();let[y,b]=await Promise.all([ae(),F()]),w=new Map(b.map(x=>[x.branch,x.type]));p=await Mt([...ce({branches:i,descriptions:y,types:w}),...a.map(x=>({value:x,label:x,type:"feature"}))],{required:!0})}xI(p,c);let m=p.length===c.length;m?h.addOption("--all",!0):AI(p),await TI(u,p),await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let g=await vr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Wo(g),h.print(),Go({result:g,operation:"remove worktrees"})}catch(i){throw Se(i)||i instanceof f?i:(d.error({error:i},"\u274C Error managing worktrees"),new f(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},yd=E({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches ("versions") and/or feature branches ("feature"). Over MCP you MUST pass "versions" or "feature" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named target must be an active worktree, or the call errors without removing anything. What survives: the release and feature branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically. Every Orca terminal open in a removed worktree is closed first; a call made from an Orca terminal INSIDE one of the targets is refused (orca_caller_inside_target) before anything is removed \u2014 re-run it from a terminal that is not an Orca pane of that worktree.',requiresHumanConfirm:!0,inputSchema:{versions:We.string().optional().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). This or "feature" is required: each must name an active worktree, or the call errors before removing anything.'),feature:We.string().optional().describe('Comma-separated feature names to remove (e.g. "checkout-v2" or "feature/checkout-v2"). This or "versions" is required; each must name an active feature worktree.'),confirm:We.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:We.array(We.string()).describe("List of removed git worktree branches"),failedWorktrees:We.array(We.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:We.number().describe("Number of git worktrees removed"),handedOff:We.object({branch:We.string(),worktreePath:We.string(),terminal:We.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:ma});import{z as ds}from"zod";var fa=async e=>{let{confirmedCommand:t}=e;await xe({operation:"sync worktrees"}),await W();try{let r=await me("release"),n=await P(),o=`${n}${le}`,s=await ti();await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=OI({releasePRsList:s,currentWorktrees:r}),a=await vr({branches:i,worktreeDir:o,projectRoot:n});return Wo(a),h.print(),Go({result:a,operation:"sync worktrees"})}catch(r){throw Se(r)||r instanceof f?r:(d.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},OI=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Cr(s)).filter(s=>!t.includes(s))}},vd=E({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:ds.array(ds.string()).describe("List of removed worktree branches"),failedWorktrees:ds.array(ds.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ds.number().describe("Number of worktrees removed during sync")},handler:fa});var wd=[{key:"develop",label:"Develop"},{key:"release",label:"Release Management"},{key:"worktrees",label:"Worktrees"},{key:"environment",label:"Environment"},{key:"configuration",label:"Configuration"},{key:"vendor",label:"Vendor"},{key:"setup",label:"Setup & Diagnostics"}],mr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Wc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:ou,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:du,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Cu,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Vu,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Gu,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Pu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Tu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:fu,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Hu,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:ju,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Fu,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:gd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:hd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:vd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:au,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Fm,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Za,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:iu,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:cu,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Uc,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:ud,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","sync"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:td,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Kl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Fc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:dd,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:"environment",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]}];var kd=e=>mr.filter(t=>t.menuGroup===e),bd=e=>mr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var II=(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},Mv=e=>wd.flatMap(({key:t,label:r})=>kd(t).flatMap(n=>{let o=II(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Rd from"node:process";var DI="MODULE_TYPELESS_PACKAGE_JSON",NI=(e,t)=>typeof e=="object"&&e!==null?e.code:t,jv=!1,Sd=()=>{if(jv)return;jv=!0;let e=Rd.emitWarning.bind(Rd);Rd.emitWarning=((t,...r)=>{NI(r[0],r[1])!==DI&&e(t,...r)})};import{Command as CN,InvalidArgumentError as $N,Option as Nw}from"commander";import{resolve as AN}from"node:path";import $e from"node:process";import{cd as ON}from"zx";import Fv from"node:process";import{$ as _I}from"zx";var Ed=async()=>{let e=await q(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await X(i.path)}))),r=t.at(-1)?.exists===!0,n=await To(e.userProject,r),o=r?Co(n):"";d.info(`Project name: ${e.projectName}
407
408
  `),d.info(`Config merge chain (later overrides earlier):
408
- `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${v(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Pd=async()=>{let e=await H(),t=Fv.env.EDITOR||Fv.env.VISUAL||"vi",r=await nn(e);r.createdConfig&&d.info(on(r)),d.info(`Opening ${v(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await AI({stdio:"inherit"})`${t} ${e.userProject}`,Et();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var xd=async({key:e,global:t})=>{Xs(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Zs(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${oo[r]} (${v(n)})`:`${e} is not set in the ${oo[r]} (${v(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}};import{DEPLOY_CONFIG_FILE as Dd}from"@slip-stream-kit/config/internal";import Nd from"node:fs/promises";import Jv from"node:path";import{DEPLOY_CONFIG_FILE as Td,deployConfigSchema as OI}from"@slip-stream-kit/config/internal";import II from"node:fs/promises";import DI from"node:path";import{pathToFileURL as NI}from"node:url";import{z as _I}from"zod";var Cd=async e=>{let t=DI.join(e,Td);try{await II.access(t)}catch{return}let r=await import(NI(t).href);if(r.default===void 0)throw new Error(`${Td} at ${t} has no default export`);let n=OI.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${Td} at ${t}:
409
- ${_I.prettifyError(n.error)}`);return n.data};var Uv="ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@3f50266774b5dac9b7f8fe18f2dd652b692f33df";var Od="skip_terraform_deploy",Ad={all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all",v1File:"deploy-all.yml"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected",v1File:"deploy-selected-services.yml"}},Vv=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),MI=(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}]}),he=e=>`\${{ ${e} }}`,$d=e=>he(`secrets[format('{0}_${e}', inputs.environment)]`),jI=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),FI=(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)`),r.length>0&&n.push("!cancelled()",...jI(r)),n.length===0?void 0:he(n.join(" && "))},Wv=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],LI=e=>e===void 0?[]:[` if: ${e}`],Gv=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${he("github.ref")}`,` environment: ${he("inputs.environment")}`," secrets: inherit"],BI=(e,t)=>{let r=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],n=t.length===0?[]:[" extra-env: |",...t.map(o=>{let s=he(`secrets.${o}`);return` ${o}=${s}`})];return[` uses: ${Uv}`," with:",` environment: ${he("inputs.environment")}`,` ref: ${he("github.ref")}`,` service: ${e.name}`,...r," secrets:",` aws-access-key-id: ${$d("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${$d("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${$d("AWS_REGION")}`,` serverless-access-key: ${he("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${he("secrets.SLACK_TOKEN")}`,` slack-channel: ${he("secrets.SLACK_CHANNEL")}`,...n]},UI=(e,t,r,n)=>{let o=e.service.workflow===void 0?BI(e,n):Gv(e.service.workflow);return["",` deploy-${e.name}:`,...Wv(r),...LI(FI(e,t,r)),...o]},Lv=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],VI=(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?Lv(Od,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return Lv(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},WI=(e,t)=>{let{title:r,concurrency:n,v1File:o}=Ad[t],s=(e.terraform??[]).length>0?he(`inputs.${Od} && '' \u2014 skip TF'' || ''''`):"";return["# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts: edit that file and re-run the command,","# a hand edit here is overwritten.",`name: '${r}'`,`run-name: '${r} [${he("inputs.environment")}]${s}'`,"",`# Same group as ${o}, so a v1 run and a v2 run never deploy into one environment at once.`,"concurrency:",` group: ${n}-${he("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},GI=e=>{let t=he(`!inputs.${Od}`);return["",` ${Vv(e)}:`,` if: ${t}`,...Gv(e)]},JI=(e,t)=>[""," notify-success:",...Wv(t),` if: ${he("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],Bv=(e,t)=>{let r=MI(e,t),n=e.terraform??[],o=n.map(Vv),s=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(s>25)throw new Error(`${Ad[t].file} would need ${s} dispatch inputs; GitHub allows 25. Mark services \`deployAll: false\` or split them.`);let i=r.map(l=>`deploy-${l.name}`),c=`${[...WI(e,t),...VI(e,t,r),"","permissions:"," contents: read","","jobs:",...n.flatMap(GI),...r.flatMap(l=>UI(l,t,o,e.extraEnv??[])),...e.notifySuccess===void 0?[]:JI(e.notifySuccess,i)].join(`
409
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${v(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Pd=async()=>{let e=await q(),t=Fv.env.EDITOR||Fv.env.VISUAL||"vi",r=await nn(e);r.createdConfig&&d.info(on(r)),d.info(`Opening ${v(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await _I({stdio:"inherit"})`${t} ${e.userProject}`,Et();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var xd=async({key:e,global:t})=>{Xs(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Zs(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${oo[r]} (${v(n)})`:`${e} is not set in the ${oo[r]} (${v(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}};import{DEPLOY_CONFIG_FILE as Dd}from"@slip-stream-kit/config/internal";import Nd from"node:fs/promises";import Jv from"node:path";import{DEPLOY_CONFIG_FILE as Td,deployConfigSchema as MI}from"@slip-stream-kit/config/internal";import jI from"node:fs/promises";import FI from"node:path";import{pathToFileURL as LI}from"node:url";import{z as BI}from"zod";var Cd=async e=>{let t=FI.join(e,Td);try{await jI.access(t)}catch{return}let r=await import(LI(t).href);if(r.default===void 0)throw new Error(`${Td} at ${t} has no default export`);let n=MI.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${Td} at ${t}:
410
+ ${BI.prettifyError(n.error)}`);return n.data};var Uv="ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@3f50266774b5dac9b7f8fe18f2dd652b692f33df";var Od="skip_terraform_deploy",Ad={all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all",v1File:"deploy-all.yml"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected",v1File:"deploy-selected-services.yml"}},Vv=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),UI=(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}]}),ge=e=>`\${{ ${e} }}`,$d=e=>ge(`secrets[format('{0}_${e}', inputs.environment)]`),VI=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),WI=(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)`),r.length>0&&n.push("!cancelled()",...VI(r)),n.length===0?void 0:ge(n.join(" && "))},Wv=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],GI=e=>e===void 0?[]:[` if: ${e}`],Gv=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${ge("github.ref")}`,` environment: ${ge("inputs.environment")}`," secrets: inherit"],JI=(e,t)=>{let r=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],n=t.length===0?[]:[" extra-env: |",...t.map(o=>{let s=ge(`secrets.${o}`);return` ${o}=${s}`})];return[` uses: ${Uv}`," with:",` environment: ${ge("inputs.environment")}`,` ref: ${ge("github.ref")}`,` service: ${e.name}`,...r," secrets:",` aws-access-key-id: ${$d("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${$d("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${$d("AWS_REGION")}`,` serverless-access-key: ${ge("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${ge("secrets.SLACK_TOKEN")}`,` slack-channel: ${ge("secrets.SLACK_CHANNEL")}`,...n]},KI=(e,t,r,n)=>{let o=e.service.workflow===void 0?JI(e,n):Gv(e.service.workflow);return["",` deploy-${e.name}:`,...Wv(r),...GI(WI(e,t,r)),...o]},Lv=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],HI=(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?Lv(Od,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return Lv(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},qI=(e,t)=>{let{title:r,concurrency:n,v1File:o}=Ad[t],s=(e.terraform??[]).length>0?ge(`inputs.${Od} && '' \u2014 skip TF'' || ''''`):"";return["# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts: edit that file and re-run the command,","# a hand edit here is overwritten.",`name: '${r}'`,`run-name: '${r} [${ge("inputs.environment")}]${s}'`,"",`# Same group as ${o}, so a v1 run and a v2 run never deploy into one environment at once.`,"concurrency:",` group: ${n}-${ge("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},YI=e=>{let t=ge(`!inputs.${Od}`);return["",` ${Vv(e)}:`,` if: ${t}`,...Gv(e)]},zI=(e,t)=>[""," notify-success:",...Wv(t),` if: ${ge("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],Bv=(e,t)=>{let r=UI(e,t),n=e.terraform??[],o=n.map(Vv),s=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(s>25)throw new Error(`${Ad[t].file} would need ${s} dispatch inputs; GitHub allows 25. Mark services \`deployAll: false\` or split them.`);let i=r.map(l=>`deploy-${l.name}`),c=`${[...qI(e,t),...HI(e,t,r),"","permissions:"," contents: read","","jobs:",...n.flatMap(YI),...r.flatMap(l=>KI(l,t,o,e.extraEnv??[])),...e.notifySuccess===void 0?[]:zI(e.notifySuccess,i)].join(`
410
411
  `).replace(`jobs:
411
412
 
412
413
  `,`jobs:
413
414
  `)}
414
- `;return{path:`.github/workflows/${Ad[t].file}`,content:c}},Id=e=>[Bv(e,"all"),Bv(e,"selected")];var KI=async e=>{try{return await Nd.readFile(e,"utf-8")}catch{return}},ga=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),_d=async(e={})=>{let t=e.cwd??await P(),r=await Cd(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Dd} at ${t}, nothing to generate.`),ga({status:"missing-config",ok:!!e.check,files:[]});let n=await Promise.all(Id(r).map(async i=>{let a=Jv.join(t,i.path),c=await KI(a),l="unchanged";return c===void 0?l="created":c!==i.content&&(l="updated"),{...i,absolute:a,status:l}})),o=n.filter(i=>i.status!=="unchanged"),s=n.map(({path:i,status:a})=>({path:i,status:a}));if(o.length===0)return d.info(`\u2705 Deploy workflows match ${Dd}.`),ga({status:"unchanged",ok:!0,files:s});if(e.check){d.error(`\u274C Deploy workflows differ from ${Dd}; run \`infra-kit deploy-sync\` and commit:`);for(let i of o)d.error(` ${i.path} (${i.status==="created"?"missing":"differs"})`);return ga({status:"drift",ok:!1,files:s})}for(let i of o)await Nd.mkdir(Jv.dirname(i.absolute),{recursive:!0}),await Nd.writeFile(i.absolute,i.content),d.info(`\u270F\uFE0F ${i.status==="created"?"Created":"Updated"} ${i.path}`);return ga({status:"written",ok:!0,files:s})};var Kv="https://dashboard.doppler.com/workplace/projects",HI=(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}"): ${Kv}/${e}`],Md=async({env:e})=>{let r=!!(await Je())?.envs[e];await wm(e);let n=await Xt(),o=await xt();r?d.info(`Removed the "${e}" service token from ${v(o)}.`):d.info(`No "${e}" service token was stored in ${v(o)} \u2014 nothing to remove.`);for(let i of HI(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Kv}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import qI from"@inquirer/confirm";import YI from"@inquirer/input";import zI from"@inquirer/password";import XI from"@inquirer/select";import ZI from"node:fs/promises";import lt from"node:process";import{$ as ha}from"zx";var QI=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Hv(),source:"stdin"};if(t){let n=lt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!lt.stdin.isTTY){let n=await Hv();if(n)return{token:n,source:"stdin"};if(!J())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return h.setInteractive(),{token:(await I(n=>zI({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:lt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Hv=async()=>{let e=[];lt.stdin.setEncoding("utf8");for await(let t of lt.stdin)e.push(t);return e.join("").trim()},jd="DOPPLER_CONFIG",eD=3e4,tD=async(e,t,r)=>{let n=ha.quiet;ha.quiet=!0;let o;try{o=(await ha({env:Vn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(eD)).stdout}catch(s){throw rD(s,r)}finally{ha.quiet=n}return Xa(o)},rD=(e,t)=>{let r=Gp(e)??(e instanceof Error?e.message:String(e));if(bm(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Rm(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(`
415
- `))},nD=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${jd}.`,"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(`
416
- `),Yv=async(e,t,r,n)=>{let o=await tD(e,t,r);za(o,r);let s=o.some(([i])=>i===jd);if(!s&&!n)throw new Error(nD(r));return s},qv="\0new-env",oD=async()=>{if(J()||!lt.stdin.isTTY)throw new C({status:"argument_required",argument:"env",agentMode:_.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([_m(),Je()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await I(s=>XI({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:qv}]},s),{output:lt.stderr,whenHeadless:"refuse"});return n!==qv?n:(await I(s=>YI({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:lt.stderr,whenHeadless:"refuse"})).trim()},sD=async(e,t,r)=>I(n=>qI({message:`Replace the "${e}" token ${ke(t)} with ${ke(r)}?`,default:!0},n),{output:lt.stderr,whenHeadless:"refuse"}),iD=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${ke(r)})`;case"replaced":return`Replaced the "${e}" service token ${ke(n??"")} \u2192 ${ke(r)}`;case"unchanged":return`The "${e}" service token is already ${ke(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${ke(n??"")} \u2014 nothing was written`;default:return Ne(t)}},Fd=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Xt(),s=e??await oD(),{token:i,source:a}=await QI({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Yv(i,o,s,n),l=(await Je())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await sD(s,l,i)?u="kept":(await Wa({[s]:i}),u=l===void 0?"stored":"replaced");let p=await xt();d.info(`${iD(s,u,i,l)} in ${v(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${jd} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:ke(i),previousRedactedToken:l===void 0?null:ke(l),storePath:p,scopeVerified:c};return h.print(),{content:k(JSON.stringify(m,null,2)),structuredContent:m}},aD=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,zv=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?aD(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},cD=e=>(e instanceof Error?e.message:String(e)).split(`
417
- `)[0]??"",lD=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",uD=async(e,t,r,n)=>{let o=ke(e.token);try{let s=await Yv(e.token,t,e.env,n);return{env:e.env,status:lD(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:cD(s)}}},Ld=async({fromFile:e,force:t})=>{let r=await Xt(),n=zv(await ZI.readFile(e,"utf8")),o=await Je(),s=await Promise.all(n.map(p=>uD(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 Wa(i);let a=await xt(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${v(e)} \u2192 ${v(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${v(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(lt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}};var Bd=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 Su(n);if(r&&h.addOption("--from",p),Ru(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Ui({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Vi({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Ud=async e=>Bd(e,"all"),Vd=async e=>Bd(e,"selected"),ya=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.`),Bd({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Zv}from"@slip-stream-kit/config/internal";import Wd from"node:fs/promises";import xn from"node:path";import Xv from"node:process";import{pathToFileURL as dD}from"node:url";var Qv="~/projects",Gd=async(e={})=>{if(e.init){await mD(e.cwd);return}await pD()},pD=async()=>{let e=un(),t=await z(e);if(d.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Xv.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await wi(),s=dn(r),i=await z(s),a=xn.join(s,n),c=await z(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=xn.join(s,u),m=await z(p);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";d.info(` ${g} ${u} ${v(p)}${y}`)}l||(Xv.exitCode=1)},mD=async e=>{let t=un();if(await z(t)){d.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await P(),n=await fD(r);await Wd.mkdir(xn.dirname(t),{recursive:!0}),await Wd.writeFile(t,gD(xn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${v(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${Zv}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${Qv}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${xn.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.")},fD=async e=>{try{let t=xn.join(e,Zv),r=await Wd.stat(t),s=(await import(`${dD(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[]},gD=(e,t)=>`${JSON.stringify({workspaceDir:Qv,source:e,targets:t},null,2)}
418
- `;import{existsSync as pN}from"node:fs";import mN from"node:fs/promises";import Rw from"node:path";import Sw from"node:process";import{z as fN}from"zod";import{chmodSync as SD,copyFileSync as ED,lstatSync as PD,mkdirSync as lw,readdirSync as xD,readlinkSync as TD,rmdirSync as uw,symlinkSync as CD,unlinkSync as $D,writeFileSync as AD}from"node:fs";import be from"node:path";import{lstatSync as hD,readlinkSync as ew}from"node:fs";import yD from"node:path";var vD=new Set(["ENOENT","ENOTDIR"]),va=e=>{let t;try{t=hD(e)}catch(r){if(vD.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:ew(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:br(e)}:{kind:"other"}},tw=(e,t)=>{let r=yD.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:ew(r)}:{kind:"file",executable:t.mode==="100755",sha:br(r)};return{...t,fingerprint:n}},rw=(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 wD}from"zx";var Z=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await wD({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},wa=e=>e.slice(0,7),Jt=e=>e.split("\0").filter(t=>t.length>0);import kD from"node:path";var Jd=`${X}/`,Kt=`${X}/README.md`,ps=`${X}/${Ve}`,ow=e=>e.startsWith(Jd),nw=e=>{let t=kD.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},sw=e=>{let t=nw(e.path),r=e.target===void 0?t:nw(e.target);return{path:t,target:r,vendored:ow(r)}},iw=e=>e.copy.map(sw),ms=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),fs=(e,t)=>e.filter(r=>!ms(r.path,t)),ka=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Tn=e=>[...new Set(e)].sort(),aw=e=>e.startsWith(Jd)?e.slice(Jd.length):null;var ba=e=>`# vendor/ \u2014 mirrored from ${e}
415
+ `;return{path:`.github/workflows/${Ad[t].file}`,content:c}},Id=e=>[Bv(e,"all"),Bv(e,"selected")];var XI=async e=>{try{return await Nd.readFile(e,"utf-8")}catch{return}},ga=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),_d=async(e={})=>{let t=e.cwd??await P(),r=await Cd(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Dd} at ${t}, nothing to generate.`),ga({status:"missing-config",ok:!!e.check,files:[]});let n=await Promise.all(Id(r).map(async i=>{let a=Jv.join(t,i.path),c=await XI(a),l="unchanged";return c===void 0?l="created":c!==i.content&&(l="updated"),{...i,absolute:a,status:l}})),o=n.filter(i=>i.status!=="unchanged"),s=n.map(({path:i,status:a})=>({path:i,status:a}));if(o.length===0)return d.info(`\u2705 Deploy workflows match ${Dd}.`),ga({status:"unchanged",ok:!0,files:s});if(e.check){d.error(`\u274C Deploy workflows differ from ${Dd}; run \`infra-kit deploy-sync\` and commit:`);for(let i of o)d.error(` ${i.path} (${i.status==="created"?"missing":"differs"})`);return ga({status:"drift",ok:!1,files:s})}for(let i of o)await Nd.mkdir(Jv.dirname(i.absolute),{recursive:!0}),await Nd.writeFile(i.absolute,i.content),d.info(`\u270F\uFE0F ${i.status==="created"?"Created":"Updated"} ${i.path}`);return ga({status:"written",ok:!0,files:s})};var Kv="https://dashboard.doppler.com/workplace/projects",ZI=(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}"): ${Kv}/${e}`],Md=async({env:e})=>{let r=!!(await Je())?.envs[e];await wm(e);let n=await Zt(),o=await xt();r?d.info(`Removed the "${e}" service token from ${v(o)}.`):d.info(`No "${e}" service token was stored in ${v(o)} \u2014 nothing to remove.`);for(let i of ZI(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Kv}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import QI from"@inquirer/confirm";import eD from"@inquirer/input";import tD from"@inquirer/password";import rD from"@inquirer/select";import nD from"node:fs/promises";import lt from"node:process";import{$ as ha}from"zx";var oD=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Hv(),source:"stdin"};if(t){let n=lt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!lt.stdin.isTTY){let n=await Hv();if(n)return{token:n,source:"stdin"};if(!K())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return h.setInteractive(),{token:(await I(n=>tD({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:lt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Hv=async()=>{let e=[];lt.stdin.setEncoding("utf8");for await(let t of lt.stdin)e.push(t);return e.join("").trim()},jd="DOPPLER_CONFIG",sD=3e4,iD=async(e,t,r)=>{let n=ha.quiet;ha.quiet=!0;let o;try{o=(await ha({env:Vn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(sD)).stdout}catch(s){throw aD(s,r)}finally{ha.quiet=n}return Xa(o)},aD=(e,t)=>{let r=Gp(e)??(e instanceof Error?e.message:String(e));if(bm(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Rm(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(`
416
+ `))},cD=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${jd}.`,"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(`
417
+ `),Yv=async(e,t,r,n)=>{let o=await iD(e,t,r);za(o,r);let s=o.some(([i])=>i===jd);if(!s&&!n)throw new Error(cD(r));return s},qv="\0new-env",lD=async()=>{if(K()||!lt.stdin.isTTY)throw new C({status:"argument_required",argument:"env",agentMode:_.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([_m(),Je()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await I(s=>rD({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:qv}]},s),{output:lt.stderr,whenHeadless:"refuse"});return n!==qv?n:(await I(s=>eD({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:lt.stderr,whenHeadless:"refuse"})).trim()},uD=async(e,t,r)=>I(n=>QI({message:`Replace the "${e}" token ${ke(t)} with ${ke(r)}?`,default:!0},n),{output:lt.stderr,whenHeadless:"refuse"}),dD=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${ke(r)})`;case"replaced":return`Replaced the "${e}" service token ${ke(n??"")} \u2192 ${ke(r)}`;case"unchanged":return`The "${e}" service token is already ${ke(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${ke(n??"")} \u2014 nothing was written`;default:return Ne(t)}},Fd=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Zt(),s=e??await lD(),{token:i,source:a}=await oD({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Yv(i,o,s,n),l=(await Je())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await uD(s,l,i)?u="kept":(await Wa({[s]:i}),u=l===void 0?"stored":"replaced");let p=await xt();d.info(`${dD(s,u,i,l)} in ${v(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${jd} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:ke(i),previousRedactedToken:l===void 0?null:ke(l),storePath:p,scopeVerified:c};return h.print(),{content:k(JSON.stringify(m,null,2)),structuredContent:m}},pD=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,zv=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?pD(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},mD=e=>(e instanceof Error?e.message:String(e)).split(`
418
+ `)[0]??"",fD=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",gD=async(e,t,r,n)=>{let o=ke(e.token);try{let s=await Yv(e.token,t,e.env,n);return{env:e.env,status:fD(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:mD(s)}}},Ld=async({fromFile:e,force:t})=>{let r=await Zt(),n=zv(await nD.readFile(e,"utf8")),o=await Je(),s=await Promise.all(n.map(p=>gD(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 Wa(i);let a=await xt(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${v(e)} \u2192 ${v(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${v(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(lt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}};var Bd=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 Su(n);if(r&&h.addOption("--from",p),Ru(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Ui({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Vi({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Ud=async e=>Bd(e,"all"),Vd=async e=>Bd(e,"selected"),ya=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.`),Bd({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Zv}from"@slip-stream-kit/config/internal";import Wd from"node:fs/promises";import xn from"node:path";import Xv from"node:process";import{pathToFileURL as hD}from"node:url";var Qv="~/projects",Gd=async(e={})=>{if(e.init){await vD(e.cwd);return}await yD()},yD=async()=>{let e=un(),t=await X(e);if(d.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Xv.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await wi(),s=dn(r),i=await X(s),a=xn.join(s,n),c=await X(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=xn.join(s,u),m=await X(p);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";d.info(` ${g} ${u} ${v(p)}${y}`)}l||(Xv.exitCode=1)},vD=async e=>{let t=un();if(await X(t)){d.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await P(),n=await wD(r);await Wd.mkdir(xn.dirname(t),{recursive:!0}),await Wd.writeFile(t,kD(xn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${v(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${Zv}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${Qv}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${xn.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.")},wD=async e=>{try{let t=xn.join(e,Zv),r=await Wd.stat(t),s=(await import(`${hD(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[]},kD=(e,t)=>`${JSON.stringify({workspaceDir:Qv,source:e,targets:t},null,2)}
419
+ `;import{existsSync as yN}from"node:fs";import vN from"node:fs/promises";import Rw from"node:path";import Sw from"node:process";import{z as wN}from"zod";import{chmodSync as CD,copyFileSync as $D,lstatSync as AD,mkdirSync as lw,readdirSync as OD,readlinkSync as ID,rmdirSync as uw,symlinkSync as DD,unlinkSync as ND,writeFileSync as _D}from"node:fs";import be from"node:path";import{lstatSync as bD,readlinkSync as ew}from"node:fs";import RD from"node:path";var SD=new Set(["ENOENT","ENOTDIR"]),va=e=>{let t;try{t=bD(e)}catch(r){if(SD.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:ew(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Rr(e)}:{kind:"other"}},tw=(e,t)=>{let r=RD.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:ew(r)}:{kind:"file",executable:t.mode==="100755",sha:Rr(r)};return{...t,fingerprint:n}},rw=(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 ED}from"zx";var Q=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await ED({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},wa=e=>e.slice(0,7),Kt=e=>e.split("\0").filter(t=>t.length>0);import PD from"node:path";var Jd=`${Z}/`,Ht=`${Z}/README.md`,ps=`${Z}/${Ve}`,ow=e=>e.startsWith(Jd),nw=e=>{let t=PD.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},sw=e=>{let t=nw(e.path),r=e.target===void 0?t:nw(e.target);return{path:t,target:r,vendored:ow(r)}},iw=e=>e.copy.map(sw),ms=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),fs=(e,t)=>e.filter(r=>!ms(r.path,t)),ka=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Tn=e=>[...new Set(e)].sort(),aw=e=>e.startsWith(Jd)?e.slice(Jd.length):null;var ba=e=>`# vendor/ \u2014 mirrored from ${e}
419
420
 
420
421
  **DO NOT EDIT files in this folder here.**
421
422
 
@@ -426,19 +427,19 @@ fail \`ik vendor check\` in CI.
426
427
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
427
428
 
428
429
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
429
- `;var bD=new Set(["100644","100755","120000"]),RD=(e,t)=>{let r=new Map;for(let n of Jt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!bD.has(s)||ms(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},Kd=async(e,t,r)=>{let n=await Z(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return RD(n,r)},cw=async e=>Jt(await Z(e,["--literal-pathspecs","ls-files","-z","--",X]));var Cn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],dw=e=>{let t=va(e);t!==null&&(t.kind==="other"?uw(e):$D(e))},OD=(e,t,r)=>{let n=be.join(e,r.source),o=be.join(t,r.target);if(lw(be.dirname(o),{recursive:!0}),dw(o),r.mode==="120000"){CD(TD(n),o);return}ED(n,o),SD(o,r.mode==="100755"?493:420)},ID=async(e,t)=>{let r=new Set;for(let n of Jt(await Z(e,["ls-files","-z"]))){if(t.has(n))continue;let o=be.posix.dirname(n);for(;o!==".";)r.add(o),o=be.posix.dirname(o)}return r},DD=async(e,t)=>{if(t.length===0)return;let r=await ID(e,new Set(t)),n=[...new Set(t.map(o=>be.dirname(be.join(e,o))))];n.sort((o,s)=>s.length-o.length);for(let o of n){let s=o;for(;s!==e&&s.startsWith(e)&&!(!PD(s,{throwIfNoEntry:!1})?.isDirectory()||xD(s).length>0||r.has(be.relative(e,s).split(be.sep).join("/")));)uw(s),s=be.dirname(s)}},pw=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Kt,...s].map(aw).filter(a=>a!==null&&!na(a));return Tn(i)},mw=async(e,t,r,n)=>{let o=be.join(e,X);lw(o,{recursive:!0}),AD(be.join(e,Kt),ba(t.name));let s=pw(r,await cw(e),n);id(o,{source:t.name,commit:t.headSha},s)},Hd=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Cn(t));let n=be.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)dw(be.join(n,a));await DD(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)OD(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await mw(n,e,t.entries,o),{touched:Tn([...o,...i,Kt,ps]),manifestWritten:!0}):{touched:Tn([...o,...i]),manifestWritten:!1}},qd=async(e,t)=>(await mw(e,t,[],[]),[Kt,ps]);var Yd=(e,t)=>`[ROOT] vendor: sync from ${e}@${wa(t)}`,ND=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
430
- `).trim()||String(e)},zd=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Z(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Z(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:ND(s)}}};var _D=20,MD=20,fw=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],gw=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of fs(e.files,r)){let p=ka(u.path,n);if(s.push(p),rw(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=fs(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}}},gs=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Xd=e=>e.entries.map(t=>t.entry.target),jD=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...Xd(e)];return gs(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...fw(r,_D),Ie(n)])},FD=(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=wa(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}`,...fw(e.lines,MD)],warnings:[]}},LD=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},BD=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},UD=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Tn([...n,...r?t.headVendorMeta:[]])},VD=(e,t)=>{if(t.dirty.length>0)return jD(e,t,t.dirty);let r=e.entries.map((u,p)=>{let m=t.entries[p]??{target:u.entry.target,tracked:[],onDisk:{}};return gw(u,m,e.exclude)}),n=r.some(u=>u.vendored),o=r.some(u=>u.writes.length+u.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...gs(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=FD(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(LD).filter(u=>u!==null);return{...i,status:"changed",message:`${BD(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:UD(r,t,n)}},Ra=(e,t)=>{switch(t.kind){case"missing":return gs(t,"skipped",`not checked out at ${t.root}`);case"source":return gs(t,"skipped","this is the source repo");case"not-git":return gs(t,"fail",`not a git repo: ${t.reason}`);case"repo":return VD(e,t)}};import{existsSync as WD,readFileSync as GD,realpathSync as Sa}from"node:fs";import Ea from"node:path";var Zd=async(e,t)=>{let r=t.exclude??[],n=(await Z(e,["rev-parse","HEAD"])).trim(),o=await Re(e),s=await Promise.all(iw(t).map(async i=>{let a=await Kd(e,i.path,r);return{entry:i,files:a.map(c=>tw(e,c))}}));return{root:e,selfRoots:[...new Set([Sa(e),Sa(o)])],name:Ea.basename(o),headSha:n,entries:s,exclude:r}},Pa=e=>{let t=Jt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},JD=async(e,t)=>{let r=await Z(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...Xd(e)]);return Pa(r).filter(n=>!ms(n,e.exclude))},KD=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await Kd(t,r.target,e.exclude),s={};for(let i of fs(n,e.exclude)){let a=ka(i.path,r);s[a]=va(Ea.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),HD=async e=>{try{return Jt(await Z(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Kt,ps]))}catch{return[]}},qD=e=>{try{let{commit:t,source:r}=is(Ea.join(e,X));return{commit:t,source:r}}catch{return null}},YD=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await De(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await Z(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
431
- `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},zD=(e,t)=>{try{return GD(Ea.join(e,Kt),"utf8")===ba(t)}catch{return!1}},XD=async e=>{try{return{toplevel:(await Z(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
432
- `)[0]??"git rev-parse failed"}}},ZD=async e=>{try{return(await Z(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},xa=async(e,t)=>{if(!WD(t.root))return{...t,kind:"missing"};let r=Sa(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await XD(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Sa(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=qD(t.root),s=o?.commit??null,[i,a,c,l,u]=await Promise.all([ZD(t.root),JD(e,t.root),KD(e,t.root),HD(t.root),YD(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:zD(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:u}};var QD=20,eN=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],tN=(e,t)=>{let{plan:r}=e,n=t.manifestOnly?"manifest":"sync";if(e.error!==void 0)return{name:n,status:"fail",message:`apply failed: ${e.error}`,notes:["restore the tracked paths with:",Ie(Cn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:eN(r,t)}},rN=e=>e.ok?{name:"commit",status:"ok",message:"committed the synced paths"}:{name:"commit",status:"fail",message:"git refused the commit; the files stay written",notes:e.output.split(`
433
- `).slice(0,QD)},nN=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[tN(e,t),...r,...e.commit?[rN(e.commit)]:[]]}},oN={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},Qd=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:oN[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>nN(o,r))],hints:n}},hw=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),yw=(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 sN=20,ep=async(e,t)=>(await Z(e,t,{allowFailure:!0})).trim(),iN=async e=>Pa(await Z(e,["status","--porcelain","-z","--untracked-files=normal"])),aN=async e=>(await ep(e,["for-each-ref","--contains","HEAD","--format=%(refname)","refs/remotes/origin/"])).length>0?null:{name:"HEAD pushed",status:"warn",message:"HEAD is on no origin/* ref, so every target will record a commit nobody else can resolve",notes:["git push"]},cN=async e=>{let[t,r]=await Promise.all([ep(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),ep(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}`}},vw=async e=>{let t=await iN(e);if(t.length>0){let n=t.slice(0,sN),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new C({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([aN(e),cN(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import lN from"node:path";var ww=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new C({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=dn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:lN.join(n,s)}))},uN="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",dN=async(e,t)=>{let r=await xa(e,t),n=Ra(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${uN} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},kw=async(e,t,r)=>Promise.all(t.map(async n=>r?dN(e,n):Ra(e,await xa(e,n))));var Ew="sync vendored files",gN=e=>{let t=Rw.join(dn(e.workspaceDir),e.source);if(pN(t))return t;throw new C({status:"refused",reason:"source-missing",source:t},1,{operation:Ew,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'})},tp=(e,t)=>new C({status:"refused",reason:"not-a-vendor-source"},1,{operation:Ew,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`}),hN=async e=>{let t=Rw.join(e,"infra-kit.json"),r;try{r=JSON.parse(await mN.readFile(t,"utf8"))}catch(s){throw tp(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw tp(t,"has no vendorSource block");let o=im.safeParse(n);if(!o.success)throw tp(t,`has an invalid vendorSource: ${fN.prettifyError(o.error)}`);return o.data},bw=(e,t)=>{Sw.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
430
+ `;var xD=new Set(["100644","100755","120000"]),TD=(e,t)=>{let r=new Map;for(let n of Kt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!xD.has(s)||ms(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},Kd=async(e,t,r)=>{let n=await Q(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return TD(n,r)},cw=async e=>Kt(await Q(e,["--literal-pathspecs","ls-files","-z","--",Z]));var Cn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],dw=e=>{let t=va(e);t!==null&&(t.kind==="other"?uw(e):ND(e))},MD=(e,t,r)=>{let n=be.join(e,r.source),o=be.join(t,r.target);if(lw(be.dirname(o),{recursive:!0}),dw(o),r.mode==="120000"){DD(ID(n),o);return}$D(n,o),CD(o,r.mode==="100755"?493:420)},jD=async(e,t)=>{let r=new Set;for(let n of Kt(await Q(e,["ls-files","-z"]))){if(t.has(n))continue;let o=be.posix.dirname(n);for(;o!==".";)r.add(o),o=be.posix.dirname(o)}return r},FD=async(e,t)=>{if(t.length===0)return;let r=await jD(e,new Set(t)),n=[...new Set(t.map(o=>be.dirname(be.join(e,o))))];n.sort((o,s)=>s.length-o.length);for(let o of n){let s=o;for(;s!==e&&s.startsWith(e)&&!(!AD(s,{throwIfNoEntry:!1})?.isDirectory()||OD(s).length>0||r.has(be.relative(e,s).split(be.sep).join("/")));)uw(s),s=be.dirname(s)}},pw=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Ht,...s].map(aw).filter(a=>a!==null&&!na(a));return Tn(i)},mw=async(e,t,r,n)=>{let o=be.join(e,Z);lw(o,{recursive:!0}),_D(be.join(e,Ht),ba(t.name));let s=pw(r,await cw(e),n);id(o,{source:t.name,commit:t.headSha},s)},Hd=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Cn(t));let n=be.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)dw(be.join(n,a));await FD(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)MD(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await mw(n,e,t.entries,o),{touched:Tn([...o,...i,Ht,ps]),manifestWritten:!0}):{touched:Tn([...o,...i]),manifestWritten:!1}},qd=async(e,t)=>(await mw(e,t,[],[]),[Ht,ps]);var Yd=(e,t)=>`[ROOT] vendor: sync from ${e}@${wa(t)}`,LD=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
431
+ `).trim()||String(e)},zd=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Q(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Q(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:LD(s)}}};var BD=20,UD=20,fw=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],gw=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of fs(e.files,r)){let p=ka(u.path,n);if(s.push(p),rw(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=fs(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}}},gs=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Xd=e=>e.entries.map(t=>t.entry.target),VD=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...Xd(e)];return gs(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...fw(r,BD),Ie(n)])},WD=(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=wa(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}`,...fw(e.lines,UD)],warnings:[]}},GD=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},JD=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},KD=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Tn([...n,...r?t.headVendorMeta:[]])},HD=(e,t)=>{if(t.dirty.length>0)return VD(e,t,t.dirty);let r=e.entries.map((u,p)=>{let m=t.entries[p]??{target:u.entry.target,tracked:[],onDisk:{}};return gw(u,m,e.exclude)}),n=r.some(u=>u.vendored),o=r.some(u=>u.writes.length+u.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...gs(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=WD(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(GD).filter(u=>u!==null);return{...i,status:"changed",message:`${JD(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:KD(r,t,n)}},Ra=(e,t)=>{switch(t.kind){case"missing":return gs(t,"skipped",`not checked out at ${t.root}`);case"source":return gs(t,"skipped","this is the source repo");case"not-git":return gs(t,"fail",`not a git repo: ${t.reason}`);case"repo":return HD(e,t)}};import{existsSync as qD,readFileSync as YD,realpathSync as Sa}from"node:fs";import Ea from"node:path";var Zd=async(e,t)=>{let r=t.exclude??[],n=(await Q(e,["rev-parse","HEAD"])).trim(),o=await Re(e),s=await Promise.all(iw(t).map(async i=>{let a=await Kd(e,i.path,r);return{entry:i,files:a.map(c=>tw(e,c))}}));return{root:e,selfRoots:[...new Set([Sa(e),Sa(o)])],name:Ea.basename(o),headSha:n,entries:s,exclude:r}},Pa=e=>{let t=Kt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},zD=async(e,t)=>{let r=await Q(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...Xd(e)]);return Pa(r).filter(n=>!ms(n,e.exclude))},XD=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await Kd(t,r.target,e.exclude),s={};for(let i of fs(n,e.exclude)){let a=ka(i.path,r);s[a]=va(Ea.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),ZD=async e=>{try{return Kt(await Q(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Ht,ps]))}catch{return[]}},QD=e=>{try{let{commit:t,source:r}=is(Ea.join(e,Z));return{commit:t,source:r}}catch{return null}},eN=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await De(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await Q(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
432
+ `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},tN=(e,t)=>{try{return YD(Ea.join(e,Ht),"utf8")===ba(t)}catch{return!1}},rN=async e=>{try{return{toplevel:(await Q(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
433
+ `)[0]??"git rev-parse failed"}}},nN=async e=>{try{return(await Q(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},xa=async(e,t)=>{if(!qD(t.root))return{...t,kind:"missing"};let r=Sa(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await rN(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Sa(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=QD(t.root),s=o?.commit??null,[i,a,c,l,u]=await Promise.all([nN(t.root),zD(e,t.root),XD(e,t.root),ZD(t.root),eN(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:tN(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:u}};var oN=20,sN=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],iN=(e,t)=>{let{plan:r}=e,n=t.manifestOnly?"manifest":"sync";if(e.error!==void 0)return{name:n,status:"fail",message:`apply failed: ${e.error}`,notes:["restore the tracked paths with:",Ie(Cn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:sN(r,t)}},aN=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(`
434
+ `).slice(0,oN)},cN=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[iN(e,t),...r,...e.commit?[aN(e.commit)]:[]]}},lN={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},Qd=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:lN[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>cN(o,r))],hints:n}},hw=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),yw=(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 uN=20,ep=async(e,t)=>(await Q(e,t,{allowFailure:!0})).trim(),dN=async e=>Pa(await Q(e,["status","--porcelain","-z","--untracked-files=normal"])),pN=async e=>(await ep(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"]},mN=async e=>{let[t,r]=await Promise.all([ep(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),ep(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}`}},vw=async e=>{let t=await dN(e);if(t.length>0){let n=t.slice(0,uN),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new C({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([pN(e),mN(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import fN from"node:path";var ww=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new C({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=dn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:fN.join(n,s)}))},gN="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",hN=async(e,t)=>{let r=await xa(e,t),n=Ra(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${gN} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},kw=async(e,t,r)=>Promise.all(t.map(async n=>r?hN(e,n):Ra(e,await xa(e,n))));var Ew="sync vendored files",kN=e=>{let t=Rw.join(dn(e.workspaceDir),e.source);if(yN(t))return t;throw new C({status:"refused",reason:"source-missing",source:t},1,{operation:Ew,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'})},tp=(e,t)=>new C({status:"refused",reason:"not-a-vendor-source"},1,{operation:Ew,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`}),bN=async e=>{let t=Rw.join(e,"infra-kit.json"),r;try{r=JSON.parse(await vN.readFile(t,"utf8"))}catch(s){throw tp(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw tp(t,"has no vendorSource block");let o=im.safeParse(n);if(!o.success)throw tp(t,`has an invalid vendorSource: ${wN.prettifyError(o.error)}`);return o.data},bw=(e,t)=>{Sw.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
434
435
  ${Ie(t)}
435
- `)},yN=async(e,t,r)=>r?(bw(t,Cn(t)),qd(t.root,e)):(await Hd({source:e,plan:t,onBeforeFirstWrite:o=>{bw(t,o)}})).touched,vN=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await yN(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 zd(t.root,n,Yd(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},wN=async(e,t,r)=>{let n=[];for(let o of t)n.push(await vN(e,o,r));return n},Pw=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})),rp=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&tt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:Pw(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:hw(t),report:t.sections}}},kN=async e=>{let t=await wi(),r=gN(t),n=await vw(r),o=await hN(r),s=ww(t,e.targets??[]),i=await Zd(r,o),a=await kw(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},np=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await kN(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=Qd(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return rp({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!J();if(l&&!Sw.stdin.isTTY)return tt(a),rp({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&tt({...a,hints:[]}),await L(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:Pw(n),throwOnDecline:!0});let u=await wN(t,n,e),p=Qd(r,u,{...s,mode:"applied"});if(l){let m=u.filter(g=>g.applied).map(g=>g.plan.name);tt(yw(a,p,m))}return rp({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var Ta=(e,t=!0)=>({line:e,reproducible:t});import Ca from"node:fs";import bN from"node:os";import RN from"node:path";import $w from"node:process";var $a="INFRA_KIT_SESSION_REPORT",op=null,xw=!1,Tw=[],Aw=(e=$w.env)=>{xw||(op=e[$a]??null,xw=!0,delete e[$a])};var Ow=(e,t)=>{if(!op)return;let r=e.summary??(Tw.length>0?[...Tw]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{Ca.writeFileSync(s,i)});try{o(op,JSON.stringify(n))}catch{}},Cw=0,Iw=e=>{let t=e?.tmpdir?.()??bN.tmpdir(),r=e?.pid??$w.pid;return Cw+=1,RN.join(t,`infra-kit-session-${r}-${Cw}.json`)},Dw=(e,t)=>{if(!(t?.exists??(i=>Ca.existsSync(i)))(e))return null;let n=t?.read??(i=>Ca.readFileSync(i,"utf-8")),o=t?.unlink??(i=>Ca.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var sp=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead"),e.commands.forEach(sp)};var ip=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(ip)};var TN=(e,t)=>[...t,e],CN=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 ng(()=>Fi({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));$(r),r.structuredContent.failedMerges>0&&($e.exitCode=1)}),_w=e=>($e.stdout.write(`${e.structuredContent.filePath}
436
- `),$(e)),$N=e=>e.description("List all release branches").action(async()=>{$(await Wi())}),AN=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".',TN,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Bl),o=n.length>0?n:void 0;$(await qi({releases:o,confirmedCommand:t.yes}))}),ON=e=>{if(e==="")return e;try{return ur(e)}catch(t){throw t instanceof vn?new EN(t.message):t}},IN=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)',ON).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Yi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Mw=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Ut.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"),DN=e=>Mw(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await Ud({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),NN=e=>Mw(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{$(await Vd({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),_N=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Bi({version:t.version,confirmedCommand:t.yes}))}),MN=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Zi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),jN=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await fa({confirmedCommand:t.yes}))}),FN=e=>e.description("Add git worktrees for release branches or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{$(await ua({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),LN=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await da())}),BN=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{$(await ma({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),UN=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{$(await Gd({init:t.init}))}),VN=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await aa();$(t),t.structuredContent.ok||($e.exitCode=1)}),WN=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 np({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!dt(a))throw a;d.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&($e.exitCode=1)}),GN=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await Ed())}),JN=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Pd())}),KN=new Set(["version"]),Aa=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},ap=()=>{let e=new SN().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");CN(t.command("merge-dev")),$N(t.command("list")),AN(t.command("create")),IN(t.command("edit")),DN(t.command("deploy-all")),NN(t.command("deploy-selected")),_N(t.command("deliver")),MN(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");FN(r.command("add")),LN(r.command("list")),BN(r.command("remove")),jN(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");GN(n.command("path")),JN(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{$(await Qs({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{$(await Bc({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{$(await xd({key:a,global:c.global}))});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{$(await ya({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{$(await ya({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),$e.exitCode=1;return}let c=await zs({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&($e.exitCode=1)}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await _d({check:a.check});$(c),c.structuredContent.ok||($e.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return VN(i.command("check")),UN(i.command("config")),WN(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 $i({fix:!!a.fix});Yt.enabled||zc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&($e.exitCode=1),$(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),u=!!($e.stdout.isTTY&&$e.stdin.isTTY);await l({...c,appName:a},u,Yt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await ei())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{$(await Di({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 Nw("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Nw("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){$(await qu());return}$(await ra({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await ca())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await Mi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await jm())}),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=>{_w(await Ya({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{_w(await _i())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");$(await Ld({fromFile:c.fromFile,force:c.force}));return}$(await Fd({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{$(await ji({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{$(await Md({env:a}))}),e.commands.forEach(Wp),sp(e),ip(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&xN(PN($e.cwd(),l)),h.start(Aa(c)),Yt.enabled=!!c.optsWithGlobals().json,Yt.enabled&&(d.level="warn"),_.source=Ts({env:$e.env,stdinIsTTY:$e.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),KN.has(Aa(c))||await kl()}),e.hook("postAction",(a,c)=>{let l=Aa(c);if(bd(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",g=`infra-kit ${l}${m}`;Ow({equivalent:Ta(g,!0)})}),e};import HN from"node:process";var qN={exit:HN.exit,emit:$,logger:d},jw=(e,t=qN)=>Se(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof C?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var cp=(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 YN from"node:fs";import lp from"node:path";import $n from"node:process";var Bw=new Set([...sm,On,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Uw=null,Oa=new Set,up=null,Fw=!1;var Lw=e=>{try{return YN.statSync(e)}catch{return null}},zN=()=>{if(Fw)return null;try{return Pr()}catch{return Fw=!0,d.debug(`session-env: ${On} unset \u2014 no overlay`),null}},XN=e=>{let t=lp.join(e,Sr),r=lp.join(e,ys),n=Lw(t),o=Lw(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?kp(lp.join(e,vs),$n.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"}},ZN=e=>e.kind==="load"?{kind:"load",vars:vp(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:wp(e.file),signature:e.signature}:e;var QN=()=>{let e=zN();if(e===null)return{kind:"no-session"};let t=XN(e);return t.signature===up?null:ZN(t)},e_=()=>{for(let e of Oa){let t=Uw[e];t===void 0?delete $n.env[e]:$n.env[e]=t}Oa.clear()},t_=(e,t,r)=>{if(Bw.has(t)){e.skipped.push(t);return}$n.env[t]=r,Oa.add(t),e.set.push(t)},r_=(e,t)=>{if(Bw.has(t)){e.skipped.push(t);return}delete $n.env[t],Oa.add(t),e.unset.push(t)},n_=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))t_(t,r,n);if(e.kind==="clear")for(let r of e.unset)r_(t,r);return t},o_=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,dp=(e=QN())=>{if(Uw??={...$n.env},e===null||e.kind==="no-session"||e.signature===up)return{set:[],unset:[],changed:!1};e_();let{set:t,unset:r,skipped:n}=n_(e);return up=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(", ")}] (${o_(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as P_}from"chalk";import{spawn as x_}from"node:child_process";import Ae from"node:process";import{Chalk as s_}from"chalk";var An=new s_({level:1}),He={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},i_={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"}},Vw={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Ww={unicode:"\u2500",ascii:"-"},a_=3,pp=e=>e,c_={ok:e=>An.green(e),findings:e=>An.yellow(e),failed:e=>An.red(e),cancelled:e=>An.gray(e)},fp=e=>e?{dim:t=>An.dim(t),bold:t=>An.bold(t)}:{dim:pp,bold:pp},l_=(e,t)=>e?c_[t]:pp,mp=e=>[...e].length,u_=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return mp(e)<=r?e:[...e].slice(0,r).join("")},Gw=e=>{let t=fp(e.color===!0).dim,r=i_[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(u_(n,e.width))},Jw=(e,t={})=>{let r=fp(t.color===!0);return`${r.dim(He.reproPrefix.trim())} ${r.bold(e)}`},d_=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,p_=(e,t)=>e==="findings"?t!=null?`${t} ${He.findingsSuffix}`:He.findingsPlain:{ok:He.ok,failed:He.failed,cancelled:He.cancelled}[e],m_=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<a_?"":` ${n(r.repeat(o))}`},Kw=e=>{let t=e.color===!0,r=fp(t),n=l_(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?He.reproPrefix:He.nonReproPrefix,i=o?Vw[e.outcome].ascii:Vw[e.outcome].unicode,a=p_(e.outcome,e.findingsCount),c=[d_(e.durationMs)],l=e.summary?.[0]?.split(`
437
- `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${He.sep}${c.join(He.sep)}`,m=mp(u)+mp(p),g=m_(m,e.width,o?Ww.ascii:Ww.unicode,r.dim),y=[`${n(u)}${r.dim(p)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(He.envNotice)),y.join(`
438
- `)};var f_=new Set([130,143]),Hw=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&f_.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import g_ from"node:process";var h_={3:"quit",4:"quit",26:"suspend",27:"quit"},y_=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":h_[t]??"continue"},v_=150,w_="\r\x1B[2K",k_=`\r
439
- `,qw=(e,t)=>{Yw(e),e.stdin.on("data",t),e.listener=t},Yw=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},zw=(e,t)=>{fm(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),qw(e,t)},Xw=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(w_)),Yw(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),gm()},b_=e=>{e.settled||(e.settled=!0,Xw(e))},Zw=(e,t)=>{let r=Gw({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},R_=async e=>{await new Promise(t=>{setTimeout(t,e)})},S_=(e,t,r)=>{Xw(e),t(),zw(e,r),Zw(e,k_)},E_=async e=>new Promise(t=>{let r=n=>{let o=y_(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){S_(e,s,r);return}t("palette")};qw(e,r),Zw(e,"")}),Qw=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??g_.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return zw(n,()=>{}),e.armed(),await R_(t.drainMs??v_),await E_(n)}finally{b_(n)}};import ek from"node:process";var Ht={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},tk=(e,t)=>{let r=t?.write??(s=>{ek.stderr.write(s)}),n=t?.stdin??ek.stdin,o=[Ht.saveCursor,Ht.scrollRegion,Ht.restoreCursor,Ht.column,Ht.sgr,Ht.cursor,Ht.wrap];e.entersAltScreen===!0&&o.push(Ht.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var rk=e=>`infra-kit ${e.groupPath.join(" ")}`,T_=()=>{C_();let e=Ae.stderr.columns;return e!=null&&e>0?e:void 0},C_=()=>{let e=Ae.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},$_=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),A_=async(e,t,r)=>{let n=Iw(),o={...t.env,[$a]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Ae.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await $_(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Dw(n),c=Hw(i.code,i.signal,a!=null,e.longRunning),l=rk(e),u=a?.equivalent??Ta(l,!0);return Kw({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)})},O_=1e3,I_=(e,t)=>e!=null&&t-e<=O_,gp=e=>{e.resetTerminal(),e.exit(0)},D_=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&gp(t)},s=()=>{let c=e();if(c==="palette"){gp(t);return}if(!I_(r,t.now())){if(c==="pause"){gp(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}},nk=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),N_=Ae.platform==="win32"?void 0:()=>{hm()},__=(e,t)=>r=>Qw(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:N_}),ok=async(e,t)=>{let r={spawn:t.spawn??x_,now:t.now??(()=>Date.now()),env:t.env??Ae.env,cliPath:t.cliPath,ascii:t.ascii??!(Ae.stdout.isTTY&&Ae.env.TERM!=="dumb"),color:t.color??P_.level>0,columns:t.columns??T_,resetTerminal:t.resetTerminal??(u=>{tk(u)})},n=t.write??(u=>Ae.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Ae.on(u,p)},unregister:(u,p)=>{Ae.off(u,p)},exit:u=>{Ae.exit(u)},raise:u=>{Ae.kill(Ae.pid,u)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:D_(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??__(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=Jw(rk(p),{color:r.color});n(`
436
+ `)},RN=async(e,t,r)=>r?(bw(t,Cn(t)),qd(t.root,e)):(await Hd({source:e,plan:t,onBeforeFirstWrite:o=>{bw(t,o)}})).touched,SN=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await RN(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 zd(t.root,n,Yd(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},EN=async(e,t,r)=>{let n=[];for(let o of t)n.push(await SN(e,o,r));return n},Pw=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})),rp=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&tt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:Pw(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:hw(t),report:t.sections}}},PN=async e=>{let t=await wi(),r=kN(t),n=await vw(r),o=await bN(r),s=ww(t,e.targets??[]),i=await Zd(r,o),a=await kw(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},np=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await PN(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=Qd(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return rp({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!K();if(l&&!Sw.stdin.isTTY)return tt(a),rp({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&tt({...a,hints:[]}),await L(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:Pw(n),throwOnDecline:!0});let u=await EN(t,n,e),p=Qd(r,u,{...s,mode:"applied"});if(l){let m=u.filter(g=>g.applied).map(g=>g.plan.name);tt(yw(a,p,m))}return rp({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var Ta=(e,t=!0)=>({line:e,reproducible:t});import Ca from"node:fs";import xN from"node:os";import TN from"node:path";import $w from"node:process";var $a="INFRA_KIT_SESSION_REPORT",op=null,xw=!1,Tw=[],Aw=(e=$w.env)=>{xw||(op=e[$a]??null,xw=!0,delete e[$a])};var Ow=(e,t)=>{if(!op)return;let r=e.summary??(Tw.length>0?[...Tw]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{Ca.writeFileSync(s,i)});try{o(op,JSON.stringify(n))}catch{}},Cw=0,Iw=e=>{let t=e?.tmpdir?.()??xN.tmpdir(),r=e?.pid??$w.pid;return Cw+=1,TN.join(t,`infra-kit-session-${r}-${Cw}.json`)},Dw=(e,t)=>{if(!(t?.exists??(i=>Ca.existsSync(i)))(e))return null;let n=t?.read??(i=>Ca.readFileSync(i,"utf-8")),o=t?.unlink??(i=>Ca.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var sp=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead"),e.commands.forEach(sp)};var ip=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(ip)};var IN=(e,t)=>[...t,e],DN=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 ng(()=>Fi({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));$(r),r.structuredContent.failedMerges>0&&($e.exitCode=1)}),_w=e=>($e.stdout.write(`${e.structuredContent.filePath}
437
+ `),$(e)),NN=e=>e.description("List all release branches").action(async()=>{$(await Wi())}),_N=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".',IN,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Bl),o=n.length>0?n:void 0;$(await qi({releases:o,confirmedCommand:t.yes}))}),MN=e=>{if(e==="")return e;try{return dr(e)}catch(t){throw t instanceof vn?new $N(t.message):t}},jN=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)',MN).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Yi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Mw=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Vt.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"),FN=e=>Mw(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await Ud({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),LN=e=>Mw(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{$(await Vd({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),BN=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Bi({version:t.version,confirmedCommand:t.yes}))}),UN=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Zi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),VN=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await fa({confirmedCommand:t.yes}))}),WN=e=>e.description("Add git worktrees for release branches or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{$(await ua({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),GN=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await da())}),JN=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{$(await ma({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),KN=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{$(await Gd({init:t.init}))}),HN=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await aa();$(t),t.structuredContent.ok||($e.exitCode=1)}),qN=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 np({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!dt(a))throw a;d.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&($e.exitCode=1)}),YN=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await Ed())}),zN=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Pd())}),XN=new Set(["version"]),Aa=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},ap=()=>{let e=new CN().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");DN(t.command("merge-dev")),NN(t.command("list")),_N(t.command("create")),jN(t.command("edit")),FN(t.command("deploy-all")),LN(t.command("deploy-selected")),BN(t.command("deliver")),UN(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");WN(r.command("add")),GN(r.command("list")),JN(r.command("remove")),VN(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");YN(n.command("path")),zN(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{$(await Qs({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{$(await Bc({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{$(await xd({key:a,global:c.global}))});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{$(await ya({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{$(await ya({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),$e.exitCode=1;return}let c=await zs({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&($e.exitCode=1)}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await _d({check:a.check});$(c),c.structuredContent.ok||($e.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return HN(i.command("check")),KN(i.command("config")),qN(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 $i({fix:!!a.fix});zt.enabled||zc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&($e.exitCode=1),$(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),u=!!($e.stdout.isTTY&&$e.stdin.isTTY);await l({...c,appName:a},u,zt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await ei())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{$(await Di({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 Nw("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Nw("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){$(await qu());return}$(await ra({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await ca())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await Mi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await jm())}),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=>{_w(await Ya({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{_w(await _i())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");$(await Ld({fromFile:c.fromFile,force:c.force}));return}$(await Fd({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{$(await ji({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{$(await Md({env:a}))}),e.commands.forEach(Wp),sp(e),ip(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&ON(AN($e.cwd(),l)),h.start(Aa(c)),zt.enabled=!!c.optsWithGlobals().json,zt.enabled&&(d.level="warn"),_.source=Ts({env:$e.env,stdinIsTTY:$e.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),XN.has(Aa(c))||await kl()}),e.hook("postAction",(a,c)=>{let l=Aa(c);if(bd(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",g=`infra-kit ${l}${m}`;Ow({equivalent:Ta(g,!0)})}),e};import ZN from"node:process";var QN={exit:ZN.exit,emit:$,logger:d},jw=(e,t=QN)=>Se(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof C?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var cp=(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 e_ from"node:fs";import lp from"node:path";import $n from"node:process";var Bw=new Set([...sm,On,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Uw=null,Oa=new Set,up=null,Fw=!1;var Lw=e=>{try{return e_.statSync(e)}catch{return null}},t_=()=>{if(Fw)return null;try{return xr()}catch{return Fw=!0,d.debug(`session-env: ${On} unset \u2014 no overlay`),null}},r_=e=>{let t=lp.join(e,Er),r=lp.join(e,ys),n=Lw(t),o=Lw(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?kp(lp.join(e,vs),$n.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"}},n_=e=>e.kind==="load"?{kind:"load",vars:vp(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:wp(e.file),signature:e.signature}:e;var o_=()=>{let e=t_();if(e===null)return{kind:"no-session"};let t=r_(e);return t.signature===up?null:n_(t)},s_=()=>{for(let e of Oa){let t=Uw[e];t===void 0?delete $n.env[e]:$n.env[e]=t}Oa.clear()},i_=(e,t,r)=>{if(Bw.has(t)){e.skipped.push(t);return}$n.env[t]=r,Oa.add(t),e.set.push(t)},a_=(e,t)=>{if(Bw.has(t)){e.skipped.push(t);return}delete $n.env[t],Oa.add(t),e.unset.push(t)},c_=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))i_(t,r,n);if(e.kind==="clear")for(let r of e.unset)a_(t,r);return t},l_=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,dp=(e=o_())=>{if(Uw??={...$n.env},e===null||e.kind==="no-session"||e.signature===up)return{set:[],unset:[],changed:!1};s_();let{set:t,unset:r,skipped:n}=c_(e);return up=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(", ")}] (${l_(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as A_}from"chalk";import{spawn as O_}from"node:child_process";import Ae from"node:process";import{Chalk as u_}from"chalk";var An=new u_({level:1}),He={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},d_={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"}},Vw={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Ww={unicode:"\u2500",ascii:"-"},p_=3,pp=e=>e,m_={ok:e=>An.green(e),findings:e=>An.yellow(e),failed:e=>An.red(e),cancelled:e=>An.gray(e)},fp=e=>e?{dim:t=>An.dim(t),bold:t=>An.bold(t)}:{dim:pp,bold:pp},f_=(e,t)=>e?m_[t]:pp,mp=e=>[...e].length,g_=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return mp(e)<=r?e:[...e].slice(0,r).join("")},Gw=e=>{let t=fp(e.color===!0).dim,r=d_[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(g_(n,e.width))},Jw=(e,t={})=>{let r=fp(t.color===!0);return`${r.dim(He.reproPrefix.trim())} ${r.bold(e)}`},h_=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,y_=(e,t)=>e==="findings"?t!=null?`${t} ${He.findingsSuffix}`:He.findingsPlain:{ok:He.ok,failed:He.failed,cancelled:He.cancelled}[e],v_=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<p_?"":` ${n(r.repeat(o))}`},Kw=e=>{let t=e.color===!0,r=fp(t),n=f_(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?He.reproPrefix:He.nonReproPrefix,i=o?Vw[e.outcome].ascii:Vw[e.outcome].unicode,a=y_(e.outcome,e.findingsCount),c=[h_(e.durationMs)],l=e.summary?.[0]?.split(`
438
+ `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${He.sep}${c.join(He.sep)}`,m=mp(u)+mp(p),g=v_(m,e.width,o?Ww.ascii:Ww.unicode,r.dim),y=[`${n(u)}${r.dim(p)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(He.envNotice)),y.join(`
439
+ `)};var w_=new Set([130,143]),Hw=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&w_.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import k_ from"node:process";var b_={3:"quit",4:"quit",26:"suspend",27:"quit"},R_=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":b_[t]??"continue"},S_=150,E_="\r\x1B[2K",P_=`\r
440
+ `,qw=(e,t)=>{Yw(e),e.stdin.on("data",t),e.listener=t},Yw=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},zw=(e,t)=>{fm(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),qw(e,t)},Xw=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(E_)),Yw(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),gm()},x_=e=>{e.settled||(e.settled=!0,Xw(e))},Zw=(e,t)=>{let r=Gw({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},T_=async e=>{await new Promise(t=>{setTimeout(t,e)})},C_=(e,t,r)=>{Xw(e),t(),zw(e,r),Zw(e,P_)},$_=async e=>new Promise(t=>{let r=n=>{let o=R_(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){C_(e,s,r);return}t("palette")};qw(e,r),Zw(e,"")}),Qw=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??k_.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return zw(n,()=>{}),e.armed(),await T_(t.drainMs??S_),await $_(n)}finally{x_(n)}};import ek from"node:process";var qt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},tk=(e,t)=>{let r=t?.write??(s=>{ek.stderr.write(s)}),n=t?.stdin??ek.stdin,o=[qt.saveCursor,qt.scrollRegion,qt.restoreCursor,qt.column,qt.sgr,qt.cursor,qt.wrap];e.entersAltScreen===!0&&o.push(qt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var rk=e=>`infra-kit ${e.groupPath.join(" ")}`,I_=()=>{D_();let e=Ae.stderr.columns;return e!=null&&e>0?e:void 0},D_=()=>{let e=Ae.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},N_=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),__=async(e,t,r)=>{let n=Iw(),o={...t.env,[$a]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Ae.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await N_(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Dw(n),c=Hw(i.code,i.signal,a!=null,e.longRunning),l=rk(e),u=a?.equivalent??Ta(l,!0);return Kw({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)})},M_=1e3,j_=(e,t)=>e!=null&&t-e<=M_,gp=e=>{e.resetTerminal(),e.exit(0)},F_=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&gp(t)},s=()=>{let c=e();if(c==="palette"){gp(t);return}if(!j_(r,t.now())){if(c==="pause"){gp(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}},nk=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),L_=Ae.platform==="win32"?void 0:()=>{hm()},B_=(e,t)=>r=>Qw(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:L_}),ok=async(e,t)=>{let r={spawn:t.spawn??O_,now:t.now??(()=>Date.now()),env:t.env??Ae.env,cliPath:t.cliPath,ascii:t.ascii??!(Ae.stdout.isTTY&&Ae.env.TERM!=="dumb"),color:t.color??A_.level>0,columns:t.columns??I_,resetTerminal:t.resetTerminal??(u=>{tk(u)})},n=t.write??(u=>Ae.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Ae.on(u,p)},unregister:(u,p)=>{Ae.off(u,p)},exit:u=>{Ae.exit(u)},raise:u=>{Ae.kill(Ae.pid,u)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:F_(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??B_(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=Jw(rk(p),{color:r.color});n(`
440
441
  ${m}
441
- `),a.childStarted();let g=await A_(p,r,()=>{o="child"});if(n(`
442
+ `),a.childStarted();let g=await __(p,r,()=>{o="child"});if(n(`
442
443
  ${g}
443
- `),await l(c)==="quit")return}}finally{a.dispose()}};Sd();Aw();var ck=ap(),ik=async(e=Oe.argv)=>{dp(),pm(e);try{await ck.parseAsync(e)}catch(t){jw(t)}},B_=()=>{try{if(Oe.env.INFRA_KIT_NO_LOCATION_WARN||Oe.argv.includes("--json"))return;Ep({selfRealPath:F_(ak(import.meta.url)),cwd:Oe.cwd(),env:Oe.env,realpath:ye,home:L_(),exists:j_})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};B_();Vp((e,t)=>{d.debug(e,t)});Rl(U.version);var lk=()=>Mv(ck.commands),U_=async()=>{let e=lk(),t=null;try{if(Oe.stdout.isTTY&&Oe.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=cp(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new sk(" "),new sk(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await I(o=>M_({message:"Select a command to run",choices:n},o),{output:Oe.stderr})}}catch(r){if(!Se(r))throw r}return t},V_=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=ak(import.meta.url),r=new Map(pr.map(n=>[n.groupPath.join(" "),n]));await ok(lk(),{renderPalette:e,resolveCommand:n=>{let o=r.get(n);return o?{groupPath:o.groupPath,entersAltScreen:o.entersAltScreen,sessionEnvNotice:o.sessionEnvNotice,longRunning:o.longRunning}:void 0},cliPath:t})};if(Oe.argv.length<=2){let e={stdoutIsTTY:!!Oe.stdout.isTTY,stdinIsTTY:!!Oe.stdin.isTTY,stderrIsTTY:!!Oe.stderr.isTTY};if(nk(Oe.env,e))await V_();else{let t=await U_();t&&await ik(["node","infra-kit",...t.split(" ")])}}else await ik();
444
+ `),await l(c)==="quit")return}}finally{a.dispose()}};Sd();Aw();var ck=ap(),ik=async(e=Oe.argv)=>{dp(),pm(e);try{await ck.parseAsync(e)}catch(t){jw(t)}},J_=()=>{try{if(Oe.env.INFRA_KIT_NO_LOCATION_WARN||Oe.argv.includes("--json"))return;Ep({selfRealPath:W_(ak(import.meta.url)),cwd:Oe.cwd(),env:Oe.env,realpath:ye,home:G_(),exists:V_})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};J_();Vp((e,t)=>{d.debug(e,t)});Rl(U.version);var lk=()=>Mv(ck.commands),K_=async()=>{let e=lk(),t=null;try{if(Oe.stdout.isTTY&&Oe.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=cp(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new sk(" "),new sk(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await I(o=>U_({message:"Select a command to run",choices:n},o),{output:Oe.stderr})}}catch(r){if(!Se(r))throw r}return t},H_=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=ak(import.meta.url),r=new Map(mr.map(n=>[n.groupPath.join(" "),n]));await ok(lk(),{renderPalette:e,resolveCommand:n=>{let o=r.get(n);return o?{groupPath:o.groupPath,entersAltScreen:o.entersAltScreen,sessionEnvNotice:o.sessionEnvNotice,longRunning:o.longRunning}:void 0},cliPath:t})};if(Oe.argv.length<=2){let e={stdoutIsTTY:!!Oe.stdout.isTTY,stdinIsTTY:!!Oe.stdin.isTTY,stderrIsTTY:!!Oe.stderr.isTTY};if(nk(Oe.env,e))await H_();else{let t=await K_();t&&await ik(["node","infra-kit",...t.split(" ")])}}else await ik();
444
445
  //# sourceMappingURL=cli.js.map