infra-kit 0.43.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{a as Kg}from"./chunk-V2ZLQPLI.js";import{a as mn,b as Ag,c as tr,d as Ki,e as Og,f as Dg,g as Ig,h as Ng,i as _g,j as Mg,k as jg,l as Fg,o as Al,p as Gg,s as Jg,u as Me}from"./chunk-O3W65BXT.js";import{a as Uf,b as Je,c as Vf,d as cl,e as Wf,f as Gf,g as Jf,h as Kf,i as To,j as Hf,k as qf,l as zf,m as Yf,n as Xf,o as Co,p as Zf,q as Qf,r as eg,s as tg,t as ll,u as _i,v as Ot,w as rg,x as Mi,y as ng}from"./chunk-VZAXKGEY.js";import{a as me,b as Z,c as Qt,d as Do,e as gl,f as Vi,g as Wi,h as hl,i as Io,j as Er,k as yl,l as Gi,m as Tg,n as at,o as _o,p as xl,q as Tl,r as Cl,s as Lg,u as $l}from"./chunk-HIGOL4H4.js";import{b as ln,c as Ii,d as al,e as Mf,f as Ni,g as jf,i as Ff,k as Lf,m as Se,o as Bf}from"./chunk-REDCBY4O.js";import{a as vl,b as wl,c as He,d as kl,e as De,f as Rl,h as No,j as Sl,k as El,n as Pl}from"./chunk-KA5BFUCS.js";import{a as y,b as xe,c as Bg,d as Ug,e as _,f as Hi,g as q}from"./chunk-TYGUMAIP.js";import{a as Vg,b as Wg}from"./chunk-QWVLAZ6N.js";import{b as Ji,c as er,d as fe,e as Cg,f as bl,g as $g}from"./chunk-L4AFEAYF.js";import{$ as Rg,A as ae,B as un,C as ug,D as gt,E as Pe,F as $,G as _e,H as dn,I as dg,J as pg,K as mg,L as fg,M as Li,N as Bi,O as Oe,P as $o,Q as pn,R as Ui,S as gg,T as hg,U as yg,V as pl,W as ml,X as vg,Y as kg,Z as bg,_ as Ao,a as Yt,aa as Sg,b as I,ba as Xt,c as og,ca as Eg,d as N,da as fl,e as te,ea as Pg,f as H,fa as xg,g as ji,ga as X,h as Ke,ha as L,i as d,ia as Oo,j as ie,ja as Zt,k as w,l as it,m as sg,n as ul,o as ig,p as ag,q as g,r as A,s as cg,t as Fi,u as re,v as Ee,w as Ae,x as lg,y as dl,z as pe}from"./chunk-JBQ5572P.js";import{a as wg}from"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-FHOMP6VJ.js";import{a as Ht,b as Ai,c as nn,d as ft,e as Df,f as qt,g as on,h as sn,i as Oi,j as an,k as Di,l as If,m as Nf,n as At,o as zt,p as st,q as le,r as _f,s as cn}from"./chunk-RVMKL6T4.js";import mB,{Separator as xS}from"@inquirer/select";import{existsSync as fB,realpathSync as gB}from"node:fs";import{homedir as hB}from"node:os";import Ge from"node:process";import{fileURLToPath as CS}from"node:url";import Yh from"node:path";import Xh from"node:process";import{z as Ce}from"zod";import th from"node:fs";import gn from"node:path";var Pr=async()=>{try{return(await L()).audit?.exclude??[]}catch(e){return d.debug({err:e,msg:"audit.exclude unreadable \u2014 no workspace package is excluded"}),[]}};import{packageConfigSchema as zg}from"@slip-stream-kit/config/internal";import Yg from"node:fs/promises";import qi from"node:path";import{pathToFileURL as jS}from"node:url";import{z as Xg}from"zod";import Hg from"node:path";var Mo=["frontend","backend","lib","e2e","mobile"],OS={ui:"frontend",api:"backend",tests:"e2e"},DS="mobile-app",IS=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],NS=(e,t)=>{let r=Hg.relative(t,e).split(Hg.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=OS[o];if(s)return s}return r.at(-1)===DS?"mobile":null},_S=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of IS)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},jo=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??NS(e,t)??_S(r)??"lib";var ht={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},qg=2e3,Ol={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${qg}} 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"},xr={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"]},Fo=(e,t=ht)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import MS from"node:fs/promises";var je=async e=>{try{return await MS.access(e),!0}catch{return!1}};var ge="infra-kit.config.ts",Tr=async e=>{try{let t=await Yg.readFile(qi.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Dl=async e=>{let t=await Yg.stat(e),o=(await import(`${jS(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ge} at ${e} has no default export`);return typeof o=="function"?await o():o},Dt=async e=>{let t=qi.join(e,ge);if(await je(t))try{let n=(await Dl(t))?.type;return Mo.find(o=>o===n)}catch{return}},Zg=e=>e,Lo=async(e,t=ht)=>{let r=qi.join(e,ge);if(!await je(r))throw new Error(`${ge} not found at ${r}`);let n=await Dl(r),o=zg.safeParse(n);if(!o.success)throw new Error(`Invalid ${ge} at ${r}: ${Xg.prettifyError(o.error)}`);return Fo(Zg(o.data),t)},yt=async e=>{let t=qi.join(e,ge);if(!await je(t))return;let r=zg.safeParse(await Dl(t));if(!r.success)throw new Error(`Invalid ${ge} at ${t}: ${Xg.prettifyError(r.error)}`);return Zg(r.data)};import Qg from"node:fs/promises";import zi from"node:path";import FS from"yaml";var LS="pnpm-workspace.yaml",BS=async e=>(await Qg.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>zi.join(e,r.name)),US=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await BS(n));continue}let o=zi.join(n,t);await je(o)&&r.push(o)}return r},eh=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await US(r,n);return r},vt=async e=>{let t=await Qg.readFile(zi.join(e,LS),"utf-8"),n=((FS.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await eh(e,s);for(let a of i)await je(zi.join(a,"package.json"))&&o.add(a)}return[...o].sort()},Cr=async(e,t)=>{let r=await vt(e),n=new Set;for(let o of t)for(let s of await eh(e,o.endsWith("/")?o.slice(0,-1):o))n.add(s);return{packages:r.filter(o=>!n.has(o)),excluded:r.filter(o=>n.has(o))}};import Bo from"node:path";var Uo=async e=>{let t=Bo.resolve(e);for(;t!==Bo.dirname(t);){if(await je(Bo.join(t,"package.json")))return t;t=Bo.dirname(t)}if(await je(Bo.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 qe=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},rr=(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?`
2
+ import{a as Yg}from"./chunk-V2ZLQPLI.js";import{a as fn,b as Ng,c as rr,d as Ki,e as _g,f as Mg,g as jg,h as Fg,i as Lg,j as Bg,k as Ug,l as Vg,o as Ol,p as qg,s as zg,u as Me}from"./chunk-GIF2JMAW.js";import{a as Vf,b as Je,c as Wf,d as cl,e as Gf,f as Jf,g as Kf,h as Hf,i as Co,j as qf,k as zf,l as Yf,m as Xf,n as Zf,o as $o,p as Qf,q as eg,r as tg,s as rg,t as ll,u as _i,v as Dt,w as ng,x as Mi,y as og}from"./chunk-VZAXKGEY.js";import{a as me,b as Z,c as er,d as Do,e as hl,f as Vi,g as Wi,h as yl,i as Io,j as Er,k as vl,l as Gi,m as Og,n as at,o as _o,p as Tl,q as Cl,r as $l,s as Wg,u as Al}from"./chunk-HIGOL4H4.js";import{b as ln,c as Ii,d as al,e as jf,f as Ni,g as Ff,i as Lf,k as Bf,m as Se,o as Uf}from"./chunk-REDCBY4O.js";import{a as wl,b as kl,c as He,d as bl,e as De,f as Sl,h as No,j as El,k as Pl,n as xl}from"./chunk-3DAG53TI.js";import{a as y,b as xe,c as Gg,d as Jg,e as _,f as Hi,g as q}from"./chunk-DQSVQO2S.js";import{a as Kg,b as Hg}from"./chunk-QWVLAZ6N.js";import{b as Ji,c as tr,d as fe,e as Dg,f as Rl,g as Ig}from"./chunk-NJ22P2UB.js";import{$ as Rg,A as Ae,B as mg,C as pl,D as pe,E as ae,F as un,G as fg,H as gt,I as Pe,J as $,K as _e,L as dn,M as gg,N as hg,O as yg,P as vg,Q as Li,R as Bi,S as Oe,T as Ao,U as pn,V as Ui,W as wg,X as kg,Y as bg,Z as ml,_ as fl,a as Xt,aa as Eg,b as I,ba as Pg,c as sg,ca as mn,d as N,da as xg,e as te,ea as Tg,f as H,fa as Zt,g as ji,ga as Cg,h as Ke,ha as gl,i as d,ia as $g,j as ie,ja as Ag,k as w,ka as X,l as it,la as L,m as ig,ma as Oo,n as ag,na as Qt,o as cg,p as lg,q as ul,r as dl,s as ug,t as dg,u as g,v as A,w as pg,x as Fi,y as re,z as Ee}from"./chunk-DVMV3WJZ.js";import{a as Sg}from"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-D7C4NYQA.js";import{a as qt,b as Ai,c as nn,d as ft,e as If,f as zt,g as on,h as sn,i as Oi,j as an,k as Di,l as Nf,m as _f,n as Ot,o as Yt,p as st,q as le,r as Mf,s as cn}from"./chunk-RVMKL6T4.js";import wB,{Separator as OS}from"@inquirer/select";import{existsSync as kB,realpathSync as bB}from"node:fs";import{homedir as RB}from"node:os";import Ge from"node:process";import{fileURLToPath as IS}from"node:url";import ty from"node:path";import ry from"node:process";import{z as Ce}from"zod";import sh from"node:fs";import hn from"node:path";var Pr=async()=>{try{return(await L()).audit?.exclude??[]}catch(e){return d.debug({err:e,msg:"audit.exclude unreadable \u2014 no workspace package is excluded"}),[]}};import{packageConfigSchema as Qg}from"@slip-stream-kit/config/internal";import eh from"node:fs/promises";import qi from"node:path";import{pathToFileURL as VS}from"node:url";import{z as th}from"zod";import Xg from"node:path";var Mo=["frontend","backend","lib","e2e","mobile"],MS={ui:"frontend",api:"backend",tests:"e2e"},jS="mobile-app",FS=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],LS=(e,t)=>{let r=Xg.relative(t,e).split(Xg.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=MS[o];if(s)return s}return r.at(-1)===jS?"mobile":null},BS=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of FS)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},jo=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??LS(e,t)??BS(r)??"lib";var ht={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Zg=2e3,Dl={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Zg}} 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"},xr={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"]},Fo=(e,t=ht)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import US from"node:fs/promises";var je=async e=>{try{return await US.access(e),!0}catch{return!1}};var ge="infra-kit.config.ts",Tr=async e=>{try{let t=await eh.readFile(qi.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Il=async e=>{let t=await eh.stat(e),o=(await import(`${VS(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ge} at ${e} has no default export`);return typeof o=="function"?await o():o},It=async e=>{let t=qi.join(e,ge);if(await je(t))try{let n=(await Il(t))?.type;return Mo.find(o=>o===n)}catch{return}},rh=e=>e,Lo=async(e,t=ht)=>{let r=qi.join(e,ge);if(!await je(r))throw new Error(`${ge} not found at ${r}`);let n=await Il(r),o=Qg.safeParse(n);if(!o.success)throw new Error(`Invalid ${ge} at ${r}: ${th.prettifyError(o.error)}`);return Fo(rh(o.data),t)},yt=async e=>{let t=qi.join(e,ge);if(!await je(t))return;let r=Qg.safeParse(await Il(t));if(!r.success)throw new Error(`Invalid ${ge} at ${t}: ${th.prettifyError(r.error)}`);return rh(r.data)};import nh from"node:fs/promises";import zi from"node:path";import WS from"yaml";var GS="pnpm-workspace.yaml",JS=async e=>(await nh.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>zi.join(e,r.name)),KS=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await JS(n));continue}let o=zi.join(n,t);await je(o)&&r.push(o)}return r},oh=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await KS(r,n);return r},vt=async e=>{let t=await nh.readFile(zi.join(e,GS),"utf-8"),n=((WS.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await oh(e,s);for(let a of i)await je(zi.join(a,"package.json"))&&o.add(a)}return[...o].sort()},Cr=async(e,t)=>{let r=await vt(e),n=new Set;for(let o of t)for(let s of await oh(e,o.endsWith("/")?o.slice(0,-1):o))n.add(s);return{packages:r.filter(o=>!n.has(o)),excluded:r.filter(o=>n.has(o))}};import Bo from"node:path";var Uo=async e=>{let t=Bo.resolve(e);for(;t!==Bo.dirname(t);){if(await je(Bo.join(t,"package.json")))return t;t=Bo.dirname(t)}if(await je(Bo.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 qe=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},nr=(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
3
  ${i}`:"")},$r=(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},Yi=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,fn=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Yi(r,t,n),i=qe(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?rr(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,gn=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Yi(r,t,n),i=qe(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?nr(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var Te="<!-- infra-kit:begin -->",Fe="<!-- infra-kit:end -->",Ar="<!-- infra-kit:version ",ze="<!-- infra-kit:package:begin -->",ct="<!-- infra-kit:package:end -->",It="<!-- infra-kit:package:version ";var VS=e=>{let t=e.indexOf(ze)+ze.length;return e.slice(t,e.indexOf(ct))},WS=e=>{let t=e.indexOf(It);if(t===-1)return null;let r=e.slice(t+It.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Mo.find(n=>n===r)??null},Nt=e=>{if(e===null)return{state:"missing"};if(!qe(e,ze,ct))return e.includes(ze)||e.includes(ct)?{state:"malformed"}:qe(e,Te,Fe)?{state:"foreign-block"}:{state:"no-block"};let t=VS(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=$r(t,It),o=WS(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import GS from"node:fs";var wt=e=>{try{return GS.readFileSync(e,"utf-8")}catch{return null}};var rh="pnpm-workspace.yaml",JS="CLAUDE.md",Nl=e=>{let t=gn.resolve(e);for(;t!==gn.dirname(t);){if(th.existsSync(gn.join(t,rh)))return t;t=gn.dirname(t)}return th.existsSync(gn.join(t,rh))?t:null},Il=new Map,Xi=()=>{Il.clear()},KS=async e=>{let t;try{t=await vt(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=gn.join(r,JS),o=wt(n);if(o!==null&&Nt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},hn=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Il.get(e);if(t)return t;let r=await KS(e);return Il.set(e,r),r};import Or from"node:fs";import nr from"node:path";var nh=`---
8
+ `};var Te="<!-- infra-kit:begin -->",Fe="<!-- infra-kit:end -->",Ar="<!-- infra-kit:version ",ze="<!-- infra-kit:package:begin -->",ct="<!-- infra-kit:package:end -->",Nt="<!-- infra-kit:package:version ";var HS=e=>{let t=e.indexOf(ze)+ze.length;return e.slice(t,e.indexOf(ct))},qS=e=>{let t=e.indexOf(Nt);if(t===-1)return null;let r=e.slice(t+Nt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Mo.find(n=>n===r)??null},_t=e=>{if(e===null)return{state:"missing"};if(!qe(e,ze,ct))return e.includes(ze)||e.includes(ct)?{state:"malformed"}:qe(e,Te,Fe)?{state:"foreign-block"}:{state:"no-block"};let t=HS(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=$r(t,Nt),o=qS(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import zS from"node:fs";var wt=e=>{try{return zS.readFileSync(e,"utf-8")}catch{return null}};var ih="pnpm-workspace.yaml",YS="CLAUDE.md",_l=e=>{let t=hn.resolve(e);for(;t!==hn.dirname(t);){if(sh.existsSync(hn.join(t,ih)))return t;t=hn.dirname(t)}return sh.existsSync(hn.join(t,ih))?t:null},Nl=new Map,Xi=()=>{Nl.clear()},XS=async e=>{let t;try{t=await vt(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=hn.join(r,YS),o=wt(n);if(o!==null&&_t(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},yn=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Nl.get(e);if(t)return t;let r=await XS(e);return Nl.set(e,r),r};import Or from"node:fs";import or from"node:path";var ah=`---
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 oh=`# {{packageName}}
77
+ `;var ch=`# {{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 sh="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{checksBullet}}\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the loaded env provides. Pass them to `use.httpCredentials`; never invent a per-app name (`E2E_CLIENT_BASIC_AUTH_*`) or fall back to one. `infra-kit audit` fails the package otherwise.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- `playwright.config.ts` takes `baseURL`, `ignoreHTTPSErrors` and `webServer` from `infraKitE2e()` (`@slip-stream-kit/config/playwright`). Every run is local by default \u2014 this worktree's dev server, reused or started for the run \u2014 and cloud only with `INFRA_KIT_E2E=cloud` (`infra-kit e2e --cloud`, the release pass is `/infra-kit:ultraqa`) or wherever `CI` is set (no dev server can run there), against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL. The one exception is a suite that must run against a production build it serves itself: it declares `e2e: { server: 'static' }` in `infra-kit.config.ts` and sets `baseURL` and `webServer` itself.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test, or skip it with a linked issue once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var ih="# {{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 ah=`# {{packageName}}
98
+ `;var lh="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- {{checksBullet}}\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the loaded env provides. Pass them to `use.httpCredentials`; never invent a per-app name (`E2E_CLIENT_BASIC_AUTH_*`) or fall back to one. `infra-kit audit` fails the package otherwise.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- `playwright.config.ts` takes `baseURL`, `ignoreHTTPSErrors` and `webServer` from `infraKitE2e()` (`@slip-stream-kit/config/playwright`). Every run is local by default \u2014 this worktree's dev server, reused or started for the run \u2014 and cloud only with `INFRA_KIT_E2E=cloud` (`infra-kit e2e --cloud`, the release pass is `/infra-kit:ultraqa`) or wherever `CI` is set (no dev server can run there), against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL. The one exception is a suite that must run against a production build it serves itself: it declares `e2e: { server: 'static' }` in `infra-kit.config.ts` and sets `baseURL` and `webServer` itself.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test, or skip it with a linked issue once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var uh="# {{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 dh=`# {{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 ch=`# {{packageName}}
119
+ `;var ph=`# {{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,33 +138,33 @@ 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 lh='# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `infra-kit`, the global CLI)\n\n- `ik env-load [-c <config>]` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply. Without `-c`, an agent loads the project\'s `defaultEnv` (set yours with `ik config-set defaultEnv <env>`); with none set it is refused and must ask the human.\n- `ik dev [app]` / `ik dev-status` \u2014 run this worktree\'s dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; no name runs every app. App names are per-repo: an unknown one is refused with the apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app\'s Playwright suite locally: against this worktree\'s dev server when it runs, otherwise the package\'s `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app\'s `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees. `ik worktrees add --feature <name> [--base <dev|main|release>]` creates `feature/<name>` at `<root>-worktrees/feature/<name>`, cut from the integration branch by default \u2014 `dev`, or `main` in a repo with `"gitFlow": "main"` (or without `dev`); `worktrees remove --feature <name>` removes it. To close the worktree a session runs in ("close this worktree"), run `infra-kit worktrees remove --self` from inside it: it previews, and its `--yes` re-run hands the removal to an Orca tab of the main checkout, which closes every tab of the worktree \u2014 this session included. The `/infra-kit:worktrees` skill is the agent entry point for feature worktrees \u2014 never create one with raw `git worktree add` or Claude Code\'s `EnterWorktree`, which skip `pnpm install`, the editor/Orca wiring and the `feature/` layout.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the integration branch (`dev`, or `main` under `"gitFlow": "main"`) into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against their `infra-kit.config.ts` rules (`--root`: the repo root against the `audit` block in `infra-kit.json`).\n- `ik audit --fix` \u2014 regenerate this repo\'s infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, git, aws, gh, doppler, portless).\n\n## Conventions\n\n- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.\n- Config is split by level: repo-wide settings live in the root `infra-kit.json` (personal overrides in `~/.infra-kit/`), per-package settings in that package\'s `infra-kit.config.ts`. The root has no `infra-kit.config.ts`.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- The git flow is the root `infra-kit.json` key `gitFlow`: `"dev"` (default) cuts features and regular releases from `dev` and delivers through a `dev \u2192 main` RC PR, hotfixes from `main`; `"main"` cuts everything from `main` and delivers straight into it, with no hotfix type. Never branch from `dev` in a `"main"` repo, even if a stale `dev` exists.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo\'s `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. The `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`, `vendor sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host\'s prompt on the argv is the approval. `release deliver` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root\'s `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n';var yn={"root/body":lh.trimEnd(),"package/frontend":ih.trimEnd(),"package/backend":oh.trimEnd(),"package/lib":ah.trimEnd(),"package/e2e":sh.trimEnd(),"package/mobile":ch.trimEnd(),"design/skeleton":nh.trimEnd()};var _l=/\{\{(\w+)\}\}/g,eE=/^- \{\{(\w+)\}\}$/,tE=e=>new Set([...e.matchAll(_l)].map(t=>t[1])),rE=(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(", ")}`)},nE=(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(", ")}`)},oE=(e,t)=>e.filter(r=>{let n=eE.exec(r);return n===null||t[n[1]]!==""}),sE=(e,t)=>{for(let r of e)for(let n of r.matchAll(_l)){let o=t[n[1]];if(o!==void 0&&o.includes(`
142
- `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},vn=(e,t)=>{let r=tE(e);nE(r,t),rE(r,t);let n=oE(e.split(`
143
- `),t);return sE(n,t),n.join(`
144
- `).replace(_l,(o,s)=>t[s])};var iE="name: TODO",Ml=e=>{let t=vn(yn["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(iE,()=>r)}
145
- `};var aE=(e,t)=>`${It}${e} ${t} -->`,cE="`README.md` \u2014 what this package is and how to run it.",jl="docs/e2e-playwright.md",lE=`\`${jl}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,uE=["ts-check","eslint-check","test"],dE="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.",pE="Run `pnpm run build` before a dependent package can see a change.",uh=(e,t)=>e?.includes(t)??!0,mE=e=>{let t=uE.filter(r=>uh(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},Fl=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=vn(yn[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?cE:"",checksBullet:mE(a),...r==="e2e"?{e2eDocBullet:i?lE:""}:{},...r==="lib"?{surfaceBullet:c?dE:"",buildBullet:uh(a,"build")?pE:""}:{}});return[aE(t,r),"",l,""].join(`
146
- `)};var fE=e=>`${Ar}${e} -->`,Vo=e=>{let t=vn(yn["root/body"],{});return[fE(e),"",t,""].join(`
147
- `)};import wn from"node:fs";import gE from"node:path";var Zi=e=>{let t;try{t=wn.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Wo=(e,t)=>{let r=Go(e,t);return r!=="unchanged"&&(wn.mkdirSync(gE.dirname(e),{recursive:!0}),wn.writeFileSync(e,t,"utf-8")),r},Go=(e,t)=>{Zi(e);let r=wn.existsSync(e)?wn.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Ll=(e,t,r)=>{let n=wn.readFileSync(e,"utf-8");if(!qe(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},dh=(e,t,r)=>qe(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Bl=(e,t,r,n)=>{let o=dh(e,r,n),s=dh(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 ea="<!-- infra-kit:import:begin -->",ta="<!-- infra-kit:import:end -->",hE="AGENTS.md",ph="CLAUDE.md",yE="README.md",Ul="DESIGN.md",vE=["frontend","mobile"],wE=e=>Or.existsSync(e)?Or.readFileSync(e,"utf-8"):null,Vl=(e,t)=>{try{return Or.readdirSync(e).includes(t)}catch{return!1}},Qi=(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},mh=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=wE(e),a=i===null?"":o?.(i)??i,c=fn({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return Go(e,c);let l=Wo(e,c);return Ll(e,r,n),i!==null&&Bl(a,c,r,n),l},kE=(e,t)=>{if(!Or.existsSync(e))return"unchanged";Zi(e);let r=Or.readFileSync(e,"utf-8"),n=rr(r,Te,Fe);return n===null?"unchanged":n.trim()===""?(t||Or.rmSync(e),"removed"):t?Go(e,n):Wo(e,n)},bE=(e,t,r)=>mh({filePath:e,dryRun:r,body:Vo(t),startMarker:Te,endMarker:Fe,prepare:n=>rr(n,ea,ta)??n}),Jo=async(e,{version:t,dryRun:r=!1})=>{let n=nr.join(e,ph),o=nr.join(e,hE),s=[];try{s.push({path:n,action:bE(n,t,r)})}catch(i){s.push(Qi(n,i))}try{s.push({path:o,action:kE(o,r)})}catch(i){s.push(Qi(o,i))}return s},RE=(e,t,r,n)=>{if(!vE.includes(r)||Vl(e,Ul))return null;let o=nr.join(e,Ul),s=Ml(t);try{return{path:o,action:n?Go(o,s):Wo(o,s),type:r}}catch(i){return Qi(o,i,r)}},ra=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await Tr(e),s=o.name??nr.basename(e),i=jo({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:Fl({version:r,type:i,packageName:s,relDir:nr.relative(t,e).split(nr.sep).join("/"),hasReadme:Vl(e,yE),hasDesign:Vl(e,Ul),hasE2eDoc:Or.existsSync(nr.join(t,jl)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},Ko=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=nr.join(e,ph),{body:a,type:c,packageName:l}=await ra(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:mh({filePath:i,body:a,startMarker:ze,endMarker:ct,dryRun:s}),type:c})}catch(p){u.push(Qi(i,p,c))}if(n){let p=RE(e,l,c,s);p&&u.push(p)}return u};import GE from"node:path";import fh from"node:path";var Wl="agent-guidance",Ho="CLAUDE.md",SE="\u2014 run: infra-kit audit --fix",EE={missing:`${Ho} missing`,"no-block":`${Ho} has no infra-kit block (expected ${ze} \u2026 ${ct})`,malformed:`${Ho} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Ho} carries the ROOT infra-kit block (${Te}); a package needs the package block`},PE=e=>e.adopted?` (workspace adopted: ${fh.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Gl=(e,t)=>{let r=Nt(wt(fh.join(e,Ho)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Wl,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${EE[r.state]} ${SE}`,o=r.state==="missing"?`${n}${PE(t)}`:n;return t.adopted?{name:Wl,status:"fail",message:o}:{name:Wl,status:"pass",message:`not yet adopted \u2014 ${o}`}};import xE from"node:path";var Jl=async(e,t=ht)=>{try{let r=await Lo(e,t);return{check:{name:ge,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ge,status:"fail",message:r.message},rules:null}}},gh="infra-kit.json",TE=async e=>await je(xE.join(e,ge))?{name:ge,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,Kl=async(e,t=xr)=>{let r=await TE(e),n=r?[r]:[];try{let{audit:o={}}=await L();return{checks:[{name:gh,status:"pass",message:"present and valid"},...n],rules:Fo(o,t)}}catch(o){return{checks:[{name:gh,status:"fail",message:o.message},...n],rules:null}}};import na from"node:fs/promises";import kn from"node:path";import{$ as CE}from"zx";var qo="playwright.config.ts",$E=[{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')"}],hh=e=>Object.entries(Ol).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"}}),AE="infra-kit-e2e",yh=async(e,t={})=>{let r=kn.join(e,qo),n=await na.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${qo}`,status:"fail",message:`missing ${qo}`}]:$E.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===AE?{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:`${qo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},OE=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,DE=/\.[cm]?[jt]sx?$/u,Hl=async(e,t)=>(await na.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&DE.test(n.name)).map(n=>kn.join(n.parentPath,n.name)),IE=async e=>{let t=await Hl(kn.join(e,"src"),!0);for(let r of[kn.join(e,qo),...t]){let n=await na.readFile(r,"utf-8").catch(()=>"");if(OE.test(n))return!0}return!1},vh=async e=>{let t="e2e-auth:gitignored";if(!await IE(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await CE({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}`}},ql="E2E__BASIC_AUTH_USERNAME",zl="E2E__BASIC_AUTH_PASSWORD",NE=/\bE2E_\w*BASIC_AUTH_\w+/gu,_E=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,ME=/\/\*[\s\S]*?\*\//gu,jE=/(^|[^:])\/\/[^\n]*/gu,FE=e=>/USER(?:NAME)?$/u.test(e)?ql:zl,LE=e=>e.replace(ME,"").replace(jE,"$1"),wh=async e=>{let t="e2e-env:basic-auth",r=[...await Hl(e,!1),...await Hl(kn.join(e,"src"),!0)],n=[];for(let o of r){let s=await na.readFile(o,"utf-8").catch(()=>""),i=new Set([...LE(s).matchAll(NE)].map(a=>a[0]).filter(a=>_E.test(a)&&a!==ql&&a!==zl));for(let a of i)n.push(`${a} \u2192 ${FE(a)} (${kn.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${ql} / ${zl}`}:{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("; ")}`}},Yl=async(e,t,r={})=>[...hh(t),...await yh(e,r),await vh(e),await wh(e)];import BE from"node:fs/promises";import UE from"node:path";var Xl=async(e,t)=>Promise.all(t.map(async r=>{let n=await BE.stat(UE.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 Zl=(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 VE from"node:fs/promises";import WE from"node:path";var bn="turbo.json",Ql=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await VE.readFile(WE.join(e,bn),"utf-8");r=JSON.parse(o)}catch(o){return[{name:bn,status:"fail",message:`cannot read/parse ${bn}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:bn,status:"fail",message:`no "tasks" object defined in ${bn}`}]: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 ${bn}`}})};var JE=async(e,t)=>{let{check:r,rules:n}=await Jl(e,t);return{checks:[r],rules:n}},KE={adopted:!1,workspaceRoot:null},HE=async(e,t,r)=>jo({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Dt(e)}),qE=async e=>(await yt(e).catch(()=>{}))?.e2e?.server==="static",eu=async(e,t=ht,r={})=>{let n=await Tr(e),o=n.name??GE.basename(e),{checks:s,rules:i}=r.isRoot?await Kl(e,t):await JE(e,t);r.isRoot||s.push(Gl(e,r.adoption??KE)),i&&(s.push(...Zl(n.scripts??{},i.requiredScripts)),s.push(...await Xl(e,i.requiredFiles)),s.push(...await Ql(e,i.turboTasks))),!r.isRoot&&await HE(e,n,r.repoRoot)==="e2e"&&s.push(...await Yl(e,n.scripts??{},{staticServer:await qE(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var tu=["plugin","marketplace","add",Qt],ru=["plugin","install",Z,"--scope","project"],kh=(e,t)=>Er({projectPath:e,home:t}).kind==="installed",oa=e=>((e??"").split(`
148
- `).find(r=>r.trim().length>0)??"").trim(),zE=(e,t)=>{if(Io(t))return null;d.debug({msg:`Running: ${Do} ${tu.join(" ")}`});let r=e({args:tu});return r.ok?null:{step:"marketplace",error:oa(r.output)}},YE=(e,t)=>{d.debug({msg:`Running: ${Do} ${Wi.join(" ")}`});let r=e({args:Wi});if(!r.ok)return{status:"update-failed",error:oa(r.output)};d.debug({msg:`Running: ${Do} ${Vi.join(" ")}`});let n=e({args:Vi,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:oa(n.output)}},nu=e=>{let{projectRoot:t,home:r}=e,n=e.run??hl;if(!n({args:gl}).ok)return{status:"claude-missing"};if(kh(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:YE(n,t);let o=zE(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${Do} ${ru.join(" ")}`});let s=n({args:ru,cwd:t});return s.ok?kh(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:oa(s.output)}};import XE from"node:fs";import ZE from"node:path";var Ye=".mcp.json",kt="mcpServers",QE="infra-kit",eP=["mcp"],tP="/infra-kit/dist/mcp.js",ou=" ",Dr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bh=e=>{if(!Dr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===QE&&r[0]===eP[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(tP)):!1},Rh=e=>/\n([ \t]+)"/.exec(e)?.[1]??ou,su=e=>{try{return{kind:"raw",raw:XE.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},iu=e=>{try{return JSON.parse(e)}catch{return}},au=e=>e instanceof Error?e.message:String(e),Rn=e=>{let t=su(ZE.join(e,Ye));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=iu(t.raw);if(!Dr(r)||!Dr(r[kt]))return{kind:"unparseable"};let n=r[kt];if(me in n)return{kind:"stale"};let o=Object.keys(n).find(s=>bh(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import sa from"node:fs";import rP from"node:path";var _t=`claude plugin install ${Z} --scope project`,Sn=`claude plugin marketplace update ${me} && claude plugin update ${Z} --scope project`,cu=`claude plugin marketplace add ${Qt}`,Ph=" ",xh=()=>({source:{source:"github",repo:Qt}}),nP=()=>({extraKnownMarketplaces:{[me]:xh()},enabledPlugins:{[Z]:!0}}),Th=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oP=e=>/\n([ \t]+)"/.exec(e)?.[1]??Ph,Sh=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Th(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Eh=e=>[Sh(e,"extraKnownMarketplaces",me,xh()),Sh(e,"enabledPlugins",Z,!0)].filter(r=>r!==null),sP=e=>{try{return sa.readFileSync(e,"utf-8")}catch{return null}},iP=e=>(sa.mkdirSync(rP.dirname(e),{recursive:!0}),sa.writeFileSync(e,`${JSON.stringify(nP(),null,Ph)}
149
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${me}`,`enabledPlugins.${Z}`]}),lu=(e,{write:t=!0}={})=>{let r=sP(e);if(r===null)return t?iP(e):{status:"withheld",path:e,added:Eh({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Th(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${Z}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Eh(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=oP(r),i=r.endsWith(`
141
+ `;var mh='# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `infra-kit`, the global CLI)\n\n- `ik env-load [-c <config>]` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply. Without `-c`, an agent loads the project\'s `defaultEnv` (set yours with `ik config-set defaultEnv <env>`); with none set it is refused and must ask the human.\n- `ik dev [app]` / `ik dev-status` \u2014 run this worktree\'s dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; no name runs every app. App names are per-repo: an unknown one is refused with the apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app\'s Playwright suite locally: against this worktree\'s dev server when it runs, otherwise the package\'s `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app\'s `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees. `ik worktrees add --feature <name> [--base <dev|main|release>]` creates `feature/<name>` at `<root>-worktrees/feature/<name>`, cut from the integration branch by default \u2014 `dev`, or `main` in a repo with `"gitFlow": "main"` (or without `dev`); `worktrees remove --feature <name>` removes it. To close the worktree a session runs in ("close this worktree"), run `infra-kit worktrees remove --self` from inside it: it previews, and its `--yes` re-run hands the removal to an Orca tab of the main checkout, which closes every tab of the worktree \u2014 this session included. The `/infra-kit:worktrees` skill is the agent entry point for feature worktrees \u2014 never create one with raw `git worktree add` or Claude Code\'s `EnterWorktree`, which skip `pnpm install`, the editor/Orca wiring and the `feature/` layout.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the integration branch (`dev`, or `main` under `"gitFlow": "main"`) into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against their `infra-kit.config.ts` rules (`--root`: the repo root against the `audit` block in `infra-kit.json`).\n- `ik audit --fix` \u2014 regenerate this repo\'s infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, git, aws, gh, doppler, portless).\n\n## Conventions\n\n- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.\n- Config is split by level: repo-wide settings live in the root `infra-kit.json` (personal overrides in `~/.infra-kit/`), per-package settings in that package\'s `infra-kit.config.ts`. The root has no `infra-kit.config.ts`.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- The git flow is the root `infra-kit.json` key `gitFlow`: `"dev"` (default) cuts features and regular releases from `dev` and delivers through a `dev \u2192 main` RC PR, hotfixes from `main`; `"main"` cuts everything from `main` and delivers straight into it, with no hotfix type. Never branch from `dev` in a `"main"` repo, even if a stale `dev` exists.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo\'s `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. The `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`, `vendor sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host\'s prompt on the argv is the approval. `release deliver` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root\'s `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n';var vn={"root/body":mh.trimEnd(),"package/frontend":uh.trimEnd(),"package/backend":ch.trimEnd(),"package/lib":dh.trimEnd(),"package/e2e":lh.trimEnd(),"package/mobile":ph.trimEnd(),"design/skeleton":ah.trimEnd()};var Ml=/\{\{(\w+)\}\}/g,sE=/^- \{\{(\w+)\}\}$/,iE=e=>new Set([...e.matchAll(Ml)].map(t=>t[1])),aE=(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(", ")}`)},cE=(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(", ")}`)},lE=(e,t)=>e.filter(r=>{let n=sE.exec(r);return n===null||t[n[1]]!==""}),uE=(e,t)=>{for(let r of e)for(let n of r.matchAll(Ml)){let o=t[n[1]];if(o!==void 0&&o.includes(`
142
+ `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},wn=(e,t)=>{let r=iE(e);cE(r,t),aE(r,t);let n=lE(e.split(`
143
+ `),t);return uE(n,t),n.join(`
144
+ `).replace(Ml,(o,s)=>t[s])};var dE="name: TODO",jl=e=>{let t=wn(vn["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(dE,()=>r)}
145
+ `};var pE=(e,t)=>`${Nt}${e} ${t} -->`,mE="`README.md` \u2014 what this package is and how to run it.",Fl="docs/e2e-playwright.md",fE=`\`${Fl}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,gE=["ts-check","eslint-check","test"],hE="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.",yE="Run `pnpm run build` before a dependent package can see a change.",fh=(e,t)=>e?.includes(t)??!0,vE=e=>{let t=gE.filter(r=>fh(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},Ll=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=wn(vn[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?mE:"",checksBullet:vE(a),...r==="e2e"?{e2eDocBullet:i?fE:""}:{},...r==="lib"?{surfaceBullet:c?hE:"",buildBullet:fh(a,"build")?yE:""}:{}});return[pE(t,r),"",l,""].join(`
146
+ `)};var wE=e=>`${Ar}${e} -->`,Vo=e=>{let t=wn(vn["root/body"],{});return[wE(e),"",t,""].join(`
147
+ `)};import kn from"node:fs";import kE from"node:path";var Zi=e=>{let t;try{t=kn.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Wo=(e,t)=>{let r=Go(e,t);return r!=="unchanged"&&(kn.mkdirSync(kE.dirname(e),{recursive:!0}),kn.writeFileSync(e,t,"utf-8")),r},Go=(e,t)=>{Zi(e);let r=kn.existsSync(e)?kn.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Bl=(e,t,r)=>{let n=kn.readFileSync(e,"utf-8");if(!qe(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},gh=(e,t,r)=>qe(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Ul=(e,t,r,n)=>{let o=gh(e,r,n),s=gh(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 ea="<!-- infra-kit:import:begin -->",ta="<!-- infra-kit:import:end -->",bE="AGENTS.md",hh="CLAUDE.md",RE="README.md",Vl="DESIGN.md",SE=["frontend","mobile"],EE=e=>Or.existsSync(e)?Or.readFileSync(e,"utf-8"):null,Wl=(e,t)=>{try{return Or.readdirSync(e).includes(t)}catch{return!1}},Qi=(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},yh=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=EE(e),a=i===null?"":o?.(i)??i,c=gn({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return Go(e,c);let l=Wo(e,c);return Bl(e,r,n),i!==null&&Ul(a,c,r,n),l},PE=(e,t)=>{if(!Or.existsSync(e))return"unchanged";Zi(e);let r=Or.readFileSync(e,"utf-8"),n=nr(r,Te,Fe);return n===null?"unchanged":n.trim()===""?(t||Or.rmSync(e),"removed"):t?Go(e,n):Wo(e,n)},xE=(e,t,r)=>yh({filePath:e,dryRun:r,body:Vo(t),startMarker:Te,endMarker:Fe,prepare:n=>nr(n,ea,ta)??n}),Jo=async(e,{version:t,dryRun:r=!1})=>{let n=or.join(e,hh),o=or.join(e,bE),s=[];try{s.push({path:n,action:xE(n,t,r)})}catch(i){s.push(Qi(n,i))}try{s.push({path:o,action:PE(o,r)})}catch(i){s.push(Qi(o,i))}return s},TE=(e,t,r,n)=>{if(!SE.includes(r)||Wl(e,Vl))return null;let o=or.join(e,Vl),s=jl(t);try{return{path:o,action:n?Go(o,s):Wo(o,s),type:r}}catch(i){return Qi(o,i,r)}},ra=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await Tr(e),s=o.name??or.basename(e),i=jo({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:Ll({version:r,type:i,packageName:s,relDir:or.relative(t,e).split(or.sep).join("/"),hasReadme:Wl(e,RE),hasDesign:Wl(e,Vl),hasE2eDoc:Or.existsSync(or.join(t,Fl)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},Ko=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=or.join(e,hh),{body:a,type:c,packageName:l}=await ra(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:yh({filePath:i,body:a,startMarker:ze,endMarker:ct,dryRun:s}),type:c})}catch(p){u.push(Qi(i,p,c))}if(n){let p=TE(e,l,c,s);p&&u.push(p)}return u};import zE from"node:path";import vh from"node:path";var Gl="agent-guidance",Ho="CLAUDE.md",CE="\u2014 run: infra-kit audit --fix",$E={missing:`${Ho} missing`,"no-block":`${Ho} has no infra-kit block (expected ${ze} \u2026 ${ct})`,malformed:`${Ho} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Ho} carries the ROOT infra-kit block (${Te}); a package needs the package block`},AE=e=>e.adopted?` (workspace adopted: ${vh.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Jl=(e,t)=>{let r=_t(wt(vh.join(e,Ho)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Gl,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${$E[r.state]} ${CE}`,o=r.state==="missing"?`${n}${AE(t)}`:n;return t.adopted?{name:Gl,status:"fail",message:o}:{name:Gl,status:"pass",message:`not yet adopted \u2014 ${o}`}};import OE from"node:path";var Kl=async(e,t=ht)=>{try{let r=await Lo(e,t);return{check:{name:ge,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ge,status:"fail",message:r.message},rules:null}}},wh="infra-kit.json",DE=async e=>await je(OE.join(e,ge))?{name:ge,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,Hl=async(e,t=xr)=>{let r=await DE(e),n=r?[r]:[];try{let{audit:o={}}=await L();return{checks:[{name:wh,status:"pass",message:"present and valid"},...n],rules:Fo(o,t)}}catch(o){return{checks:[{name:wh,status:"fail",message:o.message},...n],rules:null}}};import na from"node:fs/promises";import bn from"node:path";import{$ as IE}from"zx";var qo="playwright.config.ts",NE=[{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')"}],kh=e=>Object.entries(Dl).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"}}),_E="infra-kit-e2e",bh=async(e,t={})=>{let r=bn.join(e,qo),n=await na.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${qo}`,status:"fail",message:`missing ${qo}`}]:NE.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===_E?{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:`${qo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},ME=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,jE=/\.[cm]?[jt]sx?$/u,ql=async(e,t)=>(await na.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&jE.test(n.name)).map(n=>bn.join(n.parentPath,n.name)),FE=async e=>{let t=await ql(bn.join(e,"src"),!0);for(let r of[bn.join(e,qo),...t]){let n=await na.readFile(r,"utf-8").catch(()=>"");if(ME.test(n))return!0}return!1},Rh=async e=>{let t="e2e-auth:gitignored";if(!await FE(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await IE({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}`}},zl="E2E__BASIC_AUTH_USERNAME",Yl="E2E__BASIC_AUTH_PASSWORD",LE=/\bE2E_\w*BASIC_AUTH_\w+/gu,BE=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,UE=/\/\*[\s\S]*?\*\//gu,VE=/(^|[^:])\/\/[^\n]*/gu,WE=e=>/USER(?:NAME)?$/u.test(e)?zl:Yl,GE=e=>e.replace(UE,"").replace(VE,"$1"),Sh=async e=>{let t="e2e-env:basic-auth",r=[...await ql(e,!1),...await ql(bn.join(e,"src"),!0)],n=[];for(let o of r){let s=await na.readFile(o,"utf-8").catch(()=>""),i=new Set([...GE(s).matchAll(LE)].map(a=>a[0]).filter(a=>BE.test(a)&&a!==zl&&a!==Yl));for(let a of i)n.push(`${a} \u2192 ${WE(a)} (${bn.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${zl} / ${Yl}`}:{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("; ")}`}},Xl=async(e,t,r={})=>[...kh(t),...await bh(e,r),await Rh(e),await Sh(e)];import JE from"node:fs/promises";import KE from"node:path";var Zl=async(e,t)=>Promise.all(t.map(async r=>{let n=await JE.stat(KE.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 Ql=(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 HE from"node:fs/promises";import qE from"node:path";var Rn="turbo.json",eu=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await HE.readFile(qE.join(e,Rn),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Rn,status:"fail",message:`cannot read/parse ${Rn}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Rn,status:"fail",message:`no "tasks" object defined in ${Rn}`}]: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 ${Rn}`}})};var YE=async(e,t)=>{let{check:r,rules:n}=await Kl(e,t);return{checks:[r],rules:n}},XE={adopted:!1,workspaceRoot:null},ZE=async(e,t,r)=>jo({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await It(e)}),QE=async e=>(await yt(e).catch(()=>{}))?.e2e?.server==="static",tu=async(e,t=ht,r={})=>{let n=await Tr(e),o=n.name??zE.basename(e),{checks:s,rules:i}=r.isRoot?await Hl(e,t):await YE(e,t);r.isRoot||s.push(Jl(e,r.adoption??XE)),i&&(s.push(...Ql(n.scripts??{},i.requiredScripts)),s.push(...await Zl(e,i.requiredFiles)),s.push(...await eu(e,i.turboTasks))),!r.isRoot&&await ZE(e,n,r.repoRoot)==="e2e"&&s.push(...await Xl(e,n.scripts??{},{staticServer:await QE(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var ru=["plugin","marketplace","add",er],nu=["plugin","install",Z,"--scope","project"],Eh=(e,t)=>Er({projectPath:e,home:t}).kind==="installed",oa=e=>((e??"").split(`
148
+ `).find(r=>r.trim().length>0)??"").trim(),eP=(e,t)=>{if(Io(t))return null;d.debug({msg:`Running: ${Do} ${ru.join(" ")}`});let r=e({args:ru});return r.ok?null:{step:"marketplace",error:oa(r.output)}},tP=(e,t)=>{d.debug({msg:`Running: ${Do} ${Wi.join(" ")}`});let r=e({args:Wi});if(!r.ok)return{status:"update-failed",error:oa(r.output)};d.debug({msg:`Running: ${Do} ${Vi.join(" ")}`});let n=e({args:Vi,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:oa(n.output)}},ou=e=>{let{projectRoot:t,home:r}=e,n=e.run??yl;if(!n({args:hl}).ok)return{status:"claude-missing"};if(Eh(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:tP(n,t);let o=eP(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${Do} ${nu.join(" ")}`});let s=n({args:nu,cwd:t});return s.ok?Eh(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:oa(s.output)}};import rP from"node:fs";import nP from"node:path";var Ye=".mcp.json",kt="mcpServers",oP="infra-kit",sP=["mcp"],iP="/infra-kit/dist/mcp.js",su=" ",Dr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ph=e=>{if(!Dr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===oP&&r[0]===sP[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(iP)):!1},xh=e=>/\n([ \t]+)"/.exec(e)?.[1]??su,iu=e=>{try{return{kind:"raw",raw:rP.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},au=e=>{try{return JSON.parse(e)}catch{return}},cu=e=>e instanceof Error?e.message:String(e),Sn=e=>{let t=iu(nP.join(e,Ye));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=au(t.raw);if(!Dr(r)||!Dr(r[kt]))return{kind:"unparseable"};let n=r[kt];if(me in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Ph(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import sa from"node:fs";import aP from"node:path";var Mt=`claude plugin install ${Z} --scope project`,En=`claude plugin marketplace update ${me} && claude plugin update ${Z} --scope project`,lu=`claude plugin marketplace add ${er}`,$h=" ",Ah=()=>({source:{source:"github",repo:er}}),cP=()=>({extraKnownMarketplaces:{[me]:Ah()},enabledPlugins:{[Z]:!0}}),Oh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lP=e=>/\n([ \t]+)"/.exec(e)?.[1]??$h,Th=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Oh(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Ch=e=>[Th(e,"extraKnownMarketplaces",me,Ah()),Th(e,"enabledPlugins",Z,!0)].filter(r=>r!==null),uP=e=>{try{return sa.readFileSync(e,"utf-8")}catch{return null}},dP=e=>(sa.mkdirSync(aP.dirname(e),{recursive:!0}),sa.writeFileSync(e,`${JSON.stringify(cP(),null,$h)}
149
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${me}`,`enabledPlugins.${Z}`]}),uu=(e,{write:t=!0}={})=>{let r=uP(e);if(r===null)return t?dP(e):{status:"withheld",path:e,added:Ch({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Oh(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${Z}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Ch(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=lP(r),i=r.endsWith(`
150
150
  `)?`
151
- `:"";return sa.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var R=e=>[{type:"text",text:e}],T=e=>e;var aP="empty-rules",cP=["requiredScripts","requiredFiles"],Ch=(e,t,r)=>cP.filter(n=>e[n]?.length===0).map(n=>({name:aP,status:"fail",message:`${r} sets ${n}: [], which disables the check instead of relaxing it \u2014 delete the key to inherit the defaults (${t[n].join(", ")}), or list what this target really has`})),$h=async(e,t)=>{try{if(t){let{audit:r={}}=await L();return Ch(r,xr,'infra-kit.json "audit"')}return Ch(await yt(e)??{},ht,"infra-kit.config.ts")}catch{return[]}};import uP from"node:path";import dP from"node:process";import zo from"node:fs/promises";import uu from"node:path";var Oh="infra-kit.json",Ah=["requiredScripts","requiredFiles","turbo"],or=(e,t)=>[{path:e,action:"failed",message:t}],Dh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ih=async e=>{let t=uu.join(e,ge),r=uu.join(e,Oh),n;try{n=await yt(e)}catch(c){return or(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Ah.includes(c));if(s.length>0)return or(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Ah.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await zo.stat(r),l=await zo.readFile(r,"utf8"),u=JSON.parse(l);if(!Dh(u))return or(r,"is not a JSON object");if("audit"in u)return or(r,`already has an "audit" block \u2014 merge ${ge}'s rules into it by hand, then delete ${ge}`);await ul({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return or(r,c.message)}try{await zo.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a},lP=e=>typeof e!="string"?null:/^https:\/\/unpkg\.com\/infra-kit@([^/]+)\//.exec(e)?.[1]??null,Nh=async(e,t)=>{let r=uu.join(e,Oh);try{let n=await zo.stat(r),o=await zo.readFile(r,"utf8"),s=JSON.parse(o);if(!Dh(s))return or(r,"is not a JSON object");if(typeof s.configVersion=="number"&&s.configVersion>Ao)return or(r,`declares configVersion ${s.configVersion}; this CLI reads up to ${Ao}`);let i=lP(s.$schema),c=s.$schema!==void 0&&i===null||i!==null&&at(i,t)?s.$schema:Rg(t);if(s.$schema===c&&s.configVersion===Ao)return[];let l=Object.entries(s).filter(([u])=>u!=="$schema"&&u!=="configVersion");return await ul({path:r,raw:o,migrated:{$schema:c,configVersion:Ao,...Object.fromEntries(l)},expectedMtimeMs:n.mtimeMs}),[{path:r,action:"updated"}]}catch(n){return n.code==="ENOENT"?[]:or(r,n.message)}};var pP=["unchanged","created"],mP=["unchanged","created","updated","removed","failed"],_h=async(e,t,r)=>{let n=await Dt(e);return Ko(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},fP=async(e,t)=>{if(e.root)return[...await Ih(t),...await Nh(t,U.version),...await Jo(t,{version:U.version})];if(e.all){let n=[],{packages:o}=await Cr(t,await Pr());for(let s of o)n.push(...await _h(s,t,e.design));return n}let r=await Uo(e.cwd??dP.cwd());return _h(r,t,e.design)},gP=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 ${mP.filter(n=>pP.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},hP=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=uP.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(gP(e))},yP=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Mh=async(e,t)=>{let r=await $();Xi();let n=await hn(t),o=await fP(e,r);hP(o,r),Xi();let s=await hn(t),i=!e.all&&!e.root;return{fixed:o.map(yP),adoptionFlipped:i&&!n.adopted&&s.adopted}};import ia from"node:fs/promises";import aa from"node:path";import vP from"yaml";var Yo="dependency-drift",du="@slip-stream-kit/",wP="infra-kit",kP=["dependencies","devDependencies","optionalDependencies"],Lh=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),mu=e=>e.startsWith("catalog:"),bP=(e,t,r)=>{if(!mu(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},jh=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},RP=(e,t)=>{let r=jh(e),n=jh(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},SP=e=>{let t=new Map;for(let r of e){let n=t.get(r.name);n?n.push(r):t.set(r.name,[r])}return t},pu=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),EP=(e,t)=>[...SP(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!mu(s.spec));return o.length===0?[]:[{name:`${Yo}:catalog`,status:"fail",message:`${r} has a catalog entry (${t.default[r]}) but ${pu(o)} bypass it \u2014 run \`ik audit --fix --root\` to rewrite them to "catalog:", then pnpm install`}]}return new Set(n.map(o=>o.spec)).size<=1?[]:[{name:`${Yo}:catalog`,status:"fail",message:`${r} is pinned at more than one range: ${pu(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),PP=(e,t,r)=>{let n=new Map;for(let o of e){let s=bP(o.spec,t,o.name);s!==void 0&&RP(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${Yo}:lockstep`,status:"warn",message:`${o} is behind the infra-kit ${r} lockstep release \u2014 bump it to ^${r}`}))},xP=e=>{let t=e.filter(r=>r.name===wP);return t.length===0?[]:[{name:`${Yo}:infra-kit-pin`,status:"warn",message:`${pu(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},TP=(e,t,r)=>{let n=e.filter(i=>!Lh(i.spec)),o=n.filter(i=>i.name.startsWith(du)),s=[...EP(o,t),...PP(o,t,r),...xP(n)];return s.length>0?s:[{name:Yo,status:"pass",message:`no ${du}* or infra-kit dependency drift`}]},CP=async e=>{try{return JSON.parse(await ia.readFile(e,"utf-8"))}catch{return null}},$P=async e=>{try{let t=vP.parse(await ia.readFile(aa.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},AP=async e=>{let t=await vt(e).catch(()=>[]);return[e,...t].map(r=>aa.join(r,"package.json"))},Fh=async e=>{let t=[];for(let r of await AP(e)){let n=await CP(r);if(!n)continue;let o=aa.relative(e,r);for(let s of kP){let i=n[s]??{};for(let[a,c]of Object.entries(i))typeof c=="string"&&t.push({file:o,section:s,name:a,spec:c})}}return t},OP=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(du)&&!Lh(s.spec)&&!mu(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=aa.join(e,s),a=await ia.readFile(i,"utf-8"),c=JSON.parse(a);for(let u of n)u.file===s&&(c[u.section][u.name]="catalog:");let l=a.match(/^[ \t]+(?=")/m)?.[0]??" ";await ia.writeFile(i,`${JSON.stringify(c,null,l)}
152
- `,"utf-8")}return o},Bh=async(e,t,r=U.version)=>{let n=await $P(e),o=await Fh(e),s=t?await OP(e,o,n):[],i=s.length>0?await Fh(e):o;return{checks:TP(i,n,r),rewritten:s}};import Vh from"node:path";var ca="agent-guidance:drift",DP={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Uh=(e,t)=>e.split(`
151
+ `:"";return sa.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var R=e=>[{type:"text",text:e}],T=e=>e;var pP="empty-rules",mP=["requiredScripts","requiredFiles"],Dh=(e,t,r)=>mP.filter(n=>e[n]?.length===0).map(n=>({name:pP,status:"fail",message:`${r} sets ${n}: [], which disables the check instead of relaxing it \u2014 delete the key to inherit the defaults (${t[n].join(", ")}), or list what this target really has`})),Ih=async(e,t)=>{try{if(t){let{audit:r={}}=await L();return Dh(r,xr,'infra-kit.json "audit"')}return Dh(await yt(e)??{},ht,"infra-kit.config.ts")}catch{return[]}};import hP from"node:path";import yP from"node:process";import zo from"node:fs/promises";import du from"node:path";import{isDeepStrictEqual as _h}from"node:util";var Mh="infra-kit.json",Nh=["requiredScripts","requiredFiles","turbo"],bt=(e,t)=>[{path:e,action:"failed",message:t}],jh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fh=async e=>{let t=du.join(e,ge),r=du.join(e,Mh),n;try{n=await yt(e)}catch(c){return bt(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Nh.includes(c));if(s.length>0)return bt(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Nh.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await zo.stat(r),l=await zo.readFile(r,"utf8"),u=JSON.parse(l);if(!jh(u))return bt(r,"is not a JSON object");if("audit"in u)return bt(r,`already has an "audit" block \u2014 merge ${ge}'s rules into it by hand, then delete ${ge}`);let p=ag(l,[["audit",i]],ul(l));if(p===null||!_h(JSON.parse(p),{...u,audit:i}))return bt(r,'could not add the "audit" block without rewriting the file \u2014 add it by hand');await dl({path:r,content:p,expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return bt(r,c.message)}try{await zo.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a},fP=e=>typeof e!="string"?null:/^https:\/\/unpkg\.com\/infra-kit@([^/]+)\//.exec(e)?.[1]??null,gP=(e,t)=>{let r=[],n=e;for(let[o,s]of Object.entries(t)){let i=n===null?null:cg(n,o,s);i===null?r.push([o,s]):n=i}return n===null?null:ig(n,r,ul(e))},Lh=async(e,t)=>{let r=du.join(e,Mh);try{let n=await zo.stat(r),o=await zo.readFile(r,"utf8"),s=JSON.parse(o);if(!jh(s))return bt(r,"is not a JSON object");if(typeof s.configVersion=="number"&&s.configVersion>mn)return bt(r,`declares configVersion ${s.configVersion}; this CLI reads up to ${mn}`);let i=fP(s.$schema),c=s.$schema!==void 0&&i===null||i!==null&&at(i,t)?s.$schema:xg(t);if(s.$schema===c&&s.configVersion===mn)return[];let l=gP(o,{$schema:c,configVersion:mn});return l===null||!_h(JSON.parse(l),{...s,$schema:c,configVersion:mn})?bt(r,"could not insert $schema/configVersion without rewriting the file \u2014 add them by hand"):(await dl({path:r,content:l,expectedMtimeMs:n.mtimeMs}),[{path:r,action:"updated"}])}catch(n){return n.code==="ENOENT"?[]:bt(r,n.message)}};var vP=["unchanged","created"],wP=["unchanged","created","updated","removed","failed"],Bh=async(e,t,r)=>{let n=await It(e);return Ko(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},kP=async(e,t)=>{if(e.root)return[...await Fh(t),...await Lh(t,U.version),...await Jo(t,{version:U.version})];if(e.all){let n=[],{packages:o}=await Cr(t,await Pr());for(let s of o)n.push(...await Bh(s,t,e.design));return n}let r=await Uo(e.cwd??yP.cwd());return Bh(r,t,e.design)},bP=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 ${wP.filter(n=>vP.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},RP=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=hP.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(bP(e))},SP=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Uh=async(e,t)=>{let r=await $();Xi();let n=await yn(t),o=await kP(e,r);RP(o,r),Xi();let s=await yn(t),i=!e.all&&!e.root;return{fixed:o.map(SP),adoptionFlipped:i&&!n.adopted&&s.adopted}};import ia from"node:fs/promises";import aa from"node:path";import EP from"yaml";var Yo="dependency-drift",pu="@slip-stream-kit/",PP="infra-kit",xP=["dependencies","devDependencies","optionalDependencies"],Gh=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),fu=e=>e.startsWith("catalog:"),TP=(e,t,r)=>{if(!fu(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},Vh=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},CP=(e,t)=>{let r=Vh(e),n=Vh(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},$P=e=>{let t=new Map;for(let r of e){let n=t.get(r.name);n?n.push(r):t.set(r.name,[r])}return t},mu=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),AP=(e,t)=>[...$P(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!fu(s.spec));return o.length===0?[]:[{name:`${Yo}:catalog`,status:"fail",message:`${r} has a catalog entry (${t.default[r]}) but ${mu(o)} bypass it \u2014 run \`ik audit --fix --root\` to rewrite them to "catalog:", then pnpm install`}]}return new Set(n.map(o=>o.spec)).size<=1?[]:[{name:`${Yo}:catalog`,status:"fail",message:`${r} is pinned at more than one range: ${mu(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),OP=(e,t,r)=>{let n=new Map;for(let o of e){let s=TP(o.spec,t,o.name);s!==void 0&&CP(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${Yo}:lockstep`,status:"warn",message:`${o} is behind the infra-kit ${r} lockstep release \u2014 bump it to ^${r}`}))},DP=e=>{let t=e.filter(r=>r.name===PP);return t.length===0?[]:[{name:`${Yo}:infra-kit-pin`,status:"warn",message:`${mu(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},IP=(e,t,r)=>{let n=e.filter(i=>!Gh(i.spec)),o=n.filter(i=>i.name.startsWith(pu)),s=[...AP(o,t),...OP(o,t,r),...DP(n)];return s.length>0?s:[{name:Yo,status:"pass",message:`no ${pu}* or infra-kit dependency drift`}]},NP=async e=>{try{return JSON.parse(await ia.readFile(e,"utf-8"))}catch{return null}},_P=async e=>{try{let t=EP.parse(await ia.readFile(aa.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},MP=async e=>{let t=await vt(e).catch(()=>[]);return[e,...t].map(r=>aa.join(r,"package.json"))},Wh=async e=>{let t=[];for(let r of await MP(e)){let n=await NP(r);if(!n)continue;let o=aa.relative(e,r);for(let s of xP){let i=n[s]??{};for(let[a,c]of Object.entries(i))typeof c=="string"&&t.push({file:o,section:s,name:a,spec:c})}}return t},jP=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(pu)&&!Gh(s.spec)&&!fu(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=aa.join(e,s),a=await ia.readFile(i,"utf-8"),c=JSON.parse(a);for(let u of n)u.file===s&&(c[u.section][u.name]="catalog:");let l=a.match(/^[ \t]+(?=")/m)?.[0]??" ";await ia.writeFile(i,`${JSON.stringify(c,null,l)}
152
+ `,"utf-8")}return o},Jh=async(e,t,r=U.version)=>{let n=await _P(e),o=await Wh(e),s=t?await jP(e,o,n):[],i=s.length>0?await Wh(e):o;return{checks:IP(i,n,r),rewritten:s}};import Hh from"node:path";var ca="agent-guidance:drift",FP={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Kh=(e,t)=>e.split(`
153
153
  `).filter(r=>!r.startsWith(t)).join(`
154
- `),Wh=({content:e,expectedBody:t,startMarker:r,endMarker:n,versionPrefix:o,current:s,scope:i})=>{let a=e.slice(e.indexOf(r),e.indexOf(n)+n.length),c=Yi(r,t,n);if(Uh(a,o)===Uh(c,o))return{name:ca,status:"pass",message:`matches infra-kit ${s}`};let l=$r(a,o),u=DP[i];return l!==null&&at(l,s)?{name:ca,status:"warn",message:`block from infra-kit ${l} is newer than this CLI (${s}) \u2014 CLI behind the block, run \`pnpm add -g infra-kit@${l}\``}:l!==null&&at(s,l)?{name:ca,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:ca,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},Gh=(e,t=U.version)=>{let r=wt(Vh.join(e,"CLAUDE.md"));return r===null||!qe(r,Te,Fe)?null:Wh({content:r,expectedBody:Vo(t),startMarker:Te,endMarker:Fe,versionPrefix:Ar,current:t,scope:"root"})},Jh=async(e,t,r,n=U.version)=>{let o=wt(Vh.join(e,"CLAUDE.md"));if(o===null||Nt(o).state!=="ok")return null;let s;try{({body:s}=await ra(e,{repoRoot:t,version:n,declaredType:await Dt(e)}))}catch{return null}return Wh({content:o,expectedBody:s,startMarker:ze,endMarker:ct,versionPrefix:It,current:n,scope:r})};import Hh from"node:fs";import qh from"node:path";var fu="ik-mcp",Kh=(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:fu,args:r}};var la="run `infra-kit setup` (or `infra-kit audit --root --fix`)",IP=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),gu=e=>Dr(e)&&e.command===fu,NP=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),_P=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Kh(i,a),l=e[i];if(l!==void 0&&!gu(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 ${la}, or drop mcp.${i} from infra-kit.json`});continue}if(gu(l)&&l.type===c.type&&IP(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=NP(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: ${la}`:`"${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: ${la}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!gu(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}},MP=(e,t,r)=>{let n=r===null?ou:Rh(r),o=r===null||r.endsWith(`
154
+ `),qh=({content:e,expectedBody:t,startMarker:r,endMarker:n,versionPrefix:o,current:s,scope:i})=>{let a=e.slice(e.indexOf(r),e.indexOf(n)+n.length),c=Yi(r,t,n);if(Kh(a,o)===Kh(c,o))return{name:ca,status:"pass",message:`matches infra-kit ${s}`};let l=$r(a,o),u=FP[i];return l!==null&&at(l,s)?{name:ca,status:"warn",message:`block from infra-kit ${l} is newer than this CLI (${s}) \u2014 CLI behind the block, run \`pnpm add -g infra-kit@${l}\``}:l!==null&&at(s,l)?{name:ca,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:ca,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},zh=(e,t=U.version)=>{let r=wt(Hh.join(e,"CLAUDE.md"));return r===null||!qe(r,Te,Fe)?null:qh({content:r,expectedBody:Vo(t),startMarker:Te,endMarker:Fe,versionPrefix:Ar,current:t,scope:"root"})},Yh=async(e,t,r,n=U.version)=>{let o=wt(Hh.join(e,"CLAUDE.md"));if(o===null||_t(o).state!=="ok")return null;let s;try{({body:s}=await ra(e,{repoRoot:t,version:n,declaredType:await It(e)}))}catch{return null}return qh({content:o,expectedBody:s,startMarker:ze,endMarker:ct,versionPrefix:Nt,current:n,scope:r})};import Zh from"node:fs";import Qh from"node:path";var gu="ik-mcp",Xh=(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:gu,args:r}};var la="run `infra-kit setup` (or `infra-kit audit --root --fix`)",LP=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),hu=e=>Dr(e)&&e.command===gu,BP=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),UP=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Xh(i,a),l=e[i];if(l!==void 0&&!hu(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 ${la}, or drop mcp.${i} from infra-kit.json`});continue}if(hu(l)&&l.type===c.type&&LP(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=BP(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: ${la}`:`"${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: ${la}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!hu(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}},VP=(e,t,r)=>{let n=r===null?su:xh(r),o=r===null||r.endsWith(`
155
155
  `)?`
156
- `:"";try{return Hh.mkdirSync(qh.dirname(e),{recursive:!0}),Hh.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${au(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Xo=({projectRoot:e,proxies:t,write:r})=>{let n=qh.join(e,Ye),o=su(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${au(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:iu(s);if(!Dr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${la}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[kt];if(a!==void 0&&!Dr(a))return d.warn(`${n} has a "${kt}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=_P(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=MP(n,{...i,[kt]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var zh=async(e,t)=>{let r;try{r=(await L()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Xo({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(a=>a.status!=="unchanged"&&a.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(a=>({name:`mcp:${a.name}`,status:"fail",message:a.message})),i=s.every(a=>a.status!=="fail");return{packageDir:e,packageName:"mcp",checks:s,passed:i}};var jP="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",FP=async e=>{if(e.root)return{targets:[{dir:await $(),baseline:xr,isRoot:!0}]};if(e.all){let t=await $(),{packages:r,excluded:n}=await Cr(t,await Pr());return{targets:r.map(o=>({dir:o})),excluded:n.map(o=>Yh.relative(t,o).split(Yh.sep).join("/"))}}return{targets:[{dir:await Uo(e.cwd??Xh.cwd())}]}},LP=async e=>e.root||e.all?await $():e.cwd??Xh.cwd(),BP=async()=>{try{return await $()}catch{return}},UP=e=>{let t=0,r=0,n=0;for(let c of e)for(let l of c.checks)t+=1,l.status==="fail"?(r+=1,d.info(`[FAIL] ${c.packageName} ${l.name}: ${l.message}`)):l.status==="warn"&&(n+=1,d.info(`[WARN] ${c.packageName} ${l.name}: ${l.message}`));let o=e.every(c=>c.passed),s=(c,l)=>`${c} ${l}${c===1?"":"s"}`,i=`${s(t,"check")}, ${s(e.length,"target")}`,a=n>0?` (${s(n,"warning")})`:"";return d.info(o?`\u2705 audit passed \u2014 ${i}${a}`:`\u274C audit failed \u2014 ${r}/${i}${a}`),{allPassed:o,warnCount:n}},VP=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Mh(e,t);return n&&d.info(jP),r},WP=e=>{if(Rn(e).kind!=="stale")return null;let t=`${Ye} still registers "${me}" \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 "${me}" 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}},GP=e=>e.root?"root":e.all?"all":"package",JP=async(e,t,r)=>{let n=await $h(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await Jh(e.dir,r??e.dir,GP(t));return a?[a,...n]:n}let o=Gh(e.dir),{checks:s,rewritten:i}=await Bh(e.dir,t.fix===!0);for(let a of i)d.info(` ${"updated".padEnd(9)} ${a} (@slip-stream-kit/* \u2192 catalog:)`);return[...o?[o]:[],...n,...s]},ua=async(e={})=>{let t=Nl(await LP(e)),r=e.fix?await VP(e,t):void 0,{targets:n,excluded:o}=await FP(e);o&&o.length>0&&d.info(`${o.length} package${o.length===1?"":"s"} excluded by infra-kit.json audit.exclude`);let s=await hn(t),i=await BP(),a=[];for(let p of n){let m=await eu(p.dir,p.baseline,{adoption:s,isRoot:p.isRoot,repoRoot:i});m.checks.push(...await JP(p,e,i)),m.passed=m.checks.every(f=>f.status!=="fail"),a.push(m)}if(e.root){let p=await zh(n[0].dir,e.fix===!0);p&&a.push(p);let m=WP(n[0].dir);m&&a.push(m)}let{allPassed:c,warnCount:l}=UP(a),u={allPassed:c,warnCount:l,packages:a.map(p=>({name:p.packageName,passed:p.passed,checks:p.checks}))};return r&&(u.fixed=r),o&&(u.excluded=o),{content:R(JSON.stringify(u,null,2)),structuredContent:u}},KP={all:Ce.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ce.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},HP={allPassed:Ce.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:Ce.number().int().describe("How many checks reported a warning"),packages:Ce.array(Ce.object({name:Ce.string(),passed:Ce.boolean(),checks:Ce.array(Ce.object({name:Ce.string(),status:Ce.enum(["pass","warn","fail"]),message:Ce.string()}))})).describe("Per-package check results"),excluded:Ce.array(Ce.string()).optional().describe("On an `all` run: the repo-relative packages infra-kit.json `audit.exclude` skipped")},hu=T({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:KP,outputSchema:HP,handler:e=>ua({all:e.all,root:e.root})});import{z as B}from"zod";import{$ as nx}from"zx";var yu=1.959963984540054,qP=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],vu=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,wu=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],zP=/This reverts commit ([0-9a-f]{7,40})/u,Qh=/^Revert "(.*)"(?: \(#\d+\))?$/u,ey="",da="",ty=`--format=${ey}%H${da}%ct${da}%B${da}`,ry=e=>e.split(ey).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split(da),i=o.trim();return{hash:r,committedAt:Number(n),subject:i.split(`
156
+ `:"";try{return Zh.mkdirSync(Qh.dirname(e),{recursive:!0}),Zh.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${cu(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Xo=({projectRoot:e,proxies:t,write:r})=>{let n=Qh.join(e,Ye),o=iu(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${cu(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:au(s);if(!Dr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${la}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[kt];if(a!==void 0&&!Dr(a))return d.warn(`${n} has a "${kt}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=UP(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=VP(n,{...i,[kt]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var ey=async(e,t)=>{let r;try{r=(await L()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Xo({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(a=>a.status!=="unchanged"&&a.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(a=>({name:`mcp:${a.name}`,status:"fail",message:a.message})),i=s.every(a=>a.status!=="fail");return{packageDir:e,packageName:"mcp",checks:s,passed:i}};var WP="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",GP=async e=>{if(e.root)return{targets:[{dir:await $(),baseline:xr,isRoot:!0}]};if(e.all){let t=await $(),{packages:r,excluded:n}=await Cr(t,await Pr());return{targets:r.map(o=>({dir:o})),excluded:n.map(o=>ty.relative(t,o).split(ty.sep).join("/"))}}return{targets:[{dir:await Uo(e.cwd??ry.cwd())}]}},JP=async e=>e.root||e.all?await $():e.cwd??ry.cwd(),KP=async()=>{try{return await $()}catch{return}},HP=e=>{let t=0,r=0,n=0;for(let c of e)for(let l of c.checks)t+=1,l.status==="fail"?(r+=1,d.info(`[FAIL] ${c.packageName} ${l.name}: ${l.message}`)):l.status==="warn"&&(n+=1,d.info(`[WARN] ${c.packageName} ${l.name}: ${l.message}`));let o=e.every(c=>c.passed),s=(c,l)=>`${c} ${l}${c===1?"":"s"}`,i=`${s(t,"check")}, ${s(e.length,"target")}`,a=n>0?` (${s(n,"warning")})`:"";return d.info(o?`\u2705 audit passed \u2014 ${i}${a}`:`\u274C audit failed \u2014 ${r}/${i}${a}`),{allPassed:o,warnCount:n}},qP=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Uh(e,t);return n&&d.info(WP),r},zP=e=>{if(Sn(e).kind!=="stale")return null;let t=`${Ye} still registers "${me}" \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 "${me}" 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}},YP=e=>e.root?"root":e.all?"all":"package",XP=async(e,t,r)=>{let n=await Ih(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await Yh(e.dir,r??e.dir,YP(t));return a?[a,...n]:n}let o=zh(e.dir),{checks:s,rewritten:i}=await Jh(e.dir,t.fix===!0);for(let a of i)d.info(` ${"updated".padEnd(9)} ${a} (@slip-stream-kit/* \u2192 catalog:)`);return[...o?[o]:[],...n,...s]},ua=async(e={})=>{let t=_l(await JP(e)),r=e.fix?await qP(e,t):void 0,{targets:n,excluded:o}=await GP(e);o&&o.length>0&&d.info(`${o.length} package${o.length===1?"":"s"} excluded by infra-kit.json audit.exclude`);let s=await yn(t),i=await KP(),a=[];for(let p of n){let m=await tu(p.dir,p.baseline,{adoption:s,isRoot:p.isRoot,repoRoot:i});m.checks.push(...await XP(p,e,i)),m.passed=m.checks.every(f=>f.status!=="fail"),a.push(m)}if(e.root){let p=await ey(n[0].dir,e.fix===!0);p&&a.push(p);let m=zP(n[0].dir);m&&a.push(m)}let{allPassed:c,warnCount:l}=HP(a),u={allPassed:c,warnCount:l,packages:a.map(p=>({name:p.packageName,passed:p.passed,checks:p.checks}))};return r&&(u.fixed=r),o&&(u.excluded=o),{content:R(JSON.stringify(u,null,2)),structuredContent:u}},ZP={all:Ce.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ce.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},QP={allPassed:Ce.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:Ce.number().int().describe("How many checks reported a warning"),packages:Ce.array(Ce.object({name:Ce.string(),passed:Ce.boolean(),checks:Ce.array(Ce.object({name:Ce.string(),status:Ce.enum(["pass","warn","fail"]),message:Ce.string()}))})).describe("Per-package check results"),excluded:Ce.array(Ce.string()).optional().describe("On an `all` run: the repo-relative packages infra-kit.json `audit.exclude` skipped")},yu=T({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:ZP,outputSchema:QP,handler:e=>ua({all:e.all,root:e.root})});import{z as B}from"zod";import{$ as lx}from"zx";var vu=1.959963984540054,ex=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],wu=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,ku=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],tx=/This reverts commit ([0-9a-f]{7,40})/u,oy=/^Revert "(.*)"(?: \(#\d+\))?$/u,sy="",da="",iy=`--format=${sy}%H${da}%ct${da}%B${da}`,ay=e=>e.split(sy).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split(da),i=o.trim();return{hash:r,committedAt:Number(n),subject:i.split(`
157
157
  `)[0]??"",body:i,files:s.split(`
158
- `).map(a=>a.trim()).filter(Boolean)}}),YP=e=>qP.some(t=>t.test(e.body))?"agent":"human",ku=e=>Qh.test(e.subject),XP=e=>!ku(e)&&vu.test(e.subject),ZP=(e,t)=>{if(t===0)return null;let r=e/t,n=yu*yu,o=1+n/t,s=(r+n/(2*t))/o,i=yu*Math.sqrt(r*(1-r)/t+n/(4*t*t))/o;return{low:Math.max(0,s-i),high:Math.min(1,s+i)}},pa=e=>Math.round(e*1e4)/1e4,Zh=(e,t)=>{let r=ZP(e,t);return{hits:e,n:t,rate:t===0?null:pa(e/t),ci95:r&&{low:pa(r.low),high:pa(r.high)}}},QP=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!ku(n))continue;let o=e.slice(0,r),s=zP.exec(n.body)?.[1],i=Qh.exec(n.subject)?.[1],a=s?o.find(c=>c.hash.startsWith(s)):o.findLast(c=>c.subject===i);a&&t.add(a.hash)}return t},ex=(e,t)=>{let r=new Set(e.files.filter(n=>!wu.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},tx=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&XP(n)&&ex(e,n)),ny=(e,t)=>{let r=QP(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(YP(u))),i=s.filter(({commit:u})=>!ku(u)),a=i.filter(({commit:u})=>t-u.committedAt>=259200),c=i.filter(({commit:u})=>r.has(u.hash)).length,l=a.filter(({commit:u,position:p})=>tx(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:Zh(c,i.length),followUpFixRate:Zh(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},bu=(e,t)=>{let r=[e.n<30?`agent n=${e.n}`:null,t.n<30?`human n=${t.n}`:null].filter(Boolean);return r.length>0||e.rate===null||t.rate===null||!e.ci95||!t.ci95?{suppressed:!0,reason:`${r.join(", ")} < 30`,difference:null,intervalsOverlap:null}:{suppressed:!1,reason:null,difference:pa(e.rate-t.rate),intervalsOverlap:e.ci95.low<=t.ci95.high&&t.ci95.low<=e.ci95.high}};var Zo=90,ox=864e5,sx=async(e,t)=>{if(await Oe(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await nx({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${ty}`;return ry(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},cy=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*ox).toISOString(),o=await sx(e,n),s=ny(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:bu(s.agent.revertRate,s.human.revertRate),followUpFixRate:bu(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:vu.source,followUpWindowHours:72,followUpIgnoredFiles:wu,mergesExcluded:!0}}},ma=e=>`${(e*100).toFixed(1)}%`,oy=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${ma(e.rate)} (${e.hits}/${e.n}, 95% CI ${ma(e.ci95.low)}\u2013${ma(e.ci95.high)})`,Ru=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${oy(t.revertRate)}`,` ${72}h follow-up-fix rate: ${oy(t.followUpFixRate)}`].join(`
159
- `),fa=async({since:e=Zo})=>{let t=await cy({cwd:await $(),sinceDays:e,nowMs:Date.now()}),{classes:r,comparison:n}=t;d.info(`Change stats for ${t.repoRoot} \u2014 last ${e} days (${t.from.slice(0,10)} \u2192 ${t.until.slice(0,10)}, merges excluded)`),d.info(Ru("agent",r.agent)),d.info(Ru("human",r.human)),d.info(Ru("total",r.total));let o=(s,i)=>{if(i.suppressed)return` ${s}: comparison suppressed (${i.reason})`;let a=i.intervalsOverlap?"intervals overlap":"intervals do not overlap";return` ${s}: agent \u2212 human = ${ma(i.difference??0)} (${a})`};return d.info(["Agent vs human:",o("revert rate",n.revertRate),o("follow-up-fix rate",n.followUpFixRate)].join(`
160
- `)),{content:R(JSON.stringify(t,null,2)),structuredContent:t}},sy=B.object({hits:B.number().describe("Changes that hit the metric"),n:B.number().describe("Changes the rate is computed over"),rate:B.number().nullable().describe("hits / n, rounded to 4 places; null when n is 0"),ci95:B.object({low:B.number(),high:B.number()}).nullable().describe("Wilson 95% score interval; null when n is 0")}),Su=B.object({commits:B.number().describe("Non-merge commits in range for this class"),reverts:B.number().describe("Of those, revert commits (excluded from both rate denominators)"),changes:B.number().describe("Non-revert commits \u2014 the revert-rate denominator"),revertRate:sy.describe("Changes later reverted by an in-range commit"),followUpFixRate:sy.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),iy=B.object({suppressed:B.boolean().describe("True when either class has n below minN"),reason:B.string().nullable(),difference:B.number().nullable().describe("agent rate \u2212 human rate"),intervalsOverlap:B.boolean().nullable().describe("Whether the two Wilson intervals overlap")}),Eu=T({name:"change-stats",description:"Read-only change-failure baseline for the git repo at cwd: commits classified agent (Claude trailers) vs human, with revert rate and 72h follow-up-fix rate per class, each with n and a Wilson 95% interval. The agent-vs-human comparison is suppressed when either n < 30.",inputSchema:{since:B.number().int().positive().optional().describe(`Window in days, ending now (default ${Zo})`)},outputSchema:{repoRoot:B.string().describe("git toplevel the stats were read from"),sinceDays:B.number(),from:B.string().describe("ISO start of the window"),until:B.string().describe("ISO end of the window (now)"),classes:B.object({agent:Su,human:Su,total:Su}),comparison:B.object({minN:B.number(),revertRate:iy,followUpFixRate:iy}),heuristics:B.object({agentTrailers:B.array(B.string()),fixSubjectPattern:B.string(),followUpWindowHours:B.number(),followUpIgnoredFiles:B.array(B.string()),mergesExcluded:B.boolean()})},handler:fa});import{z as sr}from"zod";import Pu from"node:fs/promises";import ix from"node:path";var En=()=>Object.keys(Sg.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),ax=new Set(["protectedEnvs"]),Pn={project:"per-project override",global:"user-global override"},Qo=(e,t)=>{if(te()&&ax.has(e))throw new A({status:"refused",agentMode:N.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!En().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: ${En().join(", ")}.`)}},xu=e=>{try{return JSON.parse(e)}catch{return e}},cx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lx=async e=>{let t;try{t=await Pu.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${w(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!cx(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},ux=async(e,t)=>{t===null?await Pu.rm(e,{force:!0}):st(e,t,420),Oo()},es=async(e,t,r)=>{let n=await X(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await lx(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Pu.mkdir(ix.dirname(o),{recursive:!0}),st(o,`${JSON.stringify(c,null,2)}
161
- `,420),Oo();try{await L({autoMigrate:"off"})}catch(l){throw await ux(o,s),new Error(`${l.message}
162
- ${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}};var ga=async({key:e}={})=>{let[t,r]=await Promise.all([L(),X()]),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(!En().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${En().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},dx={config:sr.record(sr.string(),sr.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:sr.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:sr.string().optional().describe("The top-level key asked for, when one was."),value:sr.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:sr.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Tu=T({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:sr.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:dx,handler:e=>ga(e)});import yx from"node:fs";import{z as he}from"zod";import rs from"node:fs";import xn from"node:path";import px from"node:process";var mx=xn.join(".infra-kit","dev-context"),fx=".infra-kit",ly=(e,t)=>{let r=xn.resolve(e);for(;;){let n=xn.join(r,t);if(rs.existsSync(n))return n;let o=xn.dirname(r);if(o===r)return;r=o}},gx=e=>{let t=ly(e,mx);if(t)return t;let r=ly(e,fx);return r?xn.join(r,"dev-context"):void 0},Cu=e=>typeof e=="number"&&Number.isFinite(e)?e:0,ts=e=>typeof e=="string"?e:"",hx=(e,t,r)=>{let n=xn.join(e,t);try{let o=rs.statSync(n),s=JSON.parse(rs.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:ts(i.package),port:Cu(i.port),alias:ts(i.alias),origin:ts(i.origin),release:ts(i.release),env:ts(i.env),pid:Cu(i.pid),writtenAt:Cu(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},ns=(e=px.cwd())=>{let t=Date.now(),r=gx(e);if(!r||!rs.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=rs.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>hx(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 ha=async(e={})=>{let t=e.now??Date.now,r=e.isListening??To,n=ns(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),f=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:f}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(yx.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){d.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",f=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${f}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}},vx={active:he.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:he.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:he.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:he.array(he.object({app:he.string().describe("App folder name (the fragment filename without .json)."),package:he.string().describe("The app package name the vite helper reads to decide a local route."),port:he.number().describe("The actual bound port the dev server is listening on."),pid:he.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:he.string().describe("Registered portless hostname for the app."),origin:he.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:he.string().describe("Release slug the runner recorded for this worktree."),env:he.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:he.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:he.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:he.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:he.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.")},$u=T({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:vx,handler:()=>ha()});import Ie from"node:fs";import b$ from"node:os";import Qe from"node:path";import Cs from"node:process";import{z as Le}from"zod";import{execFileSync as wx}from"node:child_process";var uy=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},kx=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],bx=e=>kx.some(t=>t.test(e)),Rx="/bin/ps",Sx=()=>wx(Rx,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
163
- `),dy=(e=Sx)=>{try{return e().some(bx)}catch{return!0}};import{Chalk as Ex}from"chalk";import Au from"node:process";var Ou={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},Px=new Set(["warn","fail"]),xx=24,Tn=" ",py=" ",Tx=(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:[""]},my=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},Cx=e=>{let t=new Ex({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)}},fy=(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),$x=(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=fy(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}},Ax=(e,t,r,n)=>{let o=$x(my(e.rows),e.rows.length,t,r),s=Math.max(1,n-Tn.length-e.label.length-o.plainWidth);return`${Tn}${t.header(e.label)}${" ".repeat(s)}${o.text}`},Ox=(e,t,r,n,o)=>{let s=Px.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=py.length+i+1+t+2,p=Math.max(xx,o-u),[m,...f]=Tx(e.message,p),h=" ".repeat(u),b=k=>s?k:r.dim(k);return[`${py}${c(n[e.status])} ${l} ${b(m??"")}`.trimEnd(),...f.map(k=>`${h}${b(k)}`),...(e.notes??[]).map(k=>`${h}${k}`.trimEnd())]},Dx=(e,t,r,n,o)=>{let s=my(t),i=n.rule.repeat(Math.max(12,Math.min(o-Tn.length,56))),a=fy(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[`${Tn}${r.dim(i)}`,`${Tn}${c}${l.join("")}`]},Du=(e,t={})=>{let r=t.width??80,n=Cx(t.color??!1),o=t.unicode??!0?Ou.unicode:Ou.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,"",`${Tn}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[Ax(u,n,o,r),...u.rows.flatMap(p=>Ox(p,c,n,o,r)),""]);return[a,"",...l,...Dx(e,i,n,o,r)]},Ix=new Set(["","0","false","none"]),Nx=["LC_ALL","LC_CTYPE","LANG"],_x=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Ix.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,Mx=(e,t)=>{if(t)return!1;let r=Nx.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Iu=(e={})=>{let t=e.env??Au.env,r=e.stream??Au.stderr;return{color:_x(t,r),unicode:Mx(t,e.ascii??!1),width:r.columns??80}},bt=(e,t={})=>{(t.write??(n=>{Au.stderr.write(n)}))(`${Du(e,Iu(t)).join(`
158
+ `).map(a=>a.trim()).filter(Boolean)}}),rx=e=>ex.some(t=>t.test(e.body))?"agent":"human",bu=e=>oy.test(e.subject),nx=e=>!bu(e)&&wu.test(e.subject),ox=(e,t)=>{if(t===0)return null;let r=e/t,n=vu*vu,o=1+n/t,s=(r+n/(2*t))/o,i=vu*Math.sqrt(r*(1-r)/t+n/(4*t*t))/o;return{low:Math.max(0,s-i),high:Math.min(1,s+i)}},pa=e=>Math.round(e*1e4)/1e4,ny=(e,t)=>{let r=ox(e,t);return{hits:e,n:t,rate:t===0?null:pa(e/t),ci95:r&&{low:pa(r.low),high:pa(r.high)}}},sx=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!bu(n))continue;let o=e.slice(0,r),s=tx.exec(n.body)?.[1],i=oy.exec(n.subject)?.[1],a=s?o.find(c=>c.hash.startsWith(s)):o.findLast(c=>c.subject===i);a&&t.add(a.hash)}return t},ix=(e,t)=>{let r=new Set(e.files.filter(n=>!ku.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},ax=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&nx(n)&&ix(e,n)),cy=(e,t)=>{let r=sx(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(rx(u))),i=s.filter(({commit:u})=>!bu(u)),a=i.filter(({commit:u})=>t-u.committedAt>=259200),c=i.filter(({commit:u})=>r.has(u.hash)).length,l=a.filter(({commit:u,position:p})=>ax(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:ny(c,i.length),followUpFixRate:ny(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},Ru=(e,t)=>{let r=[e.n<30?`agent n=${e.n}`:null,t.n<30?`human n=${t.n}`:null].filter(Boolean);return r.length>0||e.rate===null||t.rate===null||!e.ci95||!t.ci95?{suppressed:!0,reason:`${r.join(", ")} < 30`,difference:null,intervalsOverlap:null}:{suppressed:!1,reason:null,difference:pa(e.rate-t.rate),intervalsOverlap:e.ci95.low<=t.ci95.high&&t.ci95.low<=e.ci95.high}};var Zo=90,ux=864e5,dx=async(e,t)=>{if(await Oe(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await lx({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${iy}`;return ay(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},my=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*ux).toISOString(),o=await dx(e,n),s=cy(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:Ru(s.agent.revertRate,s.human.revertRate),followUpFixRate:Ru(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:wu.source,followUpWindowHours:72,followUpIgnoredFiles:ku,mergesExcluded:!0}}},ma=e=>`${(e*100).toFixed(1)}%`,ly=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${ma(e.rate)} (${e.hits}/${e.n}, 95% CI ${ma(e.ci95.low)}\u2013${ma(e.ci95.high)})`,Su=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${ly(t.revertRate)}`,` ${72}h follow-up-fix rate: ${ly(t.followUpFixRate)}`].join(`
159
+ `),fa=async({since:e=Zo})=>{let t=await my({cwd:await $(),sinceDays:e,nowMs:Date.now()}),{classes:r,comparison:n}=t;d.info(`Change stats for ${t.repoRoot} \u2014 last ${e} days (${t.from.slice(0,10)} \u2192 ${t.until.slice(0,10)}, merges excluded)`),d.info(Su("agent",r.agent)),d.info(Su("human",r.human)),d.info(Su("total",r.total));let o=(s,i)=>{if(i.suppressed)return` ${s}: comparison suppressed (${i.reason})`;let a=i.intervalsOverlap?"intervals overlap":"intervals do not overlap";return` ${s}: agent \u2212 human = ${ma(i.difference??0)} (${a})`};return d.info(["Agent vs human:",o("revert rate",n.revertRate),o("follow-up-fix rate",n.followUpFixRate)].join(`
160
+ `)),{content:R(JSON.stringify(t,null,2)),structuredContent:t}},uy=B.object({hits:B.number().describe("Changes that hit the metric"),n:B.number().describe("Changes the rate is computed over"),rate:B.number().nullable().describe("hits / n, rounded to 4 places; null when n is 0"),ci95:B.object({low:B.number(),high:B.number()}).nullable().describe("Wilson 95% score interval; null when n is 0")}),Eu=B.object({commits:B.number().describe("Non-merge commits in range for this class"),reverts:B.number().describe("Of those, revert commits (excluded from both rate denominators)"),changes:B.number().describe("Non-revert commits \u2014 the revert-rate denominator"),revertRate:uy.describe("Changes later reverted by an in-range commit"),followUpFixRate:uy.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),dy=B.object({suppressed:B.boolean().describe("True when either class has n below minN"),reason:B.string().nullable(),difference:B.number().nullable().describe("agent rate \u2212 human rate"),intervalsOverlap:B.boolean().nullable().describe("Whether the two Wilson intervals overlap")}),Pu=T({name:"change-stats",description:"Read-only change-failure baseline for the git repo at cwd: commits classified agent (Claude trailers) vs human, with revert rate and 72h follow-up-fix rate per class, each with n and a Wilson 95% interval. The agent-vs-human comparison is suppressed when either n < 30.",inputSchema:{since:B.number().int().positive().optional().describe(`Window in days, ending now (default ${Zo})`)},outputSchema:{repoRoot:B.string().describe("git toplevel the stats were read from"),sinceDays:B.number(),from:B.string().describe("ISO start of the window"),until:B.string().describe("ISO end of the window (now)"),classes:B.object({agent:Eu,human:Eu,total:Eu}),comparison:B.object({minN:B.number(),revertRate:dy,followUpFixRate:dy}),heuristics:B.object({agentTrailers:B.array(B.string()),fixSubjectPattern:B.string(),followUpWindowHours:B.number(),followUpIgnoredFiles:B.array(B.string()),mergesExcluded:B.boolean()})},handler:fa});import{z as sr}from"zod";import xu from"node:fs/promises";import px from"node:path";var Pn=()=>Object.keys(Tg.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),mx=new Set(["protectedEnvs"]),xn={project:"per-project override",global:"user-global override"},Qo=(e,t)=>{if(te()&&mx.has(e))throw new A({status:"refused",agentMode:N.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!Pn().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: ${Pn().join(", ")}.`)}},Tu=e=>{try{return JSON.parse(e)}catch{return e}},fx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gx=async e=>{let t;try{t=await xu.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${w(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!fx(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},hx=async(e,t)=>{t===null?await xu.rm(e,{force:!0}):st(e,t,420),Oo()},es=async(e,t,r)=>{let n=await X(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await gx(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await xu.mkdir(px.dirname(o),{recursive:!0}),st(o,`${JSON.stringify(c,null,2)}
161
+ `,420),Oo();try{await L({autoMigrate:"off"})}catch(l){throw await hx(o,s),new Error(`${l.message}
162
+ ${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}};var ga=async({key:e}={})=>{let[t,r]=await Promise.all([L(),X()]),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(!Pn().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Pn().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},yx={config:sr.record(sr.string(),sr.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:sr.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:sr.string().optional().describe("The top-level key asked for, when one was."),value:sr.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:sr.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Cu=T({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:sr.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:yx,handler:e=>ga(e)});import Sx from"node:fs";import{z as he}from"zod";import rs from"node:fs";import Tn from"node:path";import vx from"node:process";var wx=Tn.join(".infra-kit","dev-context"),kx=".infra-kit",fy=(e,t)=>{let r=Tn.resolve(e);for(;;){let n=Tn.join(r,t);if(rs.existsSync(n))return n;let o=Tn.dirname(r);if(o===r)return;r=o}},bx=e=>{let t=fy(e,wx);if(t)return t;let r=fy(e,kx);return r?Tn.join(r,"dev-context"):void 0},$u=e=>typeof e=="number"&&Number.isFinite(e)?e:0,ts=e=>typeof e=="string"?e:"",Rx=(e,t,r)=>{let n=Tn.join(e,t);try{let o=rs.statSync(n),s=JSON.parse(rs.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:ts(i.package),port:$u(i.port),alias:ts(i.alias),origin:ts(i.origin),release:ts(i.release),env:ts(i.env),pid:$u(i.pid),writtenAt:$u(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},ns=(e=vx.cwd())=>{let t=Date.now(),r=bx(e);if(!r||!rs.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=rs.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>Rx(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 ha=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Co,n=ns(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),f=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:f}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(Sx.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){d.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",f=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${f}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}},Ex={active:he.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:he.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:he.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:he.array(he.object({app:he.string().describe("App folder name (the fragment filename without .json)."),package:he.string().describe("The app package name the vite helper reads to decide a local route."),port:he.number().describe("The actual bound port the dev server is listening on."),pid:he.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:he.string().describe("Registered portless hostname for the app."),origin:he.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:he.string().describe("Release slug the runner recorded for this worktree."),env:he.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:he.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:he.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:he.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:he.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.")},Au=T({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:Ex,handler:()=>ha()});import Ie from"node:fs";import T$ from"node:os";import Qe from"node:path";import Cs from"node:process";import{z as Le}from"zod";import{execFileSync as Px}from"node:child_process";var gy=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},xx=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],Tx=e=>xx.some(t=>t.test(e)),Cx="/bin/ps",$x=()=>Px(Cx,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
163
+ `),hy=(e=$x)=>{try{return e().some(Tx)}catch{return!0}};import{Chalk as Ax}from"chalk";import Ou from"node:process";var Du={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},Ox=new Set(["warn","fail"]),Dx=24,Cn=" ",yy=" ",Ix=(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:[""]},vy=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},Nx=e=>{let t=new Ax({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)}},wy=(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),_x=(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=wy(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}},Mx=(e,t,r,n)=>{let o=_x(vy(e.rows),e.rows.length,t,r),s=Math.max(1,n-Cn.length-e.label.length-o.plainWidth);return`${Cn}${t.header(e.label)}${" ".repeat(s)}${o.text}`},jx=(e,t,r,n,o)=>{let s=Ox.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=yy.length+i+1+t+2,p=Math.max(Dx,o-u),[m,...f]=Ix(e.message,p),h=" ".repeat(u),b=k=>s?k:r.dim(k);return[`${yy}${c(n[e.status])} ${l} ${b(m??"")}`.trimEnd(),...f.map(k=>`${h}${b(k)}`),...(e.notes??[]).map(k=>`${h}${k}`.trimEnd())]},Fx=(e,t,r,n,o)=>{let s=vy(t),i=n.rule.repeat(Math.max(12,Math.min(o-Cn.length,56))),a=wy(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[`${Cn}${r.dim(i)}`,`${Cn}${c}${l.join("")}`]},Iu=(e,t={})=>{let r=t.width??80,n=Nx(t.color??!1),o=t.unicode??!0?Du.unicode:Du.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,"",`${Cn}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[Mx(u,n,o,r),...u.rows.flatMap(p=>jx(p,c,n,o,r)),""]);return[a,"",...l,...Fx(e,i,n,o,r)]},Lx=new Set(["","0","false","none"]),Bx=["LC_ALL","LC_CTYPE","LANG"],Ux=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Lx.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,Vx=(e,t)=>{if(t)return!1;let r=Bx.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Nu=(e={})=>{let t=e.env??Ou.env,r=e.stream??Ou.stderr;return{color:Ux(t,r),unicode:Vx(t,e.ascii??!1),width:r.columns??80}},Rt=(e,t={})=>{(t.write??(n=>{Ou.stderr.write(n)}))(`${Iu(e,Nu(t)).join(`
164
164
  `)}
165
- `)};var jx="Tools & CLIs",Fx="Shell & integration",Lx="Project config",Bx="Doppler env tokens",Ux="Dev proxy (portless)",Vx="Claude Code plugin",Wx=`portless serving TLS on :${Xt}`,Nu=[[jx,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[Fx,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[Lx,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Bx,["tokens.json present","env tokens configured","tokens.json perms"]],[Ux,["portless installed","portless node","portless service target",Wx,"portless CA chain valid","portless CA trusted","portless routes"]],[Vx,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],gy="Other",Gx=Nu.map(([e])=>e),Jx=new Map(Nu.flatMap(([e,t])=>t.map(r=>[r,e]))),CJ=Nu.flatMap(([,e])=>e),_u=new Set(["portless routes","tokens.json perms"]),Kx=e=>{let t=new Map;for(let n of e){let o=Jx.get(n.name)??gy,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Gx,gy].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Hx=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ke(e)}},qx=e=>{let t=e.filter(r=>r.status==="fail"&&_u.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Kx(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Hx(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Mu=(e,t={})=>{bt(qx(e),t)};import{spawnSync as Ry}from"node:child_process";import ya from"node:fs";import cT from"node:os";import va from"node:path";import os from"node:process";import{z as wy}from"zod";import zx from"node:fs";import Yx from"node:os";import Xx from"node:path";var Zx="infra-kit.json",Qx="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)",eT="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Cn=async()=>{let e;try{e=await $()}catch{return null}let t=e.trim();return t===""||t===Yx.homedir()?null:t},hy=async()=>{let e=await Cn();return e===null&&d.info(Qx),e},tT=async()=>{let e=await Cn();return e===null?null:zx.existsSync(Xx.join(e,Zx))?e:(d.info(eT),null)};var rT=async e=>{try{return(await Cr(e,await Pr())).packages}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},yy=async({dryRun:e=!1}={})=>{let t=await tT(),r=U.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await Jo(t,{version:r,dryRun:e})];for(let o of await rT(t)){let s=await Dt(o);n.push(...await Ko(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};var nT=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),oT=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>nT(t[1])),sT=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:oT(t[1])},iT=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},aT=e=>{let t=e.split(`
166
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:iT(t.slice(10))},vy=(e,t)=>{try{return e==="darwin"?sT(t):e==="linux"?aT(t):null}catch{return null}};var Mt="portless service target",is=e=>({name:Mt,status:"warn",message:e}),Sy=e=>e==="darwin"?Gf:e==="linux"?Jf:null,lT=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Wf}`:`sudo systemctl restart ${Kf}`,uT="/bin/ps",dT=e=>{try{let t=Ry(uT,["-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}},ky=e=>{try{return ya.readFileSync(e,"utf-8")}catch{return null}},pT=e=>{try{return ya.statSync(e).mtime}catch{return null}},mT=2e3,fT=e=>{try{let t=Ry(e,["-p","process.version"],{encoding:"utf-8",timeout:mT}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},gT=(e,t)=>({platform:e.platform??os.platform,readServiceFile:e.readServiceFile??ky,readFile:e.readFile??ky,exists:e.exists??ya.existsSync,realpath:e.realpath??Se,mtime:e.mtime??pT,execPath:e.execPath??os.execPath,home:e.home??cT.homedir(),cwd:e.cwd??os.cwd(),repoRoot:e.repoRoot??Cn,stateDir:(e.stateDir??qf)(),processStartTime:e.processStartTime??dT,version:e.version??os.version,arch:e.arch??os.arch,nodeVersionOf:e.nodeVersionOf??fT,isGlobal:e.isGlobal??Mi().node.isGlobal,nodeFs:e.nodeFs??ya,stableNode:null,stableNodeSidecar:null,bin:t}),$n="portless node",Ir="~/.infra-kit/node",ss=e=>({row:{name:$n,status:"fail",message:e},stableNode:null,sidecar:null}),by=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},hT=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,yT=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,vT=e=>{let t=Qf(e.home),r=by(e.nodeFs.lstatSync,t);if(r===void 0)return ss(`${Ir} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return ss(`${Ir} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=eg(e.home,e.nodeFs);if(n===null)return ss(`${Ir} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=by(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 ss(`${Ir} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!yT(c,e))return ss(`${Ir} does not run as Node ${e.version} (${hT(c)}). Re-run through the current Node: \`${Ot(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:$n,status:"pass",message:`${Ir} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},wT=e=>{if(Sy(e.platform)===null)return{row:{name:$n,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=vT(e);return e.isGlobal()?t:{...t,row:{name:$n,status:"skip",message:`not a global install; the global infra-kit keeps ${Ir} current`}}},ju=(e,t)=>{let r=gT(e,t),n=wT(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},kT=(e,t)=>{let r=t.readFile(va.join(e,"package.json"));try{let n=r===null?null:wy.object({version:wy.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},bT=e=>{let t=Number.parseInt(e.readFile(va.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},RT=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},ST=(e,t,r)=>{let n=bT(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(RT(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(va.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:ln(await t.repoRoot()??r,e,t.realpath)},Nr=e=>({state:"drifted",row:e}),PT=async(e,t,r)=>{let n=Ot(r.bin,r);if(!r.exists(e))return Nr({name:Mt,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=va.join(ll(r.home),"dist","cli.js");if(t!==o)return Nr(is(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(_i(r.home,r.exists)===null)return Nr({name:Mt,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(ll(r.home));if(await ET(s,r))return Nr({name:Mt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=xT(e,n,r);if(i!==null)return i;let a=kT(s,r),c=ST(s,a,r);return c!==null?{state:"converged",row:is(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${lT(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Mt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},xT=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Nr(is(`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:Nr(is(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Fu=async e=>{let t=Sy(e.platform);if(t===null)return{state:"absent",row:{name:Mt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Mt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=vy(e.platform,r)??[];return n===void 0||o===void 0?Nr(is(`could not parse ${t} \u2014 re-run \`${Ot(e.bin,e)}\` to rewrite it.`)):PT(n,o,e)},Ey=async(e,t)=>{let{seams:r}=ju(e,t);return{state:(await Fu(r)).state,stableNode:r.stableNode}};import wa from"node:fs";import An from"node:path";var Py="auto-setup.json",TT="auto-setup.log",CT="auto-setup.lock",xy="auto-setup.notified",$T=3,AT=3600*1e3,OT=()=>An.join(At(),Py),On=()=>An.join(At(),TT),Ty=()=>An.join(At(),CT),DT=()=>An.join(At(),xy),IT=new Set(["ok","attention","failed"]),NT=e=>{if(typeof e!="object"||e===null)return!1;let{root:t,status:r,notes:n}=e;return(t===null||typeof t=="string")&&typeof r=="string"&&IT.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},_T=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(NT)},Dn=(e=t=>wa.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(OT()));return _T(t)?t:null}catch{return null}},Cy=e=>{let t=At();wa.mkdirSync(t,{recursive:!0}),st(An.join(t,Py),JSON.stringify(e),384)},MT=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),$y=(e=t=>wa.readFileSync(t,"utf8"))=>{try{let t=Number(e(DT()).trim());return Number.isFinite(t)?t:null}catch{return null}},Ay=e=>{let t=At();wa.mkdirSync(t,{recursive:!0}),st(An.join(t,xy),String(e),384)},Oy=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<AT?!1:e.version!==t?!0:MT(e)&&e.attempts<$T};import Lu from"node:fs";import Dy from"node:os";import Iy from"node:path";import jT from"node:process";import{z as ba}from"zod";var Ny=e=>{try{return Lu.readFileSync(e,"utf-8")}catch{return null}},In="claude in chrome",FT="com.anthropic.claude_code_browser_extension",ka="run `/chrome` inside Claude Code to set up Claude in Chrome",LT={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},BT=e=>{try{return Lu.accessSync(e,Lu.constants.X_OK),!0}catch{return!1}},_y=e=>{try{return JSON.parse(e)}catch{return null}},UT=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,as=(e={})=>{let t=e.platform??jT.platform,r=e.home??Dy.homedir(),n=e.readText??Ny,o=e.isExecutable??BT,s=LT[t];if(s===void 0)return{name:In,status:"skip",message:`no Chrome native host location known for ${t}`};let i=Iy.join(r,...s,`${FT}.json`),a=n(i);if(a===null)return{name:In,status:"warn",message:`Chrome native host not registered \u2014 ${ka}`};let c=ba.object({path:ba.string().min(1)}).safeParse(_y(a));if(!c.success)return{name:In,status:"fail",message:`${w(i)} has no host path \u2014 ${ka} again`};let l=c.data.path;if(!o(l))return{name:In,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${ka} again`};let u=UT.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:In,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${ka} again`}:{name:In,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},Bu=(e={})=>{let t=e.home??Dy.homedir(),r=e.readText??Ny,n=ba.object({claudeInChromeDefaultEnabled:ba.boolean().optional()}).safeParse(_y(r(Iy.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import VT from"node:fs/promises";var cs=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await VT.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}}},ls=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import GT from"node:fs";import JT from"node:os";import My from"node:path";import KT from"node:process";import{$ as WT}from"zx";var Nn=()=>WT({quiet:!0});var HT=()=>[My.join(JT.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],qT=async e=>{try{return(await Nn()`command -v ${e}`).stdout.trim()||null}catch{return null}},us=()=>({runCommand:async e=>{let t=await Nn()`${e}`;return{stdout:`${t.stdout}
167
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await qT(e);return t!==null?t:HT().map(r=>My.join(r,e)).find(r=>GT.existsSync(r))??null},realpath:Se,platform:KT.platform});var ir=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),_n=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,Mn=["darwin","linux"],Pa=e=>t=>al(t,e)?"homebrew":"unknown",xa=(e,t)=>r=>r===null?null:t(e(r),r),Vu=e=>xa(Pa(e.kegName),t=>t==="homebrew"?ir(["brew","upgrade",e.brewFormula]):null),jy=e=>Ii(e,"Homebrew")||Ii(e,"homebrew")?"homebrew":"unknown",zT={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:_n,platforms:Mn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:jy,updateFor:xa(jy,e=>e==="homebrew"?ir(["brew","update"]):null)},Uu={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},By="https://awscli.amazonaws.com/v2/install.sh",Uy={steps:[["/bin/bash","-c",`curl -fsSL ${By} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},YT="/usr/local/aws-cli",XT=e=>ln(YT,e,Se)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${By} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Uy,Fy=e=>al(e,Uu.kegName)?"homebrew":Ii(e,"aws-cli")?"script":"unknown",ZT={id:"aws",binName:"aws",...Uu,probeArgv:["aws","--version"],versionFrom:_n,platforms:Mn,prerequisites:[],bootstrapInstall:Uy,identify:Fy,updateFor:xa(Fy,(e,t)=>e==="homebrew"?ir(["brew","upgrade",Uu.brewFormula]):e==="script"?XT(t):null)},Ra={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},QT={id:"git",binName:"git",...Ra,probeArgv:["git","--version"],versionFrom:_n,platforms:Mn,prerequisites:["brew"],bootstrapInstall:ir(["brew","install",Ra.brewInstallSpec]),identify:Pa(Ra.kegName),updateFor:Vu(Ra)},Sa={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},eC={id:"gh",binName:"gh",...Sa,probeArgv:["gh","--version"],versionFrom:_n,platforms:Mn,prerequisites:["brew"],bootstrapInstall:ir(["brew","install",Sa.brewInstallSpec]),identify:Pa(Sa.kegName),updateFor:Vu(Sa)},Ea={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},tC={id:"doppler",binName:"doppler",...Ea,probeArgv:["doppler","--version"],versionFrom:_n,platforms:Mn,prerequisites:["brew"],bootstrapInstall:ir(["brew","install","gnupg"],["brew","install",Ea.brewInstallSpec]),identify:Pa(Ea.kegName),updateFor:Vu(Ea)},ds="portless",Ly=e=>Mf(e,ds)===null?"unknown":"npm",rC={id:"portless",binName:ds,npmPackage:ds,probeArgv:["portless","--version"],versionFrom:_n,platforms:[...Mn,"win32"],prerequisites:[],bootstrapInstall:ir(["npm","install","-g",ds]),identify:Ly,updateFor:xa(Ly,e=>e==="npm"?ir(["npm","install","-g",`${ds}@latest`]):null)},Wu={brew:zT,git:QT,aws:ZT,gh:eC,doppler:tC,portless:rC},_r=Object.keys(Wu),Xe=e=>Wu[e],Gu=(e,t)=>e.platforms.includes(t),Ju=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 Xe(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Vy=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Wy=async(e,t)=>{try{return await e(t)}catch{return null}},nC=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Gy=async(e,t)=>{if(!Gu(e,t.platform))return Vy(e.id);let r=await Wy(t.runCommand,e.probeArgv),n=await nC(t,e.binName);if(r==null&&n==null)return Vy(e.id);let o=r??(n==null?null:await Wy(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)}},ps=async(e,t)=>Promise.all(e.map(r=>Gy(Xe(r),t)));import we from"node:fs";import Aa from"node:os";import ue from"node:path";import ed from"node:process";import Ca from"node:fs/promises";import oC from"node:path";import sC from"node:process";var Jy=` // // Editor tooling only \u2014 a JSON Schema URL for completion and validation. Ignored at runtime.
165
+ `)};var Wx="Tools & CLIs",Gx="Shell & integration",Jx="Project config",Kx="Doppler env tokens",Hx="Dev proxy (portless)",qx="Claude Code plugin",zx=`portless serving TLS on :${Zt}`,_u=[[Wx,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[Gx,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[Jx,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Kx,["tokens.json present","env tokens configured","tokens.json perms"]],[Hx,["portless installed","portless node","portless service target",zx,"portless CA chain valid","portless CA trusted","portless routes"]],[qx,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],ky="Other",Yx=_u.map(([e])=>e),Xx=new Map(_u.flatMap(([e,t])=>t.map(r=>[r,e]))),_J=_u.flatMap(([,e])=>e),Mu=new Set(["portless routes","tokens.json perms"]),Zx=e=>{let t=new Map;for(let n of e){let o=Xx.get(n.name)??ky,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Yx,ky].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Qx=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ke(e)}},eT=e=>{let t=e.filter(r=>r.status==="fail"&&Mu.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Zx(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Qx(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var ju=(e,t={})=>{Rt(eT(e),t)};import{spawnSync as Ty}from"node:child_process";import ya from"node:fs";import fT from"node:os";import va from"node:path";import os from"node:process";import{z as Ey}from"zod";import tT from"node:fs";import rT from"node:os";import nT from"node:path";var oT="infra-kit.json",sT="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)",iT="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",$n=async()=>{let e;try{e=await $()}catch{return null}let t=e.trim();return t===""||t===rT.homedir()?null:t},by=async()=>{let e=await $n();return e===null&&d.info(sT),e},aT=async()=>{let e=await $n();return e===null?null:tT.existsSync(nT.join(e,oT))?e:(d.info(iT),null)};var cT=async e=>{try{return(await Cr(e,await Pr())).packages}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Ry=async({dryRun:e=!1}={})=>{let t=await aT(),r=U.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await Jo(t,{version:r,dryRun:e})];for(let o of await cT(t)){let s=await It(o);n.push(...await Ko(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};var lT=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),uT=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>lT(t[1])),dT=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:uT(t[1])},pT=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},mT=e=>{let t=e.split(`
166
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:pT(t.slice(10))},Sy=(e,t)=>{try{return e==="darwin"?dT(t):e==="linux"?mT(t):null}catch{return null}};var jt="portless service target",is=e=>({name:jt,status:"warn",message:e}),Cy=e=>e==="darwin"?Jf:e==="linux"?Kf:null,gT=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Gf}`:`sudo systemctl restart ${Hf}`,hT="/bin/ps",yT=e=>{try{let t=Ty(hT,["-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}},Py=e=>{try{return ya.readFileSync(e,"utf-8")}catch{return null}},vT=e=>{try{return ya.statSync(e).mtime}catch{return null}},wT=2e3,kT=e=>{try{let t=Ty(e,["-p","process.version"],{encoding:"utf-8",timeout:wT}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},bT=(e,t)=>({platform:e.platform??os.platform,readServiceFile:e.readServiceFile??Py,readFile:e.readFile??Py,exists:e.exists??ya.existsSync,realpath:e.realpath??Se,mtime:e.mtime??vT,execPath:e.execPath??os.execPath,home:e.home??fT.homedir(),cwd:e.cwd??os.cwd(),repoRoot:e.repoRoot??$n,stateDir:(e.stateDir??zf)(),processStartTime:e.processStartTime??yT,version:e.version??os.version,arch:e.arch??os.arch,nodeVersionOf:e.nodeVersionOf??kT,isGlobal:e.isGlobal??Mi().node.isGlobal,nodeFs:e.nodeFs??ya,stableNode:null,stableNodeSidecar:null,bin:t}),An="portless node",Ir="~/.infra-kit/node",ss=e=>({row:{name:An,status:"fail",message:e},stableNode:null,sidecar:null}),xy=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},RT=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,ST=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,ET=e=>{let t=eg(e.home),r=xy(e.nodeFs.lstatSync,t);if(r===void 0)return ss(`${Ir} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return ss(`${Ir} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=tg(e.home,e.nodeFs);if(n===null)return ss(`${Ir} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=xy(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 ss(`${Ir} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!ST(c,e))return ss(`${Ir} does not run as Node ${e.version} (${RT(c)}). Re-run through the current Node: \`${Dt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:An,status:"pass",message:`${Ir} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},PT=e=>{if(Cy(e.platform)===null)return{row:{name:An,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=ET(e);return e.isGlobal()?t:{...t,row:{name:An,status:"skip",message:`not a global install; the global infra-kit keeps ${Ir} current`}}},Fu=(e,t)=>{let r=bT(e,t),n=PT(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},xT=(e,t)=>{let r=t.readFile(va.join(e,"package.json"));try{let n=r===null?null:Ey.object({version:Ey.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},TT=e=>{let t=Number.parseInt(e.readFile(va.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},CT=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},$T=(e,t,r)=>{let n=TT(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(CT(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(va.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},AT=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:ln(await t.repoRoot()??r,e,t.realpath)},Nr=e=>({state:"drifted",row:e}),OT=async(e,t,r)=>{let n=Dt(r.bin,r);if(!r.exists(e))return Nr({name:jt,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=va.join(ll(r.home),"dist","cli.js");if(t!==o)return Nr(is(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(_i(r.home,r.exists)===null)return Nr({name:jt,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(ll(r.home));if(await AT(s,r))return Nr({name:jt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=DT(e,n,r);if(i!==null)return i;let a=xT(s,r),c=$T(s,a,r);return c!==null?{state:"converged",row:is(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${gT(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:jt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},DT=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Nr(is(`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:Nr(is(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Lu=async e=>{let t=Cy(e.platform);if(t===null)return{state:"absent",row:{name:jt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:jt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Sy(e.platform,r)??[];return n===void 0||o===void 0?Nr(is(`could not parse ${t} \u2014 re-run \`${Dt(e.bin,e)}\` to rewrite it.`)):OT(n,o,e)},$y=async(e,t)=>{let{seams:r}=Fu(e,t);return{state:(await Lu(r)).state,stableNode:r.stableNode}};import wa from"node:fs";import On from"node:path";var Ay="auto-setup.json",IT="auto-setup.log",NT="auto-setup.lock",Oy="auto-setup.notified",_T=3,MT=3600*1e3,jT=()=>On.join(Ot(),Ay),Dn=()=>On.join(Ot(),IT),Dy=()=>On.join(Ot(),NT),FT=()=>On.join(Ot(),Oy),LT=new Set(["ok","attention","failed"]),BT=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"&&LT.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},UT=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(BT)},In=(e=t=>wa.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(jT()));return UT(t)?t:null}catch{return null}},Iy=e=>{let t=Ot();wa.mkdirSync(t,{recursive:!0}),st(On.join(t,Ay),JSON.stringify(e),384)},VT=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),Ny=(e=t=>wa.readFileSync(t,"utf8"))=>{try{let t=Number(e(FT()).trim());return Number.isFinite(t)?t:null}catch{return null}},_y=e=>{let t=Ot();wa.mkdirSync(t,{recursive:!0}),st(On.join(t,Oy),String(e),384)},My=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<MT?!1:e.version!==t?!0:VT(e)&&e.attempts<_T};import Bu from"node:fs";import jy from"node:os";import Fy from"node:path";import WT from"node:process";import{z as ba}from"zod";var Ly=e=>{try{return Bu.readFileSync(e,"utf-8")}catch{return null}},Nn="claude in chrome",GT="com.anthropic.claude_code_browser_extension",ka="run `/chrome` inside Claude Code to set up Claude in Chrome",JT={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},KT=e=>{try{return Bu.accessSync(e,Bu.constants.X_OK),!0}catch{return!1}},By=e=>{try{return JSON.parse(e)}catch{return null}},HT=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,as=(e={})=>{let t=e.platform??WT.platform,r=e.home??jy.homedir(),n=e.readText??Ly,o=e.isExecutable??KT,s=JT[t];if(s===void 0)return{name:Nn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=Fy.join(r,...s,`${GT}.json`),a=n(i);if(a===null)return{name:Nn,status:"warn",message:`Chrome native host not registered \u2014 ${ka}`};let c=ba.object({path:ba.string().min(1)}).safeParse(By(a));if(!c.success)return{name:Nn,status:"fail",message:`${w(i)} has no host path \u2014 ${ka} again`};let l=c.data.path;if(!o(l))return{name:Nn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${ka} again`};let u=HT.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:Nn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${ka} again`}:{name:Nn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},Uu=(e={})=>{let t=e.home??jy.homedir(),r=e.readText??Ly,n=ba.object({claudeInChromeDefaultEnabled:ba.boolean().optional()}).safeParse(By(r(Fy.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import qT from"node:fs/promises";var cs=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await qT.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}}},ls=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import YT from"node:fs";import XT from"node:os";import Uy from"node:path";import ZT from"node:process";import{$ as zT}from"zx";var _n=()=>zT({quiet:!0});var QT=()=>[Uy.join(XT.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],eC=async e=>{try{return(await _n()`command -v ${e}`).stdout.trim()||null}catch{return null}},us=()=>({runCommand:async e=>{let t=await _n()`${e}`;return{stdout:`${t.stdout}
167
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await eC(e);return t!==null?t:QT().map(r=>Uy.join(r,e)).find(r=>YT.existsSync(r))??null},realpath:Se,platform:ZT.platform});var ir=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Mn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,jn=["darwin","linux"],Pa=e=>t=>al(t,e)?"homebrew":"unknown",xa=(e,t)=>r=>r===null?null:t(e(r),r),Wu=e=>xa(Pa(e.kegName),t=>t==="homebrew"?ir(["brew","upgrade",e.brewFormula]):null),Vy=e=>Ii(e,"Homebrew")||Ii(e,"homebrew")?"homebrew":"unknown",tC={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Mn,platforms:jn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Vy,updateFor:xa(Vy,e=>e==="homebrew"?ir(["brew","update"]):null)},Vu={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Jy="https://awscli.amazonaws.com/v2/install.sh",Ky={steps:[["/bin/bash","-c",`curl -fsSL ${Jy} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},rC="/usr/local/aws-cli",nC=e=>ln(rC,e,Se)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Jy} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Ky,Wy=e=>al(e,Vu.kegName)?"homebrew":Ii(e,"aws-cli")?"script":"unknown",oC={id:"aws",binName:"aws",...Vu,probeArgv:["aws","--version"],versionFrom:Mn,platforms:jn,prerequisites:[],bootstrapInstall:Ky,identify:Wy,updateFor:xa(Wy,(e,t)=>e==="homebrew"?ir(["brew","upgrade",Vu.brewFormula]):e==="script"?nC(t):null)},Ra={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},sC={id:"git",binName:"git",...Ra,probeArgv:["git","--version"],versionFrom:Mn,platforms:jn,prerequisites:["brew"],bootstrapInstall:ir(["brew","install",Ra.brewInstallSpec]),identify:Pa(Ra.kegName),updateFor:Wu(Ra)},Sa={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},iC={id:"gh",binName:"gh",...Sa,probeArgv:["gh","--version"],versionFrom:Mn,platforms:jn,prerequisites:["brew"],bootstrapInstall:ir(["brew","install",Sa.brewInstallSpec]),identify:Pa(Sa.kegName),updateFor:Wu(Sa)},Ea={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},aC={id:"doppler",binName:"doppler",...Ea,probeArgv:["doppler","--version"],versionFrom:Mn,platforms:jn,prerequisites:["brew"],bootstrapInstall:ir(["brew","install","gnupg"],["brew","install",Ea.brewInstallSpec]),identify:Pa(Ea.kegName),updateFor:Wu(Ea)},ds="portless",Gy=e=>jf(e,ds)===null?"unknown":"npm",cC={id:"portless",binName:ds,npmPackage:ds,probeArgv:["portless","--version"],versionFrom:Mn,platforms:[...jn,"win32"],prerequisites:[],bootstrapInstall:ir(["npm","install","-g",ds]),identify:Gy,updateFor:xa(Gy,e=>e==="npm"?ir(["npm","install","-g",`${ds}@latest`]):null)},Gu={brew:tC,git:sC,aws:oC,gh:iC,doppler:aC,portless:cC},_r=Object.keys(Gu),Xe=e=>Gu[e],Ju=(e,t)=>e.platforms.includes(t),Ku=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 Xe(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Hy=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),qy=async(e,t)=>{try{return await e(t)}catch{return null}},lC=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},zy=async(e,t)=>{if(!Ju(e,t.platform))return Hy(e.id);let r=await qy(t.runCommand,e.probeArgv),n=await lC(t,e.binName);if(r==null&&n==null)return Hy(e.id);let o=r??(n==null?null:await qy(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)}},ps=async(e,t)=>Promise.all(e.map(r=>zy(Xe(r),t)));import we from"node:fs";import Aa from"node:os";import ue from"node:path";import td from"node:process";import Ca from"node:fs/promises";import uC from"node:path";import dC from"node:process";var Yy=` // // Editor tooling only \u2014 a JSON Schema URL for completion and validation. Ignored at runtime.
168
168
  // "$schema": "https://\u2026/infra-kit.schema.json",
169
169
  //
170
170
  // // The committed file's shape version. A CLI that reads an older version refuses the file and
@@ -286,7 +286,7 @@ ${t.stderr}`}},resolveBinPath:async e=>{let t=await qT(e);return t!==null?t:HT()
286
286
  // // also fixes its modes), or by hand: both are supported, which is why the store carries no
287
287
  // // repo-identity field and no mandatory version. Pasting a token into an
288
288
  // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
289
- // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Ku=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
289
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Hu=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
290
290
  //
291
291
  // Merge chain (later layers override earlier ones at top-level keys):
292
292
  // 1. <repo>/infra-kit.json \u2014 committed project config (required)
@@ -308,9 +308,9 @@ ${t.stderr}`}},resolveBinPath:async e=>{let t=await qT(e);return t!==null?t:HT()
308
308
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
309
309
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
310
310
  {
311
- ${Jy}
311
+ ${Yy}
312
312
  }
313
- `,Hu=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
313
+ `,qu=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
314
314
  //
315
315
  // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
316
316
  // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
@@ -326,9 +326,9 @@ ${Jy}
326
326
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
327
327
  // override layer \u2014 it is shown here only to document the full, valid config shape.
328
328
  {
329
- ${Jy}
329
+ ${Yy}
330
330
  }
331
- `,qu=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
331
+ `,zu=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
332
332
  //
333
333
  // Machine-local registry the vendor commands (sync/manifest/diff) read to know
334
334
  // where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
@@ -340,143 +340,143 @@ ${Jy}
340
340
  // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
341
341
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
342
342
  }
343
- `;var Ky=!1,iC=e=>e.replace(/\.json$/,".example.jsonc"),aC=async e=>{try{return await Ca.readFile(e,"utf-8")}catch{return null}},jn=async e=>{let t=e.userProject,r=iC(t);await Ca.mkdir(oC.dirname(t),{recursive:!0});let n=!await ie(t);n&&await Ca.writeFile(t,`{}
344
- `,"utf-8");let o=Hu(e.projectName),s=await aC(r)!==o;return s&&await Ca.writeFile(r,o,"utf-8"),n&&Oo(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Fn=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,zu=async()=>{if(sC.env.INFRA_KIT_NO_SEED||Ky)return;Ky=!0;let e;try{e=await X()}catch{return}if(await ie(e.main))try{let t=await jn(e);t.createdConfig?d.info(Fn(t)):t.refreshedExample&&d.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as cC}from"node:child_process";import qy from"node:fs";import Ln from"node:process";import{fileURLToPath as zy}from"node:url";var Hy=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Yu=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Hy.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Ff(o,s,i)?"local-install":null:"not-a-tty"};var lC=e=>{cC(Ln.execPath,[e,"--parent-pid",String(Ln.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},uC=()=>zy(new URL("./update-check.js",import.meta.url)),dC=()=>qy.realpathSync(zy(new URL("./cli.js",import.meta.url))),pC=/^[\w@./+ -]+$/,mC=e=>pC.test(e),fC=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||at(e.latestVersion,t)&&e.updateCommand.every(mC)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ni(e.updateCommand)}`)},gC=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${w(On())}, or run: infra-kit setup`),o(e.finishedMs)},Xu=(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??dC(),c=t.readCache??_o,l=t.spawnChild??lC,u=t.fileExists??(h=>qy.existsSync(h)),p=t.notify??(h=>{d.info(h)});if(Yu({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:Se})!==null)return;let m=c();fC(m,e,p);try{gC((t.readAutoSetup??Dn)(),e,(t.readNotified??$y)(),p,t.writeNotified??Ay)}catch{}if(!xl(m,i))return;let f=t.childPath??uC();if(!u(f))return;l(f)}catch{}};import St from"node:fs/promises";import Rt from"node:path";import{pathToFileURL as vC}from"node:url";import wC from"yaml";import{z as Vn}from"zod";import hC from"node:fs/promises";import Zu from"node:os";import Qu from"node:path";import{z as yC}from"zod";import{z as ms}from"zod";var Yy="vendor.json",Xy=ms.object({workspaceDir:ms.string().min(1),source:ms.string().min(1),targets:ms.array(ms.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 Bn=()=>Qu.join(Zu.homedir(),Df,Yy),Un=e=>{if(e==="~")return Zu.homedir();if(e.startsWith("~/"))return Qu.join(Zu.homedir(),e.slice(2));if(Qu.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},$a=async()=>{let e=Bn(),t;try{t=await hC.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:
343
+ `;var Xy=!1,pC=e=>e.replace(/\.json$/,".example.jsonc"),mC=async e=>{try{return await Ca.readFile(e,"utf-8")}catch{return null}},Fn=async e=>{let t=e.userProject,r=pC(t);await Ca.mkdir(uC.dirname(t),{recursive:!0});let n=!await ie(t);n&&await Ca.writeFile(t,`{}
344
+ `,"utf-8");let o=qu(e.projectName),s=await mC(r)!==o;return s&&await Ca.writeFile(r,o,"utf-8"),n&&Oo(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Ln=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,Yu=async()=>{if(dC.env.INFRA_KIT_NO_SEED||Xy)return;Xy=!0;let e;try{e=await X()}catch{return}if(await ie(e.main))try{let t=await Fn(e);t.createdConfig?d.info(Ln(t)):t.refreshedExample&&d.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as fC}from"node:child_process";import Qy from"node:fs";import Bn from"node:process";import{fileURLToPath as ev}from"node:url";var Zy=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Xu=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Zy.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Lf(o,s,i)?"local-install":null:"not-a-tty"};var gC=e=>{fC(Bn.execPath,[e,"--parent-pid",String(Bn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},hC=()=>ev(new URL("./update-check.js",import.meta.url)),yC=()=>Qy.realpathSync(ev(new URL("./cli.js",import.meta.url))),vC=/^[\w@./+ -]+$/,wC=e=>vC.test(e),kC=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||at(e.latestVersion,t)&&e.updateCommand.every(wC)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ni(e.updateCommand)}`)},bC=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${w(Dn())}, or run: infra-kit setup`),o(e.finishedMs)},Zu=(e,t={})=>{try{let r=t.argv??Bn.argv,n=t.env??Bn.env,o=t.isTty??!!Bn.stdout.isTTY,s=t.cwd??Bn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??yC(),c=t.readCache??_o,l=t.spawnChild??gC,u=t.fileExists??(h=>Qy.existsSync(h)),p=t.notify??(h=>{d.info(h)});if(Xu({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:Se})!==null)return;let m=c();kC(m,e,p);try{bC((t.readAutoSetup??In)(),e,(t.readNotified??Ny)(),p,t.writeNotified??_y)}catch{}if(!Tl(m,i))return;let f=t.childPath??hC();if(!u(f))return;l(f)}catch{}};import Et from"node:fs/promises";import St from"node:path";import{pathToFileURL as EC}from"node:url";import PC from"yaml";import{z as Wn}from"zod";import RC from"node:fs/promises";import Qu from"node:os";import ed from"node:path";import{z as SC}from"zod";import{z as ms}from"zod";var tv="vendor.json",rv=ms.object({workspaceDir:ms.string().min(1),source:ms.string().min(1),targets:ms.array(ms.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=()=>ed.join(Qu.homedir(),If,tv),Vn=e=>{if(e==="~")return Qu.homedir();if(e.startsWith("~/"))return ed.join(Qu.homedir(),e.slice(2));if(ed.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},$a=async()=>{let e=Un(),t;try{t=await RC.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:
345
345
 
346
346
  {
347
347
  "workspaceDir": "~/projects",
348
348
  "source": "my-starter",
349
349
  "targets": ["my-repo"]
350
350
  }
351
- `)}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=Xy.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${yC.prettifyError(n.error)}`);return n.data};var Zy=e=>e.replace(/\.json$/,".yml"),Qy=async()=>{let e;try{e=await X()}catch{return}let t={label:"infra-kit.json",yml:Zy(e.main),json:e.main,schema:Eg},r=[...it.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:Rt.join(Rt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:fl},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Zy(e.userProject),json:e.userProject,schema:fl}],n=0;for(let o of r){let[s,i]=await Promise.all([ie(o.yml),ie(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${w(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await St.readFile(o.yml,"utf-8"),c=wC.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${Vn.prettifyError(l.error)}`);continue}await St.mkdir(Rt.dirname(o.json),{recursive:!0}),await St.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
352
- `,"utf-8"),await St.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${w(o.yml)} \u2192 ${w(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${a.message}`)}}}n>0&&Zt()},ev=async()=>{let e;try{e=await X()}catch{return}let t=Rt.dirname(e.userGlobal),r=[{from:Rt.join(t,"config.json"),to:e.userGlobal},{from:Rt.join(t,"config.example.jsonc"),to:Rt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([ie(o),ie(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await St.mkdir(Rt.dirname(s),{recursive:!0}),await St.rename(o,s),d.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Zt()},kC=Vn.object({workspaceDir:Vn.string().min(1),targets:Vn.array(Vn.string()).min(1)}).strict(),tv=async()=>{let e=Bn(),t=Rt.dirname(e),r=Rt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ie(r),ie(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await St.stat(r),c=(await import(`${vC(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=kC.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${Vn.prettifyError(p.error)}`);return}await St.mkdir(t,{recursive:!0}),await St.writeFile(e,`${JSON.stringify(p.data,null,2)}
353
- `,"utf-8"),await St.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${w(r)} \u2192 ${w(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${w(e)} directly to change them.`):d.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},rv=async()=>{let e=await bC(),t=0;for(let r of e)if(await ie(r))try{let n=await ig(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof sg?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Zt()},bC=async()=>{try{let e=await X();return it.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[xg()]}};var Mr="# -- infra-kit:begin --",ar="# -- infra-kit:end --",RC=[["# region infra-kit","# endregion infra-kit"]],SC="# infra-kit shell functions",Wn=class extends Error{constructor(r,n){super(n instanceof Error?n.message:String(n),{cause:n});this.step=r;this.reason=n;this.name="InitStepError"}step;reason},Gn="Run `source ~/.zshrc` or open a new terminal to activate.",EC={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Ze=async(e,t)=>{try{return await t()}catch(r){throw new Wn(e,r)}},td=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Ze("zshrc",()=>{r(TC())}),await Ze("zshenv",()=>{r(CC())}),await Ze("migrations",async()=>{await AC(),$C(),r(EC)}),await Ze("user-config",()=>{r(DC())});let n=await Ze("guidance",async()=>{let{entries:s,root:i}=await MC();return r(...s),i}),o=await Ze("plugin-pointer",async()=>hy());return r(...FC(o,n)),await Ze("worktrees",async()=>{r(...await WC(o))}),await Ze("plugin-pointer",async()=>{await JC(o,r)}),await Ze("mcp-proxies",async()=>{r(...await HC(o))}),await Ze("project-config",async()=>{r(...await IC(o))}),await Ze("token-perms",async()=>{r(await xC())}),await Ze("chrome",()=>{r(PC())}),r(...OC()),t},PC=()=>{let e=as();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"}:Bu()?{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"}},xC=async()=>{let e=await Cg();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 ov=e=>{let t=ue.dirname(e);return we.existsSync(ue.join(e,".git"))?e:t===e?null:ov(t)},sv=(e,t,r,n)=>{if(!it.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=we.realpathSync(t)}catch{}return ov(ue.dirname(o))===null?null:gs(e,Aa.homedir(),o,["the infra-kit block updated"])},iv=e=>we.existsSync(e)?we.readFileSync(e,"utf-8"):null,TC=()=>{let e=ue.join(Aa.homedir(),".zshrc"),t=iv(e),r=t===null?"":zC(t),n=fn({content:r,body:lv(),startMarker:Mr,endMarker:ar,placement:"append-end"}),o=sv("zshrc",e,t,n);return o!==null?o:(we.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},CC=()=>{let e=ue.join(Aa.homedir(),".zshenv"),t=iv(e),r=fn({content:t??"",body:rd(),startMarker:Mr,endMarker:ar}),n=sv("zshenv",e,t,r);return n!==null?n:(we.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},$C=()=>{we.rmSync(ue.join(At(),"projects"),{recursive:!0,force:!0})},AC=async()=>{await Qy(),await ev(),await rv(),await tv()},OC=()=>{let e=ed.env.SHELL??"",t=[];return e.includes("zsh")||t.push({step:"shell",outcome:"warned",message:`Your login shell ($SHELL=${e||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear) is zsh-only and won't activate in bash/fish.`,level:"warn"}),t.push({step:"shell",outcome:"unchanged",message:Gn,level:"info"}),t},DC=()=>{let e=ue.join(Aa.homedir(),".infra-kit"),t=ue.join(e,"infra-kit.json");return we.mkdirSync(e,{recursive:!0}),we.writeFileSync(ue.join(e,"infra-kit.example.jsonc"),Ku(),"utf-8"),we.writeFileSync(ue.join(e,"vendor.example.jsonc"),qu(),"utf-8"),we.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(we.writeFileSync(t,`{}
354
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},IC=async e=>{if(ed.env.INFRA_KIT_NO_SEED)return[fs("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[fs("skipped","not inside a git repository")];try{let t=await X();if(!we.existsSync(t.main))return[fs("skipped",`no project config at ${t.main}`)];let r=await jn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:Fn(r),level:"info"}]:[fs("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[fs("warned",t instanceof Error?t.message:String(t))]}},fs=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),NC=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},_C=(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"},...NC(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},MC=async()=>{let{skipped:e,root:t,version:r,written:n}=await yy({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:_C(r,n)}},Oa=e=>`cd ${Uf(e)} && infra-kit setup --skip-tools`,gs=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${Oa(t)}`,level:"info"}),jC=(e,t)=>{let r=ue.relative(e,t.path);return t.status==="withheld"?gs("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"}},nv=(e,t)=>{let r=Ye;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?me: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 ${kt} from ${ue.join(e,Ye)} \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 "${me}" key`:`no ${r}`})`,level:"info"}},FC=(e,t)=>e===null||t!==null?[]:[{step:"plugin-pointer",outcome:"warned",message:`No infra-kit.json at ${e} \u2014 setting up Claude Code there anyway: writing .claude/settings.json and installing the ${Z} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],LC=()=>[cu,_t].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),BC=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:Ni(e.updateCommand),level:"info"}]:[r]},UC=(e,t)=>e.status==="skipped-cli-stale"?BC(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${Z} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${Sn}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${Z} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...LC()]:[{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: ${_t}`,level:"warn"}],av={stale:!1},VC=async()=>{let e=_o(),t=e===null?await Cl(ed.env):e.latestVersion;return t===null||!$l(t,U.version)?av:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??jf(t)}},WC=async e=>{if(e===null)return[];let r=`${await _e(e)}${le}`,n=Object.values(cn).filter(o=>!we.existsSync(ue.join(r,o)));for(let o of Object.values(cn))we.mkdirSync(ue.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"}]},GC=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${Z} is installed; the update worker keeps it current`,level:"debug"}]:[gs("plugin-pointer",e,".claude/settings.json",[`the ${Z} plugin installed`])],JC=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(jC(e,lu(ue.join(e,".claude","settings.json"),{write:!it.withheld})));let r=Er({projectPath:e}).kind==="installed";if(it.withheld){t(...GC(e,r),nv(e,Rn(e)));return}let n=r?await VC():av;t(...UC(nu({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(nv(e,Rn(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: ${_t}`,level:"warn"})}},cv=(e,t)=>{let r=ue.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},KC=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=cv(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,gs("mcp-proxies",e,ue.relative(e,t.path),s)]},HC=async e=>{if(e===null)return[];if(!we.existsSync(ue.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 L()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
355
- `)[0]??n;return it.withheld?[gs("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?[]:it.withheld?KC(e,Xo({projectRoot:e,proxies:t,write:!1})):cv(e,Xo({projectRoot:e,proxies:t,write:!0}))},qC=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"),zC=e=>{let t=rr(e,Mr,ar);if(t!==null)return t;for(let[a,c]of RC){let l=rr(e,a,c);if(l!==null)return l}let r=e.indexOf(SC);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
356
- `),s=0;for(;s<o.length&&qC(o[s]);)s++;let i=o.slice(s).join(`
351
+ `)}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=rv.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${SC.prettifyError(n.error)}`);return n.data};var nv=e=>e.replace(/\.json$/,".yml"),ov=async()=>{let e;try{e=await X()}catch{return}let t={label:"infra-kit.json",yml:nv(e.main),json:e.main,schema:Cg},r=[...it.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:St.join(St.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:gl},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:nv(e.userProject),json:e.userProject,schema:gl}],n=0;for(let o of r){let[s,i]=await Promise.all([ie(o.yml),ie(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${w(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await Et.readFile(o.yml,"utf-8"),c=PC.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${Wn.prettifyError(l.error)}`);continue}await Et.mkdir(St.dirname(o.json),{recursive:!0}),await Et.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
352
+ `,"utf-8"),await Et.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${w(o.yml)} \u2192 ${w(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${a.message}`)}}}n>0&&Qt()},sv=async()=>{let e;try{e=await X()}catch{return}let t=St.dirname(e.userGlobal),r=[{from:St.join(t,"config.json"),to:e.userGlobal},{from:St.join(t,"config.example.jsonc"),to:St.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([ie(o),ie(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await Et.mkdir(St.dirname(s),{recursive:!0}),await Et.rename(o,s),d.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Qt()},xC=Wn.object({workspaceDir:Wn.string().min(1),targets:Wn.array(Wn.string()).min(1)}).strict(),iv=async()=>{let e=Un(),t=St.dirname(e),r=St.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ie(r),ie(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await Et.stat(r),c=(await import(`${EC(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=xC.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${Wn.prettifyError(p.error)}`);return}await Et.mkdir(t,{recursive:!0}),await Et.writeFile(e,`${JSON.stringify(p.data,null,2)}
353
+ `,"utf-8"),await Et.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${w(r)} \u2192 ${w(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${w(e)} directly to change them.`):d.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},av=async()=>{let e=await TC(),t=0;for(let r of e)if(await ie(r))try{let n=await ug(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof lg?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Qt()},TC=async()=>{try{let e=await X();return it.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[Ag()]}};var Mr="# -- infra-kit:begin --",ar="# -- infra-kit:end --",CC=[["# region infra-kit","# endregion infra-kit"]],$C="# infra-kit shell functions",Gn=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},Jn="Run `source ~/.zshrc` or open a new terminal to activate.",AC={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Ze=async(e,t)=>{try{return await t()}catch(r){throw new Gn(e,r)}},rd=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Ze("zshrc",()=>{r(IC())}),await Ze("zshenv",()=>{r(NC())}),await Ze("migrations",async()=>{await MC(),_C(),r(AC)}),await Ze("user-config",()=>{r(FC())});let n=await Ze("guidance",async()=>{let{entries:s,root:i}=await VC();return r(...s),i}),o=await Ze("plugin-pointer",async()=>by());return r(...GC(o,n)),await Ze("worktrees",async()=>{r(...await zC(o))}),await Ze("plugin-pointer",async()=>{await XC(o,r)}),await Ze("mcp-proxies",async()=>{r(...await QC(o))}),await Ze("project-config",async()=>{r(...await LC(o))}),await Ze("token-perms",async()=>{r(await DC())}),await Ze("chrome",()=>{r(OC())}),r(...jC()),t},OC=()=>{let e=as();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"}:Uu()?{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"}},DC=async()=>{let e=await Dg();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 lv=e=>{let t=ue.dirname(e);return we.existsSync(ue.join(e,".git"))?e:t===e?null:lv(t)},uv=(e,t,r,n)=>{if(!it.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=we.realpathSync(t)}catch{}return lv(ue.dirname(o))===null?null:gs(e,Aa.homedir(),o,["the infra-kit block updated"])},dv=e=>we.existsSync(e)?we.readFileSync(e,"utf-8"):null,IC=()=>{let e=ue.join(Aa.homedir(),".zshrc"),t=dv(e),r=t===null?"":t$(t),n=gn({content:r,body:fv(),startMarker:Mr,endMarker:ar,placement:"append-end"}),o=uv("zshrc",e,t,n);return o!==null?o:(we.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},NC=()=>{let e=ue.join(Aa.homedir(),".zshenv"),t=dv(e),r=gn({content:t??"",body:nd(),startMarker:Mr,endMarker:ar}),n=uv("zshenv",e,t,r);return n!==null?n:(we.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},_C=()=>{we.rmSync(ue.join(Ot(),"projects"),{recursive:!0,force:!0})},MC=async()=>{await ov(),await sv(),await av(),await iv()},jC=()=>{let e=td.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:Jn,level:"info"}),t},FC=()=>{let e=ue.join(Aa.homedir(),".infra-kit"),t=ue.join(e,"infra-kit.json");return we.mkdirSync(e,{recursive:!0}),we.writeFileSync(ue.join(e,"infra-kit.example.jsonc"),Hu(),"utf-8"),we.writeFileSync(ue.join(e,"vendor.example.jsonc"),zu(),"utf-8"),we.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(we.writeFileSync(t,`{}
354
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},LC=async e=>{if(td.env.INFRA_KIT_NO_SEED)return[fs("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[fs("skipped","not inside a git repository")];try{let t=await X();if(!we.existsSync(t.main))return[fs("skipped",`no project config at ${t.main}`)];let r=await Fn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:Ln(r),level:"info"}]:[fs("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[fs("warned",t instanceof Error?t.message:String(t))]}},fs=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),BC=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},UC=(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"},...BC(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},VC=async()=>{let{skipped:e,root:t,version:r,written:n}=await Ry({dryRun:!0});return e||t===null?{root:null,entries:[{step:"guidance",outcome:"skipped",message:"Agent-instruction files skipped \u2014 not an infra-kit repo",level:"silent"}]}:{root:t,entries:UC(r,n)}},Oa=e=>`cd ${Vf(e)} && infra-kit setup --skip-tools`,gs=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${Oa(t)}`,level:"info"}),WC=(e,t)=>{let r=ue.relative(e,t.path);return t.status==="withheld"?gs("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"}},cv=(e,t)=>{let r=Ye;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?me: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 ${kt} from ${ue.join(e,Ye)} \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 "${me}" key`:`no ${r}`})`,level:"info"}},GC=(e,t)=>e===null||t!==null?[]:[{step:"plugin-pointer",outcome:"warned",message:`No infra-kit.json at ${e} \u2014 setting up Claude Code there anyway: writing .claude/settings.json and installing the ${Z} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],JC=()=>[lu,Mt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),KC=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:Ni(e.updateCommand),level:"info"}]:[r]},HC=(e,t)=>e.status==="skipped-cli-stale"?KC(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${Z} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${En}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${Z} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...JC()]:[{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"}],pv={stale:!1},qC=async()=>{let e=_o(),t=e===null?await $l(td.env):e.latestVersion;return t===null||!Al(t,U.version)?pv:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Ff(t)}},zC=async e=>{if(e===null)return[];let r=`${await _e(e)}${le}`,n=Object.values(cn).filter(o=>!we.existsSync(ue.join(r,o)));for(let o of Object.values(cn))we.mkdirSync(ue.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"}]},YC=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${Z} is installed; the update worker keeps it current`,level:"debug"}]:[gs("plugin-pointer",e,".claude/settings.json",[`the ${Z} plugin installed`])],XC=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(WC(e,uu(ue.join(e,".claude","settings.json"),{write:!it.withheld})));let r=Er({projectPath:e}).kind==="installed";if(it.withheld){t(...YC(e,r),cv(e,Sn(e)));return}let n=r?await qC():pv;t(...HC(ou({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(cv(e,Sn(e)))}catch(r){let n=r instanceof Error?r.message:String(r);t({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${Mt}`,level:"warn"})}},mv=(e,t)=>{let r=ue.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},ZC=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=mv(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,gs("mcp-proxies",e,ue.relative(e,t.path),s)]},QC=async e=>{if(e===null)return[];if(!we.existsSync(ue.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 L()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
355
+ `)[0]??n;return it.withheld?[gs("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?[]:it.withheld?ZC(e,Xo({projectRoot:e,proxies:t,write:!1})):mv(e,Xo({projectRoot:e,proxies:t,write:!0}))},e$=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"),t$=e=>{let t=nr(e,Mr,ar);if(t!==null)return t;for(let[a,c]of CC){let l=nr(e,a,c);if(l!==null)return l}let r=e.indexOf($C);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
356
+ `),s=0;for(;s<o.length&&e$(o[s]);)s++;let i=o.slice(s).join(`
357
357
  `);return n+(i?`
358
- ${i}`:"")},lv=()=>{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(`
359
- `)},uv=()=>`${Mr}
360
- ${lv()}
361
- ${ar}`,rd=()=>["# 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(`
362
- `),nd=()=>`${Mr}
363
- ${rd()}
364
- ${ar}`;import hs from"node:fs/promises";import ys from"node:path";import{$ as YC}from"zx";var XC=async e=>ys.resolve(e,(await YC({cwd:e,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim()),od=async e=>ys.join(await XC(e),"infra-kit","merge-dev-resolutions"),vs=async(e,t)=>ys.join(await od(e),`${gg(t)}.json`),Da=async e=>{try{return JSON.parse(await hs.readFile(e,"utf8"))}catch{return null}},cr=async(e,t)=>{let r=await vs(e,t.branch);await hs.mkdir(ys.dirname(r),{recursive:!0}),await hs.writeFile(r,`${JSON.stringify(t,null,2)}
365
- `)},Ia=async e=>{let t=await od(e),r=await hs.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Da(ys.join(t,o))))).filter(o=>o!==null)},sd=async e=>Promise.all((await Ia(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await hs.stat(t.worktreePath).then(()=>!0,()=>!1)})));var ws=async()=>{try{return(await L()).defaultEnv??null}catch{return null}};var ks=["prod"],Jn={allowed:!1,reason:"disallow"},lr=e=>ks.includes(e),ZC=["dev","stage"],Kn=e=>ZC.includes(e)||lr(e),jt=(e,t=Jn)=>t.allowed?e:e.filter(r=>!lr(r)),jr=(e,t,r=Jn)=>{if(!r.allowed&&lr(e))throw r.reason==="agent-blocked"?new A({status:"refused",env:e,agentMode:N.source},2,{operation:t,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new g(void 0,{operation:t,remediation:`use \`infra-kit release deliver\` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var lt=async()=>{let e;try{e=(await L()).protectedEnvs??"disallow"}catch{return Jn}return e==="disallow"?Jn:e==="cli-only"&&te()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var bs=e=>{let{env:t,branch:r}=e;lr(t)&&d.warn([`\u26A0\uFE0F "${t}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${r}" ships ${t} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
366
- `))};import dv from"node:fs/promises";import id from"node:path";import QC from"yaml";var pv=".github/workflows",Ft=async e=>{let t=await $();return mv(id.resolve(t,pv,e))},ad=async()=>{let e=await $(),t=id.resolve(e,pv),r;try{r=await dv.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>mv(id.resolve(t,s))));return[...new Set(o.flat())]},mv=async e=>{let t;try{t=QC.parse(await dv.readFile(e,"utf-8"))}catch{return[]}let r=Hn(t,"on")??Hn(t,"true"),n=Hn(Hn(Hn(Hn(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},Hn=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var ur=async()=>{let e=await ad(),t=await fe(),r=e.map(s=>({env:s,source:"gh-workflow"})),n=new Set(e),o=Object.keys(t?.envs??{}).filter(s=>!n.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...r,...o]},Fr=async()=>(await ur()).map(t=>t.env);import{$ as c$}from"zx";import Ss from"node:process";var e$="x-seraph-loginreason",t$="AUTHENTICATED_FAILED",r$=(e,t=160)=>{let r=e.split(`
367
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},gv=(e,t)=>t===t$||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",fv=(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}`,qn=class extends Error{status;kind;body;context;constructor(t){let r=gv(t.status,t.seraphLoginReason),n=r$(t.body);super(n===""?`${t.context}: ${fv(r,t.status)}`:`${t.context}: ${fv(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Rs=e=>e instanceof qn,hv=e=>e.headers.get(e$);var zn=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new qn({status:e.status,seraphLoginReason:hv(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},Lr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,cd=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 zn(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Yn=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 zn(a,"Failed to get Jira project versions"),await a.json()},Lt=async(e,t)=>(await Yn(t)).find(o=>o.name===e)||null,Xn=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 zn(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}},ld=async(e,t)=>{let{versionName:r}=e,n=await Lt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Xn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Zn=async()=>{let e=Ss.env.JIRA_BASE_URL,t=Ss.env.JIRA_TOKEN||Ss.env.JIRA_API_TOKEN,r=Ss.env.JIRA_PROJECT_ID,n=Ss.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(`
368
- `);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}},Bt=async()=>{try{return await Zn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Na=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 zn(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},ud=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 zn(c,"Failed to remove Jira version")};import{z as yv}from"zod";var vv=/^\d{4}-\d{2}-\d{2}$/,Es=e=>{if(!vv.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},wv=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,Qn=class extends Error{constructor(t){super(wv(t)),this.name="InvalidReleaseDateError"}},Br=e=>{let t=e.trim();if(!Es(t))throw new Qn(t);return t},Ps=e=>{let t=e.trim();return t===""||Es(t)?!0:wv(t)},dd=yv.string().refine(Es,{message:"Expected a calendar date in yyyy-mm-dd form."}),pd=yv.string().refine(e=>e===""||Es(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var dr=e=>e.slice(1).split(".").map(Number),eo=e=>[...e].sort((t,r)=>{let[n,o,s]=dr(t),[i,a,c]=dr(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var bv="next",n$=/^v?(\d+)\.(\d+)\.(\d+)$/,o$=e=>e.replace(/^.*release\//,""),md=e=>{let t=o$(e.trim()),r=n$.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},kv=e=>`${e[0]}.${e[1]}.${e[2]}`,fd=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=md(o);if(!s)continue;let i=kv(s);n.has(i)||(n.add(i),r.push(s))}return eo(r.map(o=>kv(o))).map(o=>dr(`v${o}`))},Ur=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},gd=(e,t)=>{if(e.length===0)throw new Ur;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`},to=(e,t)=>{try{return gd(e,t)}catch(r){if(r instanceof Ur)return null;throw r}},hd=e=>e.trim().toLowerCase()===bv,Ma=e=>hd(e)||md(e)!==null?{version:e}:{name:e},s$=e=>e==="regular"||e==="hotfix",Rv=e=>"name"in e,i$=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:Br(n)}},yd=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=i$(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(!s$(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return _a({...Ma(n),type:s},{description:i,releaseDate:o})},vd=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},_a=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},a$=e=>{let t=e.name.trim();return Fi(t),_a({id:{kind:"name",name:t,raw:t},type:e.type},e)},wd=(e,t)=>{let r=[...t];return e.map(n=>{if(Rv(n))return a$(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(hd(o)){let a=gd(r,n.type);return r.push(dr(`v${a}`)),_a({id:Ee(a),type:n.type},n)}let s=md(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),_a({id:Ee(i),type:n.type},n)})},kd=e=>e.some(t=>!Rv(t)&&hd(t.version));var l$=e=>e.split(`
369
- `).map(t=>{let r=t.indexOf(" ");return r===-1?null:re(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),u$=async()=>{let e=await c$({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return l$(e.stdout)},d$=async()=>{let e=await Bt();return e?(await Yn(e)).map(r=>r.name):[]},xs=async()=>{let[e,t]=await Promise.allSettled([u$(),d$()]);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"),fd({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import p$ from"node:fs";import m$ from"node:path";var bd=[".claude/settings.json",".claude/settings.local.json"],f$=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],g$=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),h$=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},y$=(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(g$).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},v$=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},w$=(e,t)=>{let r=h$(e);return r===null?[]:t.filter(n=>n.mutating).filter(n=>f$.some(o=>v$(n).some(s=>y$(r,`${o} ${s}`)))).map(n=>n.groupPath.join(" "))},k$=(e,t)=>{let r;try{r=p$.readFileSync(m$.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}},Sv=(e,t)=>{let r={present:[],unreadable:[],hits:[]};for(let n of bd){let o=k$(e,n);if(o.kind!=="absent"){if(r.present.push(n),o.kind==="unreadable"){r.unreadable.push(n);continue}for(let s of o.patterns){let i=w$(s,t);i.length>0&&r.hits.push({file:n,pattern:s,commands:i})}}}return r};var R$=e=>e.every(t=>t.status!=="fail"),S$=["brew","git","gh","doppler","aws"],E$=async e=>{let t=await ps(S$,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},Ut=async(e,t,r,n)=>{try{return await Nn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},P$=async()=>{let e="orca installed",t=await tr();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)"}},Iv=(e,t,r,n)=>{let o=Qe.join(b$.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!Ie.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=Ie.readFileSync(o,"utf-8"),a=i.indexOf(Mr),c=i.indexOf(ar);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+ar.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`}},x$=()=>Iv("zshrc init block",".zshrc","shell",uv()),T$=()=>Iv("zshenv session block",".zshenv","session-env",nd()),C$=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await $(),r=Qe.join(t,"pnpm-workspace.yaml");if(!Ie.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=Ie.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},$$=async()=>{try{return Zt(),{config:await L(),error:null}}catch(e){return{config:null,error:e}}},A$=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)"}},O$=384,Rd=448,D$=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(", "),I$=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}}})),N$=async(e,t={})=>{let r="env tokens configured",n=t.readStore??fe,o=t.resolveToken??Rl;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 I$(await Fr(),o);return{name:r,status:"pass",message:D$(s)}},_$=()=>Cs.env[De]||void 0,M$=async(e={})=>{let t="tokens.json present",r=e.readStore??fe,n=e.storePath??er;if((e.readEnvToken??_$)())return{name:t,status:"skip",message:`${De} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${De} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Ts=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},j$=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??er,o=t.statPath??F$,s=t.chmodPath??Ie.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(Ts(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=Qe.dirname(i),c=Qe.dirname(a),l=Qe.dirname(c),p=[{target:l,expected:Rd,actual:Ts(l,o)},{target:c,expected:Rd,actual:Ts(c,o)},{target:a,expected:Rd,actual:Ts(a,o)},{target:i,expected:O$,actual:Ts(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${w(f.target)} is ${Ev(f.actual)}, expected ${Ev(f.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit setup --skip-tools\` or \`infra-kit doctor --fix\`.`};for(let f of p)s(f.target,f.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},Ev=e=>`0${e.toString(8).padStart(3,"0")}`,F$=e=>{try{return Ie.statSync(e)}catch{return null}},L$=async()=>{let e="user override path";try{let t=await X(),r=Ie.existsSync(t.userProject),n=await cs(t.userProject,r),o=r?ls(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},B$=async()=>{let e="legacy user-global config",t;try{t=await X()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=Qe.join(Qe.dirname(t.userGlobal),"config.json");return Ie.existsSync(r)?Ie.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Pv=/^\d+\.\d+\.\d+$/,xv=(e,t)=>e===t||!Pv.test(e)||!Pv.test(t)?!1:eo([`v${e}`,`v${t}`])[0]===`v${e}`,U$=async e=>{let t;try{t=await vt(e)}catch{return[]}return t.flatMap(r=>{let n=Nt(wt(Qe.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},Tv=e=>eo(e.map(t=>`v${t}`)).map(t=>t.slice(1)),V$=async(e,t,r)=>{let n="Guidance version",o=$r(t,Ar),s=await U$(e),a=(o===null?s:[o,...s]).filter(p=>at(p,r));if(a.length>0){let p=Tv(a).at(-1);return{name:n,status:"warn",message:`${a.length} guidance ${a.length===1?"block was":"blocks were"} generated by a newer infra-kit (newest ${p}, current ${r}) \u2014 CLI behind the block, run: pnpm add -g infra-kit@${p}`}}let c=o!==null&&xv(o,r),l=s.filter(p=>xv(p,r));if(!c&&l.length===0)return{name:n,status:"pass",message:`guidance blocks match infra-kit ${r}`};let u=[...c?[`the root block is from infra-kit ${o} \u2014 run: infra-kit audit --fix --root`]:[],...l.length>0?[`${l.length} package guidance ${l.length===1?"block was":"blocks were"} generated by an older infra-kit (oldest ${Tv(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},W$=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"},{name:"Guidance version",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await X()).main}catch{return e}if(!Ie.existsSync(t))return e;let r=Qe.dirname(t),n=Qe.join(r,"CLAUDE.md"),o=Ie.existsSync(n)?Ie.readFileSync(n,"utf-8"):"",s=qe(o,Te,Fe);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools"},await V$(r,o,U.version)]},G$=async()=>{try{let e=(await X()).main;return Ie.existsSync(e)?Qe.dirname(e):null}catch{return null}},J$=e=>{let t=Tg();return t===null||!at(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Sn}`},K$=e=>{let t=e.kind==="installed"?Gi(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${Z} version ${t}${J$(t)}`}},Cv=3,$v=(e,t)=>Se(e)===Se(t),H$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if($v(e.projectDir,e.gitRoot))return"";let r=ln(e.gitRoot,Se(e.projectDir),Se)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return $v(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},q$=(e,t)=>{let r="plugin installed",n=H$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${Z} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${Z} is not installed. Run: ${_t}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-Cv,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Cv).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${Z} is installed for ${a} only, not this project. Run: ${_t}${n}`}},z$=()=>Ut("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 Y$=(e,...t)=>{try{return JSON.parse(Ie.readFileSync(Qe.join(e,...t),"utf-8"))}catch{return null}},X$=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=Gi(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=Y$(r,Ye),o=n!==null&&typeof n=="object"?n[kt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Av=e=>`Plugin ${Z} ${e===null?"(version unreadable)":e}`,Z$=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: ${_t}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Av(e.version)} still carries an MCP server in its ${Ye}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Sn}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Av(e.version)} is skills-only \u2014 no ${Ye}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},Q$=(e,t)=>{let r=Er(e===null?{}:{projectPath:e}),n=Io();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${me} is known to Claude Code`:`Marketplace ${me} is not registered. Run: claude plugin marketplace add ${Qt}`},q$(r,t),K$(r),Z$(X$(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},eA=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${w(On())}, or run: infra-kit setup`}},tA=({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(", ")},rA=e=>{let t="Agent mode",r=ji(e),n=tA(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})`}},Ov=4,nA=e=>{let t=e.slice(0,Ov).join(", "),r=e.length-Ov;return r>0?`${t} +${r} more`:t},oA=(e,t)=>{let r="Agent allowlist",{present:n,unreadable:o,hits:s}=Sv(e,t);if(s.length>0){let i=s.map(a=>`${a.file} allows "${a.pattern}", which reaches ${a.commands.length} mutating infra-kit command${a.commands.length===1?"":"s"} (${nA(a.commands)})`);return{name:r,status:"warn",message:`${i.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 o.length>0?{name:r,status:"warn",message:`Could not read permissions.allow from ${o.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:n.length===0?{name:r,status:"pass",message:`no ${bd.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:r,status:"pass",message:`no permissions.allow pattern in ${n.join(" or ")} reaches a mutating infra-kit command`}},sA=(e,t)=>e===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:t===void 0?{name:"Agent allowlist",status:"skip",message:"no command catalog supplied"}:oA(e,t),iA=(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`},aA=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 sd(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${iA(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`}},Nv=e=>cl(["trust"],{bin:e}),cA=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Dv="ERR_TLS_CERT_ALTNAME_INVALID",_v=()=>`portless serving TLS on :${Xt}`,lA=async(e,t,r)=>{let n=_v();return await e(Xt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Xt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Xt}. Install it once (needs root): \`${Ot(t,r)}\`.`}},uA=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(Xt,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(Dv)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Dv} 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=>cA.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${Nv(n)}\`, or reinstall: \`${Ot(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},dA=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Nv(r)}\` (no sudo needed).`}},pA=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 \`${cl(["alias","--remove","<name>"],{bin:r})}\`.`}},mA=()=>[$n,Mt,_v(),"portless CA chain valid","portless CA trusted","portless routes"],fA=async(e={})=>{let t=e.resolveBin??Vf,r=e.isProxyServing??Hf,n=e.handshake??Xf,o=e.caTrusted??Yf,s=e.routes??Co,i=e.isListening??To,a=(e.caPath??zf)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...mA().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}=ju(e,c),m=s(),f=await lA(r,c,u),h=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await uA(n,m,a,c,u);return[l,p,(await Fu(u)).row,f,h,dA(o(),a,c),await pA(m,i,c)]},gA=async(e={})=>{let t="portless routes",r=e.routes??Co,n=e.isListening??To,o=e.devSessionRunning??dy,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}=uy(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??Zf().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ja=async(e={})=>{let t=await $$(),r=E$(e.probeDeps??us()),n=async(m,f)=>{let[h,b]=await Promise.all([f,r]),C=b.get(m);return C===void 0?h:{...h,detail:C}},o=await Promise.all([n("brew",Ut("brew installed",Xe("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",Ut("git installed",Xe("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",Ut("gh installed",Xe("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),Ut("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",Ut("doppler installed",Xe("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",Ut("aws installed",Xe("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")),Ut("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),Ut("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"),P$(),Promise.resolve(x$()),Promise.resolve(T$()),C$(),Promise.resolve(A$(t)),M$(),N$(t),j$(e.fix??!1),L$(),B$()]),s=await fA(e.portlessDeps);if(e.fix){let m=await gA(),f=s.findIndex(h=>h.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await G$(),a=await Cn(),c={projectDir:Cs.env.CLAUDE_PROJECT_DIR||null,cwd:Cs.cwd(),gitRoot:a},l=[await z$(),...Q$(i,c),as(),rA({env:Cs.env,stdinIsTTY:Cs.stdin.isTTY===!0,flag:N.source==="flag"}),sA(a,e.catalog)],u=[...o,await aA(a),...s,...await W$(),...l,eA(Dn(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:_u.has(m.name),detail:m.detail})),allPassed:R$(u),cliVersion:U.version};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}},Sd=T({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:Le.array(Le.object({name:Le.string().describe("Name of the check"),status:Le.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:Le.string().describe("Details about the check result"),fixable:Le.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Le.object({manager:Le.string().describe("Which package manager owns this install, read from its resolved path"),version:Le.string().nullable().describe("The version the tool reported, or null"),present:Le.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Le.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:Le.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Le.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ja()});import{E2E_MODE_ENV as WA}from"@slip-stream-kit/config/internal";import Od from"node:fs";import GA from"node:os";import As from"node:path";import Ba from"node:process";import{z as E}from"zod";var Et=(e,t,r)=>new A({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as hA,loadDev as yA,readAppAliasName as vA,readCloudOrigin as wA,readLocalContext as jv}from"@slip-stream-kit/config/internal";import Mv from"node:fs";import Vr from"node:path";import Fa from"node:process";import{z as Ed}from"zod";var kA=async e=>{let t=Vr.join(e,"apps"),r=Mv.existsSync(t)?Mv.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=Vr.join(t,o,"tests"),a=(await yt(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},bA=(e,t)=>{let[r,n]=Vr.relative(e,t).split(Vr.sep);return r==="apps"&&n?n:void 0},RA=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(bA(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new g(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new A({status:"argument_required",argument:a,choices:Ed.toJSONSchema(Ed.object({app:Ed.enum(i)})),agentMode:N.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},SA=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}})),EA=e=>ns(e).apps.find(t=>t.env!=="")?.env??null,Pd=async(e,t={})=>{let r=t.cwd??Fa.cwd(),n=t.projectRoot??await $(),o=(t.env??Fa.env)[qt]||null,s=t.healthProbe??Al,i=RA(await kA(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=Vr.join(n,"apps",c,l),p=(await Tr(u)).name,m=(await yt(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${Vr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Gg(u),h=vA(p,u),b=`${h}.localhost`,C=`https://${b}`,k=0;if(l==="ui")k=(t.listRoutes??Co)().find(S=>S.name===b||S.name===h)?.port??0;else{let S=jv(u).info.get(p);k=S?.port??0,C=S?.origin??C}let F=k>0&&await s({tag:a,port:k,kind:l})==="ok",v=F?EA(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:v,localUrl:C,served:F}},Fv=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}},xd=async(e,t={})=>{let r=t.healthProbe??Al,n=jv(e.targetDir),o=e.kind==="ui"?await yA(e.targetDir):void 0,s=o?.proxy?hA({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:wA(e.deployedUrlEnv??void 0,t.env??Fa.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Fv(e),mode:"local",baseUrl:e.localUrl,routes:await SA(s,i,r)}},Td=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw Et("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${Vr.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??Fa.env)[n];if(!r||!s){let i=s?qt:n;throw Et("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 ${qt}, and ${i} is not set`})}return{...Fv(e),mode:"cloud",baseUrl:s,routes:[]}};import PA from"node:fs";import xA from"node:path";import{stripVTControlCharacters as TA}from"node:util";import{z as M}from"zod";var Lv=2e3,Bv="--reporter=line,json",Uv=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Vv=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Cd=M.object({message:M.string().optional()}),Wv=M.object({type:M.string()}),CA=M.object({status:M.string(),retry:M.number(),error:Cd.optional(),errors:M.array(Cd).optional(),annotations:M.array(Wv).optional(),attachments:M.array(M.object({name:M.string(),path:M.string().optional()})).optional()}),$A=M.object({projectName:M.string(),status:M.string(),expectedStatus:M.string().optional(),annotations:M.array(Wv).optional(),results:M.array(CA)}),AA=M.object({title:M.string(),file:M.string(),line:M.number().optional(),tests:M.array($A)}),Gv=M.lazy(()=>M.object({title:M.string(),specs:M.array(AA).optional(),suites:M.array(Gv).optional()})),OA=M.object({config:M.object({rootDir:M.string().optional()}).optional(),suites:M.array(Gv),errors:M.array(Cd).optional(),stats:M.object({expected:M.number(),unexpected:M.number(),flaky:M.number(),skipped:M.number()})}),Jv=e=>{let t=TA(e);return t.length>Lv?`${t.slice(0,Lv)}\u2026`:t},DA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Jv(t)},IA=e=>e.status==="unexpected"||e.status==="flaky",NA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},_A=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),MA=(e,t)=>{let r=e.filter(IA),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?DA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},jA=e=>{let t=OA.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=new Map,c=0,l=(p,m)=>{let f=new Set(m.flatMap(C=>[..._A(C)])),h=m.some(C=>C.expectedStatus==="failed");if(!h&&!f.has("fixme")&&!f.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};h&&(b.fail+=1),f.has("fixme")?b.fixme+=1:f.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let f of p.specs??[]){let h=r?.rootDir?xA.resolve(r.rootDir,f.file):f.file,b=[...m,f.title].join(" \u203A ");l(h,f.tests);for(let[C,k]of NA(f.tests)){let F=MA(k,{title:b,file:h,line:f.line??null,project:C});F&&(F.runs>1&&F.failedRuns<F.runs&&(c+=1),i.push(F))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[Jv(p.message)])}},Kv=e=>{try{return jA(JSON.parse(PA.readFileSync(e,"utf8")))}catch{return null}};import $s from"node:fs";import qv from"node:path";import La from"node:process";var FA=e=>qv.join(e,"node_modules",".cache","infra-kit-e2e.lock"),LA=e=>{try{return La.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Hv=(e,t)=>{try{return $s.writeFileSync(e,`${La.pid}
370
- ${JSON.stringify({startedAt:Date.now(),command:t})}`,{flag:"wx"}),!0}catch(r){if(r.code==="EEXIST")return!1;throw r}},BA=e=>{try{let t=JSON.parse(e??"");return{...typeof t?.startedAt=="number"&&{startedAt:t.startedAt},...typeof t?.command=="string"&&{command:t.command}}}catch{return{}}},$d=e=>{try{let[t,r]=$s.readFileSync(e,"utf8").split(`
371
- `),n=Number.parseInt(t,10);return Number.isInteger(n)&&n>0?{pid:n,...BA(r)}:null}catch{return null}},zv=(e,t)=>{let r=FA(e);if($s.mkdirSync(qv.dirname(r),{recursive:!0}),!Hv(r,t)){let n=$d(r);if(n!==null&&n.pid!==La.pid&&LA(n.pid))return{holder:n};if($s.rmSync(r,{force:!0}),!Hv(r,t))return{holder:$d(r)??{pid:0}}}return{release:()=>{$d(r)?.pid===La.pid&&$s.rmSync(r,{force:!0})}}};import{spawn as UA}from"node:child_process";import VA from"node:os";import Ad from"node:process";var Yv=(e,t,r)=>new Promise((n,o)=>{let s=UA(e,t,r),i=Ad.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Ad.off(l,a)};for(let l of i)Ad.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+VA.constants.signals[u]:1))})});var JA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],KA=e=>JA.some(t=>{try{return Od.readFileSync(As.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),Dd=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,HA=(e,t)=>{let r=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl}`];e.mode==="cloud"?r.push(` deployed app at env "${e.env}"`):t?r.push(` dev server for ${e.target} on release "${e.release}", already running`):r.push(` nothing serves ${e.target} yet; the Playwright config starts it and stops it after the run`);for(let n of e.routes){let o="";n.live!==null&&(o=n.live?" \u2014 live":" \u2014 NOT responding"),r.push(` ${n.path.padEnd(24)} ${n.source.padEnd(5)} ${n.target??"(unresolved)"}${o}`)}return r.join(`
372
- `)},qA=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 Et("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(", ")}`})},zA=async(e,t)=>{if(e.env===null||!lr(e.env))return;let r=await(t.protectedEnvAccess??lt)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?Et("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`}):Et("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`})},YA=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw Et("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"}"`})},XA=async(e,t)=>{if(e.served){YA(e);let p=await xd(e,t);return qA(p),p}if(!KA(e.testsDir))throw Et("no_dev_server",{devCommand:Dd(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${Dd(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:[]}},ZA=(e,t,r)=>Yv("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Ba.env,...r,[WA]:e.mode},stdio:["inherit",Yt.enabled||H()?2:"inherit","inherit"]}),QA=(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:As.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=As.join(e.testsDir,"test-results",`ik-e2e-${n}-${Ba.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},eO=e=>{if(e.mode==="cloud")return()=>{};let t=zv(e.testsDir,`ik e2e --app ${e.app}`);if("holder"in t){let{pid:r,startedAt:n,command:o}=t.holder,s=n===void 0?void 0:`${Math.floor((Date.now()-n)/1e3)}s`,i=[`pid ${r}`,s,o].filter(Boolean).join(", ");throw Et("run_in_progress",{pid:r,startedAt:n,command:o},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${r}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (${i}) is using its dev server`})}return t.release},Ua=async(e,t={})=>{let r=await Pd(e.app,t),n=e.cloud?Td(r,t):await XA(r,t);d.info(HA(n,r.served)),n.mode==="cloud"&&await zA(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?Dd(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Nd({...o,ran:!1,exitCode:null,...Id});n.mode==="cloud"&&await q(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=eO(n);try{return await tO(o,t.runPlaywright??ZA)}finally{s()}},tO=async(e,t)=>{if(!H()||Vv(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(Ba.exitCode=i),Nd({...e,ran:!0,exitCode:i,...Id,report:H()?"caller-reporter":"off"})}let{args:r,outputDir:n}=QA(e,e.playwrightArgs),o=Od.mkdtempSync(As.join(GA.tmpdir(),"ik-e2e-report-")),s=As.join(o,"report.json");try{let i=await t(e,[Bv,...r],Uv(s));i!==0&&(Ba.exitCode=i);let a=Kv(s);return Nd({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...Id,report:"unavailable"},outputDir:n})}finally{Od.rmSync(o,{recursive:!0,force:!0})}},Id={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},Nd=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),rO={app:E.string(),testsDir:E.string(),target:E.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:E.string(),mode:E.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:E.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:E.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:E.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:E.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:E.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:E.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:E.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:E.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:E.array(E.object({path:E.string(),packageName:E.string(),source:E.enum(["local","cloud"]),target:E.string().nullable(),live:E.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:E.array(E.string()),ran:E.boolean().describe("False for --dry-run."),exitCode:E.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:E.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:E.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:E.object({expected:E.number(),unexpected:E.number(),flaky:E.number(),skipped:E.number(),repeatFlaky:E.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:E.array(E.object({title:E.string().describe("Describe path and test title, joined with \u203A."),file:E.string(),line:E.number().nullable(),project:E.string(),status:E.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:E.number().describe("The retry index of the failed attempt reported here."),runs:E.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:E.number().describe("How many of those runs failed."),error:E.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:E.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:E.array(E.object({file:E.string(),fail:E.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:E.number().describe("test.fixme \u2014 skipped as unfinished."),skip:E.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:E.array(E.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},_d=T({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:E.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:E.boolean().optional(),yes:E.boolean().optional(),cloud:E.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:E.array(E.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:rO,handler:e=>Ua(e)});import Va from"node:fs";import Md from"node:path";import{z as Os}from"zod";var nO=e=>[...e.map(t=>`unset ${t}`),`unset ${qt}`,`unset ${on}`,`unset ${sn}`,`unset ${Oi}`,`unset ${an}`],Wa=async()=>{let e=zt(),t=Md.join(e,Ht);if(!Va.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Di(t),n=nO(r),o=Md.resolve(e,Ai);Va.mkdirSync(e,{recursive:!0,mode:448}),st(o,`${n.join(`
358
+ ${i}`:"")},fv=()=>{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(`
359
+ `)},gv=()=>`${Mr}
360
+ ${fv()}
361
+ ${ar}`,nd=()=>["# 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(`
362
+ `),od=()=>`${Mr}
363
+ ${nd()}
364
+ ${ar}`;import hs from"node:fs/promises";import ys from"node:path";import{$ as r$}from"zx";var n$=async e=>ys.resolve(e,(await r$({cwd:e,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim()),sd=async e=>ys.join(await n$(e),"infra-kit","merge-dev-resolutions"),vs=async(e,t)=>ys.join(await sd(e),`${wg(t)}.json`),Da=async e=>{try{return JSON.parse(await hs.readFile(e,"utf8"))}catch{return null}},cr=async(e,t)=>{let r=await vs(e,t.branch);await hs.mkdir(ys.dirname(r),{recursive:!0}),await hs.writeFile(r,`${JSON.stringify(t,null,2)}
365
+ `)},Ia=async e=>{let t=await sd(e),r=await hs.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Da(ys.join(t,o))))).filter(o=>o!==null)},id=async e=>Promise.all((await Ia(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await hs.stat(t.worktreePath).then(()=>!0,()=>!1)})));var ws=async()=>{try{return(await L()).defaultEnv??null}catch{return null}};var ks=["prod"],Kn={allowed:!1,reason:"disallow"},lr=e=>ks.includes(e),o$=["dev","stage"],Hn=e=>o$.includes(e)||lr(e),Ft=(e,t=Kn)=>t.allowed?e:e.filter(r=>!lr(r)),jr=(e,t,r=Kn)=>{if(!r.allowed&&lr(e))throw r.reason==="agent-blocked"?new A({status:"refused",env:e,agentMode:N.source},2,{operation:t,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new g(void 0,{operation:t,remediation:`use \`infra-kit release deliver\` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var lt=async()=>{let e;try{e=(await L()).protectedEnvs??"disallow"}catch{return Kn}return e==="disallow"?Kn:e==="cli-only"&&te()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var bs=e=>{let{env:t,branch:r}=e;lr(t)&&d.warn([`\u26A0\uFE0F "${t}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${r}" ships ${t} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
366
+ `))};import hv from"node:fs/promises";import ad from"node:path";import s$ from"yaml";var yv=".github/workflows",Lt=async e=>{let t=await $();return vv(ad.resolve(t,yv,e))},cd=async()=>{let e=await $(),t=ad.resolve(e,yv),r;try{r=await hv.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>vv(ad.resolve(t,s))));return[...new Set(o.flat())]},vv=async e=>{let t;try{t=s$.parse(await hv.readFile(e,"utf-8"))}catch{return[]}let r=qn(t,"on")??qn(t,"true"),n=qn(qn(qn(qn(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},qn=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var ur=async()=>{let e=await cd(),t=await fe(),r=e.map(s=>({env:s,source:"gh-workflow"})),n=new Set(e),o=Object.keys(t?.envs??{}).filter(s=>!n.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...r,...o]},Fr=async()=>(await ur()).map(t=>t.env);import{$ as f$}from"zx";import Ss from"node:process";var i$="x-seraph-loginreason",a$="AUTHENTICATED_FAILED",c$=(e,t=160)=>{let r=e.split(`
367
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},kv=(e,t)=>t===a$||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",wv=(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}`,zn=class extends Error{status;kind;body;context;constructor(t){let r=kv(t.status,t.seraphLoginReason),n=c$(t.body);super(n===""?`${t.context}: ${wv(r,t.status)}`:`${t.context}: ${wv(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Rs=e=>e instanceof zn,bv=e=>e.headers.get(i$);var Yn=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new zn({status:e.status,seraphLoginReason:bv(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},Lr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,ld=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 Yn(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Xn=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 Yn(a,"Failed to get Jira project versions"),await a.json()},Bt=async(e,t)=>(await Xn(t)).find(o=>o.name===e)||null,Zn=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 Yn(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}},ud=async(e,t)=>{let{versionName:r}=e,n=await Bt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Zn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Qn=async()=>{let e=Ss.env.JIRA_BASE_URL,t=Ss.env.JIRA_TOKEN||Ss.env.JIRA_API_TOKEN,r=Ss.env.JIRA_PROJECT_ID,n=Ss.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(`
368
+ `);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},Ut=async()=>{try{return await Qn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Na=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 Yn(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},dd=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 Yn(c,"Failed to remove Jira version")};import{z as Rv}from"zod";var Sv=/^\d{4}-\d{2}-\d{2}$/,Es=e=>{if(!Sv.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},Ev=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,eo=class extends Error{constructor(t){super(Ev(t)),this.name="InvalidReleaseDateError"}},Br=e=>{let t=e.trim();if(!Es(t))throw new eo(t);return t},Ps=e=>{let t=e.trim();return t===""||Es(t)?!0:Ev(t)},pd=Rv.string().refine(Es,{message:"Expected a calendar date in yyyy-mm-dd form."}),md=Rv.string().refine(e=>e===""||Es(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var dr=e=>e.slice(1).split(".").map(Number),to=e=>[...e].sort((t,r)=>{let[n,o,s]=dr(t),[i,a,c]=dr(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var xv="next",l$=/^v?(\d+)\.(\d+)\.(\d+)$/,u$=e=>e.replace(/^.*release\//,""),fd=e=>{let t=u$(e.trim()),r=l$.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Pv=e=>`${e[0]}.${e[1]}.${e[2]}`,gd=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=fd(o);if(!s)continue;let i=Pv(s);n.has(i)||(n.add(i),r.push(s))}return to(r.map(o=>Pv(o))).map(o=>dr(`v${o}`))},Ur=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},hd=(e,t)=>{if(e.length===0)throw new Ur;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`},ro=(e,t)=>{try{return hd(e,t)}catch(r){if(r instanceof Ur)return null;throw r}},yd=e=>e.trim().toLowerCase()===xv,Ma=e=>yd(e)||fd(e)!==null?{version:e}:{name:e},d$=e=>e==="regular"||e==="hotfix",Tv=e=>"name"in e,p$=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:Br(n)}},vd=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=p$(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(!d$(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return _a({...Ma(n),type:s},{description:i,releaseDate:o})},wd=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},_a=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},m$=e=>{let t=e.name.trim();return Fi(t),_a({id:{kind:"name",name:t,raw:t},type:e.type},e)},kd=(e,t)=>{let r=[...t];return e.map(n=>{if(Tv(n))return m$(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(yd(o)){let a=hd(r,n.type);return r.push(dr(`v${a}`)),_a({id:Ee(a),type:n.type},n)}let s=fd(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),_a({id:Ee(i),type:n.type},n)})},bd=e=>e.some(t=>!Tv(t)&&yd(t.version));var g$=e=>e.split(`
369
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:re(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),h$=async()=>{let e=await f$({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return g$(e.stdout)},y$=async()=>{let e=await Ut();return e?(await Xn(e)).map(r=>r.name):[]},xs=async()=>{let[e,t]=await Promise.allSettled([h$(),y$()]);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"),gd({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import v$ from"node:fs";import w$ from"node:path";var Rd=[".claude/settings.json",".claude/settings.local.json"],k$=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],b$=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),R$=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},S$=(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(b$).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},E$=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},P$=(e,t)=>{let r=R$(e);return r===null?[]:t.filter(n=>n.mutating).filter(n=>k$.some(o=>E$(n).some(s=>S$(r,`${o} ${s}`)))).map(n=>n.groupPath.join(" "))},x$=(e,t)=>{let r;try{r=v$.readFileSync(w$.join(e,t),"utf-8")}catch(i){return i.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",file:t}}let n;try{n=JSON.parse(r)}catch{return{kind:"unreadable",file:t}}let o=n?.permissions;if(o==null)return{kind:"read",patterns:[]};let s=o.allow;return s===void 0?{kind:"read",patterns:[]}:Array.isArray(s)?{kind:"read",patterns:s.filter(i=>typeof i=="string")}:{kind:"unreadable",file:t}},Cv=(e,t)=>{let r={present:[],unreadable:[],hits:[]};for(let n of Rd){let o=x$(e,n);if(o.kind!=="absent"){if(r.present.push(n),o.kind==="unreadable"){r.unreadable.push(n);continue}for(let s of o.patterns){let i=P$(s,t);i.length>0&&r.hits.push({file:n,pattern:s,commands:i})}}}return r};var C$=e=>e.every(t=>t.status!=="fail"),$$=["brew","git","gh","doppler","aws"],A$=async e=>{let t=await ps($$,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 _n()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},O$=async()=>{let e="orca installed",t=await rr();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)"}},Fv=(e,t,r,n)=>{let o=Qe.join(T$.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!Ie.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=Ie.readFileSync(o,"utf-8"),a=i.indexOf(Mr),c=i.indexOf(ar);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+ar.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`}},D$=()=>Fv("zshrc init block",".zshrc","shell",gv()),I$=()=>Fv("zshenv session block",".zshenv","session-env",od()),N$=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await $(),r=Qe.join(t,"pnpm-workspace.yaml");if(!Ie.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=Ie.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},_$=async()=>{try{return Qt(),{config:await L(),error:null}}catch(e){return{config:null,error:e}}},M$=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)"}},j$=384,Sd=448,F$=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(", "),L$=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}}})),B$=async(e,t={})=>{let r="env tokens configured",n=t.readStore??fe,o=t.resolveToken??Sl;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 L$(await Fr(),o);return{name:r,status:"pass",message:F$(s)}},U$=()=>Cs.env[De]||void 0,V$=async(e={})=>{let t="tokens.json present",r=e.readStore??fe,n=e.storePath??tr;if((e.readEnvToken??U$)())return{name:t,status:"skip",message:`${De} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${De} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Ts=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},W$=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??tr,o=t.statPath??G$,s=t.chmodPath??Ie.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(Ts(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=Qe.dirname(i),c=Qe.dirname(a),l=Qe.dirname(c),p=[{target:l,expected:Sd,actual:Ts(l,o)},{target:c,expected:Sd,actual:Ts(c,o)},{target:a,expected:Sd,actual:Ts(a,o)},{target:i,expected:j$,actual:Ts(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${w(f.target)} is ${$v(f.actual)}, expected ${$v(f.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit setup --skip-tools\` or \`infra-kit doctor --fix\`.`};for(let f of p)s(f.target,f.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},$v=e=>`0${e.toString(8).padStart(3,"0")}`,G$=e=>{try{return Ie.statSync(e)}catch{return null}},J$=async()=>{let e="user override path";try{let t=await X(),r=Ie.existsSync(t.userProject),n=await cs(t.userProject,r),o=r?ls(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},K$=async()=>{let e="legacy user-global config",t;try{t=await X()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=Qe.join(Qe.dirname(t.userGlobal),"config.json");return Ie.existsSync(r)?Ie.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Av=/^\d+\.\d+\.\d+$/,Ov=(e,t)=>e===t||!Av.test(e)||!Av.test(t)?!1:to([`v${e}`,`v${t}`])[0]===`v${e}`,H$=async e=>{let t;try{t=await vt(e)}catch{return[]}return t.flatMap(r=>{let n=_t(wt(Qe.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},Dv=e=>to(e.map(t=>`v${t}`)).map(t=>t.slice(1)),q$=async(e,t,r)=>{let n="Guidance version",o=$r(t,Ar),s=await H$(e),a=(o===null?s:[o,...s]).filter(p=>at(p,r));if(a.length>0){let p=Dv(a).at(-1);return{name:n,status:"warn",message:`${a.length} guidance ${a.length===1?"block was":"blocks were"} generated by a newer infra-kit (newest ${p}, current ${r}) \u2014 CLI behind the block, run: pnpm add -g infra-kit@${p}`}}let c=o!==null&&Ov(o,r),l=s.filter(p=>Ov(p,r));if(!c&&l.length===0)return{name:n,status:"pass",message:`guidance blocks match infra-kit ${r}`};let u=[...c?[`the root block is from infra-kit ${o} \u2014 run: infra-kit audit --fix --root`]:[],...l.length>0?[`${l.length} package guidance ${l.length===1?"block was":"blocks were"} generated by an older infra-kit (oldest ${Dv(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},z$=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"},{name:"Guidance version",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await X()).main}catch{return e}if(!Ie.existsSync(t))return e;let r=Qe.dirname(t),n=Qe.join(r,"CLAUDE.md"),o=Ie.existsSync(n)?Ie.readFileSync(n,"utf-8"):"",s=qe(o,Te,Fe);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools"},await q$(r,o,U.version)]},Y$=async()=>{try{let e=(await X()).main;return Ie.existsSync(e)?Qe.dirname(e):null}catch{return null}},X$=e=>{let t=Og();return t===null||!at(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${En}`},Z$=e=>{let t=e.kind==="installed"?Gi(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${Z} version ${t}${X$(t)}`}},Iv=3,Nv=(e,t)=>Se(e)===Se(t),Q$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(Nv(e.projectDir,e.gitRoot))return"";let r=ln(e.gitRoot,Se(e.projectDir),Se)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return Nv(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},eA=(e,t)=>{let r="plugin installed",n=Q$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${Z} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${Z} is not installed. Run: ${Mt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-Iv,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Iv).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${Z} is installed for ${a} only, not this project. Run: ${Mt}${n}`}},tA=()=>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 rA=(e,...t)=>{try{return JSON.parse(Ie.readFileSync(Qe.join(e,...t),"utf-8"))}catch{return null}},nA=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=Gi(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=rA(r,Ye),o=n!==null&&typeof n=="object"?n[kt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},_v=e=>`Plugin ${Z} ${e===null?"(version unreadable)":e}`,oA=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:`${_v(e.version)} still carries an MCP server in its ${Ye}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${En}), then restart Claude Code`}}return{name:t,status:"pass",message:`${_v(e.version)} is skills-only \u2014 no ${Ye}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},sA=(e,t)=>{let r=Er(e===null?{}:{projectPath:e}),n=Io();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${me} is known to Claude Code`:`Marketplace ${me} is not registered. Run: claude plugin marketplace add ${er}`},eA(r,t),Z$(r),oA(nA(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},iA=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${w(Dn())}, or run: infra-kit setup`}},aA=({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(", ")},cA=e=>{let t="Agent mode",r=ji(e),n=aA(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})`}},Mv=4,lA=e=>{let t=e.slice(0,Mv).join(", "),r=e.length-Mv;return r>0?`${t} +${r} more`:t},uA=(e,t)=>{let r="Agent allowlist",{present:n,unreadable:o,hits:s}=Cv(e,t);if(s.length>0){let i=s.map(a=>`${a.file} allows "${a.pattern}", which reaches ${a.commands.length} mutating infra-kit command${a.commands.length===1?"":"s"} (${lA(a.commands)})`);return{name:r,status:"warn",message:`${i.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 o.length>0?{name:r,status:"warn",message:`Could not read permissions.allow from ${o.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:n.length===0?{name:r,status:"pass",message:`no ${Rd.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:r,status:"pass",message:`no permissions.allow pattern in ${n.join(" or ")} reaches a mutating infra-kit command`}},dA=(e,t)=>e===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:t===void 0?{name:"Agent allowlist",status:"skip",message:"no command catalog supplied"}:uA(e,t),pA=(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`},mA=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 id(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${pA(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`}},Lv=e=>cl(["trust"],{bin:e}),fA=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),jv="ERR_TLS_CERT_ALTNAME_INVALID",Bv=()=>`portless serving TLS on :${Zt}`,gA=async(e,t,r)=>{let n=Bv();return await e(Zt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Zt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Zt}. Install it once (needs root): \`${Dt(t,r)}\`.`}},hA=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(Zt,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(jv)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${jv} 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=>fA.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${Lv(n)}\`, or reinstall: \`${Dt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},yA=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Lv(r)}\` (no sudo needed).`}},vA=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 \`${cl(["alias","--remove","<name>"],{bin:r})}\`.`}},wA=()=>[An,jt,Bv(),"portless CA chain valid","portless CA trusted","portless routes"],kA=async(e={})=>{let t=e.resolveBin??Wf,r=e.isProxyServing??qf,n=e.handshake??Zf,o=e.caTrusted??Xf,s=e.routes??$o,i=e.isListening??Co,a=(e.caPath??Yf)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...wA().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}=Fu(e,c),m=s(),f=await gA(r,c,u),h=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await hA(n,m,a,c,u);return[l,p,(await Lu(u)).row,f,h,yA(o(),a,c),await vA(m,i,c)]},bA=async(e={})=>{let t="portless routes",r=e.routes??$o,n=e.isListening??Co,o=e.devSessionRunning??hy,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}=gy(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??Qf().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ja=async(e={})=>{let t=await _$(),r=A$(e.probeDeps??us()),n=async(m,f)=>{let[h,b]=await Promise.all([f,r]),C=b.get(m);return C===void 0?h:{...h,detail:C}},o=await Promise.all([n("brew",Vt("brew installed",Xe("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",Vt("git installed",Xe("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",Vt("gh installed",Xe("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",Xe("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",Xe("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"),O$(),Promise.resolve(D$()),Promise.resolve(I$()),N$(),Promise.resolve(M$(t)),V$(),B$(t),W$(e.fix??!1),J$(),K$()]),s=await kA(e.portlessDeps);if(e.fix){let m=await bA(),f=s.findIndex(h=>h.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await Y$(),a=await $n(),c={projectDir:Cs.env.CLAUDE_PROJECT_DIR||null,cwd:Cs.cwd(),gitRoot:a},l=[await tA(),...sA(i,c),as(),cA({env:Cs.env,stdinIsTTY:Cs.stdin.isTTY===!0,flag:N.source==="flag"}),dA(a,e.catalog)],u=[...o,await mA(a),...s,...await z$(),...l,iA(In(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Mu.has(m.name),detail:m.detail})),allPassed:C$(u),cliVersion:U.version};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}},Ed=T({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:Le.array(Le.object({name:Le.string().describe("Name of the check"),status:Le.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:Le.string().describe("Details about the check result"),fixable:Le.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Le.object({manager:Le.string().describe("Which package manager owns this install, read from its resolved path"),version:Le.string().nullable().describe("The version the tool reported, or null"),present:Le.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Le.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:Le.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Le.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ja()});import{E2E_MODE_ENV as zA}from"@slip-stream-kit/config/internal";import Dd from"node:fs";import YA from"node:os";import As from"node:path";import Ba from"node:process";import{z as E}from"zod";var Pt=(e,t,r)=>new A({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as RA,loadDev as SA,readAppAliasName as EA,readCloudOrigin as PA,readLocalContext as Vv}from"@slip-stream-kit/config/internal";import Uv from"node:fs";import Vr from"node:path";import Fa from"node:process";import{z as Pd}from"zod";var xA=async e=>{let t=Vr.join(e,"apps"),r=Uv.existsSync(t)?Uv.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=Vr.join(t,o,"tests"),a=(await yt(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},TA=(e,t)=>{let[r,n]=Vr.relative(e,t).split(Vr.sep);return r==="apps"&&n?n:void 0},CA=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(TA(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new g(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new A({status:"argument_required",argument:a,choices:Pd.toJSONSchema(Pd.object({app:Pd.enum(i)})),agentMode:N.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},$A=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}})),AA=e=>ns(e).apps.find(t=>t.env!=="")?.env??null,xd=async(e,t={})=>{let r=t.cwd??Fa.cwd(),n=t.projectRoot??await $(),o=(t.env??Fa.env)[zt]||null,s=t.healthProbe??Ol,i=CA(await xA(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=Vr.join(n,"apps",c,l),p=(await Tr(u)).name,m=(await yt(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${Vr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=qg(u),h=EA(p,u),b=`${h}.localhost`,C=`https://${b}`,k=0;if(l==="ui")k=(t.listRoutes??$o)().find(S=>S.name===b||S.name===h)?.port??0;else{let S=Vv(u).info.get(p);k=S?.port??0,C=S?.origin??C}let F=k>0&&await s({tag:a,port:k,kind:l})==="ok",v=F?AA(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:v,localUrl:C,served:F}},Wv=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}},Td=async(e,t={})=>{let r=t.healthProbe??Ol,n=Vv(e.targetDir),o=e.kind==="ui"?await SA(e.targetDir):void 0,s=o?.proxy?RA({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:PA(e.deployedUrlEnv??void 0,t.env??Fa.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Wv(e),mode:"local",baseUrl:e.localUrl,routes:await $A(s,i,r)}},Cd=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw Pt("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${Vr.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??Fa.env)[n];if(!r||!s){let i=s?zt:n;throw Pt("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 ${zt}, and ${i} is not set`})}return{...Wv(e),mode:"cloud",baseUrl:s,routes:[]}};import OA from"node:fs";import DA from"node:path";import{stripVTControlCharacters as IA}from"node:util";import{z as M}from"zod";var Gv=2e3,Jv="--reporter=line,json",Kv=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Hv=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),$d=M.object({message:M.string().optional()}),qv=M.object({type:M.string()}),NA=M.object({status:M.string(),retry:M.number(),error:$d.optional(),errors:M.array($d).optional(),annotations:M.array(qv).optional(),attachments:M.array(M.object({name:M.string(),path:M.string().optional()})).optional()}),_A=M.object({projectName:M.string(),status:M.string(),expectedStatus:M.string().optional(),annotations:M.array(qv).optional(),results:M.array(NA)}),MA=M.object({title:M.string(),file:M.string(),line:M.number().optional(),tests:M.array(_A)}),zv=M.lazy(()=>M.object({title:M.string(),specs:M.array(MA).optional(),suites:M.array(zv).optional()})),jA=M.object({config:M.object({rootDir:M.string().optional()}).optional(),suites:M.array(zv),errors:M.array($d).optional(),stats:M.object({expected:M.number(),unexpected:M.number(),flaky:M.number(),skipped:M.number()})}),Yv=e=>{let t=IA(e);return t.length>Gv?`${t.slice(0,Gv)}\u2026`:t},FA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Yv(t)},LA=e=>e.status==="unexpected"||e.status==="flaky",BA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},UA=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),VA=(e,t)=>{let r=e.filter(LA),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?FA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},WA=e=>{let t=jA.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=new Map,c=0,l=(p,m)=>{let f=new Set(m.flatMap(C=>[...UA(C)])),h=m.some(C=>C.expectedStatus==="failed");if(!h&&!f.has("fixme")&&!f.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};h&&(b.fail+=1),f.has("fixme")?b.fixme+=1:f.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let f of p.specs??[]){let h=r?.rootDir?DA.resolve(r.rootDir,f.file):f.file,b=[...m,f.title].join(" \u203A ");l(h,f.tests);for(let[C,k]of BA(f.tests)){let F=VA(k,{title:b,file:h,line:f.line??null,project:C});F&&(F.runs>1&&F.failedRuns<F.runs&&(c+=1),i.push(F))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[Yv(p.message)])}},Xv=e=>{try{return WA(JSON.parse(OA.readFileSync(e,"utf8")))}catch{return null}};import $s from"node:fs";import Qv from"node:path";import La from"node:process";var GA=e=>Qv.join(e,"node_modules",".cache","infra-kit-e2e.lock"),JA=e=>{try{return La.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Zv=(e,t)=>{try{return $s.writeFileSync(e,`${La.pid}
370
+ ${JSON.stringify({startedAt:Date.now(),command:t})}`,{flag:"wx"}),!0}catch(r){if(r.code==="EEXIST")return!1;throw r}},KA=e=>{try{let t=JSON.parse(e??"");return{...typeof t?.startedAt=="number"&&{startedAt:t.startedAt},...typeof t?.command=="string"&&{command:t.command}}}catch{return{}}},Ad=e=>{try{let[t,r]=$s.readFileSync(e,"utf8").split(`
371
+ `),n=Number.parseInt(t,10);return Number.isInteger(n)&&n>0?{pid:n,...KA(r)}:null}catch{return null}},ew=(e,t)=>{let r=GA(e);if($s.mkdirSync(Qv.dirname(r),{recursive:!0}),!Zv(r,t)){let n=Ad(r);if(n!==null&&n.pid!==La.pid&&JA(n.pid))return{holder:n};if($s.rmSync(r,{force:!0}),!Zv(r,t))return{holder:Ad(r)??{pid:0}}}return{release:()=>{Ad(r)?.pid===La.pid&&$s.rmSync(r,{force:!0})}}};import{spawn as HA}from"node:child_process";import qA from"node:os";import Od from"node:process";var tw=(e,t,r)=>new Promise((n,o)=>{let s=HA(e,t,r),i=Od.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Od.off(l,a)};for(let l of i)Od.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+qA.constants.signals[u]:1))})});var XA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],ZA=e=>XA.some(t=>{try{return Dd.readFileSync(As.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),Id=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,QA=(e,t)=>{let r=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl}`];e.mode==="cloud"?r.push(` deployed app at env "${e.env}"`):t?r.push(` dev server for ${e.target} on release "${e.release}", already running`):r.push(` nothing serves ${e.target} yet; the Playwright config starts it and stops it after the run`);for(let n of e.routes){let o="";n.live!==null&&(o=n.live?" \u2014 live":" \u2014 NOT responding"),r.push(` ${n.path.padEnd(24)} ${n.source.padEnd(5)} ${n.target??"(unresolved)"}${o}`)}return r.join(`
372
+ `)},eO=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 Pt("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(", ")}`})},tO=async(e,t)=>{if(e.env===null||!lr(e.env))return;let r=await(t.protectedEnvAccess??lt)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?Pt("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`}):Pt("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`})},rO=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw Pt("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"}"`})},nO=async(e,t)=>{if(e.served){rO(e);let p=await Td(e,t);return eO(p),p}if(!ZA(e.testsDir))throw Pt("no_dev_server",{devCommand:Id(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${Id(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:[]}},oO=(e,t,r)=>tw("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Ba.env,...r,[zA]:e.mode},stdio:["inherit",Xt.enabled||H()?2:"inherit","inherit"]}),sO=(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:As.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=As.join(e.testsDir,"test-results",`ik-e2e-${n}-${Ba.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},iO=e=>{if(e.mode==="cloud")return()=>{};let t=ew(e.testsDir,`ik e2e --app ${e.app}`);if("holder"in t){let{pid:r,startedAt:n,command:o}=t.holder,s=n===void 0?void 0:`${Math.floor((Date.now()-n)/1e3)}s`,i=[`pid ${r}`,s,o].filter(Boolean).join(", ");throw Pt("run_in_progress",{pid:r,startedAt:n,command:o},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${r}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (${i}) is using its dev server`})}return t.release},Ua=async(e,t={})=>{let r=await xd(e.app,t),n=e.cloud?Cd(r,t):await nO(r,t);d.info(QA(n,r.served)),n.mode==="cloud"&&await tO(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?Id(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return _d({...o,ran:!1,exitCode:null,...Nd});n.mode==="cloud"&&await q(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=iO(n);try{return await aO(o,t.runPlaywright??oO)}finally{s()}},aO=async(e,t)=>{if(!H()||Hv(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(Ba.exitCode=i),_d({...e,ran:!0,exitCode:i,...Nd,report:H()?"caller-reporter":"off"})}let{args:r,outputDir:n}=sO(e,e.playwrightArgs),o=Dd.mkdtempSync(As.join(YA.tmpdir(),"ik-e2e-report-")),s=As.join(o,"report.json");try{let i=await t(e,[Jv,...r],Kv(s));i!==0&&(Ba.exitCode=i);let a=Xv(s);return _d({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...Nd,report:"unavailable"},outputDir:n})}finally{Dd.rmSync(o,{recursive:!0,force:!0})}},Nd={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},_d=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),cO={app:E.string(),testsDir:E.string(),target:E.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:E.string(),mode:E.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:E.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:E.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:E.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:E.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:E.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:E.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:E.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:E.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:E.array(E.object({path:E.string(),packageName:E.string(),source:E.enum(["local","cloud"]),target:E.string().nullable(),live:E.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:E.array(E.string()),ran:E.boolean().describe("False for --dry-run."),exitCode:E.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:E.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:E.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:E.object({expected:E.number(),unexpected:E.number(),flaky:E.number(),skipped:E.number(),repeatFlaky:E.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:E.array(E.object({title:E.string().describe("Describe path and test title, joined with \u203A."),file:E.string(),line:E.number().nullable(),project:E.string(),status:E.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:E.number().describe("The retry index of the failed attempt reported here."),runs:E.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:E.number().describe("How many of those runs failed."),error:E.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:E.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:E.array(E.object({file:E.string(),fail:E.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:E.number().describe("test.fixme \u2014 skipped as unfinished."),skip:E.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:E.array(E.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},Md=T({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:E.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:E.boolean().optional(),yes:E.boolean().optional(),cloud:E.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:E.array(E.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:cO,handler:e=>Ua(e)});import Va from"node:fs";import jd from"node:path";import{z as Os}from"zod";var lO=e=>[...e.map(t=>`unset ${t}`),`unset ${zt}`,`unset ${on}`,`unset ${sn}`,`unset ${Oi}`,`unset ${an}`],Wa=async()=>{let e=Yt(),t=jd.join(e,qt);if(!Va.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Di(t),n=lO(r),o=jd.resolve(e,Ai);Va.mkdirSync(e,{recursive:!0,mode:448}),st(o,`${n.join(`
373
373
  `)}
374
- `,384),Va.rmSync(t,{force:!0}),Va.rmSync(Md.join(e,nn),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}},jd=T({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Os.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Os.string().describe("Path to the file that must be sourced to apply"),variableCount:Os.number().describe("Number of variables cleared"),unsetStatements:Os.array(Os.string()).describe("Unset statements generated")},handler:()=>Wa()});import oO from"node:process";import{z as Vt}from"zod";var Xv=["Environment","Source","Token"],sO=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=Xv.map((s,i)=>Math.max(s.length,...t.map(a=>(a[i]??"").length))),n=s=>s.map((i,a)=>i.padEnd(r[a]??0)).join(" | ").trimEnd(),o=r.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",n(Xv),o,...t.map(n)]},Ga=async()=>{let e=await He(),t=await ur(),r=await fe(),n=oO.env[De],o=await ws(),s=Ji(t,r?.envs??{},n);if(d.info(`Doppler project: ${e}`),d.info(`Default env: ${o??"none \u2014 set one with `infra-kit config-set defaultEnv <env>`"}
375
- `),s.length===0)return d.info("No environments found."),d.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),d.info(" or add a token for one manually."),Zv({project:e,defaultEnv:o,envs:s});for(let i of sO(s))d.info(i);return Zv({project:e,defaultEnv:o,envs:s})},Zv=({project:e,defaultEnv:t,envs:r})=>{let n={project:e,defaultEnv:t,configs:r.map(o=>o.env),tokens:r};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},Fd=T({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:Vt.string().describe("Detected Doppler project name"),defaultEnv:Vt.string().nullable().describe('The configured "defaultEnv" \u2014 what env-load takes when no config is named; null when unset'),configs:Vt.array(Vt.string()).describe("Every environment name known to this project"),tokens:Vt.array(Vt.object({env:Vt.string().describe("Environment / Doppler config name"),source:Vt.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:Vt.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:Ga});import uO from"@inquirer/select";import{readRepoIdentity as dO}from"@slip-stream-kit/config/internal";import pO from"node:fs";import Ud from"node:path";import Vd from"node:process";import{z as Wr}from"zod";import tw from"node:process";import{z as Qv}from"zod";var ew=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iO=async e=>{try{return await e}catch{return[]}},aO=async e=>{let t=await fe().catch(()=>null);return Ji(e,t?.envs??{},tw.env[De]).filter(r=>!r.hasToken).map(r=>r.env)},Ld=()=>({get message(){return`Choose the environment to load into terminal session ${tw.env[ft]??`UNKNOWN \u2014 ${ft} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>ew(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await iO(ur());if(e.length===0)return d.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await aO(e);return Qv.object({config:Qv.enum(t).describe(`The environment to load. ${r.length===0?"A service token is stored for every one of them.":`NO stored token for: ${r.join(", ")} \u2014 choosing one of those fails until you run \`infra-kit env-token-set <env>\`.`} The list is what env-list knows: workflow-declared environments first, then token-only ones.`)})},toArgs:(e,t)=>{let{config:r}=e;return typeof r!="string"||r.length===0?null:{...ew(t)?t:{},config:r}}});import{z as cO}from"zod";var lO=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return d.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},et=async e=>{if(!H()||!e.provider.isFormable(e.params))return;let t=await lO(e),r=typeof e.params=="object"&&e.params!==null?e.params:{},n=(t===null?[]:Object.keys(t.shape)).filter(i=>r[i]===void 0||r[i]===""),o=typeof e.argument=="string"?e.argument:e.argument(n),s=t===null?void 0:cO.toJSONSchema(t);throw new A({status:"argument_required",argument:o,...s===void 0?{}:{choices:s},agentMode:N.source},2,{operation:e.operation,remediation:s===void 0?`pass --${o} on the re-run \u2014 nothing could be listed to choose from`:`ask the human to pick from "choices", then pass --${o} on the re-run`,stderrExcerpt:`--${o} was not given and there is no human to ask`})};var rw=new Set(["DOPPLER_TOKEN",De]),nw=!1,mO=e=>{e.length===0||nw||(nw=!0,d.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},ow=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!rw.has(i));return mO(e.filter(([i])=>rw.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${ro(a)}`),`${qt}=${ro(t)}`,`${on}=${ro(t)}`,`${sn}=${ro(r)}`,`${Oi}=${ro(n)}`,`${an}=${ro(o)}`,"set +a"]},fO=async()=>{try{return await $()}catch{return""}},gO=(e,t=Vd.cwd())=>{if(e==="")return[Ud.resolve(t)];let r=dO(e).root??e;return[...new Set([r,`${r}${le}`,e])]},sw=async({config:e})=>{let t=await He(),r=await fO(),n=await Sl(t,e),o=new Date().toISOString(),i=`${ow({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
374
+ `,384),Va.rmSync(t,{force:!0}),Va.rmSync(jd.join(e,nn),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}},Fd=T({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Os.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Os.string().describe("Path to the file that must be sourced to apply"),variableCount:Os.number().describe("Number of variables cleared"),unsetStatements:Os.array(Os.string()).describe("Unset statements generated")},handler:()=>Wa()});import uO from"node:process";import{z as Wt}from"zod";var rw=["Environment","Source","Token"],dO=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=rw.map((s,i)=>Math.max(s.length,...t.map(a=>(a[i]??"").length))),n=s=>s.map((i,a)=>i.padEnd(r[a]??0)).join(" | ").trimEnd(),o=r.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",n(rw),o,...t.map(n)]},Ga=async()=>{let e=await He(),t=await ur(),r=await fe(),n=uO.env[De],o=await ws(),s=Ji(t,r?.envs??{},n);if(d.info(`Doppler project: ${e}`),d.info(`Default env: ${o??"none \u2014 set one with `infra-kit config-set defaultEnv <env>`"}
375
+ `),s.length===0)return d.info("No environments found."),d.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),d.info(" or add a token for one manually."),nw({project:e,defaultEnv:o,envs:s});for(let i of dO(s))d.info(i);return nw({project:e,defaultEnv:o,envs:s})},nw=({project:e,defaultEnv:t,envs:r})=>{let n={project:e,defaultEnv:t,configs:r.map(o=>o.env),tokens:r};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},Ld=T({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:Wt.string().describe("Detected Doppler project name"),defaultEnv:Wt.string().nullable().describe('The configured "defaultEnv" \u2014 what env-load takes when no config is named; null when unset'),configs:Wt.array(Wt.string()).describe("Every environment name known to this project"),tokens:Wt.array(Wt.object({env:Wt.string().describe("Environment / Doppler config name"),source:Wt.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:Wt.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:Ga});import hO from"@inquirer/select";import{readRepoIdentity as yO}from"@slip-stream-kit/config/internal";import vO from"node:fs";import Vd from"node:path";import Wd from"node:process";import{z as Wr}from"zod";import iw from"node:process";import{z as ow}from"zod";var sw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pO=async e=>{try{return await e}catch{return[]}},mO=async e=>{let t=await fe().catch(()=>null);return Ji(e,t?.envs??{},iw.env[De]).filter(r=>!r.hasToken).map(r=>r.env)},Bd=()=>({get message(){return`Choose the environment to load into terminal session ${iw.env[ft]??`UNKNOWN \u2014 ${ft} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>sw(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await pO(ur());if(e.length===0)return d.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await mO(e);return ow.object({config:ow.enum(t).describe(`The environment to load. ${r.length===0?"A service token is stored for every one of them.":`NO stored token for: ${r.join(", ")} \u2014 choosing one of those fails until you run \`infra-kit env-token-set <env>\`.`} The list is what env-list knows: workflow-declared environments first, then token-only ones.`)})},toArgs:(e,t)=>{let{config:r}=e;return typeof r!="string"||r.length===0?null:{...sw(t)?t:{},config:r}}});import{z as fO}from"zod";var gO=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return d.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},et=async e=>{if(!H()||!e.provider.isFormable(e.params))return;let t=await gO(e),r=typeof e.params=="object"&&e.params!==null?e.params:{},n=(t===null?[]:Object.keys(t.shape)).filter(i=>r[i]===void 0||r[i]===""),o=typeof e.argument=="string"?e.argument:e.argument(n),s=t===null?void 0:fO.toJSONSchema(t);throw new A({status:"argument_required",argument:o,...s===void 0?{}:{choices:s},agentMode:N.source},2,{operation:e.operation,remediation:s===void 0?`pass --${o} on the re-run \u2014 nothing could be listed to choose from`:`ask the human to pick from "choices", then pass --${o} on the re-run`,stderrExcerpt:`--${o} was not given and there is no human to ask`})};var aw=new Set(["DOPPLER_TOKEN",De]),cw=!1,wO=e=>{e.length===0||cw||(cw=!0,d.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},lw=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!aw.has(i));return wO(e.filter(([i])=>aw.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${no(a)}`),`${zt}=${no(t)}`,`${on}=${no(t)}`,`${sn}=${no(r)}`,`${Oi}=${no(n)}`,`${an}=${no(o)}`,"set +a"]},kO=async()=>{try{return await $()}catch{return""}},bO=(e,t=Wd.cwd())=>{if(e==="")return[Vd.resolve(t)];let r=yO(e).root??e;return[...new Set([r,`${r}${le}`,e])]},uw=async({config:e})=>{let t=await He(),r=await kO(),n=await El(t,e),o=new Date().toISOString(),i=`${lw({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
376
376
  `)}
377
- `,a=zt(),c=Ud.resolve(a,Ht);pO.mkdirSync(a,{recursive:!0,mode:448});let l=gO(r);return st(Ud.resolve(a,nn),`${l.join(`
377
+ `,a=Yt(),c=Vd.resolve(a,qt);vO.mkdirSync(a,{recursive:!0,mode:448});let l=bO(r);return st(Vd.resolve(a,nn),`${l.join(`
378
378
  `)}
379
- `,384),st(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},iw=Ld(),Ja=async e=>{let{config:t}=e,r=t?null:await ws();if(!t&&r&&H())return Bd(r,"default");if(await et({provider:iw,params:e,operation:"env-load",argument:"config"}),t)return Bd(t,"argument");if(te())throw new A({status:"argument_required",argument:"config",agentMode:N.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let n=await Fr();y.setInteractive();let o=await _(s=>uO({message:"Select environment config",choices:hO(n,r),...r?{default:r}:{}},s),{output:Vd.stderr,whenHeadless:"refuse"});return Bd(o,"picker")},hO=(e,t)=>(t&&!e.includes(t)?[t,...e]:e).map(n=>({name:n===t?`${n} (default)`:n,value:n})),Bd=async(e,t)=>{y.addOption("--config",e);let r=await sw({config:e});y.print();let n={filePath:r.filePath,variableCount:r.variableCount,project:r.project,config:r.config,configSource:t,sessionId:Vd.env[ft]??null};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},ro=e=>`'${e.replaceAll("'","'\\''")}'`,Wd=T({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess. When the project config sets "defaultEnv", omitting "config" headless loads that environment instead of refusing, and "configSource" reports "default".',inputSchema:{config:Wr.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to load the configured "defaultEnv", or, with none set, to have the human choose from a form.')},formProvider:iw,outputSchema:{filePath:Wr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Wr.number().describe("Number of variables loaded"),project:Wr.string().describe("Doppler project name"),config:Wr.string().describe("Doppler config name"),configSource:Wr.enum(["argument","default","picker"]).describe('How the config was chosen: passed as "config", the configured "defaultEnv", or the terminal picker'),sessionId:Wr.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:Ja});import yO from"node:path";import Ds from"node:process";import{z as no}from"zod";var Ka=async()=>{d.info("Environment session status:");let e=zt(),t=Ds.env[ft],r=yO.join(e,Ht),n=0,o=0,s=Ds.env[on]??null,i=Ds.env[sn]??null,a=Ds.env[an]??null;if(s){let l=Di(r);l.length>0&&(o=l.length,n=l.filter(p=>p in Ds.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})
379
+ `,384),st(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},dw=Bd(),Ja=async e=>{let{config:t}=e,r=t?null:await ws();if(!t&&r&&H())return Ud(r,"default");if(await et({provider:dw,params:e,operation:"env-load",argument:"config"}),t)return Ud(t,"argument");if(te())throw new A({status:"argument_required",argument:"config",agentMode:N.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let n=await Fr();y.setInteractive();let o=await _(s=>hO({message:"Select environment config",choices:RO(n,r),...r?{default:r}:{}},s),{output:Wd.stderr,whenHeadless:"refuse"});return Ud(o,"picker")},RO=(e,t)=>(t&&!e.includes(t)?[t,...e]:e).map(n=>({name:n===t?`${n} (default)`:n,value:n})),Ud=async(e,t)=>{y.addOption("--config",e);let r=await uw({config:e});y.print();let n={filePath:r.filePath,variableCount:r.variableCount,project:r.project,config:r.config,configSource:t,sessionId:Wd.env[ft]??null};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},no=e=>`'${e.replaceAll("'","'\\''")}'`,Gd=T({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess. When the project config sets "defaultEnv", omitting "config" headless loads that environment instead of refusing, and "configSource" reports "default".',inputSchema:{config:Wr.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to load the configured "defaultEnv", or, with none set, to have the human choose from a form.')},formProvider:dw,outputSchema:{filePath:Wr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Wr.number().describe("Number of variables loaded"),project:Wr.string().describe("Doppler project name"),config:Wr.string().describe("Doppler config name"),configSource:Wr.enum(["argument","default","picker"]).describe('How the config was chosen: passed as "config", the configured "defaultEnv", or the terminal picker'),sessionId:Wr.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:Ja});import SO from"node:path";import Ds from"node:process";import{z as oo}from"zod";var Ka=async()=>{d.info("Environment session status:");let e=Yt(),t=Ds.env[ft],r=SO.join(e,qt),n=0,o=0,s=Ds.env[on]??null,i=Ds.env[sn]??null,a=Ds.env[an]??null;if(s){let l=Di(r);l.length>0&&(o=l.length,n=l.filter(p=>p in Ds.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})
380
380
  `),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
381
- `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:R(JSON.stringify(c,null,2)),structuredContent:c}},Gd=T({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:no.string().describe("Current terminal session ID"),sessionLoadedCount:no.number().describe("Number of cached vars active in the current session"),sessionTotalCount:no.number().describe("Total number of cached var names"),sessionConfig:no.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:no.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:no.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Ka});import vO from"node:process";import{z as pr}from"zod";var aw="****",Ne=e=>typeof e!="string"||e.length<8?aw:`${aw}${e.slice(-4)}`;var cw=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${De}`:"store",redactedToken:Ne(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),wO=["ENV","SOURCE","TOKEN","PRESENT"],lw=(e,t)=>{let r=[...wO,...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())},Ha=async({check:e}={})=>{let t=await Fr(),r=await fe(),n=vO.env[De],o=cw(t,r?.envs??{},n);if(e){let a=await He();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await kl({childEnv:No(l),project:a,config:c.env});c.status=u.outcome}}for(let a of lw(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
382
- No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}},Jd=T({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:pr.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:pr.array(pr.object({env:pr.string().describe("Environment / Doppler config name"),source:pr.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:pr.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:pr.boolean().describe("Whether a token is configured for this environment"),status:pr.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Ha});import{z as x}from"zod";import{$ as kD}from"zx";import{$ as R8}from"zx";import{$ as Jr}from"zx";import bO from"node:fs/promises";import RO from"node:path";import{$ as SO}from"zx";var EO="infra-kit.json",Kd="dev",ke="main",uw=e=>e==="dev"?"dev":ke,ne=async()=>{let{main:e}=await X();try{await bO.access(e)}catch{return Kd}let t=(await L()).gitFlow??Kd;return t==="dev"&&await PO(e),t},PO=async e=>{let t=`origin/${ke}:${EO}`,r=await SO({quiet:!0,nothrow:!0})`git -C ${RO.dirname(e)} show ${t}`;if(r.exitCode!==0)return;let n;try{n=JSON.parse(r.stdout)}catch{return}if(n?.gitFlow==="main")throw new g(void 0,{operation:"resolve the git flow",remediation:`origin/${ke} sets "gitFlow": "main" but this checkout's infra-kit.json does not \u2014 switch to ${ke} and pull, or rebase this branch onto it, then re-run`})},Gr=async()=>uw(await ne());import{$ as dw}from"zx";var Hd=async e=>{let{operation:t}=e;try{await dw({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new g(r,{operation:t,remediation:"run this from inside a git repository"})}try{await dw({quiet:!0})`git remote get-url origin`}catch(r){throw new g(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},xO=4,oo=async e=>{let{operation:t}=e,r=await dg();if(r.length===0)return;d.error(`working tree has uncommitted changes:
381
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:R(JSON.stringify(c,null,2)),structuredContent:c}},Jd=T({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:oo.string().describe("Current terminal session ID"),sessionLoadedCount:oo.number().describe("Number of cached vars active in the current session"),sessionTotalCount:oo.number().describe("Total number of cached var names"),sessionConfig:oo.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:oo.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:oo.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Ka});import EO from"node:process";import{z as pr}from"zod";var pw="****",Ne=e=>typeof e!="string"||e.length<8?pw:`${pw}${e.slice(-4)}`;var mw=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${De}`:"store",redactedToken:Ne(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),PO=["ENV","SOURCE","TOKEN","PRESENT"],fw=(e,t)=>{let r=[...PO,...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())},Ha=async({check:e}={})=>{let t=await Fr(),r=await fe(),n=EO.env[De],o=mw(t,r?.envs??{},n);if(e){let a=await He();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await bl({childEnv:No(l),project:a,config:c.env});c.status=u.outcome}}for(let a of fw(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
382
+ No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}},Kd=T({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:pr.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:pr.array(pr.object({env:pr.string().describe("Environment / Doppler config name"),source:pr.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:pr.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:pr.boolean().describe("Whether a token is configured for this environment"),status:pr.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Ha});import{z as x}from"zod";import{$ as xD}from"zx";import{$ as $8}from"zx";import{$ as Jr}from"zx";import TO from"node:fs/promises";import CO from"node:path";import{$ as $O}from"zx";var AO="infra-kit.json",Hd="dev",ke="main",gw=e=>e==="dev"?"dev":ke,ne=async()=>{let{main:e}=await X();try{await TO.access(e)}catch{return Hd}let t=(await L()).gitFlow??Hd;return t==="dev"&&await OO(e),t},OO=async e=>{let t=`origin/${ke}:${AO}`,r=await $O({quiet:!0,nothrow:!0})`git -C ${CO.dirname(e)} show ${t}`;if(r.exitCode!==0)return;let n;try{n=JSON.parse(r.stdout)}catch{return}if(n?.gitFlow==="main")throw new g(void 0,{operation:"resolve the git flow",remediation:`origin/${ke} sets "gitFlow": "main" but this checkout's infra-kit.json does not \u2014 switch to ${ke} and pull, or rebase this branch onto it, then re-run`})},Gr=async()=>gw(await ne());import{$ as hw}from"zx";var qd=async e=>{let{operation:t}=e;try{await hw({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new g(r,{operation:t,remediation:"run this from inside a git repository"})}try{await hw({quiet:!0})`git remote get-url origin`}catch(r){throw new g(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},DO=4,so=async e=>{let{operation:t}=e,r=await gg();if(r.length===0)return;d.error(`working tree has uncommitted changes:
383
383
  ${r.join(`
384
- `)}`);let n=r.slice(0,xO),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},Is=async e=>{let{operation:t,base:r}=e;if(await dn()===r)return;let n=(await gt(await $())).find(o=>o.branch===r);if(n)throw new g(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},Be=async e=>{let{operation:t}=e;if(await mg())throw new g(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await oo({operation:t})};import{$ as pw}from"zx";var qd={dev:{regular:"dev",hotfix:ke},main:{regular:ke}},so=e=>Object.keys(qd[e]),Pt=(e,t)=>{let r=qd[t][e];if(r===void 0)throw new g(void 0,{operation:`use a ${e} release`,remediation:`this repo sets "gitFlow": "${t}" in infra-kit.json, which has only ${so(t).join(" and ")} releases \u2014 create it as a regular release`});return r},Ns=(e,t)=>{let r=Object.entries(qd[t]).find(([,n])=>n===e);return r?r[0]:null},_s=(e,t)=>(t??"").trim()!==""?`${e}
384
+ `)}`);let n=r.slice(0,DO),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},Is=async e=>{let{operation:t,base:r}=e;if(await dn()===r)return;let n=(await gt(await $())).find(o=>o.branch===r);if(n)throw new g(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},Be=async e=>{let{operation:t}=e;if(await yg())throw new g(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await so({operation:t})};import{$ as yw}from"zx";var zd={dev:{regular:"dev",hotfix:ke},main:{regular:ke}},io=e=>Object.keys(zd[e]),xt=(e,t)=>{let r=zd[t][e];if(r===void 0)throw new g(void 0,{operation:`use a ${e} release`,remediation:`this repo sets "gitFlow": "${t}" in infra-kit.json, which has only ${io(t).join(" and ")} releases \u2014 create it as a regular release`});return r},Ns=(e,t)=>{let r=Object.entries(zd[t]).find(([,n])=>n===e);return r?r[0]:null},_s=(e,t)=>(t??"").trim()!==""?`${e}
385
385
 
386
386
  ${t}`:`${e}
387
- `,zd=async(e="regular")=>{let t=Pt(e,await ne()),r=pw({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 pw({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new g(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},TO=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await Lt(t,r);if(!s)return(await cd({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new g(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await Xn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Yd=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=pe(t),c=await TO({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=Lr(r,c),u=await Ya({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:ae(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},qa=async()=>{let e=new Map,t=await Bt();if(!t)return e;try{let r=await Yn(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},ye=async()=>{let e=await qa();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Ms=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Xd=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",za=e=>e.flatMap(t=>{let r=re(t);return r?[{branch:t,id:r,label:ae(r)}]:[]}),Wt=e=>{try{return Ae(Ee(e))}catch(t){throw new g(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},js=e=>{let t=re(e);return t?ae(t):e},Gt=e=>e.flatMap(t=>{let r=re(t);return r?[ae(r)]:[]}),CO=(e,t)=>t?t.get(e)||"regular":void 0,ve=e=>{let{branches:t,descriptions:r,types:n}=e;return za(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(pe(s)),type:CO(o,n)}))};var $O=e=>e.map(t=>({pr:t,id:re(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>ug(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),io=200,Zd=(e,t)=>{e.length<io||d.warn({source:t,limit:io},`\u26A0\uFE0F ${t} returned ${io} PRs \u2014 the page is full, so older release PRs may be missing`)},AO=async e=>{if(e==="main"){let l=await Jr`gh pr list --limit ${io} --base ${ke} --json number,title,headRefName,state,baseRefName,createdAt`,u=JSON.parse(l.stdout);return Zd(u,`release PR discovery (base ${ke})`),u.map(p=>({...p,dualBase:!1}))}let[t,r]=await Promise.all([Jr`gh pr list --limit ${io} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Jr`gh pr list --limit ${io} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),n=JSON.parse(t.stdout),o=JSON.parse(r.stdout);Zd(n,"release PR discovery (base dev)"),Zd(o,"hotfix PR discovery (base main)");let s=new Set(n.map(l=>l.headRefName)),i=new Set(o.filter(l=>s.has(l.headRefName)).map(l=>l.headRefName)),a=[...o,...n],c=new Set;return a.filter(l=>c.has(l.headRefName)?!1:(c.add(l.headRefName),!0)).map(l=>({...l,dualBase:i.has(l.headRefName)}))},Fs="find open release PRs",mw=async e=>{try{let t=await AO(e);if(t.length===0)throw new g(void 0,{operation:Fs,remediation:"open a release PR first, or check you are in the right repo"});return $O(t)}catch(t){throw t instanceof g?t:(d.debug({err:t},"Error fetching release PRs"),new g(t,{operation:"fetch release PRs"}))}},Xa=async()=>(await mw(await ne())).map(t=>t.headRefName),OO=(e,t)=>{let r=Ns(e.baseRefName,t);if(r===null)throw new g(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let n=Xd(e.title)!==r;return(n||e.dualBase)&&d.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${r} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:r,titleMismatch:n,dualBase:e.dualBase}},K=async()=>{let e=await ne();return(await mw(e)).map(r=>OO(r,e))},Za=async e=>{let{branch:t,body:r}=e;try{await Jr({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}},DO=async(e,t)=>{let r=Jr({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`)},Ya=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=lg(t,n),a=Pt(n,await ne()),c=Jr({quiet:!0}),l=Ae(t),u=_s(r,o);try{await oo({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new g(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await DO(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Jr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Qd}from"zx";var ao=async e=>{let t=await Qd`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},ep=async e=>{let t=await Qd`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Qa=async e=>{try{let t=await Qd`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new g(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import IO from"node:process";var Ls=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var tp=null,fw=e=>{tp=e},gw=()=>{if(tp===null)throw new Error("no branch picker registered: entry/cli.ts registers the Ink pickers at startup");return tp()},hw=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(H())throw new A({status:"argument_required",argument:e,agentMode:N.source},2,t);if(!IO.stdin.isTTY)throw new g(void 0,t)},mr=async e=>{hw("version");let{runBranchPicker:t}=await gw(),r=await t(e);if(r===null)throw new Ls;return r},fr=async(e,t)=>{hw("versions");let{runBranchMultiPicker:r}=await gw(),n=await r(e,t);if(n===null)throw new Ls;return n};import{$ as Kr}from"zx";var rp=(e,t)=>`Merge remote-tracking branch '${e}' into ${t}`,NO=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},_O=2048,MO=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-_O)).filter(s=>s.length>0).join(`
388
- `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},jO=async e=>{try{return(await Kr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
389
- `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},FO=async(e,t)=>{let r=NO(t),n=await jO(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await yg(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},yw=async e=>{let{cwd:t,worktreePath:r,branches:n,integrationRef:o}=e,s=[],i=await Oe(t,o);if(!i)return n.map(a=>({branch:a,status:"error",reason:`${o} does not resolve`}));for(let a of n){let c=Date.now(),l=await LO({cwd:t,worktreePath:r,branch:a,devSha:i,integrationRef:o});s.push({...l,durationMs:Date.now()-c})}return s},LO=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o,integrationRef:s}=e,i=`origin/${n}`;if(!await Oe(t,i))return{branch:n,status:"error",reason:`${i} does not exist on origin`};if(await $o(t,s,i))return{branch:n,status:"up-to-date"};try{await pl(r),await Kr({cwd:r,quiet:!0})`git checkout --detach ${i}`;let a=rp(s,n);await Kr({cwd:r,quiet:!0})`git merge ${s} --no-edit -m ${a}`;let c=(await Kr({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:c===o?"fast-forward":"merged",mergeSha:c}}catch(a){return{branch:n,...await FO(r,a)}}finally{await ml(r)}},vw=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),ww="pnpm install --frozen-lockfile",kw=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await pl(t),await Kr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await Kr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,MO(a))}finally{await ml(t)}return{kept:o,failed:s}},Bs=async(e,t,r)=>{await Kr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await $o(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import{Buffer as Pw}from"node:buffer";import gr from"node:fs/promises";import qr from"node:path";import xw from"node:process";import{$ as nc}from"zx";import bw from"node:fs/promises";import BO from"node:path";import{$ as np}from"zx";var J="pnpm-lock.yaml",UO=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Sw=async(e,t)=>{let r=BO.join(e,J),n=`${t}:${J}`;try{let o=await np({cwd:e,quiet:!0})`git show ${n}`;await bw.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${J} to start from: ${Rw(o)}`}}try{await np({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${J}: ${Rw(o)}`}}return UO.test(await bw.readFile(r,"utf8"))?{ok:!1,reason:`${J} still carries conflict markers after pnpm ran`}:(await np({cwd:e,quiet:!0})`git add -- ${J}`,{ok:!0})},Rw=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import op from"node:process";var ec=new Set,tc=e=>(ec.add(e),()=>{ec.delete(e)}),VO=async()=>{for(let e of[...ec])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}ec.clear()},WO=["SIGINT","SIGTERM"],Ew=async(e,t={})=>{let{register:r=(i,a)=>{op.on(i,a)},unregister:n=(i,a)=>{op.off(i,a)},exit:o=i=>{op.exit(i)}}=t,s=new Map;for(let i of WO){let a=()=>{VO().then(()=>{o(Jg(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var GO="pnpm install --frozen-lockfile --ignore-scripts",sp="pnpm install --frozen-lockfile",Tw=64*1024,Dw=4096,Vs=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Dw)},W=async(e,t)=>(await nc({cwd:e,quiet:!0})`git ${t}`).stdout,ap=e=>e.split(`
390
- `).map(t=>t.trim()).filter(t=>t.length>0),lo=e=>e.split("\0").filter(t=>t.length>0),Hr=async(e,t)=>{try{return(await W(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},JO=async e=>qr.resolve(e,(await W(e,["rev-parse","--git-common-dir"])).trim()),Iw=e=>e.then(()=>!0,()=>!1),Us=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),cp=e=>e?.length===1&&e[0]===J,Cw=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,...e.editablePaths?{editablePaths:e.editablePaths}:{},lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),KO=e=>e.editablePaths??e.conflictPaths,HO=e=>qr.posix.basename(e)==="package.json",lp=e=>e.conflictPaths.includes(J)||e.lockfileBlob!==void 0,Nw=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(J);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=lo(await W(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await dp(e),...r].some(HO)},_w=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",up=async(e,t,r)=>{await W(e,["worktree","remove","--force",r]).catch(()=>gr.rm(r,{recursive:!0,force:!0})),await gr.rm(await vs(e,t),{force:!0}).catch(()=>{}),await W(e,["worktree","prune"]).catch(()=>{})},Mw=async e=>lo(await W(e,["diff","--name-only","-z","--diff-filter=U"])),rc=async e=>lo(await W(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),qO=async(e,t)=>{let r=(await W(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await Iw(gr.stat(qr.join(await JO(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(ap(await W(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},jw=e=>e.split("/").includes("node_modules"),oc=async(e,t)=>{let r=new Set(KO(t));t.editablePaths&&await Nw(e,t)&&r.add(J);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=lo(await W(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await dp(e),...o].filter(a=>!r.has(a)),i=(await rc(e)).filter(a=>!n.has(a)&&!jw(a));return[...new Set([...s,...i,...await zO(e)])].sort()},dp=async e=>{let t=lo(await W(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},zO=async e=>(await W(e,["ls-files","-v"])).split(`
391
- `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),YO=async(e,t)=>{let r=`:(exclude)${J}`;try{return await W(e,["diff","--cached","--check",t,"--",".",r]),[]}catch(n){let{stdout:o="",stderr:s="",exitCode:i}=n;if(s.trim().length>0||o.trim().length===0||i!==1&&i!==2)throw new g(n,{operation:"check the staged resolution for conflict markers"});let a=new Set;for(let c of o.split(`
392
- `)){let l=/^(.*):\d+: leftover conflict marker/.exec(c);l?.[1]&&a.add(l[1])}return[...a].sort()}},XO=async(e,t)=>{let r=[];for(let n of t)(await Iw(gr.lstat(qr.join(e,n)))||(await W(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await W(e,["--literal-pathspecs","add","-A","--",...r])},ip=async e=>(await W(e,["write-tree"])).trim(),Fw=async e=>(await W(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),ZO=e=>{let t=`${sp} && `;if(e!==sp)return e?.startsWith(t)?e.slice(t.length):e},QO=e=>e?`${sp} && ${e}`:GO,eD=async(e,t)=>{try{return await nc({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Vs(r)}}},Lw=async(e,t)=>{let r=(await W(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await W(e,["diff","--cached","--stat",l,"--",J])).trim(),o=lp(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await W(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${J}`]),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)
393
- ${l}`:l}).join(""),c=Pw.byteLength(a)>Tw;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Pw.from(a).subarray(0,Tw).toString():a,resolutionDiffTruncated:c}},Bw=async e=>{let{cwd:t,conflicted:r,verifyFailed:n,devSha:o,integrationRef:s,verify:i}=e,a=new Map;for(let c of r)a.set(c,await $w(t,c,o,s,"conflict"));for(let c of n)a.set(c,await $w(t,c,o,s,"verify-failed",i));return a},tD=async(e,t,r)=>{let n=async(a,c)=>lo(await W(e,["diff","--name-only","-z","--no-renames",`${a}...${c}`])),o=await n(t,r),s=await n(r,t);return{editablePaths:[...new Set([...o,...s])].filter(a=>a!==J).sort(),lockfileBothSides:o.includes(J)&&s.includes(J)}},rD=async(e,t,r,n)=>{let o=await Mw(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await Hr(e,"HEAD"),a=await Hr(e,"MERGE_HEAD");return i!==r||a!==n?{reason:"the merge no longer reproduces (already up to date?) \u2014 re-run release merge-dev"}:{conflictPaths:[],...await tD(e,r,n),autoMergeTree:await ip(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await Hr(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await qO(e,o),lockfileOnly:cp(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await W(e,["--version"])).trim()})`}},nD={conflict:"needs-agent","verify-failed":"verify-failed"},$w=async(e,t,r,n,o,s)=>{let i=await Da(await vs(e,t));if(i)return{resolution:Cw(i,"exists"),reason:`resolution-exists: ${i.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let a=await Oe(e,`origin/${t}`);if(!a)return{reason:`origin/${t} does not exist on origin`};let c=hg(e,t),l=()=>up(e,t,c),u=tc(l);try{await W(e,["worktree","prune"]),await gr.mkdir(qr.dirname(c),{recursive:!0}),await W(e,["worktree","add","--detach",c,a]);let p=rp(n,t);await nc({cwd:c,quiet:!0})`git merge --no-commit ${r} -m ${p}`.catch(()=>{});let m=await rD(c,o,a,r);if("reason"in m)return await l(),m;let f={branch:t,worktreePath:c,baseSha:a,devSha:r,...m,...o==="verify-failed"&&s?{handOffVerify:s}:{},ignoredAtHandoff:await rc(c),cliVersion:U.version,createdAt:new Date().toISOString()};return await cr(e,f),{resolution:Cw(f,f.lockfileOnly?"lockfile-only":nD[o])}}catch(p){return await l(),{reason:Vs(p)}}finally{u()}},Uw=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Ia(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=Ae(Ee(c)),u=o.find(p=>p.branch===l);if(!u)throw new g(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return u});if(n||o.length===0)return o;let i=await fr(ve({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},oD=async(e,t)=>{let r=await gr.realpath(t).catch(()=>null);if(!r)return!1;let n=await gt(e);for(let o of n)if(await gr.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},co=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Vw=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 oD(e,n))return co(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Hr(n,"HEAD"),i=await Hr(n,"MERGE_HEAD"),a=r??ZO(t.handOffVerify);return s===t.baseSha&&i===t.devSha?lD(e,t,o,a):sD(t,o,s,i)},sD=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return co(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 Fw(o),i=n?null:await Hr(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 co(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await oc(o,e);return c.length>0?co(t,"out-of-scope-edit",_w(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:lp(e),...await Lw(o,e)}},Aw=async(e,t)=>{let r=ap(await W(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},iD=async(e,t)=>{let r=t.worktreePath,n=await Aw(r,J),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await Hr(r,`${t.autoMergeTree}:${J}`),i=await Sw(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[J]};let a=await Aw(r,J);if(a!==null&&a!==o&&(t.lockfileBlob=a,await cr(e,t)),n!==null&&n!==a&&!s)return n===o?{code:"tree-changed",detail:`rebuilding ${J} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[J]}:{code:"out-of-scope-edit",detail:`${J} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[J]};let c=await oc(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},aD=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await dp(r)).filter(c=>n.has(c)):t.conflictPaths;await XO(r,o.filter(c=>c!==J));let s=await oc(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:_w(t),paths:s};let i=(await Mw(r)).filter(c=>c!==J);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await YO(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Vs(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await Nw(r,t)?iD(e,t):null},cD=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 rc(o)),i=await eD(o,n),a=(await rc(o)).filter(c=>!s.has(c)&&!jw(c)&&qr.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await cr(e,t),i},lD=async(e,t,r,n)=>{let o=t.worktreePath,s=await aD(e,t);if(s)return{...r,blocked:s};let i=lp(t),a=await ip(o),c=await cD(e,t,a,QO(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return co(l,"verify-failed",c.reason??"the verify command failed");let u=await oc(o,t),p=ap(await W(o,["diff","--name-only"]));return u.length>0||p.length>0||await ip(o)!==a?co(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await cr(e,t)),{...l,...await Lw(o,t)})},uD=12e4,dD=async(e,t=uD)=>{let r=nc({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...xw.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&xw.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Vs(s)};let i=(await W(e,["rev-parse","--git-path","index.lock"])).trim();return await gr.rm(qr.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},pD={"verify-failed":"verify-failed","tree-changed":"tree-changed"},mD=e=>{let t=e.blocked;return{branch:e.branch,status:pD[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},fD=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 dD(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await W(o,["rev-parse","HEAD"])).trim(),c=(await W(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await cr(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 Fw(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}},gD=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 Bs(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Vs(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await Oe(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await $o(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)},hD=e=>{d.info(`
394
- \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}`)},Ww=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Uw({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Us();if(i)return Ow(t,a,o,s);let c=[];for(let m of a){let f=await Vw(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await cr(t,m)),c.push(f)}hD(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new A({status:"refused",plan:l,agentMode:N.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await q(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,rerun:yD(p)})}catch(m){if(!xe(m))throw m;return{...Us(),declined:!0}}return Ow(t,a,o,p)},Gw=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new g(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},yD=e=>{let t=[],r=!1;for(let o of Ug())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"]},vD=async(e,t,r,n)=>{let o=await Vw(e,t,r);if(o.blocked)return mD(o);let s=await fD(e,o,t,n);if(!("sha"in s))return s;let i=await gD(e,t,s.sha);return i==="keep"?s:i},wD=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(`
395
- \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await Ui(e,r),o=[];for(let s of t){let i=n.pushed||await pn(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(-Dw)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
396
- `)[0]}}},Ow=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await vD(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await wD(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 up(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}},Jw=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Uw({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Us();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await q(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i})}catch(a){if(!xe(a))throw a;return{...Us(),declined:!0}}for(let a of s)await up(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Us(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};var bD=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),RD=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,SD=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(", ")},mp=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),pp=new Set(["up-to-date","fast-forward","merged"]),ED=(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=Ae(Ee(a))}catch(l){throw new g(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new g(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},PD={"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"},Hw=e=>{let t=PD[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},xD=(e,t)=>{d.info(`
397
- \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${Hw(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},TD=(e,t,r)=>{let n=t.find(o=>o.branch===e);return n?`git -C ${n.path} merge ${r}`:`git switch ${e} && git merge ${r}`},CD=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;y.setInteractive();let s=new Map(t.flatMap(i=>{let a=re(i.branch);return a?[[pe(a),Hw(i)]]:[]}));return fr(ve({branches:r,descriptions:s}),{required:!0})},$D=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s,integrationRef:i}=e,a=n.filter(b=>o.includes(b.branch)),c=b=>{for(let C of b)d.info(`\u2139\uFE0F ${C} was merged by someone else while we planned \u2014 dropping it from the push`)},l=await Bs(t,vw(a),i);c(l.nowUpToDate);let u=l.kept,p=new Map;if(s&&u.length>0){d.info(`
398
- \u{1F50E} Verifying ${u.length} merge(s) with: ${s}`);let b=await kw({worktreePath:r,refs:u,command:s});p=b.failed;for(let[k,F]of b.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${F.split(`
387
+ `,Yd=async(e="regular")=>{let t=xt(e,await ne()),r=yw({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 yw({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new g(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},IO=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await Bt(t,r);if(!s)return(await ld({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new g(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await Zn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Xd=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=pe(t),c=await IO({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=Lr(r,c),u=await Ya({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:ae(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},qa=async()=>{let e=new Map,t=await Ut();if(!t)return e;try{let r=await Xn(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},ye=async()=>{let e=await qa();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Ms=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Zd=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",za=e=>e.flatMap(t=>{let r=re(t);return r?[{branch:t,id:r,label:ae(r)}]:[]}),Gt=e=>{try{return Ae(Ee(e))}catch(t){throw new g(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},js=e=>{let t=re(e);return t?ae(t):e},Jt=e=>e.flatMap(t=>{let r=re(t);return r?[ae(r)]:[]}),NO=(e,t)=>t?t.get(e)||"regular":void 0,ve=e=>{let{branches:t,descriptions:r,types:n}=e;return za(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(pe(s)),type:NO(o,n)}))};var _O=e=>e.map(t=>({pr:t,id:re(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>fg(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),ao=200,Qd=(e,t)=>{e.length<ao||d.warn({source:t,limit:ao},`\u26A0\uFE0F ${t} returned ${ao} PRs \u2014 the page is full, so older release PRs may be missing`)},MO=async e=>{if(e==="main"){let l=await Jr`gh pr list --limit ${ao} --base ${ke} --json number,title,headRefName,state,baseRefName,createdAt`,u=JSON.parse(l.stdout);return Qd(u,`release PR discovery (base ${ke})`),u.map(p=>({...p,dualBase:!1}))}let[t,r]=await Promise.all([Jr`gh pr list --limit ${ao} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Jr`gh pr list --limit ${ao} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),n=JSON.parse(t.stdout),o=JSON.parse(r.stdout);Qd(n,"release PR discovery (base dev)"),Qd(o,"hotfix PR discovery (base main)");let s=new Set(n.map(l=>l.headRefName)),i=new Set(o.filter(l=>s.has(l.headRefName)).map(l=>l.headRefName)),a=[...o,...n],c=new Set;return a.filter(l=>c.has(l.headRefName)?!1:(c.add(l.headRefName),!0)).map(l=>({...l,dualBase:i.has(l.headRefName)}))},Fs="find open release PRs",vw=async e=>{try{let t=await MO(e);if(t.length===0)throw new g(void 0,{operation:Fs,remediation:"open a release PR first, or check you are in the right repo"});return _O(t)}catch(t){throw t instanceof g?t:(d.debug({err:t},"Error fetching release PRs"),new g(t,{operation:"fetch release PRs"}))}},Xa=async()=>(await vw(await ne())).map(t=>t.headRefName),jO=(e,t)=>{let r=Ns(e.baseRefName,t);if(r===null)throw new g(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let n=Zd(e.title)!==r;return(n||e.dualBase)&&d.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${r} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:r,titleMismatch:n,dualBase:e.dualBase}},K=async()=>{let e=await ne();return(await vw(e)).map(r=>jO(r,e))},Za=async e=>{let{branch:t,body:r}=e;try{await Jr({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}},FO=async(e,t)=>{let r=Jr({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`)},Ya=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=mg(t,n),a=xt(n,await ne()),c=Jr({quiet:!0}),l=Ae(t),u=_s(r,o);try{await so({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new g(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await FO(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Jr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as ep}from"zx";var co=async e=>{let t=await ep`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},tp=async e=>{let t=await ep`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Qa=async e=>{try{let t=await ep`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new g(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import LO from"node:process";var Ls=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var rp=null,ww=e=>{rp=e},kw=()=>{if(rp===null)throw new Error("no branch picker registered: entry/cli.ts registers the Ink pickers at startup");return rp()},bw=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(H())throw new A({status:"argument_required",argument:e,agentMode:N.source},2,t);if(!LO.stdin.isTTY)throw new g(void 0,t)},mr=async e=>{bw("version");let{runBranchPicker:t}=await kw(),r=await t(e);if(r===null)throw new Ls;return r},fr=async(e,t)=>{bw("versions");let{runBranchMultiPicker:r}=await kw(),n=await r(e,t);if(n===null)throw new Ls;return n};import{$ as Kr}from"zx";var np=(e,t)=>`Merge remote-tracking branch '${e}' into ${t}`,BO=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},UO=2048,VO=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-UO)).filter(s=>s.length>0).join(`
388
+ `)||`the verify command exited with code ${n??"unknown"} and printed nothing`},WO=async e=>{try{return(await Kr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
389
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},GO=async(e,t)=>{let r=BO(t),n=await WO(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await bg(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Rw=async e=>{let{cwd:t,worktreePath:r,branches:n,integrationRef:o}=e,s=[],i=await Oe(t,o);if(!i)return n.map(a=>({branch:a,status:"error",reason:`${o} does not resolve`}));for(let a of n){let c=Date.now(),l=await JO({cwd:t,worktreePath:r,branch:a,devSha:i,integrationRef:o});s.push({...l,durationMs:Date.now()-c})}return s},JO=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o,integrationRef:s}=e,i=`origin/${n}`;if(!await Oe(t,i))return{branch:n,status:"error",reason:`${i} does not exist on origin`};if(await Ao(t,s,i))return{branch:n,status:"up-to-date"};try{await ml(r),await Kr({cwd:r,quiet:!0})`git checkout --detach ${i}`;let a=np(s,n);await Kr({cwd:r,quiet:!0})`git merge ${s} --no-edit -m ${a}`;let c=(await Kr({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:c===o?"fast-forward":"merged",mergeSha:c}}catch(a){return{branch:n,...await GO(r,a)}}finally{await fl(r)}},Sw=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Ew="pnpm install --frozen-lockfile",Pw=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await ml(t),await Kr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await Kr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,VO(a))}finally{await fl(t)}return{kept:o,failed:s}},Bs=async(e,t,r)=>{await Kr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Ao(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import{Buffer as Aw}from"node:buffer";import gr from"node:fs/promises";import qr from"node:path";import Ow from"node:process";import{$ as nc}from"zx";import xw from"node:fs/promises";import KO from"node:path";import{$ as op}from"zx";var J="pnpm-lock.yaml",HO=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Cw=async(e,t)=>{let r=KO.join(e,J),n=`${t}:${J}`;try{let o=await op({cwd:e,quiet:!0})`git show ${n}`;await xw.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${J} to start from: ${Tw(o)}`}}try{await op({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${J}: ${Tw(o)}`}}return HO.test(await xw.readFile(r,"utf8"))?{ok:!1,reason:`${J} still carries conflict markers after pnpm ran`}:(await op({cwd:e,quiet:!0})`git add -- ${J}`,{ok:!0})},Tw=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import sp from"node:process";var ec=new Set,tc=e=>(ec.add(e),()=>{ec.delete(e)}),qO=async()=>{for(let e of[...ec])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}ec.clear()},zO=["SIGINT","SIGTERM"],$w=async(e,t={})=>{let{register:r=(i,a)=>{sp.on(i,a)},unregister:n=(i,a)=>{sp.off(i,a)},exit:o=i=>{sp.exit(i)}}=t,s=new Map;for(let i of zO){let a=()=>{qO().then(()=>{o(zg(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var YO="pnpm install --frozen-lockfile --ignore-scripts",ip="pnpm install --frozen-lockfile",Dw=64*1024,jw=4096,Vs=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-jw)},W=async(e,t)=>(await nc({cwd:e,quiet:!0})`git ${t}`).stdout,cp=e=>e.split(`
390
+ `).map(t=>t.trim()).filter(t=>t.length>0),uo=e=>e.split("\0").filter(t=>t.length>0),Hr=async(e,t)=>{try{return(await W(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},XO=async e=>qr.resolve(e,(await W(e,["rev-parse","--git-common-dir"])).trim()),Fw=e=>e.then(()=>!0,()=>!1),Us=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),lp=e=>e?.length===1&&e[0]===J,Iw=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,...e.editablePaths?{editablePaths:e.editablePaths}:{},lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),ZO=e=>e.editablePaths??e.conflictPaths,QO=e=>qr.posix.basename(e)==="package.json",up=e=>e.conflictPaths.includes(J)||e.lockfileBlob!==void 0,Lw=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(J);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=uo(await W(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await pp(e),...r].some(QO)},Bw=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",dp=async(e,t,r)=>{await W(e,["worktree","remove","--force",r]).catch(()=>gr.rm(r,{recursive:!0,force:!0})),await gr.rm(await vs(e,t),{force:!0}).catch(()=>{}),await W(e,["worktree","prune"]).catch(()=>{})},Uw=async e=>uo(await W(e,["diff","--name-only","-z","--diff-filter=U"])),rc=async e=>uo(await W(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),eD=async(e,t)=>{let r=(await W(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await Fw(gr.stat(qr.join(await XO(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(cp(await W(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},Vw=e=>e.split("/").includes("node_modules"),oc=async(e,t)=>{let r=new Set(ZO(t));t.editablePaths&&await Lw(e,t)&&r.add(J);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=uo(await W(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await pp(e),...o].filter(a=>!r.has(a)),i=(await rc(e)).filter(a=>!n.has(a)&&!Vw(a));return[...new Set([...s,...i,...await tD(e)])].sort()},pp=async e=>{let t=uo(await W(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},tD=async e=>(await W(e,["ls-files","-v"])).split(`
391
+ `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),rD=async(e,t)=>{let r=`:(exclude)${J}`;try{return await W(e,["diff","--cached","--check",t,"--",".",r]),[]}catch(n){let{stdout:o="",stderr:s="",exitCode:i}=n;if(s.trim().length>0||o.trim().length===0||i!==1&&i!==2)throw new g(n,{operation:"check the staged resolution for conflict markers"});let a=new Set;for(let c of o.split(`
392
+ `)){let l=/^(.*):\d+: leftover conflict marker/.exec(c);l?.[1]&&a.add(l[1])}return[...a].sort()}},nD=async(e,t)=>{let r=[];for(let n of t)(await Fw(gr.lstat(qr.join(e,n)))||(await W(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await W(e,["--literal-pathspecs","add","-A","--",...r])},ap=async e=>(await W(e,["write-tree"])).trim(),Ww=async e=>(await W(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),oD=e=>{let t=`${ip} && `;if(e!==ip)return e?.startsWith(t)?e.slice(t.length):e},sD=e=>e?`${ip} && ${e}`:YO,iD=async(e,t)=>{try{return await nc({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Vs(r)}}},Gw=async(e,t)=>{let r=(await W(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await W(e,["diff","--cached","--stat",l,"--",J])).trim(),o=up(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await W(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${J}`]),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)
393
+ ${l}`:l}).join(""),c=Aw.byteLength(a)>Dw;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Aw.from(a).subarray(0,Dw).toString():a,resolutionDiffTruncated:c}},Jw=async e=>{let{cwd:t,conflicted:r,verifyFailed:n,devSha:o,integrationRef:s,verify:i}=e,a=new Map;for(let c of r)a.set(c,await Nw(t,c,o,s,"conflict"));for(let c of n)a.set(c,await Nw(t,c,o,s,"verify-failed",i));return a},aD=async(e,t,r)=>{let n=async(a,c)=>uo(await W(e,["diff","--name-only","-z","--no-renames",`${a}...${c}`])),o=await n(t,r),s=await n(r,t);return{editablePaths:[...new Set([...o,...s])].filter(a=>a!==J).sort(),lockfileBothSides:o.includes(J)&&s.includes(J)}},cD=async(e,t,r,n)=>{let o=await Uw(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await Hr(e,"HEAD"),a=await Hr(e,"MERGE_HEAD");return i!==r||a!==n?{reason:"the merge no longer reproduces (already up to date?) \u2014 re-run release merge-dev"}:{conflictPaths:[],...await aD(e,r,n),autoMergeTree:await ap(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await Hr(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await eD(e,o),lockfileOnly:lp(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await W(e,["--version"])).trim()})`}},lD={conflict:"needs-agent","verify-failed":"verify-failed"},Nw=async(e,t,r,n,o,s)=>{let i=await Da(await vs(e,t));if(i)return{resolution:Iw(i,"exists"),reason:`resolution-exists: ${i.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let a=await Oe(e,`origin/${t}`);if(!a)return{reason:`origin/${t} does not exist on origin`};let c=kg(e,t),l=()=>dp(e,t,c),u=tc(l);try{await W(e,["worktree","prune"]),await gr.mkdir(qr.dirname(c),{recursive:!0}),await W(e,["worktree","add","--detach",c,a]);let p=np(n,t);await nc({cwd:c,quiet:!0})`git merge --no-commit ${r} -m ${p}`.catch(()=>{});let m=await cD(c,o,a,r);if("reason"in m)return await l(),m;let f={branch:t,worktreePath:c,baseSha:a,devSha:r,...m,...o==="verify-failed"&&s?{handOffVerify:s}:{},ignoredAtHandoff:await rc(c),cliVersion:U.version,createdAt:new Date().toISOString()};return await cr(e,f),{resolution:Iw(f,f.lockfileOnly?"lockfile-only":lD[o])}}catch(p){return await l(),{reason:Vs(p)}}finally{u()}},Kw=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Ia(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=Ae(Ee(c)),u=o.find(p=>p.branch===l);if(!u)throw new g(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return u});if(n||o.length===0)return o;let i=await fr(ve({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},uD=async(e,t)=>{let r=await gr.realpath(t).catch(()=>null);if(!r)return!1;let n=await gt(e);for(let o of n)if(await gr.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},lo=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Hw=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 uD(e,n))return lo(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Hr(n,"HEAD"),i=await Hr(n,"MERGE_HEAD"),a=r??oD(t.handOffVerify);return s===t.baseSha&&i===t.devSha?gD(e,t,o,a):dD(t,o,s,i)},dD=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return lo(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 Ww(o),i=n?null:await Hr(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 lo(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await oc(o,e);return c.length>0?lo(t,"out-of-scope-edit",Bw(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:up(e),...await Gw(o,e)}},_w=async(e,t)=>{let r=cp(await W(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},pD=async(e,t)=>{let r=t.worktreePath,n=await _w(r,J),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await Hr(r,`${t.autoMergeTree}:${J}`),i=await Cw(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[J]};let a=await _w(r,J);if(a!==null&&a!==o&&(t.lockfileBlob=a,await cr(e,t)),n!==null&&n!==a&&!s)return n===o?{code:"tree-changed",detail:`rebuilding ${J} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[J]}:{code:"out-of-scope-edit",detail:`${J} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[J]};let c=await oc(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},mD=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await pp(r)).filter(c=>n.has(c)):t.conflictPaths;await nD(r,o.filter(c=>c!==J));let s=await oc(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:Bw(t),paths:s};let i=(await Uw(r)).filter(c=>c!==J);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await rD(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Vs(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await Lw(r,t)?pD(e,t):null},fD=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 rc(o)),i=await iD(o,n),a=(await rc(o)).filter(c=>!s.has(c)&&!Vw(c)&&qr.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await cr(e,t),i},gD=async(e,t,r,n)=>{let o=t.worktreePath,s=await mD(e,t);if(s)return{...r,blocked:s};let i=up(t),a=await ap(o),c=await fD(e,t,a,sD(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return lo(l,"verify-failed",c.reason??"the verify command failed");let u=await oc(o,t),p=cp(await W(o,["diff","--name-only"]));return u.length>0||p.length>0||await ap(o)!==a?lo(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await cr(e,t)),{...l,...await Gw(o,t)})},hD=12e4,yD=async(e,t=hD)=>{let r=nc({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Ow.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Ow.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Vs(s)};let i=(await W(e,["rev-parse","--git-path","index.lock"])).trim();return await gr.rm(qr.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},vD={"verify-failed":"verify-failed","tree-changed":"tree-changed"},wD=e=>{let t=e.blocked;return{branch:e.branch,status:vD[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},kD=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 yD(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await W(o,["rev-parse","HEAD"])).trim(),c=(await W(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await cr(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 Ww(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}},bD=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 Bs(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Vs(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await Oe(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Ao(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)},RD=e=>{d.info(`
394
+ \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}`)},qw=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Kw({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Us();if(i)return Mw(t,a,o,s);let c=[];for(let m of a){let f=await Hw(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await cr(t,m)),c.push(f)}RD(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new A({status:"refused",plan:l,agentMode:N.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await q(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,rerun:SD(p)})}catch(m){if(!xe(m))throw m;return{...Us(),declined:!0}}return Mw(t,a,o,p)},zw=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new g(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},SD=e=>{let t=[],r=!1;for(let o of Jg())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"]},ED=async(e,t,r,n)=>{let o=await Hw(e,t,r);if(o.blocked)return wD(o);let s=await kD(e,o,t,n);if(!("sha"in s))return s;let i=await bD(e,t,s.sha);return i==="keep"?s:i},PD=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(`
395
+ \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await Ui(e,r),o=[];for(let s of t){let i=n.pushed||await pn(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(-jw)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
396
+ `)[0]}}},Mw=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await ED(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await PD(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 dp(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}},Yw=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Kw({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Us();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await q(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i})}catch(a){if(!xe(a))throw a;return{...Us(),declined:!0}}for(let a of s)await dp(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Us(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};var TD=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),CD=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,$D=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(", ")},fp=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),mp=new Set(["up-to-date","fast-forward","merged"]),AD=(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=Ae(Ee(a))}catch(l){throw new g(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new g(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},OD={"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"},Zw=e=>{let t=OD[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},DD=(e,t)=>{d.info(`
397
+ \u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${Zw(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},ID=(e,t,r)=>{let n=t.find(o=>o.branch===e);return n?`git -C ${n.path} merge ${r}`:`git switch ${e} && git merge ${r}`},ND=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;y.setInteractive();let s=new Map(t.flatMap(i=>{let a=re(i.branch);return a?[[pe(a),Zw(i)]]:[]}));return fr(ve({branches:r,descriptions:s}),{required:!0})},_D=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s,integrationRef:i}=e,a=n.filter(b=>o.includes(b.branch)),c=b=>{for(let C of b)d.info(`\u2139\uFE0F ${C} was merged by someone else while we planned \u2014 dropping it from the push`)},l=await Bs(t,Sw(a),i);c(l.nowUpToDate);let u=l.kept,p=new Map;if(s&&u.length>0){d.info(`
398
+ \u{1F50E} Verifying ${u.length} merge(s) with: ${s}`);let b=await Pw({worktreePath:r,refs:u,command:s});p=b.failed;for(let[k,F]of b.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${F.split(`
399
399
  `)[0]??""}`);let C=await Bs(t,b.kept,i);c(C.nowUpToDate),u=C.kept}if(u.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:p};d.info(`
400
400
  \u2B06\uFE0F Pushing atomically: ${u.map(b=>b.branch).join(", ")}`);let m=await Ui(t,u);if(m.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:p};let h=(await Promise.all(u.map(async b=>({branch:b.branch,landed:await pn(t,b.branch)===b.sha})))).filter(b=>b.landed);return h.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${h.map(b=>b.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:p,abortedBy:m.stderr?.split(`
401
- `)[0],observedLanded:h.map(b=>b.branch)}},AD=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Kw=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
402
- `)[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=>!pp.has(i.status));return mp({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},OD=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await _e();if(e.abort)return Kw(await Jw({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Kw(await Ww({cwd:s,versions:r,all:t,verify:i,trees:Gw(e.tree),confirmedCommand:o}))},sc=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;AD(e);let a=o===!0?ww:o||void 0;if(await Hd({operation:"merge dev into release branches"}),e.continue||e.abort)return OD(e);let c=[],l=[];for(let D of await K()){let V=RD(D);V?l.push({branch:D.branch,reason:V}):c.push(D.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 (${SD(l)})`),y.print(),mp(bD(n,l));let u=await _e();try{await kD({cwd:u,quiet:!0})`git fetch origin --prune`}catch(D){throw new g(D,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:ED(r,c,l),m=`origin/${await Gr()}`,f=await vg({cwd:u,anchor:m},async D=>{let V=tc(D.remove);try{return await DD({cwd:u,worktree:D,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i,integrationRef:m})}finally{V()}}),{entries:h,selected:b,pushed:C,pushAborted:k,abortedBy:F,declined:v,verifyFailed:S,handOffs:P}=f,O=await gt(u).catch(()=>[]);return MD({entries:h,selected:b,pushed:C,pushAborted:k,abortedBy:F,declined:v,verifyFailed:S,handOffs:P,dryRun:n,worktrees:O,skipped:l,integrationRef:m})},DD=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p,integrationRef:m}=e,f=u?await Oe(t,m):null,h=await yw({cwd:t,worktreePath:r.path,branches:n,integrationRef:m}),b={entries:h,pushed:!1,pushAborted:!1,declined:!1};if(xD(h,s),c)return{...b,selected:n};let C=await CD({entries:h,toPlan:n,all:i,explicit:a!==void 0});C.length===o.length?y.addOption("--all",!0):y.addOption("--versions",C);let k=h.filter(D=>C.includes(D.branch)&&D.mergeSha).length;k>0&&d.info(`
403
- \u2139\uFE0F This will push ${k} branch(es), re-running CI on ${k} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await q(p,`Are you sure you want to merge ${m} into these branches: ${C.join(", ")}?`,{plan:ID(h,C,s)})}catch(D){if(!xe(D))throw D;return{...b,selected:C,declined:!0}}p||y.addOption("--yes",!0);let F=await $D({cwd:t,worktreePath:r.path,entries:h,selected:C,verify:l,integrationRef:m}),v=D=>h.filter(V=>C.includes(V.branch)&&D(V)).map(V=>V.branch),S=v(D=>D.status==="conflict"),P=v(D=>D.status==="merged"&&(F.verifyFailed?.has(D.branch)??!1)),O=u&&f&&S.length+P.length>0?await Bw({cwd:t,conflicted:S,verifyFailed:P,devSha:f,integrationRef:m,verify:l}):void 0;return{entries:h,selected:C,declined:!1,...F,handOffs:O}},ID=(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:cp(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),ND=(e,t,r)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
401
+ `)[0],observedLanded:h.map(b=>b.branch)}},MD=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Xw=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
402
+ `)[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=>!mp.has(i.status));return fp({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},jD=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await _e();if(e.abort)return Xw(await Yw({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Xw(await qw({cwd:s,versions:r,all:t,verify:i,trees:zw(e.tree),confirmedCommand:o}))},sc=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;MD(e);let a=o===!0?Ew:o||void 0;if(await qd({operation:"merge dev into release branches"}),e.continue||e.abort)return jD(e);let c=[],l=[];for(let D of await K()){let V=CD(D);V?l.push({branch:D.branch,reason:V}):c.push(D.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 (${$D(l)})`),y.print(),fp(TD(n,l));let u=await _e();try{await xD({cwd:u,quiet:!0})`git fetch origin --prune`}catch(D){throw new g(D,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:AD(r,c,l),m=`origin/${await Gr()}`,f=await Rg({cwd:u,anchor:m},async D=>{let V=tc(D.remove);try{return await FD({cwd:u,worktree:D,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i,integrationRef:m})}finally{V()}}),{entries:h,selected:b,pushed:C,pushAborted:k,abortedBy:F,declined:v,verifyFailed:S,handOffs:P}=f,O=await gt(u).catch(()=>[]);return VD({entries:h,selected:b,pushed:C,pushAborted:k,abortedBy:F,declined:v,verifyFailed:S,handOffs:P,dryRun:n,worktrees:O,skipped:l,integrationRef:m})},FD=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p,integrationRef:m}=e,f=u?await Oe(t,m):null,h=await Rw({cwd:t,worktreePath:r.path,branches:n,integrationRef:m}),b={entries:h,pushed:!1,pushAborted:!1,declined:!1};if(DD(h,s),c)return{...b,selected:n};let C=await ND({entries:h,toPlan:n,all:i,explicit:a!==void 0});C.length===o.length?y.addOption("--all",!0):y.addOption("--versions",C);let k=h.filter(D=>C.includes(D.branch)&&D.mergeSha).length;k>0&&d.info(`
403
+ \u2139\uFE0F This will push ${k} branch(es), re-running CI on ${k} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await q(p,`Are you sure you want to merge ${m} into these branches: ${C.join(", ")}?`,{plan:LD(h,C,s)})}catch(D){if(!xe(D))throw D;return{...b,selected:C,declined:!0}}p||y.addOption("--yes",!0);let F=await _D({cwd:t,worktreePath:r.path,entries:h,selected:C,verify:l,integrationRef:m}),v=D=>h.filter(V=>C.includes(V.branch)&&D(V)).map(V=>V.branch),S=v(D=>D.status==="conflict"),P=v(D=>D.status==="merged"&&(F.verifyFailed?.has(D.branch)??!1)),O=u&&f&&S.length+P.length>0?await Jw({cwd:t,conflicted:S,verifyFailed:P,devSha:f,integrationRef:m,verify:l}):void 0;return{entries:h,selected:C,declined:!1,...F,handOffs:O}},LD=(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:lp(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),BD=(e,t,r)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
404
404
  `:`# ${e.branch} \u2014 ${e.status}
405
- ${TD(e.branch,t,r)}
406
- `,_D=(e,t)=>e!==void 0&&t?`${e}
407
- hand-off: ${t}`:e??t,MD=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p,integrationRef:m}=e,f=new Set(n?t.filter(k=>r.includes(k.branch)&&k.mergeSha&&!l?.has(k.branch)).map(k=>k.branch):[]),h=t.filter(k=>r.includes(k.branch)).map(k=>{let F=!!k.mergeSha,v=l?.has(k.branch)??!1,S=l?.get(k.branch),P=o&&F?"push-aborted":k.status,O=v?"verify-failed":P,D=u?.get(k.branch);return{branch:k.branch,status:O,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:f.has(k.branch),reason:_D(S,D?.reason)??k.reason,...D?.resolution?{resolution:D.resolution}:{}}}),b=h.filter(k=>!pp.has(k.status));for(let k of h){let F=t.find(v=>v.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:F?.durationMs,pushed:k.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
405
+ ${ID(e.branch,t,r)}
406
+ `,UD=(e,t)=>e!==void 0&&t?`${e}
407
+ hand-off: ${t}`:e??t,VD=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p,integrationRef:m}=e,f=new Set(n?t.filter(k=>r.includes(k.branch)&&k.mergeSha&&!l?.has(k.branch)).map(k=>k.branch):[]),h=t.filter(k=>r.includes(k.branch)).map(k=>{let F=!!k.mergeSha,v=l?.has(k.branch)??!1,S=l?.get(k.branch),P=o&&F?"push-aborted":k.status,O=v?"verify-failed":P,D=u?.get(k.branch);return{branch:k.branch,status:O,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:f.has(k.branch),reason:UD(S,D?.reason)??k.reason,...D?.resolution?{resolution:D.resolution}:{}}}),b=h.filter(k=>!mp.has(k.status));for(let k of h){let F=t.find(v=>v.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:F?.durationMs,pushed:k.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
408
408
  Operation cancelled \u2014 nothing was pushed.
409
409
  `:`
410
410
  \u{1F50D} Dry run \u2014 nothing was pushed.
411
411
  `);else if(b.length>0){d.info(`
412
412
  \u26A0\uFE0F ${b.length} branch(es) did not merge.
413
- `);for(let k of b)d.info(ND(k,c,m))}else d.info(`\u2705 All merges completed successfully!
414
- `);y.print();let C=a||i;return mp({successfulMerges:C?0:h.filter(k=>pp.has(k.status)).length,failedMerges:C?0:b.length,failedBranches:C?[]:b.map(k=>k.branch),totalBranches:h.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:h.map(k=>C?{...k,pushed:!1}:k),skipped:p})},fp=T({name:"gh-merge-dev",description:'Merge origin/dev (origin/main in a repo with "gitFlow": "main") into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.',requiresHumanConfirm:!0,inputSchema:{all:x.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:x.union([x.string(),x.array(x.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:x.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:x.union([x.boolean(),x.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:x.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch \u2014 and each clean merge that failed `verify` \u2014 mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:x.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:x.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:x.union([x.string(),x.array(x.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:x.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:x.number().describe("Number of branches that reached their desired state"),failedMerges:x.number().describe("Number of branches that did not"),failedBranches:x.array(x.string()).describe("List of branches that did not merge"),totalBranches:x.number().describe("Total number of branches processed"),dryRun:x.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:x.object({attempted:x.boolean(),aborted:x.boolean(),abortedBy:x.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:x.array(x.object({branch:x.string(),status:x.string(),mergeSha:x.string().optional(),conflictPaths:x.array(x.string()).optional(),pushed:x.boolean(),reason:x.string().optional(),resolution:x.object({worktreePath:x.string(),baseSha:x.string(),devSha:x.string(),conflictPaths:x.array(x.string()),editablePaths:x.array(x.string()).optional(),lockfileOnly:x.boolean(),rererePreResolved:x.array(x.string()),state:x.enum(["needs-agent","lockfile-only","verify-failed","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch, or for a clean merge that failed verify (`verify-failed`: edit only `editablePaths`)"),blocked:x.object({code:x.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:x.array(x.string()).optional(),detail:x.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:x.array(x.object({branch:x.string(),reason:x.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:sc});import{z as Ys}from"zod";import{$ as tt}from"zx";var qw=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},zr=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=qw(t.stderr,500);o&&(r.stderr=o);let s=qw(t.stdout,200);return s&&(r.stdout=s),r};var Ws="feature/",uo=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${Ws}${t}`};var Gs=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 Js=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=R(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw te()?new A({status:"partial_failure",...n},1,s):new g(void 0,s)};import ic from"node:fs/promises";import{$ as hp}from"zx";var jD=new Set([".omc",".DS_Store"]),FD=new Set(["state","sessions"]),LD=2e3,Zw="check 'git worktree list' for the path; uncommitted changes block removal",BD=e=>new Promise(t=>{setTimeout(t,e)}),gp=e=>typeof e=="object"&&e!==null?e.code:void 0,zw=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Yw=async e=>{try{return zw(await ic.realpath(e))}catch{return zw(e)}},UD=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await gt(t),o=await Yw(r);for(let s of n)if(await Yw(s.path)===o)return!0;return!1}catch{return!0}},VD=async e=>{let t;try{t=await ic.readdir(e)}catch(n){return{kind:gp(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>jD.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await ic.readdir(`${e}/.omc`)).every(s=>FD.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:gp(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Xw=async e=>{try{return await ic.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return gp(t)==="ENOTEMPTY"?"busy":"failed"}},WD=async e=>{let{worktreePath:t,sleep:r}=e,n=await Xw(t);return n!=="busy"?n==="removed":(await r(LD),await Xw(t)==="removed")},Ks=(e,t,r)=>{let n=new g(t,{operation:`remove worktree for ${e}`,remediation:r});return d.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},GD=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await UD({projectRoot:n,worktreePath:r}))return Ks(t,o,Zw);let i=await VD(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 WD({worktreePath:r,sleep:s})?Ks(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"})},JD=async e=>{try{return(await hp`git -C ${e} status --porcelain`).stdout.split(`
415
- `).filter(r=>r.trim().length>0)}catch{return[]}},KD=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await JD(i);if(a.length>0)return Ks(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),Zw);let c=await Dg(i,o);if(!c.closed&&"error"in c)return Ks(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await hp`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return GD({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=BD}=e,i=t.length>0?await tr():"unreachable",a=await Promise.all(t.map(l=>KD({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 hp`git worktree prune`,c};var Hs=async(e,t)=>{if(!(await Pe("release")).includes(e))return[];let n=await $(),o=`${n}${le}`,{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 g(void 0,{...t,stderrExcerpt:a?.reason})}return s};import{$ as yp}from"zx";var qs=async(e,t)=>{let r=await yp({quiet:!0,nothrow:!0})`git merge-tree --write-tree --name-only --no-messages ${e} ${t}`;if(r.exitCode!==0&&r.exitCode!==1)throw new g(new Error(r.stderr),{operation:`rehearse merging ${t} into ${e}`,remediation:"git merge-tree --write-tree needs git >= 2.38; check `git --version` and that both refs exist"});let[n="",...o]=r.stdout.trim().split(`
416
- `);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},Qw=async(e,t)=>(await yp({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),zs=(e,t)=>{if(t.conflicts.length!==0)throw new g(void 0,{operation:`deliver: ${e} would conflict`,remediation:`resolve the conflicts in ${t.conflicts.join(", ")}, push, then re-run`})},ek=async e=>{let{releaseBranch:t,viaIntegration:r,syncsDev:n,releaseMerged:o,rcMerged:s}=e,i=`origin/${t}`;if(await yp({quiet:!0})`git fetch origin main ${n?["dev"]:[]} ${o?[]:[t]}`,!r){let c="origin/main";if(!o){let l=await qs("origin/main",i);zs(`merging ${t} into main`,l),c=await Qw(l.tree,"origin/main")}n&&zs("syncing main back into dev",await qs("origin/dev",c));return}let a="origin/dev";if(!o){let c=await qs("origin/dev",i);zs(`merging ${t} into dev`,c),a=await Qw(c.tree,"origin/dev")}s?zs("syncing main back into dev",await qs(a,"origin/main")):zs("merging dev into main (RC PR)",await qs("origin/main",a))};var po=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:zr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},rk=async e=>{let t=dl(e),r=await tt`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},tk=async()=>{let e=await tt`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},HD=async(e,t)=>{let r=Wt(e),n=await ep(r);if(n.length>1){let i=n.map(a=>`#${a.number} \u2192 ${a.baseRefName}`).join(", ");throw new g(void 0,{operation:`deliver release ${r}`,remediation:`the branch has open PRs to both dev and main (${i}); close the one that should not be delivered`})}let o=n[0]??await ao(r);if(!o)throw d.error(`\u274C No PR found for branch ${r}.`),new g(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});let s=Ns(o.baseRefName,t);if(!s){let i=t==="dev"?"dev nor main":`${ke} (this repo's "gitFlow": "main")`,a=t==="dev"?"<dev|main>":ke;throw new g(void 0,{operation:`deliver release ${r}`,remediation:`PR #${o.number} targets '${o.baseRefName}', which is ${t==="dev"?"neither":"not"} ${i}; retarget it ('gh pr edit ${o.number} --base ${a}')`})}return{selectedReleaseBranch:r,releaseType:s,prNumber:o.number}},qD=async()=>{let e=await K(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));y.setInteractive();let n=await ye(),o=await mr(ve({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new g(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},zD=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n,flow:o}=e,s=Pt(r,o),i=await Qa(n);if(i.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(i.state==="CLOSED")throw new g(void 0,{operation:`merge release PR ${t} into ${s}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(i.baseRefName!==s||i.headRefName!==t)throw new g(void 0,{operation:`merge release PR #${n} ${t} into ${s}`,remediation:`PR #${n} now reads ${i.headRefName} \u2192 ${i.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await po(`merge release PR #${n} ${t} into ${s}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await tt`gh pr merge ${n} --squash --admin --delete-branch`})},YD=async e=>{let t=ae(e),r=dl(e),n=await tk();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 po(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await tt`gh pr edit ${s} --title ${r}`})),s}await po(`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 tt`gh pr create --base main --head dev --title ${r} --body ""`});let o=await tk();if(!o)throw new g(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},XD=async e=>{let t=ae(e);if(await rk(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await YD(e);await po(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await tt`gh pr merge ${n} --squash --admin`})},ZD=async()=>{tt.quiet=!1,await po("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await tt`gh workflow run deploy-all.yml --ref main -f environment=prod`}),tt.quiet=!0},QD=async()=>{await po("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 tt`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},eI=async e=>{try{await Li(e)}catch(t){d.warn({err:zr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Bi(e)}catch(t){d.warn({err:zr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},tI=async e=>{let t=await Bt();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=pe(e);await ld({versionName:r},t)}catch(r){let n=Rs(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:zr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},ac=async e=>{let{version:t,confirmedCommand:r}=e;await Be({operation:"deliver release"});let n=await ne(),{selectedReleaseBranch:o,releaseType:s,prNumber:i}=t?await HD(t,n):await qD(),a=n==="dev"&&s!=="hotfix",c=re(o);if(!c)throw new g(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=ae(c);if(y.addOption("--version",l),d.info(`Delivering ${c.kind==="name"?"named release":"version"} ${o}`),te())throw new A({status:"refused",agentMode:N.source},2,{operation:`deliver release ${o}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await ek({releaseBranch:o,viaIntegration:a,syncsDev:n==="dev",releaseMerged:(await Qa(i)).state==="MERGED",rcMerged:a&&await rk(c)!==null}),await q(r,`Are you sure you want to deliver version ${o} to production?`),y.addOption("--yes",!0),tt.quiet=!0;let p=`${await $()}${le}`;await Hs(o,{operation:`remove worktree for ${o} before merge`,remediation:`run manually: git worktree remove ${p}/${o} (use --force if uncommitted changes)`}),await zD({selectedReleaseBranch:o,releaseType:s,prNumber:i,flow:n}),a&&await XD(c),await ZD(),n==="dev"&&await QD(),await eI(o),tt.quiet=!1,await tI(c),d.info(`Successfully delivered ${o} to production!`),y.print();let m={releaseBranch:o,version:l,type:s,success:!0};return{content:R(JSON.stringify(m,null,2)),structuredContent:m}},vp=T({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes, and for every release in a repo with "gitFlow": "main" (no dev branch, no RC PR, no back-sync): squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:Ys.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:Ys.string().describe("The release branch that was delivered"),version:Ys.string().describe("The version that was delivered"),type:Ys.enum(["regular","hotfix"]).describe("Release type"),success:Ys.boolean().describe("Whether the delivery was successful")},handler:ac});import{z as hr}from"zod";var cc=async()=>{let t=(await K()).flatMap(i=>{let a=re(i.branch);return a?[{version:ae(a),jiraKey:pe(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await qa(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Ms(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:
413
+ `);for(let k of b)d.info(BD(k,c,m))}else d.info(`\u2705 All merges completed successfully!
414
+ `);y.print();let C=a||i;return fp({successfulMerges:C?0:h.filter(k=>mp.has(k.status)).length,failedMerges:C?0:b.length,failedBranches:C?[]:b.map(k=>k.branch),totalBranches:h.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:h.map(k=>C?{...k,pushed:!1}:k),skipped:p})},gp=T({name:"gh-merge-dev",description:'Merge origin/dev (origin/main in a repo with "gitFlow": "main") into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.',requiresHumanConfirm:!0,inputSchema:{all:x.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:x.union([x.string(),x.array(x.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:x.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:x.union([x.boolean(),x.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:x.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch \u2014 and each clean merge that failed `verify` \u2014 mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:x.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:x.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:x.union([x.string(),x.array(x.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:x.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:x.number().describe("Number of branches that reached their desired state"),failedMerges:x.number().describe("Number of branches that did not"),failedBranches:x.array(x.string()).describe("List of branches that did not merge"),totalBranches:x.number().describe("Total number of branches processed"),dryRun:x.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:x.object({attempted:x.boolean(),aborted:x.boolean(),abortedBy:x.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:x.array(x.object({branch:x.string(),status:x.string(),mergeSha:x.string().optional(),conflictPaths:x.array(x.string()).optional(),pushed:x.boolean(),reason:x.string().optional(),resolution:x.object({worktreePath:x.string(),baseSha:x.string(),devSha:x.string(),conflictPaths:x.array(x.string()),editablePaths:x.array(x.string()).optional(),lockfileOnly:x.boolean(),rererePreResolved:x.array(x.string()),state:x.enum(["needs-agent","lockfile-only","verify-failed","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch, or for a clean merge that failed verify (`verify-failed`: edit only `editablePaths`)"),blocked:x.object({code:x.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:x.array(x.string()).optional(),detail:x.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:x.array(x.object({branch:x.string(),reason:x.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:sc});import{z as Ys}from"zod";import{$ as tt}from"zx";var Qw=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},zr=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=Qw(t.stderr,500);o&&(r.stderr=o);let s=Qw(t.stdout,200);return s&&(r.stdout=s),r};var Ws="feature/",po=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${Ws}${t}`};var Gs=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 Js=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=R(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw te()?new A({status:"partial_failure",...n},1,s):new g(void 0,s)};import ic from"node:fs/promises";import{$ as yp}from"zx";var WD=new Set([".omc",".DS_Store"]),GD=new Set(["state","sessions"]),JD=2e3,nk="check 'git worktree list' for the path; uncommitted changes block removal",KD=e=>new Promise(t=>{setTimeout(t,e)}),hp=e=>typeof e=="object"&&e!==null?e.code:void 0,ek=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},tk=async e=>{try{return ek(await ic.realpath(e))}catch{return ek(e)}},HD=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await gt(t),o=await tk(r);for(let s of n)if(await tk(s.path)===o)return!0;return!1}catch{return!0}},qD=async e=>{let t;try{t=await ic.readdir(e)}catch(n){return{kind:hp(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>WD.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await ic.readdir(`${e}/.omc`)).every(s=>GD.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:hp(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},rk=async e=>{try{return await ic.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return hp(t)==="ENOTEMPTY"?"busy":"failed"}},zD=async e=>{let{worktreePath:t,sleep:r}=e,n=await rk(t);return n!=="busy"?n==="removed":(await r(JD),await rk(t)==="removed")},Ks=(e,t,r)=>{let n=new g(t,{operation:`remove worktree for ${e}`,remediation:r});return d.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},YD=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await HD({projectRoot:n,worktreePath:r}))return Ks(t,o,nk);let i=await qD(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 zD({worktreePath:r,sleep:s})?Ks(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"})},XD=async e=>{try{return(await yp`git -C ${e} status --porcelain`).stdout.split(`
415
+ `).filter(r=>r.trim().length>0)}catch{return[]}},ZD=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await XD(i);if(a.length>0)return Ks(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),nk);let c=await Mg(i,o);if(!c.closed&&"error"in c)return Ks(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await yp`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return YD({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=KD}=e,i=t.length>0?await rr():"unreachable",a=await Promise.all(t.map(l=>ZD({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 yp`git worktree prune`,c};var Hs=async(e,t)=>{if(!(await Pe("release")).includes(e))return[];let n=await $(),o=`${n}${le}`,{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 g(void 0,{...t,stderrExcerpt:a?.reason})}return s};import{$ as vp}from"zx";var qs=async(e,t)=>{let r=await vp({quiet:!0,nothrow:!0})`git merge-tree --write-tree --name-only --no-messages ${e} ${t}`;if(r.exitCode!==0&&r.exitCode!==1)throw new g(new Error(r.stderr),{operation:`rehearse merging ${t} into ${e}`,remediation:"git merge-tree --write-tree needs git >= 2.38; check `git --version` and that both refs exist"});let[n="",...o]=r.stdout.trim().split(`
416
+ `);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},ok=async(e,t)=>(await vp({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),zs=(e,t)=>{if(t.conflicts.length!==0)throw new g(void 0,{operation:`deliver: ${e} would conflict`,remediation:`resolve the conflicts in ${t.conflicts.join(", ")}, push, then re-run`})},sk=async e=>{let{releaseBranch:t,viaIntegration:r,syncsDev:n,releaseMerged:o,rcMerged:s}=e,i=`origin/${t}`;if(await vp({quiet:!0})`git fetch origin main ${n?["dev"]:[]} ${o?[]:[t]}`,!r){let c="origin/main";if(!o){let l=await qs("origin/main",i);zs(`merging ${t} into main`,l),c=await ok(l.tree,"origin/main")}n&&zs("syncing main back into dev",await qs("origin/dev",c));return}let a="origin/dev";if(!o){let c=await qs("origin/dev",i);zs(`merging ${t} into dev`,c),a=await ok(c.tree,"origin/dev")}s?zs("syncing main back into dev",await qs(a,"origin/main")):zs("merging dev into main (RC PR)",await qs("origin/main",a))};var mo=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:zr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},ak=async e=>{let t=pl(e),r=await tt`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},ik=async()=>{let e=await tt`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},QD=async(e,t)=>{let r=Gt(e),n=await tp(r);if(n.length>1){let i=n.map(a=>`#${a.number} \u2192 ${a.baseRefName}`).join(", ");throw new g(void 0,{operation:`deliver release ${r}`,remediation:`the branch has open PRs to both dev and main (${i}); close the one that should not be delivered`})}let o=n[0]??await co(r);if(!o)throw d.error(`\u274C No PR found for branch ${r}.`),new g(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});let s=Ns(o.baseRefName,t);if(!s){let i=t==="dev"?"dev nor main":`${ke} (this repo's "gitFlow": "main")`,a=t==="dev"?"<dev|main>":ke;throw new g(void 0,{operation:`deliver release ${r}`,remediation:`PR #${o.number} targets '${o.baseRefName}', which is ${t==="dev"?"neither":"not"} ${i}; retarget it ('gh pr edit ${o.number} --base ${a}')`})}return{selectedReleaseBranch:r,releaseType:s,prNumber:o.number}},eI=async()=>{let e=await K(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));y.setInteractive();let n=await ye(),o=await mr(ve({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new g(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},tI=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n,flow:o}=e,s=xt(r,o),i=await Qa(n);if(i.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(i.state==="CLOSED")throw new g(void 0,{operation:`merge release PR ${t} into ${s}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(i.baseRefName!==s||i.headRefName!==t)throw new g(void 0,{operation:`merge release PR #${n} ${t} into ${s}`,remediation:`PR #${n} now reads ${i.headRefName} \u2192 ${i.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await mo(`merge release PR #${n} ${t} into ${s}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await tt`gh pr merge ${n} --squash --admin --delete-branch`})},rI=async e=>{let t=ae(e),r=pl(e),n=await ik();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 mo(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await tt`gh pr edit ${s} --title ${r}`})),s}await mo(`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 tt`gh pr create --base main --head dev --title ${r} --body ""`});let o=await ik();if(!o)throw new g(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},nI=async e=>{let t=ae(e);if(await ak(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await rI(e);await mo(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await tt`gh pr merge ${n} --squash --admin`})},oI=async()=>{tt.quiet=!1,await mo("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await tt`gh workflow run deploy-all.yml --ref main -f environment=prod`}),tt.quiet=!0},sI=async()=>{await mo("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 tt`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},iI=async e=>{try{await Li(e)}catch(t){d.warn({err:zr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Bi(e)}catch(t){d.warn({err:zr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},aI=async e=>{let t=await Ut();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=pe(e);await ud({versionName:r},t)}catch(r){let n=Rs(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:zr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},ac=async e=>{let{version:t,confirmedCommand:r}=e;await Be({operation:"deliver release"});let n=await ne(),{selectedReleaseBranch:o,releaseType:s,prNumber:i}=t?await QD(t,n):await eI(),a=n==="dev"&&s!=="hotfix",c=re(o);if(!c)throw new g(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=ae(c);if(y.addOption("--version",l),d.info(`Delivering ${c.kind==="name"?"named release":"version"} ${o}`),te())throw new A({status:"refused",agentMode:N.source},2,{operation:`deliver release ${o}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await sk({releaseBranch:o,viaIntegration:a,syncsDev:n==="dev",releaseMerged:(await Qa(i)).state==="MERGED",rcMerged:a&&await ak(c)!==null}),await q(r,`Are you sure you want to deliver version ${o} to production?`),y.addOption("--yes",!0),tt.quiet=!0;let p=`${await $()}${le}`;await Hs(o,{operation:`remove worktree for ${o} before merge`,remediation:`run manually: git worktree remove ${p}/${o} (use --force if uncommitted changes)`}),await tI({selectedReleaseBranch:o,releaseType:s,prNumber:i,flow:n}),a&&await nI(c),await oI(),n==="dev"&&await sI(),await iI(o),tt.quiet=!1,await aI(c),d.info(`Successfully delivered ${o} to production!`),y.print();let m={releaseBranch:o,version:l,type:s,success:!0};return{content:R(JSON.stringify(m,null,2)),structuredContent:m}},wp=T({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes, and for every release in a repo with "gitFlow": "main" (no dev branch, no RC PR, no back-sync): squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:Ys.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:Ys.string().describe("The release branch that was delivered"),version:Ys.string().describe("The version that was delivered"),type:Ys.enum(["regular","hotfix"]).describe("Release type"),success:Ys.boolean().describe("Whether the delivery was successful")},handler:ac});import{z as hr}from"zod";var cc=async()=>{let t=(await K()).flatMap(i=>{let a=re(i.branch);return a?[{version:ae(a),jiraKey:pe(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await qa(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Ms(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:
417
417
  `),d.info(`
418
418
  ${o.join(`
419
419
  `)}
420
- `);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}},wp=T({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:hr.array(hr.object({version:hr.string().describe("Release version"),type:hr.enum(["regular","hotfix"]).describe("Release type"),description:hr.string().nullable().describe("Jira version description"),releaseDate:hr.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:hr.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:hr.number().describe("Number of release branches")},handler:cc});import rI from"node:process";var Xs="local-deploy";var kp=e=>({...e}),bp=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=rI.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1",INFRA_KIT_DEPLOY_VIA:Xs},contract:i,stripped:c}},lc=e=>{let t=Object.entries(e.contract).map(([r,n])=>` ${r.padEnd(17)}= ${n}`);return e.stripped.length>0&&t.push(` stripped from shell: ${e.stripped.join(", ")}`),t.join(`
421
- `)};import tN from"@inquirer/checkbox";import rN from"@inquirer/confirm";import nN from"@inquirer/select";import{spawn as oN}from"node:child_process";import Fp from"node:process";import{z as oe}from"zod";import{$ as ii}from"zx";import{z as ri}from"zod";import pk from"node:fs/promises";import $p from"node:path";import{DEPLOY_CONFIG_FILE as uc,deployConfigSchema as nI}from"@slip-stream-kit/config/internal";import oI from"node:fs/promises";import sI from"node:path";import{pathToFileURL as iI}from"node:url";import{z as aI}from"zod";var xt=async e=>{let t=sI.join(e,uc);try{await oI.access(t)}catch{return}let r=await import(iI(t).href);if(r.default===void 0)throw new Error(`${uc} at ${t} has no default export`);let n=nI.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${uc} at ${t}:
422
- ${aI.prettifyError(n.error)}`);let o=[...lI(n.data),...cI(n.data)];if(o.length>0)throw new Error(`Invalid ${uc} at ${t}:
420
+ `);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}},kp=T({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:hr.array(hr.object({version:hr.string().describe("Release version"),type:hr.enum(["regular","hotfix"]).describe("Release type"),description:hr.string().nullable().describe("Jira version description"),releaseDate:hr.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:hr.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:hr.number().describe("Number of release branches")},handler:cc});import cI from"node:process";var Xs="local-deploy";var bp=e=>({...e}),Rp=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=cI.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1",INFRA_KIT_DEPLOY_VIA:Xs},contract:i,stripped:c}},lc=e=>{let t=Object.entries(e.contract).map(([r,n])=>` ${r.padEnd(17)}= ${n}`);return e.stripped.length>0&&t.push(` stripped from shell: ${e.stripped.join(", ")}`),t.join(`
421
+ `)};import aN from"@inquirer/checkbox";import cN from"@inquirer/confirm";import lN from"@inquirer/select";import{spawn as uN}from"node:child_process";import Lp from"node:process";import{z as oe}from"zod";import{$ as ii}from"zx";import{z as ri}from"zod";import yk from"node:fs/promises";import Ap from"node:path";import{DEPLOY_CONFIG_FILE as uc,deployConfigSchema as lI}from"@slip-stream-kit/config/internal";import uI from"node:fs/promises";import dI from"node:path";import{pathToFileURL as pI}from"node:url";import{z as mI}from"zod";var Tt=async e=>{let t=dI.join(e,uc);try{await uI.access(t)}catch{return}let r=await import(pI(t).href);if(r.default===void 0)throw new Error(`${uc} at ${t} has no default export`);let n=lI.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${uc} at ${t}:
422
+ ${mI.prettifyError(n.error)}`);let o=[...gI(n.data),...fI(n.data)];if(o.length>0)throw new Error(`Invalid ${uc} at ${t}:
423
423
  ${o.join(`
424
- `)}`);return n.data},cI=e=>e.replaceV1!==!0?[]:ks.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),lI=e=>{let t=new Set([...e.environments,...ks]);return Object.entries(e.services).flatMap(([r,n])=>["envs","skipEnvs"].flatMap(o=>(n[o]??[]).filter(s=>!t.has(s)).map(s=>`\u2716 services.${r}.${o}: unknown environment '${s}' (known: ${[...t].join(", ")})`)))};var Zs=e=>{let t=new Map;for(let[r,n]of Object.entries(e.services)){if(n.envs!==void 0){t.set(r,[...n.envs]);continue}let o=n.skipEnvs??[],s=e.environments.filter(i=>!o.includes(i));s.length<e.environments.length&&t.set(r,s)}return t};import{serviceDependencies as uI}from"@slip-stream-kit/config/internal";var ik="28aac6de980c6073d37a872c78309134bf62c47c",ak=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${ik}`,dI=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${ik}`,fc="install-deps",nk=25,mo="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",gc="skip_terraform_deploy",ck={pilot:{all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected"}},v1:{all:{file:"deploy-all.yml",title:"01 \u2699\uFE0F Deploy all",concurrency:"deploy-all"},selected:{file:"deploy-selected-services.yml",title:"02 \u2699\uFE0F Deploy selected services",concurrency:"deploy-selected"}}},lk=(e,t)=>ck[e.replaceV1===!0?"v1":"pilot"][t],uk=e=>Object.values(ck[e]).map(({file:t})=>`.github/workflows/${t}`),Rp=uk("pilot"),Sp=uk("v1"),pc=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),pI=(e,t)=>{let r=Object.entries(e.services).flatMap(([o,s])=>{if(t==="all"&&s.deployAll===!1)return[];let i=t==="all"&&Array.isArray(s.deployAll)?s.deployAll:void 0,a=e.environments.filter(c=>(s.envs?.includes(c)??!0)&&!(s.skipEnvs?.includes(c)??!1)&&(i?.includes(c)??!0));return a.length===0?[]:[{name:o,service:s,gate:a.length===e.environments.length?void 0:a,triggers:void 0}]}),n=new Set(r.map(o=>o.name));return r.flatMap(o=>{if(o.service.runsBefore===void 0)return[o];let s=o.service.runsBefore.filter(i=>n.has(i));return s.length===0?[]:[{...o,triggers:s}]})},Ep=e=>e.filter(t=>t.triggers===void 0),Q=e=>`\${{ ${e} }}`,dc=e=>Q(`secrets[format('{0}_${e}', inputs.environment)]`),mI=e=>[fc,...e.terraform,...e.preDeploy],Pp=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),fI=e=>[`needs.${fc}.result == 'success'`,...Pp(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],gI=(e,t,r,n)=>{let o=[];return t==="selected"&&o.push(e.triggers===void 0?`inputs.${e.name}`:`(${e.triggers.map(s=>`inputs.${s}`).join(" || ")})`),e.gate!==void 0&&o.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),o.push("!cancelled()",...fI(r),...Pp(n.map(mc))),Q(o.join(" && "))},mc=e=>`deploy-${e}`,xp=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],dk=e=>e===void 0?[]:[` if: ${e}`],Tp=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${Q("github.ref")}`,` environment: ${Q("inputs.environment")}`," secrets: inherit"],hI=(e,t)=>{let r=t.extraEnv??[],n=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],o=t.deployTimeoutMinutes===void 0?[]:[` timeout-minutes: ${t.deployTimeoutMinutes}`],s=r.length===0?[]:[" extra-env: |",...r.map(i=>{let a=Q(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${ak}`," with:",` environment: ${Q("inputs.environment")}`,` ref: ${Q("github.ref")}`,` sha: ${Q("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${U.version}`,...n,...o,...t.doppler===void 0?[]:[` doppler-project: ${t.doppler.project}`]," secrets:",...t.doppler===void 0?[` aws-access-key-id: ${dc("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${dc("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${dc("AWS_REGION")}`]:[` doppler-token: ${dc("DOPPLER_TOKEN")}`],` serverless-access-key: ${Q("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${Q("secrets.SLACK_TOKEN")}`,` slack-channel: ${Q("secrets.SLACK_CHANNEL")}`,...s]},yI=(e,t,r,n,o)=>{let s=e.service.workflow===void 0?hI(e,n):Tp(e.service.workflow);return["",` ${mc(e.name)}:`,...xp([...mI(r),...o.map(mc)]),...dk(gI(e,t,r,o)),...s]},ok=(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?ok(gc,"Skip terraform deployment"):[],s=t==="all"?[]:Ep(r).flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return ok(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},wI=e=>Ep(e).map(t=>Q(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),kI=(e,t,r)=>{let{title:n,concurrency:o}=lk(e,t),s=(e.terraform??[]).length>0?Q(`inputs.${gc} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${wI(r)}`:"";return[`${mo}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${Q("inputs.environment")}]${s}${i}'`,"",`# The v1 ${t==="all"?"deploy-all":"deploy-selected"} group: two runs of this kind, v1 or v2, never deploy into one`,"# environment at once.","concurrency:",` group: ${o}-${Q("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},bI=e=>{let t=Q(`!inputs.${gc}`);return["",` ${pc(e)}:`,` if: ${t}`,...Tp(e)]},RI=(e,t)=>{let r=t.length===0?void 0:Q(["!cancelled()",...Pp(t)].join(" && "));return["",` ${pc(e)}:`,...xp(t),...dk(r),...Tp(e)]},SI=()=>["",` ${fc}:`,` uses: ${dI}`," with:",` ref: ${Q("github.ref")}`,` sha: ${Q("github.sha")}`," secrets:",` slack-token: ${Q("secrets.SLACK_TOKEN")}`,` slack-channel: ${Q("secrets.SLACK_CHANNEL")}`],EI=(e,t)=>{let r=new Set;for(let n of e){if(r.has(n))throw new Error(`${t} would declare job \`${n}\` twice; rename one of the workflows`);r.add(n)}},PI=(e,t)=>[""," notify-success:",...xp(t),` if: ${Q("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],sk=(e,t)=>{let r=pI(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(pc),preDeploy:o.map(pc)},{file:i}=lk(e,t),a=1+(n.length>0?1:0)+(t==="selected"?Ep(r).length:0);if(a>nk){let h=n.length>0?`environment, ${gc}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${h} and one checkbox per service); GitHub allows ${nk}. Fold services that always deploy together into one deploy script.`)}let c=r.map(h=>mc(h.name)),l=new Set(r.map(h=>h.name)),u=uI(e.services),p=h=>(u.get(h)??[]).filter(b=>l.has(b));EI([fc,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let f=`${[...kI(e,t,r),...vI(e,t,r),"","permissions:"," contents: read","","jobs:",...SI(),...n.flatMap(bI),...o.flatMap(h=>RI(h,s.terraform)),...r.flatMap(h=>yI(h,t,s,e,p(h.name))),...e.notifySuccess===void 0?[]:PI(e.notifySuccess,c)].join(`
424
+ `)}`);return n.data},fI=e=>e.replaceV1!==!0?[]:ks.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),gI=e=>{let t=new Set([...e.environments,...ks]);return Object.entries(e.services).flatMap(([r,n])=>["envs","skipEnvs"].flatMap(o=>(n[o]??[]).filter(s=>!t.has(s)).map(s=>`\u2716 services.${r}.${o}: unknown environment '${s}' (known: ${[...t].join(", ")})`)))};var Zs=e=>{let t=new Map;for(let[r,n]of Object.entries(e.services)){if(n.envs!==void 0){t.set(r,[...n.envs]);continue}let o=n.skipEnvs??[],s=e.environments.filter(i=>!o.includes(i));s.length<e.environments.length&&t.set(r,s)}return t};import{serviceDependencies as hI}from"@slip-stream-kit/config/internal";var dk="28aac6de980c6073d37a872c78309134bf62c47c",pk=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${dk}`,yI=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${dk}`,fc="install-deps",ck=25,fo="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",gc="skip_terraform_deploy",mk={pilot:{all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected"}},v1:{all:{file:"deploy-all.yml",title:"01 \u2699\uFE0F Deploy all",concurrency:"deploy-all"},selected:{file:"deploy-selected-services.yml",title:"02 \u2699\uFE0F Deploy selected services",concurrency:"deploy-selected"}}},fk=(e,t)=>mk[e.replaceV1===!0?"v1":"pilot"][t],gk=e=>Object.values(mk[e]).map(({file:t})=>`.github/workflows/${t}`),Sp=gk("pilot"),Ep=gk("v1"),pc=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),vI=(e,t)=>{let r=Object.entries(e.services).flatMap(([o,s])=>{if(t==="all"&&s.deployAll===!1)return[];let i=t==="all"&&Array.isArray(s.deployAll)?s.deployAll:void 0,a=e.environments.filter(c=>(s.envs?.includes(c)??!0)&&!(s.skipEnvs?.includes(c)??!1)&&(i?.includes(c)??!0));return a.length===0?[]:[{name:o,service:s,gate:a.length===e.environments.length?void 0:a,triggers:void 0}]}),n=new Set(r.map(o=>o.name));return r.flatMap(o=>{if(o.service.runsBefore===void 0)return[o];let s=o.service.runsBefore.filter(i=>n.has(i));return s.length===0?[]:[{...o,triggers:s}]})},Pp=e=>e.filter(t=>t.triggers===void 0),Q=e=>`\${{ ${e} }}`,dc=e=>Q(`secrets[format('{0}_${e}', inputs.environment)]`),wI=e=>[fc,...e.terraform,...e.preDeploy],xp=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),kI=e=>[`needs.${fc}.result == 'success'`,...xp(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],bI=(e,t,r,n)=>{let o=[];return t==="selected"&&o.push(e.triggers===void 0?`inputs.${e.name}`:`(${e.triggers.map(s=>`inputs.${s}`).join(" || ")})`),e.gate!==void 0&&o.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),o.push("!cancelled()",...kI(r),...xp(n.map(mc))),Q(o.join(" && "))},mc=e=>`deploy-${e}`,Tp=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],hk=e=>e===void 0?[]:[` if: ${e}`],Cp=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${Q("github.ref")}`,` environment: ${Q("inputs.environment")}`," secrets: inherit"],RI=(e,t)=>{let r=t.extraEnv??[],n=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],o=t.deployTimeoutMinutes===void 0?[]:[` timeout-minutes: ${t.deployTimeoutMinutes}`],s=r.length===0?[]:[" extra-env: |",...r.map(i=>{let a=Q(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${pk}`," with:",` environment: ${Q("inputs.environment")}`,` ref: ${Q("github.ref")}`,` sha: ${Q("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${U.version}`,...n,...o,...t.doppler===void 0?[]:[` doppler-project: ${t.doppler.project}`]," secrets:",...t.doppler===void 0?[` aws-access-key-id: ${dc("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${dc("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${dc("AWS_REGION")}`]:[` doppler-token: ${dc("DOPPLER_TOKEN")}`],` serverless-access-key: ${Q("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${Q("secrets.SLACK_TOKEN")}`,` slack-channel: ${Q("secrets.SLACK_CHANNEL")}`,...s]},SI=(e,t,r,n,o)=>{let s=e.service.workflow===void 0?RI(e,n):Cp(e.service.workflow);return["",` ${mc(e.name)}:`,...Tp([...wI(r),...o.map(mc)]),...hk(bI(e,t,r,o)),...s]},lk=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],EI=(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?lk(gc,"Skip terraform deployment"):[],s=t==="all"?[]:Pp(r).flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return lk(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},PI=e=>Pp(e).map(t=>Q(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),xI=(e,t,r)=>{let{title:n,concurrency:o}=fk(e,t),s=(e.terraform??[]).length>0?Q(`inputs.${gc} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${PI(r)}`:"";return[`${fo}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${Q("inputs.environment")}]${s}${i}'`,"",`# The v1 ${t==="all"?"deploy-all":"deploy-selected"} group: two runs of this kind, v1 or v2, never deploy into one`,"# environment at once.","concurrency:",` group: ${o}-${Q("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},TI=e=>{let t=Q(`!inputs.${gc}`);return["",` ${pc(e)}:`,` if: ${t}`,...Cp(e)]},CI=(e,t)=>{let r=t.length===0?void 0:Q(["!cancelled()",...xp(t)].join(" && "));return["",` ${pc(e)}:`,...Tp(t),...hk(r),...Cp(e)]},$I=()=>["",` ${fc}:`,` uses: ${yI}`," with:",` ref: ${Q("github.ref")}`,` sha: ${Q("github.sha")}`," secrets:",` slack-token: ${Q("secrets.SLACK_TOKEN")}`,` slack-channel: ${Q("secrets.SLACK_CHANNEL")}`],AI=(e,t)=>{let r=new Set;for(let n of e){if(r.has(n))throw new Error(`${t} would declare job \`${n}\` twice; rename one of the workflows`);r.add(n)}},OI=(e,t)=>[""," notify-success:",...Tp(t),` if: ${Q("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],uk=(e,t)=>{let r=vI(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(pc),preDeploy:o.map(pc)},{file:i}=fk(e,t),a=1+(n.length>0?1:0)+(t==="selected"?Pp(r).length:0);if(a>ck){let h=n.length>0?`environment, ${gc}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${h} and one checkbox per service); GitHub allows ${ck}. Fold services that always deploy together into one deploy script.`)}let c=r.map(h=>mc(h.name)),l=new Set(r.map(h=>h.name)),u=hI(e.services),p=h=>(u.get(h)??[]).filter(b=>l.has(b));AI([fc,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let f=`${[...xI(e,t,r),...EI(e,t,r),"","permissions:"," contents: read","","jobs:",...$I(),...n.flatMap(TI),...o.flatMap(h=>CI(h,s.terraform)),...r.flatMap(h=>SI(h,t,s,e,p(h.name))),...e.notifySuccess===void 0?[]:OI(e.notifySuccess,c)].join(`
425
425
  `).replace(`jobs:
426
426
 
427
427
  `,`jobs:
428
428
  `)}
429
- `;return{path:`.github/workflows/${i}`,content:f}},Cp=e=>[sk(e,"all"),sk(e,"selected")];var mk=".github/workflows",xI=/script_name:\s*(?<service>[a-z0-9-]+)/,TI=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,CI=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Ap=async e=>{let t=$p.resolve(e,mk),r;try{r=await pk.readdir(t)}catch{return new Map}return fk(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Qs=async(e,t)=>fk(e,[t]),fk=async(e,t)=>{let r=$p.resolve(e,mk),n=new Map,o=!1;for(let s of t){let i;try{i=await pk.readFile($p.resolve(r,s),"utf-8")}catch{continue}i.startsWith(mo)?o=!0:AI(i,n)}return o&&gk(n,await $I(e)),n},$I=async e=>{try{let t=await xt(e);return t?.replaceV1===!0?Zs(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},gk=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},AI=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=xI.exec(r)?.groups?.service??TI.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(CI)].map(s=>s.groups?.env??"");o.length!==0&&gk(t,new Map([[n,o]]))}},ei=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import OI from"node:fs/promises";import DI from"node:path";import II from"yaml";var NI=".github/workflows",_I="skip_terraform_deploy",ti=async(e,t)=>{let r=DI.resolve(e,NI,t),n;try{n=II.parse(await OI.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!==_I).map(([i])=>i)};var Op=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hk=(e,t)=>e[t]===void 0,yk=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Dp=async e=>{try{return await e}catch{return[]}},MI=async()=>{let e=await K();return Gt(e.map(t=>t.branch))},jI=(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},Xr=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 Dp(MI());if(l.length===0)return null;let u=yk(c,"version"),p=await Gr();return ri.enum([...new Set([...l,p])]).optional().describe(`Which release to deploy from. "${p}" deploys from the ${p} branch instead of a release branch. ${u===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${u}".`}`)},i=async c=>{let l=jt(await Dp(Ft(t)),await lt());if(l.length===0)return null;let u=l.filter(Kn),p=l.filter(f=>!Kn(f)),m=yk(c,"env");return ri.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await $(),l=await Dp(ti(c,t));if(l.length===0)return null;let u=await Qs(c,t);return ri.array(ri.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${jI(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=>Op(c)?r.some(l=>hk(c,l)):!1,buildRequestedSchema:async c=>{let l=Op(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")&&hk(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):ri.object(u)},toArgs:(c,l)=>{let u={...Op(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 FI from"@inquirer/select";var fo=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return _(r=>FI({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import{$ as ni}from"zx";var LI=async e=>{let t=ni.quiet;ni.quiet=!0;try{let r=`/${e}/environment`,n=await ni`aws sts get-caller-identity --query Account --output text`,o=await ni`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new g(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{ni.quiet=t}},vk=(e,t)=>{if(t.stage!==e)throw new g(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},wk=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new g(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},kk=(e,t)=>{if(t.includes(e))throw new g(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Ip=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;jr(t,`deploy to "${t}"`,i),kk(t,s),wk({env:t,isShared:n,isClean:o});let a=await LI(r);return vk(t,a),{identity:a}};import{serviceDependencies as BI}from"@slip-stream-kit/config/internal";import Np from"node:fs/promises";import oi from"node:path";var Sk="devops/scripts",UI=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,VI=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,WI=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,GI=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,JI=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,KI=/`[^`]*\$\{[^`]*\/environment[^`]*`/,bk={commentPrefixes:["#"],literalPrefix:e=>GI.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=WI.exec(e)?.groups?.arg;return t!==void 0&&XI(t)}},Rk={commentPrefixes:["//","/*","*"],literalPrefix:e=>JI.exec(e)?.groups?.prefix,isUnparseable:e=>KI.test(e)},_p=async e=>{let t=await xt(e),r=await Ap(e);return(t===void 0?await HI(e,r):await qI(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},HI=async(e,t)=>{let r=oi.resolve(e,Sk),n;try{n=await Np.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=UI.exec(o)?.groups?.service;return s===void 0?[]:[Ek(s,oi.resolve(r,o),t)]}))},Ek=async(e,t,r)=>{let n=xk(await Pk(t),bk);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:ei(YI(n),r.get(e)),ssmPrefix:Tk(n,bk)}},qI=async(e,t,r)=>{let n=Zs(t),o=BI(t.services),s=(a,c)=>({...(o.get(a)??[]).length===0?{}:{dependsOn:o.get(a)},...c.runsBefore===void 0?{}:{runsBefore:[...c.runsBefore]}});return(await Promise.all(Object.entries(t.services).map(async([a,c])=>{if(c.deploy===void 0){let p=oi.resolve(e,Sk,`deploy-${a}.sh`);if(!await zI(p))return null;let m=await Ek(a,p,r);return{...m,allowedEnvs:ei(m.allowedEnvs,n.get(a)),...s(a,c)}}let l=oi.resolve(e,c.deploy),u=xk(await Pk(l),Rk);return{name:a,scriptPath:l,runner:"deploy-run",allowedEnvs:ei(n.get(a)??null,r.get(a)),ssmPrefix:Tk(u,Rk),...s(a,c)}}))).filter(a=>a!==null)},zI=async e=>{try{return await Np.access(e),!0}catch{return!1}},Pk=async e=>{try{return await Np.readFile(e,"utf-8")}catch{return""}},xk=(e,t)=>e.split(`
430
- `).map((r,n)=>({line:n+1,text:r})).filter(({text:r})=>{let n=r.trimStart();return!t.commentPrefixes.some(o=>n.startsWith(o))}),YI=e=>{let t=e.reduce((n,{text:o})=>n??VI.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},XI=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Tk=(e,t)=>{for(let{line:r,text:n}of e){let o=t.literalPrefix(n);if(o!==void 0)return o;if(t.isUnparseable(n))return{unparseable:{line:r,text:n.trim()}}}return null},Ck=e=>{let t=oi.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},ZI=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ck(r)]);return t},QI=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ck(r)}:${n}: ${o}`]});if(t.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},eN=e=>{QI(e);let t=ZI(e),[r,...n]=t.keys();if(r===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'read the literal "/<project>/environment" in at least one deploy script: a deploy.ts in infra-kit.deploy.ts, or `aws ssm get-parameter --name "/<project>/environment"` in a devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},$k=async(e,t)=>(await xt(e))?.project??eN(t),si=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Mp=(e,t)=>e.filter(r=>r.runsBefore===void 0&&si(r,t)),Ak=(e,t,r)=>{let n=new Set(e.map(l=>l.name)),o=t.filter(l=>!n.has(l.name)&&si(l,r)&&(l.runsBefore??[]).some(u=>n.has(u))),s=new Map([...o,...e].map(l=>[l.name,l])),i=[],a=new Set,c=l=>{if(!a.has(l.name)){a.add(l.name);for(let u of l.dependsOn??[]){let p=s.get(u);p!==void 0&&c(p)}i.push(l)}};for(let l of e)c(l);return i};var Lp="deploy-all.yml",sN="/bin/sh",iN=async()=>{let e=ii.quiet;ii.quiet=!0;try{let t=await ii`gh run list --workflow=${Lp} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{ii.quiet=e}},aN=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await _(o=>tN({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},cN=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return H()&&Hi(i,{env:t,services:n,accountId:o,shared:r}),r?_(a=>nN({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):_(a=>rN({message:i,default:!1},a),{whenHeadless:"refuse"})},Dk=e=>e.runner==="sh"?[sN,[e.scriptPath]]:[Fp.execPath,[Fp.argv[1]??"","deploy-run",e.name]],lN=(e,t,r)=>new Promise((n,o)=>{let[s,i]=Dk(e),a=oN(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),uN=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 lN(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}},dN=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new g(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!si(c,n)});if(i.length>0)throw new g(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},jp=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:kp(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},pN=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(y.setInteractive(),aN(r,o))},Ik=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await $(),c=await _p(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has infra-kit.deploy.ts or devops/scripts/deploy-*.sh",stderrExcerpt:`no deployable services found under ${a}`});let l=await $k(a,c);await et({provider:Bp[t],params:e,operation:"deploy locally",argument:"env"});let u=await lt(),p=jt(await Ft(Lp),u),m=r??"";m||(y.setInteractive(),m=await fo(p,"deploy locally")),y.addOption("--env",m);let f=Mp(c,m);if(f.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let h=await pN({selection:t,eligible:f,service:n,env:m}),b=Ak(dN({names:h,services:c,env:m}),c,m);if(t==="selected")for(let Re of h)y.addOption("--service",Re);let C=Kn(m),k=await dn(),F=(await ii`git rev-parse HEAD`.quiet()).stdout.trim(),v=await pg(),S=bp({env:m,branch:k,sha:F,isClean:v});i&&d.info(`Deploy contract for ${m}:
431
- ${lc(S)}`);let O=(await Ip({env:m,project:l,isShared:C,isClean:v,runningEnvs:await iN(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${O}) from this machine`,`Preflight parameter: /${l}/environment`,lc(S),"Commands:",...b.map(Re=>` ${Dk(Re).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
432
- `)),jp({env:m,accountId:O,names:h,built:S,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await cN({env:m,isShared:C,names:h,accountId:O}))return d.info("Deployment cancelled"),jp({env:m,accountId:O,names:h,built:S,deployed:[],failed:[],dryRun:!1,success:!1});S.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${S.stripped.join(", ")}`);let{deployed:D,failed:V}=await uN({chosen:b,childEnv:S.childEnv,cwd:a,env:m});return V.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${D.join(", ")||"none"}], failed [${V.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Fp.exitCode=1),y.print(),jp({env:m,accountId:O,names:h,built:S,deployed:D,failed:V,dryRun:!1,success:V.length===0})},Nk=async e=>Ik(e,"all"),_k=async e=>Ik(e,"selected"),Mk='Runs the repo\'s own deploys (infra-kit.deploy.ts via deploy-run, else devops/scripts/deploy-*.sh) on THIS machine instead of dispatching CI. Supplies the build contract (VITE_DOMAIN_ENV/BRANCH/COMMIT) that the workflow YAML normally provides and that the scripts do not set themselves, and refuses unless the requested environment matches the AWS account the shell is authenticated to. "prod" is refused by default \u2014 it is delivered, not deployed \u2014 and is reachable only if this project sets `protectedEnvs` in infra-kit.json; "cli-only" allows it in a terminal but still refuses it here. Services the environment forbids are refused, matching the workflow\'s own per-service gates. Use dryRun first.',jk={env:oe.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:oe.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:oe.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Fk={environment:oe.string().describe("Environment deployed to"),accountId:oe.string().describe("AWS account the deploy targeted"),services:oe.array(oe.string()).describe("Services requested"),deployed:oe.array(oe.string()).describe("Services that completed successfully"),failed:oe.array(oe.string()).describe("Services that failed"),contract:oe.record(oe.string(),oe.string()).describe("Build contract passed to the scripts"),strippedVars:oe.array(oe.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:oe.boolean().describe("Whether this was a dry run"),success:oe.boolean().describe("Whether every requested service deployed")},Ok=e=>Xr({workflowFile:Lp,fields:["env"],toolName:e}),Bp={all:Ok("local-deploy-all"),selected:Ok("local-deploy-selected")},Up=T({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Mk}`,requiresHumanConfirm:!0,formProvider:Bp.all,inputSchema:jk,outputSchema:Fk,handler:Nk}),Vp=T({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Mk}`,requiresHumanConfirm:!0,formProvider:Bp.selected,inputSchema:{...jk,service:oe.array(oe.string()).min(1).describe('Service names as in infra-kit.deploy.ts or devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Fk,handler:_k});import gN from"@inquirer/confirm";import hc from"@inquirer/input";import Vk from"@inquirer/select";import Gp from"node:process";import{z as Y}from"zod";import{z as ai}from"zod";var go=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Uk=2500,Lk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bk=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,mN=async()=>{let e=await xs();return{regular:to(e,"regular"),hotfix:to(e,"hotfix")}},fN=(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).`,Wp=(e={})=>{let t=e.hintBudgetMs??Uk;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=>Lk(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await go(mN(),t),n=await ne(),[o,...s]=so(n);return ai.object({type:ai.enum([o,...s]).describe(n==="main"?'Release type. This repo sets "gitFlow": "main", so every release is "regular": it branches off main and bumps the minor.':'Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:ai.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. ${fN(r,t)}`),description:ai.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:ai.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=Bk(r.description),a=Bk(r.releaseDate),c=Ma(o);return{...Lk(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var hN='"1.2.5" or "next"',Jp=(e,t)=>{try{return wd(e,t)}catch(r){throw r instanceof Ur?new g(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof cg?new g(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},yN=async(e,t)=>{let r=to(e,t),n=r?` [${r}]`:"",o=(await _(i=>hc({message:` Version (e.g. ${hN})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Gp.exit(1)),s},vN=async()=>{let e=(await _(t=>hc({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Gp.exit(1));try{Fi(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Gp.exit(1)}return e},wN=async()=>(await _(e=>hc({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Ps},e),{whenHeadless:"refuse"})).trim(),kN=async e=>{y.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await _(f=>Vk({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},f),{whenHeadless:"refuse"}),c=so(await ne()),l=c.length===1?c[0]:await _(f=>Vk({message:`Release #${i} \u2014 select type:`,choices:c.map(h=>({name:h,value:h})),default:"regular"},f),{whenHeadless:"refuse"}),u;if(a==="name"){let f=await vN();u=Jp([{name:f,type:l}],[])[0]}else{let f=await yN(await n(),l);u=Jp([{version:f,type:l}],r)[0],u.id.kind==="version"&&r.push(dr(`v${u.id.raw}`))}let p=(await _(f=>hc({message:" Description (optional, press Enter to skip): "},f),{whenHeadless:"refuse"})).trim(),m=await wN();o.push({...u,...p!==""?{description:p}:{},...m!==""?{releaseDate:m}:{}}),s=await _(f=>gN({message:"Add another release?",default:!1},f),{whenHeadless:"refuse"})}return o},bN=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 ")},Wk=e=>{for(let t of e)y.addOption("--release",vd(t))},RN=async(e,t)=>{if(e&&e.length>0){let n=kd(e)?await t():[],o=Jp(e,n);return Wk(o),o}if(te())throw new A({status:"argument_required",argument:"release",agentMode:N.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await kN(t);return Wk(r),r},SN=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new g(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},EN=async(e,t)=>{let r=e.map(bN).join(`
429
+ `;return{path:`.github/workflows/${i}`,content:f}},$p=e=>[uk(e,"all"),uk(e,"selected")];var vk=".github/workflows",DI=/script_name:\s*(?<service>[a-z0-9-]+)/,II=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,NI=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Op=async e=>{let t=Ap.resolve(e,vk),r;try{r=await yk.readdir(t)}catch{return new Map}return wk(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Qs=async(e,t)=>wk(e,[t]),wk=async(e,t)=>{let r=Ap.resolve(e,vk),n=new Map,o=!1;for(let s of t){let i;try{i=await yk.readFile(Ap.resolve(r,s),"utf-8")}catch{continue}i.startsWith(fo)?o=!0:MI(i,n)}return o&&kk(n,await _I(e)),n},_I=async e=>{try{let t=await Tt(e);return t?.replaceV1===!0?Zs(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},kk=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},MI=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=DI.exec(r)?.groups?.service??II.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(NI)].map(s=>s.groups?.env??"");o.length!==0&&kk(t,new Map([[n,o]]))}},ei=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import jI from"node:fs/promises";import FI from"node:path";import LI from"yaml";var BI=".github/workflows",UI="skip_terraform_deploy",ti=async(e,t)=>{let r=FI.resolve(e,BI,t),n;try{n=LI.parse(await jI.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!==UI).map(([i])=>i)};var Dp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),bk=(e,t)=>e[t]===void 0,Rk=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Ip=async e=>{try{return await e}catch{return[]}},VI=async()=>{let e=await K();return Jt(e.map(t=>t.branch))},WI=(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},Xr=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 Ip(VI());if(l.length===0)return null;let u=Rk(c,"version"),p=await Gr();return ri.enum([...new Set([...l,p])]).optional().describe(`Which release to deploy from. "${p}" deploys from the ${p} branch instead of a release branch. ${u===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${u}".`}`)},i=async c=>{let l=Ft(await Ip(Lt(t)),await lt());if(l.length===0)return null;let u=l.filter(Hn),p=l.filter(f=>!Hn(f)),m=Rk(c,"env");return ri.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await $(),l=await Ip(ti(c,t));if(l.length===0)return null;let u=await Qs(c,t);return ri.array(ri.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${WI(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=>Dp(c)?r.some(l=>bk(c,l)):!1,buildRequestedSchema:async c=>{let l=Dp(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")&&bk(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):ri.object(u)},toArgs:(c,l)=>{let u={...Dp(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 GI from"@inquirer/select";var go=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return _(r=>GI({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import{$ as ni}from"zx";var JI=async e=>{let t=ni.quiet;ni.quiet=!0;try{let r=`/${e}/environment`,n=await ni`aws sts get-caller-identity --query Account --output text`,o=await ni`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new g(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{ni.quiet=t}},Sk=(e,t)=>{if(t.stage!==e)throw new g(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},Ek=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new g(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},Pk=(e,t)=>{if(t.includes(e))throw new g(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Np=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;jr(t,`deploy to "${t}"`,i),Pk(t,s),Ek({env:t,isShared:n,isClean:o});let a=await JI(r);return Sk(t,a),{identity:a}};import{serviceDependencies as KI}from"@slip-stream-kit/config/internal";import _p from"node:fs/promises";import oi from"node:path";var Ck="devops/scripts",HI=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,qI=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,zI=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,YI=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,XI=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,ZI=/`[^`]*\$\{[^`]*\/environment[^`]*`/,xk={commentPrefixes:["#"],literalPrefix:e=>YI.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=zI.exec(e)?.groups?.arg;return t!==void 0&&nN(t)}},Tk={commentPrefixes:["//","/*","*"],literalPrefix:e=>XI.exec(e)?.groups?.prefix,isUnparseable:e=>ZI.test(e)},Mp=async e=>{let t=await Tt(e),r=await Op(e);return(t===void 0?await QI(e,r):await eN(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},QI=async(e,t)=>{let r=oi.resolve(e,Ck),n;try{n=await _p.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=HI.exec(o)?.groups?.service;return s===void 0?[]:[$k(s,oi.resolve(r,o),t)]}))},$k=async(e,t,r)=>{let n=Ok(await Ak(t),xk);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:ei(rN(n),r.get(e)),ssmPrefix:Dk(n,xk)}},eN=async(e,t,r)=>{let n=Zs(t),o=KI(t.services),s=(a,c)=>({...(o.get(a)??[]).length===0?{}:{dependsOn:o.get(a)},...c.runsBefore===void 0?{}:{runsBefore:[...c.runsBefore]}});return(await Promise.all(Object.entries(t.services).map(async([a,c])=>{if(c.deploy===void 0){let p=oi.resolve(e,Ck,`deploy-${a}.sh`);if(!await tN(p))return null;let m=await $k(a,p,r);return{...m,allowedEnvs:ei(m.allowedEnvs,n.get(a)),...s(a,c)}}let l=oi.resolve(e,c.deploy),u=Ok(await Ak(l),Tk);return{name:a,scriptPath:l,runner:"deploy-run",allowedEnvs:ei(n.get(a)??null,r.get(a)),ssmPrefix:Dk(u,Tk),...s(a,c)}}))).filter(a=>a!==null)},tN=async e=>{try{return await _p.access(e),!0}catch{return!1}},Ak=async e=>{try{return await _p.readFile(e,"utf-8")}catch{return""}},Ok=(e,t)=>e.split(`
430
+ `).map((r,n)=>({line:n+1,text:r})).filter(({text:r})=>{let n=r.trimStart();return!t.commentPrefixes.some(o=>n.startsWith(o))}),rN=e=>{let t=e.reduce((n,{text:o})=>n??qI.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},nN=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Dk=(e,t)=>{for(let{line:r,text:n}of e){let o=t.literalPrefix(n);if(o!==void 0)return o;if(t.isUnparseable(n))return{unparseable:{line:r,text:n.trim()}}}return null},Ik=e=>{let t=oi.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},oN=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ik(r)]);return t},sN=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ik(r)}:${n}: ${o}`]});if(t.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},iN=e=>{sN(e);let t=oN(e),[r,...n]=t.keys();if(r===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'read the literal "/<project>/environment" in at least one deploy script: a deploy.ts in infra-kit.deploy.ts, or `aws ssm get-parameter --name "/<project>/environment"` in a devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},Nk=async(e,t)=>(await Tt(e))?.project??iN(t),si=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),jp=(e,t)=>e.filter(r=>r.runsBefore===void 0&&si(r,t)),_k=(e,t,r)=>{let n=new Set(e.map(l=>l.name)),o=t.filter(l=>!n.has(l.name)&&si(l,r)&&(l.runsBefore??[]).some(u=>n.has(u))),s=new Map([...o,...e].map(l=>[l.name,l])),i=[],a=new Set,c=l=>{if(!a.has(l.name)){a.add(l.name);for(let u of l.dependsOn??[]){let p=s.get(u);p!==void 0&&c(p)}i.push(l)}};for(let l of e)c(l);return i};var Bp="deploy-all.yml",dN="/bin/sh",pN=async()=>{let e=ii.quiet;ii.quiet=!0;try{let t=await ii`gh run list --workflow=${Bp} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{ii.quiet=e}},mN=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await _(o=>aN({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},fN=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return H()&&Hi(i,{env:t,services:n,accountId:o,shared:r}),r?_(a=>lN({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):_(a=>cN({message:i,default:!1},a),{whenHeadless:"refuse"})},jk=e=>e.runner==="sh"?[dN,[e.scriptPath]]:[Lp.execPath,[Lp.argv[1]??"","deploy-run",e.name]],gN=(e,t,r)=>new Promise((n,o)=>{let[s,i]=jk(e),a=uN(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),hN=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 gN(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}},yN=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new g(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!si(c,n)});if(i.length>0)throw new g(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},Fp=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:bp(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},vN=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(y.setInteractive(),mN(r,o))},Fk=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await $(),c=await Mp(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has infra-kit.deploy.ts or devops/scripts/deploy-*.sh",stderrExcerpt:`no deployable services found under ${a}`});let l=await Nk(a,c);await et({provider:Up[t],params:e,operation:"deploy locally",argument:"env"});let u=await lt(),p=Ft(await Lt(Bp),u),m=r??"";m||(y.setInteractive(),m=await go(p,"deploy locally")),y.addOption("--env",m);let f=jp(c,m);if(f.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let h=await vN({selection:t,eligible:f,service:n,env:m}),b=_k(yN({names:h,services:c,env:m}),c,m);if(t==="selected")for(let Re of h)y.addOption("--service",Re);let C=Hn(m),k=await dn(),F=(await ii`git rev-parse HEAD`.quiet()).stdout.trim(),v=await hg(),S=Rp({env:m,branch:k,sha:F,isClean:v});i&&d.info(`Deploy contract for ${m}:
431
+ ${lc(S)}`);let O=(await Np({env:m,project:l,isShared:C,isClean:v,runningEnvs:await pN(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${O}) from this machine`,`Preflight parameter: /${l}/environment`,lc(S),"Commands:",...b.map(Re=>` ${jk(Re).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
432
+ `)),Fp({env:m,accountId:O,names:h,built:S,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await fN({env:m,isShared:C,names:h,accountId:O}))return d.info("Deployment cancelled"),Fp({env:m,accountId:O,names:h,built:S,deployed:[],failed:[],dryRun:!1,success:!1});S.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${S.stripped.join(", ")}`);let{deployed:D,failed:V}=await hN({chosen:b,childEnv:S.childEnv,cwd:a,env:m});return V.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${D.join(", ")||"none"}], failed [${V.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Lp.exitCode=1),y.print(),Fp({env:m,accountId:O,names:h,built:S,deployed:D,failed:V,dryRun:!1,success:V.length===0})},Lk=async e=>Fk(e,"all"),Bk=async e=>Fk(e,"selected"),Uk='Runs the repo\'s own deploys (infra-kit.deploy.ts via deploy-run, else devops/scripts/deploy-*.sh) on THIS machine instead of dispatching CI. Supplies the build contract (VITE_DOMAIN_ENV/BRANCH/COMMIT) that the workflow YAML normally provides and that the scripts do not set themselves, and refuses unless the requested environment matches the AWS account the shell is authenticated to. "prod" is refused by default \u2014 it is delivered, not deployed \u2014 and is reachable only if this project sets `protectedEnvs` in infra-kit.json; "cli-only" allows it in a terminal but still refuses it here. Services the environment forbids are refused, matching the workflow\'s own per-service gates. Use dryRun first.',Vk={env:oe.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:oe.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:oe.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Wk={environment:oe.string().describe("Environment deployed to"),accountId:oe.string().describe("AWS account the deploy targeted"),services:oe.array(oe.string()).describe("Services requested"),deployed:oe.array(oe.string()).describe("Services that completed successfully"),failed:oe.array(oe.string()).describe("Services that failed"),contract:oe.record(oe.string(),oe.string()).describe("Build contract passed to the scripts"),strippedVars:oe.array(oe.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:oe.boolean().describe("Whether this was a dry run"),success:oe.boolean().describe("Whether every requested service deployed")},Mk=e=>Xr({workflowFile:Bp,fields:["env"],toolName:e}),Up={all:Mk("local-deploy-all"),selected:Mk("local-deploy-selected")},Vp=T({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Uk}`,requiresHumanConfirm:!0,formProvider:Up.all,inputSchema:Vk,outputSchema:Wk,handler:Lk}),Wp=T({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Uk}`,requiresHumanConfirm:!0,formProvider:Up.selected,inputSchema:{...Vk,service:oe.array(oe.string()).min(1).describe('Service names as in infra-kit.deploy.ts or devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Wk,handler:Bk});import bN from"@inquirer/confirm";import hc from"@inquirer/input";import Hk from"@inquirer/select";import Jp from"node:process";import{z as Y}from"zod";import{z as ai}from"zod";var ho=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Kk=2500,Gk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jk=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,wN=async()=>{let e=await xs();return{regular:ro(e,"regular"),hotfix:ro(e,"hotfix")}},kN=(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).`,Gp=(e={})=>{let t=e.hintBudgetMs??Kk;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=>Gk(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await ho(wN(),t),n=await ne(),[o,...s]=io(n);return ai.object({type:ai.enum([o,...s]).describe(n==="main"?'Release type. This repo sets "gitFlow": "main", so every release is "regular": it branches off main and bumps the minor.':'Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:ai.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. ${kN(r,t)}`),description:ai.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:ai.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=Jk(r.description),a=Jk(r.releaseDate),c=Ma(o);return{...Gk(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var RN='"1.2.5" or "next"',Kp=(e,t)=>{try{return kd(e,t)}catch(r){throw r instanceof Ur?new g(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof pg?new g(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},SN=async(e,t)=>{let r=ro(e,t),n=r?` [${r}]`:"",o=(await _(i=>hc({message:` Version (e.g. ${RN})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Jp.exit(1)),s},EN=async()=>{let e=(await _(t=>hc({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Jp.exit(1));try{Fi(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Jp.exit(1)}return e},PN=async()=>(await _(e=>hc({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Ps},e),{whenHeadless:"refuse"})).trim(),xN=async e=>{y.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await _(f=>Hk({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},f),{whenHeadless:"refuse"}),c=io(await ne()),l=c.length===1?c[0]:await _(f=>Hk({message:`Release #${i} \u2014 select type:`,choices:c.map(h=>({name:h,value:h})),default:"regular"},f),{whenHeadless:"refuse"}),u;if(a==="name"){let f=await EN();u=Kp([{name:f,type:l}],[])[0]}else{let f=await SN(await n(),l);u=Kp([{version:f,type:l}],r)[0],u.id.kind==="version"&&r.push(dr(`v${u.id.raw}`))}let p=(await _(f=>hc({message:" Description (optional, press Enter to skip): "},f),{whenHeadless:"refuse"})).trim(),m=await PN();o.push({...u,...p!==""?{description:p}:{},...m!==""?{releaseDate:m}:{}}),s=await _(f=>bN({message:"Add another release?",default:!1},f),{whenHeadless:"refuse"})}return o},TN=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 ")},qk=e=>{for(let t of e)y.addOption("--release",wd(t))},CN=async(e,t)=>{if(e&&e.length>0){let n=bd(e)?await t():[],o=Kp(e,n);return qk(o),o}if(te())throw new A({status:"argument_required",argument:"release",agentMode:N.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await xN(t);return qk(r),r},$N=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new g(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},AN=async(e,t)=>{let r=e.map(TN).join(`
433
433
  - `);await q(t,`Create the following ${e.length} release(s)?
434
434
  - ${r}
435
- `),y.addOption("--yes",!0)},PN=async e=>{let{entry:t,jiraConfig:r}=e,n=ae(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await oo({operation:`create release ${o}`});let s=await zd(t.type),i=await Yd({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}
435
+ `),y.addOption("--yes",!0)},ON=async e=>{let{entry:t,jiraConfig:r}=e,n=ae(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await so({operation:`create release ${o}`});let s=await Yd(t.type),i=await Xd({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}
436
436
  `),{result:i}}catch(s){let i=Rs(s)?s:void 0,a=new g(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return d.error(`\u274C ${a.message}
437
- `),{failure:{version:n,error:a.message}}}},xN=(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.`)},Gk=Wp(),yc=async e=>{let{releases:t,confirmedCommand:r}=e;await Be({operation:"create release"}),await et({provider:Gk,params:e,operation:"create release",argument:"release"});let n=await Zn(),o=null,i=await RN(t,async()=>(o===null&&(o=await xs()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});SN(i),await Is({operation:"create release",base:Pt(i[0].type,await ne())}),await EN(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await PN({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}xN(i.length,a.length,c.length),y.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},Kp=T({name:"release-create",requiresHumanConfirm:!0,formProvider:Gk,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix; main for every release in a repo with "gitFlow": "main", which has no hotfix type), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:Y.array(Y.object({version:Y.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:Y.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:Y.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:Y.string().optional().describe("Optional description for the Jira version."),releaseDate:dd.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:Y.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:Y.array(Y.string()).describe("List of created release branch names"),successCount:Y.number().describe("Number of releases created successfully"),failureCount:Y.number().describe("Number of releases that failed"),releases:Y.array(Y.object({version:Y.string().describe("Version number"),type:Y.enum(["regular","hotfix"]).describe("Release type"),branchName:Y.string().describe("Release branch name"),prUrl:Y.string().describe("GitHub PR URL"),jiraVersionUrl:Y.string().describe("Jira version URL"),releaseDate:Y.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:Y.array(Y.object({version:Y.string().describe("Version number that failed"),error:Y.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:yc});import{z as Jt}from"zod";import{$ as Xp}from"zx";import TN from"@inquirer/confirm";var ci=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;H()&&Hi(o,{branch:r,env:n}),y.setInteractive();let s=await _(i=>TN({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import CN from"@inquirer/select";import $N from"node:process";var Hp=()=>!H()&&$N.stdin.isTTY===!0,AN={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},qp=async()=>_(e=>CN({message:"\u{1F680} Where should this deploy run?",choices:yr.filter(t=>t!=="local").map(t=>({name:t,value:t,description:AN[t]}))},e),{whenHeadless:"refuse"});var yr=["ci","local"],ON={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Jk=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${yr.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw H()?new A({status:"argument_required",argument:"from",agentMode:N.source},2,r):new g(void 0,r)}let t=yr.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${yr.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},zp=(e,t)=>{let n=ON[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Yp=async e=>e||!Hp()?Jk(e):qp();var li=async e=>{let t=await Gr();if(e==="dev"&&t!=="dev")throw new g(void 0,{operation:"resolve the deploy branch",remediation:`this repo sets "gitFlow": "${t}" in infra-kit.json and has no dev branch to deploy \u2014 pass --version ${t}, or a release`});if(e)return e===t?t:Wt(e);y.setInteractive();let r=await K(),n=r.map(i=>i.branch),o=new Map(r.map(i=>[i.branch,i.type])),s=await ye();return mr([{value:t,label:t},...ve({branches:n,descriptions:s,types:o})])};var Kk="deploy-all.yml",Hk=Xr({workflowFile:Kk,fields:["version","env"],toolName:"gh-release-deploy-all"}),vc=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await et({provider:Hk,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await li(t),i=js(s);y.addOption("--version",i);let a=await lt(),c=jt(await Ft(Kk),a),l="";r?l=r:(y.setInteractive(),l=await fo(c,"launch deploy-all workflow")),y.addOption("--env",l),jr(l,"launch deploy-all workflow",a),bs({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await ci({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}}try{Xp.quiet=!0,await Xp`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Xp.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),y.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content:R(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Zp=T({name:"gh-release-deploy-all",formProvider:Hk,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:Jt.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead ("main" in a repo with "gitFlow": "main"). Omit it to be offered the open releases.'),env:Jt.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:Jt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Jt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Jt.string().describe("The release branch that was deployed"),version:Jt.string().describe("The version that was deployed"),environment:Jt.string().describe("The environment deployed to"),skipTerraformDeploy:Jt.boolean().describe("Whether terraform deployment was skipped"),success:Jt.boolean().describe("Whether the deployment was successful")},handler:vc});import DN from"@inquirer/checkbox";import{z as Ue}from"zod";import{$ as Qp}from"zx";var Zr="deploy-selected-services.yml",qk=Xr({workflowFile:Zr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),wc=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await et({provider:qk,params:e,operation:"launch deploy-selected workflow",argument:v=>v[0]??"version"});let i=await li(t),a=js(i);y.addOption("--version",a);let c=await lt(),l=jt(await Ft(Zr),c),u="";r?u=r:(y.setInteractive(),u=await fo(l,"launch deploy-selected workflow")),y.addOption("--env",u),jr(u,"launch deploy-selected workflow",c),bs({env:u,branch:i});let p=await $(),m=await ti(p,Zr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Zr}`,stderrExcerpt:`no services found in .github/workflows/${Zr}`});let f=[];if(n&&n.length>0?f=n:(y.setInteractive(),f=await _(v=>DN({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(S=>({name:S,value:S}))},v),{whenHeadless:"refuse"})),y.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let h=f.filter(v=>!m.includes(v));if(h.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let b=await Qs(p,Zr),C=f.filter(v=>{let S=b.get(v);return S!==void 0&&!S.includes(u)});if(C.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:C.map(v=>`${v} deploys only to: ${(b.get(v)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Zr} gates these services out of ${u}: ${C.join(", ")}`});let k=o??!1;k&&y.addOption("--skip-terraform",!0);let F=v=>{let S={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:k,success:v};return{content:R(JSON.stringify(S,null,2)),structuredContent:S}};if(!await ci({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),F(!1);try{Qp.quiet=!0;let v=f.flatMap(P=>["-f",`${P}=true`]);return await Qp`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${v} ${k?["-f","skip_terraform_deploy=true"]:[]}`,Qp.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),y.print(),F(!0)}catch(v){throw d.error({error:v},"\u274C Error launching workflow"),new g(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},em=T({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:qk,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:Ue.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead ("main" in a repo with "gitFlow": "main"). Omit it to be offered the open releases.'),env:Ue.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:Ue.array(Ue.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:Ue.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ue.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ue.string().describe("The release branch that was deployed"),version:Ue.string().describe("The version that was deployed"),environment:Ue.string().describe("The environment deployed to"),services:Ue.array(Ue.string()).describe("The services that were deployed"),skipTerraformDeploy:Ue.boolean().describe("Whether terraform deployment was skipped"),success:Ue.boolean().describe("Whether the deployment was successful")},handler:wc});import zk from"@inquirer/input";import{z as rt}from"zod";var Yk=["description","releaseDate"],IN=async()=>{let e=await K(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await ye(),o=await mr(ve({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},NN=async e=>{let r=(await K()).find(n=>n.branch===e);if(!r)throw new g(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},_N=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await _(o=>zk({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},MN=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await _(o=>zk({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Ps},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Br(n)},jN=e=>{if(e!==void 0)return e===""?null:e},FN=async e=>(y.setInteractive(),{description:await _N(e.description),releaseDate:await MN(e.releaseDate)}),tm=e=>e??"(none)",LN=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${tm(t.releaseDate)} \u2192 ${tm(r.releaseDate)}`,kc=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=jN(n),i=await Zn(),a;t?(a=Wt(t),await NN(a)):(y.setInteractive(),a=(await IN()).branch);let c=re(a);if(!c)throw new g(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=ae(c);y.addOption("--version",l);let u=pe(c),p=await Lt(u,i);if(!p)throw new g(void 0,{operation:`edit release ${u}`,remediation:`create the Jira fix version "${u}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},f=r!==void 0||s!==void 0;if(!f&&H())throw new A({status:"argument_required",argument:"description",agentMode:N.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let h=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await FN(m),b=Yk.filter(P=>h[P]!==m[P]),C=b.includes("description"),k=b.includes("releaseDate"),F=Lr(i,p),v=P=>{let O={version:l,branch:a,jiraVersionUrl:F,previousDescription:m.description,newDescription:h.description,previousReleaseDate:m.releaseDate,newReleaseDate:h.releaseDate,changedFields:b,changed:P};return{content:R(JSON.stringify(O,null,2)),structuredContent:O}};if(b.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${tm(m.releaseDate)}`),y.print(),v(!1);C&&y.addOption("--description",h.description),k&&y.addOption("--release-date",h.releaseDate??"");let S=b.map(P=>LN(P,m,h));return await q(o,`Update ${u}?
437
+ `),{failure:{version:n,error:a.message}}}},DN=(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.`)},zk=Gp(),yc=async e=>{let{releases:t,confirmedCommand:r}=e;await Be({operation:"create release"}),await et({provider:zk,params:e,operation:"create release",argument:"release"});let n=await Qn(),o=null,i=await CN(t,async()=>(o===null&&(o=await xs()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});$N(i),await Is({operation:"create release",base:xt(i[0].type,await ne())}),await AN(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await ON({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}DN(i.length,a.length,c.length),y.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},Hp=T({name:"release-create",requiresHumanConfirm:!0,formProvider:zk,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix; main for every release in a repo with "gitFlow": "main", which has no hotfix type), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:Y.array(Y.object({version:Y.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:Y.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:Y.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:Y.string().optional().describe("Optional description for the Jira version."),releaseDate:pd.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:Y.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:Y.array(Y.string()).describe("List of created release branch names"),successCount:Y.number().describe("Number of releases created successfully"),failureCount:Y.number().describe("Number of releases that failed"),releases:Y.array(Y.object({version:Y.string().describe("Version number"),type:Y.enum(["regular","hotfix"]).describe("Release type"),branchName:Y.string().describe("Release branch name"),prUrl:Y.string().describe("GitHub PR URL"),jiraVersionUrl:Y.string().describe("Jira version URL"),releaseDate:Y.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:Y.array(Y.object({version:Y.string().describe("Version number that failed"),error:Y.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:yc});import{z as Kt}from"zod";import{$ as Zp}from"zx";import IN from"@inquirer/confirm";var ci=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;H()&&Hi(o,{branch:r,env:n}),y.setInteractive();let s=await _(i=>IN({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import NN from"@inquirer/select";import _N from"node:process";var qp=()=>!H()&&_N.stdin.isTTY===!0,MN={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},zp=async()=>_(e=>NN({message:"\u{1F680} Where should this deploy run?",choices:yr.filter(t=>t!=="local").map(t=>({name:t,value:t,description:MN[t]}))},e),{whenHeadless:"refuse"});var yr=["ci","local"],jN={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Yk=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${yr.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw H()?new A({status:"argument_required",argument:"from",agentMode:N.source},2,r):new g(void 0,r)}let t=yr.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${yr.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Yp=(e,t)=>{let n=jN[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Xp=async e=>e||!qp()?Yk(e):zp();var li=async e=>{let t=await Gr();if(e==="dev"&&t!=="dev")throw new g(void 0,{operation:"resolve the deploy branch",remediation:`this repo sets "gitFlow": "${t}" in infra-kit.json and has no dev branch to deploy \u2014 pass --version ${t}, or a release`});if(e)return e===t?t:Gt(e);y.setInteractive();let r=await K(),n=r.map(i=>i.branch),o=new Map(r.map(i=>[i.branch,i.type])),s=await ye();return mr([{value:t,label:t},...ve({branches:n,descriptions:s,types:o})])};var Xk="deploy-all.yml",Zk=Xr({workflowFile:Xk,fields:["version","env"],toolName:"gh-release-deploy-all"}),vc=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await et({provider:Zk,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await li(t),i=js(s);y.addOption("--version",i);let a=await lt(),c=Ft(await Lt(Xk),a),l="";r?l=r:(y.setInteractive(),l=await go(c,"launch deploy-all workflow")),y.addOption("--env",l),jr(l,"launch deploy-all workflow",a),bs({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await ci({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}}try{Zp.quiet=!0,await Zp`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Zp.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),y.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content:R(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Qp=T({name:"gh-release-deploy-all",formProvider:Zk,description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Omit "version" or "env" and this server offers the human a form listing the real releases and the environments this workflow declares; a client that cannot render one gets a refusal naming the missing field, never a guess.',requiresHumanConfirm:!0,inputSchema:{version:Kt.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead ("main" in a repo with "gitFlow": "main"). Omit it to be offered the open releases.'),env:Kt.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-all.yml declares.'),skipTerraform:Kt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Kt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Kt.string().describe("The release branch that was deployed"),version:Kt.string().describe("The version that was deployed"),environment:Kt.string().describe("The environment deployed to"),skipTerraformDeploy:Kt.boolean().describe("Whether terraform deployment was skipped"),success:Kt.boolean().describe("Whether the deployment was successful")},handler:vc});import FN from"@inquirer/checkbox";import{z as Ue}from"zod";import{$ as em}from"zx";var Zr="deploy-selected-services.yml",Qk=Xr({workflowFile:Zr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),wc=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await et({provider:Qk,params:e,operation:"launch deploy-selected workflow",argument:v=>v[0]??"version"});let i=await li(t),a=js(i);y.addOption("--version",a);let c=await lt(),l=Ft(await Lt(Zr),c),u="";r?u=r:(y.setInteractive(),u=await go(l,"launch deploy-selected workflow")),y.addOption("--env",u),jr(u,"launch deploy-selected workflow",c),bs({env:u,branch:i});let p=await $(),m=await ti(p,Zr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Zr}`,stderrExcerpt:`no services found in .github/workflows/${Zr}`});let f=[];if(n&&n.length>0?f=n:(y.setInteractive(),f=await _(v=>FN({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(S=>({name:S,value:S}))},v),{whenHeadless:"refuse"})),y.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let h=f.filter(v=>!m.includes(v));if(h.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let b=await Qs(p,Zr),C=f.filter(v=>{let S=b.get(v);return S!==void 0&&!S.includes(u)});if(C.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:C.map(v=>`${v} deploys only to: ${(b.get(v)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Zr} gates these services out of ${u}: ${C.join(", ")}`});let k=o??!1;k&&y.addOption("--skip-terraform",!0);let F=v=>{let S={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:k,success:v};return{content:R(JSON.stringify(S,null,2)),structuredContent:S}};if(!await ci({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),F(!1);try{em.quiet=!0;let v=f.flatMap(P=>["-f",`${P}=true`]);return await em`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${v} ${k?["-f","skip_terraform_deploy=true"]:[]}`,em.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),y.print(),F(!0)}catch(v){throw d.error({error:v},"\u274C Error launching workflow"),new g(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},tm=T({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Qk,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:Ue.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead ("main" in a repo with "gitFlow": "main"). Omit it to be offered the open releases.'),env:Ue.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:Ue.array(Ue.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:Ue.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ue.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ue.string().describe("The release branch that was deployed"),version:Ue.string().describe("The version that was deployed"),environment:Ue.string().describe("The environment deployed to"),services:Ue.array(Ue.string()).describe("The services that were deployed"),skipTerraformDeploy:Ue.boolean().describe("Whether terraform deployment was skipped"),success:Ue.boolean().describe("Whether the deployment was successful")},handler:wc});import eb from"@inquirer/input";import{z as rt}from"zod";var tb=["description","releaseDate"],LN=async()=>{let e=await K(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await ye(),o=await mr(ve({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},BN=async e=>{let r=(await K()).find(n=>n.branch===e);if(!r)throw new g(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},UN=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await _(o=>eb({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},VN=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await _(o=>eb({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Ps},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Br(n)},WN=e=>{if(e!==void 0)return e===""?null:e},GN=async e=>(y.setInteractive(),{description:await UN(e.description),releaseDate:await VN(e.releaseDate)}),rm=e=>e??"(none)",JN=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${rm(t.releaseDate)} \u2192 ${rm(r.releaseDate)}`,kc=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=WN(n),i=await Qn(),a;t?(a=Gt(t),await BN(a)):(y.setInteractive(),a=(await LN()).branch);let c=re(a);if(!c)throw new g(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=ae(c);y.addOption("--version",l);let u=pe(c),p=await Bt(u,i);if(!p)throw new g(void 0,{operation:`edit release ${u}`,remediation:`create the Jira fix version "${u}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},f=r!==void 0||s!==void 0;if(!f&&H())throw new A({status:"argument_required",argument:"description",agentMode:N.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let h=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await GN(m),b=tb.filter(P=>h[P]!==m[P]),C=b.includes("description"),k=b.includes("releaseDate"),F=Lr(i,p),v=P=>{let O={version:l,branch:a,jiraVersionUrl:F,previousDescription:m.description,newDescription:h.description,previousReleaseDate:m.releaseDate,newReleaseDate:h.releaseDate,changedFields:b,changed:P};return{content:R(JSON.stringify(O,null,2)),structuredContent:O}};if(b.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${rm(m.releaseDate)}`),y.print(),v(!1);C&&y.addOption("--description",h.description),k&&y.addOption("--release-date",h.releaseDate??"");let S=b.map(P=>JN(P,m,h));return await q(o,`Update ${u}?
438
438
  ${S.join(`
439
439
  `)}
440
- `),y.addOption("--yes",!0),await Xn({versionId:p.id,...C?{description:h.description}:{},...k?{releaseDate:h.releaseDate}:{}},i),C&&await Za({branch:a,body:_s(F,h.description)}),d.info(`\u2705 Updated ${b.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${F}`),d.info(`\u{1F517} PR branch: ${a}
441
- `),y.print(),v(!0)},rm=T({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:rt.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:rt.string().optional().describe("New description. Empty string clears the description."),releaseDate:pd.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:rt.string().describe("Release version"),branch:rt.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:rt.string().describe("Jira fix version URL"),previousDescription:rt.string().describe("The description before the update"),newDescription:rt.string().describe("The description after the update"),previousReleaseDate:rt.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:rt.string().nullable().describe("The planned release date after the update, or null"),changedFields:rt.array(rt.enum(Yk)).describe("The fields whose value actually changed"),changed:rt.boolean().describe("Whether anything actually changed")},handler:kc});import{z as de}from"zod";import{$ as om}from"zx";import{z as Xk}from"zod";var eb=2500,bc="release-remove",Zk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),BN=e=>e.version===void 0||e.version==="",UN=async()=>{try{return{outcome:"listed",prs:await K()}}catch(e){return e instanceof g&&e.operation===Fs?{outcome:"empty"}:{outcome:"failed"}}},Qk=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${bc}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${bc}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${bc}`}),null),VN=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return za(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(pe(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},WN=(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): ${bc}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},nm=(e={})=>{let t=e.fetchBudgetMs??eb;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=>Zk(r)&&BN(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([go(UN(),t),go(ye(),t)]);if(r===null||r.outcome!=="listed")return Qk(r,t);let o=VN(r.prs,n);return o.length===0?Qk({outcome:"empty"},t):Xk.object({version:Xk.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${WN(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:{...Zk(n)?n:{},version:r.version}}};var tb=["worktree","pr","local-branch","remote-branch","jira"],ob={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"},Qr="remove a release",ut=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},rb=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new A({...e,agentMode:N.source},2,t)},GN=e=>{te()&&(e.version||rb({status:"argument_required",argument:"version"},{operation:Qr,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&&rb({status:"refused"},{operation:Qr,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"}))},sb=e=>{e.pr?.state==="MERGED"&&ut({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`})},JN=(e,t)=>{if(t.skipJira||(e.jiraConfig||ut({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)&&ut({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||ut({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)`}))},KN=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;ut({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"})},HN=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||ut({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(", ")}`})},qN=async e=>(await om`git -C ${e} status --porcelain`).stdout.split(`
442
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),zN=async e=>{try{let{terminals:t}=await Og(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},YN=async e=>{let t=await Ki([e]);if(t!==null)throw d.warn({operation:Qr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new A({status:"refused",reason:"orca_caller_inside_target",agentMode:N.source},2,{operation:Qr,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`})},XN=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await Bt();if(!n)return r;let o=await Lt(pe(e),n),s=t.moveIssuesTo?await ZN(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Na(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:Lr(n,o)}}},ZN=async(e,t)=>{let r=await Lt(e,t);return r||ut({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}"`})},QN=async(e,t)=>{let r=re(e);r||ut({operation:`remove release ${e}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:`"${e}" is not a release branch`});let n=await $(),s=`${`${n}${le}`}/${e}`,[i,a,c,l]=await Promise.all([Pe("release"),ao(e),Oe(n,`refs/heads/${e}`),pn(n,e)]),u=i.includes(e);return u&&await YN(s),{...await XN(r,t),branch:e,id:r,label:ae(r),baseBranch:a?.baseRefName??Pt("regular",await ne()),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await zN(s):0,worktreeDirty:u?await qN(s):null,localTipSha:c,remoteTipSha:l,pr:a}},nb=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}),e_=(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}`},t_=(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: ${e_(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
443
- `)},Rc=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},r_=e=>typeof e=="string"?e:e.outcome;async function ui(e,t,r){try{let n=await r(),o=r_(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${ob[e]} \u2014 ${o}`),n}catch(n){throw new Rc(e,n)}}var n_=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,o_=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>n_(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,u=o instanceof g?o.remediation:void 0;return new g(o,{operation:`remove release ${t.label} \u2014 step ${tb.indexOf(r)+1} of ${tb.length} (${ob[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},s_=async e=>(await Hs(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`})).includes(e.branch)?"removed":"absent",i_=async e=>{let t=await ao(e.branch);if(sb({...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 om`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},a_=async e=>(await dn()===e.branch&&await om`git switch ${e.baseBranch}`,await Li(e.branch),await fg(e.branch)?ut({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"),c_=async e=>(await Bi(e.branch),e.remoteTipSha?"deleted":"absent"),l_=async(e,t,r)=>{let n=await Na(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}\``;ut({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}`})},u_=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await l_(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 ud({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),d_=(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}),p_=async(e,t,r)=>{let n=await ui("worktree",r,()=>s_(e)),o=await ui("pr",r,()=>i_(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await ui("local-branch",r,()=>a_(e)),i=await ui("remote-branch",r,()=>c_(e)),a=await ui("jira",r,()=>u_(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},m_=async(e,t)=>{let r=[];try{return d_(e,await p_(e,t,r))}catch(n){throw n instanceof Rc?o_({plan:e,step:n.step,done:r,cause:n.reason}):n}},f_=async e=>{if(e)return Wt(e);y.setInteractive();let[t,r]=await Promise.all([ye(),K()]),n=r.map(s=>s.branch);n.length===0&&ut({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 mr(ve({branches:n,descriptions:t,types:o}))}catch(s){throw Me(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},ib=nm(),Sc=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Be({operation:Qr}),await L(),await et({provider:ib,params:e,operation:Qr,argument:"version"}),GN(e);try{let s=await QN(await f_(r),e);d.debug({plan:nb(s)},"release remove: resolved plan"),sb(s),JN(s,e),KN(s),await Is({operation:`remove release ${s.label}`,base:s.baseBranch}),HN(s),y.addOption("--version",s.label),n&&y.addOption("--move-issues-to",n),o&&y.addOption("--skip-jira",!0),await q(t,t_(s,!!o),{plan:{...nb(s),skipJira:!!o}}),t||y.addOption("--yes",!0);let i=await m_(s,e);return y.print(),{content:R(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Me(s)||xe(s)||s instanceof g?s:(d.error({err:zr(s)},"\u274C Error removing release"),new g(s,{operation:Qr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},sm=T({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:ib,inputSchema:{version:de.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:de.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:de.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:de.string().describe("The release branch that was targeted"),version:de.string().describe('The release label (e.g. "1.2.5")'),baseBranch:de.string().describe("The branch HEAD was moved to before the local delete"),worktree:de.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:de.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:de.number().nullable().describe("The pull request number, or null when none exists"),localBranch:de.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:de.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:de.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:de.string().nullable().describe("The origin tip before deletion"),jira:de.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:de.object({id:de.string(),name:de.string(),url:de.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Sc});import{spawn as v_}from"node:child_process";import w_ from"node:fs";import{homedir as k_}from"node:os";import Pc from"node:process";import{z as b_}from"zod";import Ec from"node:fs";import ho from"node:path";var g_=e=>{try{return Ec.statSync(e).isFile()?Ec.readFileSync(e,"utf8"):null}catch{return null}},h_=e=>{try{return Ec.realpathSync(e)}catch{return e}},y_=(e,t)=>{let o=t(ho.join(e,".git"))?.split(`
444
- `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=ho.resolve(e,o),i=`${ho.sep}.git${ho.sep}worktrees${ho.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},ab=(e={})=>{let t=e.listInstallations??yl,r=e.exists??Ec.existsSync,n=e.readGitFile??g_,o=e.realpath??h_,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=y_(i.projectPath,n);if(!r(ho.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var R_=180*1e3,S_=900*1e3,E_=4*1024*1024,P_=2e3,x_=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=v_(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&&Pc.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<E_&&(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)},P_).unref()})}),T_=({cwd:e,timeoutMs:t})=>x_({command:Pc.execPath,args:[Pc.argv[1]??"","setup","--unattended","--json"],cwd:e,env:Lg(Pc.env),timeoutMs:t}),C_=e=>{w_.writeFileSync(On(),e,{mode:384})},$_=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}},A_=new RegExp("\x1B\\[[0-9;]*m","g"),O_=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(A_,"").split(`
445
- `).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},D_=(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}},cb=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":Oa(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(R_,o)}),a=i.error===null?$_(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${O_(i)} \u2014 run: ${s}`]}:{root:e,...D_(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},I_=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}})},N_=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(`
440
+ `),y.addOption("--yes",!0),await Zn({versionId:p.id,...C?{description:h.description}:{},...k?{releaseDate:h.releaseDate}:{}},i),C&&await Za({branch:a,body:_s(F,h.description)}),d.info(`\u2705 Updated ${b.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${F}`),d.info(`\u{1F517} PR branch: ${a}
441
+ `),y.print(),v(!0)},nm=T({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:rt.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:rt.string().optional().describe("New description. Empty string clears the description."),releaseDate:md.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:rt.string().describe("Release version"),branch:rt.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:rt.string().describe("Jira fix version URL"),previousDescription:rt.string().describe("The description before the update"),newDescription:rt.string().describe("The description after the update"),previousReleaseDate:rt.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:rt.string().nullable().describe("The planned release date after the update, or null"),changedFields:rt.array(rt.enum(tb)).describe("The fields whose value actually changed"),changed:rt.boolean().describe("Whether anything actually changed")},handler:kc});import{z as de}from"zod";import{$ as sm}from"zx";import{z as rb}from"zod";var sb=2500,bc="release-remove",nb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KN=e=>e.version===void 0||e.version==="",HN=async()=>{try{return{outcome:"listed",prs:await K()}}catch(e){return e instanceof g&&e.operation===Fs?{outcome:"empty"}:{outcome:"failed"}}},ob=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${bc}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${bc}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${bc}`}),null),qN=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return za(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(pe(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},zN=(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): ${bc}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},om=(e={})=>{let t=e.fetchBudgetMs??sb;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=>nb(r)&&KN(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([ho(HN(),t),ho(ye(),t)]);if(r===null||r.outcome!=="listed")return ob(r,t);let o=qN(r.prs,n);return o.length===0?ob({outcome:"empty"},t):rb.object({version:rb.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${zN(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:{...nb(n)?n:{},version:r.version}}};var ib=["worktree","pr","local-branch","remote-branch","jira"],lb={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"},Qr="remove a release",ut=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},ab=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new A({...e,agentMode:N.source},2,t)},YN=e=>{te()&&(e.version||ab({status:"argument_required",argument:"version"},{operation:Qr,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&&ab({status:"refused"},{operation:Qr,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"}))},ub=e=>{e.pr?.state==="MERGED"&&ut({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`})},XN=(e,t)=>{if(t.skipJira||(e.jiraConfig||ut({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)&&ut({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||ut({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)`}))},ZN=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;ut({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"})},QN=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||ut({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(", ")}`})},e_=async e=>(await sm`git -C ${e} status --porcelain`).stdout.split(`
442
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),t_=async e=>{try{let{terminals:t}=await _g(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},r_=async e=>{let t=await Ki([e]);if(t!==null)throw d.warn({operation:Qr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new A({status:"refused",reason:"orca_caller_inside_target",agentMode:N.source},2,{operation:Qr,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`})},n_=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await Ut();if(!n)return r;let o=await Bt(pe(e),n),s=t.moveIssuesTo?await o_(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Na(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:Lr(n,o)}}},o_=async(e,t)=>{let r=await Bt(e,t);return r||ut({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}"`})},s_=async(e,t)=>{let r=re(e);r||ut({operation:`remove release ${e}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:`"${e}" is not a release branch`});let n=await $(),s=`${`${n}${le}`}/${e}`,[i,a,c,l]=await Promise.all([Pe("release"),co(e),Oe(n,`refs/heads/${e}`),pn(n,e)]),u=i.includes(e);return u&&await r_(s),{...await n_(r,t),branch:e,id:r,label:ae(r),baseBranch:a?.baseRefName??xt("regular",await ne()),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await t_(s):0,worktreeDirty:u?await e_(s):null,localTipSha:c,remoteTipSha:l,pr:a}},cb=e=>({branch:e.branch,label:e.label,baseBranch:e.baseBranch,worktreePath:e.worktreePath,worktreePresent:e.worktreePresent,worktreeDirty:e.worktreeDirty,orcaTerminalCount:e.orcaTerminalCount,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha,pr:e.pr,jiraConfigured:e.jiraConfig!==null,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name}:null,jiraFixCount:e.jira?.fixCount??null,jiraAffectsCount:e.jira?.affectsCount??null,moveIssuesTo:e.moveIssuesTo?{id:e.moveIssuesTo.id,name:e.moveIssuesTo.name}:null}),i_=(e,t)=>{if(t)return"skipped (--skip-jira)";if(!e.jiraConfig)return"skipped (Jira not configured)";if(!e.jira)return"none found";let{version:r,fixCount:n,affectsCount:o}=e.jira,s=`fixVersion on ${n} issue(s), affectsVersion on ${o} issue(s)`,i=e.moveIssuesTo?`, reassigned to ${e.moveIssuesTo.name}`:"";return`${r.name} \u2014 ${s}${i}`},a_=(e,t)=>{let r=e.pr?`#${e.pr.number} (${e.pr.state})`:"none",n=[`Remove release ${e.label} (${e.branch})? This will:`,` \u2022 worktree: ${e.worktreePresent?e.worktreePath:"none"}`,` \u2022 PR: ${r}`,` \u2022 local branch: ${e.localTipSha??"absent"} (switching to ${e.baseBranch} first)`,` \u2022 remote branch: ${e.remoteTipSha??"absent"}`,` \u2022 Jira version: ${i_(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
443
+ `)},Rc=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},c_=e=>typeof e=="string"?e:e.outcome;async function ui(e,t,r){try{let n=await r(),o=c_(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${lb[e]} \u2014 ${o}`),n}catch(n){throw new Rc(e,n)}}var l_=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,u_=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>l_(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,u=o instanceof g?o.remediation:void 0;return new g(o,{operation:`remove release ${t.label} \u2014 step ${ib.indexOf(r)+1} of ${ib.length} (${lb[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},d_=async e=>(await Hs(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`})).includes(e.branch)?"removed":"absent",p_=async e=>{let t=await co(e.branch);if(ub({...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 sm`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},m_=async e=>(await dn()===e.branch&&await sm`git switch ${e.baseBranch}`,await Li(e.branch),await vg(e.branch)?ut({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"),f_=async e=>(await Bi(e.branch),e.remoteTipSha?"deleted":"absent"),g_=async(e,t,r)=>{let n=await Na(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}\``;ut({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}`})},h_=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await g_(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 dd({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),y_=(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}),v_=async(e,t,r)=>{let n=await ui("worktree",r,()=>d_(e)),o=await ui("pr",r,()=>p_(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await ui("local-branch",r,()=>m_(e)),i=await ui("remote-branch",r,()=>f_(e)),a=await ui("jira",r,()=>h_(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},w_=async(e,t)=>{let r=[];try{return y_(e,await v_(e,t,r))}catch(n){throw n instanceof Rc?u_({plan:e,step:n.step,done:r,cause:n.reason}):n}},k_=async e=>{if(e)return Gt(e);y.setInteractive();let[t,r]=await Promise.all([ye(),K()]),n=r.map(s=>s.branch);n.length===0&&ut({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 mr(ve({branches:n,descriptions:t,types:o}))}catch(s){throw Me(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},db=om(),Sc=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Be({operation:Qr}),await L(),await et({provider:db,params:e,operation:Qr,argument:"version"}),YN(e);try{let s=await s_(await k_(r),e);d.debug({plan:cb(s)},"release remove: resolved plan"),ub(s),XN(s,e),ZN(s),await Is({operation:`remove release ${s.label}`,base:s.baseBranch}),QN(s),y.addOption("--version",s.label),n&&y.addOption("--move-issues-to",n),o&&y.addOption("--skip-jira",!0),await q(t,a_(s,!!o),{plan:{...cb(s),skipJira:!!o}}),t||y.addOption("--yes",!0);let i=await w_(s,e);return y.print(),{content:R(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Me(s)||xe(s)||s instanceof g?s:(d.error({err:zr(s)},"\u274C Error removing release"),new g(s,{operation:Qr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},im=T({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:db,inputSchema:{version:de.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:de.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:de.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:de.string().describe("The release branch that was targeted"),version:de.string().describe('The release label (e.g. "1.2.5")'),baseBranch:de.string().describe("The branch HEAD was moved to before the local delete"),worktree:de.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:de.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:de.number().nullable().describe("The pull request number, or null when none exists"),localBranch:de.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:de.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:de.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:de.string().nullable().describe("The origin tip before deletion"),jira:de.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:de.object({id:de.string(),name:de.string(),url:de.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Sc});import{spawn as E_}from"node:child_process";import P_ from"node:fs";import{homedir as x_}from"node:os";import Pc from"node:process";import{z as T_}from"zod";import Ec from"node:fs";import yo from"node:path";var b_=e=>{try{return Ec.statSync(e).isFile()?Ec.readFileSync(e,"utf8"):null}catch{return null}},R_=e=>{try{return Ec.realpathSync(e)}catch{return e}},S_=(e,t)=>{let o=t(yo.join(e,".git"))?.split(`
444
+ `).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=yo.resolve(e,o),i=`${yo.sep}.git${yo.sep}worktrees${yo.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},pb=(e={})=>{let t=e.listInstallations??vl,r=e.exists??Ec.existsSync,n=e.readGitFile??b_,o=e.realpath??R_,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=S_(i.projectPath,n);if(!r(yo.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var C_=180*1e3,$_=900*1e3,A_=4*1024*1024,O_=2e3,D_=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=E_(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&&Pc.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<A_&&(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)},O_).unref()})}),I_=({cwd:e,timeoutMs:t})=>D_({command:Pc.execPath,args:[Pc.argv[1]??"","setup","--unattended","--json"],cwd:e,env:Wg(Pc.env),timeoutMs:t}),N_=e=>{P_.writeFileSync(Dn(),e,{mode:384})},__=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}},M_=new RegExp("\x1B\\[[0-9;]*m","g"),j_=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(M_,"").split(`
445
+ `).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},F_=(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}},mb=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":Oa(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(C_,o)}),a=i.error===null?__(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${j_(i)} \u2014 run: ${s}`]}:{root:e,...F_(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},L_=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}})},B_=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(`
446
446
  `)}
447
- `},__=e=>({version:e.version??U.version,home:e.home??k_(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Tl({lockPath:Ty()})),readRecord:e.readRecord??Dn,writeRecord:e.writeRecord??Cy,discoverProjects:e.discoverProjects??(()=>ab()),runSetupChild:e.runSetupChild??T_,writeLog:e.writeLog??C_}),M_=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},j_=async e=>{let t=e.readRecord(),r=e.clock();if(!Oy(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+S_,s=await cb(null,e.home,e,o),i=M_(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 cb(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:I_(a)};e.writeRecord(c);try{e.writeLog(N_(c))}catch{}return"ran"},lb=async(e={})=>{try{let t=__(e),r=t.acquireLock();if(r===null)return"already-running";try{return await j_(t)}finally{r()}}catch{return"not-due"}},F_={outcome:b_.enum(["ran","not-due","already-running"])},im=async(e={})=>{let r={outcome:await lb(e)};return{content:R(JSON.stringify(r)),structuredContent:r}};import{spawnSync as V_}from"node:child_process";import{homedir as W_}from"node:os";import G_ from"node:process";var L_=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},B_=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},U_=(e,t)=>{let r=L_(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},di=(e,t)=>{let r=[...B_(e),...U_(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},pi=e=>e.steps.map(Je);var J_=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],K_=e=>{let t={...Bf(e)};for(let r of J_)delete t[r];return t},am=(e,t,r={})=>{let n=r.spawnSync??V_,o=r.env??G_.env,s=(r.agentMode??te)(),i=pi(e),a=di(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:z_({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??H_}):{ran:!1,commands:i,refusedBecause:a.reasons}},H_=e=>{d.info(e)},db=64,q_=db*1024*1024,z_=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=K_(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:q_,cwd:W_(),env:s}),l=tM(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},Y_=5,X_=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,ub=e=>e==null?[]:String(e).split(`
448
- `).map(t=>t.trim()).filter(t=>t.length>0),Z_=e=>{let t=ub(e.stderr),r=ub(e.stdout),n=[...t,...r].filter(s=>X_.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-Y_).join(" / ")},Q_="ENOBUFS",eM=e=>e.error?.code===Q_,tM=e=>{if(eM(e))return`terminated after exceeding the ${db} 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=Z_(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var rM=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},nM=e=>{let t=Xe(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},oM=(e,t)=>{let r=nM(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=di(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:pi(r),context:n}},xc=async(e=_r,t=us())=>{let r=await ps(_r,t),n={owner:null,present:rM(r)},o=Ju(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>oM(s.get(a),n)),context:n}};var cm=(e,t)=>({...mi(e),action:"skipped",commands:e.commands,detail:t}),mi=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),pb=(e,t)=>e.action==="none"?cm(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?cm(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...mi(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},sM=(e,t)=>t.ran?t.ok?{...mi(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...mi(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...mi(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},lm=async e=>{let t=e.run??am,{plans:r}=await xc(e.ids,e.probeDeps),n=[];for(let o of r){let s=pb(o,e.mode);if(s!==null){n.push(s);continue}n.push(sM(o,t(o.recipe,o.context)))}return n},um=async(e,t)=>{let{plans:r}=await xc(e,t);return r.map(n=>pb(n,"converge")??cm(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import bM from"node:process";import{z as j}from"zod";var dm={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},iM=Object.keys(dm).sort((e,t)=>dm[e]-dm[t]),mb={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},fb=new Set(["manual","warn","fail"]),pm=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 Ke(e)}},aM=e=>e.reduce((t,r)=>mb[r]>mb[t]?r:t,"skipped"),hb=e=>e.message.trim(),cM=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 "),gb=e=>e.message===Gn,lM=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?hb(r):e.length>1?cM(e):t?"activate with the last line below":"see below"},uM=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>pm(i.outcome)),n=t.filter(i=>fb.has(pm(i.outcome))).map(hb),o=t.filter(i=>!fb.has(pm(i.outcome))&&!gb(i)),s={name:e,status:aM(r),message:lM(o,t.some(gb))};return n.length>0?{...s,notes:n}:s},dM=e=>({label:"Local setup",rows:iM.map(t=>uM(t,e.filter(r=>r.step===t)))}),pM=(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 Ke(e.action)}},mM=(e,t)=>{let r=pM(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},fM=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>mM(r,t))}),gM=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 Ke(e)}},hM=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 Ke(e)}},yM=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 Ke(e)}},vM=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 Ke(e.outcome)}},wM=(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 Ke(e)}},kM=e=>({label:"Portless service",rows:[{name:"link",status:gM(e.link),message:yM(e.link)},{name:"node",status:hM(e.node.outcome),message:vM(e.node)},wM(e.service,e.command)]}),yb=(e,t)=>[dM(e.init),fM(e.tools,t),kM(e.portless)],vb=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var RM=()=>{let{link:e,node:t}=Mi();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},SM=async e=>{let t=rg(e.link).outcome,r=tg(e.node),n=_i(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 Ey(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Ot(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},kb="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",bb="--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.",EM=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(kb);if(o&&(e.tools!==void 0||r))throw new Error(bb);return{ids:e.tools??t??_r,mode:r?"update":"converge",skipTools:o}},wb=(e,t)=>e instanceof Wn?e.step:t.at(-1)?.step??"zshrc",PM=async()=>{let e=[];try{await td(t=>{e.push(t)})}catch(t){e.push({step:wb(t,e),outcome:"failed",message:`The ${wb(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},xM=(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}`}))},TM=async(e,t)=>{try{return e.skipTools?await um(e.ids,t.probeDeps):await lm({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return xM(e.ids,r)}},CM=e=>({step:e.step,outcome:e.outcome,message:e.message}),Tc=async(e={})=>{let t=EM(e);it.withheld=e.unattended===!0;let r=await PM(),n=await TM(t,e),o=await SM(e.portlessDeps??RM()),s=yb({init:r,tools:n,portless:o},{skipTools:t.skipTools});bt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(Gn),vb(s)&&(bM.exitCode=1);let i={init:r.map(CM),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}},$M=j.object({step:j.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:j.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:j.string().describe("The same line a human running this would have read")}),AM=j.object({id:j.string().describe("Dependency id"),action:j.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:j.object({present:j.boolean(),onPath:j.boolean(),version:j.string().nullable(),manager:j.string()}).describe("The tool\u2019s state before this run"),commands:j.array(j.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:j.string().describe("Why, in one line")}),OM=j.object({link:j.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:j.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:j.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:j.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")}),DM={init:j.array($M).describe("One entry per init step, in the order they ran"),tools:j.array(AM).describe("One result per requested dependency"),portlessService:OM.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:j.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:j.boolean().describe("Whether anything was installed or updated"),report:j.array(j.object({label:j.string().describe("Section heading"),rows:j.array(j.object({name:j.string().describe("Init step, tool id, or portless part"),status:j.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:j.string().describe("The row message, as printed"),notes:j.array(j.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:j.boolean().describe("Whether no tool failed (a refusal is not a failure)")},IM={tools:j.array(j.enum(_r)).optional().describe("Which tools to act on. Omit for all six."),mode:j.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:j.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},mm=T({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:IM,outputSchema:DM,requiresHumanConfirm:!0,handler:e=>Tc({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Cb}from"node:fs";import $b from"node:path";import JM from"node:process";import{z as Kt}from"zod";import{createHash as _M}from"node:crypto";import{readFileSync as MM}from"node:fs";import{Buffer as Cc}from"node:buffer";var Rb=/^\s*(?:#|\/\/|;|--|<!--)\s*infra-kit:local-(start|end)\s*(?:-->\s*)?$/,NM=Cc.from("infra-kit:local-"),fm=e=>{let t=e.findIndex(n=>Rb.exec(n)?.[1]==="start");if(t===-1)return null;let r=e.slice(t+1).findIndex(n=>Rb.exec(n)?.[1]==="end");return r===-1?null:{start:t,end:t+1+r}},Sb=e=>e.includes(NM)?e.toString("utf8").split(`
449
- `):null,Eb=e=>{let t=Sb(e),r=t&&fm(t);return t&&r?t.slice(r.start,r.end+1).join(`
450
- `):null},Pb=e=>{let t=Sb(e),r=t&&fm(t);return!t||!r?e:Cc.from([...t.slice(0,r.start),...t.slice(r.end+1)].join(`
451
- `))},xb=(e,t)=>{let r=e.toString("utf8").split(`
452
- `),n=fm(r);if(n)return Cc.from([...r.slice(0,n.start),t,...r.slice(n.end+1)].join(`
447
+ `},U_=e=>({version:e.version??U.version,home:e.home??x_(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Cl({lockPath:Dy()})),readRecord:e.readRecord??In,writeRecord:e.writeRecord??Iy,discoverProjects:e.discoverProjects??(()=>pb()),runSetupChild:e.runSetupChild??I_,writeLog:e.writeLog??N_}),V_=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},W_=async e=>{let t=e.readRecord(),r=e.clock();if(!My(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+$_,s=await mb(null,e.home,e,o),i=V_(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 mb(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:L_(a)};e.writeRecord(c);try{e.writeLog(B_(c))}catch{}return"ran"},fb=async(e={})=>{try{let t=U_(e),r=t.acquireLock();if(r===null)return"already-running";try{return await W_(t)}finally{r()}}catch{return"not-due"}},G_={outcome:T_.enum(["ran","not-due","already-running"])},am=async(e={})=>{let r={outcome:await fb(e)};return{content:R(JSON.stringify(r)),structuredContent:r}};import{spawnSync as q_}from"node:child_process";import{homedir as z_}from"node:os";import Y_ from"node:process";var J_=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},K_=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},H_=(e,t)=>{let r=J_(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},di=(e,t)=>{let r=[...K_(e),...H_(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},pi=e=>e.steps.map(Je);var X_=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],Z_=e=>{let t={...Uf(e)};for(let r of X_)delete t[r];return t},cm=(e,t,r={})=>{let n=r.spawnSync??q_,o=r.env??Y_.env,s=(r.agentMode??te)(),i=pi(e),a=di(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:tM({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??Q_}):{ran:!1,commands:i,refusedBecause:a.reasons}},Q_=e=>{d.info(e)},hb=64,eM=hb*1024*1024,tM=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=Z_(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:eM,cwd:z_(),env:s}),l=aM(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},rM=5,nM=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,gb=e=>e==null?[]:String(e).split(`
448
+ `).map(t=>t.trim()).filter(t=>t.length>0),oM=e=>{let t=gb(e.stderr),r=gb(e.stdout),n=[...t,...r].filter(s=>nM.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-rM).join(" / ")},sM="ENOBUFS",iM=e=>e.error?.code===sM,aM=e=>{if(iM(e))return`terminated after exceeding the ${hb} 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=oM(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var cM=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},lM=e=>{let t=Xe(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},uM=(e,t)=>{let r=lM(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=di(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:pi(r),context:n}},xc=async(e=_r,t=us())=>{let r=await ps(_r,t),n={owner:null,present:cM(r)},o=Ku(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>uM(s.get(a),n)),context:n}};var lm=(e,t)=>({...mi(e),action:"skipped",commands:e.commands,detail:t}),mi=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),yb=(e,t)=>e.action==="none"?lm(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?lm(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...mi(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},dM=(e,t)=>t.ran?t.ok?{...mi(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...mi(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...mi(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},um=async e=>{let t=e.run??cm,{plans:r}=await xc(e.ids,e.probeDeps),n=[];for(let o of r){let s=yb(o,e.mode);if(s!==null){n.push(s);continue}n.push(dM(o,t(o.recipe,o.context)))}return n},dm=async(e,t)=>{let{plans:r}=await xc(e,t);return r.map(n=>yb(n,"converge")??lm(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import TM from"node:process";import{z as j}from"zod";var pm={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},pM=Object.keys(pm).sort((e,t)=>pm[e]-pm[t]),vb={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},wb=new Set(["manual","warn","fail"]),mm=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 Ke(e)}},mM=e=>e.reduce((t,r)=>vb[r]>vb[t]?r:t,"skipped"),bb=e=>e.message.trim(),fM=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 "),kb=e=>e.message===Jn,gM=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?bb(r):e.length>1?fM(e):t?"activate with the last line below":"see below"},hM=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>mm(i.outcome)),n=t.filter(i=>wb.has(mm(i.outcome))).map(bb),o=t.filter(i=>!wb.has(mm(i.outcome))&&!kb(i)),s={name:e,status:mM(r),message:gM(o,t.some(kb))};return n.length>0?{...s,notes:n}:s},yM=e=>({label:"Local setup",rows:pM.map(t=>hM(t,e.filter(r=>r.step===t)))}),vM=(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 Ke(e.action)}},wM=(e,t)=>{let r=vM(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},kM=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>wM(r,t))}),bM=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 Ke(e)}},RM=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 Ke(e)}},SM=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 Ke(e)}},EM=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 Ke(e.outcome)}},PM=(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 Ke(e)}},xM=e=>({label:"Portless service",rows:[{name:"link",status:bM(e.link),message:SM(e.link)},{name:"node",status:RM(e.node.outcome),message:EM(e.node)},PM(e.service,e.command)]}),Rb=(e,t)=>[yM(e.init),kM(e.tools,t),xM(e.portless)],Sb=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var CM=()=>{let{link:e,node:t}=Mi();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},$M=async e=>{let t=ng(e.link).outcome,r=rg(e.node),n=_i(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 $y(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Dt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},Pb="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",xb="--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.",AM=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(Pb);if(o&&(e.tools!==void 0||r))throw new Error(xb);return{ids:e.tools??t??_r,mode:r?"update":"converge",skipTools:o}},Eb=(e,t)=>e instanceof Gn?e.step:t.at(-1)?.step??"zshrc",OM=async()=>{let e=[];try{await rd(t=>{e.push(t)})}catch(t){e.push({step:Eb(t,e),outcome:"failed",message:`The ${Eb(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},DM=(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}`}))},IM=async(e,t)=>{try{return e.skipTools?await dm(e.ids,t.probeDeps):await um({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return DM(e.ids,r)}},NM=e=>({step:e.step,outcome:e.outcome,message:e.message}),Tc=async(e={})=>{let t=AM(e);it.withheld=e.unattended===!0;let r=await OM(),n=await IM(t,e),o=await $M(e.portlessDeps??CM()),s=Rb({init:r,tools:n,portless:o},{skipTools:t.skipTools});Rt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(Jn),Sb(s)&&(TM.exitCode=1);let i={init:r.map(NM),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}},_M=j.object({step:j.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:j.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:j.string().describe("The same line a human running this would have read")}),MM=j.object({id:j.string().describe("Dependency id"),action:j.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:j.object({present:j.boolean(),onPath:j.boolean(),version:j.string().nullable(),manager:j.string()}).describe("The tool\u2019s state before this run"),commands:j.array(j.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:j.string().describe("Why, in one line")}),jM=j.object({link:j.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:j.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:j.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:j.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")}),FM={init:j.array(_M).describe("One entry per init step, in the order they ran"),tools:j.array(MM).describe("One result per requested dependency"),portlessService:jM.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:j.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:j.boolean().describe("Whether anything was installed or updated"),report:j.array(j.object({label:j.string().describe("Section heading"),rows:j.array(j.object({name:j.string().describe("Init step, tool id, or portless part"),status:j.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:j.string().describe("The row message, as printed"),notes:j.array(j.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:j.boolean().describe("Whether no tool failed (a refusal is not a failure)")},LM={tools:j.array(j.enum(_r)).optional().describe("Which tools to act on. Omit for all six."),mode:j.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:j.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},fm=T({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:LM,outputSchema:FM,requiresHumanConfirm:!0,handler:e=>Tc({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Ib}from"node:fs";import Nb from"node:path";import XM from"node:process";import{z as Ht}from"zod";import{createHash as UM}from"node:crypto";import{readFileSync as VM}from"node:fs";import{Buffer as Cc}from"node:buffer";var Tb=/^\s*(?:#|\/\/|;|--|<!--)\s*infra-kit:local-(start|end)\s*(?:-->\s*)?$/,BM=Cc.from("infra-kit:local-"),gm=e=>{let t=e.findIndex(n=>Tb.exec(n)?.[1]==="start");if(t===-1)return null;let r=e.slice(t+1).findIndex(n=>Tb.exec(n)?.[1]==="end");return r===-1?null:{start:t,end:t+1+r}},Cb=e=>e.includes(BM)?e.toString("utf8").split(`
449
+ `):null,$b=e=>{let t=Cb(e),r=t&&gm(t);return t&&r?t.slice(r.start,r.end+1).join(`
450
+ `):null},Ab=e=>{let t=Cb(e),r=t&&gm(t);return!t||!r?e:Cc.from([...t.slice(0,r.start),...t.slice(r.end+1)].join(`
451
+ `))},Ob=(e,t)=>{let r=e.toString("utf8").split(`
452
+ `),n=gm(r);if(n)return Cc.from([...r.slice(0,n.start),t,...r.slice(n.end+1)].join(`
453
453
  `));let o=r.join(`
454
454
  `);return Cc.from(`${o}${o===""||o.endsWith(`
455
455
  `)?"":`
456
456
  `}${t}
457
- `)};var yo=e=>_M("sha256").update(Pb(MM(e))).digest("hex");import{readFileSync as VM,writeFileSync as WM}from"node:fs";import Dc from"node:path";import{z as Tt}from"zod";var ce="vendor",jM=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),FM=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),LM=[".tsbuildinfo"],gm=e=>jM.has(e),hm=e=>FM.has(e)?!0:LM.some(t=>e.endsWith(t)),$c=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>gm(o))||hm(r)};import{readdirSync as BM}from"node:fs";import ym from"node:path";var UM=e=>e.split(ym.sep).join("/"),Ac=e=>{let t=[],r=n=>{for(let o of BM(n,{withFileTypes:!0})){let s=ym.join(n,o.name);if(o.isDirectory()){if(gm(o.name))continue;r(s);continue}hm(o.name)||t.push(UM(ym.relative(e,s)))}};return r(e),t.sort()};var nt=".sync-manifest.json",Oc=1,GM=Tt.object({schemaVersion:Tt.number().optional(),source:Tt.string(),commit:Tt.string(),syncedAt:Tt.string(),fileCount:Tt.number(),files:Tt.record(Tt.string(),Tt.string())}),vm=e=>(e.schemaVersion??Oc)>Oc,Tb=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Ac(e);for(let o of n)try{r[o]=yo(Dc.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},fi=e=>{let t=Dc.join(e,nt),r;try{r=VM(t,"utf8")}catch{throw new Error(`Missing ${nt} at ${t}`)}let n=GM.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${nt} at ${t}: ${Tt.prettifyError(n.error)}`);return n.data},wm=(e,t,r)=>{let n=Tb(e,r),o={schemaVersion:Oc,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return WM(Dc.join(e,nt),`${JSON.stringify(o,null,2)}
458
- `),o},km=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!$c(c))),n=Ac(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}yo(Dc.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 bm=30,Rm=(e,t)=>{if(t.length!==0){d.info(`
459
- ${e} (${t.length}):`);for(let r of t.slice(0,bm))d.info(` ${r}`);t.length>bm&&d.info(` \u2026and ${t.length-bm} more`)}},Ic=async(e={})=>{let t=e.cwd??await $(),r=$b.join(t,ce),n={modified:[],added:[],removed:[],fileCount:0};if(!Cb(r)){d.info(`\u2139\uFE0F No ${ce}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}if(!Cb($b.join(r,nt))){d.error(`\u274C Missing ${ce}/${nt}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let o=fi(r);if(vm(o)){d.error(`\u274C ${ce}/${nt} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=km(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${ce}/ has drifted from ${ce}/${nt}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Rm("Modified",s),Rm("Added (not in manifest)",i),Rm("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${ce}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},KM={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())},Sm=T({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:KM,handler:()=>Ic({cwd:JM.cwd()})});import Ab from"node:process";import{z as gi}from"zod";var Ob=async e=>{try{return await e()}catch{return null}},Nc=async()=>{let e=U.version;d.info(e);let t=await Ob($),r=t===null?null:await Ob(()=>_e(t)),n={version:e,cwd:Ab.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Ab.env.CLAUDE_PROJECT_DIR||null};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},Em=T({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:gi.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:gi.string().describe("The working directory of this process"),repoRoot:gi.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:gi.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:gi.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Nc});import Gb from"@inquirer/confirm";import ZM from"node:path";import{z as G}from"zod";import{$ as hi}from"zx";import HM from"@inquirer/input";import Ib from"@inquirer/select";import{$ as vr}from"zx";var vo="dev",qM="main",Nb=["new","local","remote"],_b=async()=>{let e=await vr({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},zM=2,Pm=async()=>{if(await ne()==="main")return ke;let e=await vr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${vo}`;if(e.exitCode===0)return vo;if(e.exitCode!==zM)throw new g(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${vo} exists`});return await _b()??vo},Mb=async e=>{let t=e?.trim();if(!t)return Pm();if(t===vo&&await ne()==="main")throw new g(void 0,{operation:"create feature worktree",remediation:'this repo sets "gitFlow": "main" in infra-kit.json, so features branch off main \u2014 drop --base or pass --base main'});return t===vo||t===qM||t===await _b()?t:Ae(Ee(t))},jb=async()=>_(e=>Ib({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"}}),Fb=async()=>_(e=>HM({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>uo(t)===Ws?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Lb=async(e,t)=>e.length===0?t:_(r=>Ib({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),YM=async e=>{let t=await vr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===Ws||t.exitCode!==0)throw new g(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},Db=async e=>(await vr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,XM=async e=>(await vr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Bb=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(uo))];for(let s of n)await YM(s);if(!await Db(r))throw new g(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await XM(s)?o.push({branch:s,base:r,source:"local"}):await Db(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Ub=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await vr`git worktree add ${t} ${r}`:o==="remote"?await vr`git worktree add --track -b ${r} ${t} origin/${r}`:await vr`git worktree add --no-track -b ${r} ${t} origin/${n}`},Vb=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 yi="create worktrees",QM=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],xm=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),_c=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await Be({operation:yi}),ej(e);try{let o=await $(),s=`${o}${le}`;await Wb(`${s}/${cn.release}`),await Wb(`${s}/${cn.feature}`);let i=await tj(e),a=i==="feature"?await nj(e):await rj(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let F={kind:i,createdWorktrees:[],count:0,features:[],...xm()};return{content:R(JSON.stringify(F,null,2)),structuredContent:F}}let c=await L(),l=await oj(r,c),u=await sj(n,c),p=await _e(o),m=ZM.basename(p),f=u?await ij({explicit:n!==void 0,mainRepoRoot:p}):null;await q(t,aj(f,m,a.previewLines)),t||y.addOption("--yes",!0);let h=f?await cj(f,p):null,b=await mj(a.targets,s);if(fj(b),l)for(let F of b)await hi`github ${s}/${F}`,await hi`sleep 5`;let C=h?await uj({registration:h,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):xm();dj(C),y.print();let k={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(F=>b.includes(F.branch)),...C};return{content:R(JSON.stringify(k,null,2)),structuredContent:k}}catch(o){throw Me(o)||xe(o)||o instanceof A?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:yi,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},ej=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new g(void 0,{operation:yi,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},tj=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),jb()),rj=async e=>{let{all:t,versions:r}=e,n=await Pe("release"),o=[];if(r)o=r.split(",").map(a=>Ae(Ee(a.trim())));else{let a=await K(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{y.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await ye();o=await fr(ve({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",Gt(o));let{branchesToCreate:s}=pj({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>hi`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},nj=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await Fb()],n===void 0)){let l=(await K()).map(u=>u.branch);n=await Lb(l,await Pm())}let o=await Mb(n),s=await Bb({names:r,base:o});y.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),y.addOption("--base",o);let i=await Pe("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=>Ub(l,u)})),features:a,previewLines:a.map(Vb)}},oj=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await _(o=>Gb({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},sj=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await _(o=>Gb({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--orca":"--no-orca",!0),n},Jb=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"},ij=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await tr();if(n!=="ready"){let{reason:s,text:i}=Jb(n);if(t)throw d.warn({operation:yi},`\u26D4 --orca was passed but ${i}`),new A({status:"refused",reason:s,agentMode:N.source},2,{operation:yi,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 Ig(r);return{probe:n,registered:o.registered,visibility:o.visibility}},aj=(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(`
460
- `)},cj=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Jb(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Ng(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 mn?r.code:void 0}}},lj=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,uj=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=xm();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=Pg(i),l=r.length===1&&t.visibility!=="hide",u=Mg();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await jg({cwd:m,title:Fg({branch:p}),focus:l,layout:"full",panes:c,poll:u});await _g(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:lj(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof mn&&f.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:f instanceof mn?f.code:void 0})}}return a},dj=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}`)}},Wb=async e=>{await hi`mkdir -p ${e}`},pj=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>un(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},mj=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await hi({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});d.error({error:s.reason,msg:a.message})}return n},fj=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")},Tm=T({name:"worktrees-add",description:`Create local git worktrees under the worktrees directory and run "pnpm install" in each: release worktrees for open release branches ("versions" / all=true), or feature worktrees ("feature", optional "base") \u2014 each name becomes a feature/<name> branch at <root>-worktrees/feature/<name>, cut from origin/<base> (default dev, or the default branch of a repo without dev; main; or any release branch) with no upstream, or checked out as-is when the branch already exists locally or on origin. Mutates the local filesystem. When invoked via MCP, pass "versions" (comma-separated), all=true, or "feature" \u2014 the branch picker and "open in Cursor / GitHub Desktop / Orca" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls. With "orca" true each created worktree gets an Orca terminal tab laid out per "worktrees.orca.layout"; the result reports orcaOpened, orcaSkipped (with a reason) and orcaHidden (a worktree Orca's sidebar hides, with the UI steps to reveal it). An unregistered repo is registered in Orca first (orca repo add).`,inputSchema:{feature:G.string().optional().describe('Comma-separated feature names (e.g. "checkout-v2" or "feature/checkout-v2"); each becomes a feature/<name> worktree. Cannot be combined with "versions" or "all".'),base:G.string().optional().describe(`Base for NEW feature branches: "dev" (default; the repo's default branch when it has no dev), "main", or a release ref ("1.4.0", "release/v1.4.0", "release/<name>"). Not applied to a feature branch that already exists. Implies a feature run.`),all:G.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:G.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:G.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:G.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:G.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:G.array(G.object({branch:G.string(),base:G.string(),source:G.enum(Nb)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:G.array(G.string()).describe("List of created git worktree branches"),count:G.number().describe("Number of git worktrees created"),orcaOpened:G.array(G.object({branch:G.string(),layout:G.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:G.array(G.object({branch:G.string(),reason:G.enum(QM),code:G.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:G.array(G.object({branch:G.string(),path:G.string(),fix:G.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:_c});import{z as wr}from"zod";var Mc=async()=>{await L();let[e,t]=await Promise.all([Pe("release"),Pe("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await gj(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
457
+ `)};var vo=e=>UM("sha256").update(Ab(VM(e))).digest("hex");import{readFileSync as qM,writeFileSync as zM}from"node:fs";import Dc from"node:path";import{z as Ct}from"zod";var ce="vendor",WM=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),GM=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),JM=[".tsbuildinfo"],hm=e=>WM.has(e),ym=e=>GM.has(e)?!0:JM.some(t=>e.endsWith(t)),$c=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>hm(o))||ym(r)};import{readdirSync as KM}from"node:fs";import vm from"node:path";var HM=e=>e.split(vm.sep).join("/"),Ac=e=>{let t=[],r=n=>{for(let o of KM(n,{withFileTypes:!0})){let s=vm.join(n,o.name);if(o.isDirectory()){if(hm(o.name))continue;r(s);continue}ym(o.name)||t.push(HM(vm.relative(e,s)))}};return r(e),t.sort()};var nt=".sync-manifest.json",Oc=1,YM=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())}),wm=e=>(e.schemaVersion??Oc)>Oc,Db=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Ac(e);for(let o of n)try{r[o]=vo(Dc.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},fi=e=>{let t=Dc.join(e,nt),r;try{r=qM(t,"utf8")}catch{throw new Error(`Missing ${nt} at ${t}`)}let n=YM.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${nt} at ${t}: ${Ct.prettifyError(n.error)}`);return n.data},km=(e,t,r)=>{let n=Db(e,r),o={schemaVersion:Oc,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return zM(Dc.join(e,nt),`${JSON.stringify(o,null,2)}
458
+ `),o},bm=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!$c(c))),n=Ac(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}vo(Dc.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 Rm=30,Sm=(e,t)=>{if(t.length!==0){d.info(`
459
+ ${e} (${t.length}):`);for(let r of t.slice(0,Rm))d.info(` ${r}`);t.length>Rm&&d.info(` \u2026and ${t.length-Rm} more`)}},Ic=async(e={})=>{let t=e.cwd??await $(),r=Nb.join(t,ce),n={modified:[],added:[],removed:[],fileCount:0};if(!Ib(r)){d.info(`\u2139\uFE0F No ${ce}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}if(!Ib(Nb.join(r,nt))){d.error(`\u274C Missing ${ce}/${nt}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let o=fi(r);if(wm(o)){d.error(`\u274C ${ce}/${nt} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=bm(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${ce}/ has drifted from ${ce}/${nt}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Sm("Modified",s),Sm("Added (not in manifest)",i),Sm("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${ce}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},ZM={status:Ht.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:Ht.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:Ht.number(),modified:Ht.array(Ht.string()),added:Ht.array(Ht.string()),removed:Ht.array(Ht.string())},Em=T({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:ZM,handler:()=>Ic({cwd:XM.cwd()})});import _b from"node:process";import{z as gi}from"zod";var Mb=async e=>{try{return await e()}catch{return null}},Nc=async()=>{let e=U.version;d.info(e);let t=await Mb($),r=t===null?null:await Mb(()=>_e(t)),n={version:e,cwd:_b.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:_b.env.CLAUDE_PROJECT_DIR||null};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},Pm=T({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:gi.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:gi.string().describe("The working directory of this process"),repoRoot:gi.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:gi.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:gi.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Nc});import zb from"@inquirer/confirm";import oj from"node:path";import{z as G}from"zod";import{$ as hi}from"zx";import QM from"@inquirer/input";import Fb from"@inquirer/select";import{$ as vr}from"zx";var wo="dev",ej="main",Lb=["new","local","remote"],Bb=async()=>{let e=await vr({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},tj=2,xm=async()=>{if(await ne()==="main")return ke;let e=await vr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${wo}`;if(e.exitCode===0)return wo;if(e.exitCode!==tj)throw new g(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${wo} exists`});return await Bb()??wo},Ub=async e=>{let t=e?.trim();if(!t)return xm();if(t===wo&&await ne()==="main")throw new g(void 0,{operation:"create feature worktree",remediation:'this repo sets "gitFlow": "main" in infra-kit.json, so features branch off main \u2014 drop --base or pass --base main'});return t===wo||t===ej||t===await Bb()?t:Ae(Ee(t))},Vb=async()=>_(e=>Fb({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"}}),Wb=async()=>_(e=>QM({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>po(t)===Ws?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Gb=async(e,t)=>e.length===0?t:_(r=>Fb({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),rj=async e=>{let t=await vr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===Ws||t.exitCode!==0)throw new g(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},jb=async e=>(await vr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,nj=async e=>(await vr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Jb=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(po))];for(let s of n)await rj(s);if(!await jb(r))throw new g(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await nj(s)?o.push({branch:s,base:r,source:"local"}):await jb(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Kb=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await vr`git worktree add ${t} ${r}`:o==="remote"?await vr`git worktree add --track -b ${r} ${t} origin/${r}`:await vr`git worktree add --no-track -b ${r} ${t} origin/${n}`},Hb=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 yi="create worktrees",sj=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Tm=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),_c=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await Be({operation:yi}),ij(e);try{let o=await $(),s=`${o}${le}`;await qb(`${s}/${cn.release}`),await qb(`${s}/${cn.feature}`);let i=await aj(e),a=i==="feature"?await lj(e):await cj(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let F={kind:i,createdWorktrees:[],count:0,features:[],...Tm()};return{content:R(JSON.stringify(F,null,2)),structuredContent:F}}let c=await L(),l=await uj(r,c),u=await dj(n,c),p=await _e(o),m=oj.basename(p),f=u?await pj({explicit:n!==void 0,mainRepoRoot:p}):null;await q(t,mj(f,m,a.previewLines)),t||y.addOption("--yes",!0);let h=f?await fj(f,p):null,b=await wj(a.targets,s);if(kj(b),l)for(let F of b)await hi`github ${s}/${F}`,await hi`sleep 5`;let C=h?await hj({registration:h,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):Tm();yj(C),y.print();let k={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(F=>b.includes(F.branch)),...C};return{content:R(JSON.stringify(k,null,2)),structuredContent:k}}catch(o){throw Me(o)||xe(o)||o instanceof A?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:yi,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},ij=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new g(void 0,{operation:yi,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},aj=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),Vb()),cj=async e=>{let{all:t,versions:r}=e,n=await Pe("release"),o=[];if(r)o=r.split(",").map(a=>Ae(Ee(a.trim())));else{let a=await K(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{y.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await ye();o=await fr(ve({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",Jt(o));let{branchesToCreate:s}=vj({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>hi`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},lj=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await Wb()],n===void 0)){let l=(await K()).map(u=>u.branch);n=await Gb(l,await xm())}let o=await Ub(n),s=await Jb({names:r,base:o});y.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),y.addOption("--base",o);let i=await Pe("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=>Kb(l,u)})),features:a,previewLines:a.map(Hb)}},uj=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await _(o=>zb({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},dj=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await _(o=>zb({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--orca":"--no-orca",!0),n},Yb=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"},pj=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await rr();if(n!=="ready"){let{reason:s,text:i}=Yb(n);if(t)throw d.warn({operation:yi},`\u26D4 --orca was passed but ${i}`),new A({status:"refused",reason:s,agentMode:N.source},2,{operation:yi,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 jg(r);return{probe:n,registered:o.registered,visibility:o.visibility}},mj=(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(`
460
+ `)},fj=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Yb(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Fg(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 fn?r.code:void 0}}},gj=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,hj=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Tm();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=$g(i),l=r.length===1&&t.visibility!=="hide",u=Bg();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Ug({cwd:m,title:Vg({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Lg(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:gj(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof fn&&f.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:f instanceof fn?f.code:void 0})}}return a},yj=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}`)}},qb=async e=>{await hi`mkdir -p ${e}`},vj=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>un(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},wj=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await hi({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});d.error({error:s.reason,msg:a.message})}return n},kj=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")},Cm=T({name:"worktrees-add",description:`Create local git worktrees under the worktrees directory and run "pnpm install" in each: release worktrees for open release branches ("versions" / all=true), or feature worktrees ("feature", optional "base") \u2014 each name becomes a feature/<name> branch at <root>-worktrees/feature/<name>, cut from origin/<base> (default dev, or the default branch of a repo without dev; main; or any release branch) with no upstream, or checked out as-is when the branch already exists locally or on origin. Mutates the local filesystem. When invoked via MCP, pass "versions" (comma-separated), all=true, or "feature" \u2014 the branch picker and "open in Cursor / GitHub Desktop / Orca" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls. With "orca" true each created worktree gets an Orca terminal tab laid out per "worktrees.orca.layout"; the result reports orcaOpened, orcaSkipped (with a reason) and orcaHidden (a worktree Orca's sidebar hides, with the UI steps to reveal it). An unregistered repo is registered in Orca first (orca repo add).`,inputSchema:{feature:G.string().optional().describe('Comma-separated feature names (e.g. "checkout-v2" or "feature/checkout-v2"); each becomes a feature/<name> worktree. Cannot be combined with "versions" or "all".'),base:G.string().optional().describe(`Base for NEW feature branches: "dev" (default; the repo's default branch when it has no dev), "main", or a release ref ("1.4.0", "release/v1.4.0", "release/<name>"). Not applied to a feature branch that already exists. Implies a feature run.`),all:G.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:G.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:G.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:G.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:G.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:G.array(G.object({branch:G.string(),base:G.string(),source:G.enum(Lb)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:G.array(G.string()).describe("List of created git worktree branches"),count:G.number().describe("Number of git worktrees created"),orcaOpened:G.array(G.object({branch:G.string(),layout:G.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:G.array(G.object({branch:G.string(),reason:G.enum(sj),code:G.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:G.array(G.object({branch:G.string(),path:G.string(),fix:G.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:_c});import{z as wr}from"zod";var Mc=async()=>{await L();let[e,t]=await Promise.all([Pe("release"),Pe("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await bj(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
461
461
 
462
- ${hj(r).join(`
462
+ ${Rj(r).join(`
463
463
  `)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
464
464
 
465
465
  ${t.join(`
466
466
  `)}`),d.info(n.join(`
467
467
 
468
- `));let o={worktrees:r,count:r.length,features:t};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},gj=async e=>{let[t,r]=await Promise.all([K(),ye()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=re(o);if(!s)return[];let i=ae(s),a=n.get(o)||"regular",c=r.get(pe(s))||null;return[{version:i,type:a,description:c}]})},hj=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=Ms(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Cm=T({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:wr.array(wr.object({version:wr.string().describe("Release version"),type:wr.enum(["regular","hotfix"]).describe("Release type"),description:wr.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:wr.number().describe("Number of release worktrees"),features:wr.array(wr.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:Mc});import{z as ot}from"zod";import yj from"node:fs/promises";import{$ as vj}from"zx";var Hb="remove this worktree",wj=2,kj=3,jc=async e=>{try{return await yj.realpath(e)}catch{return e}},en=(e,t)=>{throw new g(void 0,{operation:Hb,remediation:e,stderrExcerpt:t})},bj=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=Gt([e]);return un(e)&&t?["--versions",t]:en("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`)},Rj=async()=>{let e=await jc(await $()),t=await jc(await _e(e));e===t&&en("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 gt(t))await jc(o.path)===e&&(r=o.branch);if(!r)return en("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await jc(`${t}${le}/${r}`);return n!==e&&en("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:bj(r)}},Kb=async e=>(await vj({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
469
- `).filter(r=>r.trim().length>0),Sj=async e=>{let[t,r]=await Promise.all([Kb(e.worktreePath),Kb(e.mainRoot)]);t.length>0&&en("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&en(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await tr();n!=="ready"&&en(`run \`infra-kit worktrees remove ${Je(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},Ej=async e=>{let t=Je(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${wj}; ${t} && { sleep ${kj}; exit; }`;try{return(await Ag(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof mn?new g(n,{operation:Hb,remediation:`run \`infra-kit worktrees remove ${Je(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},qb=async e=>{let t=await Rj();await Sj(t),y.addOption("--self",!0),await q(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||y.addOption("--yes",!0);let r=await Ej(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),y.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:R(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var Pj=e=>{if(te()){if(e.all)throw new A({status:"refused",agentMode:N.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions&&!e.feature)throw new A({status:"argument_required",argument:"versions",agentMode:N.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},xj=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new g(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},Tj=async(e,t)=>{let r=await Ki(t.map(n=>`${e}/${n}`));if(r!==null)throw new A({status:"refused",reason:"orca_caller_inside_target",agentMode:N.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},Cj=e=>e?e.split(",").map(t=>Ae(Ee(t.trim()))):[],$j=e=>e?e.split(",").filter(t=>t.trim()!=="").map(uo):[],Aj=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&y.addOption("--versions",Gt(r)),t.length>0&&y.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Fc=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new g(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return qb(t)}await Be({operation:"remove worktrees"}),await L(),Pj({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([Pe("release"),Pe("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),y.print();let h={removedWorktrees:[],failedWorktrees:[],count:0};return{content:R(JSON.stringify(h,null,2)),structuredContent:h}}let l=await $(),u=`${l}${le}`,p=[];if(r)p=c;else if(n||o)p=[...Cj(n),...$j(o)];else{y.setInteractive();let[h,b]=await Promise.all([ye(),K()]),C=new Map(b.map(k=>[k.branch,k.type]));p=await fr([...ve({branches:i,descriptions:h,types:C}),...a.map(k=>({value:k,label:k,type:"feature"}))],{required:!0})}xj(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):Aj(p),await Tj(u,p),await q(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await Yr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Gs(f),y.print(),Js({result:f,operation:"remove worktrees"})}catch(i){throw Me(i)||xe(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},$m=T({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:ot.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:ot.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:ot.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:ot.array(ot.string()).describe("List of removed git worktree branches"),failedWorktrees:ot.array(ot.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ot.number().describe("Number of git worktrees removed"),handedOff:ot.object({branch:ot.string(),worktreePath:ot.string(),terminal:ot.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Fc});import{z as vi}from"zod";var Lc=async e=>{let{confirmedCommand:t}=e;await Be({operation:"sync worktrees"}),await L();try{let r=await Pe("release"),n=await $(),o=`${n}${le}`,s=await Xa();await q(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=Oj({releasePRsList:s,currentWorktrees:r}),a=await Yr({branches:i,worktreeDir:o,projectRoot:n});return Gs(a),y.print(),Js({result:a,operation:"sync worktrees"})}catch(r){throw Me(r)||xe(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},Oj=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>un(s)).filter(s=>!t.includes(s))}},Am=T({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:vi.array(vi.string()).describe("List of removed worktree branches"),failedWorktrees:vi.array(vi.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:vi.number().describe("Number of worktrees removed during sync")},handler:Lc});var Om=[{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"}],tn=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:$u,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:_d,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:fp,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:wp,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Kp,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:rm,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Zp,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:em,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:vp,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:sm,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Up,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Vp,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Tm,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Cm,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:$m,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Am,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Gd,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Fd,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Wd,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:jd,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Jd,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Tu,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:Sm,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","sync"]},{cliName:"deploy-run",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["deploy-run"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:mm,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Sd,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:hu,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Em,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:Eu,mcpExposed:!1,mutating:!1,groupPath:["change-stats"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:"environment",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]}];var Dm=e=>tn.filter(t=>t.menuGroup===e),Im=e=>tn.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var Dj=(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},zb=e=>Om.flatMap(({key:t,label:r})=>Dm(t).flatMap(n=>{let o=Dj(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import{Command as ZL,InvalidArgumentError as tS,Option as QR}from"commander";import{resolve as QL}from"node:path";import Ve from"node:process";import{cd as e0}from"zx";import Yb from"node:process";import{z as dt}from"zod";import{$ as Ij}from"zx";var Nj={projectName:dt.string(),layers:dt.array(dt.object({label:dt.string(),path:dt.string(),exists:dt.boolean()})),hasOverrides:dt.boolean(),overrideKeys:dt.array(dt.string())},_j={path:dt.string().describe("The per-project override file that was opened"),editor:dt.string()},Nm=async()=>{let e=await X(),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 ie(i.path)}))),r=t.at(-1)?.exists===!0,n=await cs(e.userProject,r),o=r?ls(n):"";d.info(`Project name: ${e.projectName}
468
+ `));let o={worktrees:r,count:r.length,features:t};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},bj=async e=>{let[t,r]=await Promise.all([K(),ye()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=re(o);if(!s)return[];let i=ae(s),a=n.get(o)||"regular",c=r.get(pe(s))||null;return[{version:i,type:a,description:c}]})},Rj=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=Ms(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},$m=T({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:wr.array(wr.object({version:wr.string().describe("Release version"),type:wr.enum(["regular","hotfix"]).describe("Release type"),description:wr.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:wr.number().describe("Number of release worktrees"),features:wr.array(wr.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:Mc});import{z as ot}from"zod";import Sj from"node:fs/promises";import{$ as Ej}from"zx";var Zb="remove this worktree",Pj=2,xj=3,jc=async e=>{try{return await Sj.realpath(e)}catch{return e}},en=(e,t)=>{throw new g(void 0,{operation:Zb,remediation:e,stderrExcerpt:t})},Tj=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=Jt([e]);return un(e)&&t?["--versions",t]:en("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`)},Cj=async()=>{let e=await jc(await $()),t=await jc(await _e(e));e===t&&en("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 gt(t))await jc(o.path)===e&&(r=o.branch);if(!r)return en("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await jc(`${t}${le}/${r}`);return n!==e&&en("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:Tj(r)}},Xb=async e=>(await Ej({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
469
+ `).filter(r=>r.trim().length>0),$j=async e=>{let[t,r]=await Promise.all([Xb(e.worktreePath),Xb(e.mainRoot)]);t.length>0&&en("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&en(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await rr();n!=="ready"&&en(`run \`infra-kit worktrees remove ${Je(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},Aj=async e=>{let t=Je(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${Pj}; ${t} && { sleep ${xj}; exit; }`;try{return(await Ng(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof fn?new g(n,{operation:Zb,remediation:`run \`infra-kit worktrees remove ${Je(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Qb=async e=>{let t=await Cj();await $j(t),y.addOption("--self",!0),await q(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||y.addOption("--yes",!0);let r=await Aj(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),y.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:R(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var Oj=e=>{if(te()){if(e.all)throw new A({status:"refused",agentMode:N.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions&&!e.feature)throw new A({status:"argument_required",argument:"versions",agentMode:N.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},Dj=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new g(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},Ij=async(e,t)=>{let r=await Ki(t.map(n=>`${e}/${n}`));if(r!==null)throw new A({status:"refused",reason:"orca_caller_inside_target",agentMode:N.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},Nj=e=>e?e.split(",").map(t=>Ae(Ee(t.trim()))):[],_j=e=>e?e.split(",").filter(t=>t.trim()!=="").map(po):[],Mj=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&y.addOption("--versions",Jt(r)),t.length>0&&y.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Fc=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new g(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return Qb(t)}await Be({operation:"remove worktrees"}),await L(),Oj({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([Pe("release"),Pe("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),y.print();let h={removedWorktrees:[],failedWorktrees:[],count:0};return{content:R(JSON.stringify(h,null,2)),structuredContent:h}}let l=await $(),u=`${l}${le}`,p=[];if(r)p=c;else if(n||o)p=[...Nj(n),..._j(o)];else{y.setInteractive();let[h,b]=await Promise.all([ye(),K()]),C=new Map(b.map(k=>[k.branch,k.type]));p=await fr([...ve({branches:i,descriptions:h,types:C}),...a.map(k=>({value:k,label:k,type:"feature"}))],{required:!0})}Dj(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):Mj(p),await Ij(u,p),await q(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await Yr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Gs(f),y.print(),Js({result:f,operation:"remove worktrees"})}catch(i){throw Me(i)||xe(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Am=T({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:ot.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:ot.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:ot.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:ot.array(ot.string()).describe("List of removed git worktree branches"),failedWorktrees:ot.array(ot.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ot.number().describe("Number of git worktrees removed"),handedOff:ot.object({branch:ot.string(),worktreePath:ot.string(),terminal:ot.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Fc});import{z as vi}from"zod";var Lc=async e=>{let{confirmedCommand:t}=e;await Be({operation:"sync worktrees"}),await L();try{let r=await Pe("release"),n=await $(),o=`${n}${le}`,s=await Xa();await q(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=jj({releasePRsList:s,currentWorktrees:r}),a=await Yr({branches:i,worktreeDir:o,projectRoot:n});return Gs(a),y.print(),Js({result:a,operation:"sync worktrees"})}catch(r){throw Me(r)||xe(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},jj=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>un(s)).filter(s=>!t.includes(s))}},Om=T({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:vi.array(vi.string()).describe("List of removed worktree branches"),failedWorktrees:vi.array(vi.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:vi.number().describe("Number of worktrees removed during sync")},handler:Lc});var Dm=[{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"}],tn=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Au,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:Md,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:gp,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:kp,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Hp,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:nm,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Qp,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:tm,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:wp,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:im,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Vp,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Wp,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Cm,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:$m,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Am,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Om,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Jd,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Ld,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Gd,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Fd,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Kd,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Cu,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:Em,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","sync"]},{cliName:"deploy-run",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["deploy-run"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:fm,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Ed,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:yu,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Pm,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:Pu,mcpExposed:!1,mutating:!1,groupPath:["change-stats"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:"environment",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]}];var Im=e=>tn.filter(t=>t.menuGroup===e),Nm=e=>tn.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var Fj=(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},eR=e=>Dm.flatMap(({key:t,label:r})=>Im(t).flatMap(n=>{let o=Fj(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import{Command as o0,InvalidArgumentError as iS,Option as oS}from"commander";import{resolve as s0}from"node:path";import Ve from"node:process";import{cd as i0}from"zx";import tR from"node:process";import{z as dt}from"zod";import{$ as Lj}from"zx";var Bj={projectName:dt.string(),layers:dt.array(dt.object({label:dt.string(),path:dt.string(),exists:dt.boolean()})),hasOverrides:dt.boolean(),overrideKeys:dt.array(dt.string())},Uj={path:dt.string().describe("The per-project override file that was opened"),editor:dt.string()},_m=async()=>{let e=await X(),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 ie(i.path)}))),r=t.at(-1)?.exists===!0,n=await cs(e.userProject,r),o=r?ls(n):"";d.info(`Project name: ${e.projectName}
470
470
  `),d.info(`Config merge chain (later overrides earlier):
471
- `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},_m=async()=>{let e=await X(),t=Yb.env.EDITOR||Yb.env.VISUAL||"vi",r=await jn(e);r.createdConfig&&d.info(Fn(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await Ij({stdio:"inherit"})`${t} ${e.userProject}`,Zt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};import{z as wi}from"zod";var Mj={key:wi.string(),value:wi.unknown().describe("The parsed value written"),previous:wi.unknown().describe("The value the layer held before, or null"),scope:wi.enum(["project","global"]),path:wi.string().describe("The layer file written")},Mm=async({key:e,value:t,global:r})=>{Qo(e,"config-set");let n=r?"global":"project",o=xu(t),{file:s,previous:i}=await es(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${Pn[n]} (${w(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:R(JSON.stringify(a,null,2)),structuredContent:a}};import{z as ki}from"zod";var jj={key:ki.string(),removed:ki.boolean(),previous:ki.unknown().describe("The value the layer held before, or null"),scope:ki.enum(["project","global"]),path:ki.string().describe("The layer file edited")},jm=async({key:e,global:t})=>{Qo(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await es(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${Pn[r]} (${w(n)})`:`${e} is not set in the ${Pn[r]} (${w(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}};import rR from"node:fs/promises";import bi from"node:path";import Xj from"node:process";import{pathToFileURL as Zj}from"node:url";import{z as Wm}from"zod";import{execFile as Uj,spawn as Vj}from"node:child_process";import br from"node:fs/promises";import Wj from"node:os";import kr from"node:path";import Zb from"node:process";import{promisify as Gj}from"node:util";import Xb from"node:fs/promises";import Fj from"node:path";import{pathToFileURL as Lj}from"node:url";var Bj=".infra-kit-import-from-app.mjs",Fm=async(e,t)=>{let r=Fj.join(e,Bj);await Xb.writeFile(r,`export const resolveHere = (specifier) => import.meta.resolve(specifier)
472
- `);try{let{resolveHere:n}=await import(Lj(r).href);return await import(n(t))}finally{await Xb.rm(r,{force:!0})}};var Jj=Gj(Uj),Qb="3.39.0",Kj=10*1024*1024,Hj=960,qj=60,Lm=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,zj=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${Lm(e)}`}},wo=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},Yj=(e,t,r)=>new Promise((n,o)=>{let s=Vj(e,t,{cwd:r.cwd,env:r.env,stdio:"inherit"});s.on("error",o),s.on("exit",(i,a)=>{i===0?n():o(new Error(`${e} exited with ${a??i}`))})}),Uc={run:Yj,capture:async(e,t,r)=>{let{stdout:n}=await Jj(e,t,{...r,maxBuffer:Kj});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{Zb.stdout.write(`${e}
473
- `)}},Bc=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),eR=async e=>{let t=JSON.parse(await br.readFile(kr.join(e,"package.json"),"utf-8")),r=t.devDependencies?.turbo??t.dependencies?.turbo,n=r?.replace(/^[\^~=v]+/,"");if(n===void 0||!/^\d+\.\d+\.\d+/.test(n))throw new Error(`the root package.json must pin turbo to an exact version (found ${r??"none"})`);return n},Um=async e=>{let t=await br.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=kr.join(e,r.name);return r.name==="node_modules"?br.rm(n,{recursive:!0,force:!0}):Um(n)}))},Bm=async(e,t,r)=>{let n=r.appPath??t;if(n===void 0)throw new Error("pass app and appPath, or put the deploy script in the app it deploys");if(r.app!==void 0)return{app:r.app,appPath:n};try{let o=JSON.parse(await br.readFile(kr.join(e,n,"package.json"),"utf-8"));if(o.name)return{app:o.name,appPath:n}}catch{}throw new Error(`${n} has no package.json name to deploy; pass app explicitly`)},Vm=({root:e,service:t,project:r,scriptDir:n,env:o=Zb.env,deps:s=Uc})=>{let i=async(v,S,P,O={})=>{s.log(`COMMAND: ${[S,...P].join(" ")}`);try{await s.run(S,P,{cwd:O.cwd??e,env:O.env??o})}catch(D){throw new Error(`${v} failed: ${D.message}`)}},a=async(v,S,P={})=>{let{attempts:O=8,initialDelaySeconds:D=3,maxDelaySeconds:V=60}=P,Re=async se=>{try{return await S()}catch($t){if(se>=O)throw new Error(`${v} failed after ${O} attempts: ${$t.message}`);let Ci=Math.min(V,D*2**(se-1)),$i=Math.round((Ci/2+s.random()*Ci/2)*10)/10;return s.log(`Attempt ${se}/${O} failed. Retrying in ${$i}s...`),await s.sleep($i*1e3),Re(se+1)}};return Re(1)},c=async(v,S,P=o)=>{s.log(`COMMAND: aws ${S.join(" ")}`),await a(v,()=>s.run("aws",S,{cwd:e,env:Bc(P)}))},l=async(v,S={})=>{await i(`aws ${v.slice(0,2).join(" ")}`,"aws",v,{cwd:S.cwd,env:Bc(S.env??o)})},u=async v=>{let S=await Promise.all(v.map(async P=>{try{let O=await s.capture("aws",["ssm","get-parameter","--name",P,"--query","Parameter.Value","--output","text"],{cwd:e,env:Bc(o)});return[P,O.trim()]}catch(O){throw new Error(`SSM parameter ${P}: ${O instanceof Error?O.message:String(O)}`)}}));return Object.fromEntries(S)},p=async v=>{let S=[`turbo@${await eR(e)}`,...v?[`serverless@${Qb}`]:[]];await i("Install tools","pnpm",["add","-g",...S])},m=async(v,S)=>{let P=kr.join(e,"out"),O={...o,...S.buildEnv},D=S.buildTask??O.TURBO_BUILD_TASK??"build";return await br.rm(P,{recursive:!0,force:!0}),await i(`Prune to ${v}`,"turbo",["prune",v],{env:O}),await i("Install dependencies","pnpm",["install"],{cwd:P,env:O}),await i(`Build ${v}`,"pnpm",["exec","turbo",D,`--filter=${v}`,"--env-mode=loose"],{cwd:P,env:O}),S.installProd&&(s.log("COMMAND: remove every node_modules under ./out"),await Um(P),await i("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:P,env:O}),await i("Show node_modules size","du",["-sm","./node_modules/"],{cwd:P})),P},f=(v,S,P)=>({stage:v,outDir:S,appDir:P,importFromApp:O=>Fm(P,O)}),h=async(v,S,P)=>{if(S!==void 0){s.log(`Running ${v} hooks...`);try{await S(P)}catch(O){throw new Error(`${v} hooks failed: ${O.message}`)}s.log(`${v} hooks completed successfully`)}},b=async v=>{let{app:S,appPath:P}=await Bm(e,n,v);await p(!0);let O={...o,...v.buildEnv},D=await m(S,{installProd:!0,buildTask:v.buildTask,buildEnv:v.buildEnv}),V=f(v.stage,D,kr.join(D,P));await h("Pre-deployment",v.preDeploy,V),await i("Deploy with Serverless","serverless",["deploy","--stage",v.stage,"--force"],{cwd:V.appDir,env:O}),v.restApiId===void 0?s.log(`Skipping API Gateway deployment for ${S}: no restApiId.`):await c("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",v.restApiId,"--stage-name","api"],O),await h("Post-deployment",v.postDeploy,V)},C=async v=>{let{app:S,appPath:P}=await Bm(e,n,v);await p(!1);let O={...o,...v.buildEnv},D=await m(S,{installProd:!1,buildTask:v.buildTask,buildEnv:v.buildEnv}),V=f(v.stage,D,kr.join(D,P)),Re=`s3://${v.bucket}${v.destPath??""}`,se=v.sourcePath??"./dist";await i("Sync to S3","aws",["s3","sync",se,Re,...v.syncFlags??[],"--only-show-errors"],{cwd:V.appDir,env:Bc(O)}),await c("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",v.cloudfrontId,"--paths",v.invalidationPath??"/*"],O),await h("Post-deployment",v.postDeploy,V)},k=async(v,S,P)=>{let O=await br.mkdtemp(kr.join(Wj.tmpdir(),"infra-kit-lambda-")),D=kr.join(O,"response.json"),V=["lambda","invoke","--function-name",v.functionName,...P===void 0?[]:["--region",P],"--cli-binary-format","raw-in-base64-out","--payload",v.payload??S,"--cli-read-timeout",String(Hj),"--cli-connect-timeout",String(qj),D],Re=Date.now();s.log(`COMMAND: aws ${V.join(" ")}`);try{let se=await s.capture("aws",V,{cwd:e,env:{...o,AWS_PAGER:""}}).then(zj,il=>`aws CLI failed: ${Lm(il instanceof Error?il.message:String(il))}`),$t=await br.readFile(D,"utf-8").catch(()=>""),Ci=((Date.now()-Re)/1e3).toFixed(1),$i=se!==void 0&&$t?`; response: ${Lm($t)}`:"";return{outcome:`${v.functionName} (${Ci}s)`,failure:se===void 0?void 0:se+$i}}finally{await br.rm(O,{recursive:!0,force:!0})}};return{root:e,service:t,project:r,ssm:u,aws:l,run:(v,S,P={})=>s.run(v,S,{cwd:P.cwd??e,env:P.env??o}),capture:(v,S,P={})=>s.capture(v,S,{cwd:P.cwd??e,env:P.env??o}),retry:a,skip:v=>{throw new wo(v)},pruneAndBuild:m,deployBackendApi:b,deployFrontendUi:C,invokeLambdas:async v=>{let{region:S,payload:P="{}",blocking:O=[],steps:D=[]}=v;for(let V of O){let{outcome:Re,failure:se}=await k(V,P,S);if(se!==void 0)throw new Error(`Lambda ${Re} failed: ${se}`);s.log(`Lambda ${Re} OK`)}for(let V of D){let Re=await Promise.all(V.map(se=>k(se,P,S).catch($t=>({outcome:se.functionName,failure:String($t)}))));for(let{outcome:se,failure:$t}of Re)s.log($t===void 0?`Lambda ${se} OK`:`Warning: Lambda ${se} failed, continuing: ${$t}`)}},importFromApp:Fm}};var Qj={status:Wm.enum(["deployed","skipped"]),service:Wm.string(),reason:Wm.string().optional()},tR=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),eF=async(e,t)=>{let r=bi.join(e,"devops","scripts",`deploy-${t}.sh`);try{await rR.access(r)}catch{throw new g(void 0,{operation:`deploy ${t}`,remediation:`set services['${t}'].deploy in infra-kit.deploy.ts, e.g. 'apps/<app>/deploy.ts'`,stderrExcerpt:`${t} has no deploy in infra-kit.deploy.ts and no devops/scripts/deploy-${t}.sh`})}return r},tF=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
474
- `,"%0A")}`,rF=(e,t)=>{let r=(e??"").split(`
475
- `).filter(n=>n.trim()!=="").map(n=>{let o=n.indexOf("="),s=n.slice(0,Math.max(o,0));if(!/^[A-Z_][A-Z0-9_]*$/.test(s))throw new g(void 0,{operation:"deploy-run",remediation:"write each extra-env line as KEY=VALUE with an upper-case KEY",stderrExcerpt:"an extra-env line is not KEY=VALUE"});return[s,n.slice(o+1)]});for(let[,n]of r)n!==""&&t(tF(n));return Object.fromEntries(r)},nF=async e=>{try{await rR.access(e)}catch{throw new g(void 0,{operation:`run ${bi.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(Zj(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${bi.basename(e)}`,remediation:"export the deploy as `export default (async (toolkit) => { \u2026 }) satisfies DeployScript`",stderrExcerpt:"the script has no default-exported function"});return t.default},Gm=async e=>{let{service:t,env:r=Xj.env}=e;if(!/^[a-z0-9-]+$/.test(t))throw new g(void 0,{operation:"deploy-run",remediation:"pass the service as infra-kit.deploy.ts names it, e.g. client-be",stderrExcerpt:`invalid service name '${t}'`});if(te()&&r.INFRA_KIT_DEPLOY_VIA!==Xs)throw new A({status:"refused",agentMode:N.source},2,{operation:`deploy ${t}`,remediation:"ask a human to run `infra-kit deploy-run` from their own shell, or deploy through `infra-kit release deploy-selected` (CI) or `infra-kit local deploy-selected`, which check the environment first",stderrExcerpt:"deploy-run deploys with whatever AWS credentials are loaded: refused in agent mode"});let n=e.cwd??await $(),o=e.deps??Uc,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...rF(s,o.log)},c=await xt(n),l=c?.services[t]?.deploy;if(l===void 0)await o.run("sh",[await eF(n,t)],{cwd:n,env:a});else{let u=await nF(bi.join(n,l)),p=Vm({root:n,service:t,project:c?.project,scriptDir:bi.dirname(l),env:a,deps:o});try{await u(p)}catch(m){if(!(m instanceof wo))throw m;return d.info(`\u23ED\uFE0F ${t} skipped: ${m.message}`),tR({status:"skipped",service:t,reason:m.message})}}return d.info(`\u2705 ${t} deployed`),tR({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as Ri}from"@slip-stream-kit/config/internal";import Wc from"node:fs/promises";import Gc from"node:path";import{z as ko}from"zod";var Jm=async e=>{try{return await Wc.readFile(e,"utf-8")}catch{return}},oF={status:ko.enum(["written","unchanged","drift","missing-config"]),ok:ko.boolean(),files:ko.array(ko.object({path:ko.string(),status:ko.enum(["created","updated","unchanged","removed"])}))},Vc=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),sF={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},nR=async(e,t)=>(await Promise.all(t.map(async n=>{let o=Gc.join(e,n);return(await Jm(o))?.startsWith(mo)?[{path:n,absolute:o}]:[]}))).flat(),iF=async(e,t)=>t.replaceV1!==!0?[]:(await nR(e,Rp)).map(r=>({...r,status:"removed"})),aF=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Jm(Gc.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${Ri} do not exist: ${n.join(", ")}`)},cF=async(e,t)=>{if(t.replaceV1===!0)return;let r=await nR(e,Sp);if(r.length===0)return;let n=r.map(o=>o.path).join(", ");throw new Error(`${n} ${r.length===1?"was":"were"} generated under replaceV1, which ${Ri} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},Km=async(e={})=>{let t=e.cwd??await $(),r=await xt(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Ri} at ${t}, nothing to generate.`),Vc({status:"missing-config",ok:!!e.check,files:[]});await cF(t,r),await aF(t,r);let n=await Promise.all(Cp(r).map(async a=>{let c=Gc.join(t,a.path),l=await Jm(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await iF(t,r),s=[...n.filter(a=>a.status!=="unchanged"),...o],i=[...n,...o].map(({path:a,status:c})=>({path:a,status:c}));if(s.length===0)return d.info(`\u2705 Deploy workflows match ${Ri}.`),Vc({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${Ri}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${sF[a.status]})`);return Vc({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await Wc.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await Wc.mkdir(Gc.dirname(a.absolute),{recursive:!0}),await Wc.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return Vc({status:"written",ok:!0,files:i})};import{z as Jc}from"zod";var oR="https://dashboard.doppler.com/workplace/projects",lF=(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}"): ${oR}/${e}`],uF={env:Jc.string(),removed:Jc.boolean(),storePath:Jc.string(),revokeUrl:Jc.string()},Hm=async({env:e})=>{let r=!!(await fe())?.envs[e];await $g(e);let n=await He(),o=await er();r?d.info(`Removed the "${e}" service token from ${w(o)}.`):d.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of lF(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${oR}/${n}`};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}};import dF from"@inquirer/confirm";import pF from"@inquirer/input";import mF from"@inquirer/password";import fF from"@inquirer/select";import gF from"node:fs/promises";import Ct from"node:process";import{z as be}from"zod";import{$ as Kc}from"zx";var hF=async({stdin:e,fromEnv:t})=>{if(e)return{token:await sR(),source:"stdin"};if(t){let n=Ct.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!Ct.stdin.isTTY){let n=await sR();if(n)return{token:n,source:"stdin"};if(!H())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return y.setInteractive(),{token:(await _(n=>mF({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:Ct.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},sR=async()=>{let e=[];Ct.stdin.setEncoding("utf8");for await(let t of Ct.stdin)e.push(t);return e.join("").trim()},qm="DOPPLER_CONFIG",yF=3e4,vF=async(e,t,r)=>{let n=Kc.quiet;Kc.quiet=!0;let o;try{o=(await Kc({env:No(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(yF)).stdout}catch(s){throw wF(s,r)}finally{Kc.quiet=n}return Pl(o)},wF=(e,t)=>{let r=ag(e)??(e instanceof Error?e.message:String(e));if(vl(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=wl(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(`
476
- `))},kF=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${qm}.`,"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(`
477
- `),aR=async(e,t,r,n)=>{let o=await vF(e,t,r);El(o,r);let s=o.some(([i])=>i===qm);if(!s&&!n)throw new Error(kF(r));return s},iR="\0new-env",bF=async()=>{if(H()||!Ct.stdin.isTTY)throw new A({status:"argument_required",argument:"env",agentMode:N.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([ur(),fe()]),r=Math.max(0,...e.map(({env:s})=>s.length));y.setInteractive();let n=await _(s=>fF({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:iR}]},s),{output:Ct.stderr,whenHeadless:"refuse"});return n!==iR?n:(await _(s=>pF({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:Ct.stderr,whenHeadless:"refuse"})).trim()},RF=async(e,t,r)=>_(n=>dF({message:`Replace the "${e}" token ${Ne(t)} with ${Ne(r)}?`,default:!0},n),{output:Ct.stderr,whenHeadless:"refuse"}),SF=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${Ne(r)})`;case"replaced":return`Replaced the "${e}" service token ${Ne(n??"")} \u2192 ${Ne(r)}`;case"unchanged":return`The "${e}" service token is already ${Ne(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${Ne(n??"")} \u2014 nothing was written`;default:return Ke(t)}},zm=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await He(),s=e??await bF(),{token:i,source:a}=await hF({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await aR(i,o,s,n),l=(await fe())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await RF(s,l,i)?u="kept":(await bl({[s]:i}),u=l===void 0?"stored":"replaced");let p=await er();d.info(`${SF(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${qm} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:Ne(i),previousRedactedToken:l===void 0?null:Ne(l),storePath:p,scopeVerified:c};return y.print(),{content:R(JSON.stringify(m,null,2)),structuredContent:m}},EF=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,cR=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?EF(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},PF={env:be.string(),status:be.enum(["stored","replaced","unchanged","kept"]),source:be.enum(["stdin","env","prompt"]),redactedToken:be.string(),previousRedactedToken:be.string().nullable(),storePath:be.string(),scopeVerified:be.boolean()},xF={storePath:be.string(),rows:be.array(be.object({env:be.string(),status:be.enum(["stored","replaced","unchanged","failed"]),redactedToken:be.string(),scopeVerified:be.boolean(),error:be.string().optional()})),failedCount:be.number()},TF=e=>(e instanceof Error?e.message:String(e)).split(`
478
- `)[0]??"",CF=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",$F=async(e,t,r,n)=>{let o=Ne(e.token);try{let s=await aR(e.token,t,e.env,n);return{env:e.env,status:CF(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:TF(s)}}},Ym=async({fromFile:e,force:t})=>{let r=await He(),n=cR(await gF.readFile(e,"utf8")),o=await fe(),s=await Promise.all(n.map(p=>$F(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 bl(i);let a=await er(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${w(e)} \u2192 ${w(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${w(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(Ct.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}};var Xm=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 Yp(n);if(r&&y.addOption("--from",p),zp(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new g(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?vc({version:o,env:s,skipTerraform:a,confirmedCommand:c}):wc({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Zm=async e=>Xm(e,"all"),Qm=async e=>Xm(e,"selected"),Hc=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.`),Xm({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as uR}from"@slip-stream-kit/config/internal";import ef from"node:fs/promises";import bo from"node:path";import lR from"node:process";import{pathToFileURL as AF}from"node:url";var dR="~/projects",tf=async(e={})=>{if(e.init){await DF(e.cwd);return}await OF()},OF=async()=>{let e=Bn(),t=await ie(e);if(d.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),lR.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await $a(),s=Un(r),i=await ie(s),a=bo.join(s,n),c=await ie(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${w(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=bo.join(s,u),m=await ie(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",h=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${h}`)}l||(lR.exitCode=1)},DF=async e=>{let t=Bn();if(await ie(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await $(),n=await IF(r);await ef.mkdir(bo.dirname(t),{recursive:!0}),await ef.writeFile(t,NF(bo.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${uR}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${dR}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${bo.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.")},IF=async e=>{try{let t=bo.join(e,uR),r=await ef.stat(t),s=(await import(`${AF(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[]},NF=(e,t)=>`${JSON.stringify({workspaceDir:dR,source:e,targets:t},null,2)}
479
- `;import{existsSync as UL}from"node:fs";import VL from"node:fs/promises";import UR from"node:path";import VR from"node:process";import{z}from"zod";import{chmodSync as VF,copyFileSync as WF,lstatSync as GF,mkdirSync as RR,readFileSync as bR,readdirSync as JF,readlinkSync as KF,rmSync as HF,rmdirSync as SR,symlinkSync as qF,unlinkSync as zF,writeFileSync as ER}from"node:fs";import $e from"node:path";import{lstatSync as _F,readlinkSync as pR}from"node:fs";import MF from"node:path";var jF=new Set(["ENOENT","ENOTDIR"]),Si=e=>{let t;try{t=_F(e)}catch(r){if(jF.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:pR(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:yo(e)}:{kind:"other"}},mR=(e,t)=>{let r=MF.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:pR(r)}:{kind:"file",executable:t.mode==="100755",sha:yo(r)};return{...t,fingerprint:n}},fR=(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 FF}from"zx";var ee=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await FF({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},qc=e=>e.slice(0,7),pt=e=>e.split("\0").filter(t=>t.length>0);import LF from"node:path";var rf=`${ce}/`,Rr=`${ce}/README.md`,Ei=`${ce}/${nt}`,hR=e=>e.startsWith(rf),gR=e=>{let t=LF.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},yR=e=>{let t=gR(e.path),r=e.target===void 0?t:gR(e.target);return{path:t,target:r,vendored:hR(r),module:e.module??null}},vR=e=>e.copy.map(yR),Pi=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),xi=(e,t)=>e.filter(r=>!Pi(r.path,t)),zc=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Ro=e=>[...new Set(e)].sort(),wR=e=>e.startsWith(rf)?e.slice(rf.length):null;var Yc=e=>`# vendor/ \u2014 mirrored from ${e}
471
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Mm=async()=>{let e=await X(),t=tR.env.EDITOR||tR.env.VISUAL||"vi",r=await Fn(e);r.createdConfig&&d.info(Ln(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await Lj({stdio:"inherit"})`${t} ${e.userProject}`,Qt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};import{z as wi}from"zod";var Vj={key:wi.string(),value:wi.unknown().describe("The parsed value written"),previous:wi.unknown().describe("The value the layer held before, or null"),scope:wi.enum(["project","global"]),path:wi.string().describe("The layer file written")},jm=async({key:e,value:t,global:r})=>{Qo(e,"config-set");let n=r?"global":"project",o=Tu(t),{file:s,previous:i}=await es(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${xn[n]} (${w(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:R(JSON.stringify(a,null,2)),structuredContent:a}};import{z as ki}from"zod";var Wj={key:ki.string(),removed:ki.boolean(),previous:ki.unknown().describe("The value the layer held before, or null"),scope:ki.enum(["project","global"]),path:ki.string().describe("The layer file edited")},Fm=async({key:e,global:t})=>{Qo(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await es(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${xn[r]} (${w(n)})`:`${e} is not set in the ${xn[r]} (${w(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}};import aR from"node:fs/promises";import bi from"node:path";import nF from"node:process";import{pathToFileURL as oF}from"node:url";import{z as Gm}from"zod";import{execFile as Hj,spawn as qj}from"node:child_process";import br from"node:fs/promises";import zj from"node:os";import kr from"node:path";import nR from"node:process";import{promisify as Yj}from"node:util";import rR from"node:fs/promises";import Gj from"node:path";import{pathToFileURL as Jj}from"node:url";var Kj=".infra-kit-import-from-app.mjs",Lm=async(e,t)=>{let r=Gj.join(e,Kj);await rR.writeFile(r,`export const resolveHere = (specifier) => import.meta.resolve(specifier)
472
+ `);try{let{resolveHere:n}=await import(Jj(r).href);return await import(n(t))}finally{await rR.rm(r,{force:!0})}};var Xj=Yj(Hj),oR="3.39.0",Zj=10*1024*1024,Qj=960,eF=60,Bm=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,tF=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${Bm(e)}`}},ko=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},rF=(e,t,r)=>new Promise((n,o)=>{let s=qj(e,t,{cwd:r.cwd,env:r.env,stdio:"inherit"});s.on("error",o),s.on("exit",(i,a)=>{i===0?n():o(new Error(`${e} exited with ${a??i}`))})}),Uc={run:rF,capture:async(e,t,r)=>{let{stdout:n}=await Xj(e,t,{...r,maxBuffer:Zj});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{nR.stdout.write(`${e}
473
+ `)}},Bc=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),sR=async e=>{let t=JSON.parse(await br.readFile(kr.join(e,"package.json"),"utf-8")),r=t.devDependencies?.turbo??t.dependencies?.turbo,n=r?.replace(/^[\^~=v]+/,"");if(n===void 0||!/^\d+\.\d+\.\d+/.test(n))throw new Error(`the root package.json must pin turbo to an exact version (found ${r??"none"})`);return n},Vm=async e=>{let t=await br.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=kr.join(e,r.name);return r.name==="node_modules"?br.rm(n,{recursive:!0,force:!0}):Vm(n)}))},Um=async(e,t,r)=>{let n=r.appPath??t;if(n===void 0)throw new Error("pass app and appPath, or put the deploy script in the app it deploys");if(r.app!==void 0)return{app:r.app,appPath:n};try{let o=JSON.parse(await br.readFile(kr.join(e,n,"package.json"),"utf-8"));if(o.name)return{app:o.name,appPath:n}}catch{}throw new Error(`${n} has no package.json name to deploy; pass app explicitly`)},Wm=({root:e,service:t,project:r,scriptDir:n,env:o=nR.env,deps:s=Uc})=>{let i=async(v,S,P,O={})=>{s.log(`COMMAND: ${[S,...P].join(" ")}`);try{await s.run(S,P,{cwd:O.cwd??e,env:O.env??o})}catch(D){throw new Error(`${v} failed: ${D.message}`)}},a=async(v,S,P={})=>{let{attempts:O=8,initialDelaySeconds:D=3,maxDelaySeconds:V=60}=P,Re=async se=>{try{return await S()}catch(At){if(se>=O)throw new Error(`${v} failed after ${O} attempts: ${At.message}`);let Ci=Math.min(V,D*2**(se-1)),$i=Math.round((Ci/2+s.random()*Ci/2)*10)/10;return s.log(`Attempt ${se}/${O} failed. Retrying in ${$i}s...`),await s.sleep($i*1e3),Re(se+1)}};return Re(1)},c=async(v,S,P=o)=>{s.log(`COMMAND: aws ${S.join(" ")}`),await a(v,()=>s.run("aws",S,{cwd:e,env:Bc(P)}))},l=async(v,S={})=>{await i(`aws ${v.slice(0,2).join(" ")}`,"aws",v,{cwd:S.cwd,env:Bc(S.env??o)})},u=async v=>{let S=await Promise.all(v.map(async P=>{try{let O=await s.capture("aws",["ssm","get-parameter","--name",P,"--query","Parameter.Value","--output","text"],{cwd:e,env:Bc(o)});return[P,O.trim()]}catch(O){throw new Error(`SSM parameter ${P}: ${O instanceof Error?O.message:String(O)}`)}}));return Object.fromEntries(S)},p=async v=>{let S=[`turbo@${await sR(e)}`,...v?[`serverless@${oR}`]:[]];await i("Install tools","pnpm",["add","-g",...S])},m=async(v,S)=>{let P=kr.join(e,"out"),O={...o,...S.buildEnv},D=S.buildTask??O.TURBO_BUILD_TASK??"build";return await br.rm(P,{recursive:!0,force:!0}),await i(`Prune to ${v}`,"turbo",["prune",v],{env:O}),await i("Install dependencies","pnpm",["install"],{cwd:P,env:O}),await i(`Build ${v}`,"pnpm",["exec","turbo",D,`--filter=${v}`,"--env-mode=loose"],{cwd:P,env:O}),S.installProd&&(s.log("COMMAND: remove every node_modules under ./out"),await Vm(P),await i("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:P,env:O}),await i("Show node_modules size","du",["-sm","./node_modules/"],{cwd:P})),P},f=(v,S,P)=>({stage:v,outDir:S,appDir:P,importFromApp:O=>Lm(P,O)}),h=async(v,S,P)=>{if(S!==void 0){s.log(`Running ${v} hooks...`);try{await S(P)}catch(O){throw new Error(`${v} hooks failed: ${O.message}`)}s.log(`${v} hooks completed successfully`)}},b=async v=>{let{app:S,appPath:P}=await Um(e,n,v);await p(!0);let O={...o,...v.buildEnv},D=await m(S,{installProd:!0,buildTask:v.buildTask,buildEnv:v.buildEnv}),V=f(v.stage,D,kr.join(D,P));await h("Pre-deployment",v.preDeploy,V),await i("Deploy with Serverless","serverless",["deploy","--stage",v.stage,"--force"],{cwd:V.appDir,env:O}),v.restApiId===void 0?s.log(`Skipping API Gateway deployment for ${S}: no restApiId.`):await c("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",v.restApiId,"--stage-name","api"],O),await h("Post-deployment",v.postDeploy,V)},C=async v=>{let{app:S,appPath:P}=await Um(e,n,v);await p(!1);let O={...o,...v.buildEnv},D=await m(S,{installProd:!1,buildTask:v.buildTask,buildEnv:v.buildEnv}),V=f(v.stage,D,kr.join(D,P)),Re=`s3://${v.bucket}${v.destPath??""}`,se=v.sourcePath??"./dist";await i("Sync to S3","aws",["s3","sync",se,Re,...v.syncFlags??[],"--only-show-errors"],{cwd:V.appDir,env:Bc(O)}),await c("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",v.cloudfrontId,"--paths",v.invalidationPath??"/*"],O),await h("Post-deployment",v.postDeploy,V)},k=async(v,S,P)=>{let O=await br.mkdtemp(kr.join(zj.tmpdir(),"infra-kit-lambda-")),D=kr.join(O,"response.json"),V=["lambda","invoke","--function-name",v.functionName,...P===void 0?[]:["--region",P],"--cli-binary-format","raw-in-base64-out","--payload",v.payload??S,"--cli-read-timeout",String(Qj),"--cli-connect-timeout",String(eF),D],Re=Date.now();s.log(`COMMAND: aws ${V.join(" ")}`);try{let se=await s.capture("aws",V,{cwd:e,env:{...o,AWS_PAGER:""}}).then(tF,il=>`aws CLI failed: ${Bm(il instanceof Error?il.message:String(il))}`),At=await br.readFile(D,"utf-8").catch(()=>""),Ci=((Date.now()-Re)/1e3).toFixed(1),$i=se!==void 0&&At?`; response: ${Bm(At)}`:"";return{outcome:`${v.functionName} (${Ci}s)`,failure:se===void 0?void 0:se+$i}}finally{await br.rm(O,{recursive:!0,force:!0})}};return{root:e,service:t,project:r,ssm:u,aws:l,run:(v,S,P={})=>s.run(v,S,{cwd:P.cwd??e,env:P.env??o}),capture:(v,S,P={})=>s.capture(v,S,{cwd:P.cwd??e,env:P.env??o}),retry:a,skip:v=>{throw new ko(v)},pruneAndBuild:m,deployBackendApi:b,deployFrontendUi:C,invokeLambdas:async v=>{let{region:S,payload:P="{}",blocking:O=[],steps:D=[]}=v;for(let V of O){let{outcome:Re,failure:se}=await k(V,P,S);if(se!==void 0)throw new Error(`Lambda ${Re} failed: ${se}`);s.log(`Lambda ${Re} OK`)}for(let V of D){let Re=await Promise.all(V.map(se=>k(se,P,S).catch(At=>({outcome:se.functionName,failure:String(At)}))));for(let{outcome:se,failure:At}of Re)s.log(At===void 0?`Lambda ${se} OK`:`Warning: Lambda ${se} failed, continuing: ${At}`)}},importFromApp:Lm}};var sF={status:Gm.enum(["deployed","skipped"]),service:Gm.string(),reason:Gm.string().optional()},iR=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),iF=async(e,t)=>{let r=bi.join(e,"devops","scripts",`deploy-${t}.sh`);try{await aR.access(r)}catch{throw new g(void 0,{operation:`deploy ${t}`,remediation:`set services['${t}'].deploy in infra-kit.deploy.ts, e.g. 'apps/<app>/deploy.ts'`,stderrExcerpt:`${t} has no deploy in infra-kit.deploy.ts and no devops/scripts/deploy-${t}.sh`})}return r},aF=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
474
+ `,"%0A")}`,cF=(e,t)=>{let r=(e??"").split(`
475
+ `).filter(n=>n.trim()!=="").map(n=>{let o=n.indexOf("="),s=n.slice(0,Math.max(o,0));if(!/^[A-Z_][A-Z0-9_]*$/.test(s))throw new g(void 0,{operation:"deploy-run",remediation:"write each extra-env line as KEY=VALUE with an upper-case KEY",stderrExcerpt:"an extra-env line is not KEY=VALUE"});return[s,n.slice(o+1)]});for(let[,n]of r)n!==""&&t(aF(n));return Object.fromEntries(r)},lF=async e=>{try{await aR.access(e)}catch{throw new g(void 0,{operation:`run ${bi.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(oF(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${bi.basename(e)}`,remediation:"export the deploy as `export default (async (toolkit) => { \u2026 }) satisfies DeployScript`",stderrExcerpt:"the script has no default-exported function"});return t.default},Jm=async e=>{let{service:t,env:r=nF.env}=e;if(!/^[a-z0-9-]+$/.test(t))throw new g(void 0,{operation:"deploy-run",remediation:"pass the service as infra-kit.deploy.ts names it, e.g. client-be",stderrExcerpt:`invalid service name '${t}'`});if(te()&&r.INFRA_KIT_DEPLOY_VIA!==Xs)throw new A({status:"refused",agentMode:N.source},2,{operation:`deploy ${t}`,remediation:"ask a human to run `infra-kit deploy-run` from their own shell, or deploy through `infra-kit release deploy-selected` (CI) or `infra-kit local deploy-selected`, which check the environment first",stderrExcerpt:"deploy-run deploys with whatever AWS credentials are loaded: refused in agent mode"});let n=e.cwd??await $(),o=e.deps??Uc,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...cF(s,o.log)},c=await Tt(n),l=c?.services[t]?.deploy;if(l===void 0)await o.run("sh",[await iF(n,t)],{cwd:n,env:a});else{let u=await lF(bi.join(n,l)),p=Wm({root:n,service:t,project:c?.project,scriptDir:bi.dirname(l),env:a,deps:o});try{await u(p)}catch(m){if(!(m instanceof ko))throw m;return d.info(`\u23ED\uFE0F ${t} skipped: ${m.message}`),iR({status:"skipped",service:t,reason:m.message})}}return d.info(`\u2705 ${t} deployed`),iR({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as Ri}from"@slip-stream-kit/config/internal";import Wc from"node:fs/promises";import Gc from"node:path";import{z as bo}from"zod";var Km=async e=>{try{return await Wc.readFile(e,"utf-8")}catch{return}},uF={status:bo.enum(["written","unchanged","drift","missing-config"]),ok:bo.boolean(),files:bo.array(bo.object({path:bo.string(),status:bo.enum(["created","updated","unchanged","removed"])}))},Vc=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),dF={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},cR=async(e,t)=>(await Promise.all(t.map(async n=>{let o=Gc.join(e,n);return(await Km(o))?.startsWith(fo)?[{path:n,absolute:o}]:[]}))).flat(),pF=async(e,t)=>t.replaceV1!==!0?[]:(await cR(e,Sp)).map(r=>({...r,status:"removed"})),mF=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Km(Gc.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${Ri} do not exist: ${n.join(", ")}`)},fF=async(e,t)=>{if(t.replaceV1===!0)return;let r=await cR(e,Ep);if(r.length===0)return;let n=r.map(o=>o.path).join(", ");throw new Error(`${n} ${r.length===1?"was":"were"} generated under replaceV1, which ${Ri} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},Hm=async(e={})=>{let t=e.cwd??await $(),r=await Tt(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Ri} at ${t}, nothing to generate.`),Vc({status:"missing-config",ok:!!e.check,files:[]});await fF(t,r),await mF(t,r);let n=await Promise.all($p(r).map(async a=>{let c=Gc.join(t,a.path),l=await Km(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await pF(t,r),s=[...n.filter(a=>a.status!=="unchanged"),...o],i=[...n,...o].map(({path:a,status:c})=>({path:a,status:c}));if(s.length===0)return d.info(`\u2705 Deploy workflows match ${Ri}.`),Vc({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${Ri}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${dF[a.status]})`);return Vc({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await Wc.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await Wc.mkdir(Gc.dirname(a.absolute),{recursive:!0}),await Wc.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return Vc({status:"written",ok:!0,files:i})};import{z as Jc}from"zod";var lR="https://dashboard.doppler.com/workplace/projects",gF=(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}"): ${lR}/${e}`],hF={env:Jc.string(),removed:Jc.boolean(),storePath:Jc.string(),revokeUrl:Jc.string()},qm=async({env:e})=>{let r=!!(await fe())?.envs[e];await Ig(e);let n=await He(),o=await tr();r?d.info(`Removed the "${e}" service token from ${w(o)}.`):d.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of gF(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${lR}/${n}`};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}};import yF from"@inquirer/confirm";import vF from"@inquirer/input";import wF from"@inquirer/password";import kF from"@inquirer/select";import bF from"node:fs/promises";import $t from"node:process";import{z as be}from"zod";import{$ as Kc}from"zx";var RF=async({stdin:e,fromEnv:t})=>{if(e)return{token:await uR(),source:"stdin"};if(t){let n=$t.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!$t.stdin.isTTY){let n=await uR();if(n)return{token:n,source:"stdin"};if(!H())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return y.setInteractive(),{token:(await _(n=>wF({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:$t.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},uR=async()=>{let e=[];$t.stdin.setEncoding("utf8");for await(let t of $t.stdin)e.push(t);return e.join("").trim()},zm="DOPPLER_CONFIG",SF=3e4,EF=async(e,t,r)=>{let n=Kc.quiet;Kc.quiet=!0;let o;try{o=(await Kc({env:No(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(SF)).stdout}catch(s){throw PF(s,r)}finally{Kc.quiet=n}return xl(o)},PF=(e,t)=>{let r=dg(e)??(e instanceof Error?e.message:String(e));if(wl(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=kl(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(`
476
+ `))},xF=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${zm}.`,"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(`
477
+ `),pR=async(e,t,r,n)=>{let o=await EF(e,t,r);Pl(o,r);let s=o.some(([i])=>i===zm);if(!s&&!n)throw new Error(xF(r));return s},dR="\0new-env",TF=async()=>{if(H()||!$t.stdin.isTTY)throw new A({status:"argument_required",argument:"env",agentMode:N.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([ur(),fe()]),r=Math.max(0,...e.map(({env:s})=>s.length));y.setInteractive();let n=await _(s=>kF({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:dR}]},s),{output:$t.stderr,whenHeadless:"refuse"});return n!==dR?n:(await _(s=>vF({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:$t.stderr,whenHeadless:"refuse"})).trim()},CF=async(e,t,r)=>_(n=>yF({message:`Replace the "${e}" token ${Ne(t)} with ${Ne(r)}?`,default:!0},n),{output:$t.stderr,whenHeadless:"refuse"}),$F=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${Ne(r)})`;case"replaced":return`Replaced the "${e}" service token ${Ne(n??"")} \u2192 ${Ne(r)}`;case"unchanged":return`The "${e}" service token is already ${Ne(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${Ne(n??"")} \u2014 nothing was written`;default:return Ke(t)}},Ym=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await He(),s=e??await TF(),{token:i,source:a}=await RF({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await pR(i,o,s,n),l=(await fe())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await CF(s,l,i)?u="kept":(await Rl({[s]:i}),u=l===void 0?"stored":"replaced");let p=await tr();d.info(`${$F(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${zm} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:Ne(i),previousRedactedToken:l===void 0?null:Ne(l),storePath:p,scopeVerified:c};return y.print(),{content:R(JSON.stringify(m,null,2)),structuredContent:m}},AF=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,mR=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?AF(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},OF={env:be.string(),status:be.enum(["stored","replaced","unchanged","kept"]),source:be.enum(["stdin","env","prompt"]),redactedToken:be.string(),previousRedactedToken:be.string().nullable(),storePath:be.string(),scopeVerified:be.boolean()},DF={storePath:be.string(),rows:be.array(be.object({env:be.string(),status:be.enum(["stored","replaced","unchanged","failed"]),redactedToken:be.string(),scopeVerified:be.boolean(),error:be.string().optional()})),failedCount:be.number()},IF=e=>(e instanceof Error?e.message:String(e)).split(`
478
+ `)[0]??"",NF=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",_F=async(e,t,r,n)=>{let o=Ne(e.token);try{let s=await pR(e.token,t,e.env,n);return{env:e.env,status:NF(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:IF(s)}}},Xm=async({fromFile:e,force:t})=>{let r=await He(),n=mR(await bF.readFile(e,"utf8")),o=await fe(),s=await Promise.all(n.map(p=>_F(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 Rl(i);let a=await tr(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${w(e)} \u2192 ${w(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${w(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&($t.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}};var Zm=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 Xp(n);if(r&&y.addOption("--from",p),Yp(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new g(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?vc({version:o,env:s,skipTerraform:a,confirmedCommand:c}):wc({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Qm=async e=>Zm(e,"all"),ef=async e=>Zm(e,"selected"),Hc=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.`),Zm({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as gR}from"@slip-stream-kit/config/internal";import tf from"node:fs/promises";import Ro from"node:path";import fR from"node:process";import{pathToFileURL as MF}from"node:url";var hR="~/projects",rf=async(e={})=>{if(e.init){await FF(e.cwd);return}await jF()},jF=async()=>{let e=Un(),t=await ie(e);if(d.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),fR.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await $a(),s=Vn(r),i=await ie(s),a=Ro.join(s,n),c=await ie(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${w(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=Ro.join(s,u),m=await ie(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",h=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${h}`)}l||(fR.exitCode=1)},FF=async e=>{let t=Un();if(await ie(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await $(),n=await LF(r);await tf.mkdir(Ro.dirname(t),{recursive:!0}),await tf.writeFile(t,BF(Ro.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${gR}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${hR}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Ro.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.")},LF=async e=>{try{let t=Ro.join(e,gR),r=await tf.stat(t),s=(await import(`${MF(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[]},BF=(e,t)=>`${JSON.stringify({workspaceDir:hR,source:e,targets:t},null,2)}
479
+ `;import{existsSync as HL}from"node:fs";import qL from"node:fs/promises";import KR from"node:path";import HR from"node:process";import{z}from"zod";import{chmodSync as qF,copyFileSync as zF,lstatSync as YF,mkdirSync as TR,readFileSync as xR,readdirSync as XF,readlinkSync as ZF,rmSync as QF,rmdirSync as CR,symlinkSync as eL,unlinkSync as tL,writeFileSync as $R}from"node:fs";import $e from"node:path";import{lstatSync as UF,readlinkSync as yR}from"node:fs";import VF from"node:path";var WF=new Set(["ENOENT","ENOTDIR"]),Si=e=>{let t;try{t=UF(e)}catch(r){if(WF.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:yR(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:vo(e)}:{kind:"other"}},vR=(e,t)=>{let r=VF.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:yR(r)}:{kind:"file",executable:t.mode==="100755",sha:vo(r)};return{...t,fingerprint:n}},wR=(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 GF}from"zx";var ee=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await GF({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},qc=e=>e.slice(0,7),pt=e=>e.split("\0").filter(t=>t.length>0);import JF from"node:path";var nf=`${ce}/`,Rr=`${ce}/README.md`,Ei=`${ce}/${nt}`,bR=e=>e.startsWith(nf),kR=e=>{let t=JF.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},RR=e=>{let t=kR(e.path),r=e.target===void 0?t:kR(e.target);return{path:t,target:r,vendored:bR(r),module:e.module??null}},SR=e=>e.copy.map(RR),Pi=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),xi=(e,t)=>e.filter(r=>!Pi(r.path,t)),zc=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,So=e=>[...new Set(e)].sort(),ER=e=>e.startsWith(nf)?e.slice(nf.length):null;var Yc=e=>`# vendor/ \u2014 mirrored from ${e}
480
480
 
481
481
  **DO NOT EDIT files in this folder here.**
482
482
 
@@ -487,19 +487,19 @@ fail \`ik vendor check\` in CI.
487
487
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
488
488
 
489
489
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
490
- `;var BF=new Set(["100644","100755","120000"]),UF=(e,t)=>{let r=new Map;for(let n of pt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!BF.has(s)||Pi(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},nf=async(e,t,r)=>{let n=await ee(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return UF(n,r)},kR=async e=>pt(await ee(e,["--literal-pathspecs","ls-files","-z","--",ce]));var So=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],PR=e=>{let t=Si(e);t!==null&&(t.kind==="other"?SR(e):zF(e))},YF=(e,t,r)=>{let n=$e.join(e,r.source),o=$e.join(t,r.target);RR($e.dirname(o),{recursive:!0});let s=Si(o)?.kind==="file"?Eb(bR(o)):null;if(PR(o),r.mode==="120000"){qF(KF(n),o);return}s===null?WF(n,o):ER(o,xb(bR(n),s)),VF(o,r.mode==="100755"?493:420)},XF=async(e,t)=>{let r=new Set;for(let n of pt(await ee(e,["ls-files","-z"]))){if(t.has(n))continue;let o=$e.posix.dirname(n);for(;o!==".";)r.add(o),o=$e.posix.dirname(o)}return r},ZF=async(e,t)=>{if(t.length===0)return;let r=await XF(e,new Set(t)),n=[...new Set(t.map(o=>$e.dirname($e.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)&&!(!GF(s,{throwIfNoEntry:!1})?.isDirectory()||JF(s).length>0||r.has($e.relative(e,s).split($e.sep).join("/")));)SR(s),s=$e.dirname(s)}},xR=(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,Rr,...s].map(wR).filter(a=>a!==null&&!$c(a));return Ro(i)},TR=async(e,t,r,n)=>{let o=$e.join(e,ce);RR(o,{recursive:!0}),ER($e.join(e,Rr),Yc(t.name));let s=xR(r,await kR(e),n);wm(o,{source:t.name,commit:t.headSha},s)},of=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(So(t));let n=$e.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)PR($e.join(n,a));await ZF(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&HF($e.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)YF(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await TR(n,e,t.entries,o),{touched:Ro([...o,...i,Rr,Ei]),manifestWritten:!0}):{touched:Ro([...o,...i]),manifestWritten:!1}},sf=async(e,t)=>(await TR(e,t,[],[]),[Rr,Ei]);var af=(e,t)=>`[ROOT] vendor: sync from ${e}@${qc(t)}`,QF=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
491
- `).trim()||String(e)},cf=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await ee(e,["--literal-pathspecs","add","-A",...o],{input:n}),await ee(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:QF(s)}}};var CR=20,eL=20,uf=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],lf=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of xi(e.files,r)){let p=zc(u.path,n);if(s.push(p),fR(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=xi(t.tracked.map(u=>({path:u})),r).map(u=>u.path).filter(u=>!a.has(u)),l=i.filter(u=>u.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length},pruned:!1}},rn=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),df=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),tL=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...df(e,r)];return rn(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...uf(n,CR),Je(o)])},rL=(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=qc(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}`,...uf(e.lines,eL)],warnings:[]}},nL=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},oL=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},sL=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Ro([...n,...r?t.headVendorMeta:[]])},iL=e=>e.entries.filter(t=>t.scope==="release"&&t.tracked.length>0).map(t=>`${t.target}: not in vendorTarget.modules, left in place for this repo to own`),aL=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return tL(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return rn(t,"fail","blocked: a module this repo dropped is still a dependency",[...uf(t.pruneConflicts,CR)]);let n=e.entries.flatMap((f,h)=>{let b=t.entries[h]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return b.scope==="release"?[]:b.scope==="sync"?[lf(f,b,e.exclude)]:[{...lf({...f,files:[]},b,e.exclude),pruned:!0}]}),o=n.some(f=>f.vendored),s=n.some(f=>f.writes.length+f.deletes.length>0),i=o&&(!t.readmeCurrent||!t.manifestPresent),a={...rn(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=rL(t.changelog,e.name),l=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],u=n.map(nL).filter(f=>f!==null),m=t.entries.some(f=>f.scope==="prune"&&f.tracked.length>0)?["vendored modules removed: run pnpm install to update the lockfile"]:[];return{...a,status:"changed",message:`${oL(n)} on ${t.branch}`,notes:[...u,...m,...iL(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:sL(n,t,o)}},Xc=(e,t)=>{switch(t.kind){case"missing":return rn(t,"skipped",`not checked out at ${t.root}`);case"source":return rn(t,"skipped","this is the source repo");case"not-git":return rn(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return rn(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return aL(e,t)}};import{existsSync as gL,readFileSync as hL,realpathSync as Zc}from"node:fs";import Qc from"node:path";import{readFileSync as $R}from"node:fs";import Eo from"node:path";var cL=["dependencies","devDependencies","peerDependencies","optionalDependencies"],lL=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},AR=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=lL(e);if(t.kind==="modules"){let n=t.modules.filter(o=>!r.includes(o));if(n.length>0){let o=r.length>0?r.join(", "):"none";return{reason:`unknown module(s) ${n.join(", ")} in vendorTarget.modules; the source offers: ${o}`}}}return e.map(({entry:n})=>n.module===null||t.kind==="all"||t.modules.includes(n.module)?"sync":n.vendored?"prune":"release")},OR=e=>{try{return JSON.parse($R(e,"utf8"))}catch{return null}},uL=(e,t)=>t.files.flatMap(r=>{let n=Eo.posix.relative(t.entry.path,r.path);if(Eo.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=OR(Eo.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),dL=e=>cL.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),DR=(e,t)=>{let r=e.indexOf(t);for(;r>=0;){if(!/[\w-]/.test(e[r+t.length]??""))return!0;r=e.indexOf(t,r+1)}return!1},pL=["*.sh","*.yml","*.yaml"],mL=(e,t,r)=>{let n=dL(t).includes(r)?[`${e} depends on ${r}`]:[],o=t.scripts!==null&&typeof t.scripts=="object"?t.scripts:{};for(let[s,i]of Object.entries(o))typeof i=="string"&&DR(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},fL=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...pL];return pt(await ee(e,n,{allowFailure:!0})).filter(s=>r(s)&&DR($R(Eo.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},IR=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of uL(e,c))n.set(l,c.entry.module??"");if(n.size===0)return[];let o=r.map(({target:c})=>`${c}/`),s=c=>!o.some(l=>c.startsWith(l)),i=pt(await ee(t,["ls-files","-z","--","*package.json"])).filter(c=>Eo.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=OR(Eo.join(t,p));return m===null?[]:mL(p,m,c)});u.push(...await fL(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var pf=async(e,t)=>{let r=t.exclude??[],n=(await ee(e,["rev-parse","HEAD"])).trim(),o=await _e(e),s=await Promise.all(vR(t).map(async i=>{let a=await nf(e,i.path,r);return{entry:i,files:a.map(c=>mR(e,c))}}));return{root:e,selfRoots:[...new Set([Zc(e),Zc(o)])],name:Qc.basename(o),headSha:n,entries:s,exclude:r}},el=e=>{let t=pt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},yL=async(e,t,r)=>{let n=df(e,t);if(n.length===0)return[];let o=await ee(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return el(o).filter(s=>!Pi(s,e.exclude))},vL=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await nf(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of xi(l,e.exclude)){let p=zc(u.path,n);c[p]=Si(Qc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),wL=async e=>{try{return pt(await ee(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Rr,Ei]))}catch{return[]}},kL=e=>{try{let{commit:t,source:r}=fi(Qc.join(e,ce));return{commit:t,source:r}}catch{return null}},bL=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await Oe(e.root,r)===null)return{kind:"unresolvable",sha:r};let n=e.entries.filter((i,a)=>t[a]==="sync").map(({entry:i})=>i.path);if(n.length===0)return{kind:"log",sha:r,lines:[]};let s=(await ee(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
492
- `).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},RL=(e,t)=>{try{return hL(Qc.join(e,Rr),"utf8")===Yc(t)}catch{return!1}},SL=async e=>{try{return{toplevel:(await ee(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
493
- `)[0]??"git rev-parse failed"}}},EL=async e=>{try{return(await ee(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},tl=async(e,t)=>{if(!gL(t.root))return{...t,kind:"missing"};let r=Zc(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await SL(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Zc(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=AR(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=kL(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([EL(t.root),yL(e,o,t.root),vL(e,o,t.root),wL(t.root),bL(e,o,i)]),m=l.flatMap((f,h)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[h],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:RL(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await IR(e.root,t.root,m)}};var PL=20,xL=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],TL=(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:",Je(So(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:xL(r,t)}},CL=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(`
494
- `).slice(0,PL)},$L=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[TL(e,t),...r,...e.commit?[CL(e.commit)]:[]]}},AL={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},mf=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:AL[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>$L(o,r))],hints:n}},NR=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),_R=(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 OL=20,ff=async(e,t)=>(await ee(e,t,{allowFailure:!0})).trim(),DL=async e=>el(await ee(e,["status","--porcelain","-z","--untracked-files=normal"])),IL=async e=>(await ff(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"]},NL=async e=>{let[t,r]=await Promise.all([ff(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),ff(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}`}},MR=async e=>{let t=await DL(e);if(t.length>0){let n=t.slice(0,OL),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new A({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([IL(e),NL(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import FL from"node:path";import{readFileSync as _L}from"node:fs";import ML from"node:path";import{z as jL}from"zod";var jR=e=>{let t;try{t=_L(ML.join(e,"infra-kit.json"),"utf8")}catch{return{kind:"all"}}let r;try{r=JSON.parse(t)?.vendorTarget}catch(o){return{kind:"invalid",reason:`infra-kit.json is not valid JSON: ${o.message}`}}if(r===void 0)return{kind:"all"};let n=bg.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:jL.prettifyError(n.error)}};var FR=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new A({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=Un(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=FL.join(n,s);return{name:s,root:i,selection:jR(i)}})},LL="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",BL=async(e,t)=>{let r=await tl(e,t),n=Xc(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${LL} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},LR=async(e,t,r)=>Promise.all(t.map(async n=>r?BL(e,n):Xc(e,await tl(e,n))));var WR="sync vendored files",WL=e=>{let t=UR.join(Un(e.workspaceDir),e.source);if(UL(t))return t;throw new A({status:"refused",reason:"source-missing",source:t},1,{operation:WR,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'})},gf=(e,t)=>new A({status:"refused",reason:"not-a-vendor-source"},1,{operation:WR,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`}),GL=async e=>{let t=UR.join(e,"infra-kit.json"),r;try{r=JSON.parse(await VL.readFile(t,"utf8"))}catch(s){throw gf(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw gf(t,"has no vendorSource block");let o=kg.safeParse(n);if(!o.success)throw gf(t,`has an invalid vendorSource: ${z.prettifyError(o.error)}`);return o.data},BR=(e,t)=>{VR.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
490
+ `;var KF=new Set(["100644","100755","120000"]),HF=(e,t)=>{let r=new Map;for(let n of pt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!KF.has(s)||Pi(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},of=async(e,t,r)=>{let n=await ee(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return HF(n,r)},PR=async e=>pt(await ee(e,["--literal-pathspecs","ls-files","-z","--",ce]));var Eo=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],AR=e=>{let t=Si(e);t!==null&&(t.kind==="other"?CR(e):tL(e))},rL=(e,t,r)=>{let n=$e.join(e,r.source),o=$e.join(t,r.target);TR($e.dirname(o),{recursive:!0});let s=Si(o)?.kind==="file"?$b(xR(o)):null;if(AR(o),r.mode==="120000"){eL(ZF(n),o);return}s===null?zF(n,o):$R(o,Ob(xR(n),s)),qF(o,r.mode==="100755"?493:420)},nL=async(e,t)=>{let r=new Set;for(let n of pt(await ee(e,["ls-files","-z"]))){if(t.has(n))continue;let o=$e.posix.dirname(n);for(;o!==".";)r.add(o),o=$e.posix.dirname(o)}return r},oL=async(e,t)=>{if(t.length===0)return;let r=await nL(e,new Set(t)),n=[...new Set(t.map(o=>$e.dirname($e.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)&&!(!YF(s,{throwIfNoEntry:!1})?.isDirectory()||XF(s).length>0||r.has($e.relative(e,s).split($e.sep).join("/")));)CR(s),s=$e.dirname(s)}},OR=(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,Rr,...s].map(ER).filter(a=>a!==null&&!$c(a));return So(i)},DR=async(e,t,r,n)=>{let o=$e.join(e,ce);TR(o,{recursive:!0}),$R($e.join(e,Rr),Yc(t.name));let s=OR(r,await PR(e),n);km(o,{source:t.name,commit:t.headSha},s)},sf=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Eo(t));let n=$e.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)AR($e.join(n,a));await oL(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&QF($e.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)rL(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await DR(n,e,t.entries,o),{touched:So([...o,...i,Rr,Ei]),manifestWritten:!0}):{touched:So([...o,...i]),manifestWritten:!1}},af=async(e,t)=>(await DR(e,t,[],[]),[Rr,Ei]);var cf=(e,t)=>`[ROOT] vendor: sync from ${e}@${qc(t)}`,sL=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
491
+ `).trim()||String(e)},lf=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await ee(e,["--literal-pathspecs","add","-A",...o],{input:n}),await ee(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:sL(s)}}};var IR=20,iL=20,df=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],uf=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of xi(e.files,r)){let p=zc(u.path,n);if(s.push(p),wR(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=xi(t.tracked.map(u=>({path:u})),r).map(u=>u.path).filter(u=>!a.has(u)),l=i.filter(u=>u.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length},pruned:!1}},rn=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),pf=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),aL=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...pf(e,r)];return rn(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...df(n,IR),Je(o)])},cL=(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=qc(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}`,...df(e.lines,iL)],warnings:[]}},lL=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},uL=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},dL=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return So([...n,...r?t.headVendorMeta:[]])},pL=e=>e.entries.filter(t=>t.scope==="release"&&t.tracked.length>0).map(t=>`${t.target}: not in vendorTarget.modules, left in place for this repo to own`),mL=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return aL(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return rn(t,"fail","blocked: a module this repo dropped is still a dependency",[...df(t.pruneConflicts,IR)]);let n=e.entries.flatMap((f,h)=>{let b=t.entries[h]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return b.scope==="release"?[]:b.scope==="sync"?[uf(f,b,e.exclude)]:[{...uf({...f,files:[]},b,e.exclude),pruned:!0}]}),o=n.some(f=>f.vendored),s=n.some(f=>f.writes.length+f.deletes.length>0),i=o&&(!t.readmeCurrent||!t.manifestPresent),a={...rn(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=cL(t.changelog,e.name),l=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],u=n.map(lL).filter(f=>f!==null),m=t.entries.some(f=>f.scope==="prune"&&f.tracked.length>0)?["vendored modules removed: run pnpm install to update the lockfile"]:[];return{...a,status:"changed",message:`${uL(n)} on ${t.branch}`,notes:[...u,...m,...pL(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:dL(n,t,o)}},Xc=(e,t)=>{switch(t.kind){case"missing":return rn(t,"skipped",`not checked out at ${t.root}`);case"source":return rn(t,"skipped","this is the source repo");case"not-git":return rn(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return rn(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return mL(e,t)}};import{existsSync as bL,readFileSync as RL,realpathSync as Zc}from"node:fs";import Qc from"node:path";import{readFileSync as NR}from"node:fs";import Po from"node:path";var fL=["dependencies","devDependencies","peerDependencies","optionalDependencies"],gL=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},_R=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=gL(e);if(t.kind==="modules"){let n=t.modules.filter(o=>!r.includes(o));if(n.length>0){let o=r.length>0?r.join(", "):"none";return{reason:`unknown module(s) ${n.join(", ")} in vendorTarget.modules; the source offers: ${o}`}}}return e.map(({entry:n})=>n.module===null||t.kind==="all"||t.modules.includes(n.module)?"sync":n.vendored?"prune":"release")},MR=e=>{try{return JSON.parse(NR(e,"utf8"))}catch{return null}},hL=(e,t)=>t.files.flatMap(r=>{let n=Po.posix.relative(t.entry.path,r.path);if(Po.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=MR(Po.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),yL=e=>fL.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),jR=(e,t)=>{let r=e.indexOf(t);for(;r>=0;){if(!/[\w-]/.test(e[r+t.length]??""))return!0;r=e.indexOf(t,r+1)}return!1},vL=["*.sh","*.yml","*.yaml"],wL=(e,t,r)=>{let n=yL(t).includes(r)?[`${e} depends on ${r}`]:[],o=t.scripts!==null&&typeof t.scripts=="object"?t.scripts:{};for(let[s,i]of Object.entries(o))typeof i=="string"&&jR(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},kL=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...vL];return pt(await ee(e,n,{allowFailure:!0})).filter(s=>r(s)&&jR(NR(Po.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},FR=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of hL(e,c))n.set(l,c.entry.module??"");if(n.size===0)return[];let o=r.map(({target:c})=>`${c}/`),s=c=>!o.some(l=>c.startsWith(l)),i=pt(await ee(t,["ls-files","-z","--","*package.json"])).filter(c=>Po.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=MR(Po.join(t,p));return m===null?[]:wL(p,m,c)});u.push(...await kL(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var mf=async(e,t)=>{let r=t.exclude??[],n=(await ee(e,["rev-parse","HEAD"])).trim(),o=await _e(e),s=await Promise.all(SR(t).map(async i=>{let a=await of(e,i.path,r);return{entry:i,files:a.map(c=>vR(e,c))}}));return{root:e,selfRoots:[...new Set([Zc(e),Zc(o)])],name:Qc.basename(o),headSha:n,entries:s,exclude:r}},el=e=>{let t=pt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},SL=async(e,t,r)=>{let n=pf(e,t);if(n.length===0)return[];let o=await ee(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return el(o).filter(s=>!Pi(s,e.exclude))},EL=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await of(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of xi(l,e.exclude)){let p=zc(u.path,n);c[p]=Si(Qc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),PL=async e=>{try{return pt(await ee(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Rr,Ei]))}catch{return[]}},xL=e=>{try{let{commit:t,source:r}=fi(Qc.join(e,ce));return{commit:t,source:r}}catch{return null}},TL=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await Oe(e.root,r)===null)return{kind:"unresolvable",sha:r};let n=e.entries.filter((i,a)=>t[a]==="sync").map(({entry:i})=>i.path);if(n.length===0)return{kind:"log",sha:r,lines:[]};let s=(await ee(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
492
+ `).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},CL=(e,t)=>{try{return RL(Qc.join(e,Rr),"utf8")===Yc(t)}catch{return!1}},$L=async e=>{try{return{toplevel:(await ee(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
493
+ `)[0]??"git rev-parse failed"}}},AL=async e=>{try{return(await ee(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},tl=async(e,t)=>{if(!bL(t.root))return{...t,kind:"missing"};let r=Zc(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await $L(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Zc(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=_R(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=xL(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([AL(t.root),SL(e,o,t.root),EL(e,o,t.root),PL(t.root),TL(e,o,i)]),m=l.flatMap((f,h)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[h],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:CL(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await FR(e.root,t.root,m)}};var OL=20,DL=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],IL=(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:",Je(Eo(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:DL(r,t)}},NL=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(`
494
+ `).slice(0,OL)},_L=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[IL(e,t),...r,...e.commit?[NL(e.commit)]:[]]}},ML={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},ff=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:ML[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>_L(o,r))],hints:n}},LR=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),BR=(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 jL=20,gf=async(e,t)=>(await ee(e,t,{allowFailure:!0})).trim(),FL=async e=>el(await ee(e,["status","--porcelain","-z","--untracked-files=normal"])),LL=async e=>(await gf(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"]},BL=async e=>{let[t,r]=await Promise.all([gf(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),gf(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}`}},UR=async e=>{let t=await FL(e);if(t.length>0){let n=t.slice(0,jL),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new A({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([LL(e),BL(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import GL from"node:path";import{readFileSync as UL}from"node:fs";import VL from"node:path";import{z as WL}from"zod";var VR=e=>{let t;try{t=UL(VL.join(e,"infra-kit.json"),"utf8")}catch{return{kind:"all"}}let r;try{r=JSON.parse(t)?.vendorTarget}catch(o){return{kind:"invalid",reason:`infra-kit.json is not valid JSON: ${o.message}`}}if(r===void 0)return{kind:"all"};let n=Pg.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:WL.prettifyError(n.error)}};var WR=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new A({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=Vn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=GL.join(n,s);return{name:s,root:i,selection:VR(i)}})},JL="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",KL=async(e,t)=>{let r=await tl(e,t),n=Xc(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${JL} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},GR=async(e,t,r)=>Promise.all(t.map(async n=>r?KL(e,n):Xc(e,await tl(e,n))));var qR="sync vendored files",zL=e=>{let t=KR.join(Vn(e.workspaceDir),e.source);if(HL(t))return t;throw new A({status:"refused",reason:"source-missing",source:t},1,{operation:qR,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'})},hf=(e,t)=>new A({status:"refused",reason:"not-a-vendor-source"},1,{operation:qR,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`}),YL=async e=>{let t=KR.join(e,"infra-kit.json"),r;try{r=JSON.parse(await qL.readFile(t,"utf8"))}catch(s){throw hf(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw hf(t,"has no vendorSource block");let o=Eg.safeParse(n);if(!o.success)throw hf(t,`has an invalid vendorSource: ${z.prettifyError(o.error)}`);return o.data},JR=(e,t)=>{HR.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
495
495
  ${Je(t)}
496
- `)},JL=async(e,t,r)=>r?(BR(t,So(t)),sf(t.root,e)):(await of({source:e,plan:t,onBeforeFirstWrite:o=>{BR(t,o)}})).touched,KL=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await JL(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 cf(t.root,n,af(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},HL=async(e,t,r)=>{let n=[];for(let o of t)n.push(await KL(e,o,r));return n},GR=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})),qL={mode:z.enum(["preview","check","applied"]),source:z.object({root:z.string(),name:z.string(),headSha:z.string().nullable()}),targets:z.array(z.looseObject({name:z.string(),root:z.string(),status:z.string(),applied:z.boolean()})),changed:z.boolean(),failed:z.boolean(),report:z.array(z.object({label:z.string(),rows:z.array(z.object({name:z.string(),status:z.enum(["ok","changed","skipped","manual","warn","fail"]),message:z.string(),notes:z.array(z.string()).optional()}))})).readonly().describe("The printed report sections")},hf=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&bt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:GR(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:NR(t),report:t.sections}}},zL=async e=>{let t=await $a(),r=WL(t),n=await MR(r),o=await GL(r),s=FR(t,e.targets??[]),i=await pf(r,o),a=await LR(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},yf=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await zL(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=mf(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return hf({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!H();if(l&&!VR.stdin.isTTY)return bt(a),hf({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&bt({...a,hints:[]}),await q(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:GR(n)});let u=await HL(t,n,e),p=mf(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);bt(_R(a,p,m))}return hf({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var rl=(e,t=!0)=>({line:e,reproducible:t});import nl from"node:fs";import YL from"node:os";import XL from"node:path";import qR from"node:process";var ol="INFRA_KIT_SESSION_REPORT",vf=null,JR=!1,KR=[],zR=(e=qR.env)=>{JR||(vf=e[ol]??null,JR=!0,delete e[ol])};var YR=(e,t)=>{if(!vf)return;let r=e.summary??(KR.length>0?[...KR]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{nl.writeFileSync(s,i)});try{o(vf,JSON.stringify(n))}catch{}},HR=0,XR=e=>{let t=e?.tmpdir?.()??YL.tmpdir(),r=e?.pid??qR.pid;return HR+=1,XL.join(t,`infra-kit-session-${r}-${HR}.json`)},ZR=(e,t)=>{if(!(t?.exists??(i=>nl.existsSync(i)))(e))return null;let n=t?.read??(i=>nl.readFileSync(i,"utf-8")),o=t?.unlink??(i=>nl.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var wf=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead");for(let r of e.commands)wf(r)};var kf=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)");for(let r of e.commands)kf(r)};var t0=(e,t)=>[...t,e],r0=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 Ew(()=>sc({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));I(r),r.structuredContent.failedMerges>0&&(Ve.exitCode=1)}),eS=e=>(Ve.stdout.write(`${e.structuredContent.filePath}
497
- `),I(e)),n0=e=>e.description("List all release branches").action(async()=>{I(await cc())}),o0=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".',t0,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(yd),o=n.length>0?n:void 0;I(await yc({releases:o,confirmedCommand:t.yes}))}),s0=e=>{if(e==="")return e;try{return Br(e)}catch(t){throw t instanceof Qn?new tS(t.message):t}},i0=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new tS("Expected a positive whole number of days.");return t},a0=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)',s0).option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await kc({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),rS=e=>e.option("-f, --from <where>",`Where the deploy runs: ${yr.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" ("main" with gitFlow main) deploys from that branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),c0=e=>rS(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{I(await Zm({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),l0=e=>rS(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{I(await Qm({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),u0=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await ac({version:t.version,confirmedCommand:t.yes}))}),d0=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await Sc({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),p0=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await Lc({confirmedCommand:t.yes}))}),m0=e=>e.description("Add git worktrees for release branches or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{I(await _c({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),f0=e=>e.description("List all git worktrees with detailed information").action(async()=>{I(await Mc())}),g0=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{I(await Fc({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),h0=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{I(await tf({init:t.init}))}),y0=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ic();I(t),t.structuredContent.ok||(Ve.exitCode=1)}),v0=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=await yf({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly});I(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Ve.exitCode=1)}),w0=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{I(await Nm())}),k0=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{I(await _m())}),b0=new Set(["version"]),Ti=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},bf=()=>{let e=new ZL().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");r0(t.command("merge-dev")),n0(t.command("list")),o0(t.command("create")),a0(t.command("edit")),c0(t.command("deploy-all")),l0(t.command("deploy-selected")),u0(t.command("deliver")),d0(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");m0(r.command("add")),f0(r.command("list")),g0(r.command("remove")),p0(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");w0(n.command("path")),k0(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{I(await ga({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{I(await Mm({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{I(await jm({key:a,global:c.global}))});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{I(await Hc({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{I(await Hc({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)"),Ve.exitCode=1;return}let c=await ua({all:a.all,root:a.root,fix:a.fix,design:a.design});I(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&(Ve.exitCode=1)}),e.command("deploy-run").description("Deploy a service: its deploy.ts from infra-kit.deploy.ts, else its devops/scripts .sh (what the CI deploy job runs)").argument("<service>","The service as infra-kit.deploy.ts names it, e.g. client-be").action(async a=>{I(await Gm({service:a}))}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await Km({check:a.check});I(c),c.structuredContent.ok||(Ve.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");y0(i.command("check")),h0(i.command("config")),v0(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 ja({fix:!!a.fix,catalog:tn});Yt.enabled||Mu(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(Ve.exitCode=1),I(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),u=!!(Ve.stdout.isTTY&&Ve.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()=>{I(await ha())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{I(await Ua({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 QR("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new QR("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){I(await im());return}I(await Tc({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{I(await Nc())}),e.command("change-stats").description("Change-failure baseline for this git repo: agent vs human commits, revert and 72h follow-up-fix rates").option("--since <days>",`Window in days, ending now (default ${Zo})`,i0).action(async a=>{I(await fa({since:a.since}))}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{I(await Ka())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{I(await Ga())}),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=>{eS(await Ja({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{eS(await Wa())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");I(await Ym({fromFile:c.fromFile,force:c.force}));return}I(await zm({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{I(await Ha({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{I(await Hm({env:a}))});for(let a of e.commands)og(a);return wf(e),kf(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&e0(QL(Ve.cwd(),l)),y.start(Ti(c)),Yt.enabled=!!c.optsWithGlobals().json,Yt.command=Ti(c),Yt.enabled&&(d.level="warn"),N.source=ji({env:Ve.env,stdinIsTTY:Ve.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),b0.has(Ti(c))||await zu()}),e.hook("postAction",(a,c)=>{let l=Ti(c);if(Im(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;YR({equivalent:rl(f,!0)})}),e};import R0 from"node:process";var S0={exit:R0.exit,emit:I,logger:d},nS=(e,t=S0)=>Me(e)||xe(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof A?(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));import Rf from"node:process";var E0="MODULE_TYPELESS_PACKAGE_JSON",P0=(e,t)=>typeof e=="object"&&e!==null?e.code:t,oS=!1,Sf=()=>{if(oS)return;oS=!0;let e=Rf.emitWarning.bind(Rf);Rf.emitWarning=((t,...r)=>{P0(r[0],r[1])!==E0&&e(t,...r)})};var Ef=(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 x0 from"node:fs";import Pf from"node:path";import Po from"node:process";var aS=new Set([...wg,ft,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),cS=null,sl=new Set,xf=null,sS=!1;var iS=e=>{try{return x0.statSync(e)}catch{return null}},T0=()=>{if(sS)return null;try{return zt()}catch{return sS=!0,d.debug(`session-env: ${ft} unset \u2014 no overlay`),null}},C0=e=>{let t=Pf.join(e,Ht),r=Pf.join(e,Ai),n=iS(t),o=iS(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?_f(Pf.join(e,nn),Po.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"}},$0=e=>e.kind==="load"?{kind:"load",vars:If(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Nf(e.file),signature:e.signature}:e;var A0=()=>{let e=T0();if(e===null)return{kind:"no-session"};let t=C0(e);return t.signature===xf?null:$0(t)},O0=()=>{for(let e of sl){let t=cS[e];t===void 0?delete Po.env[e]:Po.env[e]=t}sl.clear()},D0=(e,t,r)=>{if(aS.has(t)){e.skipped.push(t);return}Po.env[t]=r,sl.add(t),e.set.push(t)},I0=(e,t)=>{if(aS.has(t)){e.skipped.push(t);return}delete Po.env[t],sl.add(t),e.unset.push(t)},N0=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))D0(t,r,n);if(e.kind==="clear")for(let r of e.unset)I0(t,r);return t},_0=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Tf=(e=A0())=>{if(cS??={...Po.env},e===null||e.kind==="no-session"||e.signature===xf)return{set:[],unset:[],changed:!1};O0();let{set:t,unset:r,skipped:n}=N0(e);return xf=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(", ")}] (${_0(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as rB}from"chalk";import{spawn as nB}from"node:child_process";import We from"node:process";import{Chalk as M0}from"chalk";var xo=new M0({level:1}),mt={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."},j0={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"}},lS={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},uS={unicode:"\u2500",ascii:"-"},F0=3,Cf=e=>e,L0={ok:e=>xo.green(e),findings:e=>xo.yellow(e),failed:e=>xo.red(e),cancelled:e=>xo.gray(e)},Af=e=>e?{dim:t=>xo.dim(t),bold:t=>xo.bold(t)}:{dim:Cf,bold:Cf},B0=(e,t)=>e?L0[t]:Cf,$f=e=>[...e].length,U0=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return $f(e)<=r?e:[...e].slice(0,r).join("")},dS=e=>{let t=Af(e.color===!0).dim,r=j0[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(U0(n,e.width))},pS=(e,t={})=>{let r=Af(t.color===!0);return`${r.dim(mt.reproPrefix.trim())} ${r.bold(e)}`},V0=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,W0=(e,t)=>e==="findings"?t!=null?`${t} ${mt.findingsSuffix}`:mt.findingsPlain:{ok:mt.ok,failed:mt.failed,cancelled:mt.cancelled}[e],G0=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<F0?"":` ${n(r.repeat(o))}`},mS=e=>{let t=e.color===!0,r=Af(t),n=B0(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?mt.reproPrefix:mt.nonReproPrefix,i=o?lS[e.outcome].ascii:lS[e.outcome].unicode,a=W0(e.outcome,e.findingsCount),c=[V0(e.durationMs)],l=e.summary?.[0]?.split(`
498
- `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${mt.sep}${c.join(mt.sep)}`,m=$f(u)+$f(p),f=G0(m,e.width,o?uS.ascii:uS.unicode,r.dim),h=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&h.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&h.push(r.dim(mt.envNotice)),h.join(`
499
- `)};var J0=new Set([130,143]),fS=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&J0.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import K0 from"node:process";var H0={3:"quit",4:"quit",26:"suspend",27:"quit"},q0=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":H0[t]??"continue"},z0=150,Y0="\r\x1B[2K",X0=`\r
500
- `,gS=(e,t)=>{hS(e),e.stdin.on("data",t),e.listener=t},hS=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},yS=(e,t)=>{Vg(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),gS(e,t)},vS=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(Y0)),hS(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Wg()},Z0=e=>{e.settled||(e.settled=!0,vS(e))},wS=(e,t)=>{let r=dS({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},Q0=async e=>{await new Promise(t=>{setTimeout(t,e)})},eB=(e,t,r)=>{vS(e),t(),yS(e,r),wS(e,X0)},tB=async e=>new Promise(t=>{let r=n=>{let o=q0(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){eB(e,s,r);return}t("palette")};gS(e,r),wS(e,"")}),kS=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??K0.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return yS(n,()=>{}),e.armed(),await Q0(t.drainMs??z0),await tB(n)}finally{Z0(n)}};import bS from"node:process";var Sr={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},RS=(e,t)=>{let r=t?.write??(s=>{bS.stderr.write(s)}),n=t?.stdin??bS.stdin,o=[Sr.saveCursor,Sr.scrollRegion,Sr.restoreCursor,Sr.column,Sr.sgr,Sr.cursor,Sr.wrap];e.entersAltScreen===!0&&o.push(Sr.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var SS=e=>`infra-kit ${e.groupPath.join(" ")}`,oB=()=>{sB();let e=We.stderr.columns;return e!=null&&e>0?e:void 0},sB=()=>{let e=We.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},iB=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),aB=async(e,t,r)=>{let n=XR(),o={...t.env,[ol]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(We.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await iB(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=ZR(n),c=fS(i.code,i.signal,a!=null,e.longRunning),l=SS(e),u=a?.equivalent??rl(l,!0);return mS({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)})},cB=1e3,lB=(e,t)=>e!=null&&t-e<=cB,Of=e=>{e.resetTerminal(),e.exit(0)},uB=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Of(t)},s=()=>{let c=e();if(c==="palette"){Of(t);return}if(!lB(r,t.now())){if(c==="pause"){Of(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}},ES=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),dB=We.platform==="win32"?void 0:()=>{Kg()},pB=(e,t)=>r=>kS(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:dB}),PS=async(e,t)=>{let r={spawn:t.spawn??nB,now:t.now??(()=>Date.now()),env:t.env??We.env,cliPath:t.cliPath,ascii:t.ascii??!(We.stdout.isTTY&&We.env.TERM!=="dumb"),color:t.color??rB.level>0,columns:t.columns??oB,resetTerminal:t.resetTerminal??(u=>{RS(u)})},n=t.write??(u=>We.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{We.on(u,p)},unregister:(u,p)=>{We.off(u,p)},exit:u=>{We.exit(u)},raise:u=>{We.kill(We.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:uB(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??pB(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=pS(SS(p),{color:r.color});n(`
496
+ `)},XL=async(e,t,r)=>r?(JR(t,Eo(t)),af(t.root,e)):(await sf({source:e,plan:t,onBeforeFirstWrite:o=>{JR(t,o)}})).touched,ZL=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await XL(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 lf(t.root,n,cf(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},QL=async(e,t,r)=>{let n=[];for(let o of t)n.push(await ZL(e,o,r));return n},zR=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})),e0={mode:z.enum(["preview","check","applied"]),source:z.object({root:z.string(),name:z.string(),headSha:z.string().nullable()}),targets:z.array(z.looseObject({name:z.string(),root:z.string(),status:z.string(),applied:z.boolean()})),changed:z.boolean(),failed:z.boolean(),report:z.array(z.object({label:z.string(),rows:z.array(z.object({name:z.string(),status:z.enum(["ok","changed","skipped","manual","warn","fail"]),message:z.string(),notes:z.array(z.string()).optional()}))})).readonly().describe("The printed report sections")},yf=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&Rt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:zR(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:LR(t),report:t.sections}}},t0=async e=>{let t=await $a(),r=zL(t),n=await UR(r),o=await YL(r),s=WR(t,e.targets??[]),i=await mf(r,o),a=await GR(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},vf=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await t0(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=ff(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return yf({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!H();if(l&&!HR.stdin.isTTY)return Rt(a),yf({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&Rt({...a,hints:[]}),await q(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:zR(n)});let u=await QL(t,n,e),p=ff(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);Rt(BR(a,p,m))}return yf({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var rl=(e,t=!0)=>({line:e,reproducible:t});import nl from"node:fs";import r0 from"node:os";import n0 from"node:path";import QR from"node:process";var ol="INFRA_KIT_SESSION_REPORT",wf=null,YR=!1,XR=[],eS=(e=QR.env)=>{YR||(wf=e[ol]??null,YR=!0,delete e[ol])};var tS=(e,t)=>{if(!wf)return;let r=e.summary??(XR.length>0?[...XR]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{nl.writeFileSync(s,i)});try{o(wf,JSON.stringify(n))}catch{}},ZR=0,rS=e=>{let t=e?.tmpdir?.()??r0.tmpdir(),r=e?.pid??QR.pid;return ZR+=1,n0.join(t,`infra-kit-session-${r}-${ZR}.json`)},nS=(e,t)=>{if(!(t?.exists??(i=>nl.existsSync(i)))(e))return null;let n=t?.read??(i=>nl.readFileSync(i,"utf-8")),o=t?.unlink??(i=>nl.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var kf=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead");for(let r of e.commands)kf(r)};var bf=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)");for(let r of e.commands)bf(r)};var a0=(e,t)=>[...t,e],c0=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 $w(()=>sc({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));I(r),r.structuredContent.failedMerges>0&&(Ve.exitCode=1)}),sS=e=>(Ve.stdout.write(`${e.structuredContent.filePath}
497
+ `),I(e)),l0=e=>e.description("List all release branches").action(async()=>{I(await cc())}),u0=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".',a0,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(vd),o=n.length>0?n:void 0;I(await yc({releases:o,confirmedCommand:t.yes}))}),d0=e=>{if(e==="")return e;try{return Br(e)}catch(t){throw t instanceof eo?new iS(t.message):t}},p0=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new iS("Expected a positive whole number of days.");return t},m0=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)',d0).option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await kc({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),aS=e=>e.option("-f, --from <where>",`Where the deploy runs: ${yr.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" ("main" with gitFlow main) deploys from that branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),f0=e=>aS(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{I(await Qm({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),g0=e=>aS(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{I(await ef({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),h0=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await ac({version:t.version,confirmedCommand:t.yes}))}),y0=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await Sc({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),v0=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await Lc({confirmedCommand:t.yes}))}),w0=e=>e.description("Add git worktrees for release branches or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{I(await _c({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),k0=e=>e.description("List all git worktrees with detailed information").action(async()=>{I(await Mc())}),b0=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{I(await Fc({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),R0=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{I(await rf({init:t.init}))}),S0=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ic();I(t),t.structuredContent.ok||(Ve.exitCode=1)}),E0=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=await vf({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly});I(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Ve.exitCode=1)}),P0=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{I(await _m())}),x0=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{I(await Mm())}),T0=new Set(["version"]),Ti=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Rf=()=>{let e=new o0().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");c0(t.command("merge-dev")),l0(t.command("list")),u0(t.command("create")),m0(t.command("edit")),f0(t.command("deploy-all")),g0(t.command("deploy-selected")),h0(t.command("deliver")),y0(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");w0(r.command("add")),k0(r.command("list")),b0(r.command("remove")),v0(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");P0(n.command("path")),x0(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{I(await ga({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{I(await jm({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{I(await Fm({key:a,global:c.global}))});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{I(await Hc({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{I(await Hc({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)"),Ve.exitCode=1;return}let c=await ua({all:a.all,root:a.root,fix:a.fix,design:a.design});I(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&(Ve.exitCode=1)}),e.command("deploy-run").description("Deploy a service: its deploy.ts from infra-kit.deploy.ts, else its devops/scripts .sh (what the CI deploy job runs)").argument("<service>","The service as infra-kit.deploy.ts names it, e.g. client-be").action(async a=>{I(await Jm({service:a}))}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await Hm({check:a.check});I(c),c.structuredContent.ok||(Ve.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");S0(i.command("check")),R0(i.command("config")),E0(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 ja({fix:!!a.fix,catalog:tn});Xt.enabled||ju(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(Ve.exitCode=1),I(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),u=!!(Ve.stdout.isTTY&&Ve.stdin.isTTY);await l({...c,appName:a},u,Xt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{I(await ha())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{I(await Ua({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 oS("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new oS("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){I(await am());return}I(await Tc({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{I(await Nc())}),e.command("change-stats").description("Change-failure baseline for this git repo: agent vs human commits, revert and 72h follow-up-fix rates").option("--since <days>",`Window in days, ending now (default ${Zo})`,p0).action(async a=>{I(await fa({since:a.since}))}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{I(await Ka())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{I(await Ga())}),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=>{sS(await Ja({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{sS(await Wa())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");I(await Xm({fromFile:c.fromFile,force:c.force}));return}I(await Ym({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{I(await Ha({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{I(await qm({env:a}))});for(let a of e.commands)sg(a);return kf(e),bf(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&i0(s0(Ve.cwd(),l)),y.start(Ti(c)),Xt.enabled=!!c.optsWithGlobals().json,Xt.command=Ti(c),Xt.enabled&&(d.level="warn"),N.source=ji({env:Ve.env,stdinIsTTY:Ve.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),T0.has(Ti(c))||await Yu()}),e.hook("postAction",(a,c)=>{let l=Ti(c);if(Nm(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;tS({equivalent:rl(f,!0)})}),e};import C0 from"node:process";var $0={exit:C0.exit,emit:I,logger:d},cS=(e,t=$0)=>Me(e)||xe(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof A?(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));import Sf from"node:process";var A0="MODULE_TYPELESS_PACKAGE_JSON",O0=(e,t)=>typeof e=="object"&&e!==null?e.code:t,lS=!1,Ef=()=>{if(lS)return;lS=!0;let e=Sf.emitWarning.bind(Sf);Sf.emitWarning=((t,...r)=>{O0(r[0],r[1])!==A0&&e(t,...r)})};var Pf=(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 D0 from"node:fs";import xf from"node:path";import xo from"node:process";var pS=new Set([...Sg,ft,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),mS=null,sl=new Set,Tf=null,uS=!1;var dS=e=>{try{return D0.statSync(e)}catch{return null}},I0=()=>{if(uS)return null;try{return Yt()}catch{return uS=!0,d.debug(`session-env: ${ft} unset \u2014 no overlay`),null}},N0=e=>{let t=xf.join(e,qt),r=xf.join(e,Ai),n=dS(t),o=dS(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Mf(xf.join(e,nn),xo.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"}},_0=e=>e.kind==="load"?{kind:"load",vars:Nf(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:_f(e.file),signature:e.signature}:e;var M0=()=>{let e=I0();if(e===null)return{kind:"no-session"};let t=N0(e);return t.signature===Tf?null:_0(t)},j0=()=>{for(let e of sl){let t=mS[e];t===void 0?delete xo.env[e]:xo.env[e]=t}sl.clear()},F0=(e,t,r)=>{if(pS.has(t)){e.skipped.push(t);return}xo.env[t]=r,sl.add(t),e.set.push(t)},L0=(e,t)=>{if(pS.has(t)){e.skipped.push(t);return}delete xo.env[t],sl.add(t),e.unset.push(t)},B0=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))F0(t,r,n);if(e.kind==="clear")for(let r of e.unset)L0(t,r);return t},U0=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Cf=(e=M0())=>{if(mS??={...xo.env},e===null||e.kind==="no-session"||e.signature===Tf)return{set:[],unset:[],changed:!1};j0();let{set:t,unset:r,skipped:n}=B0(e);return Tf=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(", ")}] (${U0(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as cB}from"chalk";import{spawn as lB}from"node:child_process";import We from"node:process";import{Chalk as V0}from"chalk";var To=new V0({level:1}),mt={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."},W0={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"}},fS={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},gS={unicode:"\u2500",ascii:"-"},G0=3,$f=e=>e,J0={ok:e=>To.green(e),findings:e=>To.yellow(e),failed:e=>To.red(e),cancelled:e=>To.gray(e)},Of=e=>e?{dim:t=>To.dim(t),bold:t=>To.bold(t)}:{dim:$f,bold:$f},K0=(e,t)=>e?J0[t]:$f,Af=e=>[...e].length,H0=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Af(e)<=r?e:[...e].slice(0,r).join("")},hS=e=>{let t=Of(e.color===!0).dim,r=W0[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(H0(n,e.width))},yS=(e,t={})=>{let r=Of(t.color===!0);return`${r.dim(mt.reproPrefix.trim())} ${r.bold(e)}`},q0=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,z0=(e,t)=>e==="findings"?t!=null?`${t} ${mt.findingsSuffix}`:mt.findingsPlain:{ok:mt.ok,failed:mt.failed,cancelled:mt.cancelled}[e],Y0=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<G0?"":` ${n(r.repeat(o))}`},vS=e=>{let t=e.color===!0,r=Of(t),n=K0(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?mt.reproPrefix:mt.nonReproPrefix,i=o?fS[e.outcome].ascii:fS[e.outcome].unicode,a=z0(e.outcome,e.findingsCount),c=[q0(e.durationMs)],l=e.summary?.[0]?.split(`
498
+ `)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${mt.sep}${c.join(mt.sep)}`,m=Af(u)+Af(p),f=Y0(m,e.width,o?gS.ascii:gS.unicode,r.dim),h=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&h.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&h.push(r.dim(mt.envNotice)),h.join(`
499
+ `)};var X0=new Set([130,143]),wS=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&X0.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import Z0 from"node:process";var Q0={3:"quit",4:"quit",26:"suspend",27:"quit"},eB=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":Q0[t]??"continue"},tB=150,rB="\r\x1B[2K",nB=`\r
500
+ `,kS=(e,t)=>{bS(e),e.stdin.on("data",t),e.listener=t},bS=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},RS=(e,t)=>{Kg(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),kS(e,t)},SS=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(rB)),bS(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Hg()},oB=e=>{e.settled||(e.settled=!0,SS(e))},ES=(e,t)=>{let r=hS({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},sB=async e=>{await new Promise(t=>{setTimeout(t,e)})},iB=(e,t,r)=>{SS(e),t(),RS(e,r),ES(e,nB)},aB=async e=>new Promise(t=>{let r=n=>{let o=eB(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){iB(e,s,r);return}t("palette")};kS(e,r),ES(e,"")}),PS=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??Z0.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return RS(n,()=>{}),e.armed(),await sB(t.drainMs??tB),await aB(n)}finally{oB(n)}};import xS from"node:process";var Sr={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},TS=(e,t)=>{let r=t?.write??(s=>{xS.stderr.write(s)}),n=t?.stdin??xS.stdin,o=[Sr.saveCursor,Sr.scrollRegion,Sr.restoreCursor,Sr.column,Sr.sgr,Sr.cursor,Sr.wrap];e.entersAltScreen===!0&&o.push(Sr.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var CS=e=>`infra-kit ${e.groupPath.join(" ")}`,uB=()=>{dB();let e=We.stderr.columns;return e!=null&&e>0?e:void 0},dB=()=>{let e=We.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},pB=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),mB=async(e,t,r)=>{let n=rS(),o={...t.env,[ol]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(We.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await pB(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=nS(n),c=wS(i.code,i.signal,a!=null,e.longRunning),l=CS(e),u=a?.equivalent??rl(l,!0);return vS({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)})},fB=1e3,gB=(e,t)=>e!=null&&t-e<=fB,Df=e=>{e.resetTerminal(),e.exit(0)},hB=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Df(t)},s=()=>{let c=e();if(c==="palette"){Df(t);return}if(!gB(r,t.now())){if(c==="pause"){Df(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}},$S=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),yB=We.platform==="win32"?void 0:()=>{Yg()},vB=(e,t)=>r=>PS(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:yB}),AS=async(e,t)=>{let r={spawn:t.spawn??lB,now:t.now??(()=>Date.now()),env:t.env??We.env,cliPath:t.cliPath,ascii:t.ascii??!(We.stdout.isTTY&&We.env.TERM!=="dumb"),color:t.color??cB.level>0,columns:t.columns??uB,resetTerminal:t.resetTerminal??(u=>{TS(u)})},n=t.write??(u=>We.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{We.on(u,p)},unregister:(u,p)=>{We.off(u,p)},exit:u=>{We.exit(u)},raise:u=>{We.kill(We.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:hB(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??vB(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=yS(CS(p),{color:r.color});n(`
501
501
  ${m}
502
- `),a.childStarted();let f=await aB(p,r,()=>{o="child"});if(n(`
502
+ `),a.childStarted();let f=await mB(p,r,()=>{o="child"});if(n(`
503
503
  ${f}
504
- `),await l(c)==="quit")return}}finally{a.dispose()}};Sf();zR();fw(()=>import("./boot-26CWOALE.js"));var $S=bf(),TS=async(e=Ge.argv)=>{Tf(),Bg(e);try{await $S.parseAsync(e)}catch(t){nS(t)}},yB=()=>{try{if(Ge.env.INFRA_KIT_NO_LOCATION_WARN||Ge.argv.includes("--json"))return;Lf({selfRealPath:gB(CS(import.meta.url)),cwd:Ge.cwd(),env:Ge.env,realpath:Se,home:hB(),exists:fB})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};yB();ng((e,t)=>{d.debug(e,t)});Xu(U.version);var AS=()=>zb($S.commands),vB=async()=>{let e=AS(),t=null;try{if(Ge.stdout.isTTY&&Ge.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-26CWOALE.js");t=await r(e)}else{let r=Ef(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new xS(" "),new xS(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await _(o=>mB({message:"Select a command to run",choices:n},o),{output:Ge.stderr})}}catch(r){if(!Me(r))throw r}return t},wB=async()=>{let{runCommandPalette:e}=await import("./boot-26CWOALE.js"),t=CS(import.meta.url),r=new Map(tn.map(n=>[n.groupPath.join(" "),n]));await PS(AS(),{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(Ge.argv.length<=2){let e={stdoutIsTTY:!!Ge.stdout.isTTY,stdinIsTTY:!!Ge.stdin.isTTY,stderrIsTTY:!!Ge.stderr.isTTY};if(ES(Ge.env,e))await wB();else{let t=await vB();t&&await TS(["node","infra-kit",...t.split(" ")])}}else await TS();
504
+ `),await l(c)==="quit")return}}finally{a.dispose()}};Ef();eS();ww(()=>import("./boot-26CWOALE.js"));var NS=Rf(),DS=async(e=Ge.argv)=>{Cf(),Gg(e);try{await NS.parseAsync(e)}catch(t){cS(t)}},SB=()=>{try{if(Ge.env.INFRA_KIT_NO_LOCATION_WARN||Ge.argv.includes("--json"))return;Bf({selfRealPath:bB(IS(import.meta.url)),cwd:Ge.cwd(),env:Ge.env,realpath:Se,home:RB(),exists:kB})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};SB();og((e,t)=>{d.debug(e,t)});Zu(U.version);var _S=()=>eR(NS.commands),EB=async()=>{let e=_S(),t=null;try{if(Ge.stdout.isTTY&&Ge.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-26CWOALE.js");t=await r(e)}else{let r=Pf(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new OS(" "),new OS(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await _(o=>wB({message:"Select a command to run",choices:n},o),{output:Ge.stderr})}}catch(r){if(!Me(r))throw r}return t},PB=async()=>{let{runCommandPalette:e}=await import("./boot-26CWOALE.js"),t=IS(import.meta.url),r=new Map(tn.map(n=>[n.groupPath.join(" "),n]));await AS(_S(),{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(Ge.argv.length<=2){let e={stdoutIsTTY:!!Ge.stdout.isTTY,stdinIsTTY:!!Ge.stdin.isTTY,stderrIsTTY:!!Ge.stderr.isTTY};if($S(Ge.env,e))await PB();else{let t=await EB();t&&await DS(["node","infra-kit",...t.split(" ")])}}else await DS();
505
505
  //# sourceMappingURL=cli.js.map