infra-kit 0.11.12 → 0.11.16

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 xu,d as Du,f as hs,h as Dr,i as ys,j as _u,k as Mu,l as ju,m as Fu,n as Lu,o as Vu,p as Bu,q as Wu,t as Ju,u as Uu,v as we}from"./chunk-RD556L3P.js";import{a as Rt,b as Vp,c as ha,d as Bp,e as Wp,f as Jp,g as Up,h as $n,i as Gp,j as Kp,k as Hp,l as qp,m as zp,n as An,o as Yp,p as Xp,q as Zp,r as Qp,s as ya,t as ns,u as Pt,v as eu,w as os,x as tu}from"./chunk-CMF7HEVU.js";import{a as ae,b as H,c as Et,d as ps,e as ba,f as us,g as Ra,h as Dn,i as qt,j as ms,k as fu,l as In,m as Nn,n as Sa,o as Ea,q as xa}from"./chunk-BQPSXIH2.js";import{b as Cn,c as ts,d as ga,e as _p,f as rs,g as Mp,i as jp,k as Fp,m as he,o as Lp}from"./chunk-AWFGP6GY.js";import{a as Ou}from"./chunk-TVG47UHG.js";import{a as h,b as at,c as x,d as Tu,e as Cu,f as D,g as fs,h as W,i as gs,j as ct,k as ue,l as Iu,m as Nu}from"./chunk-2CCPRPPP.js";import{$ as te,A as au,B as cu,C as lu,D as cs,E as ls,F as $e,G as On,H as Or,I as ds,J as du,K as pu,L as uu,M as wa,N as ka,O as mu,P as p,Q as qe,R as ee,S as w,T as gu,U as hu,V as xt,W as vu,X as Pa,Y as Tt,Z as wu,_ as ku,a as it,aa as I,b as $,ba as bu,c as ru,ca as Ct,d as A,e as Q,ea as Ru,f as ie,g as ss,ga as Pu,h as $r,i as f,j as nu,k as is,l as K,m as ve,n as Te,na as Su,o as ou,p as va,q as ne,qa as Eu,r as Y,s as as,t as su,u as St,v as Ce,w as S,x as Le,y as Ar,z as iu}from"./chunk-666XR52E.js";import{a as yu}from"./chunk-MFAFQVTW.js";import{a as q}from"./chunk-SBD7FT5C.js";import{a as kt,b as Xo,c as He,d as Op,e as st,f as Er,g as xr,h as Zo,i as Tr,j as Qo,k as Dp,l as Ip,m as Np,n as bt,o as es,p as ge,q as Cr}from"./chunk-QSTGO43H.js";import{a as $u,b as Au}from"./chunk-QWVLAZ6N.js";import eD,{Separator as wv}from"@inquirer/select";import{existsSync as tD,realpathSync as rD}from"node:fs";import{homedir as nD}from"node:os";import Ee from"node:process";import{fileURLToPath as bv}from"node:url";import Tm from"node:process";import{z as De}from"zod";import Zu from"node:fs";import Nr from"node:path";import{packageConfigSchema as Hu}from"@slip-stream-kit/config/internal";import qu from"node:fs/promises";import vs from"node:path";import{pathToFileURL as Av}from"node:url";import{z as zu}from"zod";import Gu from"node:path";var _n=["frontend","backend","lib","e2e","mobile"],Sv={ui:"frontend",api:"backend",tests:"e2e"},Ev="mobile-app",xv=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Tv=(e,t)=>{let r=Gu.relative(t,e).split(Gu.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=Sv[o];if(s)return s}return r.at(-1)===Ev?"mobile":null},Cv=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of xv)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Mn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??Tv(e,t)??Cv(r)??"lib";var $t={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Ku=2e3,Ta={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Ku}} 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"},Ca={requiredScripts:["build","dev","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},$a=(e,t=$t)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import $v from"node:fs/promises";var Ve=async e=>{try{return await $v.access(e),!0}catch{return!1}};var Be="infra-kit.config.ts",zt=async e=>{try{let t=await qu.readFile(vs.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Aa=async e=>{let t=await qu.stat(e),o=(await import(`${Av(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${Be} at ${e} has no default export`);return typeof o=="function"?await o():o},Yt=async e=>{let t=vs.join(e,Be);if(await Ve(t))try{let n=(await Aa(t))?.type;return _n.find(o=>o===n)}catch{return}},jn=async(e,t=$t)=>{let r=vs.join(e,Be);if(!await Ve(r))throw new Error(`${Be} not found at ${r}`);let n=await Aa(r),o=Hu.safeParse(n);if(!o.success)throw new Error(`Invalid ${Be} at ${r}: ${zu.prettifyError(o.error)}`);return $a(o.data,t)},Oa=async e=>{let t=vs.join(e,Be);if(!await Ve(t))return;let r=Hu.safeParse(await Aa(t));if(!r.success)throw new Error(`Invalid ${Be} at ${t}: ${zu.prettifyError(r.error)}`);return r.data};import Yu from"node:fs/promises";import ws from"node:path";import Ov from"yaml";var Dv="pnpm-workspace.yaml",Iv=async e=>(await Yu.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>ws.join(e,r.name)),Nv=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await Iv(n));continue}let o=ws.join(n,t);await Ve(o)&&r.push(o)}return r},_v=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await Nv(r,n);return r},ke=async e=>{let t=await Yu.readFile(ws.join(e,Dv),"utf-8"),n=((Ov.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await _v(e,s);for(let a of i)await Ve(ws.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Fn from"node:path";var Ln=async e=>{let t=Fn.resolve(e);for(;t!==Fn.dirname(t);){if(await Ve(Fn.join(t,"package.json")))return t;t=Fn.dirname(t)}if(await Ve(Fn.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var ze=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},At=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);if(n===-1||o===-1||o<n)return null;let s=e.slice(0,n).replace(/\n+$/,""),i=e.slice(o+r.length).replace(/^\n+/,"");return s+(i?`
3
- ${i}`:"")},Da=(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},Xu=(e,t,r)=>`${e}
2
+ import{a as $u,d as _u,f as bs,h as Ir,i as Rs,j as Fu,k as Lu,l as Vu,m as Bu,n as Wu,o as Ju,p as Uu,q as Gu,t as Ku,u as Hu,v as we}from"./chunk-TT7OQ4PI.js";import{a as Rt,b as Wp,c as va,d as Jp,e as Up,f as Gp,g as Kp,h as Dn,i as Hp,j as qp,k as zp,l as Yp,m as Xp,n as Nn,o as Zp,p as Qp,q as eu,r as tu,s as wa,t as cs,u as St,v as ru,w as ls,x as nu}from"./chunk-CMF7HEVU.js";import{a as ae,b as H,c as Et,d as hs,e as Sa,f as ys,g as Pa,h as Mn,i as qt,j as vs,k as hu,l as jn,m as Fn,n as xa,o as Ta,q as Ca}from"./chunk-BQPSXIH2.js";import{b as In,c as is,d as ya,e as jp,f as as,g as Fp,i as Lp,k as Vp,m as he,o as Bp}from"./chunk-AWFGP6GY.js";import{a as Nu}from"./chunk-TVG47UHG.js";import{a as h,b as ct,c as E,d as Au,e as Ou,f as I,g as ws,h as W,i as ks,j as lt,k as ue,l as Mu,m as ju}from"./chunk-UZTYMT6R.js";import{$ as Su,A as lu,B as du,C as pu,D as ms,E as fs,F as $e,G as _n,H as Or,I as gs,J as uu,K as mu,L as fu,M as ba,N as Ra,O as gu,P as p,Q as qe,R as X,S as w,T as yu,U as vu,V as ku,W as xt,X as bu,Y as Ea,Z as Tt,_ as Ru,a as at,aa as te,b as $,ba as D,c as ou,ca as Pu,d as A,da as Ct,e as ee,f as ie,fa as Eu,g as ds,h as $r,ha as xu,i as f,j as su,k as ps,l as K,m as ve,n as Te,o as iu,oa as Tu,p as ka,q as ne,r as Y,ra as Cu,s as us,t as au,u as Pt,v as Ce,w as x,x as Le,y as Ar,z as cu}from"./chunk-J7KIXQRB.js";import{a as wu}from"./chunk-MFAFQVTW.js";import{a as q}from"./chunk-6SLDCUNI.js";import{a as kt,b as rs,c as He,d as Dp,e as it,f as Er,g as xr,h as ns,i as Tr,j as os,k as Np,l as _p,m as Mp,n as bt,o as ss,p as ge,q as Cr}from"./chunk-QSTGO43H.js";import{a as Iu,b as Du}from"./chunk-QWVLAZ6N.js";import dI,{Separator as Rv}from"@inquirer/select";import{existsSync as pI,realpathSync as uI}from"node:fs";import{homedir as mI}from"node:os";import Ee from"node:process";import{fileURLToPath as Pv}from"node:url";import Am from"node:process";import{z as Ie}from"zod";import tm from"node:fs";import Nr from"node:path";import{packageConfigSchema as Yu}from"@slip-stream-kit/config/internal";import Xu from"node:fs/promises";import Ss from"node:path";import{pathToFileURL as Dv}from"node:url";import{z as Zu}from"zod";import qu from"node:path";var Ln=["frontend","backend","lib","e2e","mobile"],Tv={ui:"frontend",api:"backend",tests:"e2e"},Cv="mobile-app",$v=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Av=(e,t)=>{let r=qu.relative(t,e).split(qu.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=Tv[o];if(s)return s}return r.at(-1)===Cv?"mobile":null},Ov=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of $v)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Vn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??Av(e,t)??Ov(r)??"lib";var $t={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},zu=2e3,$a={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${zu}} 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"},Aa={requiredScripts:["build","dev","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},Oa=(e,t=$t)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import Iv from"node:fs/promises";var Ve=async e=>{try{return await Iv.access(e),!0}catch{return!1}};var Be="infra-kit.config.ts",zt=async e=>{try{let t=await Xu.readFile(Ss.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Ia=async e=>{let t=await Xu.stat(e),o=(await import(`${Dv(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${Be} at ${e} has no default export`);return typeof o=="function"?await o():o},Yt=async e=>{let t=Ss.join(e,Be);if(await Ve(t))try{let n=(await Ia(t))?.type;return Ln.find(o=>o===n)}catch{return}},Bn=async(e,t=$t)=>{let r=Ss.join(e,Be);if(!await Ve(r))throw new Error(`${Be} not found at ${r}`);let n=await Ia(r),o=Yu.safeParse(n);if(!o.success)throw new Error(`Invalid ${Be} at ${r}: ${Zu.prettifyError(o.error)}`);return Oa(o.data,t)},Da=async e=>{let t=Ss.join(e,Be);if(!await Ve(t))return;let r=Yu.safeParse(await Ia(t));if(!r.success)throw new Error(`Invalid ${Be} at ${t}: ${Zu.prettifyError(r.error)}`);return r.data};import Qu from"node:fs/promises";import Ps from"node:path";import Nv from"yaml";var _v="pnpm-workspace.yaml",Mv=async e=>(await Qu.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Ps.join(e,r.name)),jv=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await Mv(n));continue}let o=Ps.join(n,t);await Ve(o)&&r.push(o)}return r},Fv=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await jv(r,n);return r},ke=async e=>{let t=await Qu.readFile(Ps.join(e,_v),"utf-8"),n=((Nv.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await Fv(e,s);for(let a of i)await Ve(Ps.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Wn from"node:path";var Jn=async e=>{let t=Wn.resolve(e);for(;t!==Wn.dirname(t);){if(await Ve(Wn.join(t,"package.json")))return t;t=Wn.dirname(t)}if(await Ve(Wn.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var ze=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},At=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);if(n===-1||o===-1||o<n)return null;let s=e.slice(0,n).replace(/\n+$/,""),i=e.slice(o+r.length).replace(/^\n+/,"");return s+(i?`
3
+ ${i}`:"")},Na=(e,t)=>{let r=e.indexOf(t);if(r===-1)return null;let o=e.slice(r+t.length).match(/^([^\s>]+)/);return o?o[1]:null},em=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,Ir=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Xu(r,t,n),i=ze(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?At(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,Dr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=em(r,t,n),i=ze(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?At(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var Ae="<!-- infra-kit:begin -->",Ye="<!-- infra-kit:end -->",Ia="<!-- infra-kit:version ",Xe="<!-- infra-kit:package:begin -->",lt="<!-- infra-kit:package:end -->",Xt="<!-- infra-kit:package:version ";var Mv=e=>{let t=e.indexOf(Xe)+Xe.length;return e.slice(t,e.indexOf(lt))},jv=e=>{let t=e.indexOf(Xt);if(t===-1)return null;let r=e.slice(t+Xt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return _n.find(n=>n===r)??null},Zt=e=>{if(e===null)return{state:"missing"};if(!ze(e,Xe,lt))return e.includes(Xe)||e.includes(lt)?{state:"malformed"}:ze(e,Ae,Ye)?{state:"foreign-block"}:{state:"no-block"};let t=Mv(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Da(t,Xt),o=jv(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Fv from"node:fs";var Qt=e=>{try{return Fv.readFileSync(e,"utf-8")}catch{return null}};var Qu="pnpm-workspace.yaml",Lv="CLAUDE.md",_a=e=>{let t=Nr.resolve(e);for(;t!==Nr.dirname(t);){if(Zu.existsSync(Nr.join(t,Qu)))return t;t=Nr.dirname(t)}return Zu.existsSync(Nr.join(t,Qu))?t:null},Na=new Map,ks=()=>{Na.clear()},Vv=async e=>{let t;try{t=await ke(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Nr.join(r,Lv),o=Qt(n);if(o!==null&&Zt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},_r=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Na.get(e);if(t)return t;let r=await Vv(e);return Na.set(e,r),r};import er from"node:fs";import Ot from"node:path";var em=`---
8
+ `};var Ae="<!-- infra-kit:begin -->",Ye="<!-- infra-kit:end -->",_a="<!-- infra-kit:version ",Xe="<!-- infra-kit:package:begin -->",dt="<!-- infra-kit:package:end -->",Xt="<!-- infra-kit:package:version ";var Lv=e=>{let t=e.indexOf(Xe)+Xe.length;return e.slice(t,e.indexOf(dt))},Vv=e=>{let t=e.indexOf(Xt);if(t===-1)return null;let r=e.slice(t+Xt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Ln.find(n=>n===r)??null},Zt=e=>{if(e===null)return{state:"missing"};if(!ze(e,Xe,dt))return e.includes(Xe)||e.includes(dt)?{state:"malformed"}:ze(e,Ae,Ye)?{state:"foreign-block"}:{state:"no-block"};let t=Lv(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Na(t,Xt),o=Vv(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Bv from"node:fs";var Qt=e=>{try{return Bv.readFileSync(e,"utf-8")}catch{return null}};var rm="pnpm-workspace.yaml",Wv="CLAUDE.md",ja=e=>{let t=Nr.resolve(e);for(;t!==Nr.dirname(t);){if(tm.existsSync(Nr.join(t,rm)))return t;t=Nr.dirname(t)}return tm.existsSync(Nr.join(t,rm))?t:null},Ma=new Map,Es=()=>{Ma.clear()},Jv=async e=>{let t;try{t=await ke(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Nr.join(r,Wv),o=Qt(n);if(o!==null&&Zt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},_r=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Ma.get(e);if(t)return t;let r=await Jv(e);return Ma.set(e,r),r};import er from"node:fs";import Ot from"node:path";var nm=`---
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 tm=`# {{packageName}}
77
+ `;var om=`# {{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 rm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- Run the suite with `infra-kit e2e`: it sets `e2e.baseUrlEnv` from `infra-kit.config.ts` to this worktree's dev server when one serves `e2e.target`, else to the deployed URL `infra-kit env-load` loaded (or `e2e.cloud` at `INFRA_KIT_ENV`). Never hand-set that variable to reach a local server.\n- Never point a run at a production environment.\n";var nm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var om=`# {{packageName}}
98
+ `;var sm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- Run the suite with `infra-kit e2e`: it sets `e2e.baseUrlEnv` from `infra-kit.config.ts` to this worktree's dev server when one serves `e2e.target`, else to the deployed URL `infra-kit env-load` loaded (or `e2e.cloud` at `INFRA_KIT_ENV`). Never hand-set that variable to reach a local server.\n- Never point a run at a production environment.\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.\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@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";var im="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var am=`# {{packageName}}
99
99
 
100
100
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
101
101
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -117,7 +117,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
117
117
  - Changing that map is a breaking change for every dependent package.
118
118
  - Run \`pnpm run build\` before a dependent package can see a change.
119
119
  - No app-specific logic belongs here.
120
- `;var sm=`# {{packageName}}
120
+ `;var cm=`# {{packageName}}
121
121
 
122
122
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
123
123
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -139,39 +139,39 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
139
139
  - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
140
140
  - The web build feeds the native shell, so a device run needs a rebuild first.
141
141
  - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
142
- `;var im="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.\n- `ik dev [preset]` / `ik dev-status` \u2014 run this worktree's dev servers (a `devServersPresets` preset, or every app), or report what is running.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite against this worktree's dev server when one serves `e2e.target`, else against the deployed app at `INFRA_KIT_ENV` (the env-loaded `e2e.baseUrlEnv`, or `e2e.cloud`); `--dry-run` prints the target and proxy split. A cloud run previews and needs `--yes`.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.\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- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`) 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` and `vendor sync` are human-only and are 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";var Mr={"root/body":im.trimEnd(),"package/frontend":nm.trimEnd(),"package/backend":tm.trimEnd(),"package/lib":om.trimEnd(),"package/e2e":rm.trimEnd(),"package/mobile":sm.trimEnd(),"design/skeleton":em.trimEnd()};var Ma=/\{\{(\w+)\}\}/g,qv=/^- \{\{(\w+)\}\}$/,zv=e=>new Set([...e.matchAll(Ma)].map(t=>t[1])),Yv=(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(", ")}`)},Xv=(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(", ")}`)},Zv=(e,t)=>e.filter(r=>{let n=qv.exec(r);return n===null||t[n[1]]!==""}),Qv=(e,t)=>{for(let r of e)for(let n of r.matchAll(Ma)){let o=t[n[1]];if(o!==void 0&&o.includes(`
143
- `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},jr=(e,t)=>{let r=zv(e);Xv(r,t),Yv(r,t);let n=Zv(e.split(`
144
- `),t);return Qv(n,t),n.join(`
145
- `).replace(Ma,(o,s)=>t[s])};var ew="name: TODO",ja=e=>{let t=jr(Mr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(ew,()=>r)}
146
- `};var tw=(e,t)=>`${Xt}${e} ${t} -->`,rw="`README.md` \u2014 what this package is and how to run it.",Fa="docs/e2e-playwright.md",nw=`\`${Fa}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,La=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=jr(Mr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?rw:"",...r==="e2e"?{e2eDocBullet:i?nw:""}:{}});return[tw(t,r),"",a].join(`
147
- `)};var ow=e=>`${Ia}${e} -->`,Va=e=>{let t=jr(Mr["root/body"],{});return[ow(e),"",t].join(`
148
- `)};import Fr from"node:fs";import sw from"node:path";var bs=e=>{let t;try{t=Fr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Vn=(e,t)=>{bs(e);let r=Fr.existsSync(e)?Fr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(Fr.mkdirSync(sw.dirname(e),{recursive:!0}),Fr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Ba=(e,t,r)=>{let n=Fr.readFileSync(e,"utf-8");if(!ze(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},am=(e,t,r)=>ze(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Wa=(e,t,r,n)=>{let o=am(e,r,n),s=am(t,r,n);if(!(o===null||s===null)&&(o.before!==s.before||o.after!==s.after))throw new Error("Post-write validation failed: content outside the managed markers changed")};var Ps="<!-- infra-kit:import:begin -->",Ss="<!-- infra-kit:import:end -->",iw="AGENTS.md",cm="CLAUDE.md",aw="README.md",Ja="DESIGN.md",cw=["frontend","mobile"],lw=e=>er.existsSync(e)?er.readFileSync(e,"utf-8"):null,Ua=(e,t)=>{try{return er.readdirSync(e).includes(t)}catch{return!1}},Rs=(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},lm=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=lw(e),i=s===null?"":o?.(s)??s,a=Ir({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=Vn(e,a);return Ba(e,r,n),s!==null&&Wa(i,a,r,n),c},dw=e=>{if(!er.existsSync(e))return"unchanged";bs(e);let t=er.readFileSync(e,"utf-8"),r=At(t,Ae,Ye);return r===null?"unchanged":r.trim()===""?(er.rmSync(e),"removed"):Vn(e,r)},pw=(e,t)=>lm({filePath:e,body:Va(t),startMarker:Ae,endMarker:Ye,prepare:r=>At(r,Ps,Ss)??r}),Bn=async(e,{version:t})=>{let r=Ot.join(e,cm),n=Ot.join(e,iw),o=[];try{o.push({path:r,action:pw(r,t)})}catch(s){o.push(Rs(r,s))}try{o.push({path:n,action:dw(n)})}catch(s){o.push(Rs(n,s))}return o},uw=(e,t,r)=>{if(!cw.includes(r)||Ua(e,Ja))return null;let n=Ot.join(e,Ja);try{return{path:n,action:Vn(n,ja(t)),type:r}}catch(o){return Rs(n,o,r)}},Wn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Ot.join(e,cm),i=await zt(e),a=i.name??Ot.basename(e),c=Mn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=La({version:r,type:c,packageName:a,relDir:Ot.relative(t,e).split(Ot.sep).join("/"),hasReadme:Ua(e,aw),hasDesign:Ua(e,Ja),hasE2eDoc:er.existsSync(Ot.join(t,Fa))}),d=[];try{d.push({path:s,action:lm({filePath:s,body:l,startMarker:Xe,endMarker:lt}),type:c})}catch(u){d.push(Rs(s,u,c))}if(n){let u=uw(e,a,c);u&&d.push(u)}return d};import Pw from"node:path";import dm from"node:path";var Ga="agent-guidance",Jn="CLAUDE.md",mw="\u2014 run: infra-kit audit --fix",fw={missing:`${Jn} missing`,"no-block":`${Jn} has no infra-kit block (expected ${Xe} \u2026 ${lt})`,malformed:`${Jn} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Jn} carries the ROOT infra-kit block (${Ae}); a package needs the package block`},gw=e=>e.adopted?` (workspace adopted: ${dm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Ka=(e,t)=>{let r=Zt(Qt(dm.join(e,Jn)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ga,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${fw[r.state]} ${mw}`,o=r.state==="missing"?`${n}${gw(t)}`:n;return t.adopted?{name:Ga,status:"fail",message:o}:{name:Ga,status:"pass",message:`not yet adopted \u2014 ${o}`}};var Ha=async(e,t=$t)=>{try{let r=await jn(e,t);return{check:{name:Be,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:Be,status:"fail",message:r.message},rules:null}}};import hw from"node:fs/promises";import yw from"node:path";var Es="playwright.config.ts",vw=[{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'"}],pm=e=>Object.entries(Ta).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"}}),um=async e=>{let t=yw.join(e,Es),r=await hw.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${Es}`,status:"fail",message:`missing ${Es}`}]:vw.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${Es} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},qa=async(e,t)=>[...pm(t),...await um(e)];import ww from"node:fs/promises";import kw from"node:path";var za=async(e,t)=>Promise.all(t.map(async r=>{let n=await ww.stat(kw.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 Ya=(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 bw from"node:fs/promises";import Rw from"node:path";var Lr="turbo.json",Xa=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await bw.readFile(Rw.join(e,Lr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Lr,status:"fail",message:`cannot read/parse ${Lr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Lr,status:"fail",message:`no "tasks" object defined in ${Lr}`}]:t.map(o=>{let s=o in n||`//#${o}`in n;return{name:`turbo:${o}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${o}" in ${Lr}`}})};var Sw={adopted:!1,workspaceRoot:null},Ew=async(e,t,r)=>Mn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Yt(e)}),Za=async(e,t=$t,r={})=>{let n=await zt(e),o=n.name??Pw.basename(e),{check:s,rules:i}=await Ha(e,t),a=[s];r.isRoot||a.push(Ka(e,r.adoption??Sw)),i&&(a.push(...Ya(n.scripts??{},i.requiredScripts)),a.push(...await za(e,i.requiredFiles)),a.push(...await Xa(e,i.turboTasks))),!r.isRoot&&await Ew(e,n,r.repoRoot)==="e2e"&&a.push(...await qa(e,n.scripts??{}));let c=a.every(l=>l.status==="pass");return{packageDir:e,packageName:o,checks:a,passed:c}};var Qa=["plugin","marketplace","add",Et],ec=["plugin","install",H,"--scope","project"],mm=(e,t)=>qt({projectPath:e,home:t}).kind==="installed",tc=e=>((e??"").split(`
149
- `).find(r=>r.trim().length>0)??"").trim(),xw=(e,t)=>{if(Dn(t))return null;p.debug({msg:`Running: ${ps} ${Qa.join(" ")}`});let r=e({args:Qa});return r.ok?null:{step:"marketplace",error:tc(r.output)}},Tw=(e,t)=>{p.debug({msg:`Running: ${ps} ${us.join(" ")}`});let r=e({args:us,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:tc(r.output)}},rc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Ra;if(!n({args:ba}).ok)return{status:"claude-missing"};if(mm(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Tw(n,t);let o=xw(n,r);if(o!==null)return{status:"failed",...o};p.debug({msg:`Running: ${ps} ${ec.join(" ")}`});let s=n({args:ec,cwd:t});return s.ok?mm(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:tc(s.output)}};import Cw from"node:fs";import $w from"node:path";var Oe=".mcp.json",Ze="mcpServers",Aw="infra-kit",Ow=["mcp"],Dw="/infra-kit/dist/mcp.js",nc=" ",tr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),fm=e=>{if(!tr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Aw&&r[0]===Ow[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Dw)):!1},gm=e=>/\n([ \t]+)"/.exec(e)?.[1]??nc,oc=e=>{try{return{kind:"raw",raw:Cw.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},sc=e=>{try{return JSON.parse(e)}catch{return}},ic=e=>e instanceof Error?e.message:String(e),Un=e=>{let t=oc($w.join(e,Oe));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=sc(t.raw);if(!tr(r)||!tr(r[Ze]))return{kind:"unparseable"};let n=r[Ze];if(ae in n)return{kind:"stale"};let o=Object.keys(n).find(s=>fm(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import xs from"node:fs";import Iw from"node:path";var dt=`claude plugin install ${H} --scope project`,Vr=`claude plugin update ${H} --scope project`,ac=`claude plugin marketplace add ${Et}`,ym=" ",vm=()=>({source:{source:"github",repo:Et}}),Nw=()=>({extraKnownMarketplaces:{[ae]:vm()},enabledPlugins:{[H]:!0}}),wm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_w=e=>/\n([ \t]+)"/.exec(e)?.[1]??ym,hm=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!wm(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Mw=e=>[hm(e,"extraKnownMarketplaces",ae,vm()),hm(e,"enabledPlugins",H,!0)].filter(r=>r!==null),jw=e=>{try{return xs.readFileSync(e,"utf-8")}catch{return null}},Fw=e=>(xs.mkdirSync(Iw.dirname(e),{recursive:!0}),xs.writeFileSync(e,`${JSON.stringify(Nw(),null,ym)}
150
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ae}`,`enabledPlugins.${H}`]}),cc=e=>{let t=jw(e);if(t===null)return Fw(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!wm(r))return p.warn(`Could not parse ${e} \u2014 left it untouched. Add "${H}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Mw(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=_w(t),s=t.endsWith(`
142
+ `;var lm="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.\n- `ik dev [preset]` / `ik dev-status` \u2014 run this worktree's dev servers (a `devServersPresets` preset, or every app), or report what is running.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite against this worktree's dev server when one serves `e2e.target`, else against the deployed app at `INFRA_KIT_ENV` (the env-loaded `e2e.baseUrlEnv`, or `e2e.cloud`); `--dry-run` prints the target and proxy split. A cloud run previews and needs `--yes`.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.\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- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`) 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` and `vendor sync` are human-only and are refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root's `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n";var Mr={"root/body":lm.trimEnd(),"package/frontend":im.trimEnd(),"package/backend":om.trimEnd(),"package/lib":am.trimEnd(),"package/e2e":sm.trimEnd(),"package/mobile":cm.trimEnd(),"design/skeleton":nm.trimEnd()};var Fa=/\{\{(\w+)\}\}/g,Xv=/^- \{\{(\w+)\}\}$/,Zv=e=>new Set([...e.matchAll(Fa)].map(t=>t[1])),Qv=(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(", ")}`)},ew=(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(", ")}`)},tw=(e,t)=>e.filter(r=>{let n=Xv.exec(r);return n===null||t[n[1]]!==""}),rw=(e,t)=>{for(let r of e)for(let n of r.matchAll(Fa)){let o=t[n[1]];if(o!==void 0&&o.includes(`
143
+ `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},jr=(e,t)=>{let r=Zv(e);ew(r,t),Qv(r,t);let n=tw(e.split(`
144
+ `),t);return rw(n,t),n.join(`
145
+ `).replace(Fa,(o,s)=>t[s])};var nw="name: TODO",La=e=>{let t=jr(Mr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(nw,()=>r)}
146
+ `};var ow=(e,t)=>`${Xt}${e} ${t} -->`,sw="`README.md` \u2014 what this package is and how to run it.",Va="docs/e2e-playwright.md",iw=`\`${Va}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Ba=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=jr(Mr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?sw:"",...r==="e2e"?{e2eDocBullet:i?iw:""}:{}});return[ow(t,r),"",a].join(`
147
+ `)};var aw=e=>`${_a}${e} -->`,Wa=e=>{let t=jr(Mr["root/body"],{});return[aw(e),"",t].join(`
148
+ `)};import Fr from"node:fs";import cw from"node:path";var xs=e=>{let t;try{t=Fr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Un=(e,t)=>{xs(e);let r=Fr.existsSync(e)?Fr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(Fr.mkdirSync(cw.dirname(e),{recursive:!0}),Fr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Ja=(e,t,r)=>{let n=Fr.readFileSync(e,"utf-8");if(!ze(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},dm=(e,t,r)=>ze(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Ua=(e,t,r,n)=>{let o=dm(e,r,n),s=dm(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 Cs="<!-- infra-kit:import:begin -->",$s="<!-- infra-kit:import:end -->",lw="AGENTS.md",pm="CLAUDE.md",dw="README.md",Ga="DESIGN.md",pw=["frontend","mobile"],uw=e=>er.existsSync(e)?er.readFileSync(e,"utf-8"):null,Ka=(e,t)=>{try{return er.readdirSync(e).includes(t)}catch{return!1}},Ts=(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},um=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=uw(e),i=s===null?"":o?.(s)??s,a=Dr({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=Un(e,a);return Ja(e,r,n),s!==null&&Ua(i,a,r,n),c},mw=e=>{if(!er.existsSync(e))return"unchanged";xs(e);let t=er.readFileSync(e,"utf-8"),r=At(t,Ae,Ye);return r===null?"unchanged":r.trim()===""?(er.rmSync(e),"removed"):Un(e,r)},fw=(e,t)=>um({filePath:e,body:Wa(t),startMarker:Ae,endMarker:Ye,prepare:r=>At(r,Cs,$s)??r}),Gn=async(e,{version:t})=>{let r=Ot.join(e,pm),n=Ot.join(e,lw),o=[];try{o.push({path:r,action:fw(r,t)})}catch(s){o.push(Ts(r,s))}try{o.push({path:n,action:mw(n)})}catch(s){o.push(Ts(n,s))}return o},gw=(e,t,r)=>{if(!pw.includes(r)||Ka(e,Ga))return null;let n=Ot.join(e,Ga);try{return{path:n,action:Un(n,La(t)),type:r}}catch(o){return Ts(n,o,r)}},Kn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Ot.join(e,pm),i=await zt(e),a=i.name??Ot.basename(e),c=Vn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=Ba({version:r,type:c,packageName:a,relDir:Ot.relative(t,e).split(Ot.sep).join("/"),hasReadme:Ka(e,dw),hasDesign:Ka(e,Ga),hasE2eDoc:er.existsSync(Ot.join(t,Va))}),d=[];try{d.push({path:s,action:um({filePath:s,body:l,startMarker:Xe,endMarker:dt}),type:c})}catch(u){d.push(Ts(s,u,c))}if(n){let u=gw(e,a,c);u&&d.push(u)}return d};import xw from"node:path";import mm from"node:path";var Ha="agent-guidance",Hn="CLAUDE.md",hw="\u2014 run: infra-kit audit --fix",yw={missing:`${Hn} missing`,"no-block":`${Hn} has no infra-kit block (expected ${Xe} \u2026 ${dt})`,malformed:`${Hn} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Hn} carries the ROOT infra-kit block (${Ae}); a package needs the package block`},vw=e=>e.adopted?` (workspace adopted: ${mm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",qa=(e,t)=>{let r=Zt(Qt(mm.join(e,Hn)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ha,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${yw[r.state]} ${hw}`,o=r.state==="missing"?`${n}${vw(t)}`:n;return t.adopted?{name:Ha,status:"fail",message:o}:{name:Ha,status:"pass",message:`not yet adopted \u2014 ${o}`}};var za=async(e,t=$t)=>{try{let r=await Bn(e,t);return{check:{name:Be,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:Be,status:"fail",message:r.message},rules:null}}};import ww from"node:fs/promises";import kw from"node:path";var As="playwright.config.ts",bw=[{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'"}],fm=e=>Object.entries($a).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"}}),gm=async e=>{let t=kw.join(e,As),r=await ww.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${As}`,status:"fail",message:`missing ${As}`}]:bw.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${As} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},Ya=async(e,t)=>[...fm(t),...await gm(e)];import Rw from"node:fs/promises";import Sw from"node:path";var Xa=async(e,t)=>Promise.all(t.map(async r=>{let n=await Rw.stat(Sw.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 Za=(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 Pw from"node:fs/promises";import Ew from"node:path";var Lr="turbo.json",Qa=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await Pw.readFile(Ew.join(e,Lr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Lr,status:"fail",message:`cannot read/parse ${Lr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Lr,status:"fail",message:`no "tasks" object defined in ${Lr}`}]:t.map(o=>{let s=o in n||`//#${o}`in n;return{name:`turbo:${o}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${o}" in ${Lr}`}})};var Tw={adopted:!1,workspaceRoot:null},Cw=async(e,t,r)=>Vn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Yt(e)}),ec=async(e,t=$t,r={})=>{let n=await zt(e),o=n.name??xw.basename(e),{check:s,rules:i}=await za(e,t),a=[s];r.isRoot||a.push(qa(e,r.adoption??Tw)),i&&(a.push(...Za(n.scripts??{},i.requiredScripts)),a.push(...await Xa(e,i.requiredFiles)),a.push(...await Qa(e,i.turboTasks))),!r.isRoot&&await Cw(e,n,r.repoRoot)==="e2e"&&a.push(...await Ya(e,n.scripts??{}));let c=a.every(l=>l.status==="pass");return{packageDir:e,packageName:o,checks:a,passed:c}};var tc=["plugin","marketplace","add",Et],rc=["plugin","install",H,"--scope","project"],hm=(e,t)=>qt({projectPath:e,home:t}).kind==="installed",nc=e=>((e??"").split(`
149
+ `).find(r=>r.trim().length>0)??"").trim(),$w=(e,t)=>{if(Mn(t))return null;p.debug({msg:`Running: ${hs} ${tc.join(" ")}`});let r=e({args:tc});return r.ok?null:{step:"marketplace",error:nc(r.output)}},Aw=(e,t)=>{p.debug({msg:`Running: ${hs} ${ys.join(" ")}`});let r=e({args:ys,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:nc(r.output)}},oc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Pa;if(!n({args:Sa}).ok)return{status:"claude-missing"};if(hm(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Aw(n,t);let o=$w(n,r);if(o!==null)return{status:"failed",...o};p.debug({msg:`Running: ${hs} ${rc.join(" ")}`});let s=n({args:rc,cwd:t});return s.ok?hm(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:nc(s.output)}};import Ow from"node:fs";import Iw from"node:path";var Oe=".mcp.json",Ze="mcpServers",Dw="infra-kit",Nw=["mcp"],_w="/infra-kit/dist/mcp.js",sc=" ",tr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ym=e=>{if(!tr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Dw&&r[0]===Nw[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(_w)):!1},vm=e=>/\n([ \t]+)"/.exec(e)?.[1]??sc,ic=e=>{try{return{kind:"raw",raw:Ow.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},ac=e=>{try{return JSON.parse(e)}catch{return}},cc=e=>e instanceof Error?e.message:String(e),qn=e=>{let t=ic(Iw.join(e,Oe));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=ac(t.raw);if(!tr(r)||!tr(r[Ze]))return{kind:"unparseable"};let n=r[Ze];if(ae in n)return{kind:"stale"};let o=Object.keys(n).find(s=>ym(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Os from"node:fs";import Mw from"node:path";var pt=`claude plugin install ${H} --scope project`,Vr=`claude plugin update ${H} --scope project`,lc=`claude plugin marketplace add ${Et}`,km=" ",bm=()=>({source:{source:"github",repo:Et}}),jw=()=>({extraKnownMarketplaces:{[ae]:bm()},enabledPlugins:{[H]:!0}}),Rm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fw=e=>/\n([ \t]+)"/.exec(e)?.[1]??km,wm=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Rm(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Lw=e=>[wm(e,"extraKnownMarketplaces",ae,bm()),wm(e,"enabledPlugins",H,!0)].filter(r=>r!==null),Vw=e=>{try{return Os.readFileSync(e,"utf-8")}catch{return null}},Bw=e=>(Os.mkdirSync(Mw.dirname(e),{recursive:!0}),Os.writeFileSync(e,`${JSON.stringify(jw(),null,km)}
150
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ae}`,`enabledPlugins.${H}`]}),dc=e=>{let t=Vw(e);if(t===null)return Bw(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!Rm(r))return p.warn(`Could not parse ${e} \u2014 left it untouched. Add "${H}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Lw(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=Fw(t),s=t.endsWith(`
151
151
  `)?`
152
- `:"";return xs.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};var k=e=>[{type:"text",text:e}],R=e=>e;import Lw from"node:path";import Vw from"node:process";var Bw=["unchanged","created"],Ww=["unchanged","created","updated","removed","failed"],km=async(e,t,r)=>{let n=await Yt(e);return Wn(e,{repoRoot:t,version:q.version,design:r,declaredType:n})},Jw=async(e,t)=>{if(e.root)return Bn(t,{version:q.version});if(e.all){let n=[];for(let o of await ke(t))n.push(...await km(o,t,e.design));return n}let r=await Ln(e.cwd??Vw.cwd());return km(r,t,e.design)},Uw=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 ${Ww.filter(n=>Bw.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${q.version})`},Gw=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Lw.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";p.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}p.info(Uw(e))},Kw=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},bm=async(e,t)=>{let r=await S();ks();let n=await _r(t),o=await Jw(e,r);Gw(o,r),ks();let s=await _r(t),i=!e.all&&!e.root;return{fixed:o.map(Kw),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Pm from"node:fs";import Sm from"node:path";var lc="ik-mcp",Rm=(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:lc,args:r}};var Ts="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Hw=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),dc=e=>tr(e)&&e.command===lc,qw=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),zw=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Rm(i,a),l=e[i];if(l!==void 0&&!dc(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 ${Ts}, or drop mcp.${i} from infra-kit.json`});continue}if(dc(l)&&l.type===c.type&&Hw(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=qw(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: ${Ts}`:`"${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: ${Ts}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!dc(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}},Yw=(e,t,r)=>{let n=r===null?nc:gm(r),o=r===null||r.endsWith(`
152
+ `:"";return Os.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};var k=e=>[{type:"text",text:e}],R=e=>e;import Ww from"node:path";import Jw from"node:process";var Uw=["unchanged","created"],Gw=["unchanged","created","updated","removed","failed"],Sm=async(e,t,r)=>{let n=await Yt(e);return Kn(e,{repoRoot:t,version:q.version,design:r,declaredType:n})},Kw=async(e,t)=>{if(e.root)return Gn(t,{version:q.version});if(e.all){let n=[];for(let o of await ke(t))n.push(...await Sm(o,t,e.design));return n}let r=await Jn(e.cwd??Jw.cwd());return Sm(r,t,e.design)},Hw=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 ${Gw.filter(n=>Uw.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${q.version})`},qw=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Ww.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";p.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}p.info(Hw(e))},zw=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Pm=async(e,t)=>{let r=await x();Es();let n=await _r(t),o=await Kw(e,r);qw(o,r),Es();let s=await _r(t),i=!e.all&&!e.root;return{fixed:o.map(zw),adoptionFlipped:i&&!n.adopted&&s.adopted}};import xm from"node:fs";import Tm from"node:path";var pc="ik-mcp",Em=(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:pc,args:r}};var Is="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Yw=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),uc=e=>tr(e)&&e.command===pc,Xw=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Zw=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Em(i,a),l=e[i];if(l!==void 0&&!uc(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 ${Is}, or drop mcp.${i} from infra-kit.json`});continue}if(uc(l)&&l.type===c.type&&Yw(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Xw(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: ${Is}`:`"${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: ${Is}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!uc(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}},Qw=(e,t,r)=>{let n=r===null?sc:vm(r),o=r===null||r.endsWith(`
153
153
  `)?`
154
- `:"";try{return Pm.mkdirSync(Sm.dirname(e),{recursive:!0}),Pm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return p.warn(`Could not write ${e} (${ic(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Cs=({projectRoot:e,proxies:t,write:r})=>{let n=Sm.join(e,Oe),o=oc(n);if(o.kind==="unreadable")return p.warn(`Could not read ${n} (${ic(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:sc(s);if(!tr(i))return p.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ts}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Ze];if(a!==void 0&&!tr(a))return p.warn(`${n} has a "${Ze}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=zw(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Yw(n,{...i,[Ze]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Em=async(e,t)=>{let r;try{r=(await I()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Cs({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:o.length===0}};var Xw=(e,t)=>[...t.map(r=>({name:`devServersPresets:config:${r.app}`,status:"fail",message:`could not load apps/${r.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${r.message}`})),...e.map(r=>({name:`devServersPresets:${r.preset}`,status:"fail",message:r.message}))],xm=async e=>{let t=(await I()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Su(t);if(r.length>0){let d=r.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=Ru(e),o=Pu(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await xu(e,t,s,n),c=Xw(Eu(t,i),a),l=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:l,passed:c.length===0}};var Zw="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Qw=async e=>e.root?[{dir:await S(),baseline:Ca,isRoot:!0}]:e.all?(await ke(await S())).map(r=>({dir:r})):[{dir:await Ln(e.cwd??Tm.cwd())}],ek=async e=>e.root||e.all?await S():e.cwd??Tm.cwd(),tk=async()=>{try{return await S()}catch{return}},rk=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,p.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return p.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},nk=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await bm(e,t);return n&&p.info(Zw),r},ok=e=>{if(Un(e).kind!=="stale")return null;let t=`${Oe} still registers "${ae}" \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 "${ae}" entry by hand in a PR, keeping its siblings`;return p.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},$s=async(e={})=>{let t=_a(await ek(e)),r=e.fix?await nk(e,t):void 0,n=await Qw(e),o=await _r(t),s=await tk(),i=[];for(let l of n)i.push(await Za(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await xm(n[0].dir);l&&i.push(l);let d=await Em(n[0].dir,e.fix===!0);d&&i.push(d);let u=ok(n[0].dir);u&&i.push(u)}let c={allPassed:rk(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},sk={all:De.boolean().optional().describe("Audit every non-vendor workspace package"),root:De.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},ik={allPassed:De.boolean().describe("Whether every audited package passed all checks"),packages:De.array(De.object({name:De.string(),passed:De.boolean(),checks:De.array(De.object({name:De.string(),status:De.enum(["pass","fail"]),message:De.string()}))})).describe("Per-package check results")},pc=R({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:sk,outputSchema:ik,handler:e=>$s({all:e.all,root:e.root})});import{z as Gn}from"zod";var As=async()=>{let[e,t]=await Promise.all([I(),te()]),r=Object.keys(e).sort();p.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),p.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},ak={config:Gn.record(Gn.string(),Gn.unknown()).describe("The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, ide, worktrees, dev, devServersPresets, and protectedEnvs."),configPath:Gn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:Gn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},uc=R({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 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:{},outputSchema:ak,handler:()=>As()});import mk from"node:fs";import{z as ce}from"zod";import Kn from"node:fs";import Br from"node:path";import ck from"node:process";var lk=Br.join(".infra-kit","dev-context"),dk=".infra-kit",Cm=(e,t)=>{let r=Br.resolve(e);for(;;){let n=Br.join(r,t);if(Kn.existsSync(n))return n;let o=Br.dirname(r);if(o===r)return;r=o}},pk=e=>{let t=Cm(e,lk);if(t)return t;let r=Cm(e,dk);return r?Br.join(r,"dev-context"):void 0},mc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Os=e=>typeof e=="string"?e:"",uk=(e,t,r)=>{let n=Br.join(e,t);try{let o=Kn.statSync(n),s=JSON.parse(Kn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Os(i.package),port:mc(i.port),alias:Os(i.alias),origin:Os(i.origin),release:Os(i.release),pid:mc(i.pid),writtenAt:mc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},fc=(e=ck.cwd())=>{let t=Date.now(),r=pk(e);if(!r||!Kn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Kn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>uk(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 Ds=async(e={})=>{let t=e.now??Date.now,r=e.isListening??$n,n=fc(e.cwd),o=t(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),g=await r(u.port);return{app:u.app,package:u.package,port:u.port,pid:u.pid,alias:u.alias,origin:u.origin,release:u.release,writtenAt:u.writtenAt>0?new Date(u.writtenAt).toISOString():null,fragmentMtime:new Date(u.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(mk.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){p.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let u of s){let m=u.live?"live":"NOT responding",g=`written ${u.ageSeconds}s ago`;p.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${g}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";p.info(`No active infra-kit dev session \u2014 searched ${l} (${u}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},fk={active:ce.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:ce.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:ce.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:ce.array(ce.object({app:ce.string().describe("App folder name (the fragment filename without .json)."),package:ce.string().describe("The app package name the vite helper reads to decide a local route."),port:ce.number().describe("The actual bound port the dev server is listening on."),pid:ce.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ce.string().describe("Registered portless hostname for the app."),origin:ce.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ce.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ce.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:ce.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ce.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ce.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.")},gc=R({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:fk,handler:()=>Ds()});import{spawnSync as bg}from"node:child_process";import re from"node:fs";import Rg from"node:os";import pe from"node:path";import nt from"node:process";import{z as fe}from"zod";import{execFileSync as gk}from"node:child_process";var $m=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},hk=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],yk=e=>hk.some(t=>t.test(e)),vk="/bin/ps",wk=()=>gk(vk,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
155
- `),Am=(e=wk)=>{try{return e().some(yk)}catch{return!0}};import{Chalk as kk}from"chalk";import hc from"node:process";var yc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},bk=new Set(["warn","fail"]),Rk=24,Wr=" ",Om=" ",Pk=(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:[""]},Dm=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},Sk=e=>{let t=new kk({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)}},Im=(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),Ek=(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=Im(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}},xk=(e,t,r,n)=>{let o=Ek(Dm(e.rows),e.rows.length,t,r),s=Math.max(1,n-Wr.length-e.label.length-o.plainWidth);return`${Wr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},Tk=(e,t,r,n,o)=>{let s=bk.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=Om.length+i+1+t+2,u=Math.max(Rk,o-d),[m,...g]=Pk(e.message,u),y=" ".repeat(d),P=C=>s?C:r.dim(C);return[`${Om}${c(n[e.status])} ${l} ${P(m??"")}`.trimEnd(),...g.map(C=>`${y}${P(C)}`),...(e.notes??[]).map(C=>`${y}${C}`.trimEnd())]},Ck=(e,t,r,n,o)=>{let s=Dm(t),i=n.rule.repeat(Math.max(12,Math.min(o-Wr.length,56))),a=Im(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Wr}${r.dim(i)}`,`${Wr}${c}${l.join("")}`]},vc=(e,t={})=>{let r=t.width??80,n=Sk(t.color??!1),o=t.unicode??!0?yc.unicode:yc.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Wr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[xk(d,n,o,r),...d.rows.flatMap(u=>Tk(u,c,n,o,r)),""]);return[a,"",...l,...Ck(e,i,n,o,r)]},$k=new Set(["","0","false","none"]),Ak=["LC_ALL","LC_CTYPE","LANG"],Ok=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!$k.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,Dk=(e,t)=>{if(t)return!1;let r=Ak.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},wc=(e={})=>{let t=e.env??hc.env,r=e.stream??hc.stderr;return{color:Ok(t,r),unicode:Dk(t,e.ascii??!1),width:r.columns??80}},Dt=(e,t={})=>{(t.write??(n=>{hc.stderr.write(n)}))(`${vc(e,wc(t)).join(`
154
+ `:"";try{return xm.mkdirSync(Tm.dirname(e),{recursive:!0}),xm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return p.warn(`Could not write ${e} (${cc(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Ds=({projectRoot:e,proxies:t,write:r})=>{let n=Tm.join(e,Oe),o=ic(n);if(o.kind==="unreadable")return p.warn(`Could not read ${n} (${cc(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:ac(s);if(!tr(i))return p.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Is}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Ze];if(a!==void 0&&!tr(a))return p.warn(`${n} has a "${Ze}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Zw(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Qw(n,{...i,[Ze]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Cm=async(e,t)=>{let r;try{r=(await D()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Ds({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:o.length===0}};var ek=(e,t)=>[...t.map(r=>({name:`devServersPresets:config:${r.app}`,status:"fail",message:`could not load apps/${r.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${r.message}`})),...e.map(r=>({name:`devServersPresets:${r.preset}`,status:"fail",message:r.message}))],$m=async e=>{let t=(await D()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Tu(t);if(r.length>0){let d=r.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=Eu(e),o=xu(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await $u(e,t,s,n),c=ek(Cu(t,i),a),l=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:l,passed:c.length===0}};var tk="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",rk=async e=>e.root?[{dir:await x(),baseline:Aa,isRoot:!0}]:e.all?(await ke(await x())).map(r=>({dir:r})):[{dir:await Jn(e.cwd??Am.cwd())}],nk=async e=>e.root||e.all?await x():e.cwd??Am.cwd(),ok=async()=>{try{return await x()}catch{return}},sk=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,p.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return p.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},ik=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Pm(e,t);return n&&p.info(tk),r},ak=e=>{if(qn(e).kind!=="stale")return null;let t=`${Oe} still registers "${ae}" \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 "${ae}" entry by hand in a PR, keeping its siblings`;return p.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Ns=async(e={})=>{let t=ja(await nk(e)),r=e.fix?await ik(e,t):void 0,n=await rk(e),o=await _r(t),s=await ok(),i=[];for(let l of n)i.push(await ec(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await $m(n[0].dir);l&&i.push(l);let d=await Cm(n[0].dir,e.fix===!0);d&&i.push(d);let u=ak(n[0].dir);u&&i.push(u)}let c={allPassed:sk(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},ck={all:Ie.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ie.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},lk={allPassed:Ie.boolean().describe("Whether every audited package passed all checks"),packages:Ie.array(Ie.object({name:Ie.string(),passed:Ie.boolean(),checks:Ie.array(Ie.object({name:Ie.string(),status:Ie.enum(["pass","fail"]),message:Ie.string()}))})).describe("Per-package check results")},mc=R({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:ck,outputSchema:lk,handler:e=>Ns({all:e.all,root:e.root})});import{z as zn}from"zod";var _s=async()=>{let[e,t]=await Promise.all([D(),te()]),r=Object.keys(e).sort();p.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),p.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},dk={config:zn.record(zn.string(),zn.unknown()).describe("The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, ide, worktrees, dev, devServersPresets, and protectedEnvs."),configPath:zn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:zn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},fc=R({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 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:{},outputSchema:dk,handler:()=>_s()});import hk from"node:fs";import{z as ce}from"zod";import Yn from"node:fs";import Br from"node:path";import pk from"node:process";var uk=Br.join(".infra-kit","dev-context"),mk=".infra-kit",Om=(e,t)=>{let r=Br.resolve(e);for(;;){let n=Br.join(r,t);if(Yn.existsSync(n))return n;let o=Br.dirname(r);if(o===r)return;r=o}},fk=e=>{let t=Om(e,uk);if(t)return t;let r=Om(e,mk);return r?Br.join(r,"dev-context"):void 0},gc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Ms=e=>typeof e=="string"?e:"",gk=(e,t,r)=>{let n=Br.join(e,t);try{let o=Yn.statSync(n),s=JSON.parse(Yn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Ms(i.package),port:gc(i.port),alias:Ms(i.alias),origin:Ms(i.origin),release:Ms(i.release),pid:gc(i.pid),writtenAt:gc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},hc=(e=pk.cwd())=>{let t=Date.now(),r=fk(e);if(!r||!Yn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Yn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>gk(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 js=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Dn,n=hc(e.cwd),o=t(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),g=await r(u.port);return{app:u.app,package:u.package,port:u.port,pid:u.pid,alias:u.alias,origin:u.origin,release:u.release,writtenAt:u.writtenAt>0?new Date(u.writtenAt).toISOString():null,fragmentMtime:new Date(u.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(hk.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){p.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let u of s){let m=u.live?"live":"NOT responding",g=`written ${u.ageSeconds}s ago`;p.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${g}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";p.info(`No active infra-kit dev session \u2014 searched ${l} (${u}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},yk={active:ce.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:ce.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:ce.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:ce.array(ce.object({app:ce.string().describe("App folder name (the fragment filename without .json)."),package:ce.string().describe("The app package name the vite helper reads to decide a local route."),port:ce.number().describe("The actual bound port the dev server is listening on."),pid:ce.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ce.string().describe("Registered portless hostname for the app."),origin:ce.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ce.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ce.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:ce.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ce.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ce.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.")},yc=R({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:yk,handler:()=>js()});import{spawnSync as Sg}from"node:child_process";import re from"node:fs";import Pg from"node:os";import pe from"node:path";import ot from"node:process";import{z as fe}from"zod";import{execFileSync as vk}from"node:child_process";var Im=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},wk=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],kk=e=>wk.some(t=>t.test(e)),bk="/bin/ps",Rk=()=>vk(bk,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
155
+ `),Dm=(e=Rk)=>{try{return e().some(kk)}catch{return!0}};import{Chalk as Sk}from"chalk";import vc from"node:process";var wc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},Pk=new Set(["warn","fail"]),Ek=24,Wr=" ",Nm=" ",xk=(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:[""]},_m=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},Tk=e=>{let t=new Sk({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)}},Mm=(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),Ck=(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=Mm(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}},$k=(e,t,r,n)=>{let o=Ck(_m(e.rows),e.rows.length,t,r),s=Math.max(1,n-Wr.length-e.label.length-o.plainWidth);return`${Wr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},Ak=(e,t,r,n,o)=>{let s=Pk.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=Nm.length+i+1+t+2,u=Math.max(Ek,o-d),[m,...g]=xk(e.message,u),y=" ".repeat(d),S=C=>s?C:r.dim(C);return[`${Nm}${c(n[e.status])} ${l} ${S(m??"")}`.trimEnd(),...g.map(C=>`${y}${S(C)}`),...(e.notes??[]).map(C=>`${y}${C}`.trimEnd())]},Ok=(e,t,r,n,o)=>{let s=_m(t),i=n.rule.repeat(Math.max(12,Math.min(o-Wr.length,56))),a=Mm(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Wr}${r.dim(i)}`,`${Wr}${c}${l.join("")}`]},kc=(e,t={})=>{let r=t.width??80,n=Tk(t.color??!1),o=t.unicode??!0?wc.unicode:wc.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Wr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[$k(d,n,o,r),...d.rows.flatMap(u=>Ak(u,c,n,o,r)),""]);return[a,"",...l,...Ok(e,i,n,o,r)]},Ik=new Set(["","0","false","none"]),Dk=["LC_ALL","LC_CTYPE","LANG"],Nk=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Ik.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,_k=(e,t)=>{if(t)return!1;let r=Dk.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},bc=(e={})=>{let t=e.env??vc.env,r=e.stream??vc.stderr;return{color:Nk(t,r),unicode:_k(t,e.ascii??!1),width:r.columns??80}},It=(e,t={})=>{(t.write??(n=>{vc.stderr.write(n)}))(`${kc(e,bc(t)).join(`
156
156
  `)}
157
- `)};var Ik="Tools & CLIs",Nk="Shell & integration",_k="Project config",Mk="Doppler env tokens",jk="Dev proxy (portless)",Fk="Claude Code plugin",Lk=`portless serving TLS on :${xt}`,kc=[[Ik,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Nk,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[_k,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Mk,["tokens.json present","env tokens configured","tokens.json perms"]],[jk,["portless installed","portless node","portless service target",Lk,"portless CA chain valid","portless CA trusted","portless routes"]],[Fk,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","Agent mode","Agent allowlist"]]],Nm="Other",Vk=kc.map(([e])=>e),Bk=new Map(kc.flatMap(([e,t])=>t.map(r=>[r,e]))),yM=kc.flatMap(([,e])=>e),bc=new Set(["portless routes","tokens.json perms"]),Wk=e=>{let t=new Map;for(let n of e){let o=Bk.get(n.name)??Nm,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Vk,Nm].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Jk=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return qe(e)}},Uk=e=>{let t=e.filter(r=>r.status==="fail"&&bc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Wk(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Jk(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Rc=(e,t={})=>{Dt(Uk(e),t)};var Gk=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),Kk=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>Gk(t[1])),Hk=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Kk(t[1])},qk=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},zk=e=>{let t=e.split(`
158
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:qk(t.slice(10))},_m=(e,t)=>{try{return e==="darwin"?Hk(t):e==="linux"?zk(t):null}catch{return null}};import{Buffer as tf}from"node:buffer";import Re from"node:fs/promises";import ft from"node:path";import rf from"node:process";import{$ as Ws}from"zx";import Yk from"node:process";var Hn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Mm=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(ie())throw new x({status:"argument_required",argument:e,agentMode:A.source},2,t);if(!Yk.stdin.isTTY)throw new f(void 0,t)},It=async e=>{Mm("version");let{runBranchPicker:t}=await import("./boot-XLDVLQEG.js"),r=await t(e);if(r===null)throw new Hn;return r},Nt=async(e,t)=>{Mm("versions");let{runBranchMultiPicker:r}=await import("./boot-XLDVLQEG.js"),n=await r(e,t);if(n===null)throw new Hn;return n};import{$ as Jm}from"zx";import{$ as CM}from"zx";import{$ as Ur}from"zx";import{$ as jm}from"zx";var Pc=async e=>{let{operation:t}=e;try{await jm({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await jm({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},Zk=4,Jr=async e=>{let{operation:t}=e,r=await iu();if(r.length===0)return;p.error(`working tree has uncommitted changes:
157
+ `)};var Mk="Tools & CLIs",jk="Shell & integration",Fk="Project config",Lk="Doppler env tokens",Vk="Dev proxy (portless)",Bk="Claude Code plugin",Wk=`portless serving TLS on :${xt}`,Rc=[[Mk,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[jk,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Fk,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Lk,["tokens.json present","env tokens configured","tokens.json perms"]],[Vk,["portless installed","portless node","portless service target",Wk,"portless CA chain valid","portless CA trusted","portless routes"]],[Bk,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","Agent mode","Agent allowlist"]]],jm="Other",Jk=Rc.map(([e])=>e),Uk=new Map(Rc.flatMap(([e,t])=>t.map(r=>[r,e]))),TM=Rc.flatMap(([,e])=>e),Sc=new Set(["portless routes","tokens.json perms"]),Gk=e=>{let t=new Map;for(let n of e){let o=Uk.get(n.name)??jm,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Jk,jm].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Kk=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return qe(e)}},Hk=e=>{let t=e.filter(r=>r.status==="fail"&&Sc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Gk(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Kk(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Pc=(e,t={})=>{It(Hk(e),t)};var qk=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),zk=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>qk(t[1])),Yk=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:zk(t[1])},Xk=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},Zk=e=>{let t=e.split(`
158
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:Xk(t.slice(10))},Fm=(e,t)=>{try{return e==="darwin"?Yk(t):e==="linux"?Zk(t):null}catch{return null}};import{Buffer as of}from"node:buffer";import Re from"node:fs/promises";import et from"node:path";import sf from"node:process";import{$ as qs}from"zx";import Qk from"node:process";var Xn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Lm=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(ie())throw new E({status:"argument_required",argument:e,agentMode:A.source},2,t);if(!Qk.stdin.isTTY)throw new f(void 0,t)},Dt=async e=>{Lm("version");let{runBranchPicker:t}=await import("./boot-XLDVLQEG.js"),r=await t(e);if(r===null)throw new Xn;return r},Nt=async(e,t)=>{Lm("versions");let{runBranchMultiPicker:r}=await import("./boot-XLDVLQEG.js"),n=await r(e,t);if(n===null)throw new Xn;return n};import{$ as Km}from"zx";import{$ as FM}from"zx";import{$ as Ur}from"zx";import{$ as Vm}from"zx";var Ec=async e=>{let{operation:t}=e;try{await Vm({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await Vm({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},tb=4,Jr=async e=>{let{operation:t}=e,r=await cu();if(r.length===0)return;p.error(`working tree has uncommitted changes:
159
159
  ${r.join(`
160
- `)}`);let n=r.slice(0,Zk),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},qn=async e=>{let{operation:t,base:r}=e;if(await Ar()===r)return;let n=(await St(await S())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},be=async e=>{let{operation:t}=e;if(await cu())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await Jr({operation:t})};var Qk=e=>e.map(t=>({pr:t,id:K(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>su(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),zn=200,Fm=(e,t)=>{e.length<zn||p.warn({source:t,limit:zn},`\u26A0\uFE0F ${t} returned ${zn} PRs \u2014 the page is full, so older release PRs may be missing`)},eb=async()=>{let[e,t]=await Promise.all([Ur`gh pr list --limit ${zn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Ur`gh pr list --limit ${zn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Fm(r,"release PR discovery (base dev)"),Fm(n,"hotfix PR discovery (base main)");let o=new Set(r.map(c=>c.headRefName)),s=new Set(n.filter(c=>o.has(c.headRefName)).map(c=>c.headRefName)),i=[...n,...r],a=new Set;return i.filter(c=>a.has(c.headRefName)?!1:(a.add(c.headRefName),!0)).map(c=>({...c,dualBase:s.has(c.headRefName)}))},Yn="find open release PRs",Lm=async()=>{try{let e=await eb();if(e.length===0)throw new f(void 0,{operation:Yn,remediation:"open a release PR first, or check you are in the right repo"});return Qk(e)}catch(e){throw e instanceof f?e:(p.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Is=async()=>(await Lm()).map(t=>t.headRefName),tb=e=>{let t=Xn(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Sc(e.title)!==t;return(r||e.dualBase)&&p.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await Lm()).map(tb),Ns=async e=>{let{branch:t,body:r}=e;try{await Ur({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw p.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},rb=async(e,t)=>{let r=Ur({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){p.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&&p.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},_s=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=ou(t,n),a=Qe(n),c=Ur({quiet:!0}),l=Te(t),d=Zn(r,o);try{await Jr({operation:`create release branch ${l}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${u.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await rb(l,a),m}}catch(u){throw p.error({error:u,branchName:l},`Error creating release branch ${l}`),u}finally{await Ur({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Ec}from"zx";var Gr=async e=>{let t=await Ec`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},xc=async e=>{let t=await Ec`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Tc=async e=>{try{let t=await Ec`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import eo from"node:process";var nb="x-seraph-loginreason",ob="AUTHENTICATED_FAILED",sb=(e,t=160)=>{let r=e.split(`
161
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Bm=(e,t)=>t===ob||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Vm=(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}`,Kr=class extends Error{status;kind;body;context;constructor(t){let r=Bm(t.status,t.seraphLoginReason),n=sb(t.body);super(n===""?`${t.context}: ${Vm(r,t.status)}`:`${t.context}: ${Vm(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Qn=e=>e instanceof Kr,Wm=e=>e.headers.get(nb);var Hr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Kr({status:e.status,seraphLoginReason:Wm(e),body:r,context:t});throw p.debug({status:e.status,kind:n.kind,body:r},t),n},rr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Cc=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 Hr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},qr=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 Hr(a,"Failed to get Jira project versions"),await a.json()},pt=async(e,t)=>(await qr(t)).find(o=>o.name===e)||null,zr=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await Hr(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}},$c=async(e,t)=>{let{versionName:r}=e,n=await pt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await zr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Yr=async()=>{let e=eo.env.JIRA_BASE_URL,t=eo.env.JIRA_TOKEN||eo.env.JIRA_API_TOKEN,r=eo.env.JIRA_PROJECT_ID,n=eo.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(`
162
- `);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 Yr()}catch(e){return p.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Ms=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 Hr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Ac=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 Hr(c,"Failed to remove Jira version")};var Um="dev",Gm={regular:"dev",hotfix:"main"},Qe=e=>Gm[e],Xn=e=>{let t=Object.entries(Gm).find(([,r])=>r===e);return t?t[0]:null},Zn=(e,t)=>(t??"").trim()!==""?`${e}
160
+ `)}`);let n=r.slice(0,tb),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},Zn=async e=>{let{operation:t,base:r}=e;if(await Ar()===r)return;let n=(await Pt(await x())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},be=async e=>{let{operation:t}=e;if(await du())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await Jr({operation:t})};var rb=e=>e.map(t=>({pr:t,id:K(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>au(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Qn=200,Bm=(e,t)=>{e.length<Qn||p.warn({source:t,limit:Qn},`\u26A0\uFE0F ${t} returned ${Qn} PRs \u2014 the page is full, so older release PRs may be missing`)},nb=async()=>{let[e,t]=await Promise.all([Ur`gh pr list --limit ${Qn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Ur`gh pr list --limit ${Qn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Bm(r,"release PR discovery (base dev)"),Bm(n,"hotfix PR discovery (base main)");let o=new Set(r.map(c=>c.headRefName)),s=new Set(n.filter(c=>o.has(c.headRefName)).map(c=>c.headRefName)),i=[...n,...r],a=new Set;return i.filter(c=>a.has(c.headRefName)?!1:(a.add(c.headRefName),!0)).map(c=>({...c,dualBase:s.has(c.headRefName)}))},eo="find open release PRs",Wm=async()=>{try{let e=await nb();if(e.length===0)throw new f(void 0,{operation:eo,remediation:"open a release PR first, or check you are in the right repo"});return rb(e)}catch(e){throw e instanceof f?e:(p.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Fs=async()=>(await Wm()).map(t=>t.headRefName),ob=e=>{let t=to(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=xc(e.title)!==t;return(r||e.dualBase)&&p.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await Wm()).map(ob),Ls=async e=>{let{branch:t,body:r}=e;try{await Ur({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw p.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},sb=async(e,t)=>{let r=Ur({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){p.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&&p.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Vs=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=iu(t,n),a=Qe(n),c=Ur({quiet:!0}),l=Te(t),d=ro(r,o);try{await Jr({operation:`create release branch ${l}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${u.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await sb(l,a),m}}catch(u){throw p.error({error:u,branchName:l},`Error creating release branch ${l}`),u}finally{await Ur({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Tc}from"zx";var Gr=async e=>{let t=await Tc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Cc=async e=>{let t=await Tc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},$c=async e=>{try{let t=await Tc`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import oo from"node:process";var ib="x-seraph-loginreason",ab="AUTHENTICATED_FAILED",cb=(e,t=160)=>{let r=e.split(`
161
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Um=(e,t)=>t===ab||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Jm=(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}`,Kr=class extends Error{status;kind;body;context;constructor(t){let r=Um(t.status,t.seraphLoginReason),n=cb(t.body);super(n===""?`${t.context}: ${Jm(r,t.status)}`:`${t.context}: ${Jm(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},no=e=>e instanceof Kr,Gm=e=>e.headers.get(ib);var Hr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Kr({status:e.status,seraphLoginReason:Gm(e),body:r,context:t});throw p.debug({status:e.status,kind:n.kind,body:r},t),n},rr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Ac=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 Hr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},qr=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 Hr(a,"Failed to get Jira project versions"),await a.json()},ut=async(e,t)=>(await qr(t)).find(o=>o.name===e)||null,zr=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await Hr(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}},Oc=async(e,t)=>{let{versionName:r}=e,n=await ut(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await zr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Yr=async()=>{let e=oo.env.JIRA_BASE_URL,t=oo.env.JIRA_TOKEN||oo.env.JIRA_API_TOKEN,r=oo.env.JIRA_PROJECT_ID,n=oo.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
162
+ `);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}},mt=async()=>{try{return await Yr()}catch(e){return p.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Bs=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 Hr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Ic=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 Hr(c,"Failed to remove Jira version")};var Hm="dev",qm={regular:"dev",hotfix:"main"},Qe=e=>qm[e],to=e=>{let t=Object.entries(qm).find(([,r])=>r===e);return t?t[0]:null},ro=(e,t)=>(t??"").trim()!==""?`${e}
163
163
 
164
164
  ${t}`:`${e}
165
- `,Oc=async(e="regular")=>{let t=Qe(e),r=Jm({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 Jm({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},ib=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await pt(t,r);if(!s)return(await Cc({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await zr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Dc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ne(t),c=await ib({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=rr(r,c),d=await _s({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:Y(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},js=async()=>{let e=new Map,t=await ut();if(!t)return e;try{let r=await qr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){p.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},oe=async()=>{let e=await js();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},to=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Sc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Fs=e=>e.flatMap(t=>{let r=K(t);return r?[{branch:t,id:r,label:Y(r)}]:[]}),mt=e=>{try{return Te(ve(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},ro=e=>{if(e===Um)return Um;let t=K(e);return t?Y(t):e},nr=e=>e.flatMap(t=>{let r=K(t);return r?[Y(r)]:[]}),ab=(e,t)=>t?t.get(e)||"regular":void 0,se=e=>{let{branches:t,descriptions:r,types:n}=e;return Fs(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ne(s)),type:ab(o,n)}))};import Km from"node:fs/promises";import cb from"node:path";import{$ as Ic}from"zx";var L="pnpm-lock.yaml",lb=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,qm=async(e,t)=>{let r=cb.join(e,L),n=`${t}:${L}`;try{let o=await Ic({cwd:e,quiet:!0})`git show ${n}`;await Km.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${L} to start from: ${Hm(o)}`}}try{await Ic({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${L}: ${Hm(o)}`}}return lb.test(await Km.readFile(r,"utf8"))?{ok:!1,reason:`${L} still carries conflict markers after pnpm ran`}:(await Ic({cwd:e,quiet:!0})`git add -- ${L}`,{ok:!0})},Hm=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as or}from"zx";var Nc="Merge remote-tracking branch 'origin/dev' into ",zm=e=>String(e.stderr??e.message??e).trim(),db=async e=>{try{return(await or({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
166
- `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},pb=async(e,t)=>{let r=zm(t),n=await db(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await uu(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Ym=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await $e(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await ub({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},ub=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await $e(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await On(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await wa(r),await or({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Nc}${n}`;await or({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await or({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:a===o?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:n,...await pb(r,i)}}finally{await ka(r)}},Xm=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Zm="pnpm install --frozen-lockfile",Qm=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await wa(t),await or({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await or({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,zm(a))}finally{await ka(t)}return{kept:o,failed:s}},no=async(e,t,r="origin/dev")=>{await or({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await On(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import _c from"node:process";var Ls=new Set,Vs=e=>(Ls.add(e),()=>{Ls.delete(e)}),mb=async()=>{for(let e of[...Ls])try{await e()}catch(t){p.warn({error:t,msg:"cleanup failed during shutdown"})}Ls.clear()},fb=["SIGINT","SIGTERM"],ef=async(e,t={})=>{let{register:r=(i,a)=>{_c.on(i,a)},unregister:n=(i,a)=>{_c.off(i,a)},exit:o=i=>{_c.exit(i)}}=t,s=new Map;for(let i of fb){let a=()=>{mb().then(()=>{o(Du(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var nf="pnpm install --frozen-lockfile --ignore-scripts",of=64*1024,df=4096,so=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-df)},N=async(e,t)=>(await Ws({cwd:e,quiet:!0})`git ${t}`).stdout,Mc=e=>e.split(`
167
- `).map(t=>t.trim()).filter(t=>t.length>0),Js=e=>e.split("\0").filter(t=>t.length>0),Bs=async(e,t)=>{try{return(await N(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},pf=async e=>ft.resolve(e,(await N(e,["rev-parse","--git-common-dir"])).trim()),jc=e=>e.then(()=>!0,()=>!1),oo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Fc=e=>e?.length===1&&e[0]===L,uf=async e=>ft.join(await pf(e),"infra-kit","merge-dev-resolutions"),Lc=async(e,t)=>ft.join(await uf(e),`${du(t)}.json`),mf=async e=>{try{return JSON.parse(await Re.readFile(e,"utf8"))}catch{return null}},Us=async(e,t)=>{let r=await Lc(e,t.branch);await Re.mkdir(ft.dirname(r),{recursive:!0}),await Re.writeFile(r,`${JSON.stringify(t,null,2)}
168
- `)},ff=async e=>{let t=await uf(e),r=await Re.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>mf(ft.join(t,o))))).filter(o=>o!==null)},gf=async e=>Promise.all((await ff(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await jc(Re.stat(t.worktreePath))}))),sf=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),Vc=async(e,t,r)=>{await N(e,["worktree","remove","--force",r]).catch(()=>Re.rm(r,{recursive:!0,force:!0})),await Re.rm(await Lc(e,t),{force:!0}).catch(()=>{}),await N(e,["worktree","prune"]).catch(()=>{})},hf=async e=>Js(await N(e,["diff","--name-only","-z","--diff-filter=U"])),yf=async e=>Js(await N(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),gb=async(e,t)=>{let r=(await N(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await jc(Re.stat(ft.join(await pf(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Mc(await N(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},hb=e=>e.split("/").includes("node_modules"),Gs=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set(t.ignoredAtHandoff),o=Js(await N(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await yb(e),...o].filter(a=>!r.has(a)),i=(await yf(e)).filter(a=>!n.has(a)&&!hb(a));return[...new Set([...s,...i,...await vb(e)])].sort()},yb=async e=>{let t=Js(await N(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},vb=async e=>(await N(e,["ls-files","-v"])).split(`
169
- `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),wb=async e=>{let t=`:(exclude)${L}`;try{return await N(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
170
- `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},kb=async(e,t)=>{let r=[];for(let n of t)(await jc(Re.lstat(ft.join(e,n)))||(await N(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await N(e,["--literal-pathspecs","add","-A","--",...r])},af=async e=>(await N(e,["write-tree"])).trim(),vf=async e=>(await N(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),bb=async(e,t)=>{let r=t?`${nf} && ${t}`:nf;try{return await Ws({cwd:e,quiet:!0})`sh -c ${r}`,{command:r,ok:!0}}catch(n){return{command:r,ok:!1,reason:so(n)}}},wf=async(e,t)=>{let r=(await N(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await N(e,["diff","--cached","--stat",l,"--",L])).trim(),o=t.conflictPaths.includes(L)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await N(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${L}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
171
- ${l}`:l}).join(""),c=tf.byteLength(a)>of;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?tf.from(a).subarray(0,of).toString():a,resolutionDiffTruncated:c}},kf=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await Rb(t,s,n));return o},Rb=async(e,t,r)=>{let n=await mf(await Lc(e,t));if(n)return{resolution:sf(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await $e(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=pu(e,t),i=()=>Vc(e,t,s),a=Vs(i);try{await N(e,["worktree","prune"]),await Re.mkdir(ft.dirname(s),{recursive:!0}),await N(e,["worktree","add","--detach",s,o]),await Ws({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${Nc+t}`.catch(()=>{});let c=await hf(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await Bs(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await N(e,["--version"])).trim()})`};let d=await gb(s,c),u=Fc(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await yf(s),lockfileOnly:u,cliVersion:q.version,createdAt:new Date().toISOString()};return await Us(e,m),{resolution:sf(m,u?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:so(c)}}finally{a()}},bf=async e=>{let{cwd:t,versions:r,all:n}=e,o=await ff(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=Te(ve(c)),d=o.find(u=>u.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await Nt(se({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},Pb=async(e,t)=>{let r=await Re.realpath(t).catch(()=>null);if(!r)return!1;let n=await St(e);for(let o of n)if(await Re.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Xr=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Rf=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 Pb(e,n))return Xr(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Bs(n,"HEAD"),i=await Bs(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?Tb(e,t,o,r):Sb(t,o,s,i)},Sb=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Xr(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 vf(o),i=n?null:await Bs(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 Xr(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Gs(o,e);return c.length>0?Xr(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(L),...await wf(o,e)}},cf=async(e,t)=>{let r=Mc(await N(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},Eb=async(e,t)=>{let r=t.worktreePath,n=await cf(r,L),o=t.lockfileBlob,s=await qm(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[L]};let i=await cf(r,L);if(i!==null&&i!==o&&(t.lockfileBlob=i,await Us(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${L} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[L]}:{code:"out-of-scope-edit",detail:`${L} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[L]};let a=await Gs(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},xb=async(e,t)=>{let r=t.worktreePath;await kb(r,t.conflictPaths.filter(i=>i!==L));let n=await Gs(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await hf(r)).filter(i=>i!==L);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await wb(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${so(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(L)?Eb(e,t):null},Tb=async(e,t,r,n)=>{let o=t.worktreePath,s=await xb(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(L),a=await af(o),c=await bb(o,n),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Xr(l,"verify-failed",c.reason??"the verify command failed");let d=await Gs(o,t),u=Mc(await N(o,["diff","--name-only"]));return d.length>0||u.length>0||await af(o)!==a?Xr(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...u])]):{...l,...await wf(o,t)}},Cb=12e4,$b=async(e,t=Cb)=>{let r=Ws({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...rf.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&rf.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:so(s)};let i=(await N(e,["rev-parse","--git-path","index.lock"])).trim();return await Re.rm(ft.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},Ab={"verify-failed":"verify-failed","tree-changed":"tree-changed"},Ob=e=>{let t=e.blocked;return{branch:e.branch,status:Ab[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},Db=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,u,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:u,...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 $b(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await N(o,["rev-parse","HEAD"])).trim(),c=(await N(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await Us(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 vf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},Ib=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await no(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${so(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await $e(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await On(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)},Nb=e=>{p.info(`
172
- \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?p.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):p.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Pf=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await bf({cwd:t,versions:r,all:n});if(a.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),oo();if(i)return lf(t,a,o,s);let c=[];for(let m of a){let g=await Rf(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await Us(t,m)),c.push(g)}Nb(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new x({status:"refused",plan:l,agentMode:A.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 u=new Map(d.map(m=>[m.branch,m.treeSha]));try{await W(i,`Commit and push the resolved merges for: ${[...u.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:_b(u)})}catch(m){if(!at(m))throw m;return{...oo(),declined:!0}}return lf(t,a,o,u)},Sf=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},_b=e=>{let t=[],r=!1;for(let o of Cu())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"]},Mb=async(e,t,r,n)=>{let o=await Rf(e,t,r);if(o.blocked)return Ob(o);let s=await Db(e,o,t,n);if(!("sha"in s))return s;let i=await Ib(e,t,s.sha);return i==="keep"?s:i},jb=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}));p.info(`
173
- \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await ds(e,r),o=[];for(let s of t){let i=n.pushed||await Or(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(-df)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
174
- `)[0]}}},lf=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let u=await Mb(e,d,r,n.get(d.branch));"sha"in u?s.push({record:d,sha:u.sha}):o.push(u)}let i=await jb(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(u=>u.branch===d.branch&&(u.pushed||u.status==="up-to-date")));for(let d of c)await Vc(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,u)=>l.indexOf(d.branch)-l.indexOf(u.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},Ef=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await bf({cwd:t,versions:r,all:n});if(s.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),oo();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await W(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!at(a))throw a;return{...oo(),declined:!0}}for(let a of s)await Vc(t,a.branch,a.worktreePath),p.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...oo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Fb from"node:fs";import Lb from"node:os";import Vb from"node:path";var Bb="infra-kit.json",Wb="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)",Jb="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",io=async()=>{let e;try{e=await S()}catch{return null}let t=e.trim();return t===""||t===Lb.homedir()?null:t},xf=async()=>{let e=await io();return e===null&&p.info(Wb),e},Ub=async()=>{let e=await io();return e===null?null:Fb.existsSync(Vb.join(e,Bb))?e:(p.info(Jb),null)};var Gb=async e=>{try{return await ke(e)}catch(t){return p.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Tf=async()=>{let e=await Ub(),t=q.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Bn(e,{version:t})];for(let n of await Gb(e)){let o=await Yt(n);r.push(...await Wn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import le from"node:fs";import zc from"node:os";import me from"node:path";import Yc from"node:process";import Hs from"node:fs/promises";import Kb from"node:path";import Hb from"node:process";var Cf=` // "envManagement": { // required in layer 1; provider-tagged
165
+ `,Dc=async(e="regular")=>{let t=Qe(e),r=Km({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 Km({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},lb=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await ut(t,r);if(!s)return(await Ac({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await zr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Nc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ne(t),c=await lb({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=rr(r,c),d=await Vs({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:Y(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Ws=async()=>{let e=new Map,t=await mt();if(!t)return e;try{let r=await qr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){p.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},oe=async()=>{let e=await Ws();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},so=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},xc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Js=e=>e.flatMap(t=>{let r=K(t);return r?[{branch:t,id:r,label:Y(r)}]:[]}),ft=e=>{try{return Te(ve(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},io=e=>{if(e===Hm)return Hm;let t=K(e);return t?Y(t):e},nr=e=>e.flatMap(t=>{let r=K(t);return r?[Y(r)]:[]}),db=(e,t)=>t?t.get(e)||"regular":void 0,se=e=>{let{branches:t,descriptions:r,types:n}=e;return Js(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ne(s)),type:db(o,n)}))};import zm from"node:fs/promises";import pb from"node:path";import{$ as _c}from"zx";var L="pnpm-lock.yaml",ub=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Xm=async(e,t)=>{let r=pb.join(e,L),n=`${t}:${L}`;try{let o=await _c({cwd:e,quiet:!0})`git show ${n}`;await zm.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${L} to start from: ${Ym(o)}`}}try{await _c({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${L}: ${Ym(o)}`}}return ub.test(await zm.readFile(r,"utf8"))?{ok:!1,reason:`${L} still carries conflict markers after pnpm ran`}:(await _c({cwd:e,quiet:!0})`git add -- ${L}`,{ok:!0})},Ym=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as or}from"zx";var Mc="Merge remote-tracking branch 'origin/dev' into ",Zm=e=>String(e.stderr??e.message??e).trim(),mb=async e=>{try{return(await or({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
166
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},fb=async(e,t)=>{let r=Zm(t),n=await mb(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await fu(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Qm=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await $e(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await gb({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},gb=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await $e(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await _n(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await ba(r),await or({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Mc}${n}`;await or({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await or({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:a===o?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:n,...await fb(r,i)}}finally{await Ra(r)}},ef=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),tf="pnpm install --frozen-lockfile",rf=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await ba(t),await or({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await or({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,Zm(a))}finally{await Ra(t)}return{kept:o,failed:s}},ao=async(e,t,r="origin/dev")=>{await or({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await _n(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import jc from"node:process";var Us=new Set,Gs=e=>(Us.add(e),()=>{Us.delete(e)}),hb=async()=>{for(let e of[...Us])try{await e()}catch(t){p.warn({error:t,msg:"cleanup failed during shutdown"})}Us.clear()},yb=["SIGINT","SIGTERM"],nf=async(e,t={})=>{let{register:r=(i,a)=>{jc.on(i,a)},unregister:n=(i,a)=>{jc.off(i,a)},exit:o=i=>{jc.exit(i)}}=t,s=new Map;for(let i of yb){let a=()=>{hb().then(()=>{o(_u(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var vb="pnpm install --frozen-lockfile --ignore-scripts",wb="pnpm install --frozen-lockfile",af=64*1024,uf=4096,lo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-uf)},N=async(e,t)=>(await qs({cwd:e,quiet:!0})`git ${t}`).stdout,Fc=e=>e.split(`
167
+ `).map(t=>t.trim()).filter(t=>t.length>0),zs=e=>e.split("\0").filter(t=>t.length>0),Ks=async(e,t)=>{try{return(await N(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},mf=async e=>et.resolve(e,(await N(e,["rev-parse","--git-common-dir"])).trim()),Lc=e=>e.then(()=>!0,()=>!1),co=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Vc=e=>e?.length===1&&e[0]===L,ff=async e=>et.join(await mf(e),"infra-kit","merge-dev-resolutions"),Bc=async(e,t)=>et.join(await ff(e),`${uu(t)}.json`),gf=async e=>{try{return JSON.parse(await Re.readFile(e,"utf8"))}catch{return null}},Zr=async(e,t)=>{let r=await Bc(e,t.branch);await Re.mkdir(et.dirname(r),{recursive:!0}),await Re.writeFile(r,`${JSON.stringify(t,null,2)}
168
+ `)},hf=async e=>{let t=await ff(e),r=await Re.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>gf(et.join(t,o))))).filter(o=>o!==null)},yf=async e=>Promise.all((await hf(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await Lc(Re.stat(t.worktreePath))}))),cf=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),Wc=async(e,t,r)=>{await N(e,["worktree","remove","--force",r]).catch(()=>Re.rm(r,{recursive:!0,force:!0})),await Re.rm(await Bc(e,t),{force:!0}).catch(()=>{}),await N(e,["worktree","prune"]).catch(()=>{})},vf=async e=>zs(await N(e,["diff","--name-only","-z","--diff-filter=U"])),Hs=async e=>zs(await N(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),kb=async(e,t)=>{let r=(await N(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await Lc(Re.stat(et.join(await mf(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Fc(await N(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},wf=e=>e.split("/").includes("node_modules"),Ys=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=zs(await N(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await bb(e),...o].filter(a=>!r.has(a)),i=(await Hs(e)).filter(a=>!n.has(a)&&!wf(a));return[...new Set([...s,...i,...await Rb(e)])].sort()},bb=async e=>{let t=zs(await N(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},Rb=async e=>(await N(e,["ls-files","-v"])).split(`
169
+ `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),Sb=async e=>{let t=`:(exclude)${L}`;try{return await N(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
170
+ `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},Pb=async(e,t)=>{let r=[];for(let n of t)(await Lc(Re.lstat(et.join(e,n)))||(await N(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await N(e,["--literal-pathspecs","add","-A","--",...r])},lf=async e=>(await N(e,["write-tree"])).trim(),kf=async e=>(await N(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),Eb=e=>e?`${wb} && ${e}`:vb,xb=async(e,t)=>{try{return await qs({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:lo(r)}}},bf=async(e,t)=>{let r=(await N(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await N(e,["diff","--cached","--stat",l,"--",L])).trim(),o=t.conflictPaths.includes(L)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await N(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${L}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
171
+ ${l}`:l}).join(""),c=of.byteLength(a)>af;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?of.from(a).subarray(0,af).toString():a,resolutionDiffTruncated:c}},Rf=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await Tb(t,s,n));return o},Tb=async(e,t,r)=>{let n=await gf(await Bc(e,t));if(n)return{resolution:cf(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await $e(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=mu(e,t),i=()=>Wc(e,t,s),a=Gs(i);try{await N(e,["worktree","prune"]),await Re.mkdir(et.dirname(s),{recursive:!0}),await N(e,["worktree","add","--detach",s,o]),await qs({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${Mc+t}`.catch(()=>{});let c=await vf(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await Ks(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await N(e,["--version"])).trim()})`};let d=await kb(s,c),u=Vc(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await Hs(s),lockfileOnly:u,cliVersion:q.version,createdAt:new Date().toISOString()};return await Zr(e,m),{resolution:cf(m,u?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:lo(c)}}finally{a()}},Sf=async e=>{let{cwd:t,versions:r,all:n}=e,o=await hf(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=Te(ve(c)),d=o.find(u=>u.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await Nt(se({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},Cb=async(e,t)=>{let r=await Re.realpath(t).catch(()=>null);if(!r)return!1;let n=await Pt(e);for(let o of n)if(await Re.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Xr=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Pf=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 Cb(e,n))return Xr(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Ks(n,"HEAD"),i=await Ks(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?Db(e,t,o,r):$b(t,o,s,i)},$b=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Xr(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 kf(o),i=n?null:await Ks(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 Xr(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Ys(o,e);return c.length>0?Xr(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(L),...await bf(o,e)}},df=async(e,t)=>{let r=Fc(await N(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},Ab=async(e,t)=>{let r=t.worktreePath,n=await df(r,L),o=t.lockfileBlob,s=await Xm(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[L]};let i=await df(r,L);if(i!==null&&i!==o&&(t.lockfileBlob=i,await Zr(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${L} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[L]}:{code:"out-of-scope-edit",detail:`${L} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[L]};let a=await Ys(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},Ob=async(e,t)=>{let r=t.worktreePath;await Pb(r,t.conflictPaths.filter(i=>i!==L));let n=await Ys(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await vf(r)).filter(i=>i!==L);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await Sb(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${lo(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(L)?Ab(e,t):null},Ib=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 Hs(o)),i=await xb(o,n);if(!i.ok)return i;let a=(await Hs(o)).filter(c=>!s.has(c)&&!wf(c)&&et.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await Zr(e,t),i},Db=async(e,t,r,n)=>{let o=t.worktreePath,s=await Ob(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(L),a=await lf(o),c=await Ib(e,t,a,Eb(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Xr(l,"verify-failed",c.reason??"the verify command failed");let d=await Ys(o,t),u=Fc(await N(o,["diff","--name-only"]));return d.length>0||u.length>0||await lf(o)!==a?Xr(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...u])]):(c.reused||(t.verified={treeSha:a,command:c.command},await Zr(e,t)),{...l,...await bf(o,t)})},Nb=12e4,_b=async(e,t=Nb)=>{let r=qs({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...sf.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&sf.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:lo(s)};let i=(await N(e,["rev-parse","--git-path","index.lock"])).trim();return await Re.rm(et.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},Mb={"verify-failed":"verify-failed","tree-changed":"tree-changed"},jb=e=>{let t=e.blocked;return{branch:e.branch,status:Mb[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},Fb=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,u,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:u,...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 _b(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await N(o,["rev-parse","HEAD"])).trim(),c=(await N(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await Zr(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await kf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},Lb=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await ao(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${lo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await $e(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await _n(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},Vb=e=>{p.info(`
172
+ \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?p.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):p.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Ef=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Sf({cwd:t,versions:r,all:n});if(a.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),co();if(i)return pf(t,a,o,s);let c=[];for(let m of a){let g=await Pf(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await Zr(t,m)),c.push(g)}Vb(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new E({status:"refused",plan:l,agentMode:A.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 u=new Map(d.map(m=>[m.branch,m.treeSha]));try{await W(i,`Commit and push the resolved merges for: ${[...u.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Bb(u)})}catch(m){if(!ct(m))throw m;return{...co(),declined:!0}}return pf(t,a,o,u)},xf=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},Bb=e=>{let t=[],r=!1;for(let o of Ou())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"]},Wb=async(e,t,r,n)=>{let o=await Pf(e,t,r);if(o.blocked)return jb(o);let s=await Fb(e,o,t,n);if(!("sha"in s))return s;let i=await Lb(e,t,s.sha);return i==="keep"?s:i},Jb=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}));p.info(`
173
+ \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await gs(e,r),o=[];for(let s of t){let i=n.pushed||await Or(e,s.record.branch)===s.sha;o.push({branch:s.record.branch,status:i?"merged":"push-aborted",mergeSha:s.sha,conflictPaths:s.record.conflictPaths,pushed:i,...i?{}:{reason:n.stderr?.trim().slice(-uf)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
174
+ `)[0]}}},pf=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let u=await Wb(e,d,r,n.get(d.branch));"sha"in u?s.push({record:d,sha:u.sha}):o.push(u)}let i=await Jb(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(u=>u.branch===d.branch&&(u.pushed||u.status==="up-to-date")));for(let d of c)await Wc(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,u)=>l.indexOf(d.branch)-l.indexOf(u.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},Tf=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Sf({cwd:t,versions:r,all:n});if(s.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),co();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await W(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!ct(a))throw a;return{...co(),declined:!0}}for(let a of s)await Wc(t,a.branch,a.worktreePath),p.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...co(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Ub from"node:fs";import Gb from"node:os";import Kb from"node:path";var Hb="infra-kit.json",qb="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)",zb="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",po=async()=>{let e;try{e=await x()}catch{return null}let t=e.trim();return t===""||t===Gb.homedir()?null:t},Cf=async()=>{let e=await po();return e===null&&p.info(qb),e},Yb=async()=>{let e=await po();return e===null?null:Ub.existsSync(Kb.join(e,Hb))?e:(p.info(zb),null)};var Xb=async e=>{try{return await ke(e)}catch(t){return p.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},$f=async()=>{let e=await Yb(),t=q.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Gn(e,{version:t})];for(let n of await Xb(e)){let o=await Yt(n);r.push(...await Kn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import le from"node:fs";import Xc from"node:os";import me from"node:path";import Zc from"node:process";import Zs from"node:fs/promises";import Zb from"node:path";import Qb from"node:process";var Af=` // "envManagement": { // required in layer 1; provider-tagged
175
175
  // "provider": "doppler",
176
176
  // "config": { "name": "my-doppler-project" }
177
177
  // },
@@ -261,17 +261,15 @@ ${l}`:l}).join(""),c=tf.byteLength(a)>of;return{diffStat:r,...o?{lockfileDiffSta
261
261
  // }
262
262
  //
263
263
  // // Marks the repo as the source \`ik vendor sync\` copies from: the tracked paths to mirror into
264
- // // every target in ~/.infra-kit/vendor.json, the path segments dropped on both sides of the diff,
265
- // // and the stale target paths a sync removes first. Absent or null means "not a source", which is
266
- // // every consumer repo.
264
+ // // every target in ~/.infra-kit/vendor.json and the path segments dropped on both sides of the
265
+ // // diff. Absent or null means "not a source", which is every consumer repo.
267
266
  // //
268
267
  // // PROJECT LAYER ONLY. This key is REFUSED here and in the per-project override \u2014 a machine-wide
269
268
  // // copy would make every repo on this machine a source, and a per-project override would make this
270
269
  // // machine disagree with every other clone. Commit it in the source repo's own infra-kit.json.
271
270
  // "vendorSource": {
272
271
  // "copy": [{ "path": ".claude" }, { "path": "vendor/configs" }],
273
- // "exclude": ["serverless-config"],
274
- // "legacyCleanup": ["configs"]
272
+ // "exclude": ["serverless-config"]
275
273
  // }
276
274
  //
277
275
  // // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in
@@ -280,7 +278,7 @@ ${l}`:l}).join(""),c=tf.byteLength(a)>of;return{diffStat:r,...o?{lockfileDiffSta
280
278
  // // also fixes its modes), or by hand: both are supported, which is why the store carries no
281
279
  // // repo-identity field and no mandatory version. Pasting a token into an
282
280
  // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
283
- // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Bc=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
281
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Jc=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
284
282
  //
285
283
  // Merge chain (later layers override earlier ones at top-level keys):
286
284
  // 1. <repo>/infra-kit.json \u2014 committed project config (required)
@@ -301,9 +299,9 @@ ${l}`:l}).join(""),c=tf.byteLength(a)>of;return{diffStat:r,...o?{lockfileDiffSta
301
299
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
302
300
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
303
301
  {
304
- ${Cf}
302
+ ${Af}
305
303
  }
306
- `,Wc=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
304
+ `,Uc=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
307
305
  //
308
306
  // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
309
307
  // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
@@ -320,106 +318,108 @@ ${Cf}
320
318
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
321
319
  // override layer \u2014 it is shown here only to document the full, valid config shape.
322
320
  {
323
- ${Cf}
321
+ ${Af}
324
322
  }
325
- `,Jc=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
323
+ `,Gc=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
326
324
  //
327
325
  // Machine-local registry the vendor commands (sync/manifest/diff) read to know
328
- // where your project repos live and which ones to stamp. This .example.jsonc is
326
+ // where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
329
327
  // reference only \u2014 it is NOT loaded. The real file is the strict-JSON sibling
330
328
  // vendor.json (no comments, double-quoted keys); run \`infra-kit vendor config --init\`
331
329
  // to scaffold it.
332
330
  {
333
- // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
331
+ // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where the source and target repos are cloned
332
+ // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
334
333
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
335
334
  }
336
- `;var $f=!1,qb=e=>e.replace(/\.json$/,".example.jsonc"),zb=async e=>{try{return await Hs.readFile(e,"utf-8")}catch{return null}},Zr=async e=>{let t=e.userProject,r=qb(t);await Hs.mkdir(Kb.dirname(t),{recursive:!0});let n=!await ee(t);n&&await Hs.writeFile(t,`{}
337
- `,"utf-8");let o=Wc(e.projectName),s=await zb(r)!==o;return s&&await Hs.writeFile(r,o,"utf-8"),n&&bu(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Qr=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,Uc=async()=>{if(Hb.env.INFRA_KIT_NO_SEED||$f)return;$f=!0;let e;try{e=await te()}catch{return}if(await ee(e.main))try{let t=await Zr(e);t.createdConfig?p.info(Qr(t)):t.refreshedExample&&p.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){p.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as Yb}from"node:child_process";import Of from"node:fs";import en from"node:process";import{fileURLToPath as Df}from"node:url";var Af=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Gc=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Af.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?jp(o,s,i)?"local-install":null:"not-a-tty"};var Xb=e=>{Yb(en.execPath,[e,"--parent-pid",String(en.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Zb=()=>Df(new URL("./update-check.js",import.meta.url)),Qb=()=>Of.realpathSync(Df(new URL("./cli.js",import.meta.url))),eR=/^[\w@./+ -]+$/i,tR=e=>eR.test(e),rR=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||In(e.latestVersion,t)&&e.updateCommand.every(tR)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${rs(e.updateCommand)}`)},Kc=(e,t={})=>{try{let r=t.argv??en.argv,n=t.env??en.env,o=t.isTty??!!en.stdout.isTTY,s=t.cwd??en.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??Qb(),c=t.readCache??Nn,l=t.spawnChild??Xb,d=t.fileExists??(y=>Of.existsSync(y)),u=t.notify??(y=>{p.info(y)});if(Gc({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:he})!==null)return;let m=c();if(rR(m,e,u),!Sa(m,i))return;let g=t.childPath??Zb();if(!d(g))return;l(g)}catch{}};import tt from"node:fs/promises";import et from"node:path";import{pathToFileURL as sR}from"node:url";import iR from"yaml";import{z as _f}from"zod";import nR from"node:fs/promises";import Hc from"node:os";import qc from"node:path";import{z as oR}from"zod";import{z as qs}from"zod";var If="vendor.json",zs=qs.object({workspaceDir:qs.string().min(1),targets:qs.array(qs.string()).min(1)}).strict();var tn=()=>qc.join(Hc.homedir(),Op,If),Ys=e=>{if(e==="~")return Hc.homedir();if(e.startsWith("~/"))return qc.join(Hc.homedir(),e.slice(2));if(qc.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Xs=async()=>{let e=tn(),t;try{t=await nR.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 and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
335
+ `;var Of=!1,eR=e=>e.replace(/\.json$/,".example.jsonc"),tR=async e=>{try{return await Zs.readFile(e,"utf-8")}catch{return null}},Qr=async e=>{let t=e.userProject,r=eR(t);await Zs.mkdir(Zb.dirname(t),{recursive:!0});let n=!await X(t);n&&await Zs.writeFile(t,`{}
336
+ `,"utf-8");let o=Uc(e.projectName),s=await tR(r)!==o;return s&&await Zs.writeFile(r,o,"utf-8"),n&&Pu(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},en=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,Kc=async()=>{if(Qb.env.INFRA_KIT_NO_SEED||Of)return;Of=!0;let e;try{e=await te()}catch{return}if(await X(e.main))try{let t=await Qr(e);t.createdConfig?p.info(en(t)):t.refreshedExample&&p.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){p.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as rR}from"node:child_process";import Df from"node:fs";import tn from"node:process";import{fileURLToPath as Nf}from"node:url";var If=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Hc=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return If.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Lp(o,s,i)?"local-install":null:"not-a-tty"};var nR=e=>{rR(tn.execPath,[e,"--parent-pid",String(tn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},oR=()=>Nf(new URL("./update-check.js",import.meta.url)),sR=()=>Df.realpathSync(Nf(new URL("./cli.js",import.meta.url))),iR=/^[\w@./+ -]+$/i,aR=e=>iR.test(e),cR=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||jn(e.latestVersion,t)&&e.updateCommand.every(aR)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${as(e.updateCommand)}`)},qc=(e,t={})=>{try{let r=t.argv??tn.argv,n=t.env??tn.env,o=t.isTty??!!tn.stdout.isTTY,s=t.cwd??tn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??sR(),c=t.readCache??Fn,l=t.spawnChild??nR,d=t.fileExists??(y=>Df.existsSync(y)),u=t.notify??(y=>{p.info(y)});if(Hc({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:he})!==null)return;let m=c();if(cR(m,e,u),!xa(m,i))return;let g=t.childPath??oR();if(!d(g))return;l(g)}catch{}};import rt from"node:fs/promises";import tt from"node:path";import{pathToFileURL as pR}from"node:url";import uR from"yaml";import{z as on}from"zod";import lR from"node:fs/promises";import zc from"node:os";import Yc from"node:path";import{z as dR}from"zod";import{z as uo}from"zod";var _f="vendor.json",Mf=uo.object({workspaceDir:uo.string().min(1),source:uo.string().min(1),targets:uo.array(uo.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var rn=()=>Yc.join(zc.homedir(),Dp,_f),nn=e=>{if(e==="~")return zc.homedir();if(e.startsWith("~/"))return Yc.join(zc.homedir(),e.slice(2));if(Yc.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Qs=async()=>{let e=rn(),t;try{t=await lR.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:
338
337
 
339
338
  {
340
339
  "workspaceDir": "~/projects",
340
+ "source": "my-starter",
341
341
  "targets": ["my-repo"]
342
342
  }
343
- `)}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=zs.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${oR.prettifyError(n.error)}`);return n.data};var Nf=e=>e.replace(/\.json$/,".yml"),Mf=async()=>{let e;try{e=await te()}catch{return}let t=[{label:"infra-kit.json",yml:Nf(e.main),json:e.main,schema:vu},{label:"~/.infra-kit/infra-kit.json",yml:et.join(et.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Pa},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Nf(e.userProject),json:e.userProject,schema:Pa}],r=0;for(let n of t){let[o,s]=await Promise.all([ee(n.yml),ee(n.json)]);if(o){if(s){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${w(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await tt.readFile(n.yml,"utf-8"),a=iR.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 invalid config: ${_f.prettifyError(c.error)}`);continue}await tt.mkdir(et.dirname(n.json),{recursive:!0}),await tt.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
344
- `,"utf-8"),await tt.rm(n.yml,{force:!0}),p.info(`\u2713 Migrated ${w(n.yml)} \u2192 ${w(n.json)}`),r++}catch(i){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${i.message}`)}}}r>0&&Ct()},jf=async()=>{let e;try{e=await te()}catch{return}let t=et.dirname(e.userGlobal),r=[{from:et.join(t,"config.json"),to:e.userGlobal},{from:et.join(t,"config.example.jsonc"),to:et.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([ee(o),ee(s)]);if(i){if(a){p.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await tt.mkdir(et.dirname(s),{recursive:!0}),await tt.rename(o,s),p.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){p.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Ct()},Ff=async()=>{let e=tn(),t=et.dirname(e),r=et.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ee(r),ee(e)]);if(n){if(o){p.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await tt.stat(r),c=(await import(`${sR(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,u=zs.safeParse(d);if(!u.success){p.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${_f.prettifyError(u.error)}`);return}await tt.mkdir(t,{recursive:!0}),await tt.writeFile(e,`${JSON.stringify(u.data,null,2)}
345
- `,"utf-8"),await tt.rm(r,{force:!0}),l?p.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.`):p.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){p.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},Lf=async()=>{let e=await aR(),t=0;for(let r of e)if(await ee(r))try{let n=await hu(r);if(!n.changed)continue;p.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof gu?"changed while migrating":n.message;p.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Ct()},aR=async()=>{try{let e=await te();return[e.main,e.userGlobal,e.userProject]}catch{return[ku()]}};var sr="# -- infra-kit:begin --",_t="# -- infra-kit:end --",cR=[["# region infra-kit","# endregion infra-kit"]],lR="# infra-kit shell functions",rn=class extends Error{constructor(r,n){super(n instanceof Error?n.message:String(n),{cause:n});this.step=r;this.reason=n;this.name="InitStepError"}step;reason},nn="Run `source ~/.zshrc` or open a new terminal to activate.",dR={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},rt=async(e,t)=>{try{return await t()}catch(r){throw new rn(e,r)}},Xc=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await rt("zshrc",()=>{r(pR())}),await rt("zshenv",()=>{r(uR())}),await rt("migrations",async()=>{await fR(),mR(),r(dR)}),await rt("user-config",()=>{r(hR())});let n=await rt("guidance",async()=>{let{entries:s,root:i}=await wR();return r(...s),i}),o=await rt("plugin-pointer",async()=>xf());return r(...RR(o,n)),await rt("worktrees",async()=>{r(...await TR(o))}),await rt("plugin-pointer",async()=>{await CR(o,r)}),await rt("mcp-proxies",async()=>{r(...await AR(o))}),await rt("project-config",async()=>{r(...await yR())}),r(...gR()),t};var pR=()=>{let e=me.join(zc.homedir(),".zshrc"),t=le.existsSync(e)?DR(le.readFileSync(e,"utf-8")):"",r=Ir({content:t,body:Bf(),startMarker:sr,endMarker:_t,placement:"append-end"});return le.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},uR=()=>{let e=me.join(zc.homedir(),".zshenv"),t=le.existsSync(e)?le.readFileSync(e,"utf-8"):"",r=Ir({content:t,body:Zc(),startMarker:sr,endMarker:_t});return le.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},mR=()=>{le.rmSync(me.join(Np(),"projects"),{recursive:!0,force:!0})},fR=async()=>{await Mf(),await jf(),await Lf(),await Ff()},gR=()=>{let e=Yc.env.SHELL??"",t=[];return e.includes("zsh")||t.push({step:"shell",outcome:"warned",message:`Your login shell ($SHELL=${e||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear) is zsh-only and won't activate in bash/fish.`,level:"warn"}),t.push({step:"shell",outcome:"unchanged",message:nn,level:"info"}),t},hR=()=>{let e=me.join(zc.homedir(),".infra-kit"),t=me.join(e,"infra-kit.json");return le.mkdirSync(e,{recursive:!0}),le.writeFileSync(me.join(e,"infra-kit.example.jsonc"),Bc(),"utf-8"),le.writeFileSync(me.join(e,"vendor.example.jsonc"),Jc(),"utf-8"),le.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(le.writeFileSync(t,`{}
346
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},yR=async()=>{if(Yc.env.INFRA_KIT_NO_SEED)return[Zs("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await te();if(!le.existsSync(e.main))return[Zs("skipped",`no project config at ${e.main}`)];let t=await Zr(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:Qr(t),level:"info"}]:[Zs("unchanged","the user-project config was already present")]}catch(e){return p.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[Zs("warned",e instanceof Error?e.message:String(e))]}},Zs=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),vR=(e,t,r)=>{let n=[];for(let s of r){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;n.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${me.relative(e,s.path)}${i}`,level:"info"})}n.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${t})`,level:"info"});let o=r.filter(s=>s.action==="failed");return o.length===0||n.push({step:"guidance",outcome:"warned",message:`${o.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),n},wR=async()=>{let{skipped:e,root:t,version:r,written:n}=await Tf();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:vR(t,r,n)}},kR=(e,t)=>{let r=me.relative(e,t.path);return t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},bR=(e,t)=>{let r=Oe;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?ae:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${Ze} from ${me.join(e,Oe)} \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 "${ae}" key`:`no ${r}`})`,level:"info"}},RR=(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 ${H} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],PR=()=>[ac,dt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),SR=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${q.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${q.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:rs(e.updateCommand),level:"info"}]:[r]},ER=(e,t)=>e.status==="skipped-cli-stale"?SR(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${H} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${Vr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${H} (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"},...PR()]:[{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: ${dt}`,level:"warn"}],Vf={stale:!1},xR=async()=>{let e=Nn(),t=e===null?await Ea(Yc.env):e.latestVersion;return t===null||!xa(t,q.version)?Vf:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Mp(t)}},TR=async e=>{if(e===null)return[];let r=`${await Le(e)}${ge}`,n=Object.values(Cr).filter(o=>!le.existsSync(me.join(r,o)));for(let o of Object.values(Cr))le.mkdirSync(me.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"}]},CR=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(kR(e,cc(me.join(e,".claude","settings.json"))));let n=qt({projectPath:e}).kind==="installed"?await xR():Vf;t(...ER(rc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(bR(e,Un(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: ${dt}`,level:"warn"})}},$R=(e,t)=>{let r=me.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},AR=async e=>{if(e===null)return[];if(!le.existsSync(me.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 I()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
347
- `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:$R(e,Cs({projectRoot:e,proxies:t,write:!0}))},OR=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"),DR=e=>{let t=At(e,sr,_t);if(t!==null)return t;for(let[a,c]of cR){let l=At(e,a,c);if(l!==null)return l}let r=e.indexOf(lR);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
348
- `),s=0;for(;s<o.length&&OR(o[s]);)s++;let i=o.slice(s).join(`
343
+ `)}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=Mf.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${dR.prettifyError(n.error)}`);return n.data};var jf=e=>e.replace(/\.json$/,".yml"),Ff=async()=>{let e;try{e=await te()}catch{return}let t=[{label:"infra-kit.json",yml:jf(e.main),json:e.main,schema:bu},{label:"~/.infra-kit/infra-kit.json",yml:tt.join(tt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ea},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:jf(e.userProject),json:e.userProject,schema:Ea}],r=0;for(let n of t){let[o,s]=await Promise.all([X(n.yml),X(n.json)]);if(o){if(s){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${w(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await rt.readFile(n.yml,"utf-8"),a=uR.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 invalid config: ${on.prettifyError(c.error)}`);continue}await rt.mkdir(tt.dirname(n.json),{recursive:!0}),await rt.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
344
+ `,"utf-8"),await rt.rm(n.yml,{force:!0}),p.info(`\u2713 Migrated ${w(n.yml)} \u2192 ${w(n.json)}`),r++}catch(i){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${i.message}`)}}}r>0&&Ct()},Lf=async()=>{let e;try{e=await te()}catch{return}let t=tt.dirname(e.userGlobal),r=[{from:tt.join(t,"config.json"),to:e.userGlobal},{from:tt.join(t,"config.example.jsonc"),to:tt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([X(o),X(s)]);if(i){if(a){p.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await rt.mkdir(tt.dirname(s),{recursive:!0}),await rt.rename(o,s),p.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){p.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Ct()},mR=on.object({workspaceDir:on.string().min(1),targets:on.array(on.string()).min(1)}).strict(),Vf=async()=>{let e=rn(),t=tt.dirname(e),r=tt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([X(r),X(e)]);if(n){if(o){p.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await rt.stat(r),c=(await import(`${pR(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,u=mR.safeParse(d);if(!u.success){p.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${on.prettifyError(u.error)}`);return}await rt.mkdir(t,{recursive:!0}),await rt.writeFile(e,`${JSON.stringify(u.data,null,2)}
345
+ `,"utf-8"),await rt.rm(r,{force:!0}),l?p.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.`):p.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){p.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},Bf=async()=>{let e=await fR(),t=0;for(let r of e)if(await X(r))try{let n=await vu(r);if(!n.changed)continue;p.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof yu?"changed while migrating":n.message;p.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Ct()},fR=async()=>{try{let e=await te();return[e.main,e.userGlobal,e.userProject]}catch{return[Su()]}};var sr="# -- infra-kit:begin --",_t="# -- infra-kit:end --",gR=[["# region infra-kit","# endregion infra-kit"]],hR="# infra-kit shell functions",sn=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},an="Run `source ~/.zshrc` or open a new terminal to activate.",yR={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},nt=async(e,t)=>{try{return await t()}catch(r){throw new sn(e,r)}},Qc=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await nt("zshrc",()=>{r(vR())}),await nt("zshenv",()=>{r(wR())}),await nt("migrations",async()=>{await bR(),kR(),r(yR)}),await nt("user-config",()=>{r(SR())});let n=await nt("guidance",async()=>{let{entries:s,root:i}=await xR();return r(...s),i}),o=await nt("plugin-pointer",async()=>Cf());return r(...$R(o,n)),await nt("worktrees",async()=>{r(...await NR(o))}),await nt("plugin-pointer",async()=>{await _R(o,r)}),await nt("mcp-proxies",async()=>{r(...await jR(o))}),await nt("project-config",async()=>{r(...await PR())}),r(...RR()),t};var vR=()=>{let e=me.join(Xc.homedir(),".zshrc"),t=le.existsSync(e)?LR(le.readFileSync(e,"utf-8")):"",r=Dr({content:t,body:Jf(),startMarker:sr,endMarker:_t,placement:"append-end"});return le.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},wR=()=>{let e=me.join(Xc.homedir(),".zshenv"),t=le.existsSync(e)?le.readFileSync(e,"utf-8"):"",r=Dr({content:t,body:el(),startMarker:sr,endMarker:_t});return le.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},kR=()=>{le.rmSync(me.join(Mp(),"projects"),{recursive:!0,force:!0})},bR=async()=>{await Ff(),await Lf(),await Bf(),await Vf()},RR=()=>{let e=Zc.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:an,level:"info"}),t},SR=()=>{let e=me.join(Xc.homedir(),".infra-kit"),t=me.join(e,"infra-kit.json");return le.mkdirSync(e,{recursive:!0}),le.writeFileSync(me.join(e,"infra-kit.example.jsonc"),Jc(),"utf-8"),le.writeFileSync(me.join(e,"vendor.example.jsonc"),Gc(),"utf-8"),le.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(le.writeFileSync(t,`{}
346
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},PR=async()=>{if(Zc.env.INFRA_KIT_NO_SEED)return[ei("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await te();if(!le.existsSync(e.main))return[ei("skipped",`no project config at ${e.main}`)];let t=await Qr(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:en(t),level:"info"}]:[ei("unchanged","the user-project config was already present")]}catch(e){return p.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[ei("warned",e instanceof Error?e.message:String(e))]}},ei=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),ER=(e,t,r)=>{let n=[];for(let s of r){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;n.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${me.relative(e,s.path)}${i}`,level:"info"})}n.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${t})`,level:"info"});let o=r.filter(s=>s.action==="failed");return o.length===0||n.push({step:"guidance",outcome:"warned",message:`${o.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),n},xR=async()=>{let{skipped:e,root:t,version:r,written:n}=await $f();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:ER(t,r,n)}},TR=(e,t)=>{let r=me.relative(e,t.path);return t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},CR=(e,t)=>{let r=Oe;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?ae:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${Ze} from ${me.join(e,Oe)} \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 "${ae}" key`:`no ${r}`})`,level:"info"}},$R=(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 ${H} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],AR=()=>[lc,pt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),OR=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${q.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${q.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:as(e.updateCommand),level:"info"}]:[r]},IR=(e,t)=>e.status==="skipped-cli-stale"?OR(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${H} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${Vr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${H} (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"},...AR()]:[{step:"plugin-pointer",outcome:"warned",message:`Could not install the Claude Code plugin \u2014 ${e.status==="unverified"?"the install reported success but Claude Code recorded no installation":`the ${e.step} step failed: ${e.error}`}. Run by hand: ${pt}`,level:"warn"}],Wf={stale:!1},DR=async()=>{let e=Fn(),t=e===null?await Ta(Zc.env):e.latestVersion;return t===null||!Ca(t,q.version)?Wf:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Fp(t)}},NR=async e=>{if(e===null)return[];let r=`${await Le(e)}${ge}`,n=Object.values(Cr).filter(o=>!le.existsSync(me.join(r,o)));for(let o of Object.values(Cr))le.mkdirSync(me.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"}]},_R=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(TR(e,dc(me.join(e,".claude","settings.json"))));let n=qt({projectPath:e}).kind==="installed"?await DR():Wf;t(...IR(oc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(CR(e,qn(e)))}catch(r){let n=r instanceof Error?r.message:String(r);t({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${pt}`,level:"warn"})}},MR=(e,t)=>{let r=me.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},jR=async e=>{if(e===null)return[];if(!le.existsSync(me.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 D()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
347
+ `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:MR(e,Ds({projectRoot:e,proxies:t,write:!0}))},FR=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"),LR=e=>{let t=At(e,sr,_t);if(t!==null)return t;for(let[a,c]of gR){let l=At(e,a,c);if(l!==null)return l}let r=e.indexOf(hR);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
348
+ `),s=0;for(;s<o.length&&FR(o[s]);)s++;let i=o.slice(s).join(`
349
349
  `);return n+(i?`
350
- ${i}`:"")},Bf=()=>{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(`
351
- `)},Wf=()=>`${sr}
352
- ${Bf()}
353
- ${_t}`,Zc=()=>["# 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.","# 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',' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
354
- `),Qc=()=>`${sr}
355
- ${Zc()}
356
- ${_t}`;var IR="Could not find requested project",NR="Could not find requested config",Jf="Invalid Auth token",Uf="does not have access to requested config",ir=e=>e.includes(Jf)||e.includes(Uf)?"auth":e.includes(IR)?"project":e.includes(NR)?"config":"unknown",ar=e=>e.includes(Uf)?"mis-scoped":e.includes(Jf)?"revoked":null;var Gf=e=>[`Doppler rejected the service token for env "${e}" \u2014 it is invalid, revoked, or scoped to a different config.`,`Fix: run \`infra-kit env-token-set ${e}\` with a token scoped to that config.`,"CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config."].join(`
357
- `),on=class extends gs{authKind;constructor(t,r=null,n){super(n??Gf(t),t),this.name="DopplerAuthError",this.authKind=r}};var el=({kind:e,project:t,config:r,available:n})=>{let o=e==="project"?[`Doppler project "${t}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${r}" not found in project "${t}".`];if(n&&n.length>0){let s=e==="project"?"Available projects":`Available configs in "${t}"`;o.push(`${s}: ${n.join(", ")}.`)}return o.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: pass an existing config, or create it in Doppler."),o.join(`
358
- `)};import{$ as Qs}from"zx";var _R=5e3,MR="DOPPLER_CONFIG",We=async()=>{let{envManagement:e}=await I();return e.config.name},tl=async({childEnv:e,project:t,config:r})=>{let n=Qs.quiet;Qs.quiet=!0;try{let s=(await Qs({env:e})`doppler secrets get ${MR} --plain --project ${t} --config ${r}`.timeout(_R)).stdout.trim();return s!==r?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(o){return{outcome:jR(o)}}finally{Qs.quiet=n}},jR=e=>{let t=$r(e)??(e instanceof Error?e.message:String(e));return ir(t)!=="auth"?"unreachable":ar(t)??"unreachable"};import FR from"node:process";var de="INFRA_KIT_ENV_TOKEN",ao=async e=>{let t=FR.env[de];if(t)return{token:t,source:"env"};let n=(await ue())?.envs[e];if(n)return{token:n,source:"store"};throw new gs(LR(e,await ct()),e)},LR=(e,t)=>[`No Doppler service token for env "${e}".`,`Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config "${e}" \u2192 Access tab \u2192 "Generate Service Token".`,`Fix: run \`infra-kit env-token-set ${e}\` and paste it.`,`It is stored in ${w(t)} (mode 0600, never in the repo).`,`CI / agents: set ${de} instead \u2014 it takes precedence and needs no home config.`].join(`
359
- `);import VR from"node:fs/promises";var co=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await VR.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}}},lo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import WR from"node:fs";import JR from"node:os";import Kf from"node:path";import UR from"node:process";import{$ as BR}from"zx";var cr=()=>BR({quiet:!0});var GR=()=>[Kf.join(JR.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],KR=async e=>{try{return(await cr()`command -v ${e}`).stdout.trim()||null}catch{return null}},po=()=>({runCommand:async e=>{let t=await cr()`${e}`;return{stdout:`${t.stdout}
360
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await KR(e);return t!==null?t:GR().map(r=>Kf.join(r,e)).find(r=>WR.existsSync(r))??null},realpath:he,platform:UR.platform});var Mt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),sn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,an=["darwin","linux"],ni=e=>t=>ga(t,e)?"homebrew":"unknown",oi=(e,t)=>r=>r===null?null:t(e(r),r),nl=e=>oi(ni(e.kegName),t=>t==="homebrew"?Mt(["brew","upgrade",e.brewFormula]):null),Hf=e=>ts(e,"Homebrew")||ts(e,"homebrew")?"homebrew":"unknown",HR={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:sn,platforms:an,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Hf,updateFor:oi(Hf,e=>e==="homebrew"?Mt(["brew","update"]):null)},rl={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Yf="https://awscli.amazonaws.com/v2/install.sh",Xf={steps:[["/bin/bash","-c",`curl -fsSL ${Yf} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},qR="/usr/local/aws-cli",zR=e=>Cn(qR,e,he)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Yf} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Xf,qf=e=>ga(e,rl.kegName)?"homebrew":ts(e,"aws-cli")?"script":"unknown",YR={id:"aws",binName:"aws",...rl,probeArgv:["aws","--version"],versionFrom:sn,platforms:an,prerequisites:[],bootstrapInstall:Xf,identify:qf,updateFor:oi(qf,(e,t)=>e==="homebrew"?Mt(["brew","upgrade",rl.brewFormula]):e==="script"?zR(t):null)},ei={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},XR={id:"git",binName:"git",...ei,probeArgv:["git","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install",ei.brewInstallSpec]),identify:ni(ei.kegName),updateFor:nl(ei)},ti={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},ZR={id:"gh",binName:"gh",...ti,probeArgv:["gh","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install",ti.brewInstallSpec]),identify:ni(ti.kegName),updateFor:nl(ti)},ri={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},QR={id:"doppler",binName:"doppler",...ri,probeArgv:["doppler","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install","gnupg"],["brew","install",ri.brewInstallSpec]),identify:ni(ri.kegName),updateFor:nl(ri)},uo="portless",zf=e=>_p(e,uo)===null?"unknown":"npm",eP={id:"portless",binName:uo,npmPackage:uo,probeArgv:["portless","--version"],versionFrom:sn,platforms:[...an,"win32"],prerequisites:[],bootstrapInstall:Mt(["npm","install","-g",uo]),identify:zf,updateFor:oi(zf,e=>e==="npm"?Mt(["npm","install","-g",`${uo}@latest`]):null)},ol={brew:HR,git:XR,aws:YR,gh:ZR,doppler:QR,portless:eP},lr=Object.keys(ol),Ie=e=>ol[e],sl=(e,t)=>e.platforms.includes(t),il=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 Ie(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Zf=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Qf=async(e,t)=>{try{return await e(t)}catch{return null}},tP=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},eg=async(e,t)=>{if(!sl(e,t.platform))return Zf(e.id);let r=await Qf(t.runCommand,e.probeArgv),n=await tP(t,e.binName);if(r==null&&n==null)return Zf(e.id);let o=r??(n==null?null:await Qf(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)}},mo=async(e,t)=>Promise.all(e.map(r=>eg(Ie(r),t)));var tg=["prod"],cn={allowed:!1,reason:"disallow"},jt=e=>tg.includes(e),rP=["dev","stage"],ln=e=>rP.includes(e)||jt(e),gt=(e,t=cn)=>t.allowed?e:e.filter(r=>!jt(r)),dr=(e,t,r=cn)=>{if(!r.allowed&&jt(e))throw r.reason==="agent-blocked"?new x({status:"refused",env:e,agentMode:A.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 f(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 Je=async()=>{let e;try{e=(await I()).protectedEnvs??"disallow"}catch{return cn}return e==="disallow"?cn:e==="cli-only"&&Q()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var fo=e=>{let{env:t,branch:r}=e;jt(t)&&p.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(`
361
- `))};import rg from"node:fs/promises";import al from"node:path";import nP from"yaml";var ng=".github/workflows",ht=async e=>{let t=await S();return og(al.resolve(t,ng,e))},cl=async()=>{let e=await S(),t=al.resolve(e,ng),r;try{r=await rg.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>og(al.resolve(t,s))));return[...new Set(o.flat())]},og=async e=>{let t;try{t=nP.parse(await rg.readFile(e,"utf-8"))}catch{return[]}let r=dn(t,"on")??dn(t,"true"),n=dn(dn(dn(dn(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},dn=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var pn=async()=>{let e=await cl(),t=await ue(),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]},pr=async()=>(await pn()).map(t=>t.env);import{$ as lP}from"zx";import{z as sg}from"zod";var ig=/^\d{4}-\d{2}-\d{2}$/,go=e=>{if(!ig.test(e))return!1;let[t,r,n]=e.split("-").map(Number),o=new Date(Date.UTC(t,r-1,n));return o.getUTCFullYear()===t&&o.getUTCMonth()===r-1&&o.getUTCDate()===n},ag=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,un=class extends Error{constructor(t){super(ag(t)),this.name="InvalidReleaseDateError"}},ur=e=>{let t=e.trim();if(!go(t))throw new un(t);return t},ho=e=>{let t=e.trim();return t===""||go(t)?!0:ag(t)},ll=sg.string().refine(go,{message:"Expected a calendar date in yyyy-mm-dd form."}),dl=sg.string().refine(e=>e===""||go(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Ft=e=>e.slice(1).split(".").map(Number),mn=e=>[...e].sort((t,r)=>{let[n,o,s]=Ft(t),[i,a,c]=Ft(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var lg="next",oP=/^v?(\d+)\.(\d+)\.(\d+)$/,sP=e=>e.replace(/^.*release\//,""),pl=e=>{let t=sP(e.trim()),r=oP.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},cg=e=>`${e[0]}.${e[1]}.${e[2]}`,ul=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=pl(o);if(!s)continue;let i=cg(s);n.has(i)||(n.add(i),r.push(s))}return mn(r.map(o=>cg(o))).map(o=>Ft(`v${o}`))},mr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},ml=(e,t)=>{if(e.length===0)throw new mr;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`},fn=(e,t)=>{try{return ml(e,t)}catch(r){if(r instanceof mr)return null;throw r}},fl=e=>e.trim().toLowerCase()===lg,ii=e=>fl(e)||pl(e)!==null?{version:e}:{name:e},iP=e=>e==="regular"||e==="hotfix",dg=e=>"name"in e,aP=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:ur(n)}},gl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=aP(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!iP(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return si({...ii(n),type:s},{description:i,releaseDate:o})},hl=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},si=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},cP=e=>{let t=e.name.trim();return is(t),si({id:{kind:"name",name:t,raw:t},type:e.type},e)},yl=(e,t)=>{let r=[...t];return e.map(n=>{if(dg(n))return cP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(fl(o)){let a=ml(r,n.type);return r.push(Ft(`v${a}`)),si({id:ve(a),type:n.type},n)}let s=pl(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),si({id:ve(i),type:n.type},n)})},vl=e=>e.some(t=>!dg(t)&&fl(t.version));var dP=e=>e.split(`
362
- `).map(t=>{let r=t.indexOf(" ");return r===-1?null:K(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),pP=async()=>{let e=await lP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return dP(e.stdout)},uP=async()=>{let e=await ut();return e?(await qr(e)).map(r=>r.name):[]},yo=async()=>{let[e,t]=await Promise.allSettled([pP(),uP()]);return e.status==="rejected"&&p.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&p.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),ul({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import mP from"node:fs";import fP from"node:path";var wl=[".claude/settings.json",".claude/settings.local.json"],gP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],hP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),yP=e=>{let t=e.trim();if(t==="Bash")return"*";let r=/^Bash\((.*)\)$/s.exec(t);if(r===null)return null;let n=r[1]??"";return n.endsWith(":*")?`${n.slice(0,-2)}*`:n},vP=(e,t)=>{let r=e.indexOf("*");if(r===-1)return e===t||e.startsWith(`${t} `);let n=e.slice(0,r);return new RegExp(`^${e.split("*").map(hP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},wP=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},kP=()=>fr.filter(e=>e.mutating),bP=e=>{let t=yP(e);return t===null?[]:kP().filter(r=>gP.some(n=>wP(r).some(o=>vP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},RP=(e,t)=>{let r;try{r=mP.readFileSync(fP.join(e,t),"utf-8")}catch(i){return i.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",file:t}}let n;try{n=JSON.parse(r)}catch{return{kind:"unreadable",file:t}}let o=n?.permissions;if(o==null)return{kind:"read",patterns:[]};let s=o.allow;return s===void 0?{kind:"read",patterns:[]}:Array.isArray(s)?{kind:"read",patterns:s.filter(i=>typeof i=="string")}:{kind:"unreadable",file:t}},pg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of wl){let n=RP(e,r);if(n.kind!=="absent"){if(t.present.push(r),n.kind==="unreadable"){t.unreadable.push(r);continue}for(let o of n.patterns){let s=bP(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var PP=e=>e.every(t=>t.status!=="fail"),SP=["brew","git","gh","doppler","aws"],EP=async e=>{let t=await mo(SP,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},yt=async(e,t,r,n)=>{try{return await cr()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},xP=async()=>{let e="orca installed",t=await Dr();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)"}},Pg=(e,t,r,n)=>{let o=pe.join(Rg.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!re.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=re.readFileSync(o,"utf-8"),a=i.indexOf(sr),c=i.indexOf(_t);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+_t.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},TP=()=>Pg("zshrc init block",".zshrc","shell",Wf()),CP=()=>Pg("zshenv session block",".zshenv","session-env",Qc()),$P=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await S(),r=pe.join(t,"pnpm-workspace.yaml");if(!re.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=re.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},AP=async()=>{try{return Ct(),{config:await I(),error:null}}catch(e){return{config:null,error:e}}},OP=e=>{let t="infra-kit config valid";return e.error?{name:t,status:"fail",message:e.error.message}:{name:t,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}},DP=384,kl=448,IP=e=>e.length===0?"no envs declared":e.map(t=>{let r=t.source===null?"no token":`token (${t.source})`;return`${t.env}: ${r}`}).join(", "),NP=async(e,t)=>Promise.all(e.map(async r=>{try{let{source:n}=await t(r);return{env:r,source:n}}catch{return{env:r,source:null}}})),_P=async(e,t={})=>{let r="env tokens configured",n=t.readStore??ue,o=t.resolveToken??ao;if(!e.config)return{name:r,status:"skip",message:"infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await NP(await pr(),o);return{name:r,status:"pass",message:IP(s)}},MP=()=>nt.env[de]||void 0,jP=async(e={})=>{let t="tokens.json present",r=e.readStore??ue,n=e.storePath??ct;if((e.readEnvToken??MP)())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(", ")}`}},vo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},FP=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??ct,o=t.statPath??LP,s=t.chmodPath??re.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(vo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=pe.dirname(i),c=pe.dirname(a),l=pe.dirname(c),u=[{target:l,expected:kl,actual:vo(l,o)},{target:c,expected:kl,actual:vo(c,o)},{target:a,expected:kl,actual:vo(a,o)},{target:i,expected:DP,actual:vo(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(u.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=u.map(g=>`${w(g.target)} is ${ug(g.actual)}, expected ${ug(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of u)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},ug=e=>`0${e.toString(8).padStart(3,"0")}`,LP=e=>{try{return re.statSync(e)}catch{return null}},VP=async()=>{let e="user override path";try{let t=await te(),r=re.existsSync(t.userProject),n=await co(t.userProject,r),o=r?lo(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}}},BP=async()=>{let e="legacy user-global config",t;try{t=await te()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=pe.join(pe.dirname(t.userGlobal),"config.json");return re.existsSync(r)?re.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"}},WP={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},JP=async e=>{let t=WP[e];try{return await cr()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},UP=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=Tt(e.config).map(s=>s.provider);if(r.length===0)return{name:t,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(r.map(s=>JP(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:t,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:t,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},mg=/^\d+\.\d+\.\d+$/,GP=(e,t)=>e===t||!mg.test(e)||!mg.test(t)?!1:mn([`v${e}`,`v${t}`])[0]===`v${e}`,KP=async(e,t)=>{let r;try{r=await ke(e)}catch{return[]}let n=[];for(let o of r){let s=Zt(Qt(pe.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&GP(s.version,t)&&n.push(s.version)}return n},HP=async(e,t)=>{let r=await KP(e,t);if(r.length===0)return"";let n=mn(r.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${r.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${t}) \u2014 run: infra-kit audit --fix --all`},qP=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await te()).main}catch{return e}if(!re.existsSync(t))return e;let r=pe.dirname(t),n=pe.join(r,"CLAUDE.md"),o=re.existsSync(n)?re.readFileSync(n,"utf-8"):"",s=ze(o,Ae,Ye),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await HP(r,q.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},zP=async()=>{try{let e=(await te()).main;return re.existsSync(e)?pe.dirname(e):null}catch{return null}},YP=e=>{let t=fu();return t===null||!In(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Vr}`},XP=e=>{let t=e.kind==="installed"?ms(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 ${H} version ${t}${YP(t)}`}},fg=3,gg=(e,t)=>he(e)===he(t),ZP=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(gg(e.projectDir,e.gitRoot))return"";let r=Cn(e.gitRoot,he(e.projectDir),he)?"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 gg(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}`},QP=(e,t)=>{let r="plugin installed",n=ZP(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${H} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${H} is not installed. Run: ${dt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-fg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,fg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${H} is installed for ${a} only, not this project. Run: ${dt}${n}`}},eS=()=>yt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),tS=(e,...t)=>{try{return JSON.parse(re.readFileSync(pe.join(e,...t),"utf-8"))}catch{return null}},rS=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ms(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=tS(r,Oe),o=n!==null&&typeof n=="object"?n[Ze]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},hg=e=>`Plugin ${H} ${e===null?"(version unreadable)":e}`,nS=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: ${dt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${hg(e.version)} still carries an MCP server in its ${Oe}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Vr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${hg(e.version)} is skills-only \u2014 no ${Oe}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},oS=(e,t)=>{let r=qt(e===null?{}:{projectPath:e}),n=Dn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ae} is known to Claude Code`:`Marketplace ${ae} is not registered. Run: claude plugin marketplace add ${Et}`},QP(r,t),XP(r),nS(rS(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${q.version}`}]},sS=({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(", ")},iS=e=>{let t="Agent mode",r=ss(e),n=sS(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})`}},yg=4,aS=e=>{let t=e.slice(0,yg).join(", "),r=e.length-yg;return r>0?`${t} +${r} more`:t},cS=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=pg(e);if(o.length>0){let s=o.map(i=>`${i.file} allows "${i.pattern}", which reaches ${i.commands.length} mutating infra-kit command${i.commands.length===1?"":"s"} (${aS(i.commands)})`);return{name:t,status:"warn",message:`${s.join("; ")} \u2014 a prefix allow lets an agent run the --yes re-run of a mutating command unprompted; narrow it to read-only argv (e.g. Bash(infra-kit release list:*)) so the host prompts for the rest`}}return n.length>0?{name:t,status:"warn",message:`Could not read permissions.allow from ${n.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:r.length===0?{name:t,status:"pass",message:`no ${wl.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:t,status:"pass",message:`no permissions.allow pattern in ${r.join(" or ")} reaches a mutating infra-kit command`}},lS=(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`},dS=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 gf(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} (${lS(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`}},Sg=e=>ha(["trust"],{bin:e}),pS=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),vg="ERR_TLS_CERT_ALTNAME_INVALID",Eg=()=>`portless serving TLS on :${xt}`,uS=async(e,t,r)=>{let n=Eg();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): \`${Pt(t,r)}\`.`}},mS=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(xt,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(vg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${vg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>pS.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${Sg(n)}\`, or reinstall: \`${Pt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},fS=(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: \`${Sg(r)}\` (no sudo needed).`}},gS=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 \`${ha(["alias","--remove","<name>"],{bin:r})}\`.`}},Lt="portless service target",ko=e=>({name:Lt,status:"warn",message:e}),xg=e=>e==="darwin"?Wp:e==="linux"?Jp:null,hS=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Bp}`:`sudo systemctl restart ${Up}`,yS="/bin/ps",vS=e=>{try{let t=bg(yS,["-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}},wg=e=>{try{return re.readFileSync(e,"utf-8")}catch{return null}},wS=e=>{try{return re.statSync(e).mtime}catch{return null}},kS=2e3,bS=e=>{try{let t=bg(e,["-p","process.version"],{encoding:"utf-8",timeout:kS}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},RS=(e,t)=>({platform:e.platform??nt.platform,readServiceFile:e.readServiceFile??wg,readFile:e.readFile??wg,exists:e.exists??re.existsSync,realpath:e.realpath??he,mtime:e.mtime??wS,execPath:e.execPath??nt.execPath,home:e.home??Rg.homedir(),cwd:e.cwd??nt.cwd(),repoRoot:e.repoRoot??io,stateDir:(e.stateDir??Kp)(),processStartTime:e.processStartTime??vS,version:e.version??nt.version,arch:e.arch??nt.arch,nodeVersionOf:e.nodeVersionOf??bS,isGlobal:e.isGlobal??os().node.isGlobal,nodeFs:e.nodeFs??re,stableNode:null,stableNodeSidecar:null,bin:t}),bo="portless node",gr="~/.infra-kit/node",wo=e=>({row:{name:bo,status:"fail",message:e},stableNode:null,sidecar:null}),kg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},PS=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,SS=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,ES=e=>{let t=Xp(e.home),r=kg(e.nodeFs.lstatSync,t);if(r===void 0)return wo(`${gr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return wo(`${gr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Zp(e.home,e.nodeFs);if(n===null)return wo(`${gr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=kg(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 wo(`${gr} 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(!SS(c,e))return wo(`${gr} does not run as Node ${e.version} (${PS(c)}). Re-run through the current Node: \`${Pt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:bo,status:"pass",message:`${gr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},xS=e=>{if(xg(e.platform)===null)return{row:{name:bo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=ES(e);return e.isGlobal()?t:{...t,row:{name:bo,status:"skip",message:`not a global install; the global infra-kit keeps ${gr} current`}}},Tg=(e,t)=>{let r=RS(e,t),n=xS(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},TS=(e,t)=>{let r=t.readFile(pe.join(e,"package.json"));try{let n=r===null?null:fe.object({version:fe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},CS=e=>{let t=Number.parseInt(e.readFile(pe.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},$S=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},AS=(e,t,r)=>{let n=CS(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o($S(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(pe.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},OS=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Cn(await t.repoRoot()??r,e,t.realpath)},hr=e=>({state:"drifted",row:e}),DS=async(e,t,r)=>{let n=Pt(r.bin,r);if(!r.exists(e))return hr({name:Lt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=pe.join(ya(r.home),"dist","cli.js");if(t!==o)return hr(ko(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(ns(r.home,r.exists)===null)return hr({name:Lt,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=r.realpath(ya(r.home));if(await OS(s,r))return hr({name:Lt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=IS(e,n,r);if(i!==null)return i;let a=TS(s,r),c=AS(s,a,r);return c!==null?{state:"converged",row:ko(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${hS(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Lt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},IS=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:hr(ko(`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:hr(ko(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Cg=async e=>{let t=xg(e.platform);if(t===null)return{state:"absent",row:{name:Lt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Lt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=_m(e.platform,r)??[];return n===void 0||o===void 0?hr(ko(`could not parse ${t} \u2014 re-run \`${Pt(e.bin,e)}\` to rewrite it.`)):DS(n,o,e)},$g=async(e,t)=>{let{seams:r}=Tg(e,t);return{state:(await Cg(r)).state,stableNode:r.stableNode}},NS=()=>[bo,Lt,Eg(),"portless CA chain valid","portless CA trusted","portless routes"],_S=async(e={})=>{let t=e.resolveBin??Vp,r=e.isProxyServing??Gp,n=e.handshake??zp,o=e.caTrusted??qp,s=e.routes??An,i=e.isListening??$n,a=(e.caPath??Hp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...NS().map(P=>({name:P,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:u}=Tg(e,c),m=s(),g=await uS(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await mS(n,m,a,c,d);return[l,u,(await Cg(d)).row,g,y,fS(o(),a,c),await gS(m,i,c)]},MS=async(e={})=>{let t="portless routes",r=e.routes??An,n=e.isListening??$n,o=e.devSessionRunning??Am,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=$m(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??Yp().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ai=async(e={})=>{let t=await AP(),r=EP(e.probeDeps??po()),n=async(m,g)=>{let[y,P]=await Promise.all([g,r]),v=P.get(m);return v===void 0?y:{...y,detail:v}},o=await Promise.all([n("brew",yt("brew installed",Ie("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",yt("git installed",Ie("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",yt("gh installed",Ie("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),yt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",yt("doppler installed",Ie("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",yt("aws installed",Ie("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")),yt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),yt("typescript-language-server installed",["typescript-language-server","--version"],"typescript-language-server is installed","typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing"),xP(),Promise.resolve(TP()),Promise.resolve(CP()),$P(),Promise.resolve(OP(t)),jP(),_P(t),FP(e.fix??!1),VP(),BP(),UP(t)]),s=await _S(e.portlessDeps);if(e.fix){let m=await MS(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await zP(),a=await io(),c={projectDir:nt.env.CLAUDE_PROJECT_DIR||null,cwd:nt.cwd(),gitRoot:a},l=[await eS(),...oS(i,c),iS({env:nt.env,stdinIsTTY:nt.stdin.isTTY===!0,flag:A.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:cS(a)],d=[...o,await dS(a),...s,...await qP(),...l],u={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:bc.has(m.name),detail:m.detail})),allPassed:PP(d),cliVersion:q.version};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},bl=R({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:fe.array(fe.object({name:fe.string().describe("Name of the check"),status:fe.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:fe.string().describe("Details about the check result"),fixable:fe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:fe.object({manager:fe.string().describe("Which package manager owns this install, read from its resolved path"),version:fe.string().nullable().describe("The version the tool reported, or null"),present:fe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:fe.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:fe.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:fe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ai()});import{spawn as US}from"node:child_process";import El from"node:process";import{z as V}from"zod";import{describeProxyRoutes as jS,loadDev as FS,readLocalContext as LS,slugifyHostLabel as Ag}from"@slip-stream-kit/config/internal";import Og from"node:fs";import gn from"node:path";import Rl from"node:process";import{z as Pl}from"zod";var VS=async e=>{let t=gn.join(e,"apps"),r=Og.existsSync(t)?Og.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=gn.join(t,o,"tests"),i=await Oa(s).catch(()=>{});i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},BS=(e,t)=>{let[r,n]=gn.relative(e,t).split(gn.sep);return r==="apps"&&n?n:void 0},WS=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(BS(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target, baseUrlEnv }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new x({status:"argument_required",argument:a,choices:Pl.toJSONSchema(Pl.object({app:Pl.enum(i)})),agentMode:A.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(", ")}`})},JS=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}})),Sl=async(e,t={})=>{let r=t.cwd??Rl.cwd(),n=t.projectRoot??await S(),o=(t.env??Rl.env)[st]||null,s=t.healthProbe??Ju,i=WS(await VS(n),e,r,n),{target:a,baseUrlEnv:c,cloud:l}=i.e2e,[d,u]=a.split("/"),m=gn.join(n,"apps",d,u),g=(await zt(m)).name;if(!g)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${gn.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${m} has no package.json name`});let y=Uu(m),P=`${y}.${Ag(g)}.localhost`,v=LS(m),C=`https://${P}`,_=0;if(u==="ui")_=(t.listRoutes??An)().find(j=>j.name===P||j.name===`${y}.${Ag(g)}`)?.port??0;else{let j=v.info.get(g);_=j?.port??0,C=j?.origin??C}let O=_>0&&await s({tag:a,port:_,kind:u})==="ok",E={app:i.app,testsDir:i.testsDir,target:a,packageName:g,baseUrlEnv:c,release:y,env:o,localUrl:C};if(O){let j=u==="ui"?await FS(m):void 0,Ke=j?.proxy?jS({proxy:j.proxy,localContext:v,env:o??void 0,getRelease:()=>y}):[],xe=new Map([...v.info].map(([fa,Yo])=>[fa,Yo.port]));return{...E,mode:"local",baseUrl:C,routes:await JS(Ke,xe,s)}}let G=t.env??Rl.env,B=l?o&&l.replaceAll("<env>",o):G[c];if(!o||!B){let j=o?`${c} is not set (and \`e2e.cloud\` is not configured)`:`${st} is not set`;throw new f(void 0,{operation:`resolve where ${i.app}'s e2e tests run`,remediation:"start the dev server (`infra-kit dev`), or load an environment (`infra-kit env-load -c <env>`) to run against cloud",stderrExcerpt:`nothing serves ${a} at ${C}, and ${j}`})}return{...E,mode:"cloud",baseUrl:B,routes:[]}};var GS=e=>{let t=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl} (${e.baseUrlEnv})`,e.mode==="local"?` dev server for ${e.target} on release "${e.release}"`:` nothing serves ${e.target} at ${e.localUrl}; cloud env "${e.env}" (${st})`];for(let r of e.routes){let n="";r.live!==null&&(n=r.live?" \u2014 live":" \u2014 NOT responding"),t.push(` ${r.path.padEnd(24)} ${r.source.padEnd(5)} ${r.target??"(unresolved)"}${n}`)}return t.join(`
363
- `)},KS=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},HS=async(e,t)=>{if(e.env===null||!jt(e.env))return;let r=await(t.protectedEnvAccess??Je)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new x({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},qS=(e,t)=>new Promise((r,n)=>{let o=US("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...El.env,[e.baseUrlEnv]:e.baseUrl},stdio:["inherit",it.enabled||ie()?2:"inherit","inherit"]});o.once("error",n),o.once("close",s=>{r(s??1)})}),ci=async(e,t={})=>{let r=await Sl(e.app,t);p.info(GS(r));let n=(t.env??El.env)[r.baseUrlEnv];n&&n!==r.baseUrl&&p.info(` ${r.baseUrlEnv} was ${n} in this shell; the run uses ${r.baseUrl}`),r.mode==="local"?KS(r):await HS(r,t);let o={...r,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Dg({...o,ran:!1,exitCode:null});r.mode==="cloud"&&await W(e.yes,`Run ${r.app} e2e against ${r.baseUrl} ("${r.env}", shared)?`,{plan:o});let s=await(t.runPlaywright??qS)(r,e.playwrightArgs??[]);return s!==0&&(El.exitCode=s),Dg({...o,ran:!0,exitCode:s})},Dg=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),zS={app:V.string(),testsDir:V.string(),target:V.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:V.string(),mode:V.enum(["local","cloud"]).describe("local: this worktree\u2019s dev server serves the target. cloud: it does not; the run uses the env-loaded baseUrlEnv, or e2e.cloud at env."),baseUrl:V.string().describe("The URL the run was pointed at, via the baseUrlEnv variable."),baseUrlEnv:V.string(),release:V.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:V.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),localUrl:V.string().describe("The local address probed, whether or not anything answered."),routes:V.array(V.object({path:V.string(),packageName:V.string(),source:V.enum(["local","cloud"]),target:V.string().nullable(),live:V.boolean().nullable()})).describe("Local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:V.array(V.string()),ran:V.boolean().describe("False for --dry-run."),exitCode:V.number().nullable().describe("Playwright\u2019s exit code; null when it did not run.")},xl=R({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree\u2019s local dev server when it serves the target, else against the deployed app at INFRA_KIT_ENV. dryRun resolves and reports the target and the proxy topology without running. A cloud run is confirm-gated; a protected env (prod) follows protectedEnvs.",requiresHumanConfirm:!0,inputSchema:{app:V.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:V.boolean().optional(),yes:V.boolean().optional()},outputSchema:zS,handler:e=>ci(e)});import Tl from"node:fs";import Ig from"node:path";import{z as Ro}from"zod";var YS=e=>[...e.map(t=>`unset ${t}`),`unset ${st}`,`unset ${Er}`,`unset ${xr}`,`unset ${Zo}`,`unset ${Tr}`],li=async()=>{let e=bt(),t=Ig.join(e,kt);if(!Tl.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Qo(t),n=YS(r),o=Ig.resolve(e,Xo);Tl.mkdirSync(e,{recursive:!0,mode:448}),es(o,`${n.join(`
350
+ ${i}`:"")},Jf=()=>{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(`
351
+ `)},Uf=()=>`${sr}
352
+ ${Jf()}
353
+ ${_t}`,el=()=>["# 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.","# 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',' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
354
+ `),tl=()=>`${sr}
355
+ ${el()}
356
+ ${_t}`;var VR="Could not find requested project",BR="Could not find requested config",Gf="Invalid Auth token",Kf="does not have access to requested config",ir=e=>e.includes(Gf)||e.includes(Kf)?"auth":e.includes(VR)?"project":e.includes(BR)?"config":"unknown",ar=e=>e.includes(Kf)?"mis-scoped":e.includes(Gf)?"revoked":null;var Hf=e=>[`Doppler rejected the service token for env "${e}" \u2014 it is invalid, revoked, or scoped to a different config.`,`Fix: run \`infra-kit env-token-set ${e}\` with a token scoped to that config.`,"CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config."].join(`
357
+ `),cn=class extends ks{authKind;constructor(t,r=null,n){super(n??Hf(t),t),this.name="DopplerAuthError",this.authKind=r}};var rl=({kind:e,project:t,config:r,available:n})=>{let o=e==="project"?[`Doppler project "${t}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${r}" not found in project "${t}".`];if(n&&n.length>0){let s=e==="project"?"Available projects":`Available configs in "${t}"`;o.push(`${s}: ${n.join(", ")}.`)}return o.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: pass an existing config, or create it in Doppler."),o.join(`
358
+ `)};import{$ as ti}from"zx";var WR=5e3,JR="DOPPLER_CONFIG",We=async()=>{let{envManagement:e}=await D();return e.config.name},nl=async({childEnv:e,project:t,config:r})=>{let n=ti.quiet;ti.quiet=!0;try{let s=(await ti({env:e})`doppler secrets get ${JR} --plain --project ${t} --config ${r}`.timeout(WR)).stdout.trim();return s!==r?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(o){return{outcome:UR(o)}}finally{ti.quiet=n}},UR=e=>{let t=$r(e)??(e instanceof Error?e.message:String(e));return ir(t)!=="auth"?"unreachable":ar(t)??"unreachable"};import GR from"node:process";var de="INFRA_KIT_ENV_TOKEN",mo=async e=>{let t=GR.env[de];if(t)return{token:t,source:"env"};let n=(await ue())?.envs[e];if(n)return{token:n,source:"store"};throw new ks(KR(e,await lt()),e)},KR=(e,t)=>[`No Doppler service token for env "${e}".`,`Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config "${e}" \u2192 Access tab \u2192 "Generate Service Token".`,`Fix: run \`infra-kit env-token-set ${e}\` and paste it.`,`It is stored in ${w(t)} (mode 0600, never in the repo).`,`CI / agents: set ${de} instead \u2014 it takes precedence and needs no home config.`].join(`
359
+ `);import HR from"node:fs/promises";var fo=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await HR.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}}},go=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import zR from"node:fs";import YR from"node:os";import qf from"node:path";import XR from"node:process";import{$ as qR}from"zx";var cr=()=>qR({quiet:!0});var ZR=()=>[qf.join(YR.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],QR=async e=>{try{return(await cr()`command -v ${e}`).stdout.trim()||null}catch{return null}},ho=()=>({runCommand:async e=>{let t=await cr()`${e}`;return{stdout:`${t.stdout}
360
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await QR(e);return t!==null?t:ZR().map(r=>qf.join(r,e)).find(r=>zR.existsSync(r))??null},realpath:he,platform:XR.platform});var Mt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),ln=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,dn=["darwin","linux"],si=e=>t=>ya(t,e)?"homebrew":"unknown",ii=(e,t)=>r=>r===null?null:t(e(r),r),sl=e=>ii(si(e.kegName),t=>t==="homebrew"?Mt(["brew","upgrade",e.brewFormula]):null),zf=e=>is(e,"Homebrew")||is(e,"homebrew")?"homebrew":"unknown",eS={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:ln,platforms:dn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:zf,updateFor:ii(zf,e=>e==="homebrew"?Mt(["brew","update"]):null)},ol={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Zf="https://awscli.amazonaws.com/v2/install.sh",Qf={steps:[["/bin/bash","-c",`curl -fsSL ${Zf} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},tS="/usr/local/aws-cli",rS=e=>In(tS,e,he)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Zf} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Qf,Yf=e=>ya(e,ol.kegName)?"homebrew":is(e,"aws-cli")?"script":"unknown",nS={id:"aws",binName:"aws",...ol,probeArgv:["aws","--version"],versionFrom:ln,platforms:dn,prerequisites:[],bootstrapInstall:Qf,identify:Yf,updateFor:ii(Yf,(e,t)=>e==="homebrew"?Mt(["brew","upgrade",ol.brewFormula]):e==="script"?rS(t):null)},ri={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},oS={id:"git",binName:"git",...ri,probeArgv:["git","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install",ri.brewInstallSpec]),identify:si(ri.kegName),updateFor:sl(ri)},ni={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},sS={id:"gh",binName:"gh",...ni,probeArgv:["gh","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install",ni.brewInstallSpec]),identify:si(ni.kegName),updateFor:sl(ni)},oi={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},iS={id:"doppler",binName:"doppler",...oi,probeArgv:["doppler","--version"],versionFrom:ln,platforms:dn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install","gnupg"],["brew","install",oi.brewInstallSpec]),identify:si(oi.kegName),updateFor:sl(oi)},yo="portless",Xf=e=>jp(e,yo)===null?"unknown":"npm",aS={id:"portless",binName:yo,npmPackage:yo,probeArgv:["portless","--version"],versionFrom:ln,platforms:[...dn,"win32"],prerequisites:[],bootstrapInstall:Mt(["npm","install","-g",yo]),identify:Xf,updateFor:ii(Xf,e=>e==="npm"?Mt(["npm","install","-g",`${yo}@latest`]):null)},il={brew:eS,git:oS,aws:nS,gh:sS,doppler:iS,portless:aS},lr=Object.keys(il),De=e=>il[e],al=(e,t)=>e.platforms.includes(t),cl=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 De(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var eg=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),tg=async(e,t)=>{try{return await e(t)}catch{return null}},cS=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},rg=async(e,t)=>{if(!al(e,t.platform))return eg(e.id);let r=await tg(t.runCommand,e.probeArgv),n=await cS(t,e.binName);if(r==null&&n==null)return eg(e.id);let o=r??(n==null?null:await tg(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)}},vo=async(e,t)=>Promise.all(e.map(r=>rg(De(r),t)));var ng=["prod"],pn={allowed:!1,reason:"disallow"},jt=e=>ng.includes(e),lS=["dev","stage"],un=e=>lS.includes(e)||jt(e),gt=(e,t=pn)=>t.allowed?e:e.filter(r=>!jt(r)),dr=(e,t,r=pn)=>{if(!r.allowed&&jt(e))throw r.reason==="agent-blocked"?new E({status:"refused",env:e,agentMode:A.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 f(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 Je=async()=>{let e;try{e=(await D()).protectedEnvs??"disallow"}catch{return pn}return e==="disallow"?pn:e==="cli-only"&&ee()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var wo=e=>{let{env:t,branch:r}=e;jt(t)&&p.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(`
361
+ `))};import og from"node:fs/promises";import ll from"node:path";import dS from"yaml";var sg=".github/workflows",ht=async e=>{let t=await x();return ig(ll.resolve(t,sg,e))},dl=async()=>{let e=await x(),t=ll.resolve(e,sg),r;try{r=await og.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>ig(ll.resolve(t,s))));return[...new Set(o.flat())]},ig=async e=>{let t;try{t=dS.parse(await og.readFile(e,"utf-8"))}catch{return[]}let r=mn(t,"on")??mn(t,"true"),n=mn(mn(mn(mn(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},mn=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var fn=async()=>{let e=await dl(),t=await ue(),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]},pr=async()=>(await fn()).map(t=>t.env);import{$ as hS}from"zx";import{z as ag}from"zod";var cg=/^\d{4}-\d{2}-\d{2}$/,ko=e=>{if(!cg.test(e))return!1;let[t,r,n]=e.split("-").map(Number),o=new Date(Date.UTC(t,r-1,n));return o.getUTCFullYear()===t&&o.getUTCMonth()===r-1&&o.getUTCDate()===n},lg=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,gn=class extends Error{constructor(t){super(lg(t)),this.name="InvalidReleaseDateError"}},ur=e=>{let t=e.trim();if(!ko(t))throw new gn(t);return t},bo=e=>{let t=e.trim();return t===""||ko(t)?!0:lg(t)},pl=ag.string().refine(ko,{message:"Expected a calendar date in yyyy-mm-dd form."}),ul=ag.string().refine(e=>e===""||ko(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Ft=e=>e.slice(1).split(".").map(Number),hn=e=>[...e].sort((t,r)=>{let[n,o,s]=Ft(t),[i,a,c]=Ft(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var pg="next",pS=/^v?(\d+)\.(\d+)\.(\d+)$/,uS=e=>e.replace(/^.*release\//,""),ml=e=>{let t=uS(e.trim()),r=pS.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},dg=e=>`${e[0]}.${e[1]}.${e[2]}`,fl=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=ml(o);if(!s)continue;let i=dg(s);n.has(i)||(n.add(i),r.push(s))}return hn(r.map(o=>dg(o))).map(o=>Ft(`v${o}`))},mr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},gl=(e,t)=>{if(e.length===0)throw new mr;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`},yn=(e,t)=>{try{return gl(e,t)}catch(r){if(r instanceof mr)return null;throw r}},hl=e=>e.trim().toLowerCase()===pg,ci=e=>hl(e)||ml(e)!==null?{version:e}:{name:e},mS=e=>e==="regular"||e==="hotfix",ug=e=>"name"in e,fS=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:ur(n)}},yl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=fS(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!mS(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return ai({...ci(n),type:s},{description:i,releaseDate:o})},vl=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},ai=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},gS=e=>{let t=e.name.trim();return ps(t),ai({id:{kind:"name",name:t,raw:t},type:e.type},e)},wl=(e,t)=>{let r=[...t];return e.map(n=>{if(ug(n))return gS(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(hl(o)){let a=gl(r,n.type);return r.push(Ft(`v${a}`)),ai({id:ve(a),type:n.type},n)}let s=ml(o);if(!s)throw new Error(`Invalid version "${o}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return r.push(s),ai({id:ve(i),type:n.type},n)})},kl=e=>e.some(t=>!ug(t)&&hl(t.version));var yS=e=>e.split(`
362
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:K(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),vS=async()=>{let e=await hS({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return yS(e.stdout)},wS=async()=>{let e=await mt();return e?(await qr(e)).map(r=>r.name):[]},Ro=async()=>{let[e,t]=await Promise.allSettled([vS(),wS()]);return e.status==="rejected"&&p.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&p.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),fl({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import kS from"node:fs";import bS from"node:path";var bl=[".claude/settings.json",".claude/settings.local.json"],RS=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],SS=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),PS=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},ES=(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(SS).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},xS=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},TS=()=>fr.filter(e=>e.mutating),CS=e=>{let t=PS(e);return t===null?[]:TS().filter(r=>RS.some(n=>xS(r).some(o=>ES(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},$S=(e,t)=>{let r;try{r=kS.readFileSync(bS.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}},mg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of bl){let n=$S(e,r);if(n.kind!=="absent"){if(t.present.push(r),n.kind==="unreadable"){t.unreadable.push(r);continue}for(let o of n.patterns){let s=CS(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var AS=e=>e.every(t=>t.status!=="fail"),OS=["brew","git","gh","doppler","aws"],IS=async e=>{let t=await vo(OS,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},yt=async(e,t,r,n)=>{try{return await cr()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},DS=async()=>{let e="orca installed",t=await Ir();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)"}},Eg=(e,t,r,n)=>{let o=pe.join(Pg.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!re.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=re.readFileSync(o,"utf-8"),a=i.indexOf(sr),c=i.indexOf(_t);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+_t.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},NS=()=>Eg("zshrc init block",".zshrc","shell",Uf()),_S=()=>Eg("zshenv session block",".zshenv","session-env",tl()),MS=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await x(),r=pe.join(t,"pnpm-workspace.yaml");if(!re.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=re.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}`}}},jS=async()=>{try{return Ct(),{config:await D(),error:null}}catch(e){return{config:null,error:e}}},FS=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)"}},LS=384,Rl=448,VS=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(", "),BS=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}}})),WS=async(e,t={})=>{let r="env tokens configured",n=t.readStore??ue,o=t.resolveToken??mo;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 BS(await pr(),o);return{name:r,status:"pass",message:VS(s)}},JS=()=>ot.env[de]||void 0,US=async(e={})=>{let t="tokens.json present",r=e.readStore??ue,n=e.storePath??lt;if((e.readEnvToken??JS)())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(", ")}`}},So=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},GS=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??lt,o=t.statPath??KS,s=t.chmodPath??re.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(So(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=pe.dirname(i),c=pe.dirname(a),l=pe.dirname(c),u=[{target:l,expected:Rl,actual:So(l,o)},{target:c,expected:Rl,actual:So(c,o)},{target:a,expected:Rl,actual:So(a,o)},{target:i,expected:LS,actual:So(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(u.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=u.map(g=>`${w(g.target)} is ${fg(g.actual)}, expected ${fg(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of u)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},fg=e=>`0${e.toString(8).padStart(3,"0")}`,KS=e=>{try{return re.statSync(e)}catch{return null}},HS=async()=>{let e="user override path";try{let t=await te(),r=re.existsSync(t.userProject),n=await fo(t.userProject,r),o=r?go(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}}},qS=async()=>{let e="legacy user-global config",t;try{t=await te()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=pe.join(pe.dirname(t.userGlobal),"config.json");return re.existsSync(r)?re.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"}},zS={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},YS=async e=>{let t=zS[e];try{return await cr()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},XS=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=Tt(e.config).map(s=>s.provider);if(r.length===0)return{name:t,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(r.map(s=>YS(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:t,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:t,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},gg=/^\d+\.\d+\.\d+$/,ZS=(e,t)=>e===t||!gg.test(e)||!gg.test(t)?!1:hn([`v${e}`,`v${t}`])[0]===`v${e}`,QS=async(e,t)=>{let r;try{r=await ke(e)}catch{return[]}let n=[];for(let o of r){let s=Zt(Qt(pe.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&ZS(s.version,t)&&n.push(s.version)}return n},eP=async(e,t)=>{let r=await QS(e,t);if(r.length===0)return"";let n=hn(r.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${r.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${t}) \u2014 run: infra-kit audit --fix --all`},tP=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await te()).main}catch{return e}if(!re.existsSync(t))return e;let r=pe.dirname(t),n=pe.join(r,"CLAUDE.md"),o=re.existsSync(n)?re.readFileSync(n,"utf-8"):"",s=ze(o,Ae,Ye),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await eP(r,q.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},rP=async()=>{try{let e=(await te()).main;return re.existsSync(e)?pe.dirname(e):null}catch{return null}},nP=e=>{let t=hu();return t===null||!jn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Vr}`},oP=e=>{let t=e.kind==="installed"?vs(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 ${H} version ${t}${nP(t)}`}},hg=3,yg=(e,t)=>he(e)===he(t),sP=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(yg(e.projectDir,e.gitRoot))return"";let r=In(e.gitRoot,he(e.projectDir),he)?"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 yg(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}`},iP=(e,t)=>{let r="plugin installed",n=sP(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${H} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${H} is not installed. Run: ${pt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-hg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,hg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${H} is installed for ${a} only, not this project. Run: ${pt}${n}`}},aP=()=>yt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),cP=(e,...t)=>{try{return JSON.parse(re.readFileSync(pe.join(e,...t),"utf-8"))}catch{return null}},lP=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=vs(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=cP(r,Oe),o=n!==null&&typeof n=="object"?n[Ze]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},vg=e=>`Plugin ${H} ${e===null?"(version unreadable)":e}`,dP=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${pt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${vg(e.version)} still carries an MCP server in its ${Oe}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Vr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${vg(e.version)} is skills-only \u2014 no ${Oe}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},pP=(e,t)=>{let r=qt(e===null?{}:{projectPath:e}),n=Mn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ae} is known to Claude Code`:`Marketplace ${ae} is not registered. Run: claude plugin marketplace add ${Et}`},iP(r,t),oP(r),dP(lP(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${q.version}`}]},uP=({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(", ")},mP=e=>{let t="Agent mode",r=ds(e),n=uP(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})`}},wg=4,fP=e=>{let t=e.slice(0,wg).join(", "),r=e.length-wg;return r>0?`${t} +${r} more`:t},gP=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=mg(e);if(o.length>0){let s=o.map(i=>`${i.file} allows "${i.pattern}", which reaches ${i.commands.length} mutating infra-kit command${i.commands.length===1?"":"s"} (${fP(i.commands)})`);return{name:t,status:"warn",message:`${s.join("; ")} \u2014 a prefix allow lets an agent run the --yes re-run of a mutating command unprompted; narrow it to read-only argv (e.g. Bash(infra-kit release list:*)) so the host prompts for the rest`}}return n.length>0?{name:t,status:"warn",message:`Could not read permissions.allow from ${n.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:r.length===0?{name:t,status:"pass",message:`no ${bl.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:t,status:"pass",message:`no permissions.allow pattern in ${r.join(" or ")} reaches a mutating infra-kit command`}},hP=(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`},yP=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 yf(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} (${hP(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`}},xg=e=>va(["trust"],{bin:e}),vP=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),kg="ERR_TLS_CERT_ALTNAME_INVALID",Tg=()=>`portless serving TLS on :${xt}`,wP=async(e,t,r)=>{let n=Tg();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): \`${St(t,r)}\`.`}},kP=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(xt,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(kg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${kg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>vP.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${xg(n)}\`, or reinstall: \`${St(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},bP=(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: \`${xg(r)}\` (no sudo needed).`}},RP=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 \`${va(["alias","--remove","<name>"],{bin:r})}\`.`}},Lt="portless service target",Eo=e=>({name:Lt,status:"warn",message:e}),Cg=e=>e==="darwin"?Up:e==="linux"?Gp:null,SP=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Jp}`:`sudo systemctl restart ${Kp}`,PP="/bin/ps",EP=e=>{try{let t=Sg(PP,["-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}},bg=e=>{try{return re.readFileSync(e,"utf-8")}catch{return null}},xP=e=>{try{return re.statSync(e).mtime}catch{return null}},TP=2e3,CP=e=>{try{let t=Sg(e,["-p","process.version"],{encoding:"utf-8",timeout:TP}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},$P=(e,t)=>({platform:e.platform??ot.platform,readServiceFile:e.readServiceFile??bg,readFile:e.readFile??bg,exists:e.exists??re.existsSync,realpath:e.realpath??he,mtime:e.mtime??xP,execPath:e.execPath??ot.execPath,home:e.home??Pg.homedir(),cwd:e.cwd??ot.cwd(),repoRoot:e.repoRoot??po,stateDir:(e.stateDir??qp)(),processStartTime:e.processStartTime??EP,version:e.version??ot.version,arch:e.arch??ot.arch,nodeVersionOf:e.nodeVersionOf??CP,isGlobal:e.isGlobal??ls().node.isGlobal,nodeFs:e.nodeFs??re,stableNode:null,stableNodeSidecar:null,bin:t}),xo="portless node",gr="~/.infra-kit/node",Po=e=>({row:{name:xo,status:"fail",message:e},stableNode:null,sidecar:null}),Rg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},AP=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,OP=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,IP=e=>{let t=Qp(e.home),r=Rg(e.nodeFs.lstatSync,t);if(r===void 0)return Po(`${gr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Po(`${gr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=eu(e.home,e.nodeFs);if(n===null)return Po(`${gr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Rg(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 Po(`${gr} 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(!OP(c,e))return Po(`${gr} does not run as Node ${e.version} (${AP(c)}). Re-run through the current Node: \`${St(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:xo,status:"pass",message:`${gr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},DP=e=>{if(Cg(e.platform)===null)return{row:{name:xo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=IP(e);return e.isGlobal()?t:{...t,row:{name:xo,status:"skip",message:`not a global install; the global infra-kit keeps ${gr} current`}}},$g=(e,t)=>{let r=$P(e,t),n=DP(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},NP=(e,t)=>{let r=t.readFile(pe.join(e,"package.json"));try{let n=r===null?null:fe.object({version:fe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},_P=e=>{let t=Number.parseInt(e.readFile(pe.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},MP=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},jP=(e,t,r)=>{let n=_P(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(MP(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(pe.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},FP=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:In(await t.repoRoot()??r,e,t.realpath)},hr=e=>({state:"drifted",row:e}),LP=async(e,t,r)=>{let n=St(r.bin,r);if(!r.exists(e))return hr({name:Lt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=pe.join(wa(r.home),"dist","cli.js");if(t!==o)return hr(Eo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(cs(r.home,r.exists)===null)return hr({name:Lt,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=r.realpath(wa(r.home));if(await FP(s,r))return hr({name:Lt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=VP(e,n,r);if(i!==null)return i;let a=NP(s,r),c=jP(s,a,r);return c!==null?{state:"converged",row:Eo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${SP(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Lt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},VP=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:hr(Eo(`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:hr(Eo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Ag=async e=>{let t=Cg(e.platform);if(t===null)return{state:"absent",row:{name:Lt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Lt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Fm(e.platform,r)??[];return n===void 0||o===void 0?hr(Eo(`could not parse ${t} \u2014 re-run \`${St(e.bin,e)}\` to rewrite it.`)):LP(n,o,e)},Og=async(e,t)=>{let{seams:r}=$g(e,t);return{state:(await Ag(r)).state,stableNode:r.stableNode}},BP=()=>[xo,Lt,Tg(),"portless CA chain valid","portless CA trusted","portless routes"],WP=async(e={})=>{let t=e.resolveBin??Wp,r=e.isProxyServing??Hp,n=e.handshake??Xp,o=e.caTrusted??Yp,s=e.routes??Nn,i=e.isListening??Dn,a=(e.caPath??zp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...BP().map(S=>({name:S,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:u}=$g(e,c),m=s(),g=await wP(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await kP(n,m,a,c,d);return[l,u,(await Ag(d)).row,g,y,bP(o(),a,c),await RP(m,i,c)]},JP=async(e={})=>{let t="portless routes",r=e.routes??Nn,n=e.isListening??Dn,o=e.devSessionRunning??Dm,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=Im(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??Zp().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},li=async(e={})=>{let t=await jS(),r=IS(e.probeDeps??ho()),n=async(m,g)=>{let[y,S]=await Promise.all([g,r]),v=S.get(m);return v===void 0?y:{...y,detail:v}},o=await Promise.all([n("brew",yt("brew installed",De("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",yt("git installed",De("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",yt("gh installed",De("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),yt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",yt("doppler installed",De("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",yt("aws installed",De("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")),yt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),yt("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"),DS(),Promise.resolve(NS()),Promise.resolve(_S()),MS(),Promise.resolve(FS(t)),US(),WS(t),GS(e.fix??!1),HS(),qS(),XS(t)]),s=await WP(e.portlessDeps);if(e.fix){let m=await JP(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await rP(),a=await po(),c={projectDir:ot.env.CLAUDE_PROJECT_DIR||null,cwd:ot.cwd(),gitRoot:a},l=[await aP(),...pP(i,c),mP({env:ot.env,stdinIsTTY:ot.stdin.isTTY===!0,flag:A.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:gP(a)],d=[...o,await yP(a),...s,...await tP(),...l],u={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Sc.has(m.name),detail:m.detail})),allPassed:AS(d),cliVersion:q.version};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},Sl=R({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:fe.array(fe.object({name:fe.string().describe("Name of the check"),status:fe.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:fe.string().describe("Details about the check result"),fixable:fe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:fe.object({manager:fe.string().describe("Which package manager owns this install, read from its resolved path"),version:fe.string().nullable().describe("The version the tool reported, or null"),present:fe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:fe.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:fe.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:fe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>li()});import{spawn as XP}from"node:child_process";import Tl from"node:process";import{z as V}from"zod";import{describeProxyRoutes as UP,loadDev as GP,readLocalContext as KP,slugifyHostLabel as Ig}from"@slip-stream-kit/config/internal";import Dg from"node:fs";import vn from"node:path";import Pl from"node:process";import{z as El}from"zod";var HP=async e=>{let t=vn.join(e,"apps"),r=Dg.existsSync(t)?Dg.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=vn.join(t,o,"tests"),i=await Da(s).catch(()=>{});i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},qP=(e,t)=>{let[r,n]=vn.relative(e,t).split(vn.sep);return r==="apps"&&n?n:void 0},zP=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(qP(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target, baseUrlEnv }` 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 E({status:"argument_required",argument:a,choices:El.toJSONSchema(El.object({app:El.enum(i)})),agentMode:A.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(", ")}`})},YP=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}})),xl=async(e,t={})=>{let r=t.cwd??Pl.cwd(),n=t.projectRoot??await x(),o=(t.env??Pl.env)[it]||null,s=t.healthProbe??Ku,i=zP(await HP(n),e,r,n),{target:a,baseUrlEnv:c,cloud:l}=i.e2e,[d,u]=a.split("/"),m=vn.join(n,"apps",d,u),g=(await zt(m)).name;if(!g)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${vn.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${m} has no package.json name`});let y=Hu(m),S=`${y}.${Ig(g)}.localhost`,v=KP(m),C=`https://${S}`,_=0;if(u==="ui")_=(t.listRoutes??Nn)().find(j=>j.name===S||j.name===`${y}.${Ig(g)}`)?.port??0;else{let j=v.info.get(g);_=j?.port??0,C=j?.origin??C}let O=_>0&&await s({tag:a,port:_,kind:u})==="ok",P={app:i.app,testsDir:i.testsDir,target:a,packageName:g,baseUrlEnv:c,release:y,env:o,localUrl:C};if(O){let j=u==="ui"?await GP(m):void 0,Ke=j?.proxy?UP({proxy:j.proxy,localContext:v,env:o??void 0,getRelease:()=>y}):[],xe=new Map([...v.info].map(([ha,ts])=>[ha,ts.port]));return{...P,mode:"local",baseUrl:C,routes:await YP(Ke,xe,s)}}let G=t.env??Pl.env,B=l?o&&l.replaceAll("<env>",o):G[c];if(!o||!B){let j=o?`${c} is not set (and \`e2e.cloud\` is not configured)`:`${it} is not set`;throw new f(void 0,{operation:`resolve where ${i.app}'s e2e tests run`,remediation:"start the dev server (`infra-kit dev`), or load an environment (`infra-kit env-load -c <env>`) to run against cloud",stderrExcerpt:`nothing serves ${a} at ${C}, and ${j}`})}return{...P,mode:"cloud",baseUrl:B,routes:[]}};var ZP=e=>{let t=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl} (${e.baseUrlEnv})`,e.mode==="local"?` dev server for ${e.target} on release "${e.release}"`:` nothing serves ${e.target} at ${e.localUrl}; cloud env "${e.env}" (${it})`];for(let r of e.routes){let n="";r.live!==null&&(n=r.live?" \u2014 live":" \u2014 NOT responding"),t.push(` ${r.path.padEnd(24)} ${r.source.padEnd(5)} ${r.target??"(unresolved)"}${n}`)}return t.join(`
363
+ `)},QP=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},eE=async(e,t)=>{if(e.env===null||!jt(e.env))return;let r=await(t.protectedEnvAccess??Je)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new E({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},tE=(e,t)=>new Promise((r,n)=>{let o=XP("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Tl.env,[e.baseUrlEnv]:e.baseUrl},stdio:["inherit",at.enabled||ie()?2:"inherit","inherit"]});o.once("error",n),o.once("close",s=>{r(s??1)})}),di=async(e,t={})=>{let r=await xl(e.app,t);p.info(ZP(r));let n=(t.env??Tl.env)[r.baseUrlEnv];n&&n!==r.baseUrl&&p.info(` ${r.baseUrlEnv} was ${n} in this shell; the run uses ${r.baseUrl}`),r.mode==="local"?QP(r):await eE(r,t);let o={...r,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Ng({...o,ran:!1,exitCode:null});r.mode==="cloud"&&await W(e.yes,`Run ${r.app} e2e against ${r.baseUrl} ("${r.env}", shared)?`,{plan:o});let s=await(t.runPlaywright??tE)(r,e.playwrightArgs??[]);return s!==0&&(Tl.exitCode=s),Ng({...o,ran:!0,exitCode:s})},Ng=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),rE={app:V.string(),testsDir:V.string(),target:V.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:V.string(),mode:V.enum(["local","cloud"]).describe("local: this worktree\u2019s dev server serves the target. cloud: it does not; the run uses the env-loaded baseUrlEnv, or e2e.cloud at env."),baseUrl:V.string().describe("The URL the run was pointed at, via the baseUrlEnv variable."),baseUrlEnv:V.string(),release:V.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:V.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),localUrl:V.string().describe("The local address probed, whether or not anything answered."),routes:V.array(V.object({path:V.string(),packageName:V.string(),source:V.enum(["local","cloud"]),target:V.string().nullable(),live:V.boolean().nullable()})).describe("Local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:V.array(V.string()),ran:V.boolean().describe("False for --dry-run."),exitCode:V.number().nullable().describe("Playwright\u2019s exit code; null when it did not run.")},Cl=R({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree\u2019s local dev server when it serves the target, else against the deployed app at INFRA_KIT_ENV. dryRun resolves and reports the target and the proxy topology without running. A cloud run is confirm-gated; a protected env (prod) follows protectedEnvs.",requiresHumanConfirm:!0,inputSchema:{app:V.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:V.boolean().optional(),yes:V.boolean().optional()},outputSchema:rE,handler:e=>di(e)});import $l from"node:fs";import _g from"node:path";import{z as To}from"zod";var nE=e=>[...e.map(t=>`unset ${t}`),`unset ${it}`,`unset ${Er}`,`unset ${xr}`,`unset ${ns}`,`unset ${Tr}`],pi=async()=>{let e=bt(),t=_g.join(e,kt);if(!$l.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=os(t),n=nE(r),o=_g.resolve(e,rs);$l.mkdirSync(e,{recursive:!0,mode:448}),ss(o,`${n.join(`
364
364
  `)}
365
- `,384),Tl.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Cl=R({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:Ro.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Ro.string().describe("Path to the file that must be sourced to apply"),variableCount:Ro.number().describe("Number of variables cleared"),unsetStatements:Ro.array(Ro.string()).describe("Unset statements generated")},handler:()=>li()});import XS from"node:process";import{z as Vt}from"zod";var di=(e,t,r)=>e.map(({env:n,source:o})=>({env:n,source:o,hasToken:!!(r||t[n])})),Ng=["Environment","Source","Token"],ZS=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=Ng.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(Ng),o,...t.map(n)]},pi=async()=>{let e=await We(),t=await pn(),r=await ue(),n=XS.env[de],o=di(t,r?.envs??{},n);if(p.info(`Doppler project: ${e}
366
- `),o.length===0)return p.info("No environments found."),p.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),p.info(" or add a token for one manually."),_g({project:e,envs:o});for(let s of ZS(o))p.info(s);return _g({project:e,envs:o})},_g=({project:e,envs:t})=>{let r={project:e,configs:t.map(n=>n.env),tokens:t};return{content:k(JSON.stringify(r,null,2)),structuredContent:r}},$l=R({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"),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:pi});import nE from"@inquirer/select";import{Buffer as oE}from"node:buffer";import sE from"node:fs";import iE from"node:path";import Ol from"node:process";import{z as hn}from"zod";import{$ as ui}from"zx";import Fg from"node:process";import{z as Mg}from"zod";var jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),QS=async e=>{try{return await e}catch{return[]}},eE=async e=>{let t=await ue().catch(()=>null);return di(e,t?.envs??{},Fg.env[de]).filter(r=>!r.hasToken).map(r=>r.env)},Al=()=>({get message(){return`Choose the environment to load into terminal session ${Fg.env[He]??`UNKNOWN \u2014 ${He} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>jg(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await QS(pn());if(e.length===0)return p.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await eE(e);return Mg.object({config:Mg.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:{...jg(t)?t:{},config:r}}});import{z as tE}from"zod";var rE=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return p.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},Ne=async e=>{if(!ie()||!e.provider.isFormable(e.params))return;let t=await rE(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:tE.toJSONSchema(t);throw new x({status:"argument_required",argument:o,...s===void 0?{}:{choices:s},agentMode:A.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 aE="DOPPLER_CONFIG",Lg=new Set(["DOPPLER_TOKEN",de]),Vg=!1,cE=e=>{e.length===0||Vg||(Vg=!0,p.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Wg=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!Lg.has(i));return cE(e.filter(([i])=>Lg.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${yn(a)}`),`${st}=${yn(t)}`,`${Er}=${yn(t)}`,`${xr}=${yn(r)}`,`${Zo}=${yn(n)}`,`${Tr}=${yn(o)}`,"set +a"]},lE=async()=>{try{return await S()}catch{return""}},Jg=async({config:e})=>{let t=await We(),r=await lE(),n=await uE(t,e),o=new Date().toISOString(),i=`${Wg({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
365
+ `,384),$l.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Al=R({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:To.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:To.string().describe("Path to the file that must be sourced to apply"),variableCount:To.number().describe("Number of variables cleared"),unsetStatements:To.array(To.string()).describe("Unset statements generated")},handler:()=>pi()});import oE from"node:process";import{z as Vt}from"zod";var ui=(e,t,r)=>e.map(({env:n,source:o})=>({env:n,source:o,hasToken:!!(r||t[n])})),Mg=["Environment","Source","Token"],sE=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=Mg.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(Mg),o,...t.map(n)]},mi=async()=>{let e=await We(),t=await fn(),r=await ue(),n=oE.env[de],o=ui(t,r?.envs??{},n);if(p.info(`Doppler project: ${e}
366
+ `),o.length===0)return p.info("No environments found."),p.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),p.info(" or add a token for one manually."),jg({project:e,envs:o});for(let s of sE(o))p.info(s);return jg({project:e,envs:o})},jg=({project:e,envs:t})=>{let r={project:e,configs:t.map(n=>n.env),tokens:t};return{content:k(JSON.stringify(r,null,2)),structuredContent:r}},Ol=R({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"),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:mi});import dE from"@inquirer/select";import{Buffer as pE}from"node:buffer";import uE from"node:fs";import mE from"node:path";import Dl from"node:process";import{z as wn}from"zod";import{$ as fi}from"zx";import Vg from"node:process";import{z as Fg}from"zod";var Lg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iE=async e=>{try{return await e}catch{return[]}},aE=async e=>{let t=await ue().catch(()=>null);return ui(e,t?.envs??{},Vg.env[de]).filter(r=>!r.hasToken).map(r=>r.env)},Il=()=>({get message(){return`Choose the environment to load into terminal session ${Vg.env[He]??`UNKNOWN \u2014 ${He} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>Lg(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await iE(fn());if(e.length===0)return p.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await aE(e);return Fg.object({config:Fg.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:{...Lg(t)?t:{},config:r}}});import{z as cE}from"zod";var lE=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return p.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},Ne=async e=>{if(!ie()||!e.provider.isFormable(e.params))return;let t=await lE(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:cE.toJSONSchema(t);throw new E({status:"argument_required",argument:o,...s===void 0?{}:{choices:s},agentMode:A.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 fE="DOPPLER_CONFIG",Bg=new Set(["DOPPLER_TOKEN",de]),Wg=!1,gE=e=>{e.length===0||Wg||(Wg=!0,p.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Ug=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!Bg.has(i));return gE(e.filter(([i])=>Bg.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${kn(a)}`),`${it}=${kn(t)}`,`${Er}=${kn(t)}`,`${xr}=${kn(r)}`,`${ns}=${kn(n)}`,`${Tr}=${kn(o)}`,"set +a"]},hE=async()=>{try{return await x()}catch{return""}},Gg=async({config:e})=>{let t=await We(),r=await hE(),n=await wE(t,e),o=new Date().toISOString(),i=`${Ug({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
367
367
  `)}
368
- `,a=bt(),c=iE.resolve(a,kt);return sE.mkdirSync(a,{recursive:!0,mode:448}),es(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},Ug=Al(),mi=async e=>{let{config:t}=e;await Ne({provider:Ug,params:e,operation:"env-load",argument:"config"});let r="";if(t)r=t;else{if(Q())throw new x({status:"argument_required",argument:"config",agentMode:A.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await pr();h.setInteractive(),r=await D(i=>nE({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:Ol.stderr,whenHeadless:"refuse"})}h.addOption("--config",r);let n=await Jg({config:r});h.print();let o={filePath:n.filePath,variableCount:n.variableCount,project:n.project,config:n.config,sessionId:Ol.env[He]??null};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},Bg=1024*1024,dE=3e4,pE=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],vn=(e,t=Ol.env)=>{let r={...t};for(let n of pE)delete r[n];return r.DOPPLER_TOKEN=e,r},uE=async(e,t)=>{let{token:r}=await ao(t),n=vn(r),o=ui.quiet;ui.quiet=!0;try{let s;try{s=await ui({env:n})`doppler secrets download --no-file --format json --project ${e} --config ${t}`.timeout(dE)}catch(a){throw mE(a,e,t)}fE(s.stdout);let i=gi(s.stdout);return fi(i,t),i}finally{ui.quiet=o}},fi=(e,t)=>{let r=e.find(([n])=>n===aE)?.[1];if(!(r===void 0||r===t))throw new on(t,null,`Doppler returned secrets for config "${r}" but "${t}" was requested \u2014 the service token for env "${t}" is scoped to the wrong config. Refusing to load another environment's secrets.
369
- Fix: run \`infra-kit env-token-set ${t}\` with a token scoped to "${t}".`)},mE=(e,t,r)=>{let n=$r(e)??(e instanceof Error?e.message:String(e)),o=ir(n);return o==="auth"?new on(r,ar(n)):o==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(el({kind:o,project:t,config:r,available:null}))},fE=e=>{let t=oE.byteLength(e,"utf-8");if(t>Bg)throw new Error(`doppler returned unexpectedly large output (${t} bytes > ${Bg}) \u2014 refusing to write to disk`)},yn=e=>`'${e.replaceAll("'","'\\''")}'`,gE=/^[A-Z_]\w*$/i,gi=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let r=[];for(let[n,o]of Object.entries(t)){if(!gE.test(n))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(n.slice(0,80))})`);if(typeof o!="string")throw new TypeError(`doppler returned a non-string value for "${n}" (got ${typeof o})`);r.push([n,o])}if(r.length===0)throw new Error("doppler returned empty output for env-load");return r},Dl=R({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.',inputSchema:{config:hn.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Ug,outputSchema:{filePath:hn.string().describe("Path to the file that must be sourced to apply variables"),variableCount:hn.number().describe("Number of variables loaded"),project:hn.string().describe("Doppler project name"),config:hn.string().describe("Doppler config name"),sessionId:hn.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:mi});import hE from"node:path";import Po from"node:process";import{z as wn}from"zod";var hi=async()=>{p.info("Environment session status:");let e=bt(),t=Po.env[He],r=hE.join(e,kt),n=0,o=0,s=Po.env[Er]??null,i=Po.env[xr]??null,a=Po.env[Tr]??null;if(s){let l=Qo(r);l.length>0&&(o=l.length,n=l.filter(u=>u in Po.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(p.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
368
+ `,a=bt(),c=mE.resolve(a,kt);return uE.mkdirSync(a,{recursive:!0,mode:448}),ss(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},Kg=Il(),gi=async e=>{let{config:t}=e;await Ne({provider:Kg,params:e,operation:"env-load",argument:"config"});let r="";if(t)r=t;else{if(ee())throw new E({status:"argument_required",argument:"config",agentMode:A.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await pr();h.setInteractive(),r=await I(i=>dE({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:Dl.stderr,whenHeadless:"refuse"})}h.addOption("--config",r);let n=await Gg({config:r});h.print();let o={filePath:n.filePath,variableCount:n.variableCount,project:n.project,config:n.config,sessionId:Dl.env[He]??null};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},Jg=1024*1024,yE=3e4,vE=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],bn=(e,t=Dl.env)=>{let r={...t};for(let n of vE)delete r[n];return r.DOPPLER_TOKEN=e,r},wE=async(e,t)=>{let{token:r}=await mo(t),n=bn(r),o=fi.quiet;fi.quiet=!0;try{let s;try{s=await fi({env:n})`doppler secrets download --no-file --format json --project ${e} --config ${t}`.timeout(yE)}catch(a){throw kE(a,e,t)}bE(s.stdout);let i=yi(s.stdout);return hi(i,t),i}finally{fi.quiet=o}},hi=(e,t)=>{let r=e.find(([n])=>n===fE)?.[1];if(!(r===void 0||r===t))throw new cn(t,null,`Doppler returned secrets for config "${r}" but "${t}" was requested \u2014 the service token for env "${t}" is scoped to the wrong config. Refusing to load another environment's secrets.
369
+ Fix: run \`infra-kit env-token-set ${t}\` with a token scoped to "${t}".`)},kE=(e,t,r)=>{let n=$r(e)??(e instanceof Error?e.message:String(e)),o=ir(n);return o==="auth"?new cn(r,ar(n)):o==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(rl({kind:o,project:t,config:r,available:null}))},bE=e=>{let t=pE.byteLength(e,"utf-8");if(t>Jg)throw new Error(`doppler returned unexpectedly large output (${t} bytes > ${Jg}) \u2014 refusing to write to disk`)},kn=e=>`'${e.replaceAll("'","'\\''")}'`,RE=/^[A-Z_]\w*$/i,yi=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let r=[];for(let[n,o]of Object.entries(t)){if(!RE.test(n))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(n.slice(0,80))})`);if(typeof o!="string")throw new TypeError(`doppler returned a non-string value for "${n}" (got ${typeof o})`);r.push([n,o])}if(r.length===0)throw new Error("doppler returned empty output for env-load");return r},Nl=R({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.',inputSchema:{config:wn.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Kg,outputSchema:{filePath:wn.string().describe("Path to the file that must be sourced to apply variables"),variableCount:wn.number().describe("Number of variables loaded"),project:wn.string().describe("Doppler project name"),config:wn.string().describe("Doppler config name"),sessionId:wn.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:gi});import SE from"node:path";import Co from"node:process";import{z as Rn}from"zod";var vi=async()=>{p.info("Environment session status:");let e=bt(),t=Co.env[He],r=SE.join(e,kt),n=0,o=0,s=Co.env[Er]??null,i=Co.env[xr]??null,a=Co.env[Tr]??null;if(s){let l=os(r);l.length>0&&(o=l.length,n=l.filter(u=>u in Co.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(p.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
370
370
  `),o>0&&n<o){let u=o-n;p.warn(` ${u} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else p.info(` Session ${t}: no env loaded
371
- `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Il=R({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:wn.string().describe("Current terminal session ID"),sessionLoadedCount:wn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:wn.number().describe("Total number of cached var names"),sessionConfig:wn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:wn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:wn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:hi});import yE from"node:process";import{z as Bt}from"zod";var Gg="****",kn=e=>typeof e!="string"||e.length<8?Gg:`${Gg}${e.slice(-4)}`;var Kg=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${de}`:"store",redactedToken:kn(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),vE=["ENV","SOURCE","TOKEN","PRESENT"],Hg=(e,t)=>{let r=[...vE,...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())},yi=async({check:e}={})=>{let t=await pr(),r=await ue(),n=yE.env[de],o=Kg(t,r?.envs??{},n);if(e){let a=await We();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await tl({childEnv:vn(l),project:a,config:c.env});c.status=d.outcome}}for(let a of Hg(o,!!e))p.info(a);let s=o.filter(a=>!a.present);s.length>0&&p.info(`
372
- No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},Nl=R({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:Bt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Bt.array(Bt.object({env:Bt.string().describe("Environment / Doppler config name"),source:Bt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Bt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Bt.boolean().describe("Whether a token is configured for this environment"),status:Bt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:yi});import{z as b}from"zod";import{$ as wE}from"zx";var kE=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),bE=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,RE=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(", ")},Ml=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),_l=new Set(["up-to-date","fast-forward","merged"]),PE=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=Te(ve(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},SE={"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"},zg=e=>{let t=SE[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},EE=(e,t)=>{p.info(`
373
- \u{1F4CB} Merge plan:`);for(let r of e)p.info(` ${r.branch} \u2014 ${zg(r)}`);for(let r of t)p.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},xE=(e,t)=>{let r=t.find(n=>n.branch===e);return r?`git -C ${r.path} merge origin/dev`:`git switch ${e} && git merge origin/dev`},TE=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=K(i.branch);return a?[[ne(a),zg(i)]]:[]}));return Nt(se({branches:r,descriptions:s}),{required:!0})},CE=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let P of y)p.info(`\u2139\uFE0F ${P} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await no(t,Xm(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){p.info(`
374
- \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await Qm({worktreePath:r,refs:l,command:s});d=y.failed;for(let[v,C]of y.failed)p.info(`\u2717 ${v} failed verification \u2014 not pushing it. ${C.split(`
375
- `)[0]??""}`);let P=await no(t,y.kept);a(P.nowUpToDate),l=P.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};p.info(`
376
- \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let u=await ds(t,l);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Or(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&p.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
377
- `)[0],observedLanded:g.map(y=>y.branch)}},$E=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},qg=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
378
- `)[0];p.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=>!_l.has(i.status));return Ml({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},AE=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Le();if(e.abort)return qg(await Ef({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return qg(await Pf({cwd:s,versions:r,all:t,verify:i,trees:Sf(e.tree),confirmedCommand:o}))},vi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;$E(e);let a=o===!0?Zm:o||void 0;if(await Pc({operation:"merge dev into release branches"}),e.continue||e.abort)return AE(e);let c=[],l=[];for(let B of await F()){let j=bE(B);j?l.push({branch:B.branch,reason:j}):c.push(B.branch)}if(c.length===0)return p.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${RE(l)})`),h.print(),Ml(kE(n,l));let d=await Le();try{await wE({cwd:d,quiet:!0})`git fetch origin --prune`}catch(B){throw new f(B,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let u=r===void 0?c:PE(r,c,l),m=await mu({cwd:d},async B=>{let j=Vs(B.remove);try{return await OE({cwd:d,worktree:B,toPlan:u,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{j()}}),{entries:g,selected:y,pushed:P,pushAborted:v,abortedBy:C,declined:_,verifyFailed:O,handOffs:E}=m,G=await St(d).catch(()=>[]);return NE({entries:g,selected:y,pushed:P,pushAborted:v,abortedBy:C,declined:_,verifyFailed:O,handOffs:E,dryRun:n,worktrees:G,skipped:l})},OE=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:u}=e,m=d?await $e(t,"origin/dev"):null,g=await Ym({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(EE(g,s),c)return{...y,selected:n};let P=await TE({entries:g,toPlan:n,all:i,explicit:a!==void 0});P.length===o.length?h.addOption("--all",!0):h.addOption("--versions",P);let v=g.filter(E=>P.includes(E.branch)&&E.mergeSha).length;v>0&&p.info(`
379
- \u2139\uFE0F This will push ${v} branch(es), re-running CI on ${v} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await W(u,`Are you sure you want to merge dev into these branches: ${P.join(", ")}?`,{throwOnDecline:!0,plan:DE(g,P,s)})}catch(E){if(!at(E))throw E;return{...y,selected:P,declined:!0}}u||h.addOption("--yes",!0);let C=await CE({cwd:t,worktreePath:r.path,entries:g,selected:P,verify:l}),_=g.filter(E=>P.includes(E.branch)&&E.status==="conflict").map(E=>E.branch),O=d&&m&&_.length>0?await kf({cwd:t,branches:_,devSha:m}):void 0;return{entries:g,selected:P,declined:!1,...C,handOffs:O}},DE=(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:Fc(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),IE=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
371
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},_l=R({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:Rn.string().describe("Current terminal session ID"),sessionLoadedCount:Rn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Rn.number().describe("Total number of cached var names"),sessionConfig:Rn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Rn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Rn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:vi});import PE from"node:process";import{z as Bt}from"zod";var Hg="****",Sn=e=>typeof e!="string"||e.length<8?Hg:`${Hg}${e.slice(-4)}`;var qg=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${de}`:"store",redactedToken:Sn(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),EE=["ENV","SOURCE","TOKEN","PRESENT"],zg=(e,t)=>{let r=[...EE,...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())},wi=async({check:e}={})=>{let t=await pr(),r=await ue(),n=PE.env[de],o=qg(t,r?.envs??{},n);if(e){let a=await We();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await nl({childEnv:bn(l),project:a,config:c.env});c.status=d.outcome}}for(let a of zg(o,!!e))p.info(a);let s=o.filter(a=>!a.present);s.length>0&&p.info(`
372
+ No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},Ml=R({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:Bt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Bt.array(Bt.object({env:Bt.string().describe("Environment / Doppler config name"),source:Bt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Bt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Bt.boolean().describe("Whether a token is configured for this environment"),status:Bt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:wi});import{z as b}from"zod";import{$ as xE}from"zx";var TE=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),CE=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,$E=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(", ")},Fl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),jl=new Set(["up-to-date","fast-forward","merged"]),AE=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=Te(ve(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},OE={"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"},Xg=e=>{let t=OE[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},IE=(e,t)=>{p.info(`
373
+ \u{1F4CB} Merge plan:`);for(let r of e)p.info(` ${r.branch} \u2014 ${Xg(r)}`);for(let r of t)p.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},DE=(e,t)=>{let r=t.find(n=>n.branch===e);return r?`git -C ${r.path} merge origin/dev`:`git switch ${e} && git merge origin/dev`},NE=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=K(i.branch);return a?[[ne(a),Xg(i)]]:[]}));return Nt(se({branches:r,descriptions:s}),{required:!0})},_E=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let S of y)p.info(`\u2139\uFE0F ${S} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await ao(t,ef(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){p.info(`
374
+ \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await rf({worktreePath:r,refs:l,command:s});d=y.failed;for(let[v,C]of y.failed)p.info(`\u2717 ${v} failed verification \u2014 not pushing it. ${C.split(`
375
+ `)[0]??""}`);let S=await ao(t,y.kept);a(S.nowUpToDate),l=S.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};p.info(`
376
+ \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let u=await gs(t,l);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Or(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&p.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
377
+ `)[0],observedLanded:g.map(y=>y.branch)}},ME=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Yg=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
378
+ `)[0];p.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=>!jl.has(i.status));return Fl({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},jE=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Le();if(e.abort)return Yg(await Tf({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Yg(await Ef({cwd:s,versions:r,all:t,verify:i,trees:xf(e.tree),confirmedCommand:o}))},ki=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;ME(e);let a=o===!0?tf:o||void 0;if(await Ec({operation:"merge dev into release branches"}),e.continue||e.abort)return jE(e);let c=[],l=[];for(let B of await F()){let j=CE(B);j?l.push({branch:B.branch,reason:j}):c.push(B.branch)}if(c.length===0)return p.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${$E(l)})`),h.print(),Fl(TE(n,l));let d=await Le();try{await xE({cwd:d,quiet:!0})`git fetch origin --prune`}catch(B){throw new f(B,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let u=r===void 0?c:AE(r,c,l),m=await gu({cwd:d},async B=>{let j=Gs(B.remove);try{return await FE({cwd:d,worktree:B,toPlan:u,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{j()}}),{entries:g,selected:y,pushed:S,pushAborted:v,abortedBy:C,declined:_,verifyFailed:O,handOffs:P}=m,G=await Pt(d).catch(()=>[]);return BE({entries:g,selected:y,pushed:S,pushAborted:v,abortedBy:C,declined:_,verifyFailed:O,handOffs:P,dryRun:n,worktrees:G,skipped:l})},FE=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:u}=e,m=d?await $e(t,"origin/dev"):null,g=await Qm({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(IE(g,s),c)return{...y,selected:n};let S=await NE({entries:g,toPlan:n,all:i,explicit:a!==void 0});S.length===o.length?h.addOption("--all",!0):h.addOption("--versions",S);let v=g.filter(P=>S.includes(P.branch)&&P.mergeSha).length;v>0&&p.info(`
379
+ \u2139\uFE0F This will push ${v} branch(es), re-running CI on ${v} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await W(u,`Are you sure you want to merge dev into these branches: ${S.join(", ")}?`,{throwOnDecline:!0,plan:LE(g,S,s)})}catch(P){if(!ct(P))throw P;return{...y,selected:S,declined:!0}}u||h.addOption("--yes",!0);let C=await _E({cwd:t,worktreePath:r.path,entries:g,selected:S,verify:l}),_=g.filter(P=>S.includes(P.branch)&&P.status==="conflict").map(P=>P.branch),O=d&&m&&_.length>0?await Rf({cwd:t,branches:_,devSha:m}):void 0;return{entries:g,selected:S,declined:!1,...C,handOffs:O}},LE=(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:Vc(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),VE=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
380
380
  `:`# ${e.branch} \u2014 ${e.status}
381
- ${xE(e.branch,t)}
382
- `,NE=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:u}=e,m=new Set(n?t.filter(v=>r.includes(v.branch)&&v.mergeSha&&!l?.has(v.branch)).map(v=>v.branch):[]),g=t.filter(v=>r.includes(v.branch)).map(v=>{let C=!!v.mergeSha,_=e.verifyFailed?.get(v.branch),O=o&&C?"push-aborted":v.status,E=_?"verify-failed":O,G=d?.get(v.branch);return{branch:v.branch,status:E,mergeSha:v.mergeSha,conflictPaths:v.conflictPaths,pushed:m.has(v.branch),reason:_??G?.reason??v.reason,...G?.resolution?{resolution:G.resolution}:{}}}),y=g.filter(v=>!_l.has(v.status));for(let v of g){let C=t.find(_=>_.branch===v.branch);p.info({branch:v.branch,status:v.status,mergeSha:v.mergeSha,conflictCount:v.conflictPaths?.length??0,durationMs:C?.durationMs,pushed:v.pushed,msg:"merge-dev branch result"})}if(i||a)p.info(i?`
381
+ ${DE(e.branch,t)}
382
+ `,BE=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:u}=e,m=new Set(n?t.filter(v=>r.includes(v.branch)&&v.mergeSha&&!l?.has(v.branch)).map(v=>v.branch):[]),g=t.filter(v=>r.includes(v.branch)).map(v=>{let C=!!v.mergeSha,_=e.verifyFailed?.get(v.branch),O=o&&C?"push-aborted":v.status,P=_?"verify-failed":O,G=d?.get(v.branch);return{branch:v.branch,status:P,mergeSha:v.mergeSha,conflictPaths:v.conflictPaths,pushed:m.has(v.branch),reason:_??G?.reason??v.reason,...G?.resolution?{resolution:G.resolution}:{}}}),y=g.filter(v=>!jl.has(v.status));for(let v of g){let C=t.find(_=>_.branch===v.branch);p.info({branch:v.branch,status:v.status,mergeSha:v.mergeSha,conflictCount:v.conflictPaths?.length??0,durationMs:C?.durationMs,pushed:v.pushed,msg:"merge-dev branch result"})}if(i||a)p.info(i?`
383
383
  Operation cancelled \u2014 nothing was pushed.
384
384
  `:`
385
385
  \u{1F50D} Dry run \u2014 nothing was pushed.
386
386
  `);else if(y.length>0){p.info(`
387
387
  \u26A0\uFE0F ${y.length} branch(es) did not merge.
388
- `);for(let v of y)p.info(IE(v,c))}else p.info(`\u2705 All merges completed successfully!
389
- `);h.print();let P=a||i;return Ml({successfulMerges:P?0:g.filter(v=>_l.has(v.status)).length,failedMerges:P?0:y.length,failedBranches:P?[]:y.map(v=>v.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(v=>P?{...v,pushed:!1}:v),skipped:u})},jl=R({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:b.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:b.union([b.string(),b.array(b.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:vi});import{z as To}from"zod";import{$ as _e}from"zx";var Yg=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Wt=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=Yg(t.stderr,500);o&&(r.stderr=o);let s=Yg(t.stdout,200);return s&&(r.stdout=s),r};var So=e=>{let{removed:t,failed:r}=e;if(t.length>0){p.info("\u274C Removed worktrees:");for(let n of t)p.info(n);p.info("")}if(r.length>0){p.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)p.warn(`${n} \u2014 ${o}`);p.warn("")}t.length===0&&r.length===0&&p.info("\u2139\uFE0F No worktrees to remove")};var Eo=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=k(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw Q()?new x({status:"partial_failure",...n},1,s):new f(void 0,s)};import ki from"node:fs/promises";import{$ as eh}from"zx";var _E=new Set([".omc",".DS_Store"]),ME=new Set(["state","sessions"]),jE=2e3,FE="check 'git worktree list' for the path; uncommitted changes block removal",LE=e=>new Promise(t=>{setTimeout(t,e)}),Fl=e=>typeof e=="object"&&e!==null?e.code:void 0,Xg=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Zg=async e=>{try{return Xg(await ki.realpath(e))}catch{return Xg(e)}},VE=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await St(t),o=await Zg(r);for(let s of n)if(await Zg(s.path)===o)return!0;return!1}catch{return!0}},BE=async e=>{let t;try{t=await ki.readdir(e)}catch(n){return{kind:Fl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>_E.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await ki.readdir(`${e}/.omc`)).every(s=>ME.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Fl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Qg=async e=>{try{return await ki.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Fl(t)==="ENOTEMPTY"?"busy":"failed"}},WE=async e=>{let{worktreePath:t,sleep:r}=e,n=await Qg(t);return n!=="busy"?n==="removed":(await r(jE),await Qg(t)==="removed")},wi=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return p.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},JE=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await VE({projectRoot:n,worktreePath:r}))return wi(t,o,FE);let i=await BE(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 WE({worktreePath:r,sleep:s})?wi(t,o,a):(p.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"})},UE=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await Mu(i,o);if(!a.closed&&"error"in a)return wi(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await eh`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return JE({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},yr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=LE}=e,i=t.length>0?await Dr():"unreachable",a=await Promise.all(t.map(l=>UE({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 eh`git worktree prune`,c};var xo=async(e,t)=>{if(!(await Ce("release")).includes(e))return[];let n=await S(),o=`${n}${ge}`,{removed:s,failed:i}=await yr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var bn=async(e,t,r)=>{try{return await r()}catch(n){throw p.debug({err:Wt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},GE=async e=>{let t=va(e),r=await _e`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},th=async()=>{let e=await _e`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},KE=async e=>{let t=mt(e),r=await xc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await Gr(t);if(!n)throw p.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=Xn(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},HE=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await oe(),o=await It(se({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw p.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},qE=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Qe(r),s=await Tc(n);if(s.state==="MERGED"){p.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await bn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin --delete-branch`})},zE=async e=>{let t=Y(e),r=va(e),n=await th();if(n){let s=n.number;return n.title!==r&&(p.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await bn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await _e`gh pr edit ${s} --title ${r}`})),s}await bn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await _e`gh pr create --base main --head dev --title ${r} --body ""`});let o=await th();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},YE=async e=>{let t=Y(e);if(await GE(e)){p.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await zE(e);await bn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin`})},XE=async()=>{_e.quiet=!1,await bn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await _e`gh workflow run deploy-all.yml --ref main -f environment=prod`}),_e.quiet=!0},ZE=async()=>{await bn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await _e`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},QE=async e=>{try{await cs(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ls(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},ex=async e=>{let t=await ut();if(!t){p.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await $c({versionName:r},t)}catch(r){let n=Qn(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";p.error({err:Wt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},bi=async e=>{let{version:t,confirmedCommand:r}=e;await be({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await KE(t):await HE(),i=K(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=Y(i);if(h.addOption("--version",a),p.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),Q())throw new x({status:"refused",agentMode:A.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await W(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),_e.quiet=!0;let l=`${await S()}${ge}`;await xo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await qE({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await YE(i),await XE(),await ZE(),await QE(n),_e.quiet=!1,await ex(i),p.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Ll=R({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:To.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:To.string().describe("The release branch that was delivered"),version:To.string().describe("The version that was delivered"),type:To.enum(["regular","hotfix"]).describe("Release type"),success:To.boolean().describe("Whether the delivery was successful")},handler:bi});import{z as vt}from"zod";import{$ as zl}from"zx";import{z as Ao}from"zod";import rh from"node:fs/promises";import Vl from"node:path";var nh=".github/workflows",tx=/script_name:\s*(?<service>[a-z0-9-]+)/,rx=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,nx=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Bl=async e=>{let t=Vl.resolve(e,nh),r;try{r=await rh.readdir(t)}catch{return new Map}return oh(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Co=async(e,t)=>oh(Vl.resolve(e,nh),[t]),oh=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await rh.readFile(Vl.resolve(e,n),"utf-8")}catch{continue}ox(o,r)}return r},ox=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=tx.exec(r)?.groups?.service??rx.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(nx)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},Wl=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import sx from"node:fs/promises";import ix from"node:path";import ax from"yaml";var cx=".github/workflows",lx="skip_terraform_deploy",$o=async(e,t)=>{let r=ix.resolve(e,cx,t),n;try{n=ax.parse(await sx.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!==lx).map(([i])=>i)};var sh="dev",Jl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ih=(e,t)=>e[t]===void 0,ah=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Ul=async e=>{try{return await e}catch{return[]}},dx=async()=>{let e=await F();return nr(e.map(t=>t.branch))},px=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},vr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(p.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Ul(dx());if(l.length===0)return null;let d=ah(c,"version");return Ao.enum([...new Set([...l,sh])]).optional().describe(`Which release to deploy from. "${sh}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=gt(await Ul(ht(t)),await Je());if(l.length===0)return null;let d=l.filter(ln),u=l.filter(g=>!ln(g)),m=ah(c,"env");return Ao.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${u.length>0?u.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 S(),l=await Ul($o(c,t));if(l.length===0)return null;let d=await Co(c,t);return Ao.array(Ao.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${px(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Jl(c)?r.some(l=>ih(c,l)):!1,buildRequestedSchema:async c=>{let l=Jl(c)?c:{},d={};if(r.includes("version")){let u=await s(l);if(u===null)return o("releases");d.version=u}if(r.includes("env")){let u=await i(l);if(u===null)return o("envs");d.env=u}if(r.includes("services")&&ih(l,"services")){let u=await a();if(u===null)return o("services");d.services=u}return Object.keys(d).length===0?o("fields"):Ao.object(d)},toArgs:(c,l)=>{let d={...Jl(l)?l:{}};for(let u of r){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;d[u]=m}}return d}}};import ux from"@inquirer/select";var Rn=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return D(r=>ux({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import mx from"@inquirer/confirm";var Oo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ie()&&fs(o,{branch:r,env:n}),h.setInteractive();let s=await D(i=>mx({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import fx from"@inquirer/select";import gx from"node:process";var Gl=()=>!ie()&&gx.stdin.isTTY===!0,hx={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Kl=async()=>D(e=>fx({message:"\u{1F680} Where should this deploy run?",choices:Jt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:hx[t]}))},e),{whenHeadless:"refuse"});var Jt=["ci","local"],yx={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},ch=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Jt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ie()?new x({status:"argument_required",argument:"from",agentMode:A.source},2,r):new f(void 0,r)}let t=Jt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Jt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Hl=(e,t)=>{let n=yx[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},ql=async e=>e||!Gl()?ch(e):Kl();var Do=async e=>{if(e)return e==="dev"?"dev":mt(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await oe();return It([{value:"dev",label:"dev"},...se({branches:r,descriptions:o,types:n})])};var lh="deploy-all.yml",dh=vr({workflowFile:lh,fields:["version","env"],toolName:"gh-release-deploy-all"}),Ri=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Ne({provider:dh,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await Do(t),i=ro(s);h.addOption("--version",i);let a=await Je(),c=gt(await ht(lh),a),l="";r?l=r:(h.setInteractive(),l=await Rn(c,"launch deploy-all workflow")),h.addOption("--env",l),dr(l,"launch deploy-all workflow",a),fo({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await Oo({confirmedCommand:o,branch:s,env:l})){p.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}try{zl.quiet=!0,await zl`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,zl.quiet=!1,p.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw p.error({error:u},"\u274C Error launching workflow"),new f(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Yl=R({name:"gh-release-deploy-all",formProvider:dh,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:vt.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:vt.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:vt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:vt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:vt.string().describe("The release branch that was deployed"),version:vt.string().describe("The version that was deployed"),environment:vt.string().describe("The environment deployed to"),skipTerraformDeploy:vt.boolean().describe("Whether terraform deployment was skipped"),success:vt.boolean().describe("Whether the deployment was successful")},handler:Ri});import vx from"@inquirer/checkbox";import{z as Pe}from"zod";import{$ as Xl}from"zx";var wr="deploy-selected-services.yml",ph=vr({workflowFile:wr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Pi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ne({provider:ph,params:e,operation:"launch deploy-selected workflow",argument:O=>O[0]??"version"});let i=await Do(t),a=ro(i);h.addOption("--version",a);let c=await Je(),l=gt(await ht(wr),c),d="";r?d=r:(h.setInteractive(),d=await Rn(l,"launch deploy-selected workflow")),h.addOption("--env",d),dr(d,"launch deploy-selected workflow",c),fo({env:d,branch:i});let u=await S(),m=await $o(u,wr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${wr}`,stderrExcerpt:`no services found in .github/workflows/${wr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await D(O=>vx({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(E=>({name:E,value:E}))},O),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(O=>!m.includes(O));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let P=await Co(u,wr),v=g.filter(O=>{let E=P.get(O);return E!==void 0&&!E.includes(d)});if(v.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:v.map(O=>`${O} deploys only to: ${(P.get(O)??[]).join(", ")}`).join("; "),stderrExcerpt:`${wr} gates these services out of ${d}: ${v.join(", ")}`});let C=o??!1;C&&h.addOption("--skip-terraform",!0);let _=O=>{let E={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:C,success:O};return{content:k(JSON.stringify(E,null,2)),structuredContent:E}};if(!await Oo({confirmedCommand:s,branch:i,env:d}))return p.info("Deployment cancelled"),_(!1);try{Xl.quiet=!0;let O=g.flatMap(G=>["-f",`${G}=true`]);return await Xl`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${O} ${C?["-f","skip_terraform_deploy=true"]:[]}`,Xl.quiet=!1,p.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),_(!0)}catch(O){throw p.error({error:O},"\u274C Error launching workflow"),new f(O,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Zl=R({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:ph,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:Pe.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:Pe.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:Pe.array(Pe.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:Pe.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Pe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Pe.string().describe("The release branch that was deployed"),version:Pe.string().describe("The version that was deployed"),environment:Pe.string().describe("The environment deployed to"),services:Pe.array(Pe.string()).describe("The services that were deployed"),skipTerraformDeploy:Pe.boolean().describe("Whether terraform deployment was skipped"),success:Pe.boolean().describe("Whether the deployment was successful")},handler:Pi});import{z as Ut}from"zod";var Si=async()=>{let t=(await F()).flatMap(i=>{let a=K(i.branch);return a?[{version:Y(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await js(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=to(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",u=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${u}`});p.info(`All release branches:
388
+ `);for(let v of y)p.info(VE(v,c))}else p.info(`\u2705 All merges completed successfully!
389
+ `);h.print();let S=a||i;return Fl({successfulMerges:S?0:g.filter(v=>jl.has(v.status)).length,failedMerges:S?0:y.length,failedBranches:S?[]:y.map(v=>v.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(v=>S?{...v,pushed:!1}:v),skipped:u})},Ll=R({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:b.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:b.union([b.string(),b.array(b.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:ki});import{z as Io}from"zod";import{$ as _e}from"zx";var Zg=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Wt=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=Zg(t.stderr,500);o&&(r.stderr=o);let s=Zg(t.stdout,200);return s&&(r.stdout=s),r};var $o=e=>{let{removed:t,failed:r}=e;if(t.length>0){p.info("\u274C Removed worktrees:");for(let n of t)p.info(n);p.info("")}if(r.length>0){p.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)p.warn(`${n} \u2014 ${o}`);p.warn("")}t.length===0&&r.length===0&&p.info("\u2139\uFE0F No worktrees to remove")};var Ao=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=k(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw ee()?new E({status:"partial_failure",...n},1,s):new f(void 0,s)};import Ri from"node:fs/promises";import{$ as rh}from"zx";var WE=new Set([".omc",".DS_Store"]),JE=new Set(["state","sessions"]),UE=2e3,GE="check 'git worktree list' for the path; uncommitted changes block removal",KE=e=>new Promise(t=>{setTimeout(t,e)}),Vl=e=>typeof e=="object"&&e!==null?e.code:void 0,Qg=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},eh=async e=>{try{return Qg(await Ri.realpath(e))}catch{return Qg(e)}},HE=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await Pt(t),o=await eh(r);for(let s of n)if(await eh(s.path)===o)return!0;return!1}catch{return!0}},qE=async e=>{let t;try{t=await Ri.readdir(e)}catch(n){return{kind:Vl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>WE.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Ri.readdir(`${e}/.omc`)).every(s=>JE.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Vl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},th=async e=>{try{return await Ri.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Vl(t)==="ENOTEMPTY"?"busy":"failed"}},zE=async e=>{let{worktreePath:t,sleep:r}=e,n=await th(t);return n!=="busy"?n==="removed":(await r(UE),await th(t)==="removed")},bi=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return p.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},YE=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await HE({projectRoot:n,worktreePath:r}))return bi(t,o,GE);let i=await qE(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 zE({worktreePath:r,sleep:s})?bi(t,o,a):(p.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"})},XE=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await Lu(i,o);if(!a.closed&&"error"in a)return bi(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await rh`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return YE({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},yr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=KE}=e,i=t.length>0?await Ir():"unreachable",a=await Promise.all(t.map(l=>XE({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 rh`git worktree prune`,c};var Oo=async(e,t)=>{if(!(await Ce("release")).includes(e))return[];let n=await x(),o=`${n}${ge}`,{removed:s,failed:i}=await yr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Pn=async(e,t,r)=>{try{return await r()}catch(n){throw p.debug({err:Wt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},ZE=async e=>{let t=ka(e),r=await _e`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},nh=async()=>{let e=await _e`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},QE=async e=>{let t=ft(e),r=await Cc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await Gr(t);if(!n)throw p.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=to(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},ex=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await oe(),o=await Dt(se({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw p.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},tx=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Qe(r),s=await $c(n);if(s.state==="MERGED"){p.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await Pn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin --delete-branch`})},rx=async e=>{let t=Y(e),r=ka(e),n=await nh();if(n){let s=n.number;return n.title!==r&&(p.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Pn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await _e`gh pr edit ${s} --title ${r}`})),s}await Pn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await _e`gh pr create --base main --head dev --title ${r} --body ""`});let o=await nh();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},nx=async e=>{let t=Y(e);if(await ZE(e)){p.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await rx(e);await Pn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin`})},ox=async()=>{_e.quiet=!1,await Pn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await _e`gh workflow run deploy-all.yml --ref main -f environment=prod`}),_e.quiet=!0},sx=async()=>{await Pn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await _e`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},ix=async e=>{try{await ms(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await fs(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},ax=async e=>{let t=await mt();if(!t){p.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await Oc({versionName:r},t)}catch(r){let n=no(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";p.error({err:Wt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Si=async e=>{let{version:t,confirmedCommand:r}=e;await be({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await QE(t):await ex(),i=K(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=Y(i);if(h.addOption("--version",a),p.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ee())throw new E({status:"refused",agentMode:A.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await W(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),_e.quiet=!0;let l=`${await x()}${ge}`;await Oo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await tx({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await nx(i),await ox(),await sx(),await ix(n),_e.quiet=!1,await ax(i),p.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Bl=R({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:Io.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:Io.string().describe("The release branch that was delivered"),version:Io.string().describe("The version that was delivered"),type:Io.enum(["regular","hotfix"]).describe("Release type"),success:Io.boolean().describe("Whether the delivery was successful")},handler:Si});import{z as vt}from"zod";import{$ as Xl}from"zx";import{z as _o}from"zod";import oh from"node:fs/promises";import Wl from"node:path";var sh=".github/workflows",cx=/script_name:\s*(?<service>[a-z0-9-]+)/,lx=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,dx=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Jl=async e=>{let t=Wl.resolve(e,sh),r;try{r=await oh.readdir(t)}catch{return new Map}return ih(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Do=async(e,t)=>ih(Wl.resolve(e,sh),[t]),ih=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await oh.readFile(Wl.resolve(e,n),"utf-8")}catch{continue}px(o,r)}return r},px=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=cx.exec(r)?.groups?.service??lx.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(dx)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},Ul=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import ux from"node:fs/promises";import mx from"node:path";import fx from"yaml";var gx=".github/workflows",hx="skip_terraform_deploy",No=async(e,t)=>{let r=mx.resolve(e,gx,t),n;try{n=fx.parse(await ux.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!==hx).map(([i])=>i)};var ah="dev",Gl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ch=(e,t)=>e[t]===void 0,lh=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Kl=async e=>{try{return await e}catch{return[]}},yx=async()=>{let e=await F();return nr(e.map(t=>t.branch))},vx=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},vr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(p.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Kl(yx());if(l.length===0)return null;let d=lh(c,"version");return _o.enum([...new Set([...l,ah])]).optional().describe(`Which release to deploy from. "${ah}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=gt(await Kl(ht(t)),await Je());if(l.length===0)return null;let d=l.filter(un),u=l.filter(g=>!un(g)),m=lh(c,"env");return _o.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${u.length>0?u.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 x(),l=await Kl(No(c,t));if(l.length===0)return null;let d=await Do(c,t);return _o.array(_o.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${vx(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Gl(c)?r.some(l=>ch(c,l)):!1,buildRequestedSchema:async c=>{let l=Gl(c)?c:{},d={};if(r.includes("version")){let u=await s(l);if(u===null)return o("releases");d.version=u}if(r.includes("env")){let u=await i(l);if(u===null)return o("envs");d.env=u}if(r.includes("services")&&ch(l,"services")){let u=await a();if(u===null)return o("services");d.services=u}return Object.keys(d).length===0?o("fields"):_o.object(d)},toArgs:(c,l)=>{let d={...Gl(l)?l:{}};for(let u of r){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;d[u]=m}}return d}}};import wx from"@inquirer/select";var En=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return I(r=>wx({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import kx from"@inquirer/confirm";var Mo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ie()&&ws(o,{branch:r,env:n}),h.setInteractive();let s=await I(i=>kx({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import bx from"@inquirer/select";import Rx from"node:process";var Hl=()=>!ie()&&Rx.stdin.isTTY===!0,Sx={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},ql=async()=>I(e=>bx({message:"\u{1F680} Where should this deploy run?",choices:Jt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:Sx[t]}))},e),{whenHeadless:"refuse"});var Jt=["ci","local"],Px={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},dh=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Jt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ie()?new E({status:"argument_required",argument:"from",agentMode:A.source},2,r):new f(void 0,r)}let t=Jt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Jt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},zl=(e,t)=>{let n=Px[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Yl=async e=>e||!Hl()?dh(e):ql();var jo=async e=>{if(e)return e==="dev"?"dev":ft(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await oe();return Dt([{value:"dev",label:"dev"},...se({branches:r,descriptions:o,types:n})])};var ph="deploy-all.yml",uh=vr({workflowFile:ph,fields:["version","env"],toolName:"gh-release-deploy-all"}),Pi=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Ne({provider:uh,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await jo(t),i=io(s);h.addOption("--version",i);let a=await Je(),c=gt(await ht(ph),a),l="";r?l=r:(h.setInteractive(),l=await En(c,"launch deploy-all workflow")),h.addOption("--env",l),dr(l,"launch deploy-all workflow",a),wo({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await Mo({confirmedCommand:o,branch:s,env:l})){p.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}try{Xl.quiet=!0,await Xl`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Xl.quiet=!1,p.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw p.error({error:u},"\u274C Error launching workflow"),new f(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Zl=R({name:"gh-release-deploy-all",formProvider:uh,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:vt.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:vt.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:vt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:vt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:vt.string().describe("The release branch that was deployed"),version:vt.string().describe("The version that was deployed"),environment:vt.string().describe("The environment deployed to"),skipTerraformDeploy:vt.boolean().describe("Whether terraform deployment was skipped"),success:vt.boolean().describe("Whether the deployment was successful")},handler:Pi});import Ex from"@inquirer/checkbox";import{z as Se}from"zod";import{$ as Ql}from"zx";var wr="deploy-selected-services.yml",mh=vr({workflowFile:wr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Ei=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ne({provider:mh,params:e,operation:"launch deploy-selected workflow",argument:O=>O[0]??"version"});let i=await jo(t),a=io(i);h.addOption("--version",a);let c=await Je(),l=gt(await ht(wr),c),d="";r?d=r:(h.setInteractive(),d=await En(l,"launch deploy-selected workflow")),h.addOption("--env",d),dr(d,"launch deploy-selected workflow",c),wo({env:d,branch:i});let u=await x(),m=await No(u,wr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${wr}`,stderrExcerpt:`no services found in .github/workflows/${wr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await I(O=>Ex({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},O),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(O=>!m.includes(O));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let S=await Do(u,wr),v=g.filter(O=>{let P=S.get(O);return P!==void 0&&!P.includes(d)});if(v.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:v.map(O=>`${O} deploys only to: ${(S.get(O)??[]).join(", ")}`).join("; "),stderrExcerpt:`${wr} gates these services out of ${d}: ${v.join(", ")}`});let C=o??!1;C&&h.addOption("--skip-terraform",!0);let _=O=>{let P={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:C,success:O};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await Mo({confirmedCommand:s,branch:i,env:d}))return p.info("Deployment cancelled"),_(!1);try{Ql.quiet=!0;let O=g.flatMap(G=>["-f",`${G}=true`]);return await Ql`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${O} ${C?["-f","skip_terraform_deploy=true"]:[]}`,Ql.quiet=!1,p.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),_(!0)}catch(O){throw p.error({error:O},"\u274C Error launching workflow"),new f(O,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},ed=R({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:mh,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:Se.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:Se.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:Se.array(Se.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:Se.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Se.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Se.string().describe("The release branch that was deployed"),version:Se.string().describe("The version that was deployed"),environment:Se.string().describe("The environment deployed to"),services:Se.array(Se.string()).describe("The services that were deployed"),skipTerraformDeploy:Se.boolean().describe("Whether terraform deployment was skipped"),success:Se.boolean().describe("Whether the deployment was successful")},handler:Ei});import{z as Ut}from"zod";var xi=async()=>{let t=(await F()).flatMap(i=>{let a=K(i.branch);return a?[{version:Y(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Ws(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=so(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",u=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${u}`});p.info(`All release branches:
390
390
  `),p.info(`
391
391
  ${o.join(`
392
392
  `)}
393
- `);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Ql=R({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:Ut.array(Ut.object({version:Ut.string().describe("Release version"),type:Ut.enum(["regular","hotfix"]).describe("Release type"),description:Ut.string().nullable().describe("Jira version description"),releaseDate:Ut.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Ut.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Ut.number().describe("Number of release branches")},handler:Si});import wx from"node:process";var ed=e=>({...e}),td=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=wx.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},Ei=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(`
394
- `)};import Ix from"@inquirer/checkbox";import Nx from"@inquirer/confirm";import _x from"@inquirer/select";import{spawn as Mx}from"node:child_process";import jx from"node:process";import{z}from"zod";import{$ as No}from"zx";import{$ as Io}from"zx";var kx=async e=>{let t=Io.quiet;Io.quiet=!0;try{let r=`/${e}/environment`,n=await Io`aws sts get-caller-identity --query Account --output text`,o=await Io`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Io.quiet=t}},uh=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},mh=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},fh=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},rd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;dr(t,`deploy to "${t}"`,i),fh(t,s),mh({env:t,isShared:n,isClean:o});let a=await kx(r);return uh(t,a),{identity:a}};import gh from"node:fs/promises";import xi from"node:path";var bx="devops/scripts",Rx=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,Px=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,Sx=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,Ex=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,nd=async e=>{let t=xi.resolve(e,bx),r;try{r=await gh.readdir(t)}catch{return[]}let n=await Bl(e);return(await Promise.all(r.map(s=>({entry:s,match:Rx.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=xi.resolve(t,s),c=i?.groups?.service??"",l=Tx(await xx(a));return{name:c,scriptPath:a,allowedEnvs:Wl(Cx(l),n.get(c)),ssmPrefix:Ax(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},xx=async e=>{try{return await gh.readFile(e,"utf-8")}catch{return""}},Tx=e=>e.split(`
395
- `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),Cx=e=>{let t=e.reduce((n,{text:o})=>n??Px.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},$x=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Ax=e=>{for(let{line:t,text:r}of e){let n=Ex.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=Sx.exec(r)?.groups?.arg;if(o!==void 0&&$x(o))return{unparseable:{line:t,text:r.trim()}}}return null},Ox=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],xi.basename(r.scriptPath)]);return t},Dx=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${xi.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},hh=e=>{Dx(e);let t=Ox(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},Ti=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),od=(e,t)=>e.filter(r=>Ti(r,t));var id="deploy-all.yml",vh="/bin/sh",Fx=async()=>{let e=No.quiet;No.quiet=!0;try{let t=await No`gh run list --workflow=${id} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{No.quiet=e}},Lx=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await D(o=>Ix({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},Vx=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 ie()&&fs(i,{env:t,services:n,accountId:o,shared:r}),r?D(a=>_x({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):D(a=>Nx({message:i,default:!1},a),{whenHeadless:"refuse"})},Bx=(e,t,r)=>new Promise((n,o)=>{let s=Mx(vh,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),Wx=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){p.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await Bx(a,r,n);if(c!==0){i.push(a.name),p.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),p.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},Jx=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!Ti(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},sd=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:ed(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Ux=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),Lx(r,o))},wh=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await S(),c=await nd(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=hh(c);await Ne({provider:ad[t],params:e,operation:"deploy locally",argument:"env"});let d=await Je(),u=gt(await ht(id),d),m=r??"";m||(h.setInteractive(),m=await Rn(u,"deploy locally")),h.addOption("--env",m);let g=od(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await Ux({selection:t,eligible:g,service:n,env:m}),P=Jx({names:y,services:c,env:m});if(t==="selected")for(let xe of y)h.addOption("--service",xe);let v=ln(m),C=await Ar(),_=(await No`git rev-parse HEAD`.quiet()).stdout.trim(),O=await au(),E=td({env:m,branch:C,sha:_,isClean:O});i&&p.info(`Deploy contract for ${m}:
396
- ${Ei(E)}`);let B=(await rd({env:m,project:l,isShared:v,isClean:O,runningEnvs:await Fx(),protectedEnvAccess:d})).identity.accountId;if(s)return p.info([`Would deploy to "${m}" (AWS account ${B}) from this machine`,`Preflight parameter: /${l}/environment`,Ei(E),"Commands:",...P.map(xe=>` ${vh} ${xe.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
397
- `)),sd({env:m,accountId:B,names:y,built:E,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await Vx({env:m,isShared:v,names:y,accountId:B}))return p.info("Deployment cancelled"),sd({env:m,accountId:B,names:y,built:E,deployed:[],failed:[],dryRun:!1,success:!1});E.stripped.length>0&&p.info(`Stripped ambient VITE_* from the build env: ${E.stripped.join(", ")}`);let{deployed:j,failed:Ke}=await Wx({chosen:P,childEnv:E.childEnv,cwd:a,env:m});return Ke.length>0&&(p.error(`Partial deploy to "${m}": succeeded [${j.join(", ")||"none"}], failed [${Ke.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),jx.exitCode=1),h.print(),sd({env:m,accountId:B,names:y,built:E,deployed:j,failed:Ke,dryRun:!1,success:Ke.length===0})},kh=async e=>wh(e,"all"),bh=async e=>wh(e,"selected"),Rh='Runs the repo\'s own devops/scripts/deploy-*.sh on THIS machine instead of dispatching CI. Supplies the build contract (VITE_DOMAIN_ENV/BRANCH/COMMIT) that the workflow YAML normally provides and that the scripts do not set themselves, and refuses unless the requested environment matches the AWS account the shell is authenticated to. "prod" is refused by default \u2014 it is delivered, not deployed \u2014 and is reachable only if this project sets `protectedEnvs` in infra-kit.json; "cli-only" allows it in a terminal but still refuses it here. Services the environment forbids are refused, matching the workflow\'s own per-service gates. Use dryRun first.',Ph={env:z.string().optional().describe('Target environment, e.g. "dev" or a personal env like "arthur". Omit it to be offered the environments this project may reach.'),dryRun:z.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:z.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Sh={environment:z.string().describe("Environment deployed to"),accountId:z.string().describe("AWS account the deploy targeted"),services:z.array(z.string()).describe("Services requested"),deployed:z.array(z.string()).describe("Services that completed successfully"),failed:z.array(z.string()).describe("Services that failed"),contract:z.record(z.string(),z.string()).describe("Build contract passed to the scripts"),strippedVars:z.array(z.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:z.boolean().describe("Whether this was a dry run"),success:z.boolean().describe("Whether every requested service deployed")},yh=e=>vr({workflowFile:id,fields:["env"],toolName:e}),ad={all:yh("local-deploy-all"),selected:yh("local-deploy-selected")},cd=R({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Rh}`,requiresHumanConfirm:!0,formProvider:ad.all,inputSchema:Ph,outputSchema:Sh,handler:kh}),ld=R({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Rh}`,requiresHumanConfirm:!0,formProvider:ad.selected,inputSchema:{...Ph,service:z.array(z.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Sh,handler:bh});import Hx from"@inquirer/confirm";import Ci from"@inquirer/input";import Ch from"@inquirer/select";import pd from"node:process";import{z as J}from"zod";import{z as _o}from"zod";var Pn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Th=2500,Eh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xh=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,Gx=async()=>{let e=await yo();return{regular:fn(e,"regular"),hotfix:fn(e,"hotfix")}},Kx=(e,t)=>e===null?(p.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?(p.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).`,dd=(e={})=>{let t=e.hintBudgetMs??Th;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=>Eh(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Pn(Gx(),t);return _o.object({type:_o.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:_o.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. ${Kx(r,t)}`),description:_o.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:_o.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=xh(r.description),a=xh(r.releaseDate),c=ii(o);return{...Eh(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var qx='"1.2.5" or "next"',ud=(e,t)=>{try{return yl(e,t)}catch(r){throw r instanceof mr?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof nu?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},zx=async(e,t)=>{let r=fn(e,t),n=r?` [${r}]`:"",o=(await D(i=>Ci({message:` Version (e.g. ${qx})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(p.error("No version provided. Exiting..."),pd.exit(1)),s},Yx=async()=>{let e=(await D(t=>Ci({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(p.error("No name provided. Exiting..."),pd.exit(1));try{is(e)}catch(t){let r=t instanceof Error?t.message:String(t);p.error(`${r} Exiting...`),pd.exit(1)}return e},Xx=async()=>(await D(e=>Ci({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:ho},e),{whenHeadless:"refuse"})).trim(),Zx=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await D(m=>Ch({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await D(m=>Ch({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),l;if(a==="name"){let m=await Yx();l=ud([{name:m,type:c}],[])[0]}else{let m=await zx(await n(),c);l=ud([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Ft(`v${l.id.raw}`))}let d=(await D(m=>Ci({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),u=await Xx();o.push({...l,...d!==""?{description:d}:{},...u!==""?{releaseDate:u}:{}}),s=await D(m=>Hx({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},Qx=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 ")},$h=e=>{for(let t of e)h.addOption("--release",hl(t))},eT=async(e,t)=>{if(e&&e.length>0){let n=vl(e)?await t():[],o=ud(e,n);return $h(o),o}if(Q())throw new x({status:"argument_required",argument:"release",agentMode:A.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 Zx(t);return $h(r),r},tT=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},rT=async(e,t)=>{let r=e.map(Qx).join(`
393
+ `);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},td=R({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:Ut.array(Ut.object({version:Ut.string().describe("Release version"),type:Ut.enum(["regular","hotfix"]).describe("Release type"),description:Ut.string().nullable().describe("Jira version description"),releaseDate:Ut.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Ut.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Ut.number().describe("Number of release branches")},handler:xi});import xx from"node:process";var rd=e=>({...e}),nd=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=xx.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},Ti=e=>{let t=Object.entries(e.contract).map(([r,n])=>` ${r.padEnd(17)}= ${n}`);return e.stripped.length>0&&t.push(` stripped from shell: ${e.stripped.join(", ")}`),t.join(`
394
+ `)};import Vx from"@inquirer/checkbox";import Bx from"@inquirer/confirm";import Wx from"@inquirer/select";import{spawn as Jx}from"node:child_process";import Ux from"node:process";import{z}from"zod";import{$ as Lo}from"zx";import{$ as Fo}from"zx";var Tx=async e=>{let t=Fo.quiet;Fo.quiet=!0;try{let r=`/${e}/environment`,n=await Fo`aws sts get-caller-identity --query Account --output text`,o=await Fo`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Fo.quiet=t}},fh=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},gh=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},hh=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},od=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;dr(t,`deploy to "${t}"`,i),hh(t,s),gh({env:t,isShared:n,isClean:o});let a=await Tx(r);return fh(t,a),{identity:a}};import yh from"node:fs/promises";import Ci from"node:path";var Cx="devops/scripts",$x=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,Ax=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,Ox=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,Ix=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,sd=async e=>{let t=Ci.resolve(e,Cx),r;try{r=await yh.readdir(t)}catch{return[]}let n=await Jl(e);return(await Promise.all(r.map(s=>({entry:s,match:$x.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ci.resolve(t,s),c=i?.groups?.service??"",l=Nx(await Dx(a));return{name:c,scriptPath:a,allowedEnvs:Ul(_x(l),n.get(c)),ssmPrefix:jx(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},Dx=async e=>{try{return await yh.readFile(e,"utf-8")}catch{return""}},Nx=e=>e.split(`
395
+ `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),_x=e=>{let t=e.reduce((n,{text:o})=>n??Ax.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},Mx=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},jx=e=>{for(let{line:t,text:r}of e){let n=Ix.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=Ox.exec(r)?.groups?.arg;if(o!==void 0&&Mx(o))return{unparseable:{line:t,text:r.trim()}}}return null},Fx=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ci.basename(r.scriptPath)]);return t},Lx=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ci.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},vh=e=>{Lx(e);let t=Fx(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},$i=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),id=(e,t)=>e.filter(r=>$i(r,t));var cd="deploy-all.yml",kh="/bin/sh",Gx=async()=>{let e=Lo.quiet;Lo.quiet=!0;try{let t=await Lo`gh run list --workflow=${cd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Lo.quiet=e}},Kx=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await I(o=>Vx({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},Hx=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 ie()&&ws(i,{env:t,services:n,accountId:o,shared:r}),r?I(a=>Wx({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):I(a=>Bx({message:i,default:!1},a),{whenHeadless:"refuse"})},qx=(e,t,r)=>new Promise((n,o)=>{let s=Jx(kh,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),zx=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){p.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await qx(a,r,n);if(c!==0){i.push(a.name),p.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),p.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},Yx=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!$i(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},ad=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:rd(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Xx=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),Kx(r,o))},bh=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await x(),c=await sd(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=vh(c);await Ne({provider:ld[t],params:e,operation:"deploy locally",argument:"env"});let d=await Je(),u=gt(await ht(cd),d),m=r??"";m||(h.setInteractive(),m=await En(u,"deploy locally")),h.addOption("--env",m);let g=id(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await Xx({selection:t,eligible:g,service:n,env:m}),S=Yx({names:y,services:c,env:m});if(t==="selected")for(let xe of y)h.addOption("--service",xe);let v=un(m),C=await Ar(),_=(await Lo`git rev-parse HEAD`.quiet()).stdout.trim(),O=await lu(),P=nd({env:m,branch:C,sha:_,isClean:O});i&&p.info(`Deploy contract for ${m}:
396
+ ${Ti(P)}`);let B=(await od({env:m,project:l,isShared:v,isClean:O,runningEnvs:await Gx(),protectedEnvAccess:d})).identity.accountId;if(s)return p.info([`Would deploy to "${m}" (AWS account ${B}) from this machine`,`Preflight parameter: /${l}/environment`,Ti(P),"Commands:",...S.map(xe=>` ${kh} ${xe.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
397
+ `)),ad({env:m,accountId:B,names:y,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await Hx({env:m,isShared:v,names:y,accountId:B}))return p.info("Deployment cancelled"),ad({env:m,accountId:B,names:y,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&p.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:j,failed:Ke}=await zx({chosen:S,childEnv:P.childEnv,cwd:a,env:m});return Ke.length>0&&(p.error(`Partial deploy to "${m}": succeeded [${j.join(", ")||"none"}], failed [${Ke.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Ux.exitCode=1),h.print(),ad({env:m,accountId:B,names:y,built:P,deployed:j,failed:Ke,dryRun:!1,success:Ke.length===0})},Rh=async e=>bh(e,"all"),Sh=async e=>bh(e,"selected"),Ph='Runs the repo\'s own devops/scripts/deploy-*.sh on THIS machine instead of dispatching CI. Supplies the build contract (VITE_DOMAIN_ENV/BRANCH/COMMIT) that the workflow YAML normally provides and that the scripts do not set themselves, and refuses unless the requested environment matches the AWS account the shell is authenticated to. "prod" is refused by default \u2014 it is delivered, not deployed \u2014 and is reachable only if this project sets `protectedEnvs` in infra-kit.json; "cli-only" allows it in a terminal but still refuses it here. Services the environment forbids are refused, matching the workflow\'s own per-service gates. Use dryRun first.',Eh={env:z.string().optional().describe('Target environment, e.g. "dev" or a personal env like "arthur". Omit it to be offered the environments this project may reach.'),dryRun:z.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:z.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},xh={environment:z.string().describe("Environment deployed to"),accountId:z.string().describe("AWS account the deploy targeted"),services:z.array(z.string()).describe("Services requested"),deployed:z.array(z.string()).describe("Services that completed successfully"),failed:z.array(z.string()).describe("Services that failed"),contract:z.record(z.string(),z.string()).describe("Build contract passed to the scripts"),strippedVars:z.array(z.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:z.boolean().describe("Whether this was a dry run"),success:z.boolean().describe("Whether every requested service deployed")},wh=e=>vr({workflowFile:cd,fields:["env"],toolName:e}),ld={all:wh("local-deploy-all"),selected:wh("local-deploy-selected")},dd=R({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Ph}`,requiresHumanConfirm:!0,formProvider:ld.all,inputSchema:Eh,outputSchema:xh,handler:Rh}),pd=R({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Ph}`,requiresHumanConfirm:!0,formProvider:ld.selected,inputSchema:{...Eh,service:z.array(z.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:xh,handler:Sh});import eT from"@inquirer/confirm";import Ai from"@inquirer/input";import Ah from"@inquirer/select";import md from"node:process";import{z as J}from"zod";import{z as Vo}from"zod";var xn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var $h=2500,Th=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ch=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,Zx=async()=>{let e=await Ro();return{regular:yn(e,"regular"),hotfix:yn(e,"hotfix")}},Qx=(e,t)=>e===null?(p.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?(p.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).`,ud=(e={})=>{let t=e.hintBudgetMs??$h;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=>Th(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await xn(Zx(),t);return Vo.object({type:Vo.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Vo.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign" \u2014 no "@" here, the date has its own field. ${Qx(r,t)}`),description:Vo.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Vo.string().optional().describe("Optional. Planned production date, yyyy-mm-dd. Becomes the Jira fix version's release date; delivery overwrites it with the actual date. On the re-run it is passed as <token>@yyyy-mm-dd inside -r.")})},toArgs:(r,n)=>{let o=typeof r.release=="string"?r.release.trim():"";if(o==="")return null;let s=r.type==="hotfix"?"hotfix":"regular",i=Ch(r.description),a=Ch(r.releaseDate),c=ci(o);return{...Th(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var tT='"1.2.5" or "next"',fd=(e,t)=>{try{return wl(e,t)}catch(r){throw r instanceof mr?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof su?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},rT=async(e,t)=>{let r=yn(e,t),n=r?` [${r}]`:"",o=(await I(i=>Ai({message:` Version (e.g. ${tT})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(p.error("No version provided. Exiting..."),md.exit(1)),s},nT=async()=>{let e=(await I(t=>Ai({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(p.error("No name provided. Exiting..."),md.exit(1));try{ps(e)}catch(t){let r=t instanceof Error?t.message:String(t);p.error(`${r} Exiting...`),md.exit(1)}return e},oT=async()=>(await I(e=>Ai({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:bo},e),{whenHeadless:"refuse"})).trim(),sT=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await I(m=>Ah({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await I(m=>Ah({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),l;if(a==="name"){let m=await nT();l=fd([{name:m,type:c}],[])[0]}else{let m=await rT(await n(),c);l=fd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Ft(`v${l.id.raw}`))}let d=(await I(m=>Ai({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),u=await oT();o.push({...l,...d!==""?{description:d}:{},...u!==""?{releaseDate:u}:{}}),s=await I(m=>eT({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},iT=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 ")},Oh=e=>{for(let t of e)h.addOption("--release",vl(t))},aT=async(e,t)=>{if(e&&e.length>0){let n=kl(e)?await t():[],o=fd(e,n);return Oh(o),o}if(ee())throw new E({status:"argument_required",argument:"release",agentMode:A.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 sT(t);return Oh(r),r},cT=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},lT=async(e,t)=>{let r=e.map(iT).join(`
398
398
  - `);await W(t,`Create the following ${e.length} release(s)?
399
399
  - ${r}
400
- `),h.addOption("--yes",!0)},nT=async e=>{let{entry:t,jiraConfig:r}=e,n=Y(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Jr({operation:`create release ${o}`});let s=await Oc(t.type),i=await Dc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return p.info(`\u2705 Successfully created release: ${o} (${t.type})`),p.info(`\u{1F517} GitHub PR: ${i.prUrl}`),p.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
401
- `),{result:i}}catch(s){let i=Qn(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return p.error(`\u274C ${a.message}
402
- `),{failure:{version:n,error:a.message}}}},oT=(e,t,r)=>{t===e?p.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(p.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),p.warn(`\u274C ${r} release(s) failed.`)):p.error(`\u274C All ${e} release branch(es) failed to create.`)},Ah=dd(),$i=async e=>{let{releases:t,confirmedCommand:r}=e;await be({operation:"create release"}),await Ne({provider:Ah,params:e,operation:"create release",argument:"release"});let n=await Yr(),o=null,i=await eT(t,async()=>(o===null&&(o=await yo()),o));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});tT(i),await qn({operation:"create release",base:Qe(i[0].type)}),await rT(i,!!r);let a=[],c=[];for(let d of i){let{result:u,failure:m}=await nT({entry:d,jiraConfig:n});u&&a.push(u),m&&c.push(m)}oT(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},md=R({name:"release-create",requiresHumanConfirm:!0,formProvider:Ah,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:J.array(J.object({version:J.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:J.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:J.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:J.string().optional().describe("Optional description for the Jira version."),releaseDate:ll.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:J.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:J.array(J.string()).describe("List of created release branch names"),successCount:J.number().describe("Number of releases created successfully"),failureCount:J.number().describe("Number of releases that failed"),releases:J.array(J.object({version:J.string().describe("Version number"),type:J.enum(["regular","hotfix"]).describe("Release type"),branchName:J.string().describe("Release branch name"),prUrl:J.string().describe("GitHub PR URL"),jiraVersionUrl:J.string().describe("Jira version URL"),releaseDate:J.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:J.array(J.object({version:J.string().describe("Version number that failed"),error:J.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:$i});import Oh from"@inquirer/input";import{z as Me}from"zod";var Dh=["description","releaseDate"],sT=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await oe(),o=await It(se({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},iT=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},aT=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await D(o=>Oh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},cT=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await D(o=>Oh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:ho},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:ur(n)},lT=e=>{if(e!==void 0)return e===""?null:e},dT=async e=>(h.setInteractive(),{description:await aT(e.description),releaseDate:await cT(e.releaseDate)}),fd=e=>e??"(none)",pT=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${fd(t.releaseDate)} \u2192 ${fd(r.releaseDate)}`,Ai=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=lT(n),i=await Yr(),a;t?(a=mt(t),await iT(a)):(h.setInteractive(),a=(await sT()).branch);let c=K(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=Y(c);h.addOption("--version",l);let d=ne(c),u=await pt(d,i);if(!u)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:u.description??"",releaseDate:u.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&ie())throw new x({status:"argument_required",argument:"description",agentMode:A.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await dT(m),P=Dh.filter(G=>y[G]!==m[G]),v=P.includes("description"),C=P.includes("releaseDate"),_=rr(i,u),O=G=>{let B={version:l,branch:a,jiraVersionUrl:_,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:P,changed:G};return{content:k(JSON.stringify(B,null,2)),structuredContent:B}};if(P.length===0)return p.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${fd(m.releaseDate)}`),h.print(),O(!1);v&&h.addOption("--description",y.description),C&&h.addOption("--release-date",y.releaseDate??"");let E=P.map(G=>pT(G,m,y));return await W(o,`Update ${d}?
403
- ${E.join(`
400
+ `),h.addOption("--yes",!0)},dT=async e=>{let{entry:t,jiraConfig:r}=e,n=Y(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Jr({operation:`create release ${o}`});let s=await Dc(t.type),i=await Nc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return p.info(`\u2705 Successfully created release: ${o} (${t.type})`),p.info(`\u{1F517} GitHub PR: ${i.prUrl}`),p.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
401
+ `),{result:i}}catch(s){let i=no(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return p.error(`\u274C ${a.message}
402
+ `),{failure:{version:n,error:a.message}}}},pT=(e,t,r)=>{t===e?p.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(p.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),p.warn(`\u274C ${r} release(s) failed.`)):p.error(`\u274C All ${e} release branch(es) failed to create.`)},Ih=ud(),Oi=async e=>{let{releases:t,confirmedCommand:r}=e;await be({operation:"create release"}),await Ne({provider:Ih,params:e,operation:"create release",argument:"release"});let n=await Yr(),o=null,i=await aT(t,async()=>(o===null&&(o=await Ro()),o));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});cT(i),await Zn({operation:"create release",base:Qe(i[0].type)}),await lT(i,!!r);let a=[],c=[];for(let d of i){let{result:u,failure:m}=await dT({entry:d,jiraConfig:n});u&&a.push(u),m&&c.push(m)}pT(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},gd=R({name:"release-create",requiresHumanConfirm:!0,formProvider:Ih,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:J.array(J.object({version:J.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:J.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:J.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:J.string().optional().describe("Optional description for the Jira version."),releaseDate:pl.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:J.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:J.array(J.string()).describe("List of created release branch names"),successCount:J.number().describe("Number of releases created successfully"),failureCount:J.number().describe("Number of releases that failed"),releases:J.array(J.object({version:J.string().describe("Version number"),type:J.enum(["regular","hotfix"]).describe("Release type"),branchName:J.string().describe("Release branch name"),prUrl:J.string().describe("GitHub PR URL"),jiraVersionUrl:J.string().describe("Jira version URL"),releaseDate:J.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:J.array(J.object({version:J.string().describe("Version number that failed"),error:J.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Oi});import Dh from"@inquirer/input";import{z as Me}from"zod";var Nh=["description","releaseDate"],uT=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await oe(),o=await Dt(se({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},mT=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},fT=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await I(o=>Dh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},gT=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await I(o=>Dh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:bo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:ur(n)},hT=e=>{if(e!==void 0)return e===""?null:e},yT=async e=>(h.setInteractive(),{description:await fT(e.description),releaseDate:await gT(e.releaseDate)}),hd=e=>e??"(none)",vT=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${hd(t.releaseDate)} \u2192 ${hd(r.releaseDate)}`,Ii=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=hT(n),i=await Yr(),a;t?(a=ft(t),await mT(a)):(h.setInteractive(),a=(await uT()).branch);let c=K(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=Y(c);h.addOption("--version",l);let d=ne(c),u=await ut(d,i);if(!u)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:u.description??"",releaseDate:u.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&ie())throw new E({status:"argument_required",argument:"description",agentMode:A.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await yT(m),S=Nh.filter(G=>y[G]!==m[G]),v=S.includes("description"),C=S.includes("releaseDate"),_=rr(i,u),O=G=>{let B={version:l,branch:a,jiraVersionUrl:_,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:S,changed:G};return{content:k(JSON.stringify(B,null,2)),structuredContent:B}};if(S.length===0)return p.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${hd(m.releaseDate)}`),h.print(),O(!1);v&&h.addOption("--description",y.description),C&&h.addOption("--release-date",y.releaseDate??"");let P=S.map(G=>vT(G,m,y));return await W(o,`Update ${d}?
403
+ ${P.join(`
404
404
  `)}
405
- `),h.addOption("--yes",!0),await zr({versionId:u.id,...v?{description:y.description}:{},...C?{releaseDate:y.releaseDate}:{}},i),v&&await Ns({branch:a,body:Zn(_,y.description)}),p.info(`\u2705 Updated ${P.join(" and ")} for ${d}`),p.info(`\u{1F517} Jira Version: ${_}`),p.info(`\u{1F517} PR branch: ${a}
406
- `),h.print(),O(!0)},gd=R({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Me.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Me.string().optional().describe("New description. Empty string clears the description."),releaseDate:dl.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Me.string().describe("Release version"),branch:Me.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Me.string().describe("Jira fix version URL"),previousDescription:Me.string().describe("The description before the update"),newDescription:Me.string().describe("The description after the update"),previousReleaseDate:Me.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Me.string().nullable().describe("The planned release date after the update, or null"),changedFields:Me.array(Me.enum(Dh)).describe("The fields whose value actually changed"),changed:Me.boolean().describe("Whether anything actually changed")},handler:Ai});import{z as M}from"zod";import{$ as bd}from"zx";import Ih from"node:fs/promises";import Oi from"node:path";var hd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Oi.dirname(t),o;try{o=await Ih.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>Oi.resolve(n,d.path))),c=[],l=[];for(let d of r){let u=Oi.resolve(d);if(a.has(u)){l.push(d);continue}let m=Oi.relative(n,u);i.push({path:m}),a.add(u),c.push(d)}return s.folders=i,await Ih.writeFile(t,`${JSON.stringify(s,null,2)}
407
- `,"utf-8"),{added:c,skipped:l}};import{$ as uT}from"zx";var yd=async e=>{await uT`cursor ${e}`};import Nh from"node:fs/promises";import Di from"node:path";var vd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Di.dirname(t),o;try{o=await Nh.readFile(t,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${t}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(r.map(m=>Di.resolve(m))),c=new Set,l=i.filter(m=>{let g=Di.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await Nh.writeFile(t,`${JSON.stringify(s,null,2)}
408
- `,"utf-8");let d=[],u=[];for(let m of r){let g=Di.resolve(m);c.has(g)?d.push(m):u.push(m)}return{removed:d,notFound:u}};import _h from"node:path";var Mo=(e,t)=>_h.isAbsolute(e)?e:_h.resolve(t,e);var wd=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await I(),s=Tt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await mT({ide:c,projectRoot:t,folderPaths:i}));return a},mT=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return p.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),{ran:!1,provider:"cursor",added:0,skipped:0};let o=Mo(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await hd({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return p.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await yd(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var kr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await I(),s=Tt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await fT({ide:c,projectRoot:t,folderPaths:i}));return a},fT=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=Mo(t.config.workspaceConfigPath,r);try{let{removed:s}=await vd({workspacePath:o,folderPaths:n});return s.length>0&&p.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return p.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var br=["workspace","none"];import{z as Mh}from"zod";var Lh=2500,Ii="release-remove",jh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gT=e=>e.version===void 0||e.version==="",hT=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===Yn?{outcome:"empty"}:{outcome:"failed"}}},Fh=(e,t)=>(e===null?p.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Ii}`}):e.outcome==="failed"?p.info({msg:`Tool execution form enumeration failed (gh pr list): ${Ii}`}):p.info({msg:`Tool execution form options empty (open release PRs): ${Ii}`}),null),yT=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Fs(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ne(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},vT=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(p.info({msg:`Tool execution form descriptions unavailable (timeout): ${Ii}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},kd=(e={})=>{let t=e.fetchBudgetMs??Lh;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=>jh(r)&&gT(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Pn(hT(),t),Pn(oe(),t)]);if(r===null||r.outcome!=="listed")return Fh(r,t);let o=yT(r.prs,n);return o.length===0?Fh({outcome:"empty"},t):Mh.object({version:Mh.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${vT(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:{...jh(n)?n:{},version:r.version}}};var Vh=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],_i={worktree:"remove the worktree","ide-folders":"strip the worktree from configured editors",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},Rr="remove a release",Ue=e=>{throw p.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},Bh=(e,t)=>{throw p.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new x({...e,agentMode:A.source},2,t)},wT=e=>{Q()&&(e.version||Bh({status:"argument_required",argument:"version"},{operation:Rr,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&&Bh({status:"refused"},{operation:Rr,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"}))},Jh=e=>{e.pr?.state==="MERGED"&&Ue({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`})},kT=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ue({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)&&Ue({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||Ue({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)`}))},bT=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ue({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"})},RT=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ue({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(", ")}`})},PT=async e=>(await bd`git -C ${e} status --porcelain`).stdout.split(`
409
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),ST=async e=>{try{let{terminals:t}=await _u(e);return t.filter(r=>r.connected).length}catch(t){return p.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},ET=async e=>{let t=await ys([e]);if(t!==null)throw p.warn({operation:Rr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new x({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:Rr,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`})},xT=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 pt(ne(e),n),s=t.moveIssuesTo?await TT(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Ms(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:rr(n,o)}}},TT=async(e,t)=>{let r=await pt(e,t);return r||Ue({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}"`})},CT=async(e,t)=>{let r=K(e);r||Ue({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(),o=`${n}${ge}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([Ce("release"),Gr(e),$e(n,`refs/heads/${e}`),Or(n,e)]),d=i.includes(e);return d&&await ET(s),{...await xT(r,t),branch:e,id:r,label:Y(r),baseBranch:a?.baseRefName??Qe("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await ST(s):0,worktreeDirty:d?await PT(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Wh=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}),$T=(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}`},AT=(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: ${$T(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
410
- `)},Ni=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},OT=e=>typeof e=="string"?e:e.outcome;async function jo(e,t,r){try{let n=await r(),o=OT(n);return t.push({step:e}),p.info({step:e,outcome:o},`\u2705 ${_i[e]} \u2014 ${o}`),n}catch(n){throw new Ni(e,n)}}var DT=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),p.warn({err:Wt(n),step:e},`\u26A0\uFE0F ${_i[e]} failed (non-blocking)`)}},IT=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,NT=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(u=>IT(t,u)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Vh.indexOf(r)+1} of ${Vh.length} (${_i[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},_T=async e=>{let t=await xo(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`});return{outcome:t.includes(e.branch)?"removed":"absent",removedBranches:t}},MT=e=>{let t=e.map(s=>({provider:s.provider,outcome:jT(s),removed:s.removed})),r=t.some(s=>s.outcome==="verified"),o=t.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:r?"verified":o,providers:t}},jT=e=>e.removed.length>0?"verified":"attempted",FT=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await DT("ide-folders",r,async()=>{let o=await kr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=MT(o)}),p.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${_i["ide-folders"]} \u2014 ${n.outcome}`),n},LT=async e=>{let t=await Gr(e.branch);if(Jh({...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 bd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},VT=async e=>(await Ar()===e.branch&&await bd`git switch ${e.baseBranch}`,await cs(e.branch),await lu(e.branch)?Ue({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"),BT=async e=>(await ls(e.branch),e.remoteTipSha?"deleted":"absent"),WT=async(e,t,r)=>{let n=await Ms(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}\``;Ue({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}`})},JT=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await WT(e,e.jira,e.jiraConfig),p.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Ac({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),UT=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree.outcome,ideFolders:t.ideFolders,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),GT=async(e,t,r)=>{let n=await jo("worktree",r,()=>_T(e)),o=await FT(e,n.removedBranches,r),s=await jo("pr",r,()=>LT(e));p.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await jo("local-branch",r,()=>VT(e)),a=await jo("remote-branch",r,()=>BT(e)),c=await jo("jira",r,()=>JT(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},KT=async(e,t)=>{let r=[];try{return UT(e,await GT(e,t,r))}catch(n){throw n instanceof Ni?NT({plan:e,step:n.step,done:r,cause:n.reason}):n}},HT=async e=>{if(e)return mt(e);h.setInteractive();let[t,r]=await Promise.all([oe(),F()]),n=r.map(s=>s.branch);n.length===0&&Ue({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 It(se({branches:n,descriptions:t,types:o}))}catch(s){throw we(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},Uh=kd(),Mi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await be({operation:Rr}),await I(),await Ne({provider:Uh,params:e,operation:Rr,argument:"version"}),wT(e);try{let s=await CT(await HT(r),e);p.debug({plan:Wh(s)},"release remove: resolved plan"),Jh(s),kT(s,e),bT(s),await qn({operation:`remove release ${s.label}`,base:s.baseBranch}),RT(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await W(t,AT(s,!!o),{throwOnDecline:!0,plan:{...Wh(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await KT(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw we(s)||at(s)||s instanceof f?s:(p.error({err:Wt(s)},"\u274C Error removing release"),new f(s,{operation:Rr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Rd=R({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:Uh,inputSchema:{version:M.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:M.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:M.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:M.string().describe("The release branch that was targeted"),version:M.string().describe('The release label (e.g. "1.2.5")'),baseBranch:M.string().describe("The branch HEAD was moved to before the local delete"),worktree:M.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:M.object({outcome:M.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:M.array(M.object({provider:M.string(),outcome:M.enum(["verified","attempted","skipped"]),removed:M.array(M.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:M.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:M.number().nullable().describe("The pull request number, or null when none exists"),localBranch:M.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:M.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:M.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:M.string().nullable().describe("The origin tip before deletion"),jira:M.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:M.object({id:M.string(),name:M.string(),url:M.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Mi});import{spawnSync as XT}from"node:child_process";import{homedir as ZT}from"node:os";import QT from"node:process";var qT=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},zT=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},YT=(e,t)=>{let r=qT(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},Fo=(e,t)=>{let r=[...zT(e),...YT(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Lo=e=>e.steps.map(Rt);var eC=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],tC=e=>{let t={...Lp(e)};for(let r of eC)delete t[r];return t},Pd=(e,t,r={})=>{let n=r.spawnSync??XT,o=r.env??QT.env,s=(r.agentMode??Q)(),i=Lo(e),a=Fo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:oC({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??rC}):{ran:!1,commands:i,refusedBecause:a.reasons}},rC=e=>{p.info(e)},Kh=64,nC=Kh*1024*1024,oC=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=tC(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:nC,cwd:ZT(),env:s}),l=dC(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},sC=5,iC=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Gh=e=>e==null?[]:String(e).split(`
411
- `).map(t=>t.trim()).filter(t=>t.length>0),aC=e=>{let t=Gh(e.stderr),r=Gh(e.stdout),n=[...t,...r].filter(s=>iC.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-sC).join(" / ")},cC="ENOBUFS",lC=e=>e.error?.code===cC,dC=e=>{if(lC(e))return`terminated after exceeding the ${Kh} 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=aC(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var pC=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},uC=e=>{let t=Ie(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},mC=(e,t)=>{let r=uC(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=Fo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Lo(r),context:n}},ji=async(e=lr,t=po())=>{let r=await mo(lr,t),n={owner:null,present:pC(r)},o=il(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>mC(s.get(a),n)),context:n}};var Sd=(e,t)=>({...Vo(e),action:"skipped",commands:e.commands,detail:t}),Vo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Hh=(e,t)=>e.action==="none"?Sd(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?Sd(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Vo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},fC=(e,t)=>t.ran?t.ok?{...Vo(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Vo(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Vo(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Ed=async e=>{let t=e.run??Pd,{plans:r}=await ji(e.ids,e.probeDeps),n=[];for(let o of r){let s=Hh(o,e.mode);if(s!==null){n.push(s);continue}n.push(fC(o,t(o.recipe,o.context)))}return n},xd=async(e,t)=>{let{plans:r}=await ji(e,t);return r.map(n=>Hh(n,"converge")??Sd(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import AC from"node:process";import{z as T}from"zod";var Td={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},gC=Object.keys(Td).sort((e,t)=>Td[e]-Td[t]),qh={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},zh=new Set(["manual","warn","fail"]),Cd=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 qe(e)}},hC=e=>e.reduce((t,r)=>qh[r]>qh[t]?r:t,"skipped"),Xh=e=>e.message.trim(),yC=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 "),Yh=e=>e.message===nn,vC=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Xh(r):e.length>1?yC(e):t?"activate with the last line below":"see below"},wC=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Cd(i.outcome)),n=t.filter(i=>zh.has(Cd(i.outcome))).map(Xh),o=t.filter(i=>!zh.has(Cd(i.outcome))&&!Yh(i)),s={name:e,status:hC(r),message:vC(o,t.some(Yh))};return n.length>0?{...s,notes:n}:s},kC=e=>({label:"Local setup",rows:gC.map(t=>wC(t,e.filter(r=>r.step===t)))}),bC=(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 qe(e.action)}},RC=(e,t)=>{let r=bC(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},PC=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>RC(r,t))}),SC=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 qe(e)}},EC=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 qe(e)}},xC=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 qe(e)}},TC=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 qe(e.outcome)}},CC=(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 qe(e)}},$C=e=>({label:"Portless service",rows:[{name:"link",status:SC(e.link),message:xC(e.link)},{name:"node",status:EC(e.node.outcome),message:TC(e.node)},CC(e.service,e.command)]}),Zh=(e,t)=>[kC(e.init),PC(e.tools,t),$C(e.portless)],Qh=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var OC=()=>{let{link:e,node:t}=os();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},DC=async e=>{let t=eu(e.link).outcome,r=Qp(e.node),n=ns(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 $g(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Pt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},ty="--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.",IC=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||r))throw new Error(ty);return{ids:e.tools??t??lr,mode:r?"update":"converge",skipTools:n}},ey=(e,t)=>e instanceof rn?e.step:t.at(-1)?.step??"zshrc",NC=async()=>{let e=[];try{await Xc(t=>{e.push(t)})}catch(t){e.push({step:ey(t,e),outcome:"failed",message:`The ${ey(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},_C=(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}`}))},MC=async(e,t)=>{try{return e.skipTools?await xd(e.ids,t.probeDeps):await Ed({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return _C(e.ids,r)}},jC=e=>({step:e.step,outcome:e.outcome,message:e.message}),Fi=async(e={})=>{let t=IC(e),r=await NC(),n=await MC(t,e),o=await DC(e.portlessDeps??OC()),s=Zh({init:r,tools:n,portless:o},{skipTools:t.skipTools});Dt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),p.info(nn),Qh(s)&&(AC.exitCode=1);let i={init:r.map(jC),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},FC=T.object({step:T.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:T.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:T.string().describe("The same line a human running this would have read")}),LC=T.object({id:T.string().describe("Dependency id"),action:T.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:T.object({present:T.boolean(),onPath:T.boolean(),version:T.string().nullable(),manager:T.string()}).describe("The tool\u2019s state before this run"),commands:T.array(T.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:T.string().describe("Why, in one line")}),VC=T.object({link:T.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:T.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:T.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:T.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")}),BC={init:T.array(FC).describe("One entry per init step, in the order they ran"),tools:T.array(LC).describe("One result per requested dependency"),portlessService:VC.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:T.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:T.boolean().describe("Whether anything was installed or updated"),report:T.array(T.object({label:T.string().describe("Section heading"),rows:T.array(T.object({name:T.string().describe("Init step, tool id, or portless part"),status:T.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:T.string().describe("The row message, as printed"),notes:T.array(T.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:T.boolean().describe("Whether no tool failed (a refusal is not a failure)")},WC={tools:T.array(T.enum(lr)).optional().describe("Which tools to act on. Omit for all six."),mode:T.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:T.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},$d=R({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:WC,outputSchema:BC,requiresHumanConfirm:!0,handler:e=>Fi({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as ny}from"node:fs";import oy from"node:path";import QC from"node:process";import{z as wt}from"zod";import{createHash as JC}from"node:crypto";import{readFileSync as UC}from"node:fs";var Pr=e=>JC("sha256").update(UC(e)).digest("hex");import{readFileSync as YC,writeFileSync as XC}from"node:fs";import Wi from"node:path";import{z as ot}from"zod";var X="vendor",GC=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),KC=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),HC=[".tsbuildinfo"],Ad=e=>GC.has(e),Od=e=>KC.has(e)?!0:HC.some(t=>e.endsWith(t)),Li=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Ad(o))||Od(r)};import{readdirSync as qC}from"node:fs";import Dd from"node:path";var zC=e=>e.split(Dd.sep).join("/"),Vi=e=>{let t=[],r=n=>{for(let o of qC(n,{withFileTypes:!0})){let s=Dd.join(n,o.name);if(o.isDirectory()){if(Ad(o.name))continue;r(s);continue}Od(o.name)||t.push(zC(Dd.relative(e,s)))}};return r(e),t.sort()};var je=".sync-manifest.json",Bi=1,ZC=ot.object({schemaVersion:ot.number().optional(),source:ot.string(),commit:ot.string(),syncedAt:ot.string(),fileCount:ot.number(),files:ot.record(ot.string(),ot.string())}),Id=e=>(e.schemaVersion??Bi)>Bi,ry=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Vi(e);for(let o of n)try{r[o]=Pr(Wi.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},Bo=e=>{let t=Wi.join(e,je),r;try{r=YC(t,"utf8")}catch{throw new Error(`Missing ${je} at ${t}`)}let n=ZC.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${je} at ${t}: ${ot.prettifyError(n.error)}`);return n.data},Nd=(e,t,r)=>{let n=ry(e,r),o={schemaVersion:Bi,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return XC(Wi.join(e,je),`${JSON.stringify(o,null,2)}
412
- `),o},_d=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Li(c))),n=Vi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Pr(Wi.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 Md=30,jd=(e,t)=>{if(t.length!==0){p.info(`
413
- ${e} (${t.length}):`);for(let r of t.slice(0,Md))p.info(` ${r}`);t.length>Md&&p.info(` \u2026and ${t.length-Md} more`)}},Ji=async(e={})=>{let t=e.cwd??await S(),r=oy.join(t,X),n={modified:[],added:[],removed:[],fileCount:0};if(!ny(r)){p.info(`\u2139\uFE0F No ${X}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!ny(oy.join(r,je))){p.error(`\u274C Missing ${X}/${je}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=Bo(r);if(Id(o)){p.error(`\u274C ${X}/${je} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=_d(r,o),c=s.length>0||i.length>0||a.length>0;c?(p.error(`\u274C ${X}/ has drifted from ${X}/${je}.`),p.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),jd("Modified",s),jd("Added (not in manifest)",i),jd("Removed (in manifest, now missing)",a)):p.info(`\u2705 ${X}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},e$={status:wt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:wt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:wt.number(),modified:wt.array(wt.string()),added:wt.array(wt.string()),removed:wt.array(wt.string())},Fd=R({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:e$,handler:()=>Ji({cwd:QC.cwd()})});import sy from"node:process";import{z as Wo}from"zod";var iy=async e=>{try{return await e()}catch{return null}},Ui=async()=>{let e=q.version;p.info(e);let t=await iy(S),r=t===null?null:await iy(()=>Le(t)),n={version:e,cwd:sy.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:sy.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Ld=R({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:Wo.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Wo.string().describe("The working directory of this process"),repoRoot:Wo.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Wo.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Wo.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ui});import cy from"@inquirer/confirm";import t$ from"node:path";import{z as U}from"zod";import{$ as Jo}from"zx";var Gi="create worktrees",r$=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Vd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Ki=async e=>{let{confirmedCommand:t,all:r,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await be({operation:Gi});try{let a=await Ce("release"),c=await S(),l=`${c}${ge}`;await ay(`${l}/${Cr.release}`),await ay(`${l}/${Cr.feature}`);let d=[];if(n)d=n.split(",").map(j=>Te(ve(j.trim())));else{let j=await F(),Ke=j.map(xe=>xe.branch);if(Ke.length===0){p.info("\u2139\uFE0F No open release branches found"),h.print();let xe={createdWorktrees:[],count:0,...Vd()};return{content:k(JSON.stringify(xe,null,2)),structuredContent:xe}}if(r)d=Ke;else{h.setInteractive();let xe=new Map(j.map(Yo=>[Yo.branch,Yo.type])),fa=await oe();d=await Nt(se({branches:Ke,descriptions:fa,types:xe}),{required:!0})}}r?h.addOption("--all",!0):h.addOption("--versions",nr(d));let u=await I(),m=i??(Tt(u).length>0?"workspace":"none");h.addOption("--ide",m);let g=await n$(o,u),y=await o$(s,u),P=await Le(c),v=t$.basename(P),C=y?await s$({explicit:s!==void 0,mainRepoRoot:P}):null;await W(t,i$(C,v)),t||h.addOption("--yes",!0);let _=C?await a$(C,P):null,{branchesToCreate:O}=p$({selectedReleaseBranches:d,currentWorktrees:a}),E=await u$(O,l);if(m$(E),m==="workspace"&&await wd({projectRoot:c,worktreeDir:l,branches:E}),g)for(let j of E)await Jo`github ${l}/${j}`,await Jo`sleep 5`;let G=_?await l$({registration:_,createdWorktrees:E,worktreeDir:l,mainRepoRoot:P,repoName:v,config:u}):Vd();d$(G),h.print();let B={createdWorktrees:E,count:E.length,...G};return{content:k(JSON.stringify(B,null,2)),structuredContent:B}}catch(a){throw we(a)||a instanceof x?a:(p.debug({err:a},"Error managing worktrees"),new f(a,{operation:Gi,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},n$=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await D(o=>cy({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},o$=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await D(o=>cy({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},ly=e=>e==="absent"?{reason:"orca_absent",text:"the orca CLI is not installed (Orca \u2192 Settings \u2192 Experimental \u2192 CLI)"}:{reason:"orca_unreachable",text:"Orca is not running"},s$=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Dr();if(n!=="ready"){let{reason:s,text:i}=ly(n);if(t)throw p.warn({operation:Gi},`\u26D4 --orca was passed but ${i}`),new x({status:"refused",reason:s,agentMode:A.source},2,{operation:Gi,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 p.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await ju(r);return{probe:n,registered:o.registered,visibility:o.visibility}},i$=(e,t)=>{let r=["Are you sure you want to proceed with these worktree changes?"];return e?.probe==="ready"&&!e.registered&&r.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),r.join(`
414
- `)},a$=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:ly(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Fu(t);return{kind:"ready",visibility:r}}catch(r){return p.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 hs?r.code:void 0}}},c$=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,l$=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Vd();if(t.kind==="skip"){for(let u of r)a.orcaSkipped.push({branch:u,reason:t.reason,code:t.code});return a}let c=wu(i),l=r.length===1&&t.visibility!=="hide",d=Vu();for(let u of r){let m=`${n}/${u}`;try{let{layout:g}=await Bu({cwd:m,title:Wu({branch:u}),focus:l,layout:"full",panes:c,poll:d});await Lu(o,m)?a.orcaOpened.push({branch:u,layout:g}):a.orcaHidden.push({branch:u,path:m,fix:c$(s)})}catch(g){p.warn({error:g,branch:u},`\u26A0\uFE0F Failed to open Orca terminals for ${u}`),g instanceof hs&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:u,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:u,reason:"orca_error",code:g instanceof hs?g.code:void 0})}}return a},d$=e=>{for(let t of e.orcaOpened)p.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)p.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})`:"";p.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},ay=async e=>{await Jo`mkdir -p ${e}`},p$=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>as(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},u$=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o}`;return await Jo`git worktree add ${s} ${o}`,await Jo({cwd:s})`pnpm install`,o})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o],a=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});p.error({error:s.reason,msg:a.message})}return n},m$=e=>{if(e.length>0){p.info("\u2705 Created git worktrees:");for(let t of e)p.info(t);p.info("")}else p.info("\u2139\uFE0F No new git worktrees to create")},Bd=R({name:"worktrees-add",description:`Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \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:{all:U.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:U.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:U.enum(br).optional().describe('Editor open mode for created worktrees, applied to the configured editor (Cursor, per the "ide" config). "workspace" (the only attach style) adds each worktree to the Cursor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when an "ide" is configured \u2192 "none" otherwise.'),cursor:U.enum(br).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:U.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:U.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{createdWorktrees:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created"),orcaOpened:U.array(U.object({branch:U.string(),layout:U.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:U.array(U.object({branch:U.string(),reason:U.enum(r$),code:U.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:U.array(U.object({branch:U.string(),path:U.string(),fix:U.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:Ki});import{z as Sn}from"zod";var Hi=async()=>{await I();let e=await Ce("release");if(e.length===0)return p.info("\u2139\uFE0F No active worktrees found"),{content:k(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[t,r]=await Promise.all([F(),oe()]),n=new Map(t.map(c=>[c.branch,c.type])),o=e.flatMap(c=>{let l=K(c);if(!l)return[];let d=Y(l),u=n.get(c)||"regular",m=r.get(ne(l))||null;return[{version:d,type:u,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let l=to(c.version,c.type,s);return c.description?`${l} ${c.description}`:l});p.info(`\u{1F33F} Active worktrees:
405
+ `),h.addOption("--yes",!0),await zr({versionId:u.id,...v?{description:y.description}:{},...C?{releaseDate:y.releaseDate}:{}},i),v&&await Ls({branch:a,body:ro(_,y.description)}),p.info(`\u2705 Updated ${S.join(" and ")} for ${d}`),p.info(`\u{1F517} Jira Version: ${_}`),p.info(`\u{1F517} PR branch: ${a}
406
+ `),h.print(),O(!0)},yd=R({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Me.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Me.string().optional().describe("New description. Empty string clears the description."),releaseDate:ul.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Me.string().describe("Release version"),branch:Me.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Me.string().describe("Jira fix version URL"),previousDescription:Me.string().describe("The description before the update"),newDescription:Me.string().describe("The description after the update"),previousReleaseDate:Me.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Me.string().nullable().describe("The planned release date after the update, or null"),changedFields:Me.array(Me.enum(Nh)).describe("The fields whose value actually changed"),changed:Me.boolean().describe("Whether anything actually changed")},handler:Ii});import{z as M}from"zod";import{$ as Sd}from"zx";import _h from"node:fs/promises";import Di from"node:path";var vd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Di.dirname(t),o;try{o=await _h.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>Di.resolve(n,d.path))),c=[],l=[];for(let d of r){let u=Di.resolve(d);if(a.has(u)){l.push(d);continue}let m=Di.relative(n,u);i.push({path:m}),a.add(u),c.push(d)}return s.folders=i,await _h.writeFile(t,`${JSON.stringify(s,null,2)}
407
+ `,"utf-8"),{added:c,skipped:l}};import{$ as wT}from"zx";var wd=async e=>{await wT`cursor ${e}`};import Mh from"node:fs/promises";import Ni from"node:path";var kd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Ni.dirname(t),o;try{o=await Mh.readFile(t,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${t}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(r.map(m=>Ni.resolve(m))),c=new Set,l=i.filter(m=>{let g=Ni.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await Mh.writeFile(t,`${JSON.stringify(s,null,2)}
408
+ `,"utf-8");let d=[],u=[];for(let m of r){let g=Ni.resolve(m);c.has(g)?d.push(m):u.push(m)}return{removed:d,notFound:u}};import jh from"node:path";var Bo=(e,t)=>jh.isAbsolute(e)?e:jh.resolve(t,e);var bd=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await D(),s=Tt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await kT({ide:c,projectRoot:t,folderPaths:i}));return a},kT=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return p.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),{ran:!1,provider:"cursor",added:0,skipped:0};let o=Bo(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await vd({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return p.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await wd(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var kr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await D(),s=Tt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await bT({ide:c,projectRoot:t,folderPaths:i}));return a},bT=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=Bo(t.config.workspaceConfigPath,r);try{let{removed:s}=await kd({workspacePath:o,folderPaths:n});return s.length>0&&p.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return p.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var br=["workspace","none"];import{z as Fh}from"zod";var Bh=2500,_i="release-remove",Lh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),RT=e=>e.version===void 0||e.version==="",ST=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===eo?{outcome:"empty"}:{outcome:"failed"}}},Vh=(e,t)=>(e===null?p.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${_i}`}):e.outcome==="failed"?p.info({msg:`Tool execution form enumeration failed (gh pr list): ${_i}`}):p.info({msg:`Tool execution form options empty (open release PRs): ${_i}`}),null),PT=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Js(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ne(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},ET=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(p.info({msg:`Tool execution form descriptions unavailable (timeout): ${_i}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Rd=(e={})=>{let t=e.fetchBudgetMs??Bh;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=>Lh(r)&&RT(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([xn(ST(),t),xn(oe(),t)]);if(r===null||r.outcome!=="listed")return Vh(r,t);let o=PT(r.prs,n);return o.length===0?Vh({outcome:"empty"},t):Fh.object({version:Fh.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${ET(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:{...Lh(n)?n:{},version:r.version}}};var Wh=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],ji={worktree:"remove the worktree","ide-folders":"strip the worktree from configured editors",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},Rr="remove a release",Ue=e=>{throw p.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},Jh=(e,t)=>{throw p.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new E({...e,agentMode:A.source},2,t)},xT=e=>{ee()&&(e.version||Jh({status:"argument_required",argument:"version"},{operation:Rr,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&&Jh({status:"refused"},{operation:Rr,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"}))},Gh=e=>{e.pr?.state==="MERGED"&&Ue({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`})},TT=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ue({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)&&Ue({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||Ue({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)`}))},CT=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ue({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"})},$T=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ue({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(", ")}`})},AT=async e=>(await Sd`git -C ${e} status --porcelain`).stdout.split(`
409
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),OT=async e=>{try{let{terminals:t}=await Fu(e);return t.filter(r=>r.connected).length}catch(t){return p.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},IT=async e=>{let t=await Rs([e]);if(t!==null)throw p.warn({operation:Rr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new E({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:Rr,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`})},DT=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await mt();if(!n)return r;let o=await ut(ne(e),n),s=t.moveIssuesTo?await NT(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Bs(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:rr(n,o)}}},NT=async(e,t)=>{let r=await ut(e,t);return r||Ue({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}"`})},_T=async(e,t)=>{let r=K(e);r||Ue({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 x(),o=`${n}${ge}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([Ce("release"),Gr(e),$e(n,`refs/heads/${e}`),Or(n,e)]),d=i.includes(e);return d&&await IT(s),{...await DT(r,t),branch:e,id:r,label:Y(r),baseBranch:a?.baseRefName??Qe("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await OT(s):0,worktreeDirty:d?await AT(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Uh=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}),MT=(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}`},jT=(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: ${MT(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
410
+ `)},Mi=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},FT=e=>typeof e=="string"?e:e.outcome;async function Wo(e,t,r){try{let n=await r(),o=FT(n);return t.push({step:e}),p.info({step:e,outcome:o},`\u2705 ${ji[e]} \u2014 ${o}`),n}catch(n){throw new Mi(e,n)}}var LT=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),p.warn({err:Wt(n),step:e},`\u26A0\uFE0F ${ji[e]} failed (non-blocking)`)}},VT=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,BT=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(u=>VT(t,u)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Wh.indexOf(r)+1} of ${Wh.length} (${ji[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},WT=async e=>{let t=await Oo(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`});return{outcome:t.includes(e.branch)?"removed":"absent",removedBranches:t}},JT=e=>{let t=e.map(s=>({provider:s.provider,outcome:UT(s),removed:s.removed})),r=t.some(s=>s.outcome==="verified"),o=t.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:r?"verified":o,providers:t}},UT=e=>e.removed.length>0?"verified":"attempted",GT=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await LT("ide-folders",r,async()=>{let o=await kr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=JT(o)}),p.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${ji["ide-folders"]} \u2014 ${n.outcome}`),n},KT=async e=>{let t=await Gr(e.branch);if(Gh({...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 Sd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},HT=async e=>(await Ar()===e.branch&&await Sd`git switch ${e.baseBranch}`,await ms(e.branch),await pu(e.branch)?Ue({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"),qT=async e=>(await fs(e.branch),e.remoteTipSha?"deleted":"absent"),zT=async(e,t,r)=>{let n=await Bs(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}\``;Ue({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}`})},YT=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await zT(e,e.jira,e.jiraConfig),p.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Ic({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),XT=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree.outcome,ideFolders:t.ideFolders,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),ZT=async(e,t,r)=>{let n=await Wo("worktree",r,()=>WT(e)),o=await GT(e,n.removedBranches,r),s=await Wo("pr",r,()=>KT(e));p.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Wo("local-branch",r,()=>HT(e)),a=await Wo("remote-branch",r,()=>qT(e)),c=await Wo("jira",r,()=>YT(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},QT=async(e,t)=>{let r=[];try{return XT(e,await ZT(e,t,r))}catch(n){throw n instanceof Mi?BT({plan:e,step:n.step,done:r,cause:n.reason}):n}},eC=async e=>{if(e)return ft(e);h.setInteractive();let[t,r]=await Promise.all([oe(),F()]),n=r.map(s=>s.branch);n.length===0&&Ue({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 Dt(se({branches:n,descriptions:t,types:o}))}catch(s){throw we(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},Kh=Rd(),Fi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await be({operation:Rr}),await D(),await Ne({provider:Kh,params:e,operation:Rr,argument:"version"}),xT(e);try{let s=await _T(await eC(r),e);p.debug({plan:Uh(s)},"release remove: resolved plan"),Gh(s),TT(s,e),CT(s),await Zn({operation:`remove release ${s.label}`,base:s.baseBranch}),$T(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await W(t,jT(s,!!o),{throwOnDecline:!0,plan:{...Uh(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await QT(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw we(s)||ct(s)||s instanceof f?s:(p.error({err:Wt(s)},"\u274C Error removing release"),new f(s,{operation:Rr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Pd=R({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:Kh,inputSchema:{version:M.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:M.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:M.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:M.string().describe("The release branch that was targeted"),version:M.string().describe('The release label (e.g. "1.2.5")'),baseBranch:M.string().describe("The branch HEAD was moved to before the local delete"),worktree:M.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:M.object({outcome:M.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:M.array(M.object({provider:M.string(),outcome:M.enum(["verified","attempted","skipped"]),removed:M.array(M.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:M.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:M.number().nullable().describe("The pull request number, or null when none exists"),localBranch:M.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:M.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:M.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:M.string().nullable().describe("The origin tip before deletion"),jira:M.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:M.object({id:M.string(),name:M.string(),url:M.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Fi});import{spawnSync as oC}from"node:child_process";import{homedir as sC}from"node:os";import iC from"node:process";var tC=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},rC=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},nC=(e,t)=>{let r=tC(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},Jo=(e,t)=>{let r=[...rC(e),...nC(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Uo=e=>e.steps.map(Rt);var aC=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],cC=e=>{let t={...Bp(e)};for(let r of aC)delete t[r];return t},Ed=(e,t,r={})=>{let n=r.spawnSync??oC,o=r.env??iC.env,s=(r.agentMode??ee)(),i=Uo(e),a=Jo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:pC({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??lC}):{ran:!1,commands:i,refusedBecause:a.reasons}},lC=e=>{p.info(e)},qh=64,dC=qh*1024*1024,pC=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=cC(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:dC,cwd:sC(),env:s}),l=yC(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},uC=5,mC=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Hh=e=>e==null?[]:String(e).split(`
411
+ `).map(t=>t.trim()).filter(t=>t.length>0),fC=e=>{let t=Hh(e.stderr),r=Hh(e.stdout),n=[...t,...r].filter(s=>mC.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-uC).join(" / ")},gC="ENOBUFS",hC=e=>e.error?.code===gC,yC=e=>{if(hC(e))return`terminated after exceeding the ${qh} 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=fC(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var vC=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},wC=e=>{let t=De(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},kC=(e,t)=>{let r=wC(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=Jo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Uo(r),context:n}},Li=async(e=lr,t=ho())=>{let r=await vo(lr,t),n={owner:null,present:vC(r)},o=cl(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>kC(s.get(a),n)),context:n}};var xd=(e,t)=>({...Go(e),action:"skipped",commands:e.commands,detail:t}),Go=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),zh=(e,t)=>e.action==="none"?xd(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?xd(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Go(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},bC=(e,t)=>t.ran?t.ok?{...Go(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Go(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Go(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Td=async e=>{let t=e.run??Ed,{plans:r}=await Li(e.ids,e.probeDeps),n=[];for(let o of r){let s=zh(o,e.mode);if(s!==null){n.push(s);continue}n.push(bC(o,t(o.recipe,o.context)))}return n},Cd=async(e,t)=>{let{plans:r}=await Li(e,t);return r.map(n=>zh(n,"converge")??xd(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import jC from"node:process";import{z as T}from"zod";var $d={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},RC=Object.keys($d).sort((e,t)=>$d[e]-$d[t]),Yh={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},Xh=new Set(["manual","warn","fail"]),Ad=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 qe(e)}},SC=e=>e.reduce((t,r)=>Yh[r]>Yh[t]?r:t,"skipped"),Qh=e=>e.message.trim(),PC=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 "),Zh=e=>e.message===an,EC=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Qh(r):e.length>1?PC(e):t?"activate with the last line below":"see below"},xC=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Ad(i.outcome)),n=t.filter(i=>Xh.has(Ad(i.outcome))).map(Qh),o=t.filter(i=>!Xh.has(Ad(i.outcome))&&!Zh(i)),s={name:e,status:SC(r),message:EC(o,t.some(Zh))};return n.length>0?{...s,notes:n}:s},TC=e=>({label:"Local setup",rows:RC.map(t=>xC(t,e.filter(r=>r.step===t)))}),CC=(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 qe(e.action)}},$C=(e,t)=>{let r=CC(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},AC=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>$C(r,t))}),OC=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 qe(e)}},IC=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 qe(e)}},DC=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 qe(e)}},NC=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 qe(e.outcome)}},_C=(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 qe(e)}},MC=e=>({label:"Portless service",rows:[{name:"link",status:OC(e.link),message:DC(e.link)},{name:"node",status:IC(e.node.outcome),message:NC(e.node)},_C(e.service,e.command)]}),ey=(e,t)=>[TC(e.init),AC(e.tools,t),MC(e.portless)],ty=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var FC=()=>{let{link:e,node:t}=ls();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},LC=async e=>{let t=ru(e.link).outcome,r=tu(e.node),n=cs(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 Og(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=St(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},ny="--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.",VC=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||r))throw new Error(ny);return{ids:e.tools??t??lr,mode:r?"update":"converge",skipTools:n}},ry=(e,t)=>e instanceof sn?e.step:t.at(-1)?.step??"zshrc",BC=async()=>{let e=[];try{await Qc(t=>{e.push(t)})}catch(t){e.push({step:ry(t,e),outcome:"failed",message:`The ${ry(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},WC=(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}`}))},JC=async(e,t)=>{try{return e.skipTools?await Cd(e.ids,t.probeDeps):await Td({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return WC(e.ids,r)}},UC=e=>({step:e.step,outcome:e.outcome,message:e.message}),Vi=async(e={})=>{let t=VC(e),r=await BC(),n=await JC(t,e),o=await LC(e.portlessDeps??FC()),s=ey({init:r,tools:n,portless:o},{skipTools:t.skipTools});It({title:"infra-kit setup",sections:s},{ascii:e.ascii}),p.info(an),ty(s)&&(jC.exitCode=1);let i={init:r.map(UC),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},GC=T.object({step:T.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:T.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:T.string().describe("The same line a human running this would have read")}),KC=T.object({id:T.string().describe("Dependency id"),action:T.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:T.object({present:T.boolean(),onPath:T.boolean(),version:T.string().nullable(),manager:T.string()}).describe("The tool\u2019s state before this run"),commands:T.array(T.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:T.string().describe("Why, in one line")}),HC=T.object({link:T.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:T.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:T.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:T.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")}),qC={init:T.array(GC).describe("One entry per init step, in the order they ran"),tools:T.array(KC).describe("One result per requested dependency"),portlessService:HC.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:T.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:T.boolean().describe("Whether anything was installed or updated"),report:T.array(T.object({label:T.string().describe("Section heading"),rows:T.array(T.object({name:T.string().describe("Init step, tool id, or portless part"),status:T.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:T.string().describe("The row message, as printed"),notes:T.array(T.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:T.boolean().describe("Whether no tool failed (a refusal is not a failure)")},zC={tools:T.array(T.enum(lr)).optional().describe("Which tools to act on. Omit for all six."),mode:T.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:T.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},Od=R({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:zC,outputSchema:qC,requiresHumanConfirm:!0,handler:e=>Vi({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as sy}from"node:fs";import iy from"node:path";import i$ from"node:process";import{z as wt}from"zod";import{createHash as YC}from"node:crypto";import{readFileSync as XC}from"node:fs";var Sr=e=>YC("sha256").update(XC(e)).digest("hex");import{readFileSync as n$,writeFileSync as o$}from"node:fs";import Ui from"node:path";import{z as st}from"zod";var Z="vendor",ZC=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),QC=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),e$=[".tsbuildinfo"],Id=e=>ZC.has(e),Dd=e=>QC.has(e)?!0:e$.some(t=>e.endsWith(t)),Bi=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Id(o))||Dd(r)};import{readdirSync as t$}from"node:fs";import Nd from"node:path";var r$=e=>e.split(Nd.sep).join("/"),Wi=e=>{let t=[],r=n=>{for(let o of t$(n,{withFileTypes:!0})){let s=Nd.join(n,o.name);if(o.isDirectory()){if(Id(o.name))continue;r(s);continue}Dd(o.name)||t.push(r$(Nd.relative(e,s)))}};return r(e),t.sort()};var je=".sync-manifest.json",Ji=1,s$=st.object({schemaVersion:st.number().optional(),source:st.string(),commit:st.string(),syncedAt:st.string(),fileCount:st.number(),files:st.record(st.string(),st.string())}),_d=e=>(e.schemaVersion??Ji)>Ji,oy=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Wi(e);for(let o of n)try{r[o]=Sr(Ui.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},Ko=e=>{let t=Ui.join(e,je),r;try{r=n$(t,"utf8")}catch{throw new Error(`Missing ${je} at ${t}`)}let n=s$.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${je} at ${t}: ${st.prettifyError(n.error)}`);return n.data},Md=(e,t,r)=>{let n=oy(e,r),o={schemaVersion:Ji,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return o$(Ui.join(e,je),`${JSON.stringify(o,null,2)}
412
+ `),o},jd=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Bi(c))),n=Wi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Sr(Ui.join(e,c))!==r[c]&&o.push(c)}let i=new Set(n),a=Object.keys(r).filter(c=>!i.has(c));return{modified:o,added:s,removed:a}};var Fd=30,Ld=(e,t)=>{if(t.length!==0){p.info(`
413
+ ${e} (${t.length}):`);for(let r of t.slice(0,Fd))p.info(` ${r}`);t.length>Fd&&p.info(` \u2026and ${t.length-Fd} more`)}},Gi=async(e={})=>{let t=e.cwd??await x(),r=iy.join(t,Z),n={modified:[],added:[],removed:[],fileCount:0};if(!sy(r)){p.info(`\u2139\uFE0F No ${Z}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!sy(iy.join(r,je))){p.error(`\u274C Missing ${Z}/${je}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=Ko(r);if(_d(o)){p.error(`\u274C ${Z}/${je} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=jd(r,o),c=s.length>0||i.length>0||a.length>0;c?(p.error(`\u274C ${Z}/ has drifted from ${Z}/${je}.`),p.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Ld("Modified",s),Ld("Added (not in manifest)",i),Ld("Removed (in manifest, now missing)",a)):p.info(`\u2705 ${Z}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},a$={status:wt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:wt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:wt.number(),modified:wt.array(wt.string()),added:wt.array(wt.string()),removed:wt.array(wt.string())},Vd=R({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:a$,handler:()=>Gi({cwd:i$.cwd()})});import ay from"node:process";import{z as Ho}from"zod";var cy=async e=>{try{return await e()}catch{return null}},Ki=async()=>{let e=q.version;p.info(e);let t=await cy(x),r=t===null?null:await cy(()=>Le(t)),n={version:e,cwd:ay.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:ay.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Bd=R({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:Ho.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Ho.string().describe("The working directory of this process"),repoRoot:Ho.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Ho.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Ho.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ki});import dy from"@inquirer/confirm";import c$ from"node:path";import{z as U}from"zod";import{$ as qo}from"zx";var Hi="create worktrees",l$=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Wd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),qi=async e=>{let{confirmedCommand:t,all:r,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await be({operation:Hi});try{let a=await Ce("release"),c=await x(),l=`${c}${ge}`;await ly(`${l}/${Cr.release}`),await ly(`${l}/${Cr.feature}`);let d=[];if(n)d=n.split(",").map(j=>Te(ve(j.trim())));else{let j=await F(),Ke=j.map(xe=>xe.branch);if(Ke.length===0){p.info("\u2139\uFE0F No open release branches found"),h.print();let xe={createdWorktrees:[],count:0,...Wd()};return{content:k(JSON.stringify(xe,null,2)),structuredContent:xe}}if(r)d=Ke;else{h.setInteractive();let xe=new Map(j.map(ts=>[ts.branch,ts.type])),ha=await oe();d=await Nt(se({branches:Ke,descriptions:ha,types:xe}),{required:!0})}}r?h.addOption("--all",!0):h.addOption("--versions",nr(d));let u=await D(),m=i??(Tt(u).length>0?"workspace":"none");h.addOption("--ide",m);let g=await d$(o,u),y=await p$(s,u),S=await Le(c),v=c$.basename(S),C=y?await u$({explicit:s!==void 0,mainRepoRoot:S}):null;await W(t,m$(C,v)),t||h.addOption("--yes",!0);let _=C?await f$(C,S):null,{branchesToCreate:O}=v$({selectedReleaseBranches:d,currentWorktrees:a}),P=await w$(O,l);if(k$(P),m==="workspace"&&await bd({projectRoot:c,worktreeDir:l,branches:P}),g)for(let j of P)await qo`github ${l}/${j}`,await qo`sleep 5`;let G=_?await h$({registration:_,createdWorktrees:P,worktreeDir:l,mainRepoRoot:S,repoName:v,config:u}):Wd();y$(G),h.print();let B={createdWorktrees:P,count:P.length,...G};return{content:k(JSON.stringify(B,null,2)),structuredContent:B}}catch(a){throw we(a)||a instanceof E?a:(p.debug({err:a},"Error managing worktrees"),new f(a,{operation:Hi,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},d$=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await I(o=>dy({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},p$=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await I(o=>dy({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},py=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"},u$=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Ir();if(n!=="ready"){let{reason:s,text:i}=py(n);if(t)throw p.warn({operation:Hi},`\u26D4 --orca was passed but ${i}`),new E({status:"refused",reason:s,agentMode:A.source},2,{operation:Hi,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 p.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await Vu(r);return{probe:n,registered:o.registered,visibility:o.visibility}},m$=(e,t)=>{let r=["Are you sure you want to proceed with these worktree changes?"];return e?.probe==="ready"&&!e.registered&&r.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),r.join(`
414
+ `)},f$=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:py(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Bu(t);return{kind:"ready",visibility:r}}catch(r){return p.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof bs?r.code:void 0}}},g$=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,h$=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Wd();if(t.kind==="skip"){for(let u of r)a.orcaSkipped.push({branch:u,reason:t.reason,code:t.code});return a}let c=Ru(i),l=r.length===1&&t.visibility!=="hide",d=Ju();for(let u of r){let m=`${n}/${u}`;try{let{layout:g}=await Uu({cwd:m,title:Gu({branch:u}),focus:l,layout:"full",panes:c,poll:d});await Wu(o,m)?a.orcaOpened.push({branch:u,layout:g}):a.orcaHidden.push({branch:u,path:m,fix:g$(s)})}catch(g){p.warn({error:g,branch:u},`\u26A0\uFE0F Failed to open Orca terminals for ${u}`),g instanceof bs&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:u,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:u,reason:"orca_error",code:g instanceof bs?g.code:void 0})}}return a},y$=e=>{for(let t of e.orcaOpened)p.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)p.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})`:"";p.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},ly=async e=>{await qo`mkdir -p ${e}`},v$=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>us(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},w$=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o}`;return await qo`git worktree add ${s} ${o}`,await qo({cwd:s})`pnpm install`,o})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o],a=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});p.error({error:s.reason,msg:a.message})}return n},k$=e=>{if(e.length>0){p.info("\u2705 Created git worktrees:");for(let t of e)p.info(t);p.info("")}else p.info("\u2139\uFE0F No new git worktrees to create")},Jd=R({name:"worktrees-add",description:`Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \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:{all:U.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:U.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:U.enum(br).optional().describe('Editor open mode for created worktrees, applied to the configured editor (Cursor, per the "ide" config). "workspace" (the only attach style) adds each worktree to the Cursor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when an "ide" is configured \u2192 "none" otherwise.'),cursor:U.enum(br).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:U.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:U.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{createdWorktrees:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created"),orcaOpened:U.array(U.object({branch:U.string(),layout:U.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:U.array(U.object({branch:U.string(),reason:U.enum(l$),code:U.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:U.array(U.object({branch:U.string(),path:U.string(),fix:U.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:qi});import{z as Tn}from"zod";var zi=async()=>{await D();let e=await Ce("release");if(e.length===0)return p.info("\u2139\uFE0F No active worktrees found"),{content:k(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[t,r]=await Promise.all([F(),oe()]),n=new Map(t.map(c=>[c.branch,c.type])),o=e.flatMap(c=>{let l=K(c);if(!l)return[];let d=Y(l),u=n.get(c)||"regular",m=r.get(ne(l))||null;return[{version:d,type:u,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let l=so(c.version,c.type,s);return c.description?`${l} ${c.description}`:l});p.info(`\u{1F33F} Active worktrees:
415
415
 
416
416
  ${i.join(`
417
- `)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},Wd=R({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:Sn.array(Sn.object({version:Sn.string().describe("Release version"),type:Sn.enum(["regular","hotfix"]).describe("Release type"),description:Sn.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Sn.number().describe("Number of worktrees")},handler:Hi});import{z as Sr}from"zod";var f$=e=>{if(Q()){if(e.all)throw new x({status:"refused",agentMode:A.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)throw new x({status:"argument_required",argument:"versions",agentMode:A.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions"})}},g$=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},h$=async(e,t)=>{let r=await ys(t.map(n=>`${e}/${n}`));if(r!==null)throw new x({status:"refused",reason:"orca_caller_inside_target",agentMode:A.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`})},qi=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await be({operation:"remove worktrees"}),await I(),f$({all:r,versions:n});try{let o=await Ce("release");if(o.length===0){p.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let s=await S(),i=`${s}${ge}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(d=>Te(ve(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([oe(),F()]),m=new Map(u.map(g=>[g.branch,g.type]));a=await Nt(se({branches:o,descriptions:d,types:m}),{required:!0})}g$(a,o);let c=a.length===o.length;c?h.addOption("--all",!0):h.addOption("--versions",nr(a)),await h$(i,a),await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let l=await yr({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await kr({projectRoot:s,worktreeDir:i,removedWorktrees:l.removed}),So(l),h.print(),Eo({result:l,operation:"remove worktrees"})}catch(o){throw we(o)||o instanceof f?o:(p.error({error:o},"\u274C Error managing worktrees"),new f(o,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Jd=R({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (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 version must be an active worktree, or the call errors without removing anything. What survives: the release 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:Sr.string().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Required: each must name an active worktree, or the call errors before removing anything.'),confirm:Sr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Sr.array(Sr.string()).describe("List of removed git worktree branches"),failedWorktrees:Sr.array(Sr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Sr.number().describe("Number of git worktrees removed")},handler:qi});import{z as Uo}from"zod";var zi=async e=>{let{confirmedCommand:t}=e;await be({operation:"sync worktrees"}),await I();try{let r=await Ce("release"),n=await S(),o=`${n}${ge}`,s=await Is();await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=y$({releasePRsList:s,currentWorktrees:r}),a=await yr({branches:i,worktreeDir:o,projectRoot:n});return await kr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),So(a),h.print(),Eo({result:a,operation:"sync worktrees"})}catch(r){throw we(r)||r instanceof f?r:(p.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},y$=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>as(s)).filter(s=>!t.includes(s))}},Ud=R({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:Uo.array(Uo.string()).describe("List of removed worktree branches"),failedWorktrees:Uo.array(Uo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Uo.number().describe("Number of worktrees removed during sync")},handler:zi});var Gd=[{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"}],fr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:gc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:xl,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:jl,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Ql,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:md,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:gd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Yl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Zl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Ll,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Rd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:cd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:ld,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Bd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Wd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Jd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Ud,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Il,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:$l,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Dl,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Cl,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Nl,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:uc,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{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:Fd,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,humanOnly:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:$d,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:bl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:pc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Ld,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]}];var Kd=e=>fr.filter(t=>t.menuGroup===e),Hd=e=>fr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var v$=(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},dy=e=>Gd.flatMap(({key:t,label:r})=>Kd(t).flatMap(n=>{let o=v$(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import qd from"node:process";var w$="MODULE_TYPELESS_PACKAGE_JSON",k$=(e,t)=>typeof e=="object"&&e!==null?e.code:t,py=!1,zd=()=>{if(py)return;py=!0;let e=qd.emitWarning.bind(qd);qd.emitWarning=((t,...r)=>{k$(r[0],r[1])!==w$&&e(t,...r)})};import{Command as BA,InvalidArgumentError as WA}from"commander";import{resolve as JA}from"node:path";import Fe from"node:process";import{cd as UA}from"zx";import uy from"node:process";import{$ as b$}from"zx";var Yd=async()=>{let e=await te(),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 ee(i.path)}))),r=t.at(-1)?.exists===!0,n=await co(e.userProject,r),o=r?lo(n):"";p.info(`Project name: ${e.projectName}
417
+ `)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},Ud=R({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:Tn.array(Tn.object({version:Tn.string().describe("Release version"),type:Tn.enum(["regular","hotfix"]).describe("Release type"),description:Tn.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Tn.number().describe("Number of worktrees")},handler:zi});import{z as Pr}from"zod";var b$=e=>{if(ee()){if(e.all)throw new E({status:"refused",agentMode:A.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)throw new E({status:"argument_required",argument:"versions",agentMode:A.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions"})}},R$=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},S$=async(e,t)=>{let r=await Rs(t.map(n=>`${e}/${n}`));if(r!==null)throw new E({status:"refused",reason:"orca_caller_inside_target",agentMode:A.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`})},Yi=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await be({operation:"remove worktrees"}),await D(),b$({all:r,versions:n});try{let o=await Ce("release");if(o.length===0){p.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let s=await x(),i=`${s}${ge}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(d=>Te(ve(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([oe(),F()]),m=new Map(u.map(g=>[g.branch,g.type]));a=await Nt(se({branches:o,descriptions:d,types:m}),{required:!0})}R$(a,o);let c=a.length===o.length;c?h.addOption("--all",!0):h.addOption("--versions",nr(a)),await S$(i,a),await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let l=await yr({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await kr({projectRoot:s,worktreeDir:i,removedWorktrees:l.removed}),$o(l),h.print(),Ao({result:l,operation:"remove worktrees"})}catch(o){throw we(o)||o instanceof f?o:(p.error({error:o},"\u274C Error managing worktrees"),new f(o,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Gd=R({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (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 version must be an active worktree, or the call errors without removing anything. What survives: the release 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:Pr.string().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Required: each must name an active worktree, or the call errors before removing anything.'),confirm:Pr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Pr.array(Pr.string()).describe("List of removed git worktree branches"),failedWorktrees:Pr.array(Pr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Pr.number().describe("Number of git worktrees removed")},handler:Yi});import{z as zo}from"zod";var Xi=async e=>{let{confirmedCommand:t}=e;await be({operation:"sync worktrees"}),await D();try{let r=await Ce("release"),n=await x(),o=`${n}${ge}`,s=await Fs();await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=P$({releasePRsList:s,currentWorktrees:r}),a=await yr({branches:i,worktreeDir:o,projectRoot:n});return await kr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),$o(a),h.print(),Ao({result:a,operation:"sync worktrees"})}catch(r){throw we(r)||r instanceof f?r:(p.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},P$=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>us(s)).filter(s=>!t.includes(s))}},Kd=R({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:zo.array(zo.string()).describe("List of removed worktree branches"),failedWorktrees:zo.array(zo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:zo.number().describe("Number of worktrees removed during sync")},handler:Xi});var Hd=[{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"}],fr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:yc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:Cl,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:Ll,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:td,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:gd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Zl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:ed,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Bl,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Pd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:dd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:pd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Jd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Ud,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Gd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Kd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:_l,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Ol,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Nl,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Al,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Ml,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:fc,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{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:Vd,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,humanOnly:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:Od,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Sl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:mc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Bd,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:null,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 qd=e=>fr.filter(t=>t.menuGroup===e),zd=e=>fr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var E$=(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},uy=e=>Hd.flatMap(({key:t,label:r})=>qd(t).flatMap(n=>{let o=E$(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Yd from"node:process";var x$="MODULE_TYPELESS_PACKAGE_JSON",T$=(e,t)=>typeof e=="object"&&e!==null?e.code:t,my=!1,Xd=()=>{if(my)return;my=!0;let e=Yd.emitWarning.bind(Yd);Yd.emitWarning=((t,...r)=>{T$(r[0],r[1])!==x$&&e(t,...r)})};import{Command as XA,InvalidArgumentError as ZA}from"commander";import{resolve as QA}from"node:path";import Fe from"node:process";import{cd as eO}from"zx";import fy from"node:process";import{$ as C$}from"zx";var Zd=async()=>{let e=await te(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await X(i.path)}))),r=t.at(-1)?.exists===!0,n=await fo(e.userProject,r),o=r?go(n):"";p.info(`Project name: ${e.projectName}
418
418
  `),p.info(`Config merge chain (later overrides earlier):
419
- `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";p.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}},Xd=async()=>{let e=await te(),t=uy.env.EDITOR||uy.env.VISUAL||"vi",r=await Zr(e);r.createdConfig&&p.info(Qr(r)),p.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await b$({stdio:"inherit"})`${t} ${e.userProject}`,Ct();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var my="https://dashboard.doppler.com/workplace/projects",R$=(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}"): ${my}/${e}`],Zd=async({env:e})=>{let r=!!(await ue())?.envs[e];await Nu(e);let n=await We(),o=await ct();r?p.info(`Removed the "${e}" service token from ${w(o)}.`):p.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of R$(n,e))p.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${my}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import P$ from"@inquirer/password";import Xi from"node:process";import{$ as Yi}from"zx";var S$=async({stdin:e,fromEnv:t})=>{if(e)return{token:await E$(),source:"stdin"};if(t){let n=Xi.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return h.setInteractive(),{token:(await D(n=>P$({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:Xi.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},E$=async()=>{let e=[];Xi.stdin.setEncoding("utf8");for await(let t of Xi.stdin)e.push(t);return e.join("").trim()},Qd="DOPPLER_CONFIG",x$=3e4,T$=async(e,t,r)=>{let n=Yi.quiet;Yi.quiet=!0;let o;try{o=(await Yi({env:vn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(x$)).stdout}catch(s){throw C$(s,r)}finally{Yi.quiet=n}return gi(o)},C$=(e,t)=>{let r=$r(e)??(e instanceof Error?e.message:String(e));if(ir(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=ar(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(`
420
- `))},$$=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Qd}.`,"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(`
421
- `),ep=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await We(),{token:s,source:i}=await S$({stdin:t,fromEnv:r});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await T$(s,o,e);fi(a,e);let c=a.some(([u])=>u===Qd);if(!c&&!n)throw new Error($$(e));await Iu(e,s);let l=await ct();p.info(`Stored the "${e}" service token (${kn(s)}) in ${w(l)} (mode 0600).`),c||p.warn(`Scope was NOT verified (no ${Qd} in the payload) \u2014 written because --force was given.`);let d={env:e,source:i,redactedToken:kn(s),storePath:l,scopeVerified:c};return h.print(),{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var tp=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,u=await ql(n);if(r&&h.addOption("--from",u),Hl(u,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),u==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Ri({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Pi({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},rp=async e=>tp(e,"all"),np=async e=>tp(e,"selected"),Zi=async(e,t)=>{let r=`release deploy-${t} --from local`;return p.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),tp({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as gy}from"@slip-stream-kit/config/internal";import op from"node:fs/promises";import sp from"node:path";import fy from"node:process";import{pathToFileURL as A$}from"node:url";var hy="~/projects",ip=async(e={})=>{if(e.init){await D$(e.cwd);return}await O$()},O$=async()=>{let e=tn(),t=await ee(e);if(p.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){p.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),fy.exitCode=1;return}let{workspaceDir:r,targets:n}=await Xs(),o=Ys(r),s=await ee(o);p.info(`workspaceDir: ${r} (resolved: ${o}) ${s?"[\u2713 exists]":"[ ] not found"}`),p.info("Targets:");let i=s;for(let a of n){let c=sp.join(o,a),l=await ee(c);l||(i=!1);let d=l?"[\u2713]":"[ ]",u=l?"":" (not found \u2014 clone or remove)";p.info(` ${d} ${a} ${w(c)}${u}`)}i||(fy.exitCode=1)},D$=async e=>{let t=tn();if(await ee(t)){p.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await S(),n=await I$(r);await op.mkdir(sp.dirname(t),{recursive:!0}),await op.writeFile(t,N$(n),"utf-8"),p.info(`\u2713 Created ${w(t)}`),n.length>0&&p.info(` Seeded ${n.length} target(s) from the source ${gy}.`),p.info(` Edit \`workspaceDir\` (placeholder: ${hy}) to point at where your repos live.`),n.length===0&&p.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},I$=async e=>{try{let t=sp.join(e,gy),r=await op.stat(t),s=(await import(`${A$(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[]},N$=e=>`${JSON.stringify({workspaceDir:hy,targets:e},null,2)}
422
- `;import yp from"node:process";import{chmodSync as W$,copyFileSync as J$,lstatSync as U$,mkdirSync as xy,readdirSync as G$,readlinkSync as K$,rmdirSync as Ty,symlinkSync as H$,unlinkSync as q$,writeFileSync as z$}from"node:fs";import ye from"node:path";import{lstatSync as _$,readlinkSync as yy}from"node:fs";import M$ from"node:path";var j$=new Set(["ENOENT","ENOTDIR"]),Qi=e=>{let t;try{t=_$(e)}catch(r){if(j$.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:yy(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Pr(e)}:{kind:"other"}},vy=(e,t)=>{let r=M$.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:yy(r)}:{kind:"file",executable:t.mode==="100755",sha:Pr(r)};return{...t,fingerprint:n}},wy=(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 F$}from"zx";var Z=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await F$({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ea=e=>e.slice(0,7),Gt=e=>e.split("\0").filter(t=>t.length>0);import L$ from"node:path";var ap=`${X}/`,Kt=`${X}/README.md`,Go=`${X}/${je}`,by=e=>e.startsWith(ap),ky=e=>{let t=L$.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},Ry=e=>{let t=ky(e.path),r=e.target===void 0?t:ky(e.target);return{path:t,target:r,vendored:by(r)}},Py=e=>e.copy.map(Ry),Ko=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Ho=(e,t)=>e.filter(r=>!Ko(r.path,t)),ta=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,En=e=>[...new Set(e)].sort(),Sy=e=>e.startsWith(ap)?e.slice(ap.length):null;var ra=e=>`# vendor/ \u2014 mirrored from ${e}
419
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";p.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}},Qd=async()=>{let e=await te(),t=fy.env.EDITOR||fy.env.VISUAL||"vi",r=await Qr(e);r.createdConfig&&p.info(en(r)),p.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await C$({stdio:"inherit"})`${t} ${e.userProject}`,Ct();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var gy="https://dashboard.doppler.com/workplace/projects",$$=(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}"): ${gy}/${e}`],ep=async({env:e})=>{let r=!!(await ue())?.envs[e];await ju(e);let n=await We(),o=await lt();r?p.info(`Removed the "${e}" service token from ${w(o)}.`):p.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of $$(n,e))p.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${gy}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import A$ from"@inquirer/password";import Qi from"node:process";import{$ as Zi}from"zx";var O$=async({stdin:e,fromEnv:t})=>{if(e)return{token:await I$(),source:"stdin"};if(t){let n=Qi.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return h.setInteractive(),{token:(await I(n=>A$({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:Qi.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},I$=async()=>{let e=[];Qi.stdin.setEncoding("utf8");for await(let t of Qi.stdin)e.push(t);return e.join("").trim()},tp="DOPPLER_CONFIG",D$=3e4,N$=async(e,t,r)=>{let n=Zi.quiet;Zi.quiet=!0;let o;try{o=(await Zi({env:bn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(D$)).stdout}catch(s){throw _$(s,r)}finally{Zi.quiet=n}return yi(o)},_$=(e,t)=>{let r=$r(e)??(e instanceof Error?e.message:String(e));if(ir(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=ar(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(`
420
+ `))},M$=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${tp}.`,"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(`
421
+ `),rp=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await We(),{token:s,source:i}=await O$({stdin:t,fromEnv:r});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await N$(s,o,e);hi(a,e);let c=a.some(([u])=>u===tp);if(!c&&!n)throw new Error(M$(e));await Mu(e,s);let l=await lt();p.info(`Stored the "${e}" service token (${Sn(s)}) in ${w(l)} (mode 0600).`),c||p.warn(`Scope was NOT verified (no ${tp} in the payload) \u2014 written because --force was given.`);let d={env:e,source:i,redactedToken:Sn(s),storePath:l,scopeVerified:c};return h.print(),{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var np=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,u=await Yl(n);if(r&&h.addOption("--from",u),zl(u,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),u==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Pi({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Ei({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},op=async e=>np(e,"all"),sp=async e=>np(e,"selected"),ea=async(e,t)=>{let r=`release deploy-${t} --from local`;return p.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),np({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as yy}from"@slip-stream-kit/config/internal";import ip from"node:fs/promises";import Cn from"node:path";import hy from"node:process";import{pathToFileURL as j$}from"node:url";var vy="~/projects",ap=async(e={})=>{if(e.init){await L$(e.cwd);return}await F$()},F$=async()=>{let e=rn(),t=await X(e);if(p.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){p.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),hy.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await Qs(),s=nn(r),i=await X(s),a=Cn.join(s,n),c=await X(a);p.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),p.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${w(a)}${c?"":" (not found \u2014 clone it)"}`),p.info("Targets:");let l=i&&c;for(let d of o){let u=Cn.join(s,d),m=await X(u);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";p.info(` ${g} ${d} ${w(u)}${y}`)}l||(hy.exitCode=1)},L$=async e=>{let t=rn();if(await X(t)){p.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await x(),n=await V$(r);await ip.mkdir(Cn.dirname(t),{recursive:!0}),await ip.writeFile(t,B$(Cn.basename(r),n),"utf-8"),p.info(`\u2713 Created ${w(t)}`),n.length>0&&p.info(` Seeded ${n.length} target(s) from the source ${yy}.`),p.info(` Edit \`workspaceDir\` (placeholder: ${vy}) to point at where your repos live.`),p.info(` \`source\` is seeded with ${Cn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&p.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},V$=async e=>{try{let t=Cn.join(e,yy),r=await ip.stat(t),s=(await import(`${j$(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[]},B$=(e,t)=>`${JSON.stringify({workspaceDir:vy,source:e,targets:t},null,2)}
422
+ `;import{existsSync as FA}from"node:fs";import LA from"node:fs/promises";import Vy from"node:path";import kp from"node:process";import{z as VA}from"zod";import{chmodSync as z$,copyFileSync as Y$,lstatSync as X$,mkdirSync as Cy,readdirSync as Z$,readlinkSync as Q$,rmdirSync as $y,symlinkSync as eA,unlinkSync as tA,writeFileSync as rA}from"node:fs";import ye from"node:path";import{lstatSync as W$,readlinkSync as wy}from"node:fs";import J$ from"node:path";var U$=new Set(["ENOENT","ENOTDIR"]),ta=e=>{let t;try{t=W$(e)}catch(r){if(U$.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:wy(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Sr(e)}:{kind:"other"}},ky=(e,t)=>{let r=J$.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:wy(r)}:{kind:"file",executable:t.mode==="100755",sha:Sr(r)};return{...t,fingerprint:n}},by=(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 G$}from"zx";var Q=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await G$({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ra=e=>e.slice(0,7),Gt=e=>e.split("\0").filter(t=>t.length>0);import K$ from"node:path";var cp=`${Z}/`,Kt=`${Z}/README.md`,Yo=`${Z}/${je}`,Sy=e=>e.startsWith(cp),Ry=e=>{let t=K$.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},Py=e=>{let t=Ry(e.path),r=e.target===void 0?t:Ry(e.target);return{path:t,target:r,vendored:Sy(r)}},Ey=e=>e.copy.map(Py),Xo=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Zo=(e,t)=>e.filter(r=>!Xo(r.path,t)),na=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,$n=e=>[...new Set(e)].sort(),xy=e=>e.startsWith(cp)?e.slice(cp.length):null;var oa=e=>`# vendor/ \u2014 mirrored from ${e}
423
423
 
424
424
  **DO NOT EDIT files in this folder here.**
425
425
 
@@ -430,19 +430,19 @@ fail \`ik vendor check\` in CI.
430
430
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
431
431
 
432
432
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
433
- `;var V$=new Set(["100644","100755","120000"]),B$=(e,t)=>{let r=new Map;for(let n of Gt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!V$.has(s)||Ko(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},na=async(e,t,r)=>{let n=await Z(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return B$(n,r)},Ey=async e=>Gt(await Z(e,["--literal-pathspecs","ls-files","-z","--",X]));var xn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],Cy=e=>{let t=Qi(e);t!==null&&(t.kind==="other"?Ty(e):q$(e))},Y$=(e,t,r)=>{let n=ye.join(e,r.source),o=ye.join(t,r.target);if(xy(ye.dirname(o),{recursive:!0}),Cy(o),r.mode==="120000"){H$(K$(n),o);return}J$(n,o),W$(o,r.mode==="100755"?493:420)},X$=async(e,t)=>{let r=new Set;for(let n of Gt(await Z(e,["ls-files","-z"]))){if(t.has(n))continue;let o=ye.posix.dirname(n);for(;o!==".";)r.add(o),o=ye.posix.dirname(o)}return r},Z$=async(e,t)=>{if(t.length===0)return;let r=await X$(e,new Set(t)),n=[...new Set(t.map(o=>ye.dirname(ye.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)&&!(!U$(s,{throwIfNoEntry:!1})?.isDirectory()||G$(s).length>0||r.has(ye.relative(e,s).split(ye.sep).join("/")));)Ty(s),s=ye.dirname(s)}},$y=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Kt,...s].map(Sy).filter(a=>a!==null&&!Li(a));return En(i)},Ay=async(e,t,r,n)=>{let o=ye.join(e,X);xy(o,{recursive:!0}),z$(ye.join(e,Kt),ra(t.name));let s=$y(r,await Ey(e),n);Nd(o,{source:t.name,commit:t.headSha},s)},cp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(xn(t));let n=ye.resolve(t.root),o=[...t.legacy,...t.entries.flatMap(a=>a.deletes)];for(let a of o)Cy(ye.join(n,a));await Z$(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)Y$(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await Ay(n,e,t.entries,o),{touched:En([...o,...i,Kt,Go]),manifestWritten:!0}):{touched:En([...o,...i]),manifestWritten:!1}},lp=async(e,t)=>(await Ay(e,t,[],[]),[Kt,Go]);var dp=(e,t)=>`[ROOT] vendor: sync from ${e}@${ea(t)}`,Q$=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
434
- `).trim()||String(e)},pp=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Z(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Z(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:Q$(s)}}};var eA=20,tA=20,Oy=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],Dy=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of Ho(e.files,r)){let u=ta(d.path,n);if(s.push(u),wy(d.fingerprint,t.onDisk[u]??null))continue;let m=o.has(u)?"modified":"added";i.push({source:d.path,target:u,mode:d.mode,change:m})}let a=new Set(s),c=Ho(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},qo=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],legacy:[],writeVendorMeta:!1,recoveryPaths:[]}),up=e=>[...e.entries.map(t=>t.entry.target),...e.legacyCleanup],rA=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...up(e)];return qo(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...Oy(r,eA),Rt(n)])},nA=(e,t)=>{if(e.kind==="unknown-sha")return{notes:[],warnings:["no manifest commit recorded, so the source commits since the last sync are unknown"]};let r=ea(e.sha);return e.kind==="unresolvable"?{notes:[],warnings:[`manifest commit ${r} is not in ${t}, so the changelog is unknown`]}:{notes:[`${e.lines.length} ${t} commit(s) since ${r}`,...Oy(e.lines,tA)],warnings:[]}},oA=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},sA=(e,t)=>{let r=o=>e.reduce((s,i)=>s+i.counts[o],0),n=t.length>0?`, ${t.length} legacy removed`:"";return`${r("added")} added, ${r("modified")} modified, ${r("removed")} removed${n}`},iA=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return En([...n,...t.legacy,...r?t.headVendorMeta:[]])},aA=(e,t)=>{if(t.dirty.length>0)return rA(e,t,t.dirty);let r=e.entries.map((d,u)=>{let m=t.entries[u]??{target:d.entry.target,tracked:[],onDisk:{}};return Dy(d,m,e.exclude)}),n=r.some(d=>d.vendored),o=r.some(d=>d.writes.length+d.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...qo(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&t.legacy.length===0&&!s)return i;let a=nA(t.changelog,e.name),c=r.map(oA).filter(d=>d!==null),l=t.legacy.length>0?[`legacy: ${t.legacy.length} tracked file(s) removed`]:[];return{...i,status:"changed",message:`${sA(r,t.legacy)} on ${t.branch}`,notes:[...c,...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:a.warnings,legacy:t.legacy,recoveryPaths:iA(r,t,n)}},oa=(e,t)=>{switch(t.kind){case"missing":return qo(t,"skipped",`not checked out at ${t.root}`);case"source":return qo(t,"skipped","this is the source repo");case"not-git":return qo(t,"fail",`not a git repo: ${t.reason}`);case"repo":return aA(e,t)}};import{existsSync as cA,readFileSync as lA,realpathSync as sa}from"node:fs";import ia from"node:path";var mp=async(e,t)=>{let r=t.exclude??[],n=(await Z(e,["rev-parse","HEAD"])).trim(),o=await Le(e),s=await Promise.all(Py(t).map(async i=>{let a=await na(e,i.path,r);return{entry:i,files:a.map(c=>vy(e,c))}}));return{root:e,selfRoots:[...new Set([sa(e),sa(o)])],name:ia.basename(o),headSha:n,entries:s,exclude:r,legacyCleanup:t.legacyCleanup??[]}},aa=e=>{let t=Gt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},dA=async(e,t)=>{let r=await Z(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...up(e)]);return aa(r).filter(n=>!Ko(n,e.exclude))},pA=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await na(t,r.target,e.exclude),s={};for(let i of Ho(n,e.exclude)){let a=ta(i.path,r);s[a]=Qi(ia.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),uA=async(e,t)=>(await Promise.all(e.legacyCleanup.map(n=>na(t,n,e.exclude)))).flat().map(n=>n.path),mA=async e=>{try{return Gt(await Z(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Kt,Go]))}catch{return[]}},fA=e=>{try{return Bo(ia.join(e,X)).commit}catch{return null}},gA=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await $e(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await Z(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
435
- `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},hA=(e,t)=>{try{return lA(ia.join(e,Kt),"utf8")===ra(t)}catch{return!1}},yA=async e=>{try{return{toplevel:(await Z(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
436
- `)[0]??"git rev-parse failed"}}},vA=async e=>{try{return(await Z(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},ca=async(e,t)=>{if(!cA(t.root))return{...t,kind:"missing"};let r=sa(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await yA(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(sa(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=fA(t.root),[s,i,a,c,l,d]=await Promise.all([vA(t.root),dA(e,t.root),pA(e,t.root),uA(e,t.root),mA(t.root),gA(e,o)]);return{...t,kind:"repo",branch:s,dirty:i,entries:a,legacy:c,headVendorMeta:l,readmeCurrent:hA(t.root,e.name),manifestPresent:o!==null,changelog:d}};var wA=20,kA=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],bA=(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:",Rt(xn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:kA(r,t)}},RA=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(`
437
- `).slice(0,wA)},PA=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[bA(e,t),...r,...e.commit?[RA(e.commit)]:[]]}},SA={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},fp=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:SA[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>PA(o,r))],hints:n}},Iy=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail"));var EA=20,gp=async(e,t)=>(await Z(e,t,{allowFailure:!0})).trim(),xA=async e=>aa(await Z(e,["status","--porcelain","-z","--untracked-files=normal"])),TA=async e=>(await gp(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"]},CA=async e=>{let[t,r]=await Promise.all([gp(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),gp(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}`}},Ny=async e=>{let t=await xA(e);if(t.length>0){let n=t.slice(0,EA),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new x({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([TA(e),CA(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import $A from"node:path";var _y=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new x({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=Ys(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:$A.join(n,s)}))},AA="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",OA=async(e,t)=>{let r=await ca(e,t),n=oa(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${AA} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],legacy:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},My=async(e,t,r)=>Promise.all(t.map(async n=>r?OA(e,n):oa(e,await ca(e,n))));var vp="sync vendored files",DA=()=>{if(Q())throw new x({status:"refused",agentMode:A.source},2,{operation:vp,stderrExcerpt:"vendor sync is human-only: refused in agent mode regardless of --yes",remediation:"ask a human to run `infra-kit vendor sync` from their own shell \u2014 a sync is never confirmed by an agent"})},IA=()=>{if(!yp.stdin.isTTY)throw new x({status:"refused",reason:"no-tty"},2,{operation:vp,stderrExcerpt:"the apply needs a real terminal on stdin",remediation:"run `infra-kit vendor sync --yes` from a real terminal; Claude Code's `!` prefix is not one"})},NA=async()=>{let e=await I({autoMigrate:"off"});if(e.vendorSource)return e.vendorSource;throw new x({status:"refused",reason:"not-a-vendor-source"},1,{operation:vp,stderrExcerpt:"this repo is not a vendor source; `infra-kit vendor sync` runs only in a repo whose infra-kit.json has a vendorSource block",remediation:"run it from the source repo, or point -C at it"})},jy=(e,t)=>{yp.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
433
+ `;var H$=new Set(["100644","100755","120000"]),q$=(e,t)=>{let r=new Map;for(let n of Gt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!H$.has(s)||Xo(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},lp=async(e,t,r)=>{let n=await Q(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return q$(n,r)},Ty=async e=>Gt(await Q(e,["--literal-pathspecs","ls-files","-z","--",Z]));var An=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],Ay=e=>{let t=ta(e);t!==null&&(t.kind==="other"?$y(e):tA(e))},nA=(e,t,r)=>{let n=ye.join(e,r.source),o=ye.join(t,r.target);if(Cy(ye.dirname(o),{recursive:!0}),Ay(o),r.mode==="120000"){eA(Q$(n),o);return}Y$(n,o),z$(o,r.mode==="100755"?493:420)},oA=async(e,t)=>{let r=new Set;for(let n of Gt(await Q(e,["ls-files","-z"]))){if(t.has(n))continue;let o=ye.posix.dirname(n);for(;o!==".";)r.add(o),o=ye.posix.dirname(o)}return r},sA=async(e,t)=>{if(t.length===0)return;let r=await oA(e,new Set(t)),n=[...new Set(t.map(o=>ye.dirname(ye.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)&&!(!X$(s,{throwIfNoEntry:!1})?.isDirectory()||Z$(s).length>0||r.has(ye.relative(e,s).split(ye.sep).join("/")));)$y(s),s=ye.dirname(s)}},Oy=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Kt,...s].map(xy).filter(a=>a!==null&&!Bi(a));return $n(i)},Iy=async(e,t,r,n)=>{let o=ye.join(e,Z);Cy(o,{recursive:!0}),rA(ye.join(e,Kt),oa(t.name));let s=Oy(r,await Ty(e),n);Md(o,{source:t.name,commit:t.headSha},s)},dp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(An(t));let n=ye.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)Ay(ye.join(n,a));await sA(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)nA(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await Iy(n,e,t.entries,o),{touched:$n([...o,...i,Kt,Yo]),manifestWritten:!0}):{touched:$n([...o,...i]),manifestWritten:!1}},pp=async(e,t)=>(await Iy(e,t,[],[]),[Kt,Yo]);var up=(e,t)=>`[ROOT] vendor: sync from ${e}@${ra(t)}`,iA=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
434
+ `).trim()||String(e)},mp=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Q(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Q(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:iA(s)}}};var aA=20,cA=20,Dy=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],Ny=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of Zo(e.files,r)){let u=na(d.path,n);if(s.push(u),by(d.fingerprint,t.onDisk[u]??null))continue;let m=o.has(u)?"modified":"added";i.push({source:d.path,target:u,mode:d.mode,change:m})}let a=new Set(s),c=Zo(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},Qo=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),fp=e=>e.entries.map(t=>t.entry.target),lA=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...fp(e)];return Qo(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...Dy(r,aA),Rt(n)])},dA=(e,t)=>{if(e.kind==="unknown-sha")return{notes:[],warnings:["no manifest commit recorded, so the source commits since the last sync are unknown"]};let r=ra(e.sha);return e.kind==="unresolvable"?{notes:[],warnings:[`manifest commit ${r} is not in ${t}, so the changelog is unknown`]}:{notes:[`${e.lines.length} ${t} commit(s) since ${r}`,...Dy(e.lines,cA)],warnings:[]}},pA=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},uA=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},mA=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return $n([...n,...r?t.headVendorMeta:[]])},fA=(e,t)=>{if(t.dirty.length>0)return lA(e,t,t.dirty);let r=e.entries.map((d,u)=>{let m=t.entries[u]??{target:d.entry.target,tracked:[],onDisk:{}};return Ny(d,m,e.exclude)}),n=r.some(d=>d.vendored),o=r.some(d=>d.writes.length+d.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...Qo(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=dA(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(pA).filter(d=>d!==null);return{...i,status:"changed",message:`${uA(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:mA(r,t,n)}},sa=(e,t)=>{switch(t.kind){case"missing":return Qo(t,"skipped",`not checked out at ${t.root}`);case"source":return Qo(t,"skipped","this is the source repo");case"not-git":return Qo(t,"fail",`not a git repo: ${t.reason}`);case"repo":return fA(e,t)}};import{existsSync as gA,readFileSync as hA,realpathSync as ia}from"node:fs";import aa from"node:path";var gp=async(e,t)=>{let r=t.exclude??[],n=(await Q(e,["rev-parse","HEAD"])).trim(),o=await Le(e),s=await Promise.all(Ey(t).map(async i=>{let a=await lp(e,i.path,r);return{entry:i,files:a.map(c=>ky(e,c))}}));return{root:e,selfRoots:[...new Set([ia(e),ia(o)])],name:aa.basename(o),headSha:n,entries:s,exclude:r}},ca=e=>{let t=Gt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},yA=async(e,t)=>{let r=await Q(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...fp(e)]);return ca(r).filter(n=>!Xo(n,e.exclude))},vA=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await lp(t,r.target,e.exclude),s={};for(let i of Zo(n,e.exclude)){let a=na(i.path,r);s[a]=ta(aa.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),wA=async e=>{try{return Gt(await Q(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Kt,Yo]))}catch{return[]}},kA=e=>{try{let{commit:t,source:r}=Ko(aa.join(e,Z));return{commit:t,source:r}}catch{return null}},bA=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await $e(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await Q(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
435
+ `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},RA=(e,t)=>{try{return hA(aa.join(e,Kt),"utf8")===oa(t)}catch{return!1}},SA=async e=>{try{return{toplevel:(await Q(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
436
+ `)[0]??"git rev-parse failed"}}},PA=async e=>{try{return(await Q(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},la=async(e,t)=>{if(!gA(t.root))return{...t,kind:"missing"};let r=ia(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await SA(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(ia(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=kA(t.root),s=o?.commit??null,[i,a,c,l,d]=await Promise.all([PA(t.root),yA(e,t.root),vA(e,t.root),wA(t.root),bA(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:RA(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:d}};var EA=20,xA=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],TA=(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:",Rt(An(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:xA(r,t)}},CA=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(`
437
+ `).slice(0,EA)},$A=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[TA(e,t),...r,...e.commit?[CA(e.commit)]:[]]}},AA={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},hp=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:AA[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>$A(o,r))],hints:n}},_y=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail"));var OA=20,yp=async(e,t)=>(await Q(e,t,{allowFailure:!0})).trim(),IA=async e=>ca(await Q(e,["status","--porcelain","-z","--untracked-files=normal"])),DA=async e=>(await yp(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"]},NA=async e=>{let[t,r]=await Promise.all([yp(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),yp(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}`}},My=async e=>{let t=await IA(e);if(t.length>0){let n=t.slice(0,OA),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new E({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([DA(e),NA(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import _A from"node:path";var jy=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new E({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=nn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:_A.join(n,s)}))},MA="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",jA=async(e,t)=>{let r=await la(e,t),n=sa(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${MA} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},Fy=async(e,t,r)=>Promise.all(t.map(async n=>r?jA(e,n):sa(e,await la(e,n))));var da="sync vendored files",BA=()=>{if(ee())throw new E({status:"refused",agentMode:A.source},2,{operation:da,stderrExcerpt:"vendor sync is human-only: refused in agent mode regardless of --yes",remediation:"ask a human to run `infra-kit vendor sync` from their own shell \u2014 a sync is never confirmed by an agent"})},WA=()=>{if(!kp.stdin.isTTY)throw new E({status:"refused",reason:"no-tty"},2,{operation:da,stderrExcerpt:"the apply needs a real terminal on stdin",remediation:"run `infra-kit vendor sync --yes` from a real terminal; Claude Code's `!` prefix is not one"})},JA=e=>{let t=Vy.join(nn(e.workspaceDir),e.source);if(FA(t))return t;throw new E({status:"refused",reason:"source-missing",source:t},1,{operation:da,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'})},vp=(e,t)=>new E({status:"refused",reason:"not-a-vendor-source"},1,{operation:da,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`}),UA=async e=>{let t=Vy.join(e,"infra-kit.json"),r;try{r=JSON.parse(await LA.readFile(t,"utf8"))}catch(s){throw vp(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw vp(t,"has no vendorSource block");let o=ku.safeParse(n);if(!o.success)throw vp(t,`has an invalid vendorSource: ${VA.prettifyError(o.error)}`);return o.data},Ly=(e,t)=>{kp.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
438
438
  ${Rt(t)}
439
- `)},_A=async(e,t,r)=>r?(jy(t,xn(t)),lp(t.root,e)):(await cp({source:e,plan:t,onBeforeFirstWrite:o=>{jy(t,o)}})).touched,MA=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await _A(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 pp(t.root,n,dp(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},jA=async(e,t,r)=>{let n=[];for(let o of t)n.push(await MA(e,o,r));return n},Fy=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})),hp=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&Dt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:Fy(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:Iy(t),report:t.sections}}},FA=async e=>{let t=await S(),r=await Ny(t),n=await NA(),o=await Xs(),s=_y(o,e.targets??[]),i=await mp(t,n),a=await My(i,s,!!e.manifestOnly);return{source:i,sourceRows:r,plans:a}},wp=async(e={})=>{DA();let{source:t,sourceRows:r,plans:n}=await FA(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=fp(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return hp({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!it.enabled;if(l&&Dt(a),l&&!yp.stdin.isTTY)return hp({mode:"preview",report:a,outcomes:o,source:t,print:!1});await W(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:Fy(n),throwOnDecline:!0}),IA();let d=await jA(t,n,e),u=fp(r,d,{...s,mode:"applied"});return hp({mode:"applied",report:u,outcomes:d,source:t,print:!0})};var la=(e,t=!0)=>({line:e,reproducible:t});import da from"node:fs";import LA from"node:os";import VA from"node:path";import Wy from"node:process";var pa="INFRA_KIT_SESSION_REPORT",kp=null,Ly=!1,Vy=[],Jy=(e=Wy.env)=>{Ly||(kp=e[pa]??null,Ly=!0,delete e[pa])};var Uy=(e,t)=>{if(!kp)return;let r=e.summary??(Vy.length>0?[...Vy]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{da.writeFileSync(s,i)});try{o(kp,JSON.stringify(n))}catch{}},By=0,Gy=e=>{let t=e?.tmpdir?.()??LA.tmpdir(),r=e?.pid??Wy.pid;return By+=1,VA.join(t,`infra-kit-session-${r}-${By}.json`)},Ky=(e,t)=>{if(!(t?.exists??(i=>da.existsSync(i)))(e))return null;let n=t?.read??(i=>da.readFileSync(i,"utf-8")),o=t?.unlink??(i=>da.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var bp=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead"),e.commands.forEach(bp)};var Rp=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Rp)};var GA=(e,t)=>[...t,e],Hy=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&br.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${br.join(", ")}.`)}},KA=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 ef(()=>vi({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));$(r),r.structuredContent.failedMerges>0&&(Fe.exitCode=1)}),qy=e=>(Fe.stdout.write(`${e.structuredContent.filePath}
440
- `),$(e)),HA=e=>e.description("List all release branches").action(async()=>{$(await Si())}),qA=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".',GA,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(gl),o=n.length>0?n:void 0;$(await $i({releases:o,confirmedCommand:t.yes}))}),zA=e=>{if(e==="")return e;try{return ur(e)}catch(t){throw t instanceof un?new WA(t.message):t}},YA=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)',zA).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Ai({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),zy=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Jt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),XA=e=>zy(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await rp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),ZA=e=>zy(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{$(await np({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),QA=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await bi({version:t.version,confirmedCommand:t.yes}))}),eO=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Mi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),tO=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await zi({confirmedCommand:t.yes}))}),rO=e=>e.description("Add git worktrees for release 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("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{let r=Hy(t.ide,"--ide")??Hy(t.cursor,"--cursor");$(await Ki({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),nO=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await Hi())}),oO=e=>e.description("Remove git worktrees for release 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").action(async t=>{$(await qi({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),sO=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{$(await ip({init:t.init}))}),iO=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ji();$(t),t.structuredContent.ok||(Fe.exitCode=1)}),aO=e=>e.description("Mirror the source repo's vendorSource files into every target in ~/.infra-kit/vendor.json (human-only)").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan (needs a real terminal on stdin)").option("--check","Preview only; exit 1 when any target would change").option("--commit","Commit exactly the synced paths in each target after it syncs").option("--manifest-only","Rewrite vendor/README.md and vendor/.sync-manifest.json only; copy nothing").action(async(t,r)=>{let n;try{n=await wp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!at(a))throw a;p.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),cO=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await Yd())}),lO=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Xd())}),dO=new Set(["version"]),ua=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Pp=()=>{let e=new BA().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");KA(t.command("merge-dev")),HA(t.command("list")),qA(t.command("create")),YA(t.command("edit")),XA(t.command("deploy-all")),ZA(t.command("deploy-selected")),QA(t.command("deliver")),eO(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");rO(r.command("add")),nO(r.command("list")),oO(r.command("remove")),tO(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");cO(n.command("path")),lO(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{$(await As())});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{$(await Zi({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{$(await Zi({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){p.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await $s({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:d}=c.structuredContent,u=(d??[]).some(m=>m.action==="failed");(!l||u)&&(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return iO(i.command("check")),sO(i.command("config")),aO(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 ai({fix:!!a.fix});it.enabled||Rc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Fe.exitCode=1),$(c)}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (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("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),d=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,preset:a},d,it.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await Ds())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree\u2019s dev server, else the deployed app at INFRA_KIT_ENV").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("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{$(await ci({app:c.app,dryRun:c.dryRun,yes:c.yes,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{$(await Fi({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await Ui())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await hi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await pi())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async a=>{qy(await mi({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{qy(await li())}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{$(await ep({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{$(await yi({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{$(await Zd({env:a}))}),e.commands.forEach(ru),bp(e),Rp(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&UA(JA(Fe.cwd(),l)),h.start(ua(c)),it.enabled=!!c.optsWithGlobals().json,it.enabled&&(p.level="warn"),A.source=ss({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),dO.has(ua(c))||await Uc()}),e.hook("postAction",(a,c)=>{let l=ua(c);if(Hd(l))return;let u=h.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",g=`infra-kit ${l}${m}`;Uy({equivalent:la(g,!0)})}),e};import pO from"node:process";var uO={exit:pO.exit,emit:$,logger:p},Yy=(e,t=uO)=>we(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof x?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var Sp=(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 mO from"node:fs";import Xy from"node:path";import zo from"node:process";var ev=new Set([...yu,He,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),tv=null,ma=new Set,Ep=null,Zy=!1;var Qy=e=>{try{return mO.statSync(e)}catch{return null}},fO=()=>{if(Zy)return null;try{return bt()}catch{return Zy=!0,p.debug(`session-env: ${He} unset \u2014 no overlay`),null}},gO=e=>{let t=Xy.join(e,kt),r=Xy.join(e,Xo),n=Qy(t),o=Qy(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},hO=e=>e.kind==="load"?{kind:"load",vars:Dp(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Ip(e.file),signature:e.signature}:e;var yO=()=>{let e=fO();if(e===null)return{kind:"no-session"};let t=gO(e);return t.signature===Ep?null:hO(t)},vO=()=>{for(let e of ma){let t=tv[e];t===void 0?delete zo.env[e]:zo.env[e]=t}ma.clear()},wO=(e,t,r)=>{if(ev.has(t)){e.skipped.push(t);return}zo.env[t]=r,ma.add(t),e.set.push(t)},kO=(e,t)=>{if(ev.has(t)){e.skipped.push(t);return}delete zo.env[t],ma.add(t),e.unset.push(t)},bO=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))wO(t,r,n);if(e.kind==="clear")for(let r of e.unset)kO(t,r);return t},RO=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,xp=(e=yO())=>{if(tv??={...zo.env},e===null||e.kind==="no-session"||e.signature===Ep)return{set:[],unset:[],changed:!1};vO();let{set:t,unset:r,skipped:n}=bO(e);return Ep=e.signature,n.length>0&&p.warn(`session-env: skipped protected names [${n.join(", ")}]`),p.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${RO(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as JO}from"chalk";import{spawn as UO}from"node:child_process";import Se from"node:process";import{Chalk as PO}from"chalk";var Tn=new PO({level:1}),Ge={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},SO={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"}},rv={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},nv={unicode:"\u2500",ascii:"-"},EO=3,Tp=e=>e,xO={ok:e=>Tn.green(e),findings:e=>Tn.yellow(e),failed:e=>Tn.red(e),cancelled:e=>Tn.gray(e)},$p=e=>e?{dim:t=>Tn.dim(t),bold:t=>Tn.bold(t)}:{dim:Tp,bold:Tp},TO=(e,t)=>e?xO[t]:Tp,Cp=e=>[...e].length,CO=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Cp(e)<=r?e:[...e].slice(0,r).join("")},ov=e=>{let t=$p(e.color===!0).dim,r=SO[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(CO(n,e.width))},sv=(e,t={})=>{let r=$p(t.color===!0);return`${r.dim(Ge.reproPrefix.trim())} ${r.bold(e)}`},$O=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,AO=(e,t)=>e==="findings"?t!=null?`${t} ${Ge.findingsSuffix}`:Ge.findingsPlain:{ok:Ge.ok,failed:Ge.failed,cancelled:Ge.cancelled}[e],OO=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<EO?"":` ${n(r.repeat(o))}`},iv=e=>{let t=e.color===!0,r=$p(t),n=TO(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ge.reproPrefix:Ge.nonReproPrefix,i=o?rv[e.outcome].ascii:rv[e.outcome].unicode,a=AO(e.outcome,e.findingsCount),c=[$O(e.durationMs)],l=e.summary?.[0]?.split(`
441
- `)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,u=`${Ge.sep}${c.join(Ge.sep)}`,m=Cp(d)+Cp(u),g=OO(m,e.width,o?nv.ascii:nv.unicode,r.dim),y=[`${n(d)}${r.dim(u)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Ge.envNotice)),y.join(`
442
- `)};var DO=new Set([130,143]),av=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&DO.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import IO from"node:process";var NO={3:"quit",4:"quit",26:"suspend",27:"quit"},_O=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":NO[t]??"continue"},MO=150,jO="\r\x1B[2K",FO=`\r
443
- `,cv=(e,t)=>{lv(e),e.stdin.on("data",t),e.listener=t},lv=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},dv=(e,t)=>{$u(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),cv(e,t)},pv=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(jO)),lv(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Au()},LO=e=>{e.settled||(e.settled=!0,pv(e))},uv=(e,t)=>{let r=ov({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},VO=async e=>{await new Promise(t=>{setTimeout(t,e)})},BO=(e,t,r)=>{pv(e),t(),dv(e,r),uv(e,FO)},WO=async e=>new Promise(t=>{let r=n=>{let o=_O(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){BO(e,s,r);return}t("palette")};cv(e,r),uv(e,"")}),mv=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??IO.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return dv(n,()=>{}),e.armed(),await VO(t.drainMs??MO),await WO(n)}finally{LO(n)}};import fv from"node:process";var Ht={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},gv=(e,t)=>{let r=t?.write??(s=>{fv.stderr.write(s)}),n=t?.stdin??fv.stdin,o=[Ht.saveCursor,Ht.scrollRegion,Ht.restoreCursor,Ht.column,Ht.sgr,Ht.cursor,Ht.wrap];e.entersAltScreen===!0&&o.push(Ht.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var hv=e=>`infra-kit ${e.groupPath.join(" ")}`,GO=()=>{KO();let e=Se.stderr.columns;return e!=null&&e>0?e:void 0},KO=()=>{let e=Se.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},HO=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),qO=async(e,t,r)=>{let n=Gy(),o={...t.env,[pa]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let u=t.spawn(Se.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await HO(u)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Ky(n),c=av(i.code,i.signal,a!=null,e.longRunning),l=hv(e),d=a?.equivalent??la(l,!0);return iv({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},zO=1e3,YO=(e,t)=>e!=null&&t-e<=zO,Ap=e=>{e.resetTerminal(),e.exit(0)},XO=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Ap(t)},s=()=>{let c=e();if(c==="palette"){Ap(t);return}if(!YO(r,t.now())){if(c==="pause"){Ap(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}},yv=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),ZO=Se.platform==="win32"?void 0:()=>{Ou()},QO=(e,t)=>r=>mv(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:ZO}),vv=async(e,t)=>{let r={spawn:t.spawn??UO,now:t.now??(()=>Date.now()),env:t.env??Se.env,cliPath:t.cliPath,ascii:t.ascii??!(Se.stdout.isTTY&&Se.env.TERM!=="dumb"),color:t.color??JO.level>0,columns:t.columns??GO,resetTerminal:t.resetTerminal??(d=>{gv(d)})},n=t.write??(d=>Se.stderr.write(d)),o="palette",s=t.signals??{register:(d,u)=>{Se.on(d,u)},unregister:(d,u)=>{Se.off(d,u)},exit:d=>{Se.exit(d)},raise:d=>{Se.kill(Se.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:XO(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??QO(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let u=t.resolveCommand(d);if(!u)continue;let m=sv(hv(u),{color:r.color});n(`
439
+ `)},GA=async(e,t,r)=>r?(Ly(t,An(t)),pp(t.root,e)):(await dp({source:e,plan:t,onBeforeFirstWrite:o=>{Ly(t,o)}})).touched,KA=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await GA(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 mp(t.root,n,up(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},HA=async(e,t,r)=>{let n=[];for(let o of t)n.push(await KA(e,o,r));return n},By=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})),wp=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&It(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:By(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:_y(t),report:t.sections}}},qA=async e=>{let t=await Qs(),r=JA(t),n=await My(r),o=await UA(r),s=jy(t,e.targets??[]),i=await gp(r,o),a=await Fy(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},bp=async(e={})=>{BA();let{source:t,sourceRows:r,plans:n}=await qA(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=hp(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return wp({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!at.enabled;if(l&&It(a),l&&!kp.stdin.isTTY)return wp({mode:"preview",report:a,outcomes:o,source:t,print:!1});await W(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:By(n),throwOnDecline:!0}),WA();let d=await HA(t,n,e),u=hp(r,d,{...s,mode:"applied"});return wp({mode:"applied",report:u,outcomes:d,source:t,print:!0})};var pa=(e,t=!0)=>({line:e,reproducible:t});import ua from"node:fs";import zA from"node:os";import YA from"node:path";import Gy from"node:process";var ma="INFRA_KIT_SESSION_REPORT",Rp=null,Wy=!1,Jy=[],Ky=(e=Gy.env)=>{Wy||(Rp=e[ma]??null,Wy=!0,delete e[ma])};var Hy=(e,t)=>{if(!Rp)return;let r=e.summary??(Jy.length>0?[...Jy]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{ua.writeFileSync(s,i)});try{o(Rp,JSON.stringify(n))}catch{}},Uy=0,qy=e=>{let t=e?.tmpdir?.()??zA.tmpdir(),r=e?.pid??Gy.pid;return Uy+=1,YA.join(t,`infra-kit-session-${r}-${Uy}.json`)},zy=(e,t)=>{if(!(t?.exists??(i=>ua.existsSync(i)))(e))return null;let n=t?.read??(i=>ua.readFileSync(i,"utf-8")),o=t?.unlink??(i=>ua.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Sp=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead"),e.commands.forEach(Sp)};var Pp=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Pp)};var tO=(e,t)=>[...t,e],Yy=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&br.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${br.join(", ")}.`)}},rO=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 nf(()=>ki({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));$(r),r.structuredContent.failedMerges>0&&(Fe.exitCode=1)}),Xy=e=>(Fe.stdout.write(`${e.structuredContent.filePath}
440
+ `),$(e)),nO=e=>e.description("List all release branches").action(async()=>{$(await xi())}),oO=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".',tO,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(yl),o=n.length>0?n:void 0;$(await Oi({releases:o,confirmedCommand:t.yes}))}),sO=e=>{if(e==="")return e;try{return ur(e)}catch(t){throw t instanceof gn?new ZA(t.message):t}},iO=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)',sO).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Ii({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Zy=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Jt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),aO=e=>Zy(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await op({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),cO=e=>Zy(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{$(await sp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),lO=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Si({version:t.version,confirmedCommand:t.yes}))}),dO=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Fi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),pO=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Xi({confirmedCommand:t.yes}))}),uO=e=>e.description("Add git worktrees for release 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("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{let r=Yy(t.ide,"--ide")??Yy(t.cursor,"--cursor");$(await qi({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),mO=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await zi())}),fO=e=>e.description("Remove git worktrees for release 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").action(async t=>{$(await Yi({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),gO=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{$(await ap({init:t.init}))}),hO=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Gi();$(t),t.structuredContent.ok||(Fe.exitCode=1)}),yO=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory (human-only)").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan (needs a real terminal on stdin)").option("--check","Preview only; exit 1 when any target would change").option("--commit","Commit exactly the synced paths in each target after it syncs").option("--manifest-only","Rewrite vendor/README.md and vendor/.sync-manifest.json only; copy nothing").action(async(t,r)=>{let n;try{n=await bp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!ct(a))throw a;p.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),vO=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await Zd())}),wO=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Qd())}),kO=new Set(["version"]),fa=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Ep=()=>{let e=new XA().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");rO(t.command("merge-dev")),nO(t.command("list")),oO(t.command("create")),iO(t.command("edit")),aO(t.command("deploy-all")),cO(t.command("deploy-selected")),lO(t.command("deliver")),dO(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");uO(r.command("add")),mO(r.command("list")),fO(r.command("remove")),pO(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");vO(n.command("path")),wO(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{$(await _s())});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{$(await ea({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{$(await ea({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){p.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await Ns({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:d}=c.structuredContent,u=(d??[]).some(m=>m.action==="failed");(!l||u)&&(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return hO(i.command("check")),gO(i.command("config")),yO(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 li({fix:!!a.fix});at.enabled||Pc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Fe.exitCode=1),$(c)}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (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("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),d=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,preset:a},d,at.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await js())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree\u2019s dev server, else the deployed app at INFRA_KIT_ENV").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("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{$(await di({app:c.app,dryRun:c.dryRun,yes:c.yes,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{$(await Vi({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await Ki())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await vi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await mi())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async a=>{Xy(await gi({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Xy(await pi())}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{$(await rp({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{$(await wi({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{$(await ep({env:a}))}),e.commands.forEach(ou),Sp(e),Pp(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&eO(QA(Fe.cwd(),l)),h.start(fa(c)),at.enabled=!!c.optsWithGlobals().json,at.enabled&&(p.level="warn"),A.source=ds({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),kO.has(fa(c))||await Kc()}),e.hook("postAction",(a,c)=>{let l=fa(c);if(zd(l))return;let u=h.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",g=`infra-kit ${l}${m}`;Hy({equivalent:pa(g,!0)})}),e};import bO from"node:process";var RO={exit:bO.exit,emit:$,logger:p},Qy=(e,t=RO)=>we(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof E?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var xp=(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 SO from"node:fs";import ev from"node:path";import es from"node:process";var nv=new Set([...wu,He,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),ov=null,ga=new Set,Tp=null,tv=!1;var rv=e=>{try{return SO.statSync(e)}catch{return null}},PO=()=>{if(tv)return null;try{return bt()}catch{return tv=!0,p.debug(`session-env: ${He} unset \u2014 no overlay`),null}},EO=e=>{let t=ev.join(e,kt),r=ev.join(e,rs),n=rv(t),o=rv(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},xO=e=>e.kind==="load"?{kind:"load",vars:Np(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:_p(e.file),signature:e.signature}:e;var TO=()=>{let e=PO();if(e===null)return{kind:"no-session"};let t=EO(e);return t.signature===Tp?null:xO(t)},CO=()=>{for(let e of ga){let t=ov[e];t===void 0?delete es.env[e]:es.env[e]=t}ga.clear()},$O=(e,t,r)=>{if(nv.has(t)){e.skipped.push(t);return}es.env[t]=r,ga.add(t),e.set.push(t)},AO=(e,t)=>{if(nv.has(t)){e.skipped.push(t);return}delete es.env[t],ga.add(t),e.unset.push(t)},OO=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))$O(t,r,n);if(e.kind==="clear")for(let r of e.unset)AO(t,r);return t},IO=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Cp=(e=TO())=>{if(ov??={...es.env},e===null||e.kind==="no-session"||e.signature===Tp)return{set:[],unset:[],changed:!1};CO();let{set:t,unset:r,skipped:n}=OO(e);return Tp=e.signature,n.length>0&&p.warn(`session-env: skipped protected names [${n.join(", ")}]`),p.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${IO(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as QO}from"chalk";import{spawn as eI}from"node:child_process";import Pe from"node:process";import{Chalk as DO}from"chalk";var On=new DO({level:1}),Ge={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},NO={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"}},sv={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},iv={unicode:"\u2500",ascii:"-"},_O=3,$p=e=>e,MO={ok:e=>On.green(e),findings:e=>On.yellow(e),failed:e=>On.red(e),cancelled:e=>On.gray(e)},Op=e=>e?{dim:t=>On.dim(t),bold:t=>On.bold(t)}:{dim:$p,bold:$p},jO=(e,t)=>e?MO[t]:$p,Ap=e=>[...e].length,FO=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Ap(e)<=r?e:[...e].slice(0,r).join("")},av=e=>{let t=Op(e.color===!0).dim,r=NO[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(FO(n,e.width))},cv=(e,t={})=>{let r=Op(t.color===!0);return`${r.dim(Ge.reproPrefix.trim())} ${r.bold(e)}`},LO=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,VO=(e,t)=>e==="findings"?t!=null?`${t} ${Ge.findingsSuffix}`:Ge.findingsPlain:{ok:Ge.ok,failed:Ge.failed,cancelled:Ge.cancelled}[e],BO=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<_O?"":` ${n(r.repeat(o))}`},lv=e=>{let t=e.color===!0,r=Op(t),n=jO(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ge.reproPrefix:Ge.nonReproPrefix,i=o?sv[e.outcome].ascii:sv[e.outcome].unicode,a=VO(e.outcome,e.findingsCount),c=[LO(e.durationMs)],l=e.summary?.[0]?.split(`
441
+ `)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,u=`${Ge.sep}${c.join(Ge.sep)}`,m=Ap(d)+Ap(u),g=BO(m,e.width,o?iv.ascii:iv.unicode,r.dim),y=[`${n(d)}${r.dim(u)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Ge.envNotice)),y.join(`
442
+ `)};var WO=new Set([130,143]),dv=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&WO.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import JO from"node:process";var UO={3:"quit",4:"quit",26:"suspend",27:"quit"},GO=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":UO[t]??"continue"},KO=150,HO="\r\x1B[2K",qO=`\r
443
+ `,pv=(e,t)=>{uv(e),e.stdin.on("data",t),e.listener=t},uv=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},mv=(e,t)=>{Iu(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),pv(e,t)},fv=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(HO)),uv(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Du()},zO=e=>{e.settled||(e.settled=!0,fv(e))},gv=(e,t)=>{let r=av({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},YO=async e=>{await new Promise(t=>{setTimeout(t,e)})},XO=(e,t,r)=>{fv(e),t(),mv(e,r),gv(e,qO)},ZO=async e=>new Promise(t=>{let r=n=>{let o=GO(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){XO(e,s,r);return}t("palette")};pv(e,r),gv(e,"")}),hv=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??JO.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return mv(n,()=>{}),e.armed(),await YO(t.drainMs??KO),await ZO(n)}finally{zO(n)}};import yv from"node:process";var Ht={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},vv=(e,t)=>{let r=t?.write??(s=>{yv.stderr.write(s)}),n=t?.stdin??yv.stdin,o=[Ht.saveCursor,Ht.scrollRegion,Ht.restoreCursor,Ht.column,Ht.sgr,Ht.cursor,Ht.wrap];e.entersAltScreen===!0&&o.push(Ht.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var wv=e=>`infra-kit ${e.groupPath.join(" ")}`,tI=()=>{rI();let e=Pe.stderr.columns;return e!=null&&e>0?e:void 0},rI=()=>{let e=Pe.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},nI=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),oI=async(e,t,r)=>{let n=qy(),o={...t.env,[ma]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let u=t.spawn(Pe.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await nI(u)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=zy(n),c=dv(i.code,i.signal,a!=null,e.longRunning),l=wv(e),d=a?.equivalent??pa(l,!0);return lv({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},sI=1e3,iI=(e,t)=>e!=null&&t-e<=sI,Ip=e=>{e.resetTerminal(),e.exit(0)},aI=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Ip(t)},s=()=>{let c=e();if(c==="palette"){Ip(t);return}if(!iI(r,t.now())){if(c==="pause"){Ip(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}},kv=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),cI=Pe.platform==="win32"?void 0:()=>{Nu()},lI=(e,t)=>r=>hv(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:cI}),bv=async(e,t)=>{let r={spawn:t.spawn??eI,now:t.now??(()=>Date.now()),env:t.env??Pe.env,cliPath:t.cliPath,ascii:t.ascii??!(Pe.stdout.isTTY&&Pe.env.TERM!=="dumb"),color:t.color??QO.level>0,columns:t.columns??tI,resetTerminal:t.resetTerminal??(d=>{vv(d)})},n=t.write??(d=>Pe.stderr.write(d)),o="palette",s=t.signals??{register:(d,u)=>{Pe.on(d,u)},unregister:(d,u)=>{Pe.off(d,u)},exit:d=>{Pe.exit(d)},raise:d=>{Pe.kill(Pe.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:aI(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??lI(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let u=t.resolveCommand(d);if(!u)continue;let m=cv(wv(u),{color:r.color});n(`
444
444
  ${m}
445
- `),a.childStarted();let g=await qO(u,r,()=>{o="child"});if(n(`
445
+ `),a.childStarted();let g=await oI(u,r,()=>{o="child"});if(n(`
446
446
  ${g}
447
- `),await l(c)==="quit")return}}finally{a.dispose()}};zd();Jy();var Rv=Pp(),kv=async(e=Ee.argv)=>{xp(),Tu(e);try{await Rv.parseAsync(e)}catch(t){Yy(t)}},oD=()=>{try{if(Ee.env.INFRA_KIT_NO_LOCATION_WARN||Ee.argv.includes("--json"))return;Fp({selfRealPath:rD(bv(import.meta.url)),cwd:Ee.cwd(),env:Ee.env,realpath:he,home:nD(),exists:tD})&&p.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};oD();tu((e,t)=>{p.debug(e,t)});Kc(q.version);var Pv=()=>dy(Rv.commands),sD=async()=>{let e=Pv(),t=null;try{if(Ee.stdout.isTTY&&Ee.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-XLDVLQEG.js");t=await r(e)}else{let r=Sp(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new wv(" "),new wv(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await D(o=>eD({message:"Select a command to run",choices:n},o),{output:Ee.stderr})}}catch(r){if(!we(r))throw r}return t},iD=async()=>{let{runCommandPalette:e}=await import("./boot-XLDVLQEG.js"),t=bv(import.meta.url),r=new Map(fr.map(n=>[n.groupPath.join(" "),n]));await vv(Pv(),{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(Ee.argv.length<=2){let e={stdoutIsTTY:!!Ee.stdout.isTTY,stdinIsTTY:!!Ee.stdin.isTTY,stderrIsTTY:!!Ee.stderr.isTTY};if(yv(Ee.env,e))await iD();else{let t=await sD();t&&await kv(["node","infra-kit",...t.split(" ")])}}else await kv();
447
+ `),await l(c)==="quit")return}}finally{a.dispose()}};Xd();Ky();var Ev=Ep(),Sv=async(e=Ee.argv)=>{Cp(),Au(e);try{await Ev.parseAsync(e)}catch(t){Qy(t)}},fI=()=>{try{if(Ee.env.INFRA_KIT_NO_LOCATION_WARN||Ee.argv.includes("--json"))return;Vp({selfRealPath:uI(Pv(import.meta.url)),cwd:Ee.cwd(),env:Ee.env,realpath:he,home:mI(),exists:pI})&&p.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};fI();nu((e,t)=>{p.debug(e,t)});qc(q.version);var xv=()=>uy(Ev.commands),gI=async()=>{let e=xv(),t=null;try{if(Ee.stdout.isTTY&&Ee.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-XLDVLQEG.js");t=await r(e)}else{let r=xp(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new Rv(" "),new Rv(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await I(o=>dI({message:"Select a command to run",choices:n},o),{output:Ee.stderr})}}catch(r){if(!we(r))throw r}return t},hI=async()=>{let{runCommandPalette:e}=await import("./boot-XLDVLQEG.js"),t=Pv(import.meta.url),r=new Map(fr.map(n=>[n.groupPath.join(" "),n]));await bv(xv(),{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(Ee.argv.length<=2){let e={stdoutIsTTY:!!Ee.stdout.isTTY,stdinIsTTY:!!Ee.stdin.isTTY,stderrIsTTY:!!Ee.stderr.isTTY};if(kv(Ee.env,e))await hI();else{let t=await gI();t&&await Sv(["node","infra-kit",...t.split(" ")])}}else await Sv();
448
448
  //# sourceMappingURL=cli.js.map