infra-kit 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/{chunk-WUTG6VMP.js → chunk-2H6VQIGT.js} +5 -5
  2. package/dist/chunk-2H6VQIGT.js.map +7 -0
  3. package/dist/chunk-6UJQB36N.js +2 -0
  4. package/dist/chunk-6UJQB36N.js.map +7 -0
  5. package/dist/chunk-AG7XWZNT.js +3 -0
  6. package/dist/chunk-AG7XWZNT.js.map +7 -0
  7. package/dist/chunk-F656FWV5.js +11 -0
  8. package/dist/chunk-F656FWV5.js.map +7 -0
  9. package/dist/{chunk-OPL7C5H6.js → chunk-OWX4O3IS.js} +2 -2
  10. package/dist/chunk-R2SZWOPC.js +3 -0
  11. package/dist/chunk-R2SZWOPC.js.map +7 -0
  12. package/dist/chunk-RZF36IGQ.js +4 -0
  13. package/dist/chunk-RZF36IGQ.js.map +7 -0
  14. package/dist/cli.js +114 -147
  15. package/dist/cli.js.map +4 -4
  16. package/dist/dev-server.js +2 -2
  17. package/dist/dev-server.js.map +2 -2
  18. package/dist/dev-wizard-run-J5WSWCZT.js +2 -0
  19. package/dist/{dev-wizard-run-ITRFKMTL.js.map → dev-wizard-run-J5WSWCZT.js.map} +1 -1
  20. package/dist/mcp-proxy.js +9 -9
  21. package/dist/mcp-proxy.js.map +2 -2
  22. package/dist/update-check.js +1 -1
  23. package/dist/update-check.js.map +1 -1
  24. package/package.json +3 -3
  25. package/readme.md +4 -4
  26. package/dist/chunk-7AMRJ4IW.js +0 -9
  27. package/dist/chunk-7AMRJ4IW.js.map +0 -7
  28. package/dist/chunk-JUNJK2YC.js +0 -3
  29. package/dist/chunk-JUNJK2YC.js.map +0 -7
  30. package/dist/chunk-MOVRKV3I.js +0 -4
  31. package/dist/chunk-MOVRKV3I.js.map +0 -7
  32. package/dist/chunk-WUTG6VMP.js.map +0 -7
  33. package/dist/chunk-YYC3QGGC.js +0 -2
  34. package/dist/chunk-YYC3QGGC.js.map +0 -7
  35. package/dist/dev-wizard-run-ITRFKMTL.js +0 -2
  36. /package/dist/{chunk-OPL7C5H6.js.map → chunk-OWX4O3IS.js.map} +0 -0
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{a as Qd,b as Bo,d as bt,e as Go,f as ip,g as ap,h as cp,i as lp,j as dp,k as pp,l as up,m as mp,p as gp,r as ue}from"./chunk-OPL7C5H6.js";import{a as hd,b as vd,c as wi,d as yd,e as wd,f as kd,g as bd,h as fn,i as Rd,j as Ed,k as Pd,l as Sd,m as xd,n as ki,o as Td,p as bi,q as Io,r as jr,s as Ad,t as Cd,u as Id}from"./chunk-YYC3QGGC.js";import{a as q,b as W,c as fr,d as jo,e as xi,f as Fo,g as Ti,h as vn,i as Fr,j as Lo,k as Jd,l as H,m as yn,n as wn,o as Ci,p as Ii,r as $i}from"./chunk-JUNJK2YC.js";import{b as mn,c as Ao,d as yi,e as pd,f as Co,g as ud,i as md,k as fd,m as de,o as gd}from"./chunk-AWFGP6GY.js";import{a as fp}from"./chunk-TVG47UHG.js";import{a as Wo,b as ep,c as qe,d as oe,e as rp,f as tp,g as h,h as Vo,i as A,j as np,k as S,l as Jo,m as se}from"./chunk-WUTG6VMP.js";import{$ as Ke,A as Md,B as jd,C as Fd,D as Do,E as No,F as hn,G as Ei,H as Mo,I as Ld,J as Wd,K as Pi,L as Si,M as Vd,N as l,O as G,P as y,Q as Bd,R as Gd,S as gr,T as Ud,U as Ai,V as hr,W as Kd,X as qd,Y as V,Z as P,_ as Hd,a as gn,b as E,ba as zd,c as $d,d as I,da as Yd,e as ne,f as we,g as $o,h as vt,i as g,j as _d,k as _o,ka as Zd,l as L,m as xe,n as Me,na as Xd,o as Od,p as Ri,q as Y,r as B,s as Oo,t as Dd,u as yt,v as ke,w as b,x as wt,y as kt,z as Nd}from"./chunk-7AMRJ4IW.js";import"./chunk-MFAFQVTW.js";import{a as te,b as gt,c as un,d as Ge,e as ld,f as So,g as pr,h as ur,i as xo,j as ht,k as Ne,l as mr,m as To,p as z,q as dd,r as Mr,s as Ue,t as ye}from"./chunk-MOVRKV3I.js";import{a as op,b as sp}from"./chunk-QWVLAZ6N.js";import Hx,{Separator as Og}from"@inquirer/select";import{existsSync as zx,realpathSync as Yx}from"node:fs";import{homedir as Zx}from"node:os";import ae from"node:process";import{fileURLToPath as Ng}from"node:url";import Hp from"node:process";import{z as Re}from"zod";import bp from"node:fs";import Et from"node:path";import{packageConfigSchema as Ug}from"@slip-stream-kit/config/internal";import vp from"node:fs/promises";import Ni from"node:path";import{pathToFileURL as Kg}from"node:url";import{z as qg}from"zod";import hp from"node:path";var kn=["frontend","backend","lib","e2e","mobile"],Lg={ui:"frontend",api:"backend",tests:"e2e"},Wg="mobile-app",Vg=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Jg=(e,r)=>{let t=hp.relative(r,e).split(hp.sep).filter(s=>s!==""&&s!=="."),[n,,o]=t;if(t.length===3&&n==="apps"&&o!==void 0){let s=Lg[o];if(s)return s}return t.at(-1)===Wg?"mobile":null},Bg=e=>{let r=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of Vg)if(n.packages.some(o=>r.has(o)))return n.type;return r.has("vite")&&r.has("react")&&!!e.scripts?.dev?"frontend":null},_i=({packageDir:e,repoRoot:r,pkgJson:t,declaredType:n})=>n??Jg(e,r)??Bg(t)??"lib";var vr={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Oi={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"]},Di=(e,r=vr)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import Gg from"node:fs/promises";var je=async e=>{try{return await Gg.access(e),!0}catch{return!1}};var He="infra-kit.config.ts",bn=async e=>{try{let r=await vp.readFile(Ni.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},yp=async e=>{let r=await vp.stat(e),o=(await import(`${Kg(e).href}?mtime=${Number(r.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${He} at ${e} has no default export`);return typeof o=="function"?await o():o},Rn=async e=>{let r=Ni.join(e,He);if(await je(r))try{let n=(await yp(r))?.type;return kn.find(o=>o===n)}catch{return}},En=async(e,r=vr)=>{let t=Ni.join(e,He);if(!await je(t))throw new Error(`${He} not found at ${t}`);let n=await yp(t),o=Ug.safeParse(n);if(!o.success)throw new Error(`Invalid ${He} at ${t}: ${qg.prettifyError(o.error)}`);return Di(o.data,r)};import wp from"node:fs/promises";import Uo from"node:path";import Hg from"yaml";var zg="pnpm-workspace.yaml",Yg=async e=>(await wp.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Uo.join(e,t.name)),Zg=async(e,r)=>{let t=[];for(let n of e){if(r==="*"){t.push(...await Yg(n));continue}let o=Uo.join(n,r);await je(o)&&t.push(o)}return t},Xg=async(e,r)=>{let t=[e];for(let n of r.split("/"))t=await Zg(t,n);return t},me=async e=>{let r=await wp.readFile(Uo.join(e,zg),"utf-8"),n=((Hg.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await Xg(e,s);for(let a of i)await je(Uo.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Pn from"node:path";var Sn=async e=>{let r=Pn.resolve(e);for(;r!==Pn.dirname(r);){if(await je(Pn.join(r,"package.json")))return r;r=Pn.dirname(r)}if(await je(Pn.join(r,"package.json")))return r;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 Fe=(e,r,t)=>{let n=e.indexOf(r),o=e.indexOf(t);return n!==-1&&o!==-1&&o>=n},yr=(e,r,t)=>{let n=e.indexOf(r),o=e.indexOf(t);if(n===-1||o===-1||o<n)return null;let s=e.slice(0,n).replace(/\n+$/,""),i=e.slice(o+t.length).replace(/^\n+/,"");return s+(i?`
3
- ${i}`:"")},Mi=(e,r)=>{let t=e.indexOf(r);if(t===-1)return null;let o=e.slice(t+r.length).match(/^([^\s>]+)/);return o?o[1]:null},kp=(e,r,t)=>`${e}
4
- ${r}
5
- ${t}`,Rt=({content:e,body:r,startMarker:t,endMarker:n,placement:o="replace-in-place"})=>{let s=kp(t,r,n),i=Fe(e,t,n);if(o==="replace-in-place"&&i){let d=e.indexOf(t),p=e.indexOf(n)+n.length;return e.slice(0,d)+s+e.slice(p)}let c=(i?yr(e,t,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
2
+ import{a as Bd,b as No,d as lr,e as _o,f as Ud,g as Kd,h as qd,i as Hd,j as Yd,k as zd,l as Xd,m as Zd,p as np,r as le}from"./chunk-OWX4O3IS.js";import{a as nd,b as od,c as li,d as sd,e as id,f as ad,g as cd,h as tn,i as ld,j as dd,k as pd,l as ud,m as md,n as di,o as fd,p as gd,q as hd,r as vd,s as pi,t as Ro,u as st,v as yd,w as Po,x as wd}from"./chunk-AG7XWZNT.js";import{a as G,b as J,c as it,d as $o,e as hi,f as Io,g as vi,h as on,i as Pt,j as Do,k as Id,l as sn,m as an,n as ki,o as bi,q as Ri}from"./chunk-R2SZWOPC.js";import{b as en,c as ko,d as ci,e as Zl,f as bo,g as Ql,i as ed,k as td,m as ie,o as rd}from"./chunk-AWFGP6GY.js";import{a as rp}from"./chunk-TVG47UHG.js";import{a as Oo,b as We,c as ne,d as Wd,e as Gd,f as T,g,h as Mo,i as Qd,j as x,k as jo,l as Q}from"./chunk-2H6VQIGT.js";import{$ as jd,A as Sd,B as xd,C as Td,D as To,E as Co,F as nn,G as mi,H as Ao,I as Cd,J as Ad,K as fi,L as gi,M as $d,N as l,O as yi,P as K,Q as w,R as Dd,S as Od,T as at,U as Nd,V as wi,W as ct,X as _d,Y as Md,Z as q,_ as $,a as rn,aa as lt,b as E,c as kd,ca as Fd,d as A,e as Z,ea as Ld,f as ae,g as Eo,h as sr,i as f,j as bd,k as So,l as L,la as Jd,m as Ee,n as De,o as Rd,oa as Vd,p as ui,q as Y,r as B,s as xo,t as Pd,u as ir,v as ve,w as R,x as ar,y as cr,z as Ed}from"./chunk-F656FWV5.js";import"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-6UJQB36N.js";import{a as er,b as Yl,c as Rt,d as zl,e as ho,f as tr,g as rr,h as vo,i as nr,j as yo,l as Xl,m as or,n as wo,o as he}from"./chunk-RZF36IGQ.js";import{a as ep,b as tp}from"./chunk-QWVLAZ6N.js";import Fx,{Separator as Sg}from"@inquirer/select";import{existsSync as Lx,realpathSync as Jx}from"node:fs";import{homedir as Vx}from"node:os";import ge from"node:process";import{fileURLToPath as Tg}from"node:url";import Mp from"node:process";import{z as we}from"zod";import lp from"node:fs";import pr from"node:path";import{packageConfigSchema as jg}from"@slip-stream-kit/config/internal";import sp from"node:fs/promises";import xi from"node:path";import{pathToFileURL as Fg}from"node:url";import{z as Lg}from"zod";import op from"node:path";var cn=["frontend","backend","lib","e2e","mobile"],Ig={ui:"frontend",api:"backend",tests:"e2e"},Dg="mobile-app",Og=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Ng=(e,t)=>{let r=op.relative(t,e).split(op.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=Ig[o];if(s)return s}return r.at(-1)===Dg?"mobile":null},_g=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of Og)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Pi=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??Ng(e,t)??_g(r)??"lib";var dt={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Ei={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"]},Si=(e,t=dt)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import Mg from"node:fs/promises";var Oe=async e=>{try{return await Mg.access(e),!0}catch{return!1}};var Ge="infra-kit.config.ts",ln=async e=>{try{let t=await sp.readFile(xi.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},ip=async e=>{let t=await sp.stat(e),o=(await import(`${Fg(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${Ge} at ${e} has no default export`);return typeof o=="function"?await o():o},dn=async e=>{let t=xi.join(e,Ge);if(await Oe(t))try{let n=(await ip(t))?.type;return cn.find(o=>o===n)}catch{return}},pn=async(e,t=dt)=>{let r=xi.join(e,Ge);if(!await Oe(r))throw new Error(`${Ge} not found at ${r}`);let n=await ip(r),o=jg.safeParse(n);if(!o.success)throw new Error(`Invalid ${Ge} at ${r}: ${Lg.prettifyError(o.error)}`);return Si(o.data,t)};import ap from"node:fs/promises";import Fo from"node:path";import Jg from"yaml";var Vg="pnpm-workspace.yaml",Bg=async e=>(await ap.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Fo.join(e,r.name)),Wg=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await Bg(n));continue}let o=Fo.join(n,t);await Oe(o)&&r.push(o)}return r},Gg=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await Wg(r,n);return r},de=async e=>{let t=await ap.readFile(Fo.join(e,Vg),"utf-8"),n=((Jg.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await Gg(e,s);for(let a of i)await Oe(Fo.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import un from"node:path";var mn=async e=>{let t=un.resolve(e);for(;t!==un.dirname(t);){if(await Oe(un.join(t,"package.json")))return t;t=un.dirname(t)}if(await Oe(un.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 Ne=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},pt=(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}`:"")},Ti=(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},cp=(e,t,r)=>`${e}
4
+ ${t}
5
+ ${r}`,dr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=cp(r,t,n),i=Ne(e,r,n);if(o==="replace-in-place"&&i){let d=e.indexOf(r),p=e.indexOf(n)+n.length;return e.slice(0,d)+s+e.slice(p)}let c=(i?pt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var be="<!-- infra-kit:begin -->",Le="<!-- infra-kit:end -->",ji="<!-- infra-kit:version ",We="<!-- infra-kit:package:begin -->",ze="<!-- infra-kit:package:end -->",Lr="<!-- infra-kit:package:version ";var Qg=e=>{let r=e.indexOf(We)+We.length;return e.slice(r,e.indexOf(ze))},eh=e=>{let r=e.indexOf(Lr);if(r===-1)return null;let t=e.slice(r+Lr.length).match(/^\S+\s+([^\s>]+)/)?.[1];return kn.find(n=>n===t)??null},Wr=e=>{if(e===null)return{state:"missing"};if(!Fe(e,We,ze))return e.includes(We)||e.includes(ze)?{state:"malformed"}:Fe(e,be,Le)?{state:"foreign-block"}:{state:"no-block"};let r=Qg(e);if(r.trim()==="")return{state:"malformed"};let t={state:"ok"},n=Mi(r,Lr),o=eh(r);return n!==null&&(t.version=n),o!==null&&(t.type=o),t};import rh from"node:fs";var Vr=e=>{try{return rh.readFileSync(e,"utf-8")}catch{return null}};var Rp="pnpm-workspace.yaml",th="CLAUDE.md",Li=e=>{let r=Et.resolve(e);for(;r!==Et.dirname(r);){if(bp.existsSync(Et.join(r,Rp)))return r;r=Et.dirname(r)}return bp.existsSync(Et.join(r,Rp))?r:null},Fi=new Map,Ko=()=>{Fi.clear()},nh=async e=>{let r;try{r=await me(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let t of r){let n=Et.join(t,th),o=Vr(n);if(o!==null&&Wr(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Pt=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let r=Fi.get(e);if(r)return r;let t=await nh(e);return Fi.set(e,t),t};import At from"node:fs";import Jr from"node:path";var Ep=`---
8
+ `};var ye="<!-- infra-kit:begin -->",_e="<!-- infra-kit:end -->",Ci="<!-- infra-kit:version ",Me="<!-- infra-kit:package:begin -->",Ue="<!-- infra-kit:package:end -->",Et="<!-- infra-kit:package:version ";var Ug=e=>{let t=e.indexOf(Me)+Me.length;return e.slice(t,e.indexOf(Ue))},Kg=e=>{let t=e.indexOf(Et);if(t===-1)return null;let r=e.slice(t+Et.length).match(/^\S+\s+([^\s>]+)/)?.[1];return cn.find(n=>n===r)??null},St=e=>{if(e===null)return{state:"missing"};if(!Ne(e,Me,Ue))return e.includes(Me)||e.includes(Ue)?{state:"malformed"}:Ne(e,ye,_e)?{state:"foreign-block"}:{state:"no-block"};let t=Ug(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Ti(t,Et),o=Kg(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import qg from"node:fs";var xt=e=>{try{return qg.readFileSync(e,"utf-8")}catch{return null}};var dp="pnpm-workspace.yaml",Hg="CLAUDE.md",$i=e=>{let t=pr.resolve(e);for(;t!==pr.dirname(t);){if(lp.existsSync(pr.join(t,dp)))return t;t=pr.dirname(t)}return lp.existsSync(pr.join(t,dp))?t:null},Ai=new Map,Lo=()=>{Ai.clear()},Yg=async e=>{let t;try{t=await de(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=pr.join(r,Hg),o=xt(n);if(o!==null&&St(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},ur=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Ai.get(e);if(t)return t;let r=await Yg(e);return Ai.set(e,r),r};import hr from"node:fs";import Tt from"node:path";var pp=`---
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 Pp=`# {{packageName}}
77
+ `;var up=`# {{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 Sp=`# {{packageName}}
98
+ `;var mp=`# {{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
  - Every spec cleans up what it creates, in teardown.
118
118
  - Selectors live in Page Objects, never inline in specs.
119
119
  - Never point a run at a production environment.
120
- `;var xp="# {{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 Tp=`# {{packageName}}
120
+ `;var fp="# {{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 gp=`# {{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,7 +139,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
139
139
  - Changing that map is a breaking change for every dependent package.
140
140
  - Run \`pnpm run build\` before a dependent package can see a change.
141
141
  - No app-specific logic belongs here.
142
- `;var Ap=`# {{packageName}}
142
+ `;var hp=`# {{packageName}}
143
143
 
144
144
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
145
145
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -161,33 +161,23 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
161
161
  - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
162
162
  - The web build feeds the native shell, so a device run needs a rebuild first.
163
163
  - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
164
- `;var Cp="# 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 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 desc-edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch.\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, 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|desc-edit|merge-dev|deploy-all|deploy-selected`, `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` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n";var St={"root/body":Cp.trimEnd(),"package/frontend":xp.trimEnd(),"package/backend":Pp.trimEnd(),"package/lib":Tp.trimEnd(),"package/e2e":Sp.trimEnd(),"package/mobile":Ap.trimEnd(),"design/skeleton":Ep.trimEnd()};var Wi=/\{\{(\w+)\}\}/g,ph=/^- \{\{(\w+)\}\}$/,uh=e=>new Set([...e.matchAll(Wi)].map(r=>r[1])),mh=(e,r)=>{let t=Object.keys(r).filter(n=>!e.has(n));if(t.length>0)throw new Error(`renderTemplate: variable(s) never used by the template: ${t.join(", ")}`)},fh=(e,r)=>{let t=[...e].filter(n=>!(n in r));if(t.length>0)throw new Error(`renderTemplate: placeholder(s) with no variable: ${t.map(n=>`{{${n}}}`).join(", ")}`)},gh=(e,r)=>e.filter(t=>{let n=ph.exec(t);return n===null||r[n[1]]!==""}),hh=(e,r)=>{for(let t of e)for(let n of t.matchAll(Wi)){let o=r[n[1]];if(o!==void 0&&o.includes(`
165
- `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},xt=(e,r)=>{let t=uh(e);fh(t,r),mh(t,r);let n=gh(e.split(`
166
- `),r);return hh(n,r),n.join(`
167
- `).replace(Wi,(o,s)=>r[s])};var vh="name: TODO",Vi=e=>{let r=xt(St["design/skeleton"],{packageName:e}),t=`name: ${e}`;return`${r.replace(vh,()=>t)}
168
- `};var yh=(e,r)=>`${Lr}${e} ${r} -->`,wh="`README.md` \u2014 what this package is and how to run it.",Ji=e=>{let{version:r,type:t,packageName:n,relDir:o,hasReadme:s}=e,i=xt(St[`package/${t}`],{packageName:n,relDir:o,type:t,readmeBullet:s?wh:""});return[yh(r,t),"",i].join(`
169
- `)};var kh=e=>`${ji}${e} -->`,Bi=e=>{let r=xt(St["root/body"],{});return[kh(e),"",r].join(`
170
- `)};import Tt from"node:fs";import bh from"node:path";var qo=e=>{let r;try{r=Tt.lstatSync(e)}catch{return}if(r.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},xn=(e,r)=>{qo(e);let t=Tt.existsSync(e)?Tt.readFileSync(e,"utf-8"):null;return t===r?"unchanged":(Tt.mkdirSync(bh.dirname(e),{recursive:!0}),Tt.writeFileSync(e,r,"utf-8"),t===null?"created":"updated")},Gi=(e,r,t)=>{let n=Tt.readFileSync(e,"utf-8");if(!Fe(n,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Ip=(e,r,t)=>Fe(e,r,t)?{before:e.slice(0,e.indexOf(r)),after:e.slice(e.indexOf(t)+t.length)}:null,Ui=(e,r,t,n)=>{let o=Ip(e,t,n),s=Ip(r,t,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 zo="<!-- infra-kit:import:begin -->",Yo="<!-- infra-kit:import:end -->",Rh="AGENTS.md",$p="CLAUDE.md",Eh="README.md",Ki="DESIGN.md",Ph=["frontend","mobile"],Sh=e=>At.existsSync(e)?At.readFileSync(e,"utf-8"):null,qi=(e,r)=>{try{return At.readdirSync(e).includes(r)}catch{return!1}},Ho=(e,r,t)=>{let n=r instanceof Error?r.message:String(r),o={path:e,action:"failed",message:n};return t&&(o.type=t),o},_p=({filePath:e,body:r,startMarker:t,endMarker:n,prepare:o})=>{let s=Sh(e),i=s===null?"":o?.(s)??s,a=Rt({content:i,body:r,startMarker:t,endMarker:n,placement:"replace-in-place"}),c=xn(e,a);return Gi(e,t,n),s!==null&&Ui(i,a,t,n),c},xh=e=>{if(!At.existsSync(e))return"unchanged";qo(e);let r=At.readFileSync(e,"utf-8"),t=yr(r,be,Le);return t===null?"unchanged":t.trim()===""?(At.rmSync(e),"removed"):xn(e,t)},Th=(e,r)=>_p({filePath:e,body:Bi(r),startMarker:be,endMarker:Le,prepare:t=>yr(t,zo,Yo)??t}),Tn=async(e,{version:r})=>{let t=Jr.join(e,$p),n=Jr.join(e,Rh),o=[];try{o.push({path:t,action:Th(t,r)})}catch(s){o.push(Ho(t,s))}try{o.push({path:n,action:xh(n)})}catch(s){o.push(Ho(n,s))}return o},Ah=(e,r,t)=>{if(!Ph.includes(t)||qi(e,Ki))return null;let n=Jr.join(e,Ki);try{return{path:n,action:xn(n,Vi(r)),type:t}}catch(o){return Ho(n,o,t)}},An=async(e,{repoRoot:r,version:t,design:n,declaredType:o})=>{let s=Jr.join(e,$p),i=await bn(e),a=i.name??Jr.basename(e),c=_i({packageDir:e,repoRoot:r,pkgJson:i,declaredType:o}),d=Ji({version:t,type:c,packageName:a,relDir:Jr.relative(r,e).split(Jr.sep).join("/"),hasReadme:qi(e,Eh),hasDesign:qi(e,Ki)}),p=[];try{p.push({path:s,action:_p({filePath:s,body:d,startMarker:We,endMarker:ze}),type:c})}catch(u){p.push(Ho(s,u,c))}if(n){let u=Ah(e,a,c);u&&p.push(u)}return p};import Mh from"node:path";import Op from"node:path";var Hi="agent-guidance",Cn="CLAUDE.md",Ch="\u2014 run: infra-kit audit --fix",Ih={missing:`${Cn} missing`,"no-block":`${Cn} has no infra-kit block (expected ${We} \u2026 ${ze})`,malformed:`${Cn} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Cn} carries the ROOT infra-kit block (${be}); a package needs the package block`},$h=e=>e.adopted?` (workspace adopted: ${Op.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",zi=(e,r)=>{let t=Wr(Vr(Op.join(e,Cn)));if(t.state==="ok"){let s=t.version??"unknown",i=t.type??"unknown";return{name:Hi,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${Ih[t.state]} ${Ch}`,o=t.state==="missing"?`${n}${$h(r)}`:n;return r.adopted?{name:Hi,status:"fail",message:o}:{name:Hi,status:"pass",message:`not yet adopted \u2014 ${o}`}};var Yi=async(e,r=vr)=>{try{let t=await En(e,r);return{check:{name:He,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:He,status:"fail",message:t.message},rules:null}}};import _h from"node:fs/promises";import Oh from"node:path";var Zi=async(e,r)=>Promise.all(r.map(async t=>{let n=await _h.stat(Oh.join(e,t)).catch(()=>null);return n?n.isFile()?{name:`file:${t}`,status:"pass",message:"exists"}:{name:`file:${t}`,status:"fail",message:`not a file: ${t} (found a directory)`}:{name:`file:${t}`,status:"fail",message:`missing file: ${t}`}}));var Xi=(e,r)=>r.map(t=>{let n=e[t];return typeof n!="string"?{name:`script:${t}`,status:"fail",message:`missing "${t}" in package.json scripts`}:n.trim().length===0?{name:`script:${t}`,status:"fail",message:`"${t}" is empty in package.json scripts`}:{name:`script:${t}`,status:"pass",message:"defined"}});import Dh from"node:fs/promises";import Nh from"node:path";var Ct="turbo.json",Qi=async(e,r)=>{if(r.length===0)return[];let t;try{let o=await Dh.readFile(Nh.join(e,Ct),"utf-8");t=JSON.parse(o)}catch(o){return[{name:Ct,status:"fail",message:`cannot read/parse ${Ct}: ${o.message}`}]}let n=t.tasks;return n===null||typeof n!="object"?[{name:Ct,status:"fail",message:`no "tasks" object defined in ${Ct}`}]:r.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 ${Ct}`}})};var jh={adopted:!1,workspaceRoot:null},ea=async(e,r=vr,t={})=>{let n=await bn(e),o=n.name??Mh.basename(e),{check:s,rules:i}=await Yi(e,r),a=[s];t.isRoot||a.push(zi(e,t.adoption??jh)),i&&(a.push(...Xi(n.scripts??{},i.requiredScripts)),a.push(...await Zi(e,i.requiredFiles)),a.push(...await Qi(e,i.turboTasks)));let c=a.every(d=>d.status==="pass");return{packageDir:e,packageName:o,checks:a,passed:c}};var ra=["plugin","marketplace","add",fr],ta=["plugin","install",W,"--scope","project"],Dp=(e,r)=>Fr({projectPath:e,home:r}).kind==="installed",na=e=>((e??"").split(`
171
- `).find(t=>t.trim().length>0)??"").trim(),Fh=(e,r)=>{if(vn(r))return null;l.debug({msg:`Running: ${jo} ${ra.join(" ")}`});let t=e({args:ra});return t.ok?null:{step:"marketplace",error:na(t.output)}},Lh=(e,r)=>{l.debug({msg:`Running: ${jo} ${Fo.join(" ")}`});let t=e({args:Fo,cwd:r});return t.ok?{status:"updated"}:{status:"update-failed",error:na(t.output)}},oa=e=>{let{projectRoot:r,home:t}=e,n=e.run??Ti;if(!n({args:xi}).ok)return{status:"claude-missing"};if(Dp(r,t))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Lh(n,r);let o=Fh(n,t);if(o!==null)return{status:"failed",...o};l.debug({msg:`Running: ${jo} ${ta.join(" ")}`});let s=n({args:ta,cwd:r});return s.ok?Dp(r,t)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:na(s.output)}};import Wh from"node:fs";import Vh from"node:path";var Z=".mcp.json",Te="mcpServers",Jh="infra-kit",Bh=["mcp"],Gh="/infra-kit/dist/mcp.js",sa=" ",Br=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Np=e=>{if(!Br(e))return!1;let{command:r,args:t}=e;return Array.isArray(t)?r===Jh&&t[0]===Bh[0]?!0:t.some(n=>typeof n=="string"&&n.endsWith(Gh)):!1},Mp=e=>/\n([ \t]+)"/.exec(e)?.[1]??sa,ia=e=>{try{return{kind:"raw",raw:Wh.readFileSync(e,"utf-8")}}catch(r){return r.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:r}}},aa=e=>{try{return JSON.parse(e)}catch{return}},ca=e=>e instanceof Error?e.message:String(e),Gr=e=>{let r=ia(Vh.join(e,Z));if(r.kind==="absent")return{kind:"missing-file"};if(r.kind==="unreadable")return{kind:"unparseable"};let t=aa(r.raw);if(!Br(t)||!Br(t[Te]))return{kind:"unparseable"};let n=t[Te];if(q in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Np(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Zo from"node:fs";import Uh from"node:path";var Ye=`claude plugin install ${W} --scope project`,It=`claude plugin update ${W} --scope project`,la=`claude plugin marketplace add ${fr}`,Fp=" ",Lp=()=>({source:{source:"github",repo:fr}}),Kh=()=>({extraKnownMarketplaces:{[q]:Lp()},enabledPlugins:{[W]:!0}}),Wp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qh=e=>/\n([ \t]+)"/.exec(e)?.[1]??Fp,jp=(e,r,t,n)=>{let o=e[r];return o===void 0?(e[r]={[t]:n},`${r}.${t}`):!Wp(o)||t in o?null:(o[t]=n,`${r}.${t}`)},Hh=e=>[jp(e,"extraKnownMarketplaces",q,Lp()),jp(e,"enabledPlugins",W,!0)].filter(t=>t!==null),zh=e=>{try{return Zo.readFileSync(e,"utf-8")}catch{return null}},Yh=e=>(Zo.mkdirSync(Uh.dirname(e),{recursive:!0}),Zo.writeFileSync(e,`${JSON.stringify(Kh(),null,Fp)}
172
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${q}`,`enabledPlugins.${W}`]}),da=e=>{let r=zh(e);if(r===null)return Yh(e);let t;try{t=JSON.parse(r)}catch{t=void 0}if(!Wp(t))return l.warn(`Could not parse ${e} \u2014 left it untouched. Add "${W}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Hh(t);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=qh(r),s=r.endsWith(`
164
+ `;var vp="# 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 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.\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, 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`, `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` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n";var mr={"root/body":vp.trimEnd(),"package/frontend":fp.trimEnd(),"package/backend":up.trimEnd(),"package/lib":gp.trimEnd(),"package/e2e":mp.trimEnd(),"package/mobile":hp.trimEnd(),"design/skeleton":pp.trimEnd()};var Ii=/\{\{(\w+)\}\}/g,nh=/^- \{\{(\w+)\}\}$/,oh=e=>new Set([...e.matchAll(Ii)].map(t=>t[1])),sh=(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(", ")}`)},ih=(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(", ")}`)},ah=(e,t)=>e.filter(r=>{let n=nh.exec(r);return n===null||t[n[1]]!==""}),ch=(e,t)=>{for(let r of e)for(let n of r.matchAll(Ii)){let o=t[n[1]];if(o!==void 0&&o.includes(`
165
+ `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},fr=(e,t)=>{let r=oh(e);ih(r,t),sh(r,t);let n=ah(e.split(`
166
+ `),t);return ch(n,t),n.join(`
167
+ `).replace(Ii,(o,s)=>t[s])};var lh="name: TODO",Di=e=>{let t=fr(mr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(lh,()=>r)}
168
+ `};var dh=(e,t)=>`${Et}${e} ${t} -->`,ph="`README.md` \u2014 what this package is and how to run it.",Oi=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s}=e,i=fr(mr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?ph:""});return[dh(t,r),"",i].join(`
169
+ `)};var uh=e=>`${Ci}${e} -->`,Ni=e=>{let t=fr(mr["root/body"],{});return[uh(e),"",t].join(`
170
+ `)};import gr from"node:fs";import mh from"node:path";var Jo=e=>{let t;try{t=gr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},fn=(e,t)=>{Jo(e);let r=gr.existsSync(e)?gr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(gr.mkdirSync(mh.dirname(e),{recursive:!0}),gr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},_i=(e,t,r)=>{let n=gr.readFileSync(e,"utf-8");if(!Ne(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},yp=(e,t,r)=>Ne(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Mi=(e,t,r,n)=>{let o=yp(e,r,n),s=yp(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 Bo="<!-- infra-kit:import:begin -->",Wo="<!-- infra-kit:import:end -->",fh="AGENTS.md",wp="CLAUDE.md",gh="README.md",ji="DESIGN.md",hh=["frontend","mobile"],vh=e=>hr.existsSync(e)?hr.readFileSync(e,"utf-8"):null,Fi=(e,t)=>{try{return hr.readdirSync(e).includes(t)}catch{return!1}},Vo=(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},kp=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=vh(e),i=s===null?"":o?.(s)??s,a=dr({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=fn(e,a);return _i(e,r,n),s!==null&&Mi(i,a,r,n),c},yh=e=>{if(!hr.existsSync(e))return"unchanged";Jo(e);let t=hr.readFileSync(e,"utf-8"),r=pt(t,ye,_e);return r===null?"unchanged":r.trim()===""?(hr.rmSync(e),"removed"):fn(e,r)},wh=(e,t)=>kp({filePath:e,body:Ni(t),startMarker:ye,endMarker:_e,prepare:r=>pt(r,Bo,Wo)??r}),gn=async(e,{version:t})=>{let r=Tt.join(e,wp),n=Tt.join(e,fh),o=[];try{o.push({path:r,action:wh(r,t)})}catch(s){o.push(Vo(r,s))}try{o.push({path:n,action:yh(n)})}catch(s){o.push(Vo(n,s))}return o},kh=(e,t,r)=>{if(!hh.includes(r)||Fi(e,ji))return null;let n=Tt.join(e,ji);try{return{path:n,action:fn(n,Di(t)),type:r}}catch(o){return Vo(n,o,r)}},hn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Tt.join(e,wp),i=await ln(e),a=i.name??Tt.basename(e),c=Pi({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),d=Oi({version:r,type:c,packageName:a,relDir:Tt.relative(t,e).split(Tt.sep).join("/"),hasReadme:Fi(e,gh),hasDesign:Fi(e,ji)}),p=[];try{p.push({path:s,action:kp({filePath:s,body:d,startMarker:Me,endMarker:Ue}),type:c})}catch(u){p.push(Vo(s,u,c))}if(n){let u=kh(e,a,c);u&&p.push(u)}return p};import Ch from"node:path";import bp from"node:path";var Li="agent-guidance",vn="CLAUDE.md",bh="\u2014 run: infra-kit audit --fix",Rh={missing:`${vn} missing`,"no-block":`${vn} has no infra-kit block (expected ${Me} \u2026 ${Ue})`,malformed:`${vn} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${vn} carries the ROOT infra-kit block (${ye}); a package needs the package block`},Ph=e=>e.adopted?` (workspace adopted: ${bp.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Ji=(e,t)=>{let r=St(xt(bp.join(e,vn)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Li,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${Rh[r.state]} ${bh}`,o=r.state==="missing"?`${n}${Ph(t)}`:n;return t.adopted?{name:Li,status:"fail",message:o}:{name:Li,status:"pass",message:`not yet adopted \u2014 ${o}`}};var Vi=async(e,t=dt)=>{try{let r=await pn(e,t);return{check:{name:Ge,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:Ge,status:"fail",message:r.message},rules:null}}};import Eh from"node:fs/promises";import Sh from"node:path";var Bi=async(e,t)=>Promise.all(t.map(async r=>{let n=await Eh.stat(Sh.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 Wi=(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 xh from"node:fs/promises";import Th from"node:path";var vr="turbo.json",Gi=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await xh.readFile(Th.join(e,vr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:vr,status:"fail",message:`cannot read/parse ${vr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:vr,status:"fail",message:`no "tasks" object defined in ${vr}`}]: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 ${vr}`}})};var Ah={adopted:!1,workspaceRoot:null},Ui=async(e,t=dt,r={})=>{let n=await ln(e),o=n.name??Ch.basename(e),{check:s,rules:i}=await Vi(e,t),a=[s];r.isRoot||a.push(Ji(e,r.adoption??Ah)),i&&(a.push(...Wi(n.scripts??{},i.requiredScripts)),a.push(...await Bi(e,i.requiredFiles)),a.push(...await Gi(e,i.turboTasks)));let c=a.every(d=>d.status==="pass");return{packageDir:e,packageName:o,checks:a,passed:c}};var Ki=["plugin","marketplace","add",it],qi=["plugin","install",J,"--scope","project"],Rp=(e,t)=>Pt({projectPath:e,home:t}).kind==="installed",Hi=e=>((e??"").split(`
171
+ `).find(r=>r.trim().length>0)??"").trim(),$h=(e,t)=>{if(on(t))return null;l.debug({msg:`Running: ${$o} ${Ki.join(" ")}`});let r=e({args:Ki});return r.ok?null:{step:"marketplace",error:Hi(r.output)}},Ih=(e,t)=>{l.debug({msg:`Running: ${$o} ${Io.join(" ")}`});let r=e({args:Io,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:Hi(r.output)}},Yi=e=>{let{projectRoot:t,home:r}=e,n=e.run??vi;if(!n({args:hi}).ok)return{status:"claude-missing"};if(Rp(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Ih(n,t);let o=$h(n,r);if(o!==null)return{status:"failed",...o};l.debug({msg:`Running: ${$o} ${qi.join(" ")}`});let s=n({args:qi,cwd:t});return s.ok?Rp(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:Hi(s.output)}};import Dh from"node:fs";import Oh from"node:path";var z=".mcp.json",Se="mcpServers",Nh="infra-kit",_h=["mcp"],Mh="/infra-kit/dist/mcp.js",zi=" ",Ct=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pp=e=>{if(!Ct(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Nh&&r[0]===_h[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Mh)):!1},Ep=e=>/\n([ \t]+)"/.exec(e)?.[1]??zi,Xi=e=>{try{return{kind:"raw",raw:Dh.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Zi=e=>{try{return JSON.parse(e)}catch{return}},Qi=e=>e instanceof Error?e.message:String(e),At=e=>{let t=Xi(Oh.join(e,z));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Zi(t.raw);if(!Ct(r)||!Ct(r[Se]))return{kind:"unparseable"};let n=r[Se];if(G in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Pp(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Go from"node:fs";import jh from"node:path";var Ke=`claude plugin install ${J} --scope project`,yr=`claude plugin update ${J} --scope project`,ea=`claude plugin marketplace add ${it}`,xp=" ",Tp=()=>({source:{source:"github",repo:it}}),Fh=()=>({extraKnownMarketplaces:{[G]:Tp()},enabledPlugins:{[J]:!0}}),Cp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lh=e=>/\n([ \t]+)"/.exec(e)?.[1]??xp,Sp=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Cp(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Jh=e=>[Sp(e,"extraKnownMarketplaces",G,Tp()),Sp(e,"enabledPlugins",J,!0)].filter(r=>r!==null),Vh=e=>{try{return Go.readFileSync(e,"utf-8")}catch{return null}},Bh=e=>(Go.mkdirSync(jh.dirname(e),{recursive:!0}),Go.writeFileSync(e,`${JSON.stringify(Fh(),null,xp)}
172
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${G}`,`enabledPlugins.${J}`]}),ta=e=>{let t=Vh(e);if(t===null)return Bh(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!Cp(r))return l.warn(`Could not parse ${e} \u2014 left it untouched. Add "${J}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Jh(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=Lh(t),s=t.endsWith(`
173
173
  `)?`
174
- `:"";return Zo.writeFileSync(e,`${JSON.stringify(t,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};var w=e=>[{type:"text",text:e}],k=e=>e;import Zh from"node:path";import Xh from"node:process";var Qh=["unchanged","created"],ev=["unchanged","created","updated","removed","failed"],Vp=async(e,r,t)=>{let n=await Rn(e);return An(e,{repoRoot:r,version:H.version,design:t,declaredType:n})},rv=async(e,r)=>{if(e.root)return Tn(r,{version:H.version});if(e.all){let n=[];for(let o of await me(r))n.push(...await Vp(o,r,e.design));return n}let t=await Sn(e.cwd??Xh.cwd());return Vp(t,r,e.design)},tv=e=>{let r=new Map;for(let n of e)r.set(n.action,(r.get(n.action)??0)+1);return`Agent guidance synced \u2014 ${ev.filter(n=>Qh.includes(n)||(r.get(n)??0)>0).map(n=>`${r.get(n)??0} ${n}`).join(", ")} (infra-kit ${H.version})`},nv=(e,r)=>{for(let t of e){if(t.action==="unchanged")continue;let n=Zh.relative(r,t.path),o=t.type?` (${t.type})`:"",s=t.action==="failed"&&t.message?` \u2014 ${t.message}`:"";l.info(` ${t.action.padEnd(9)} ${n}${o}${s}`)}l.info(tv(e))},ov=e=>{let r={path:e.path,action:e.action};return e.type&&(r.type=e.type),r},Jp=async(e,r)=>{let t=await b();Ko();let n=await Pt(r),o=await rv(e,t);nv(o,t),Ko();let s=await Pt(r),i=!e.all&&!e.root;return{fixed:o.map(ov),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Gp from"node:fs";import Up from"node:path";var pa="ik-mcp",Bp=(e,r)=>{let t=["--name",e];for(let n of r.env)t.push("--env",n);for(let n of r.unset)t.push("--unset",n);return t.push("--",r.command,...r.args),{type:"stdio",command:pa,args:t}};var Xo="run `infra-kit setup` (or `infra-kit audit --root --fix`)",sv=(e,r)=>Array.isArray(e)&&e.length===r.length&&e.every((t,n)=>t===r[n]),ua=e=>Br(e)&&e.command===pa,iv=(e,r)=>({...e??{},type:r.type,command:r.command,args:r.args}),av=(e,r,t)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(r)){let c=Bp(i,a),d=e[i];if(d!==void 0&&!ua(d)){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 ${Xo}, or drop mcp.${i} from infra-kit.json`});continue}if(ua(d)&&d.type===c.type&&sv(d.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(t){o[i]=iv(d,c),s=!0,n.push({name:i,status:"written",message:""});continue}n.push({name:i,status:"drifted",message:d===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: ${Xo}`:`"${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: ${Xo}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(r,i)||!ua(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}},cv=(e,r,t)=>{let n=t===null?sa:Mp(t),o=t===null||t.endsWith(`
174
+ `:"";return Go.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};var k=e=>[{type:"text",text:e}],b=e=>e;import Wh from"node:path";import Gh from"node:process";var Uh=["unchanged","created"],Kh=["unchanged","created","updated","removed","failed"],Ap=async(e,t,r)=>{let n=await dn(e);return hn(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},qh=async(e,t)=>{if(e.root)return gn(t,{version:U.version});if(e.all){let n=[];for(let o of await de(t))n.push(...await Ap(o,t,e.design));return n}let r=await mn(e.cwd??Gh.cwd());return Ap(r,t,e.design)},Hh=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 ${Kh.filter(n=>Uh.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},Yh=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Wh.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";l.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}l.info(Hh(e))},zh=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},$p=async(e,t)=>{let r=await R();Lo();let n=await ur(t),o=await qh(e,r);Yh(o,r),Lo();let s=await ur(t),i=!e.all&&!e.root;return{fixed:o.map(zh),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Dp from"node:fs";import Op from"node:path";var ra="ik-mcp",Ip=(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:ra,args:r}};var Uo="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Xh=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),na=e=>Ct(e)&&e.command===ra,Zh=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Qh=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Ip(i,a),d=e[i];if(d!==void 0&&!na(d)){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 ${Uo}, or drop mcp.${i} from infra-kit.json`});continue}if(na(d)&&d.type===c.type&&Xh(d.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Zh(d,c),s=!0,n.push({name:i,status:"written",message:""});continue}n.push({name:i,status:"drifted",message:d===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: ${Uo}`:`"${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: ${Uo}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!na(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}},ev=(e,t,r)=>{let n=r===null?zi:Ep(r),o=r===null||r.endsWith(`
175
175
  `)?`
176
- `:"";try{return Gp.mkdirSync(Up.dirname(e),{recursive:!0}),Gp.writeFileSync(e,`${JSON.stringify(r,null,n)}${o}`,"utf-8"),!0}catch(s){return l.warn(`Could not write ${e} (${ca(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Qo=({projectRoot:e,proxies:r,write:t})=>{let n=Up.join(e,Z),o=ia(n);if(o.kind==="unreadable")return l.warn(`Could not read ${n} (${ca(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:aa(s);if(!Br(i))return l.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Xo}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Te];if(a!==void 0&&!Br(a))return l.warn(`${n} has a "${Te}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=av(a??{},r,t);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let d=cv(n,{...i,[Te]:c.servers},s);return{status:d?"ok":"failed",path:n,entries:c.entries,wrote:d}};var Kp=async(e,r)=>{let t;try{t=(await P()).mcp}catch{return null}if(!t||Object.keys(t).length===0)return null;let n=Qo({projectRoot:e,proxies:t,write:r});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 lv=(e,r)=>[...r.map(t=>({name:`devServersPresets:config:${t.app}`,status:"fail",message:`could not load apps/${t.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${t.message}`})),...e.map(t=>({name:`devServersPresets:${t.preset}`,status:"fail",message:t.message}))],qp=async e=>{let r=(await P()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=Zd(r);if(t.length>0){let p=t.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:p,passed:!1}}let n=zd(e),o=Yd(e),s={api:n.map(p=>p.name),ui:o.map(p=>p.name)},{ctx:i,loadErrors:a}=await Qd(e,r,s,n),c=lv(Xd(r,i),a),d=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:d,passed:c.length===0}};var dv="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",pv=async e=>e.root?[{dir:await b(),baseline:Oi,isRoot:!0}]:e.all?(await me(await b())).map(t=>({dir:t})):[{dir:await Sn(e.cwd??Hp.cwd())}],uv=async e=>e.root||e.all?await b():e.cwd??Hp.cwd(),mv=e=>{let r=0,t=0;for(let i of e)for(let a of i.checks)r+=1,a.status!=="pass"&&(t+=1,l.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(r,"check")}, ${o(e.length,"target")}`;return l.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${t}/${s}`),n},fv=async(e,r)=>{let{fixed:t,adoptionFlipped:n}=await Jp(e,r);return n&&l.info(dv),t},gv=e=>{if(Gr(e).kind!=="stale")return null;let r=`${Z} still registers "${q}" \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 "${q}" entry by hand in a PR, keeping its siblings`;return l.info(`[INFO] mcp mcp:legacy-key: ${r}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:r}],passed:!0}},es=async(e={})=>{let r=Li(await uv(e)),t=e.fix?await fv(e,r):void 0,n=await pv(e),o=await Pt(r),s=[];for(let c of n)s.push(await ea(c.dir,c.baseline,{adoption:o,isRoot:c.isRoot}));if(e.root){let c=await qp(n[0].dir);c&&s.push(c);let d=await Kp(n[0].dir,e.fix===!0);d&&s.push(d);let p=gv(n[0].dir);p&&s.push(p)}let a={allPassed:mv(s),packages:s.map(c=>({name:c.packageName,passed:c.passed,checks:c.checks}))};return t&&(a.fixed=t),{content:w(JSON.stringify(a,null,2)),structuredContent:a}},hv={all:Re.boolean().optional().describe("Audit every non-vendor workspace package"),root:Re.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},vv={allPassed:Re.boolean().describe("Whether every audited package passed all checks"),packages:Re.array(Re.object({name:Re.string(),passed:Re.boolean(),checks:Re.array(Re.object({name:Re.string(),status:Re.enum(["pass","fail"]),message:Re.string()}))})).describe("Per-package check results")},ma=k({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:hv,outputSchema:vv,handler:e=>es({all:e.all,root:e.root})});import{z as In}from"zod";var rs=async()=>{let[e,r]=await Promise.all([P(),V()]),t=Object.keys(e).sort();l.info(`Merged config for ${r.projectName} \u2014 ${t.length} section(s): ${t.join(", ")}`),l.info(` source: ${r.main}`);let n={config:e,configPath:r.main,projectName:r.projectName};return{content:w(JSON.stringify(n,null,2)),structuredContent:n}},yv={config:In.record(In.string(),In.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, envAutoLoad, dev, devServersPresets, and devProxy."),configPath:In.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:In.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},fa=k({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:yv,handler:()=>rs()});import Pv from"node:fs";import{z as ie}from"zod";import $n from"node:fs";import $t from"node:path";import wv from"node:process";var kv=$t.join(".infra-kit","dev-context"),bv=".infra-kit",zp=(e,r)=>{let t=$t.resolve(e);for(;;){let n=$t.join(t,r);if($n.existsSync(n))return n;let o=$t.dirname(t);if(o===t)return;t=o}},Rv=e=>{let r=zp(e,kv);if(r)return r;let t=zp(e,bv);return t?$t.join(t,"dev-context"):void 0},ga=e=>typeof e=="number"&&Number.isFinite(e)?e:0,ts=e=>typeof e=="string"?e:"",Ev=(e,r,t)=>{let n=$t.join(e,r);try{let o=$n.statSync(n),s=JSON.parse($n.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:r.replace(/\.json$/,""),package:ts(i.package),port:ga(i.port),alias:ts(i.alias),origin:ts(i.origin),release:ts(i.release),pid:ga(i.pid),writtenAt:ga(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(t-o.mtimeMs))}}catch{return null}},ha=(e=wv.cwd())=>{let r=Date.now(),t=Rv(e);if(!t||!$n.existsSync(t))return{session:"none",fragmentDir:t,readAt:r,apps:[]};let n;try{n=$n.readdirSync(t).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:t,readAt:r,apps:[]}}let o=n.map(s=>Ev(t,s,r)).filter(s=>s!==null).sort((s,i)=>s.app.localeCompare(i.app));return{session:o.length>0?"active":"none",fragmentDir:t,readAt:r,apps:o}};var ns=async(e={})=>{let r=e.now??Date.now,t=e.isListening??fn,n=ha(e.cwd),o=r(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),v=await t(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:v}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(Pv.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),d=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){l.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${d}:`);for(let u of s){let m=u.live?"live":"NOT responding",v=`written ${u.ageSeconds}s ago`;l.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${v}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";l.info(`No active infra-kit dev session \u2014 searched ${d} (${u}).`)}let p={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}},Sv={active:ie.boolean().describe("True when at least one dev-context fragment exists on disk (an infra-kit dev session has apps registered). False means no active dev session was found \u2014 this is a clean result, NOT an error."),contextDir:ie.string().nullable().describe("The RESOLVED dev-context fragment directory \u2014 found by searching UPWARD from the working directory. This is where the read looked, NOT proof anything is there: when no fragment directory exists the resolver derives one from an up-tree `.infra-kit`, so this can name a path (even under $HOME) that was never written to. Check contextDirExists before drawing any conclusion from it. Null when no `.infra-kit` anchor exists up-tree at all."),contextDirExists:ie.boolean().describe('Whether contextDir actually exists on disk. False with a non-null contextDir means the path was DERIVED, not read \u2014 the usual state in a repo where `infra-kit dev` has never run. Distinguishes "looked and found nothing" from "had nowhere to look".'),apps:ie.array(ie.object({app:ie.string().describe("App folder name (the fragment filename without .json)."),package:ie.string().describe("The app package name the vite helper reads to decide a local route."),port:ie.number().describe("The actual bound port the dev server is listening on."),pid:ie.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ie.string().describe("Registered portless hostname for the app."),origin:ie.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ie.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ie.string().nullable().describe("ISO 8601 time the runner self-reported writing the fragment (writer clock \u2014 may be wrong; prefer fragmentMtime). Null when the fragment did not record it."),fragmentMtime:ie.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ie.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ie.boolean().describe("Whether a TCP connection to the app port succeeds RIGHT NOW (a real engine liveness probe, not an inference). A fresh fragment with live:false is a crashed or killed dev server whose fragment was not cleaned up.")})).describe("One entry per dev-context fragment on disk, sorted by app name. Empty when no dev session is active.")},va=k({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:Sv,handler:()=>ns()});import{spawnSync as pk}from"node:child_process";import F from"node:fs";import gm from"node:os";import Q from"node:path";import Sr from"node:process";import{z as ce}from"zod";import{execFileSync as xv}from"node:child_process";var Yp=(e,r)=>{let t=e.filter(n=>!n.live).map(n=>n.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},Tv=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],Av=e=>Tv.some(r=>r.test(e)),Cv="/bin/ps",Iv=()=>xv(Cv,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
177
- `),Zp=(e=Iv)=>{try{return e().some(Av)}catch{return!0}};import{Chalk as $v}from"chalk";import ya from"node:process";var _v="Tools & CLIs",Ov="Shell & integration",Dv="Project config",Nv="Doppler env tokens",Mv="Dev proxy (portless)",jv="Claude Code plugin",Fv=`portless serving TLS on :${gr}`,wa=[[_v,["brew installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Ov,["zshrc init block","zshenv session block","warm cache","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Dv,["infra-kit config valid","user override path","legacy user-global config"]],[Nv,["tokens.json present","env tokens configured","env token valid","tokens.json perms"]],[Mv,["portless installed","portless service target",Fv,"portless CA chain valid","portless CA trusted","portless routes"]],[jv,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","MCP server key","Agent mode","Agent allowlist"]]],Xp="Other",Lv=wa.map(([e])=>e),Wv=new Map(wa.flatMap(([e,r])=>r.map(t=>[t,e]))),t$=wa.flatMap(([,e])=>e),ka=new Set(["portless routes","tokens.json perms"]),Vv=e=>{let r=new Map;for(let n of e){let o=Wv.get(n.name)??Xp,s=r.get(o);s?s.push(n):r.set(o,[n])}return[...Lv,Xp].flatMap(n=>{let o=r.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})},Qp={unicode:{pass:"\u2713",fail:"\u2717",warn:"!",separator:"\xB7",rule:"\u2500"},ascii:{pass:"ok",fail:"!!",warn:"!?",separator:"-",rule:"-"}},Jv=24,Bv=(e,r)=>{let t=e.split(/\s+/).filter(s=>s.length>0),n=[],o="";for(let s of t)o.length===0?o=s:`${o} ${s}`.length<=r?o=`${o} ${s}`:(n.push(o),o=s);return o.length>0&&n.push(o),n.length>0?n:[""]},ru=e=>{let r=t=>e.filter(n=>n.status===t).length;return{passed:r("pass"),failed:r("fail"),warned:r("warn")}},Gv=e=>{let r=new $v({level:e?1:0});return{header:t=>r.bold.cyan(t),pass:t=>r.green(t),fail:t=>r.red(t),warn:t=>r.yellow(t),dim:t=>r.dim(t),bold:t=>r.bold(t)}},Uv=(e,r,t,n)=>{if(e.failed===0&&e.warned===0){let c=`${r}/${r} ok`;return{text:t.pass(c),plainWidth:c.length}}let o=`${e.passed}/${r}`,s=[...e.failed===0?[]:[{plain:`${e.failed} failed`,paint:t.fail}],...e.warned===0?[]:[{plain:`${e.warned} warning${e.warned===1?"":"s"}`,paint:t.warn}]],i=[t.dim(o),...s.map(c=>c.paint(c.plain))].join(` ${n.separator} `),a=s.reduce((c,d)=>c+d.plain.length+3,o.length);return{text:i,plainWidth:a}},_t=" ",eu=" ",Kv=(e,r,t,n)=>{let o=ru(e.checks),s=Uv(o,e.checks.length,r,t),i=Math.max(1,n-_t.length-e.label.length-s.plainWidth);return`${_t}${r.header(e.label)}${" ".repeat(i)}${s.text}`},qv=(e,r,t,n,o)=>{let s=e.status!=="pass",i=n.pass.length,a=n[e.status],c=e.name.padEnd(r),d=t[e.status],p=d(a),u=s?d(c):c,m=eu.length+i+1+r+2,v=Math.max(Jv,o-m),[f,...T]=Bv(e.message,v),C=re=>s?re:t.dim(re);return[`${eu}${p} ${u} ${C(f??"")}`.trimEnd(),...T.map(re=>`${" ".repeat(m)}${C(re)}`)]},Hv=(e,r,t,n)=>{let o=ru(e),s=t.rule.repeat(Math.max(12,Math.min(n-_t.length,56))),i=e.filter(p=>p.status==="fail"&&ka.has(p.name)).length,a=[r.pass(`${o.passed} passed`),...o.failed===0?[]:[r.fail(`${o.failed} failed`)],...o.warned===0?[]:[r.warn(`${o.warned} warned`)]].join(` ${t.separator} `),c=r.dim(`${i} fixable \u2014 run \`infra-kit doctor --fix\``),d=i>0?` ${c}`:"";return[`${_t}${r.dim(s)}`,`${_t}${a}${d}`]},zv=(e,r={})=>{let t=r.color??!1,n=r.unicode??!0,o=r.width??80,s=Gv(t),i=n?Qp.unicode:Qp.ascii;if(e.length===0)return[s.bold("infra-kit doctor"),"",`${_t}${s.dim("No checks ran.")}`];let a=Math.max(...e.map(d=>d.name.length)),c=Vv(e).flatMap(d=>[Kv(d,s,i,o),...d.checks.flatMap(p=>qv(p,a,s,i,o)),""]);return[s.bold("infra-kit doctor"),"",...c,...Hv(e,s,i,o)]},Yv=new Set(["","0","false","none"]),Zv=["LC_ALL","LC_CTYPE","LANG"],Xv=(e,r)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Yv.has(e.FORCE_COLOR.toLowerCase()):!!r.isTTY,Qv=(e,r)=>{if(r)return!1;let t=Zv.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return t===void 0?!0:/UTF-?8/i.test(t)},ey=(e={})=>{let r=e.env??ya.env,t=e.stream??ya.stderr;return{color:Xv(r,t),unicode:Qv(r,e.ascii??!1),width:t.columns??80}},ba=(e,r={})=>{(r.write??(n=>{ya.stderr.write(n)}))(`${zv(e,ey(r)).join(`
176
+ `:"";try{return Dp.mkdirSync(Op.dirname(e),{recursive:!0}),Dp.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return l.warn(`Could not write ${e} (${Qi(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Ko=({projectRoot:e,proxies:t,write:r})=>{let n=Op.join(e,z),o=Xi(n);if(o.kind==="unreadable")return l.warn(`Could not read ${n} (${Qi(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Zi(s);if(!Ct(i))return l.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Uo}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Se];if(a!==void 0&&!Ct(a))return l.warn(`${n} has a "${Se}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Qh(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let d=ev(n,{...i,[Se]:c.servers},s);return{status:d?"ok":"failed",path:n,entries:c.entries,wrote:d}};var Np=async(e,t)=>{let r;try{r=(await $()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Ko({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(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 tv=(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}))],_p=async e=>{let t=(await $()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Jd(t);if(r.length>0){let p=r.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:p,passed:!1}}let n=Fd(e),o=Ld(e),s={api:n.map(p=>p.name),ui:o.map(p=>p.name)},{ctx:i,loadErrors:a}=await Bd(e,t,s,n),c=tv(Vd(t,i),a),d=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:d,passed:c.length===0}};var rv="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",nv=async e=>e.root?[{dir:await R(),baseline:Ei,isRoot:!0}]:e.all?(await de(await R())).map(r=>({dir:r})):[{dir:await mn(e.cwd??Mp.cwd())}],ov=async e=>e.root||e.all?await R():e.cwd??Mp.cwd(),sv=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,l.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 l.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},iv=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await $p(e,t);return n&&l.info(rv),r},av=e=>{if(At(e).kind!=="stale")return null;let t=`${z} still registers "${G}" \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 "${G}" entry by hand in a PR, keeping its siblings`;return l.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},qo=async(e={})=>{let t=$i(await ov(e)),r=e.fix?await iv(e,t):void 0,n=await nv(e),o=await ur(t),s=[];for(let c of n)s.push(await Ui(c.dir,c.baseline,{adoption:o,isRoot:c.isRoot}));if(e.root){let c=await _p(n[0].dir);c&&s.push(c);let d=await Np(n[0].dir,e.fix===!0);d&&s.push(d);let p=av(n[0].dir);p&&s.push(p)}let a={allPassed:sv(s),packages:s.map(c=>({name:c.packageName,passed:c.passed,checks:c.checks}))};return r&&(a.fixed=r),{content:k(JSON.stringify(a,null,2)),structuredContent:a}},cv={all:we.boolean().optional().describe("Audit every non-vendor workspace package"),root:we.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},lv={allPassed:we.boolean().describe("Whether every audited package passed all checks"),packages:we.array(we.object({name:we.string(),passed:we.boolean(),checks:we.array(we.object({name:we.string(),status:we.enum(["pass","fail"]),message:we.string()}))})).describe("Per-package check results")},oa=b({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:cv,outputSchema:lv,handler:e=>qo({all:e.all,root:e.root})});import{z as yn}from"zod";var Ho=async()=>{let[e,t]=await Promise.all([$(),q()]),r=Object.keys(e).sort();l.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),l.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},dv={config:yn.record(yn.string(),yn.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:yn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:yn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},sa=b({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:dv,handler:()=>Ho()});import hv from"node:fs";import{z as ee}from"zod";import wn from"node:fs";import wr from"node:path";import pv from"node:process";var uv=wr.join(".infra-kit","dev-context"),mv=".infra-kit",jp=(e,t)=>{let r=wr.resolve(e);for(;;){let n=wr.join(r,t);if(wn.existsSync(n))return n;let o=wr.dirname(r);if(o===r)return;r=o}},fv=e=>{let t=jp(e,uv);if(t)return t;let r=jp(e,mv);return r?wr.join(r,"dev-context"):void 0},ia=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Yo=e=>typeof e=="string"?e:"",gv=(e,t,r)=>{let n=wr.join(e,t);try{let o=wn.statSync(n),s=JSON.parse(wn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Yo(i.package),port:ia(i.port),alias:Yo(i.alias),origin:Yo(i.origin),release:Yo(i.release),pid:ia(i.pid),writtenAt:ia(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},aa=(e=pv.cwd())=>{let t=Date.now(),r=fv(e);if(!r||!wn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=wn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>gv(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 zo=async(e={})=>{let t=e.now??Date.now,r=e.isListening??tn,n=aa(e.cwd),o=t(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),h=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:h}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(hv.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),d=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){l.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${d}:`);for(let u of s){let m=u.live?"live":"NOT responding",h=`written ${u.ageSeconds}s ago`;l.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${h}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";l.info(`No active infra-kit dev session \u2014 searched ${d} (${u}).`)}let p={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},vv={active:ee.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:ee.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:ee.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:ee.array(ee.object({app:ee.string().describe("App folder name (the fragment filename without .json)."),package:ee.string().describe("The app package name the vite helper reads to decide a local route."),port:ee.number().describe("The actual bound port the dev server is listening on."),pid:ee.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ee.string().describe("Registered portless hostname for the app."),origin:ee.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ee.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ee.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:ee.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ee.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ee.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.")},ca=b({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:vv,handler:()=>zo()});import{spawnSync as Ku}from"node:child_process";import H from"node:fs";import qu from"node:os";import re from"node:path";import Le from"node:process";import{z as oe}from"zod";import{execFileSync as yv}from"node:child_process";var Fp=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},wv=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],kv=e=>wv.some(t=>t.test(e)),bv="/bin/ps",Rv=()=>yv(bv,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
177
+ `),Lp=(e=Rv)=>{try{return e().some(kv)}catch{return!0}};import{Chalk as Pv}from"chalk";import la from"node:process";var Ev="Tools & CLIs",Sv="Shell & integration",xv="Project config",Tv="Doppler env tokens",Cv="Dev proxy (portless)",Av="Claude Code plugin",$v=`portless serving TLS on :${at}`,da=[[Ev,["brew installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Sv,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[xv,["infra-kit config valid","user override path","legacy user-global config"]],[Tv,["tokens.json present","env tokens configured","tokens.json perms"]],[Cv,["portless installed","portless node","portless service target",$v,"portless CA chain valid","portless CA trusted","portless routes"]],[Av,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","MCP server key","Agent mode","Agent allowlist"]]],Jp="Other",Iv=da.map(([e])=>e),Dv=new Map(da.flatMap(([e,t])=>t.map(r=>[r,e]))),K$=da.flatMap(([,e])=>e),pa=new Set(["portless routes","tokens.json perms"]),Ov=e=>{let t=new Map;for(let n of e){let o=Dv.get(n.name)??Jp,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Iv,Jp].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})},Vp={unicode:{pass:"\u2713",fail:"\u2717",warn:"!",separator:"\xB7",rule:"\u2500"},ascii:{pass:"ok",fail:"!!",warn:"!?",separator:"-",rule:"-"}},Nv=24,_v=(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:[""]},Wp=e=>{let t=r=>e.filter(n=>n.status===r).length;return{passed:t("pass"),failed:t("fail"),warned:t("warn")}},Mv=e=>{let t=new Pv({level:e?1:0});return{header:r=>t.bold.cyan(r),pass:r=>t.green(r),fail:r=>t.red(r),warn:r=>t.yellow(r),dim:r=>t.dim(r),bold:r=>t.bold(r)}},jv=(e,t,r,n)=>{if(e.failed===0&&e.warned===0){let c=`${t}/${t} ok`;return{text:r.pass(c),plainWidth:c.length}}let o=`${e.passed}/${t}`,s=[...e.failed===0?[]:[{plain:`${e.failed} failed`,paint:r.fail}],...e.warned===0?[]:[{plain:`${e.warned} warning${e.warned===1?"":"s"}`,paint:r.warn}]],i=[r.dim(o),...s.map(c=>c.paint(c.plain))].join(` ${n.separator} `),a=s.reduce((c,d)=>c+d.plain.length+3,o.length);return{text:i,plainWidth:a}},kr=" ",Bp=" ",Fv=(e,t,r,n)=>{let o=Wp(e.checks),s=jv(o,e.checks.length,t,r),i=Math.max(1,n-kr.length-e.label.length-s.plainWidth);return`${kr}${t.header(e.label)}${" ".repeat(i)}${s.text}`},Lv=(e,t,r,n,o)=>{let s=e.status!=="pass",i=n.pass.length,a=n[e.status],c=e.name.padEnd(t),d=r[e.status],p=d(a),u=s?d(c):c,m=Bp.length+i+1+t+2,h=Math.max(Nv,o-m),[y,...v]=_v(e.message,h),I=F=>s?F:r.dim(F);return[`${Bp}${p} ${u} ${I(y??"")}`.trimEnd(),...v.map(F=>`${" ".repeat(m)}${I(F)}`)]},Jv=(e,t,r,n)=>{let o=Wp(e),s=r.rule.repeat(Math.max(12,Math.min(n-kr.length,56))),i=e.filter(p=>p.status==="fail"&&pa.has(p.name)).length,a=[t.pass(`${o.passed} passed`),...o.failed===0?[]:[t.fail(`${o.failed} failed`)],...o.warned===0?[]:[t.warn(`${o.warned} warned`)]].join(` ${r.separator} `),c=t.dim(`${i} fixable \u2014 run \`infra-kit doctor --fix\``),d=i>0?` ${c}`:"";return[`${kr}${t.dim(s)}`,`${kr}${a}${d}`]},Vv=(e,t={})=>{let r=t.color??!1,n=t.unicode??!0,o=t.width??80,s=Mv(r),i=n?Vp.unicode:Vp.ascii;if(e.length===0)return[s.bold("infra-kit doctor"),"",`${kr}${s.dim("No checks ran.")}`];let a=Math.max(...e.map(d=>d.name.length)),c=Ov(e).flatMap(d=>[Fv(d,s,i,o),...d.checks.flatMap(p=>Lv(p,a,s,i,o)),""]);return[s.bold("infra-kit doctor"),"",...c,...Jv(e,s,i,o)]},Bv=new Set(["","0","false","none"]),Wv=["LC_ALL","LC_CTYPE","LANG"],Gv=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Bv.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,Uv=(e,t)=>{if(t)return!1;let r=Wv.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Kv=(e={})=>{let t=e.env??la.env,r=e.stream??la.stderr;return{color:Gv(t,r),unicode:Uv(t,e.ascii??!1),width:r.columns??80}},ua=(e,t={})=>{(t.write??(n=>{la.stderr.write(n)}))(`${Vv(e,Kv(t)).join(`
178
178
  `)}
179
- `)};var ry=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),ty=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(r=>ry(r[1])),ny=e=>{let r=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return r===null?null:ty(r[1])},oy=e=>{let r=[],t="",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 d=i[a+1];if(c==="\\"&&(d==='"'||d==="\\")){t+=d,o=!0,s=!0;continue}if(/\s/.test(c)&&!n){o&&(r.push(t),t="",o=!1);continue}t+=c,o=!0}return o&&r.push(t),r},sy=e=>{let r=e.split(`
180
- `).find(t=>t.startsWith("ExecStart="));return r===void 0?null:oy(r.slice(10))},tu=(e,r)=>{try{return e==="darwin"?ny(r):e==="linux"?sy(r):null}catch{return null}};import by from"@inquirer/select";import{Buffer as Ry}from"node:buffer";import Ey from"node:fs";import Py from"node:path";import $a from"node:process";import{z as Wt}from"zod";import{$ as as}from"zx";var iy="Could not find requested project",ay="Could not find requested config",nu="Invalid Auth token",ou="does not have access to requested config",Ur=e=>e.includes(nu)||e.includes(ou)?"auth":e.includes(iy)?"project":e.includes(ay)?"config":"unknown",Kr=e=>e.includes(ou)?"mis-scoped":e.includes(nu)?"revoked":null;var su=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(`
181
- `),Ot=class extends Wo{authKind;constructor(r,t=null,n){super(n??su(r),r),this.name="DopplerAuthError",this.authKind=t}};var Ra=({kind:e,project:r,config:t,available:n})=>{let o=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}".`];if(n&&n.length>0){let s=e==="project"?"Available projects":`Available configs in "${r}"`;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(`
182
- `)};import{$ as os}from"zx";var cy=5e3,ly="DOPPLER_CONFIG",Ae=async()=>{let{envManagement:e}=await P();return e.config.name},_n=async({childEnv:e,project:r,config:t})=>{let n=os.quiet;os.quiet=!0;try{let s=(await os({env:e})`doppler secrets get ${ly} --plain --project ${r} --config ${t}`.timeout(cy)).stdout.trim();return s!==t?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(o){return{outcome:dy(o)}}finally{os.quiet=n}},dy=e=>{let r=vt(e)??(e instanceof Error?e.message:String(e));return Ur(r)!=="auth"?"unreachable":Kr(r)??"unreachable"};import iu from"node:process";var X="INFRA_KIT_ENV_TOKEN",Dt=async e=>{let r=iu.env[X];if(r)return{token:r,source:"env"};let n=(await oe())?.envs[e];if(n)return{token:n,source:"store"};throw new Wo(py(e,await qe()),e)},au=async e=>iu.env[X]?!0:!!(await oe())?.envs[e],py=(e,r)=>[`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 ${y(r)} (mode 0600, never in the repo).`,`CI / agents: set ${X} instead \u2014 it takes precedence and needs no home config.`].join(`
183
- `);import hu from"node:process";import{z as fu}from"zod";import fy from"node:process";import{z as wr}from"zod";var cu=["prod"],Nt={allowed:!1,reason:"disallow"},Mt=e=>cu.includes(e),uy=["dev","stage"],jt=e=>uy.includes(e)||Mt(e),Ze=(e,r=Nt)=>r.allowed?e:e.filter(t=>!Mt(t)),qr=(e,r,t=Nt)=>{if(!t.allowed&&Mt(e))throw t.reason==="agent-blocked"?new A({status:"refused",env:e,agentMode:I.source},2,{operation:r,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new g(void 0,{operation:r,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 Xe=async()=>{let e;try{e=(await P()).protectedEnvs??"disallow"}catch{return Nt}return e==="disallow"?Nt:e==="cli-only"&&ne()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var On=e=>{let{env:r,branch:t}=e;Mt(r)&&l.warn([`\u26A0\uFE0F "${r}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${t}" ships ${r} 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(`
184
- `))};import lu from"node:fs/promises";import Ea from"node:path";import my from"yaml";var du=".github/workflows",Qe=async e=>{let r=await b();return pu(Ea.resolve(r,du,e))},Pa=async()=>{let e=await b(),r=Ea.resolve(e,du),t;try{t=await lu.readdir(r)}catch{return[]}let n=t.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>pu(Ea.resolve(r,s))));return[...new Set(o.flat())]},pu=async e=>{let r;try{r=my.parse(await lu.readFile(e,"utf-8"))}catch{return[]}let t=Ft(r,"on")??Ft(r,"true"),n=Ft(Ft(Ft(Ft(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},Ft=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var Lt=async()=>{let e=await Pa(),r=await oe(),t=e.map(s=>({env:s,source:"gh-workflow"})),n=new Set(e),o=Object.keys(r?.envs??{}).filter(s=>!n.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...t,...o]},Hr=async()=>(await Lt()).map(r=>r.env);var ss=(e,r,t)=>e.map(({env:n,source:o})=>({env:n,source:o,hasToken:!!(t||r[n])})),uu=["Environment","Source","Token"],gy=e=>{let r=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),t=uu.map((s,i)=>Math.max(s.length,...r.map(a=>(a[i]??"").length))),n=s=>s.map((i,a)=>i.padEnd(t[a]??0)).join(" | ").trimEnd(),o=t.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",n(uu),o,...r.map(n)]},is=async()=>{let e=await Ae(),r=await Lt(),t=await oe(),n=fy.env[X],o=ss(r,t?.envs??{},n);if(l.info(`Doppler project: ${e}
185
- `),o.length===0)return l.info("No environments found."),l.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),l.info(" or add a token for one manually."),mu({project:e,envs:o});for(let s of gy(o))l.info(s);return mu({project:e,envs:o})},mu=({project:e,envs:r})=>{let t={project:e,configs:r.map(n=>n.env),tokens:r};return{content:w(JSON.stringify(t,null,2)),structuredContent:t}},Sa=k({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:wr.string().describe("Detected Doppler project name"),configs:wr.array(wr.string()).describe("Every environment name known to this project"),tokens:wr.array(wr.object({env:wr.string().describe("Environment / Doppler config name"),source:wr.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:wr.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:is});var gu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hy=async e=>{try{return await e}catch{return[]}},vy=async e=>{let r=await oe().catch(()=>null);return ss(e,r?.envs??{},hu.env[X]).filter(t=>!t.hasToken).map(t=>t.env)},xa=()=>({get message(){return`Choose the environment to load into terminal session ${hu.env[Ge]??`UNKNOWN \u2014 ${Ge} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>gu(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await hy(Lt());if(e.length===0)return l.info({msg:"Tool execution form options empty: env-load"}),null;let r=e.map(n=>n.env),t=await vy(e);return fu.object({config:fu.enum(r).describe(`The environment to load. ${t.length===0?"A service token is stored for every one of them.":`NO stored token for: ${t.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,r)=>{let{config:t}=e;return typeof t!="string"||t.length===0?null:{...gu(r)?r:{},config:t}}});import{z as yy}from"zod";var wy=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(r){return l.debug({err:r,operation:e.operation},"argument form builder threw; refusing without choices"),null}},Ee=async e=>{if(!we()||!e.provider.isFormable(e.params))return;let r=await wy(e),t=typeof e.params=="object"&&e.params!==null?e.params:{},n=(r===null?[]:Object.keys(r.shape)).filter(i=>t[i]===void 0||t[i]===""),o=typeof e.argument=="string"?e.argument:e.argument(n),s=r===null?void 0:yy.toJSONSchema(r);throw new A({status:"argument_required",argument:o,...s===void 0?{}:{choices:s},agentMode:I.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`})};import vu from"node:fs";import{$ as ky}from"zx";import zr from"node:fs";import Dn from"node:path";var Ta=({autoLoaded:e,projectDir:r,canonicalProjectRoot:t})=>!e||!r||!t?!1:t===r,er=e=>{if(!e)return"";try{return zr.realpathSync(e)}catch{return""}},Aa=(e,r)=>{try{let t=Mr(e);zr.mkdirSync(t,{recursive:!0,mode:448}),Ue(Dn.join(t,te),r,384)}catch(t){l.debug(`warm-cache write skipped: ${t.message}`)}},Ca=(e=Date.now(),r=un)=>{let t=dd(),n;try{n=zr.readdirSync(t,{withFileTypes:!0})}catch{return}for(let o of n){if(!o.isDirectory())continue;let s=Dn.join(t,o.name);try{let{mtimeMs:i}=zr.statSync(Dn.join(s,te));e-i>=r*1e3&&zr.rmSync(s,{recursive:!0,force:!0})}catch{}}},Ia=(e,r)=>{try{let t=Mr(e);if(r){zr.rmSync(t,{recursive:!0,force:!0});return}if(!zr.existsSync(Dn.join(t,te)))return;Ue(Dn.join(t,gt),`# infra-kit warm cache cleared
186
- `,384)}catch(t){l.debug(`warm-cache invalidate skipped: ${t.message}`)}};var yu=e=>e.split(`
187
- `).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),Nn=async()=>{let e;try{e=(await ky({quiet:!0})`git worktree list --porcelain`).stdout}catch(t){return l.debug(`warm-cache purge skipped (not a git repo?): ${t.message}`),[]}let r=[];for(let t of yu(e)){let n=er(t);if(!n)continue;let o=Mr(n);try{if(!vu.existsSync(o))continue;vu.rmSync(o,{recursive:!0,force:!0}),r.push(o)}catch(s){l.debug(`warm-cache purge skipped for ${o}: ${s.message}`)}}return r};var Sy=e=>e?[`${Ne}=${Yr("1")}`]:[`unset ${Ne}`,`unset ${mr}`],xy="DOPPLER_CONFIG",wu=new Set(["DOPPLER_TOKEN",X]),ku=!1,Ty=e=>{e.length===0||ku||(ku=!0,l.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Ru=({pairs:e,config:r,project:t,projectRoot:n,loadedAt:o,autoLoaded:s})=>{let i=e.filter(([a])=>!wu.has(a));return Ty(e.filter(([a])=>wu.has(a)).map(([a])=>a)),["set -a",...i.map(([a,c])=>`${a}=${Yr(c)}`),`${So}=${Yr(r)}`,`${pr}=${Yr(r)}`,`${ur}=${Yr(t)}`,`${xo}=${Yr(n)}`,`${ht}=${Yr(o)}`,...Sy(s),"set +a"]},Ay=async()=>{try{return await b()}catch{return""}},cs=async({config:e,autoLoaded:r=!1,beforeWrite:t,projectDir:n})=>{let o=await Ae(),s=await Ay(),i=await $y(o,e),a=new Date().toISOString(),d=`${Ru({pairs:i,config:e,project:o,projectRoot:s,loadedAt:a,autoLoaded:r}).join(`
188
- `)}
189
- `,p=z(),u=Py.resolve(p,te);if(t&&!t())return null;Ey.mkdirSync(p,{recursive:!0,mode:448}),Ue(u,d,384);let m=er(s);return Ta({autoLoaded:r,projectDir:n,canonicalProjectRoot:m})&&(Aa(n,d),Ca()),{filePath:u,variableCount:i.length,project:o,config:e}},Eu=xa(),ls=async e=>{let{config:r}=e;await Ee({provider:Eu,params:e,operation:"env-load",argument:"config"});let t="";if(r)t=r;else{if(ne())throw new A({status:"argument_required",argument:"config",agentMode:I.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await Hr();h.setInteractive(),t=await S(i=>by({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:$a.stderr,whenHeadless:"refuse"})}h.addOption("--config",t);let n=await cs({config:t,autoLoaded:!1});if(!n)throw new Error("env-load: write was unexpectedly aborted");h.print();let o={filePath:n.filePath,variableCount:n.variableCount,project:n.project,config:n.config,sessionId:$a.env[Ge]??null};return{content:w(JSON.stringify(o,null,2)),structuredContent:o}},bu=1024*1024,Cy=3e4,Iy=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],kr=(e,r=$a.env)=>{let t={...r};for(let n of Iy)delete t[n];return t.DOPPLER_TOKEN=e,t},$y=async(e,r)=>{let{token:t}=await Dt(r),n=kr(t),o=as.quiet;as.quiet=!0;try{let s;try{s=await as({env:n})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(Cy)}catch(a){throw _y(a,e,r)}Oy(s.stdout);let i=ps(s.stdout);return ds(i,r),i}finally{as.quiet=o}},ds=(e,r)=>{let t=e.find(([n])=>n===xy)?.[1];if(!(t===void 0||t===r))throw new Ot(r,null,`Doppler returned secrets for config "${t}" but "${r}" was requested \u2014 the service token for env "${r}" is scoped to the wrong config. Refusing to load another environment's secrets.
190
- Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},_y=(e,r,t)=>{let n=vt(e)??(e instanceof Error?e.message:String(e)),o=Ur(n);return o==="auth"?new Ot(t,Kr(n)):o==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(Ra({kind:o,project:r,config:t,available:null}))},Oy=e=>{let r=Ry.byteLength(e,"utf-8");if(r>bu)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${bu}) \u2014 refusing to write to disk`)},Yr=e=>`'${e.replaceAll("'","'\\''")}'`,Dy=/^[A-Z_]\w*$/i,ps=e=>{let r;try{r=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let t=[];for(let[n,o]of Object.entries(r)){if(!Dy.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})`);t.push([n,o])}if(t.length===0)throw new Error("doppler returned empty output for env-load");return t},_a=k({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:Wt.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Eu,outputSchema:{filePath:Wt.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Wt.number().describe("Number of variables loaded"),project:Wt.string().describe("Doppler project name"),config:Wt.string().describe("Doppler config name"),sessionId:Wt.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:ls});import Ny from"node:fs";import My from"node:os";import jy from"node:path";var Fy="infra-kit.json",Ly="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)",Wy="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Mn=async()=>{let e;try{e=await b()}catch{return null}let r=e.trim();return r===""||r===My.homedir()?null:r},Pu=async()=>{let e=await Mn();return e===null&&l.info(Ly),e},Vy=async()=>{let e=await Mn();return e===null?null:Ny.existsSync(jy.join(e,Fy))?e:(l.info(Wy),null)};var Jy=async e=>{try{return await me(e)}catch(r){return l.debug({err:r,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Su=async()=>{let e=await Vy(),r=H.version;if(e===null)return{skipped:!0,root:null,version:r,written:[]};let t=[...await Tn(e,{version:r})];for(let n of await Jy(e)){let o=await Rn(n);t.push(...await An(n,{repoRoot:e,version:r,declaredType:o}))}return{skipped:!1,root:e,version:r,written:t}};import fe from"node:fs";import Va from"node:os";import Pe from"node:path";import Ja from"node:process";import ms from"node:fs/promises";import By from"node:path";import Gy from"node:process";var xu=` // "envManagement": { // required in layer 1; provider-tagged
179
+ `)};var qv=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),Hv=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>qv(t[1])),Yv=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Hv(t[1])},zv=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 d=i[a+1];if(c==="\\"&&(d==='"'||d==="\\")){r+=d,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},Xv=e=>{let t=e.split(`
180
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:zv(t.slice(10))},Gp=(e,t)=>{try{return e==="darwin"?Yv(t):e==="linux"?Xv(t):null}catch{return null}};import Zv from"node:fs";import Qv from"node:os";import ey from"node:path";var ty="infra-kit.json",ry="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)",ny="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",kn=async()=>{let e;try{e=await R()}catch{return null}let t=e.trim();return t===""||t===Qv.homedir()?null:t},Up=async()=>{let e=await kn();return e===null&&l.info(ry),e},oy=async()=>{let e=await kn();return e===null?null:Zv.existsSync(ey.join(e,ty))?e:(l.info(ny),null)};var sy=async e=>{try{return await de(e)}catch(t){return l.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Kp=async()=>{let e=await oy(),t=U.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await gn(e,{version:t})];for(let n of await sy(e)){let o=await dn(n);r.push(...await hn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import ce from"node:fs";import ba from"node:os";import pe from"node:path";import Ra from"node:process";import Zo from"node:fs/promises";import iy from"node:path";import ay from"node:process";var qp=` // "envManagement": { // required in layer 1; provider-tagged
191
181
  // "provider": "doppler",
192
182
  // "config": { "name": "my-doppler-project" }
193
183
  // },
@@ -196,13 +186,6 @@ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},_y=(
196
186
  // "provider": "cursor",
197
187
  // "config": { "workspaceConfigPath": "/path/to/your.code-workspace" }
198
188
  // },
199
- // // Or, for Zed (no workspace file \u2014 one window with all worktrees via "zed <root> <wt...>"):
200
- // "ide": { "provider": "zed", "config": {} },
201
- // // Or drive BOTH editors at once with an array (at most one entry per provider):
202
- // "ide": [
203
- // { "provider": "cursor", "config": { "workspaceConfigPath": "/path/to/your.code-workspace" } },
204
- // { "provider": "zed", "config": {} }
205
- // ],
206
189
  //
207
190
  // "taskManager": {
208
191
  // "provider": "jira",
@@ -220,14 +203,6 @@ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},_y=(
220
203
  // "orca": { "layout": "two-columns" }
221
204
  // },
222
205
  //
223
- // // Auto-load Doppler env when working inside this project/worktree. Omit to
224
- // // disable. "trigger" (pick one): "shell-startup" (new shells) | "cli-invocation"
225
- // // (before each infra-kit command, primes subsequent commands). "config" is the
226
- // // environment to load \u2014 must have a service token (infra-kit env-token-set) or
227
- // // auto-load quietly disables. Requires the committed infra-kit.json at the git
228
- // // repo root, and the zsh shell integration (infra-kit init + a new shell). zsh only.
229
- // "envAutoLoad": { "trigger": "shell-startup", "config": "dev" },
230
- //
231
206
  // // Per-app local-dev overrides, keyed by APP FOLDER name (the directory under
232
207
  // // apps/). Both fields optional: "port" pins the local listen port (otherwise
233
208
  // // <APP>_PORT / PORT / a built-in default), "prefixUrl" pins the URL prefix the
@@ -253,19 +228,6 @@ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},_y=(
253
228
  // }
254
229
  // },
255
230
  //
256
- // // DEPRECATED \u2014 accepted but IGNORED; safe to delete. Remove it and this note in a
257
- // // future release.
258
- // //
259
- // // The proxy port is no longer configurable. Every dev URL is now
260
- // // https://<release>.<package>.localhost with NO port, and the only port that can
261
- // // serve a port-free HTTPS URL is 443 \u2014 so a setting here could only put the port
262
- // // back into the URL. Set up the daemon once (the install is the only step needing
263
- // // root; trusting its local CA does not). Run \`infra-kit doctor\`: it checks both and
264
- // // prints each fix as a command you can paste, with the paths filled in for your
265
- // // machine. Do not type a bare \`portless\` \u2014 it lives in node_modules, not on PATH.
266
- // // infra-kit itself never elevates.
267
- // "devProxy": { "port": 443 },
268
- //
269
231
  // // May this project deploy to the delivery-shaped environments ("prod")? The LIST lives in code
270
232
  // // (lib/workflow-envs/protected-envs); this decides only whether THIS project may reach it.
271
233
  // // "disallow" \u2014 the DEFAULT when the key is absent. Filtered out of every deploy picker and
@@ -310,7 +272,7 @@ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},_y=(
310
272
  // // also fixes its modes), or by hand: both are supported, which is why the store carries no
311
273
  // // repo-identity field and no mandatory version. Pasting a token into an
312
274
  // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
313
- // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Oa=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
275
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,ma=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
314
276
  //
315
277
  // Merge chain (later layers override earlier ones at top-level keys):
316
278
  // 1. <repo>/infra-kit.json \u2014 committed project config (required)
@@ -319,8 +281,8 @@ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},_y=(
319
281
  //
320
282
  // Merge is shallow: setting a top-level key replaces that whole section from
321
283
  // layer 1. Arrays do not concatenate. Top-level keys recognized:
322
- // envManagement, ide, taskManager, worktrees, envAutoLoad, dev,
323
- // devServersPresets, devProxy, protectedEnvs, mcp (project layer only). The schema is strict \u2014 an
284
+ // envManagement, ide, taskManager, worktrees, dev, devServersPresets,
285
+ // protectedEnvs, mcp (project layer only). The schema is strict \u2014 an
324
286
  // unrecognized top-level key is a parse error, not a silently ignored one.
325
287
  //
326
288
  // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
@@ -331,16 +293,16 @@ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},_y=(
331
293
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
332
294
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
333
295
  {
334
- ${xu}
296
+ ${qp}
335
297
  }
336
- `,Da=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
298
+ `,fa=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
337
299
  //
338
300
  // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
339
301
  // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
340
302
  // top-level key set here replaces that whole section wholesale; arrays do not
341
- // concatenate. Top-level keys recognized: envManagement, ide,
342
- // taskManager, worktrees, envAutoLoad, dev, devServersPresets, devProxy,
343
- // protectedEnvs, mcp (project layer only \u2014 refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
303
+ // concatenate. Top-level keys recognized: envManagement, ide, taskManager,
304
+ // worktrees, dev, devServersPresets, protectedEnvs, mcp (project layer only \u2014
305
+ // refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
344
306
  // error, not a silently ignored one.
345
307
  //
346
308
  // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
@@ -350,9 +312,9 @@ ${xu}
350
312
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
351
313
  // override layer \u2014 it is shown here only to document the full, valid config shape.
352
314
  {
353
- ${xu}
315
+ ${qp}
354
316
  }
355
- `,Na=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
317
+ `,ga=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
356
318
  //
357
319
  // Machine-local registry the vendor commands (sync/manifest/diff) read to know
358
320
  // where your project repos live and which ones to stamp. This .example.jsonc is
@@ -363,98 +325,103 @@ ${xu}
363
325
  // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
364
326
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
365
327
  }
366
- `;var Tu=!1,Uy=e=>e.replace(/\.json$/,".example.jsonc"),Ky=async e=>{try{return await ms.readFile(e,"utf-8")}catch{return null}},Vt=async e=>{let r=e.userProject,t=Uy(r);await ms.mkdir(By.dirname(r),{recursive:!0});let n=!await G(r);n&&await ms.writeFile(r,`{}
367
- `,"utf-8");let o=Da(e.projectName),s=await Ky(t)!==o;return s&&await ms.writeFile(t,o,"utf-8"),n&&Hd(),{configPath:r,examplePath:t,createdConfig:n,refreshedExample:s}},Jt=e=>`Created ${y(e.configPath)} \u2014 see ${y(e.examplePath)} for the annotated reference.`,Ma=async()=>{if(Gy.env.INFRA_KIT_NO_SEED||Tu)return;Tu=!0;let e;try{e=await V()}catch{return}if(await G(e.main))try{let r=await Vt(e);r.createdConfig?l.info(Jt(r)):r.refreshedExample&&l.debug(`Refreshed ${y(r.examplePath)} to match the current schema.`)}catch(r){l.debug({err:r,msg:`Skipped seeding ${y(e.userProject)} (config bootstrap failed).`})}};import{spawn as qy}from"node:child_process";import Cu from"node:fs";import Bt from"node:process";import{fileURLToPath as Iu}from"node:url";var Au=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],ja=e=>{let{argv:r,env:t,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Au.some(c=>{let d=t[c];return d!=null&&d!==""})?"opt-out":r.includes("--json")?"json":n?md(o,s,i)?"local-install":null:"not-a-tty"};var Hy=e=>{qy(Bt.execPath,[e,"--parent-pid",String(Bt.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},zy=()=>Iu(new URL("./update-check.js",import.meta.url)),Yy=()=>Cu.realpathSync(Iu(new URL("./cli.js",import.meta.url))),Zy=/^[\w@./+ -]+$/i,Xy=e=>Zy.test(e),Qy=(e,r,t)=>{!e?.latestVersion||!e.updateCommand||yn(e.latestVersion,r)&&e.updateCommand.every(Xy)&&t(`infra-kit ${e.latestVersion} is available (you have ${r}). Run: ${Co(e.updateCommand)}`)},Fa=(e,r={})=>{try{let t=r.argv??Bt.argv,n=r.env??Bt.env,o=r.isTty??!!Bt.stdout.isTTY,s=r.cwd??Bt.cwd(),i=r.nowMs??Date.now(),a=r.selfRealPath??Yy(),c=r.readCache??wn,d=r.spawnChild??Hy,p=r.fileExists??(f=>Cu.existsSync(f)),u=r.notify??(f=>{l.info(f)});if(ja({argv:t,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:de})!==null)return;let m=c();if(Qy(m,e,u),!Ci(m,i))return;let v=r.childPath??zy();if(!p(v))return;d(v)}catch{}};import pe from"node:fs/promises";import Ve from"node:path";import{pathToFileURL as tw}from"node:url";import nw from"yaml";import{z as Nu}from"zod";import ew from"node:fs/promises";import La from"node:os";import Wa from"node:path";import{z as rw}from"zod";import{z as fs}from"zod";var $u="vendor.json",gs=fs.object({workspaceDir:fs.string().min(1),targets:fs.array(fs.string()).min(1)}).strict();var Gt=()=>Wa.join(La.homedir(),ld,$u),_u=e=>{if(e==="~")return La.homedir();if(e.startsWith("~/"))return Wa.join(La.homedir(),e.slice(2));if(Wa.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Ou=async()=>{let e=Gt(),r;try{r=await ew.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:
328
+ `;var Hp=!1,cy=e=>e.replace(/\.json$/,".example.jsonc"),ly=async e=>{try{return await Zo.readFile(e,"utf-8")}catch{return null}},br=async e=>{let t=e.userProject,r=cy(t);await Zo.mkdir(iy.dirname(t),{recursive:!0});let n=!await K(t);n&&await Zo.writeFile(t,`{}
329
+ `,"utf-8");let o=fa(e.projectName),s=await ly(r)!==o;return s&&await Zo.writeFile(r,o,"utf-8"),n&&jd(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Rr=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,ha=async()=>{if(ay.env.INFRA_KIT_NO_SEED||Hp)return;Hp=!0;let e;try{e=await q()}catch{return}if(await K(e.main))try{let t=await br(e);t.createdConfig?l.info(Rr(t)):t.refreshedExample&&l.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){l.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as dy}from"node:child_process";import zp from"node:fs";import Pr from"node:process";import{fileURLToPath as Xp}from"node:url";var Yp=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],va=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Yp.some(c=>{let d=r[c];return d!=null&&d!==""})?"opt-out":t.includes("--json")?"json":n?ed(o,s,i)?"local-install":null:"not-a-tty"};var py=e=>{dy(Pr.execPath,[e,"--parent-pid",String(Pr.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},uy=()=>Xp(new URL("./update-check.js",import.meta.url)),my=()=>zp.realpathSync(Xp(new URL("./cli.js",import.meta.url))),fy=/^[\w@./+ -]+$/i,gy=e=>fy.test(e),hy=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||sn(e.latestVersion,t)&&e.updateCommand.every(gy)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${bo(e.updateCommand)}`)},ya=(e,t={})=>{try{let r=t.argv??Pr.argv,n=t.env??Pr.env,o=t.isTty??!!Pr.stdout.isTTY,s=t.cwd??Pr.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??my(),c=t.readCache??an,d=t.spawnChild??py,p=t.fileExists??(y=>zp.existsSync(y)),u=t.notify??(y=>{l.info(y)});if(va({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:ie})!==null)return;let m=c();if(hy(m,e,u),!ki(m,i))return;let h=t.childPath??uy();if(!p(h))return;d(h)}catch{}};import Fe from"node:fs/promises";import je from"node:path";import{pathToFileURL as wy}from"node:url";import ky from"yaml";import{z as ru}from"zod";import vy from"node:fs/promises";import wa from"node:os";import ka from"node:path";import{z as yy}from"zod";import{z as Qo}from"zod";var Zp="vendor.json",es=Qo.object({workspaceDir:Qo.string().min(1),targets:Qo.array(Qo.string()).min(1)}).strict();var Er=()=>ka.join(wa.homedir(),zl,Zp),Qp=e=>{if(e==="~")return wa.homedir();if(e.startsWith("~/"))return ka.join(wa.homedir(),e.slice(2));if(ka.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},eu=async()=>{let e=Er(),t;try{t=await vy.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:
368
330
 
369
331
  {
370
332
  "workspaceDir": "~/projects",
371
333
  "targets": ["my-repo"]
372
334
  }
373
- `)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(o){throw new Error(`Invalid JSON in vendor.json at ${e}: ${o.message}`)}let n=gs.safeParse(t);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${rw.prettifyError(n.error)}`);return n.data};var Du=e=>e.replace(/\.json$/,".yml"),Mu=async()=>{let e;try{e=await V()}catch{return}let r=[{label:"infra-kit.json",yml:Du(e.main),json:e.main,schema:Ud},{label:"~/.infra-kit/infra-kit.json",yml:Ve.join(Ve.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ai},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Du(e.userProject),json:e.userProject,schema:Ai}],t=0;for(let n of r){let[o,s]=await Promise.all([G(n.yml),G(n.json)]);if(o){if(s){l.info(`\u26A0 Skipped ${y(n.yml)} \u2014 ${y(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await pe.readFile(n.yml,"utf-8"),a=nw.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${y(n.yml)} \u2014 invalid config: ${Nu.prettifyError(c.error)}`);continue}await pe.mkdir(Ve.dirname(n.json),{recursive:!0}),await pe.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
374
- `,"utf-8"),await pe.rm(n.yml,{force:!0}),l.info(`\u2713 Migrated ${y(n.yml)} \u2192 ${y(n.json)}`),t++}catch(i){l.info(`\u26A0 Skipped ${y(n.yml)} \u2014 ${i.message}`)}}}t>0&&Ke()},ju=async()=>{let e;try{e=await V()}catch{return}let r=Ve.dirname(e.userGlobal),t=[{from:Ve.join(r,"config.json"),to:e.userGlobal},{from:Ve.join(r,"config.example.jsonc"),to:Ve.join(r,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of t){let[i,a]=await Promise.all([G(o),G(s)]);if(i){if(a){l.info(`\u26A0 Skipped ${y(o)} \u2014 ${y(s)} already exists (remove the stale file manually)`);continue}try{await pe.mkdir(Ve.dirname(s),{recursive:!0}),await pe.rename(o,s),l.info(`\u2713 Renamed ${y(o)} \u2192 ${y(s)}`),n++}catch(c){l.info(`\u26A0 Skipped ${y(o)} \u2014 ${c.message}`)}}}n>0&&Ke()},Fu=async()=>{let e=Gt(),r=Ve.dirname(e),t=Ve.join(r,"vendor.config.ts"),[n,o]=await Promise.all([G(t),G(e)]);if(n){if(o){l.info(`\u26A0 Skipped ${y(t)} \u2014 ${y(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await pe.stat(t),c=(await import(`${tw(t).href}?mtime=${Number(s.mtimeMs)}`)).default,d=typeof c=="function",p=d?await c():c,u=gs.safeParse(p);if(!u.success){l.info(`\u26A0 Skipped ${y(t)} \u2014 invalid factory config: ${Nu.prettifyError(u.error)}`);return}await pe.mkdir(r,{recursive:!0}),await pe.writeFile(e,`${JSON.stringify(u.data,null,2)}
375
- `,"utf-8"),await pe.rm(t,{force:!0}),d?l.info(`\u26A0 Migrated ${y(t)} \u2192 ${y(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 ${y(e)} directly to change them.`):l.info(`\u2713 Migrated ${y(t)} \u2192 ${y(e)}`)}catch(s){l.info(`\u26A0 Skipped ${y(t)} \u2014 ${s.message}`)}}},ow=e=>{let r=e.ide;if(r===null||typeof r!="object")return{changed:!1,result:e};let t=!1,n=s=>{if(s===null||typeof s!="object"||!("config"in s))return s;let i=s.config;if(i===null||typeof i!="object"||!("mode"in i))return s;t=!0;let a=Object.fromEntries(Object.entries(i).filter(([c])=>c!=="mode"));return{...s,config:a}},o=Array.isArray(r)?r.map(n):n(r);return t?{changed:!0,result:{...e,ide:o}}:{changed:!1,result:e}},Lu=async()=>{let e;try{e=await V()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let n of r)if(await G(n))try{let o=await pe.readFile(n,"utf-8");if(o.trim()==="")continue;let s=JSON.parse(o),{changed:i,result:a}=ow(s);if(!i)continue;await pe.writeFile(n,`${JSON.stringify(a,null,2)}
376
- `,"utf-8"),l.info(`\u2713 Normalized ide config in ${y(n)} (removed legacy "mode")`),t++}catch(o){l.info(`\u26A0 Skipped normalizing ${y(n)} \u2014 ${o.message}`)}t>0&&Ke()},Wu=async()=>{let e=await sw(),r=0;for(let t of e)if(await G(t))try{let n=await pe.readFile(t,"utf-8");if(n.trim()==="")continue;let{changed:o,result:s}=Gd(JSON.parse(n));if(!o)continue;await pe.writeFile(t,`${JSON.stringify(s,null,2)}
377
- `,"utf-8"),l.info(`\u2713 Migrated cmux \u2192 orca keys in ${y(t)}`),r++}catch(n){l.info(`\u26A0 Skipped migrating ${y(t)} \u2014 ${n.message}`)}r>0&&Ke()},sw=async()=>{try{let e=await V();return[e.main,e.userGlobal,e.userProject]}catch{return[qd()]}};var Zr="# -- infra-kit:begin --",br="# -- infra-kit:end --",iw=[["# region infra-kit","# endregion infra-kit"]],aw="# infra-kit shell functions",Ut=class extends Error{constructor(t,n){super(n instanceof Error?n.message:String(n),{cause:n});this.step=t;this.reason=n;this.name="InitStepError"}step;reason},jn="Run `source ~/.zshrc` or open a new terminal to activate.",cw={step:"migrations",outcome:"skipped",message:"Config migrations checked (legacy yml layers, ide structure, user-global filename, cmux \u2192 orca keys, factory config)",level:"silent"},rr=async(e,r)=>{try{return await r()}catch(t){throw new Ut(e,t)}},Ba=async e=>{let r=[],t=(...s)=>{for(let i of s)r.push(i),e?.(i)};await rr("zshrc",()=>{t(lw())}),await rr("zshenv",()=>{t(dw())}),await rr("migrations",async()=>{await pw(),t(cw)}),await rr("user-config",()=>{t(mw())});let n=await rr("guidance",async()=>{let{entries:s,root:i}=await hw();return t(...s),i}),o=await rr("plugin-pointer",async()=>Pu());return t(...ww(o,n)),await rr("plugin-pointer",async()=>{await Pw(o,t)}),await rr("mcp-proxies",async()=>{t(...await xw(o))}),await rr("project-config",async()=>{t(...await fw())}),t(...uw()),r},vs=e=>{if(e.level!=="silent"){if(e.level==="warn"){l.warn(e.message);return}if(e.level==="debug"){l.debug({msg:e.message});return}l.info(e.message)}},lw=()=>{let e=Pe.join(Va.homedir(),".zshrc"),r=fe.existsSync(e)?Aw(fe.readFileSync(e,"utf-8")):"",t=Rt({content:r,body:Ju(),startMarker:Zr,endMarker:br,placement:"append-end"});return fe.writeFileSync(e,t),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},dw=()=>{let e=Pe.join(Va.homedir(),".zshenv"),r=fe.existsSync(e)?fe.readFileSync(e,"utf-8"):"",t=Rt({content:r,body:Ga(),startMarker:Zr,endMarker:br});return fe.writeFileSync(e,t),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},pw=async()=>{await Mu(),await Lu(),await ju(),await Wu(),await Fu()},uw=()=>{let e=Ja.env.SHELL??"",r=[];return e.includes("zsh")||r.push({step:"shell",outcome:"warned",message:`Your login shell ($SHELL=${e||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear/auto-load) is zsh-only and won't activate in bash/fish.`,level:"warn"}),r.push({step:"shell",outcome:"unchanged",message:jn,level:"info"}),r},mw=()=>{let e=Pe.join(Va.homedir(),".infra-kit"),r=Pe.join(e,"infra-kit.json");return fe.mkdirSync(e,{recursive:!0}),fe.writeFileSync(Pe.join(e,"infra-kit.example.jsonc"),Oa(),"utf-8"),fe.writeFileSync(Pe.join(e,"vendor.example.jsonc"),Na(),"utf-8"),fe.existsSync(r)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${r} (refreshed reference examples)`,level:"info"}:(fe.writeFileSync(r,`{}
378
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`,level:"info"})},fw=async()=>{if(Ja.env.INFRA_KIT_NO_SEED)return[hs("INFRA_KIT_NO_SEED is set")];try{let e=await V();if(!fe.existsSync(e.main))return[hs(`no project config at ${e.main}`)];let r=await Vt(e);return r.createdConfig?[{step:"project-config",outcome:"written",message:Jt(r),level:"info"}]:[hs("the user-project config was already present")]}catch(e){return l.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[hs(e instanceof Error?e.message:String(e))]}},hs=e=>({step:"project-config",outcome:"skipped",message:`Skipped seeding the user-project config \u2014 ${e}`,level:"silent"}),gw=(e,r,t)=>{let n=[];for(let s of t){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)} ${Pe.relative(e,s.path)}${i}`,level:"info"})}n.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${r})`,level:"info"});let o=t.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},hw=async()=>{let{skipped:e,root:r,version:t,written:n}=await Su();return e||r===null?{root:null,entries:[{step:"guidance",outcome:"skipped",message:"Agent-instruction files skipped \u2014 not an infra-kit repo",level:"silent"}]}:{root:r,entries:gw(r,t,n)}},vw=(e,r)=>{let t=Pe.relative(e,r.path);return r.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${t} (Claude Code plugin pointer)`,level:"info"}:r.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${t} \u2014 added ${r.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:r.status==="unchanged"?"unchanged":"warned",message:`${t} \u2014 ${r.status}`,level:"silent"}},yw=(e,r)=>{let t=Z;if(r.kind==="stale"||r.kind==="wrong-key"){let o=r.kind==="stale"?q:r.key;return{step:"mcp-server",outcome:"unchanged",message:` ${t} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a compatibility stub. Delete the "${o}" entry from ${t} by hand in a PR, keeping its siblings`,level:"info"}}return r.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${Te} from ${Pe.join(e,Z)} \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 (${r.kind==="absent"?`${t} carries no "${q}" key`:`no ${t}`})`,level:"info"}},ww=(e,r)=>e===null||r!==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 ${W} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],kw=()=>[la,Ye].map(e=>({step:"plugin-pointer",outcome:"skipped",message:e,level:"info"})),bw=e=>({step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${H.version} is behind ${e.latestVersion}, update it first: ${Co(e.updateCommand)}`:`CLI ${H.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"}),Rw=(e,r)=>e.status==="skipped-cli-stale"?[bw(r)]:e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${W} 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: ${It}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${W} (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"},...kw()]:[{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: ${Ye}`,level:"warn"}],Vu={stale:!1},Ew=async()=>{let e=wn(),r=e===null?await Ii(Ja.env):e.latestVersion;return r===null||!$i(r,H.version)?Vu:{stale:!0,latestVersion:r,updateCommand:e?.updateCommand??ud(r)}},Pw=async(e,r)=>{if(e===null){r({step:"plugin-pointer",outcome:"skipped",message:"Claude Code plugin steps skipped \u2014 no git root safe to write into",level:"silent"});return}try{r(vw(e,da(Pe.join(e,".claude","settings.json"))));let n=Fr({projectPath:e}).kind==="installed"?await Ew():Vu;r(...Rw(oa({projectRoot:e,cliIsStale:()=>n.stale}),n)),r(yw(e,Gr(e)))}catch(t){let n=t instanceof Error?t.message:String(t);r({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${Ye}`,level:"warn"})}},Sw=(e,r)=>{let t=Pe.relative(e,r.path);if(r.status!=="ok"&&r.status!=="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${t} could not be read as JSON \u2014 ik-mcp entries not synced`,level:"warn"}];if(r.status==="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${t} could not be written \u2014 ik-mcp entries not synced`,level:"warn"}];let n=[];for(let o of r.entries)o.status==="written"?n.push({step:"mcp-proxies",outcome:"written",message:` updated ${t} \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},xw=async e=>{if(e===null)return[];if(!fe.existsSync(Pe.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 r;try{r=(await P()).mcp}catch(t){let n=t instanceof Error?t.message:String(t);return[{step:"mcp-proxies",outcome:"skipped",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
379
- `)[0]??n})`,level:"warn"}]}return!r||Object.keys(r).length===0?[]:Sw(e,Qo({projectRoot:e,proxies:r,write:!0}))},Tw=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("export _INFRA_KIT_")||e.startsWith(": ${_INFRA_KIT_")||e.startsWith("fi")||e.startsWith("zmodload ")||e.startsWith("autoload ")||e.startsWith("add-zsh-hook ")||e.startsWith("_infra_kit_autoload"),Aw=e=>{let r=yr(e,Zr,br);if(r!==null)return r;for(let[a,c]of iw){let d=yr(e,a,c);if(d!==null)return d}let t=e.indexOf(aw);if(t===-1)return e;let n=e.slice(0,t).replace(/\n+$/,""),o=e.slice(t).split(`
380
- `),s=0;for(;s<o.length&&Tw(o[s]);)s++;let i=o.slice(s).join(`
335
+ `)}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=es.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${yy.prettifyError(n.error)}`);return n.data};var tu=e=>e.replace(/\.json$/,".yml"),nu=async()=>{let e;try{e=await q()}catch{return}let t=[{label:"infra-kit.json",yml:tu(e.main),json:e.main,schema:Nd},{label:"~/.infra-kit/infra-kit.json",yml:je.join(je.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:wi},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:tu(e.userProject),json:e.userProject,schema:wi}],r=0;for(let n of t){let[o,s]=await Promise.all([K(n.yml),K(n.json)]);if(o){if(s){l.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${w(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await Fe.readFile(n.yml,"utf-8"),a=ky.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${w(n.yml)} \u2014 invalid config: ${ru.prettifyError(c.error)}`);continue}await Fe.mkdir(je.dirname(n.json),{recursive:!0}),await Fe.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
336
+ `,"utf-8"),await Fe.rm(n.yml,{force:!0}),l.info(`\u2713 Migrated ${w(n.yml)} \u2192 ${w(n.json)}`),r++}catch(i){l.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${i.message}`)}}}r>0&&lt()},ou=async()=>{let e;try{e=await q()}catch{return}let t=je.dirname(e.userGlobal),r=[{from:je.join(t,"config.json"),to:e.userGlobal},{from:je.join(t,"config.example.jsonc"),to:je.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([K(o),K(s)]);if(i){if(a){l.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await Fe.mkdir(je.dirname(s),{recursive:!0}),await Fe.rename(o,s),l.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){l.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&lt()},su=async()=>{let e=Er(),t=je.dirname(e),r=je.join(t,"vendor.config.ts"),[n,o]=await Promise.all([K(r),K(e)]);if(n){if(o){l.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await Fe.stat(r),c=(await import(`${wy(r).href}?mtime=${Number(s.mtimeMs)}`)).default,d=typeof c=="function",p=d?await c():c,u=es.safeParse(p);if(!u.success){l.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${ru.prettifyError(u.error)}`);return}await Fe.mkdir(t,{recursive:!0}),await Fe.writeFile(e,`${JSON.stringify(u.data,null,2)}
337
+ `,"utf-8"),await Fe.rm(r,{force:!0}),d?l.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.`):l.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){l.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},iu=async()=>{let e=await by(),t=0;for(let r of e)if(await K(r))try{let n=await Od(r);if(!n.changed)continue;l.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof Dd?"changed while migrating":n.message;l.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&lt()},by=async()=>{try{let e=await q();return[e.main,e.userGlobal,e.userProject]}catch{return[Md()]}};var $t="# -- infra-kit:begin --",ut="# -- infra-kit:end --",Ry=[["# region infra-kit","# endregion infra-kit"]],Py="# infra-kit shell functions",Sr=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},bn="Run `source ~/.zshrc` or open a new terminal to activate.",Ey={step:"migrations",outcome:"skipped",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},qe=async(e,t)=>{try{return await t()}catch(r){throw new Sr(e,r)}},Pa=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await qe("zshrc",()=>{r(Sy())}),await qe("zshenv",()=>{r(xy())}),await qe("migrations",async()=>{await Cy(),Ty(),r(Ey)}),await qe("user-config",()=>{r($y())});let n=await qe("guidance",async()=>{let{entries:s,root:i}=await Oy();return r(...s),i}),o=await qe("plugin-pointer",async()=>Up());return r(...My(o,n)),await qe("plugin-pointer",async()=>{await Vy(o,r)}),await qe("mcp-proxies",async()=>{r(...await Wy(o))}),await qe("project-config",async()=>{r(...await Iy())}),r(...Ay()),t},rs=e=>{if(e.level!=="silent"){if(e.level==="warn"){l.warn(e.message);return}if(e.level==="debug"){l.debug({msg:e.message});return}l.info(e.message)}},Sy=()=>{let e=pe.join(ba.homedir(),".zshrc"),t=ce.existsSync(e)?Uy(ce.readFileSync(e,"utf-8")):"",r=dr({content:t,body:cu(),startMarker:$t,endMarker:ut,placement:"append-end"});return ce.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},xy=()=>{let e=pe.join(ba.homedir(),".zshenv"),t=ce.existsSync(e)?ce.readFileSync(e,"utf-8"):"",r=dr({content:t,body:Ea(),startMarker:$t,endMarker:ut});return ce.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},Ty=()=>{ce.rmSync(pe.join(Xl(),"projects"),{recursive:!0,force:!0})},Cy=async()=>{await nu(),await ou(),await iu(),await su()},Ay=()=>{let e=Ra.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:bn,level:"info"}),t},$y=()=>{let e=pe.join(ba.homedir(),".infra-kit"),t=pe.join(e,"infra-kit.json");return ce.mkdirSync(e,{recursive:!0}),ce.writeFileSync(pe.join(e,"infra-kit.example.jsonc"),ma(),"utf-8"),ce.writeFileSync(pe.join(e,"vendor.example.jsonc"),ga(),"utf-8"),ce.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ce.writeFileSync(t,`{}
338
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},Iy=async()=>{if(Ra.env.INFRA_KIT_NO_SEED)return[ts("INFRA_KIT_NO_SEED is set")];try{let e=await q();if(!ce.existsSync(e.main))return[ts(`no project config at ${e.main}`)];let t=await br(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:Rr(t),level:"info"}]:[ts("the user-project config was already present")]}catch(e){return l.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[ts(e instanceof Error?e.message:String(e))]}},ts=e=>({step:"project-config",outcome:"skipped",message:`Skipped seeding the user-project config \u2014 ${e}`,level:"silent"}),Dy=(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)} ${pe.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},Oy=async()=>{let{skipped:e,root:t,version:r,written:n}=await Kp();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:Dy(t,r,n)}},Ny=(e,t)=>{let r=pe.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"}},_y=(e,t)=>{let r=z;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?G: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 ${Se} from ${pe.join(e,z)} \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 "${G}" key`:`no ${r}`})`,level:"info"}},My=(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 ${J} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],jy=()=>[ea,Ke].map(e=>({step:"plugin-pointer",outcome:"skipped",message:e,level:"info"})),Fy=e=>({step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${U.version} is behind ${e.latestVersion}, update it first: ${bo(e.updateCommand)}`:`CLI ${U.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"}),Ly=(e,t)=>e.status==="skipped-cli-stale"?[Fy(t)]:e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${J} 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: ${yr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${J} (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"},...jy()]:[{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: ${Ke}`,level:"warn"}],au={stale:!1},Jy=async()=>{let e=an(),t=e===null?await bi(Ra.env):e.latestVersion;return t===null||!Ri(t,U.version)?au:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Ql(t)}},Vy=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(Ny(e,ta(pe.join(e,".claude","settings.json"))));let n=Pt({projectPath:e}).kind==="installed"?await Jy():au;t(...Ly(Yi({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(_y(e,At(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: ${Ke}`,level:"warn"})}},By=(e,t)=>{let r=pe.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},Wy=async e=>{if(e===null)return[];if(!ce.existsSync(pe.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 $()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"skipped",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
339
+ `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:By(e,Ko({projectRoot:e,proxies:t,write:!0}))},Gy=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"),Uy=e=>{let t=pt(e,$t,ut);if(t!==null)return t;for(let[a,c]of Ry){let d=pt(e,a,c);if(d!==null)return d}let r=e.indexOf(Py);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
340
+ `),s=0;for(;s<o.length&&Gy(o[s]);)s++;let i=o.slice(s).join(`
381
341
  `);return n+(i?`
382
- ${i}`:"")},Ju=()=>{let e="pnpm exec infra-kit";return["zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null","zmodload zsh/sched 2>/dev/null",'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",": ${_INFRA_KIT_LAST_LOAD_MTIME:=0}",": ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}",": ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}",": ${_INFRA_KIT_WARM_TTL:=7200}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED _INFRA_KIT_WARM_TTL",`env-load() { local f m; f=$(${e} env-load "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source "$f"; ${e} env-status; }`,`env-clear() { local f m; f=$(${e} env-clear "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`,"_infra_kit_notify() {"," zle && print -u2 -n $'\\r\\e[K'",' print -u2 -- "$1"'," zle && zle reset-prompt","}","_infra_kit_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local dir="$cache_root/$INFRA_KIT_SESSION"',' local load_file="$dir/env-load.sh"',' local clear_file="$dir/env-clear.sh"'," local load_mtime=0 clear_mtime=0",' [[ -f "$load_file" ]] && load_mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)',' [[ -f "$clear_file" ]] && clear_mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( load_mtime > _INFRA_KIT_LAST_LOAD_MTIME && load_mtime >= _INFRA_KIT_SHELL_STARTED && load_mtime >= clear_mtime )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$load_mtime",' _infra_kit_notify "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," if (( clear_mtime > _INFRA_KIT_LAST_CLEAR_MTIME && clear_mtime >= _INFRA_KIT_SHELL_STARTED && clear_mtime > load_mtime )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$clear_mtime",' _infra_kit_notify "infra-kit: auto-cleared env"'," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi","_INFRA_KIT_AUTOLOAD_WINDOW=6","export _INFRA_KIT_AUTOLOAD_WINDOW","_infra_kit_poll_autoload() {"," _infra_kit_autoload"," if (( _INFRA_KIT_LAST_LOAD_MTIME < _INFRA_KIT_SHELL_STARTED )) && (( ${EPOCHSECONDS:-0} - _INFRA_KIT_SHELL_STARTED < _INFRA_KIT_AUTOLOAD_WINDOW )); then"," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," fi","}","_infra_kit_warm_source() {",' local canon="$1" key'," if (( $+commands[shasum] )); then",' key=$(printf %s "$canon" | shasum -a 256 | cut -c1-64)'," elif (( $+commands[sha256sum] )); then",' key=$(printf %s "$canon" | sha256sum | cut -c1-64)'," else"," return"," fi",' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local warm="$cache_root/projects/$key/env-load.sh"',' local wclear="$cache_root/projects/$key/env-clear.sh"',' [[ -f "$warm" ]] || return'," local wm=0 cm=0",' wm=$(zstat +mtime -- "$warm" 2>/dev/null || echo 0)',' [[ -f "$wclear" ]] && cm=$(zstat +mtime -- "$wclear" 2>/dev/null || echo 0)'," (( cm >= wm )) && return"," (( ${EPOCHSECONDS:-0} - wm >= _INFRA_KIT_WARM_TTL )) && return",' source "$warm"',' _infra_kit_notify "infra-kit: loaded cached vars for ${INFRA_KIT_ENV_CONFIG:-?} (refreshing\u2026)"',"}","_infra_kit_startup_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local dir="$PWD" prev=""',' while [[ -n "$dir" && "$dir" != "$prev" ]]; do',' if [[ -f "$dir/infra-kit.json" ]]; then',' [[ -n "$INFRA_KIT_ENV_CONFIG" && "$dir" == "$INFRA_KIT_ENV_PROJECT_ROOT" ]] && return',' local canon="${dir:A}"',' _infra_kit_warm_source "$canon"',` ( ${e} env-autoload --project-dir "$canon" & ) >/dev/null 2>&1`," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," return"," fi",' prev="$dir"',' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
383
- `)},Bu=()=>`${Zr}
384
- ${Ju()}
385
- ${br}`,Ga=()=>["# 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, as the","# .zshrc precmd gate does. 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(`
386
- `),Ua=()=>`${Zr}
387
- ${Ga()}
388
- ${br}`;import Cw from"node:fs/promises";var Fn=async(e,r)=>{if(!r)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let t=await Cw.readFile(e,"utf-8"),n=t.trim()===""?{}:JSON.parse(t);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}}},Ln=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import $w from"node:fs";import _w from"node:os";import Gu from"node:path";import Ow from"node:process";import{$ as Iw}from"zx";var Xr=()=>Iw({quiet:!0});var Dw=()=>[Gu.join(_w.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],Nw=async e=>{try{return(await Xr()`command -v ${e}`).stdout.trim()||null}catch{return null}},Wn=()=>({runCommand:async e=>{let r=await Xr()`${e}`;return{stdout:`${r.stdout}
389
- ${r.stderr}`}},resolveBinPath:async e=>{let r=await Nw(e);return r!==null?r:Dw().map(t=>Gu.join(t,e)).find(t=>$w.existsSync(t))??null},realpath:de,platform:Ow.platform});var Qr=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Jn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,Bn=["darwin","linux"],qa=e=>r=>yi(r,e)?"homebrew":"unknown",ks=(e,r)=>t=>t===null?null:r(e(t),t),Hu=e=>ks(qa(e.kegName),r=>r==="homebrew"?Qr(["brew","upgrade",e.brewFormula]):null),Uu=e=>Ao(e,"Homebrew")||Ao(e,"homebrew")?"homebrew":"unknown",Mw={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Jn,platforms:Bn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Uu,updateFor:ks(Uu,e=>e==="homebrew"?Qr(["brew","update"]):null)},Ka={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},zu="https://awscli.amazonaws.com/v2/install.sh",Yu={steps:[["/bin/bash","-c",`curl -fsSL ${zu} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},jw="/usr/local/aws-cli",Fw=e=>mn(jw,e,de)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${zu} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Yu,Ku=e=>yi(e,Ka.kegName)?"homebrew":Ao(e,"aws-cli")?"script":"unknown",Lw={id:"aws",binName:"aws",...Ka,probeArgv:["aws","--version"],versionFrom:Jn,platforms:Bn,prerequisites:[],bootstrapInstall:Yu,identify:Ku,updateFor:ks(Ku,(e,r)=>e==="homebrew"?Qr(["brew","upgrade",Ka.brewFormula]):e==="script"?Fw(r):null)},ys={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},Ww={id:"gh",binName:"gh",...ys,probeArgv:["gh","--version"],versionFrom:Jn,platforms:Bn,prerequisites:["brew"],bootstrapInstall:Qr(["brew","install",ys.brewInstallSpec]),identify:qa(ys.kegName),updateFor:Hu(ys)},ws={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},Vw={id:"doppler",binName:"doppler",...ws,probeArgv:["doppler","--version"],versionFrom:Jn,platforms:Bn,prerequisites:["brew"],bootstrapInstall:Qr(["brew","install","gnupg"],["brew","install",ws.brewInstallSpec]),identify:qa(ws.kegName),updateFor:Hu(ws)},Vn="portless",qu=e=>pd(e,Vn)===null?"unknown":"npm",Jw={id:"portless",binName:Vn,npmPackage:Vn,probeArgv:["portless","--version"],versionFrom:Jn,platforms:[...Bn,"win32"],prerequisites:[],bootstrapInstall:Qr(["npm","install","-g",Vn]),identify:qu,updateFor:ks(qu,e=>e==="npm"?Qr(["npm","install","-g",`${Vn}@latest`]):null)},Ha={brew:Mw,aws:Lw,gh:Ww,doppler:Vw,portless:Jw},et=Object.keys(Ha),Ce=e=>Ha[e],za=(e,r)=>e.platforms.includes(r),Ya=e=>{let r=[],t=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!t.has(o)){t.add(o);for(let i of Ce(o).prerequisites)n(i,[...s,o]);r.push(o)}};for(let o of e)n(o,[]);return r};var Zu=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Xu=async(e,r)=>{try{return await e(r)}catch{return null}},Bw=async(e,r)=>{try{let t=await e.resolveBinPath(r);return t==null?null:e.realpath(t)}catch{return null}},Qu=async(e,r)=>{if(!za(e,r.platform))return Zu(e.id);let t=await Xu(r.runCommand,e.probeArgv),n=await Bw(r,e.binName);if(t==null&&n==null)return Zu(e.id);let o=t??(n==null?null:await Xu(r.runCommand,[n,...e.probeArgv.slice(1)]));return{id:e.id,present:!0,onPath:t!=null,binRealPath:n,version:o==null?null:e.versionFrom(o.stdout),manager:n==null?"unknown":e.identify(n)}},Gn=async(e,r)=>Promise.all(e.map(t=>Qu(Ce(t),r)));import{$ as Zw}from"zx";import Kn from"node:process";var Gw="x-seraph-loginreason",Uw="AUTHENTICATED_FAILED",Kw=(e,r=160)=>{let t=e.split(`
390
- `,1)[0].trim();return t.length>r?`${t.slice(0,r)}\u2026`:t},rm=(e,r)=>r===Uw||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",em=(e,r)=>e==="auth"?`Jira rejected the credentials (HTTP ${r}) \u2014 check JIRA_EMAIL and JIRA_TOKEN; Atlassian API tokens expire`:e==="forbidden"?`Jira authenticated the account but refused the operation (HTTP ${r}) \u2014 the account lacks permission on this project`:e==="not-found-or-forbidden"?`Jira returned HTTP ${r}: 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 ${r}`,Kt=class extends Error{status;kind;body;context;constructor(r){let t=rm(r.status,r.seraphLoginReason),n=Kw(r.body);super(n===""?`${r.context}: ${em(t,r.status)}`:`${r.context}: ${em(t,r.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=r.status,this.kind=t,this.body=r.body,this.context=r.context}},Un=e=>e instanceof Kt,tm=e=>e.headers.get(Gw);var qt=async(e,r)=>{if(e.ok)return;let t=await e.text(),n=new Kt({status:e.status,seraphLoginReason:tm(e),body:t,context:r});throw l.debug({status:e.status,kind:n.kind,body:t},r),n},Rr=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,Za=async(e,r)=>{let{baseUrl:t,token:n,email:o,projectId:s}=r,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1},a=`${t}/rest/api/3/version`,c=btoa(`${o}:${n}`),d=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await qt(d,"Failed to create Jira version"),{success:!0,version:await d.json()}},Ht=async e=>{let{baseUrl:r,token:t,email:n,projectId:o}=e,s=`${r}/rest/api/3/project/${o}/versions`,i=btoa(`${n}:${t}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await qt(a,"Failed to get Jira project versions"),await a.json()},tr=async(e,r)=>(await Ht(r)).find(o=>o.name===e)||null,zt=async(e,r)=>{let{baseUrl:t,token:n,email:o}=r,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=`${t}/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)});return await qt(c,"Failed to update Jira version"),{success:!0,version:await c.json()}},Xa=async(e,r)=>{let{versionName:t}=e,n=await tr(t,r);if(!n)throw new Error(`Version "${t}" not found in Jira project`);return await zt({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)},Yt=async()=>{let e=Kn.env.JIRA_BASE_URL,r=Kn.env.JIRA_TOKEN||Kn.env.JIRA_API_TOKEN,t=Kn.env.JIRA_PROJECT_ID,n=Kn.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||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(`
391
- `);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:n}},nr=async()=>{try{return await Yt()}catch(e){return l.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var bs=async(e,r)=>{let{baseUrl:t,token:n,email:o}=r,s=`${t}/rest/api/3/version/${e}/relatedIssueCounts`,i=btoa(`${o}:${n}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});await qt(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Qa=async(e,r)=>{let{baseUrl:t,token:n,email:o}=r,s={};e.moveFixIssuesTo!==void 0&&(s.moveFixIssuesTo=e.moveFixIssuesTo),e.moveAffectedIssuesTo!==void 0&&(s.moveAffectedIssuesTo=e.moveAffectedIssuesTo);let i=`${t}/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 qt(c,"Failed to remove Jira version")};var Er=e=>e.slice(1).split(".").map(Number),Zt=e=>[...e].sort((r,t)=>{let[n,o,s]=Er(r),[i,a,c]=Er(t);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var om="next",qw=/^v?(\d+)\.(\d+)\.(\d+)$/,Hw=e=>e.replace(/^.*release\//,""),rc=e=>{let r=Hw(e.trim()),t=qw.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},nm=e=>`${e[0]}.${e[1]}.${e[2]}`,tc=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],n=new Set;for(let o of r){let s=rc(o);if(!s)continue;let i=nm(s);n.has(i)||(n.add(i),t.push(s))}return Zt(t.map(o=>nm(o))).map(o=>Er(`v${o}`))},rt=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},nc=(e,r)=>{if(e.length===0)throw new rt;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,a=e.reduce((c,d)=>d[0]===s&&d[1]===i?Math.max(c,d[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=t;return`${n}.${o+1}.0`},Xt=(e,r)=>{try{return nc(e,r)}catch(t){if(t instanceof rt)return null;throw t}},oc=e=>e.trim().toLowerCase()===om,Rs=e=>oc(e)||rc(e)!==null?{version:e}:{name:e},zw=e=>e==="regular"||e==="hotfix",sm=e=>"name"in e,sc=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":"),n=r,o="regular",s="";if(t!==-1){n=r.slice(0,t).trim();let a=r.slice(t+1),c=a.indexOf(":"),d=c===-1?a.trim():a.slice(0,c).trim();s=c===-1?"":a.slice(c+1).trim();let p=d.toLowerCase();if(!zw(p))throw new Error(`Invalid release type "${d}". Expected "regular" or "hotfix".`);o=p}let i={...Rs(n),type:o};return s!==""&&(i.description=s),i},ic=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},ec=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Yw=e=>{let r=e.name.trim();return _o(r),ec({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},ac=(e,r)=>{let t=[...r];return e.map(n=>{if(sm(n))return Yw(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(oc(o)){let a=nc(t,n.type);return t.push(Er(`v${a}`)),ec({id:xe(a),type:n.type},n.description)}let s=rc(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 t.push(s),ec({id:xe(i),type:n.type},n.description)})},cc=e=>e.some(r=>!sm(r)&&oc(r.version));var Xw=e=>e.split(`
392
- `).map(r=>{let t=r.indexOf(" ");return t===-1?null:L(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Qw=async()=>{let e=await Zw({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return Xw(e.stdout)},ek=async()=>{let e=await nr();return e?(await Ht(e)).map(t=>t.name):[]},qn=async()=>{let[e,r]=await Promise.allSettled([Qw(),ek()]);return e.status==="rejected"&&l.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&l.warn({err:r.reason},"Failed to fetch Jira versions; continuing without them"),tc({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};import rk from"node:fs";import tk from"node:path";var lc=[".claude/settings.json",".claude/settings.local.json"],nk=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],ok=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),sk=e=>{let r=e.trim();if(r==="Bash")return"*";let t=/^Bash\((.*)\)$/s.exec(r);if(t===null)return null;let n=t[1]??"";return n.endsWith(":*")?`${n.slice(0,-2)}*`:n},ik=(e,r)=>{let t=e.indexOf("*");if(t===-1)return e===r||e.startsWith(`${r} `);let n=e.slice(0,t);return new RegExp(`^${e.split("*").map(ok).join(".*")}$`,"s").test(r)||n===r||n.startsWith(`${r} `)},ak=e=>{let r=e.groupPath.join(" ");return r===e.cliName?[r]:[r,e.cliName]},ck=()=>tt.filter(e=>e.mutating),lk=e=>{let r=sk(e);return r===null?[]:ck().filter(t=>nk.some(n=>ak(t).some(o=>ik(r,`${n} ${o}`)))).map(t=>t.groupPath.join(" "))},dk=(e,r)=>{let t;try{t=rk.readFileSync(tk.join(e,r),"utf-8")}catch(i){return i.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",file:r}}let n;try{n=JSON.parse(t)}catch{return{kind:"unreadable",file:r}}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:r}},im=e=>{let r={present:[],unreadable:[],hits:[]};for(let t of lc){let n=dk(e,t);if(n.kind!=="absent"){if(r.present.push(t),n.kind==="unreadable"){r.unreadable.push(t);continue}for(let o of n.patterns){let s=lk(o);s.length>0&&r.hits.push({file:t,pattern:o,commands:s})}}}return r};var uk=["brew","gh","doppler","aws"],mk=async e=>{let r=await Gn(uk,e);return new Map(r.map(t=>[t.id,{manager:t.manager,version:t.version,present:t.present,onPath:t.onPath}]))},Pr=async(e,r,t,n)=>{try{return await Xr()`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:n}}},fk=async()=>{let e="orca installed",r=await bt();return r==="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"}:r==="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)"}},hm=(e,r,t,n)=>{let o=Q.join(gm.homedir(),r),s="Run: infra-kit setup --skip-tools";if(!F.existsSync(o))return{name:e,status:"fail",message:`~/${r} not found. ${s}`};let i=F.readFileSync(o,"utf-8"),a=i.indexOf(Zr),c=i.indexOf(br);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${t} block missing from ~/${r}. ${s}`}:i.slice(a,c+br.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${t} block in ~/${r} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${t} block in ~/${r} is up to date`}},gk=()=>hm("zshrc init block",".zshrc","shell",Bu()),hk=()=>hm("zshenv session block",".zshenv","session-env",Ua()),vk=async()=>{let e="warm cache",r;try{r=await b()}catch{return{name:e,status:"pass",message:"warm cache: not a git project"}}let t=er(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let n=Q.join(Mr(t),te);if(!F.existsSync(n))return{name:e,status:"pass",message:"warm cache: none yet (populated on next auto-load)"};let o=Math.floor((Date.now()-F.statSync(n).mtimeMs)/1e3),s=Math.floor(o/60),i=Math.floor(un/60);return o>=un?{name:e,status:"pass",message:`warm cache: present but stale (${s}m old, TTL ${i}m) \u2014 will refresh`}:{name:e,status:"pass",message:`warm cache: present, ${s}m old`}},yk=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await b(),t=Q.join(r,"pnpm-workspace.yaml");if(!F.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let n=F.readFileSync(t,"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(r){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${r.message}`}}},wk=async()=>{let e=await V(),r=[];for(let t of[e.main,e.userGlobal,e.userProject])if(F.existsSync(t))try{let{stripped:n}=Bd(JSON.parse(F.readFileSync(t,"utf8")));n.length>0&&r.push({file:t,paths:n})}catch{}return r},kk=async()=>{try{return Ke(),{config:await P(),error:null,legacyCmuxKeys:await wk()}}catch(e){return{config:null,error:e,legacyCmuxKeys:[]}}},bk=e=>{let r="infra-kit config valid";if(e.error)return{name:r,status:"fail",message:e.error.message};if(e.legacyCmuxKeys.length>0){let t=e.legacyCmuxKeys.map(({file:n,paths:o})=>`${o.join(", ")} in ${y(n)}`).join("; ");return{name:r,status:"warn",message:`legacy cmux keys are ignored (${t}) \u2014 run \`infra-kit setup\` to migrate them to orca`}}return{name:r,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}},Rk=384,dc=448,Ek=e=>e.map(r=>{let t=r.source===null?"no token":`token (${r.source})`;return`${r.env}: ${t}`}).join(", "),Pk=async(e,r)=>Promise.all(e.map(async t=>{try{let{source:n}=await r(t);return{env:t,source:n}}catch{return{env:t,source:null}}})),Sk=async(e,r={})=>{let t="env tokens configured",n=r.readStore??oe,o=r.resolveToken??Dt;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let s;try{s=await n()}catch(m){return{name:t,status:"fail",message:`Token store unreadable \u2014 ${m.message}`}}let i=await Hr(),a=e.config.envAutoLoad?.config,c=a&&!i.includes(a)?[...i,a]:i,d=await Pk(c,o),p=Ek(d);if(a===void 0)return{name:t,status:"pass",message:`No envAutoLoad configured \u2014 no env is load-bearing. ${p}`};let u=d.find(m=>m.env===a);return!u||u.source===null?s===null||Object.keys(s.envs).length===0?{name:t,status:"pass",message:"Skipped \u2014 there is no token store to read (see tokens.json present)"}:{name:t,status:"fail",message:`No Doppler service token for the auto-load env "${a}" \u2014 your shell env will not load. Fix: run \`infra-kit env-token-set ${a}\`. ${p}`}:{name:t,status:"pass",message:`auto-load env "${a}": token (${u.source}). ${p}`}},xk={valid:{status:"pass",describe:"live and correctly scoped"},revoked:{status:"fail",describe:"REJECTED by Doppler (revoked or invalid)"},"mis-scoped":{status:"fail",describe:"live but scoped to a DIFFERENT config"},unreachable:{status:"pass",describe:"could not be checked (Doppler unreachable)"}},Tk=async(e,r={})=>{let t="env token valid",n=r.resolveToken??Dt,o=r.probe??_n;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let s=e.config.envAutoLoad?.config;if(s===void 0)return{name:t,status:"pass",message:"Skipped \u2014 no envAutoLoad env to probe"};let i;try{i=(await n(s)).token}catch{return{name:t,status:"pass",message:`Skipped \u2014 no token for env "${s}" (see env tokens configured)`}}let a=e.config.envManagement.config.name,c=await o({childEnv:kr(i),project:a,config:s}),d=xk[c.outcome],p=c.outcome==="revoked"||c.outcome==="mis-scoped"?` Fix: run \`infra-kit env-token-set ${s}\` with a token scoped to "${s}".`:"";return{name:t,status:d.status,message:`The token for env "${s}" (project "${a}") is ${d.describe}.${p}`}},Ak=()=>Sr.env[X]||void 0,Ck=async(e={})=>{let r="tokens.json present",t=e.readStore??oe,n=e.storePath??qe;if((e.readEnvToken??Ak)())return{name:r,status:"pass",message:`Skipped \u2014 ${X} is set; that channel takes precedence over the store`};let s;try{s=y(await n())}catch{return{name:r,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}let i;try{i=await t()}catch{return{name:r,status:"pass",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:r,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${X} instead.`}}return{name:r,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Hn=(e,r)=>{let t=r(e);return t===null?null:t.mode&511},Ik=async(e,r={})=>{let t="tokens.json perms",n=r.storePath??qe,o=r.statPath??$k,s=r.chmodPath??F.chmodSync,i;try{i=await n()}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(Hn(i,o)===null)return{name:t,status:"pass",message:`No store to protect at ${y(i)} (see tokens.json present)`};let a=Q.dirname(i),c=Q.dirname(a),d=Q.dirname(c),u=[{target:d,expected:dc,actual:Hn(d,o)},{target:c,expected:dc,actual:Hn(c,o)},{target:a,expected:dc,actual:Hn(a,o)},{target:i,expected:Rk,actual:Hn(i,o)}].filter(v=>v.actual!==null&&v.actual!==v.expected);if(u.length===0)return{name:t,status:"pass",message:`${y(i)} is 0600 (0700 dirs)`};let m=u.map(v=>`${y(v.target)} is ${am(v.actual)}, expected ${am(v.expected)}`).join("; ");if(!e)return{name:t,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let v of u)s(v.target,v.expected);return{name:t,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},am=e=>`0${e.toString(8).padStart(3,"0")}`,$k=e=>{try{return F.statSync(e)}catch{return null}},_k=async()=>{let e="user override path";try{let r=await V(),t=F.existsSync(r.userProject),n=await Fn(r.userProject,t),o=t?Ln(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${y(r.userProject)} ${o} \u2014 project: ${r.projectName}`}}catch(r){return{name:e,status:"fail",message:r.message}}},Ok=async()=>{let e="legacy user-global config",r;try{r=await V()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=Q.join(Q.dirname(r.userGlobal),"config.json");return F.existsSync(t)?F.existsSync(r.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${y(t)} \u2014 ${y(r.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${y(t)} \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"}},Dk={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"},zed:{command:["zed","--version"],label:"Zed",failMsg:"Zed is not installed. Install from: https://zed.dev/"}},Nk=async e=>{let r=Dk[e];try{return await Xr()`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},Mk=async e=>{let r="ide installed";if(!e.config)return{name:r,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let t=hr(e.config).map(s=>s.provider);if(t.length===0)return{name:r,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(t.map(s=>Nk(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:r,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:r,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},cm=/^\d+\.\d+\.\d+$/,jk=(e,r)=>e===r||!cm.test(e)||!cm.test(r)?!1:Zt([`v${e}`,`v${r}`])[0]===`v${e}`,Fk=async(e,r)=>{let t;try{t=await me(e)}catch{return[]}let n=[];for(let o of t){let s=Wr(Vr(Q.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&jk(s.version,r)&&n.push(s.version)}return n},Lk=async(e,r)=>{let t=await Fk(e,r);if(t.length===0)return"";let n=Zt(t.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${t.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${r}) \u2014 run: infra-kit audit --fix --all`},Wk=async()=>{let e;try{e=(await V()).main}catch{return[]}if(!F.existsSync(e))return[];let r=Q.dirname(e),t=Q.join(r,"CLAUDE.md"),n=F.existsSync(t)?F.readFileSync(t,"utf-8"):"",o=Fe(n,be,Le),s=o?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",i=await Lk(r,H.version);return[{name:"CLAUDE.md block",status:o?"pass":"fail",message:`${s}${i}`}]},Vk=async()=>{try{let e=(await V()).main;return F.existsSync(e)?Q.dirname(e):null}catch{return null}},Jk=e=>{let r=Jd();return r===null||!yn(r,e)?"":` \u2014 plugin ${r} is fetched but not applied. Run: ${It}`},Bk=e=>{let r=e.kind==="installed"?Lo(e.installation):null;return{name:"plugin version",status:r===null?"fail":"pass",message:r===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${W} version ${r}${Jk(r)}`}},lm=3,dm=(e,r)=>de(e)===de(r),Gk=e=>{if(e===void 0||e.gitRoot===null)return"";let r=y(e.gitRoot);if(e.projectDir!==null){if(dm(e.projectDir,e.gitRoot))return"";let t=mn(e.gitRoot,de(e.projectDir),de)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${y(e.projectDir)}, ${t}: the plugin and this repo's .claude/settings.json hooks load only from ${r} (measured); restart Claude Code there`}return dm(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${y(e.cwd)} rather than ${r}, it loaded neither the plugin nor this repo's hooks; launch it at ${r}`},Uk=(e,r)=>{let t="plugin installed",n=Gk(r);if(e.kind==="installed"){let{scope:c,projectPath:d}=e.installation,p=d===null?"":`, ${y(d)}`;return{name:t,status:"pass",message:`Plugin ${W} installed (${c??"unknown"} scope${p})${n}`}}if(e.kind==="absent")return{name:t,status:"fail",message:`Plugin ${W} is not installed. Run: ${Ye}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":y(c.projectPath)),s=o.length-lm,i=s>0?` and ${s} more`:"",a=`${o.slice(0,lm).join(", ")}${i}`;return{name:t,status:"fail",message:`Plugin ${W} is installed for ${a} only, not this project. Run: ${Ye}${n}`}},Kk=()=>Pr("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),qk=(e,...r)=>{try{return JSON.parse(F.readFileSync(Q.join(e,...r),"utf-8"))}catch{return null}},Hk=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let r=Lo(e.installation),{installPath:t}=e.installation;if(t===null)return{kind:"skills-only",version:r};let n=qk(t,Z),o=n!==null&&typeof n=="object"?n[Te]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:r}:{kind:"stale-server",version:r,keys:Object.keys(o)}},pm=e=>`Plugin ${W} ${e===null?"(version unreadable)":e}`,zk=e=>{let r="plugin MCP server";if(e.kind==="not-installed")return{name:r,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${Ye}`};if(e.kind==="stale-server"){let t=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:r,status:"pass",message:`${pm(e.version)} still carries an MCP server in its ${Z}${t} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${It}), then restart Claude Code`}}return{name:r,status:"pass",message:`${pm(e.version)} is skills-only \u2014 no ${Z}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},Yk=(e,r)=>{let t=Fr(e===null?{}:{projectPath:e}),n=vn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${q} is known to Claude Code`:`Marketplace ${q} is not registered. Run: claude plugin marketplace add ${fr}`},Uk(t,r),Bk(t),zk(Hk(t)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${H.version}`}]},vm=e=>`${Z} still registers "${e}" \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 "${e}" entry from ${Z} by hand in a PR, keeping its siblings (\`claude mcp remove ${e} --scope project\` also works but re-indents the file)`,Zk={stale:vm(q),absent:`${Z} carries no "${q}" key \u2014 nothing spawns the retired server`,"missing-file":`no ${Z} at the repo root \u2014 nothing spawns the retired server`,unparseable:`Could not read ${Te} from ${Z} \u2014 fix the JSON and re-run`},Xk=new Set(["absent","missing-file","stale","wrong-key"]),Qk=e=>{let r="MCP server key",t=Gr(e);return t.kind==="wrong-key"?{name:r,status:"pass",message:vm(t.key)}:{name:r,status:Xk.has(t.kind)?"pass":"fail",message:Zk[t.kind]}},eb=({env:e,stdinIsTTY:r,flag:t})=>{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 ${r?"is a TTY":"is not a TTY"}`,`--agent ${t?"passed":"not passed"}`].join(", ")},rb=e=>{let r="Agent mode",t=$o(e),n=eb(e);return{name:r,status:"pass",message:`${t===null?"human":"agent"} \u2014 ${t==="flag"?"the --agent flag, which beats every environment value":e.env.INFRA_KIT_AGENT==="1"?"INFRA_KIT_AGENT=1":t==="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})`}},um=4,tb=e=>{let r=e.slice(0,um).join(", "),t=e.length-um;return t>0?`${r} +${t} more`:r},nb=e=>{let r="Agent allowlist",{present:t,unreadable:n,hits:o}=im(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"} (${tb(i.commands)})`);return{name:r,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:r,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`}:t.length===0?{name:r,status:"pass",message:`no ${lc.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:r,status:"pass",message:`no permissions.allow pattern in ${t.join(" or ")} reaches a mutating infra-kit command`}},ym=e=>wi(["trust"],{bin:e}),ob=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),mm="ERR_TLS_CERT_ALTNAME_INVALID",sb=async(e,r,t)=>{let n=`portless serving TLS on :${gr}`;return await e(gr,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${gr}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${gr}. Install it once (needs root): \`${jr(r,t)}\`.`}},ib=async(e,r,t,n,o)=>{let s="portless CA chain valid",i=["localhost",...r.slice(0,1).map(p=>p.name)],c=(await Promise.all(i.map(async p=>({servername:p,result:await e(gr,p)})))).filter(p=>!p.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${y(t)} (${i.join(", ")})`};let d=c.map(p=>p.result.ok?"":p.result.code);return d.includes(mm)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${mm} for servername(s) ${c.map(p=>p.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:d.some(p=>ob.has(p))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${y(t)}. Its CA was regenerated \u2014 run \`${ym(n)}\`, or reinstall: \`${jr(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${d.join(", ")})`}},ab=(e,r,t)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${y(r)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${ym(t)}\` (no sudo needed).`}},cb=async(e,r,t)=>{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 r(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 \`${wi(["alias","--remove","<name>"],{bin:t})}\`.`}},nt="portless service target",Es=e=>({name:nt,status:"pass",message:`Warning \u2014 ${e}`}),lb=e=>e==="darwin"?wd:e==="linux"?kd:null,db=e=>e==="darwin"?`sudo launchctl kickstart -k system/${yd}`:`sudo systemctl restart ${bd}`,pb="/bin/ps",ub=e=>{try{let r=pk(pb,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(r.status!==0)return null;let t=new Date(r.stdout.trim());return Number.isNaN(t.getTime())?null:t}catch{return null}},fm=e=>{try{return F.readFileSync(e,"utf-8")}catch{return null}},mb=e=>{try{return F.statSync(e).mtime}catch{return null}},wm=(e,r)=>({platform:e.platform??Sr.platform,readServiceFile:e.readServiceFile??fm,readFile:e.readFile??fm,exists:e.exists??F.existsSync,realpath:e.realpath??de,mtime:e.mtime??mb,execPath:e.execPath??Sr.execPath,home:e.home??gm.homedir(),cwd:e.cwd??Sr.cwd(),repoRoot:e.repoRoot??Mn,stateDir:(e.stateDir??Ed)(),processStartTime:e.processStartTime??ub,bin:r}),fb=(e,r)=>{let t=r.readFile(Q.join(e,"package.json"));try{let n=t===null?null:ce.object({version:ce.string()}).safeParse(JSON.parse(t));return n?.success===!0?n.data.version:"?"}catch{return"?"}},gb=(e,r)=>{let t=Number.parseInt(r.readFile(Q.join(r.stateDir,"proxy.pid"))?.trim()??"",10);if(!Number.isInteger(t)||t<=0)return!1;let n=r.processStartTime(t),o=r.mtime(Q.join(e,"package.json"));return n!==null&&o!==null&&n.getTime()<o.getTime()},hb=async(e,r)=>{let t=r.realpath(r.cwd);return t===r.realpath(r.home)?!1:mn(await r.repoRoot()??t,e,r.realpath)},Qt=e=>({state:"drifted",row:e}),vb=async(e,r,t)=>{let n=jr(t.bin,t);if(!t.exists(e))return Qt({name:nt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded). Re-run: \`${n}\``});let o=Q.join(bi(t.home),"dist","cli.js");if(r!==o)return Qt(Es(`The service points at \`${r}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Io(t.home,t.exists)===null)return Qt({name:nt,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=t.realpath(bi(t.home));if(await hb(s,t))return Qt({name:nt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});if(t.realpath(e)!==t.realpath(t.execPath))return Qt(Es(`The service runs \`${e}\`; infra-kit runs \`${t.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${n}\``));let i=fb(s,t);return gb(s,t)?{state:"converged",row:Es(`The running daemon predates portless ${i} that \`dev\` will talk to. Restart it: \`${db(t.platform)}\` (or reboot).`)}:{state:"converged",row:{name:nt,status:"pass",message:`service runs \`${e}\` + stable link \u2192 portless ${i}`}}},km=async e=>{let r=lb(e.platform);if(r===null)return{state:"absent",row:{name:nt,status:"pass",message:"Skipped \u2014 no portless OS service file on this platform"}};let t=e.readServiceFile(r);if(t===null)return{state:"absent",row:{name:nt,status:"pass",message:`Skipped \u2014 the OS service is not installed (no ${r})`}};let[n,o]=tu(e.platform,t)??[];return n===void 0||o===void 0?Qt(Es(`could not parse ${r} \u2014 re-run \`${jr(e.bin,e)}\` to rewrite it.`)):vb(n,o,e)},bm=async(e,r)=>(await km(wm(e,r))).state,yb=async(e={})=>{let r=e.resolveBin??vd,t=e.isProxyServing??Rd,n=e.handshake??xd,o=e.caTrusted??Sd,s=e.routes??ki,i=e.isListening??fn,a=(e.caPath??Pd)(),c=r();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."}];let d={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},p=wm(e,c),u=s(),m=await sb(t,c,p),v=m.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await ib(n,u,a,c,p);return[d,(await km(p)).row,m,v,ab(o(),a,c),await cb(u,i,c)]},wb=async(e={})=>{let r="portless routes",t=e.routes??ki,n=e.isListening??fn,o=e.devSessionRunning??Zp,s=t();if(s.length===0)return{name:r,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async p=>({name:p.name,port:p.port,live:await n(p.port)}))),{prunable:a,withheld:c}=Yp(i,o());if(c.length>0)return{name:r,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:r,status:"pass",message:`${s.length} portless route(s), all live`};let d=e.removeAlias??Td().removeAlias;for(let p of a)await d(p);return{name:r,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Ps=async(e={})=>{let r=await kk(),t=mk(e.probeDeps??Wn()),n=async(m,v)=>{let[f,T]=await Promise.all([v,t]),C=T.get(m);return C===void 0?f:{...f,detail:C}},o=await Promise.all([n("brew",Pr("brew installed",Ce("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("gh",Pr("gh installed",Ce("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),Pr("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",Pr("doppler installed",Ce("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",Pr("aws installed",Ce("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")),Pr("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),Pr("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"),fk(),Promise.resolve(gk()),Promise.resolve(hk()),vk(),yk(),Promise.resolve(bk(r)),Ck(),Sk(r),Tk(r),Ik(e.fix??!1),_k(),Ok(),Mk(r)]),s=await yb();if(e.fix){let m=await wb(),v=s.findIndex(f=>f.name===m.name);v>=0?s[v]=m:s.push(m)}let i=await Vk(),a=await Mn(),c={projectDir:Sr.env.CLAUDE_PROJECT_DIR||null,cwd:Sr.cwd(),gitRoot:a},d=[await Kk(),...Yk(i,c),...a===null?[]:[Qk(a)],rb({env:Sr.env,stdinIsTTY:Sr.stdin.isTTY===!0,flag:I.source==="flag"}),...a===null?[]:[nb(a)]],p=[...o,...s,...await Wk(),...d],u={checks:p.map(m=>({name:m.name,status:m.status,message:m.message,fixable:ka.has(m.name),detail:m.detail})),allPassed:p.every(m=>m.status!=="fail"),cliVersion:H.version};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}},pc=k({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:ce.array(ce.object({name:ce.string().describe("Name of the check"),status:ce.enum(["pass","fail","warn"]).describe("Check result; warn is advisory and never fails the run"),message:ce.string().describe("Details about the check result"),fixable:ce.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ce.object({manager:ce.string().describe("Which package manager owns this install, read from its resolved path"),version:ce.string().nullable().describe("The version the tool reported, or null"),present:ce.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ce.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:ce.boolean().describe("Whether no check failed (warnings are advisory and do not count)"),cliVersion:ce.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Ps()});import uc from"node:fs";import Rm from"node:path";import{z as en}from"zod";var kb=async e=>{let r="";try{r=await b()}catch{return}let t=er(r);t&&Ia(t,e)},bb=e=>[...e.map(r=>`unset ${r}`),`unset ${So}`,`unset ${pr}`,`unset ${ur}`,`unset ${xo}`,`unset ${ht}`,`unset ${Ne}`,`export ${mr}='1'`],Ss=async({purge:e=!1}={})=>{let r=z(),t=Rm.join(r,te),n=uc.existsSync(t);if(!n&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await kb(e);let o=n?To(t):[],s=bb(o),i=Rm.resolve(r,gt);uc.mkdirSync(r,{recursive:!0,mode:448}),Ue(i,`${s.join(`
342
+ ${i}`:"")},cu=()=>{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(`
343
+ `)},lu=()=>`${$t}
344
+ ${cu()}
345
+ ${ut}`,Ea=()=>["# 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(`
346
+ `),Sa=()=>`${$t}
347
+ ${Ea()}
348
+ ${ut}`;var Ky="Could not find requested project",qy="Could not find requested config",du="Invalid Auth token",pu="does not have access to requested config",It=e=>e.includes(du)||e.includes(pu)?"auth":e.includes(Ky)?"project":e.includes(qy)?"config":"unknown",Dt=e=>e.includes(pu)?"mis-scoped":e.includes(du)?"revoked":null;var uu=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(`
349
+ `),xr=class extends Oo{authKind;constructor(t,r=null,n){super(n??uu(t),t),this.name="DopplerAuthError",this.authKind=r}};var xa=({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(`
350
+ `)};import{$ as ns}from"zx";var Hy=5e3,Yy="DOPPLER_CONFIG",xe=async()=>{let{envManagement:e}=await $();return e.config.name},Ta=async({childEnv:e,project:t,config:r})=>{let n=ns.quiet;ns.quiet=!0;try{let s=(await ns({env:e})`doppler secrets get ${Yy} --plain --project ${t} --config ${r}`.timeout(Hy)).stdout.trim();return s!==r?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(o){return{outcome:zy(o)}}finally{ns.quiet=n}},zy=e=>{let t=sr(e)??(e instanceof Error?e.message:String(e));return It(t)!=="auth"?"unreachable":Dt(t)??"unreachable"};import Xy from"node:process";var te="INFRA_KIT_ENV_TOKEN",Rn=async e=>{let t=Xy.env[te];if(t)return{token:t,source:"env"};let n=(await ne())?.envs[e];if(n)return{token:n,source:"store"};throw new Oo(Zy(e,await We()),e)},Zy=(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 ${te} instead \u2014 it takes precedence and needs no home config.`].join(`
351
+ `);import Qy from"node:fs/promises";var Pn=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await Qy.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}}},En=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import tw from"node:fs";import rw from"node:os";import mu from"node:path";import nw from"node:process";import{$ as ew}from"zx";var Ot=()=>ew({quiet:!0});var ow=()=>[mu.join(rw.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],sw=async e=>{try{return(await Ot()`command -v ${e}`).stdout.trim()||null}catch{return null}},Sn=()=>({runCommand:async e=>{let t=await Ot()`${e}`;return{stdout:`${t.stdout}
352
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await sw(e);return t!==null?t:ow().map(r=>mu.join(r,e)).find(r=>tw.existsSync(r))??null},realpath:ie,platform:nw.platform});var Nt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Tn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,Cn=["darwin","linux"],Aa=e=>t=>ci(t,e)?"homebrew":"unknown",is=(e,t)=>r=>r===null?null:t(e(r),r),vu=e=>is(Aa(e.kegName),t=>t==="homebrew"?Nt(["brew","upgrade",e.brewFormula]):null),fu=e=>ko(e,"Homebrew")||ko(e,"homebrew")?"homebrew":"unknown",iw={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Tn,platforms:Cn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:fu,updateFor:is(fu,e=>e==="homebrew"?Nt(["brew","update"]):null)},Ca={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},yu="https://awscli.amazonaws.com/v2/install.sh",wu={steps:[["/bin/bash","-c",`curl -fsSL ${yu} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},aw="/usr/local/aws-cli",cw=e=>en(aw,e,ie)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${yu} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:wu,gu=e=>ci(e,Ca.kegName)?"homebrew":ko(e,"aws-cli")?"script":"unknown",lw={id:"aws",binName:"aws",...Ca,probeArgv:["aws","--version"],versionFrom:Tn,platforms:Cn,prerequisites:[],bootstrapInstall:wu,identify:gu,updateFor:is(gu,(e,t)=>e==="homebrew"?Nt(["brew","upgrade",Ca.brewFormula]):e==="script"?cw(t):null)},os={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},dw={id:"gh",binName:"gh",...os,probeArgv:["gh","--version"],versionFrom:Tn,platforms:Cn,prerequisites:["brew"],bootstrapInstall:Nt(["brew","install",os.brewInstallSpec]),identify:Aa(os.kegName),updateFor:vu(os)},ss={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},pw={id:"doppler",binName:"doppler",...ss,probeArgv:["doppler","--version"],versionFrom:Tn,platforms:Cn,prerequisites:["brew"],bootstrapInstall:Nt(["brew","install","gnupg"],["brew","install",ss.brewInstallSpec]),identify:Aa(ss.kegName),updateFor:vu(ss)},xn="portless",hu=e=>Zl(e,xn)===null?"unknown":"npm",uw={id:"portless",binName:xn,npmPackage:xn,probeArgv:["portless","--version"],versionFrom:Tn,platforms:[...Cn,"win32"],prerequisites:[],bootstrapInstall:Nt(["npm","install","-g",xn]),identify:hu,updateFor:is(hu,e=>e==="npm"?Nt(["npm","install","-g",`${xn}@latest`]):null)},$a={brew:iw,aws:lw,gh:dw,doppler:pw,portless:uw},_t=Object.keys($a),Te=e=>$a[e],Ia=(e,t)=>e.platforms.includes(t),Da=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 Te(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var ku=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),bu=async(e,t)=>{try{return await e(t)}catch{return null}},mw=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Ru=async(e,t)=>{if(!Ia(e,t.platform))return ku(e.id);let r=await bu(t.runCommand,e.probeArgv),n=await mw(t,e.binName);if(r==null&&n==null)return ku(e.id);let o=r??(n==null?null:await bu(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)}},An=async(e,t)=>Promise.all(e.map(r=>Ru(Te(r),t)));var Pu=["prod"],Tr={allowed:!1,reason:"disallow"},Cr=e=>Pu.includes(e),fw=["dev","stage"],Ar=e=>fw.includes(e)||Cr(e),He=(e,t=Tr)=>t.allowed?e:e.filter(r=>!Cr(r)),Mt=(e,t,r=Tr)=>{if(!r.allowed&&Cr(e))throw r.reason==="agent-blocked"?new T({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 Ye=async()=>{let e;try{e=(await $()).protectedEnvs??"disallow"}catch{return Tr}return e==="disallow"?Tr:e==="cli-only"&&Z()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var $n=e=>{let{env:t,branch:r}=e;Cr(t)&&l.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(`
353
+ `))};import Eu from"node:fs/promises";import Oa from"node:path";import gw from"yaml";var Su=".github/workflows",ze=async e=>{let t=await R();return xu(Oa.resolve(t,Su,e))},Na=async()=>{let e=await R(),t=Oa.resolve(e,Su),r;try{r=await Eu.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>xu(Oa.resolve(t,s))));return[...new Set(o.flat())]},xu=async e=>{let t;try{t=gw.parse(await Eu.readFile(e,"utf-8"))}catch{return[]}let r=$r(t,"on")??$r(t,"true"),n=$r($r($r($r(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},$r=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var Ir=async()=>{let e=await Na(),t=await ne(),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]},jt=async()=>(await Ir()).map(t=>t.env);import{$ as Ew}from"zx";import Dn from"node:process";var hw="x-seraph-loginreason",vw="AUTHENTICATED_FAILED",yw=(e,t=160)=>{let r=e.split(`
354
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Cu=(e,t)=>t===vw||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Tu=(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}`,Dr=class extends Error{status;kind;body;context;constructor(t){let r=Cu(t.status,t.seraphLoginReason),n=yw(t.body);super(n===""?`${t.context}: ${Tu(r,t.status)}`:`${t.context}: ${Tu(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},In=e=>e instanceof Dr,Au=e=>e.headers.get(hw);var Or=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Dr({status:e.status,seraphLoginReason:Au(e),body:r,context:t});throw l.debug({status:e.status,kind:n.kind,body:r},t),n},Ft=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,_a=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}`),d=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Or(d,"Failed to create Jira version"),{success:!0,version:await d.json()}},Nr=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 Or(a,"Failed to get Jira project versions"),await a.json()},Xe=async(e,t)=>(await Nr(t)).find(o=>o.name===e)||null,_r=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 Or(c,"Failed to update Jira version");let d=await c.json();if(e.releaseDate===null&&(d.releaseDate||null)!==null)throw new Error(`Jira accepted the update (the write happened) but still reports releaseDate=${d.releaseDate}; the clear payload in updateJiraVersion needs revisiting`);return{success:!0,version:d}},Ma=async(e,t)=>{let{versionName:r}=e,n=await Xe(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await _r({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Mr=async()=>{let e=Dn.env.JIRA_BASE_URL,t=Dn.env.JIRA_TOKEN||Dn.env.JIRA_API_TOKEN,r=Dn.env.JIRA_PROJECT_ID,n=Dn.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(`
355
+ `);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}},Ze=async()=>{try{return await Mr()}catch(e){return l.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var as=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 Or(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},ja=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 Or(c,"Failed to remove Jira version")};import{z as $u}from"zod";var Iu=/^\d{4}-\d{2}-\d{2}$/,On=e=>{if(!Iu.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},Du=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,jr=class extends Error{constructor(t){super(Du(t)),this.name="InvalidReleaseDateError"}},Lt=e=>{let t=e.trim();if(!On(t))throw new jr(t);return t},Nn=e=>{let t=e.trim();return t===""||On(t)?!0:Du(t)},Fa=$u.string().refine(On,{message:"Expected a calendar date in yyyy-mm-dd form."}),La=$u.string().refine(e=>e===""||On(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var mt=e=>e.slice(1).split(".").map(Number),Fr=e=>[...e].sort((t,r)=>{let[n,o,s]=mt(t),[i,a,c]=mt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var Nu="next",ww=/^v?(\d+)\.(\d+)\.(\d+)$/,kw=e=>e.replace(/^.*release\//,""),Ja=e=>{let t=kw(e.trim()),r=ww.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Ou=e=>`${e[0]}.${e[1]}.${e[2]}`,Va=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Ja(o);if(!s)continue;let i=Ou(s);n.has(i)||(n.add(i),r.push(s))}return Fr(r.map(o=>Ou(o))).map(o=>mt(`v${o}`))},Jt=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Ba=(e,t)=>{if(e.length===0)throw new Jt;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,d)=>d[0]===s&&d[1]===i?Math.max(c,d[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},Lr=(e,t)=>{try{return Ba(e,t)}catch(r){if(r instanceof Jt)return null;throw r}},Wa=e=>e.trim().toLowerCase()===Nu,ls=e=>Wa(e)||Ja(e)!==null?{version:e}:{name:e},bw=e=>e==="regular"||e==="hotfix",_u=e=>"name"in e,Rw=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:Lt(n)}},Ga=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=Rw(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),d=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let p=d.toLowerCase();if(!bw(p))throw new Error(`Invalid release type "${d}". Expected "regular" or "hotfix".`);s=p}return cs({...ls(n),type:s},{description:i,releaseDate:o})},Ua=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},cs=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},Pw=e=>{let t=e.name.trim();return So(t),cs({id:{kind:"name",name:t,raw:t},type:e.type},e)},Ka=(e,t)=>{let r=[...t];return e.map(n=>{if(_u(n))return Pw(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Wa(o)){let a=Ba(r,n.type);return r.push(mt(`v${a}`)),cs({id:Ee(a),type:n.type},n)}let s=Ja(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),cs({id:Ee(i),type:n.type},n)})},qa=e=>e.some(t=>!_u(t)&&Wa(t.version));var Sw=e=>e.split(`
356
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:L(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),xw=async()=>{let e=await Ew({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return Sw(e.stdout)},Tw=async()=>{let e=await Ze();return e?(await Nr(e)).map(r=>r.name):[]},_n=async()=>{let[e,t]=await Promise.allSettled([xw(),Tw()]);return e.status==="rejected"&&l.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&l.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Va({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import Cw from"node:fs";import Aw from"node:path";var Ha=[".claude/settings.json",".claude/settings.local.json"],$w=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],Iw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Dw=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},Ow=(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(Iw).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},Nw=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},_w=()=>Vt.filter(e=>e.mutating),Mw=e=>{let t=Dw(e);return t===null?[]:_w().filter(r=>$w.some(n=>Nw(r).some(o=>Ow(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},jw=(e,t)=>{let r;try{r=Cw.readFileSync(Aw.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}},Mu=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Ha){let n=jw(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=Mw(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var Fw=["brew","gh","doppler","aws"],Lw=async e=>{let t=await An(Fw,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},ft=async(e,t,r,n)=>{try{return await Ot()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},Jw=async()=>{let e="orca installed",t=await lr();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)"}},Hu=(e,t,r,n)=>{let o=re.join(qu.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!H.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=H.readFileSync(o,"utf-8"),a=i.indexOf($t),c=i.indexOf(ut);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+ut.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`}},Vw=()=>Hu("zshrc init block",".zshrc","shell",lu()),Bw=()=>Hu("zshenv session block",".zshenv","session-env",Sa()),Ww=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await R(),r=re.join(t,"pnpm-workspace.yaml");if(!H.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=H.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}`}}},Gw=async()=>{try{return lt(),{config:await $(),error:null}}catch(e){return{config:null,error:e}}},Uw=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)"}},Kw=384,Ya=448,qw=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(", "),Hw=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}}})),Yw=async(e,t={})=>{let r="env tokens configured",n=t.readStore??ne,o=t.resolveToken??Rn;if(!e.config)return{name:r,status:"pass",message:"Skipped \u2014 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 Hw(await jt(),o);return{name:r,status:"pass",message:qw(s)}},zw=()=>Le.env[te]||void 0,Xw=async(e={})=>{let t="tokens.json present",r=e.readStore??ne,n=e.storePath??We;if((e.readEnvToken??zw)())return{name:t,status:"pass",message:`Skipped \u2014 ${te} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"pass",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 ${te} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Mn=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},Zw=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??We,o=t.statPath??Qw,s=t.chmodPath??H.chmodSync,i;try{i=await n()}catch{return{name:r,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(Mn(i,o)===null)return{name:r,status:"pass",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=re.dirname(i),c=re.dirname(a),d=re.dirname(c),u=[{target:d,expected:Ya,actual:Mn(d,o)},{target:c,expected:Ya,actual:Mn(c,o)},{target:a,expected:Ya,actual:Mn(a,o)},{target:i,expected:Kw,actual:Mn(i,o)}].filter(h=>h.actual!==null&&h.actual!==h.expected);if(u.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=u.map(h=>`${w(h.target)} is ${ju(h.actual)}, expected ${ju(h.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let h of u)s(h.target,h.expected);return{name:r,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},ju=e=>`0${e.toString(8).padStart(3,"0")}`,Qw=e=>{try{return H.statSync(e)}catch{return null}},ek=async()=>{let e="user override path";try{let t=await q(),r=H.existsSync(t.userProject),n=await Pn(t.userProject,r),o=r?En(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}}},tk=async()=>{let e="legacy user-global config",t;try{t=await q()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let r=re.join(re.dirname(t.userGlobal),"config.json");return H.existsSync(r)?H.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"}},rk={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},nk=async e=>{let t=rk[e];try{return await Ot()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},ok=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let r=ct(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=>nk(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("; ")}},Fu=/^\d+\.\d+\.\d+$/,sk=(e,t)=>e===t||!Fu.test(e)||!Fu.test(t)?!1:Fr([`v${e}`,`v${t}`])[0]===`v${e}`,ik=async(e,t)=>{let r;try{r=await de(e)}catch{return[]}let n=[];for(let o of r){let s=St(xt(re.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&sk(s.version,t)&&n.push(s.version)}return n},ak=async(e,t)=>{let r=await ik(e,t);if(r.length===0)return"";let n=Fr(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`},ck=async()=>{let e;try{e=(await q()).main}catch{return[]}if(!H.existsSync(e))return[];let t=re.dirname(e),r=re.join(t,"CLAUDE.md"),n=H.existsSync(r)?H.readFileSync(r,"utf-8"):"",o=Ne(n,ye,_e),s=o?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",i=await ak(t,U.version);return[{name:"CLAUDE.md block",status:o?"pass":"fail",message:`${s}${i}`}]},lk=async()=>{try{let e=(await q()).main;return H.existsSync(e)?re.dirname(e):null}catch{return null}},dk=e=>{let t=Id();return t===null||!sn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${yr}`},pk=e=>{let t=e.kind==="installed"?Do(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 ${J} version ${t}${dk(t)}`}},Lu=3,Ju=(e,t)=>ie(e)===ie(t),uk=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(Ju(e.projectDir,e.gitRoot))return"";let r=en(e.gitRoot,ie(e.projectDir),ie)?"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 Ju(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}`},mk=(e,t)=>{let r="plugin installed",n=uk(t);if(e.kind==="installed"){let{scope:c,projectPath:d}=e.installation,p=d===null?"":`, ${w(d)}`;return{name:r,status:"pass",message:`Plugin ${J} installed (${c??"unknown"} scope${p})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${J} is not installed. Run: ${Ke}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-Lu,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Lu).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${J} is installed for ${a} only, not this project. Run: ${Ke}${n}`}},fk=()=>ft("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),gk=(e,...t)=>{try{return JSON.parse(H.readFileSync(re.join(e,...t),"utf-8"))}catch{return null}},hk=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=Do(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=gk(r,z),o=n!==null&&typeof n=="object"?n[Se]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Vu=e=>`Plugin ${J} ${e===null?"(version unreadable)":e}`,vk=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: ${Ke}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Vu(e.version)} still carries an MCP server in its ${z}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${yr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Vu(e.version)} is skills-only \u2014 no ${z}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},yk=(e,t)=>{let r=Pt(e===null?{}:{projectPath:e}),n=on();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${G} is known to Claude Code`:`Marketplace ${G} is not registered. Run: claude plugin marketplace add ${it}`},mk(r,t),pk(r),vk(hk(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},Yu=e=>`${z} still registers "${e}" \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 "${e}" entry from ${z} by hand in a PR, keeping its siblings (\`claude mcp remove ${e} --scope project\` also works but re-indents the file)`,wk={stale:Yu(G),absent:`${z} carries no "${G}" key \u2014 nothing spawns the retired server`,"missing-file":`no ${z} at the repo root \u2014 nothing spawns the retired server`,unparseable:`Could not read ${Se} from ${z} \u2014 fix the JSON and re-run`},kk=new Set(["absent","missing-file","stale","wrong-key"]),bk=e=>{let t="MCP server key",r=At(e);return r.kind==="wrong-key"?{name:t,status:"pass",message:Yu(r.key)}:{name:t,status:kk.has(r.kind)?"pass":"fail",message:wk[r.kind]}},Rk=({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(", ")},Pk=e=>{let t="Agent mode",r=Eo(e),n=Rk(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})`}},Bu=4,Ek=e=>{let t=e.slice(0,Bu).join(", "),r=e.length-Bu;return r>0?`${t} +${r} more`:t},Sk=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Mu(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"} (${Ek(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 ${Ha.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`}},zu=e=>li(["trust"],{bin:e}),xk=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Wu="ERR_TLS_CERT_ALTNAME_INVALID",Tk=async(e,t,r)=>{let n=`portless serving TLS on :${at}`;return await e(at,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${at}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${at}. Install it once (needs root): \`${st(t,r)}\`.`}},Ck=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(p=>p.name)],c=(await Promise.all(i.map(async p=>({servername:p,result:await e(at,p)})))).filter(p=>!p.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let d=c.map(p=>p.result.ok?"":p.result.code);return d.includes(Wu)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Wu} for servername(s) ${c.map(p=>p.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:d.some(p=>xk.has(p))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${zu(n)}\`, or reinstall: \`${st(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${d.join(", ")})`}},Ak=(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: \`${zu(r)}\` (no sudo needed).`}},$k=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 \`${li(["alias","--remove","<name>"],{bin:r})}\`.`}},Wt="portless service target",Fn=e=>({name:Wt,status:"pass",message:`Warning \u2014 ${e}`}),Xu=e=>e==="darwin"?id:e==="linux"?ad:null,Ik=e=>e==="darwin"?`sudo launchctl kickstart -k system/${sd}`:`sudo systemctl restart ${cd}`,Dk="/bin/ps",Ok=e=>{try{let t=Ku(Dk,["-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}},Gu=e=>{try{return H.readFileSync(e,"utf-8")}catch{return null}},Nk=e=>{try{return H.statSync(e).mtime}catch{return null}},_k=2e3,Mk=e=>{try{let t=Ku(e,["-p","process.version"],{encoding:"utf-8",timeout:_k}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},jk=(e,t)=>({platform:e.platform??Le.platform,readServiceFile:e.readServiceFile??Gu,readFile:e.readFile??Gu,exists:e.exists??H.existsSync,realpath:e.realpath??ie,mtime:e.mtime??Nk,execPath:e.execPath??Le.execPath,home:e.home??qu.homedir(),cwd:e.cwd??Le.cwd(),repoRoot:e.repoRoot??kn,stateDir:(e.stateDir??dd)(),processStartTime:e.processStartTime??Ok,version:e.version??Le.version,arch:e.arch??Le.arch,nodeVersionOf:e.nodeVersionOf??Mk,isGlobal:e.isGlobal??Po().node.isGlobal,nodeFs:e.nodeFs??H,stableNode:null,stableNodeSidecar:null,bin:t}),ds="portless node",Bt="~/.infra-kit/node",jn=e=>({row:{name:ds,status:"fail",message:e},stableNode:null,sidecar:null}),Uu=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},Fk=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,Lk=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,Jk=e=>{let t=gd(e.home),r=Uu(e.nodeFs.lstatSync,t);if(r===void 0)return jn(`${Bt} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return jn(`${Bt} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=hd(e.home,e.nodeFs);if(n===null)return jn(`${Bt} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Uu(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 jn(`${Bt} 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(!Lk(c,e))return jn(`${Bt} does not run as Node ${e.version} (${Fk(c)}). Re-run through the current Node: \`${st(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:ds,status:"pass",message:`${Bt} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},Vk=e=>{if(Xu(e.platform)===null)return{row:{name:ds,status:"pass",message:"Skipped \u2014 no portless OS service on this platform"},stableNode:null,sidecar:null};let t=Jk(e);return e.isGlobal()?t:{...t,row:{name:ds,status:"pass",message:`Skipped \u2014 not a global install; the global infra-kit keeps ${Bt} current`}}},Zu=(e,t)=>{let r=jk(e,t),n=Vk(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},Bk=(e,t)=>{let r=t.readFile(re.join(e,"package.json"));try{let n=r===null?null:oe.object({version:oe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},Wk=e=>{let t=Number.parseInt(e.readFile(re.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},Gk=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},Uk=(e,t,r)=>{let n=Wk(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(Gk(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(re.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},Kk=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:en(await t.repoRoot()??r,e,t.realpath)},Gt=e=>({state:"drifted",row:e}),qk=async(e,t,r)=>{let n=st(r.bin,r);if(!r.exists(e))return Gt({name:Wt,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=re.join(pi(r.home),"dist","cli.js");if(t!==o)return Gt(Fn(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Ro(r.home,r.exists)===null)return Gt({name:Wt,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(pi(r.home));if(await Kk(s,r))return Gt({name:Wt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=Hk(e,n,r);if(i!==null)return i;let a=Bk(s,r),c=Uk(s,a,r);return c!==null?{state:"converged",row:Fn(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${Ik(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Wt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},Hk=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Gt(Fn(`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:Gt(Fn(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Qu=async e=>{let t=Xu(e.platform);if(t===null)return{state:"absent",row:{name:Wt,status:"pass",message:"Skipped \u2014 no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Wt,status:"pass",message:`Skipped \u2014 the OS service is not installed (no ${t})`}};let[n,o]=Gp(e.platform,r)??[];return n===void 0||o===void 0?Gt(Fn(`could not parse ${t} \u2014 re-run \`${st(e.bin,e)}\` to rewrite it.`)):qk(n,o,e)},em=async(e,t)=>{let{seams:r}=Zu(e,t);return{state:(await Qu(r)).state,stableNode:r.stableNode}},Yk=async(e={})=>{let t=e.resolveBin??od,r=e.isProxyServing??ld,n=e.handshake??md,o=e.caTrusted??ud,s=e.routes??di,i=e.isListening??tn,a=(e.caPath??pd)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."}];let d={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:p,node:u}=Zu(e,c),m=s(),h=await Tk(r,c,p),y=h.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await Ck(n,m,a,c,p);return[d,u,(await Qu(p)).row,h,y,Ak(o(),a,c),await $k(m,i,c)]},zk=async(e={})=>{let t="portless routes",r=e.routes??di,n=e.isListening??tn,o=e.devSessionRunning??Lp,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async p=>({name:p.name,port:p.port,live:await n(p.port)}))),{prunable:a,withheld:c}=Fp(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 d=e.removeAlias??fd().removeAlias;for(let p of a)await d(p);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ps=async(e={})=>{let t=await Gw(),r=Lw(e.probeDeps??Sn()),n=async(m,h)=>{let[y,v]=await Promise.all([h,r]),I=v.get(m);return I===void 0?y:{...y,detail:I}},o=await Promise.all([n("brew",ft("brew installed",Te("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("gh",ft("gh installed",Te("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),ft("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",ft("doppler installed",Te("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",ft("aws installed",Te("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")),ft("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),ft("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"),Jw(),Promise.resolve(Vw()),Promise.resolve(Bw()),Ww(),Promise.resolve(Uw(t)),Xw(),Yw(t),Zw(e.fix??!1),ek(),tk(),ok(t)]),s=await Yk(e.portlessDeps);if(e.fix){let m=await zk(),h=s.findIndex(y=>y.name===m.name);h>=0?s[h]=m:s.push(m)}let i=await lk(),a=await kn(),c={projectDir:Le.env.CLAUDE_PROJECT_DIR||null,cwd:Le.cwd(),gitRoot:a},d=[await fk(),...yk(i,c),...a===null?[]:[bk(a)],Pk({env:Le.env,stdinIsTTY:Le.stdin.isTTY===!0,flag:A.source==="flag"}),...a===null?[]:[Sk(a)]],p=[...o,...s,...await ck(),...d],u={checks:p.map(m=>({name:m.name,status:m.status,message:m.message,fixable:pa.has(m.name),detail:m.detail})),allPassed:p.every(m=>m.status!=="fail"),cliVersion:U.version};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},za=b({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:oe.array(oe.object({name:oe.string().describe("Name of the check"),status:oe.enum(["pass","fail","warn"]).describe("Check result; warn is advisory and never fails the run"),message:oe.string().describe("Details about the check result"),fixable:oe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:oe.object({manager:oe.string().describe("Which package manager owns this install, read from its resolved path"),version:oe.string().nullable().describe("The version the tool reported, or null"),present:oe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:oe.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:oe.boolean().describe("Whether no check failed (warnings are advisory and do not count)"),cliVersion:oe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ps()});import Xa from"node:fs";import tm from"node:path";import{z as Ln}from"zod";var Xk=e=>[...e.map(t=>`unset ${t}`),`unset ${ho}`,`unset ${tr}`,`unset ${rr}`,`unset ${vo}`,`unset ${nr}`],us=async()=>{let e=or(),t=tm.join(e,er);if(!Xa.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=yo(t),n=Xk(r),o=tm.resolve(e,Yl);Xa.mkdirSync(e,{recursive:!0,mode:448}),wo(o,`${n.join(`
357
+ `)}
358
+ `,384),Xa.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Za=b({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:Ln.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Ln.string().describe("Path to the file that must be sourced to apply"),variableCount:Ln.number().describe("Number of variables cleared"),unsetStatements:Ln.array(Ln.string()).describe("Unset statements generated")},handler:()=>us()});import Zk from"node:process";import{z as gt}from"zod";var ms=(e,t,r)=>e.map(({env:n,source:o})=>({env:n,source:o,hasToken:!!(r||t[n])})),rm=["Environment","Source","Token"],Qk=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=rm.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(rm),o,...t.map(n)]},fs=async()=>{let e=await xe(),t=await Ir(),r=await ne(),n=Zk.env[te],o=ms(t,r?.envs??{},n);if(l.info(`Doppler project: ${e}
359
+ `),o.length===0)return l.info("No environments found."),l.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),l.info(" or add a token for one manually."),nm({project:e,envs:o});for(let s of Qk(o))l.info(s);return nm({project:e,envs:o})},nm=({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}},Qa=b({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:gt.string().describe("Detected Doppler project name"),configs:gt.array(gt.string()).describe("Every environment name known to this project"),tokens:gt.array(gt.object({env:gt.string().describe("Environment / Doppler config name"),source:gt.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:gt.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:fs});import ob from"@inquirer/select";import{Buffer as sb}from"node:buffer";import ib from"node:fs";import ab from"node:path";import tc from"node:process";import{z as Jr}from"zod";import{$ as gs}from"zx";import im from"node:process";import{z as om}from"zod";var sm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eb=async e=>{try{return await e}catch{return[]}},tb=async e=>{let t=await ne().catch(()=>null);return ms(e,t?.envs??{},im.env[te]).filter(r=>!r.hasToken).map(r=>r.env)},ec=()=>({get message(){return`Choose the environment to load into terminal session ${im.env[Rt]??`UNKNOWN \u2014 ${Rt} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>sm(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await eb(Ir());if(e.length===0)return l.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await tb(e);return om.object({config:om.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:{...sm(t)?t:{},config:r}}});import{z as rb}from"zod";var nb=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return l.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},ke=async e=>{if(!ae()||!e.provider.isFormable(e.params))return;let t=await nb(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:rb.toJSONSchema(t);throw new T({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 cb="DOPPLER_CONFIG",am=new Set(["DOPPLER_TOKEN",te]),cm=!1,lb=e=>{e.length===0||cm||(cm=!0,l.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},dm=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!am.has(i));return lb(e.filter(([i])=>am.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${Vr(a)}`),`${ho}=${Vr(t)}`,`${tr}=${Vr(t)}`,`${rr}=${Vr(r)}`,`${vo}=${Vr(n)}`,`${nr}=${Vr(o)}`,"set +a"]},db=async()=>{try{return await R()}catch{return""}},pm=async({config:e})=>{let t=await xe(),r=await db(),n=await mb(t,e),o=new Date().toISOString(),i=`${dm({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
393
360
  `)}
394
- `,384),n&&uc.rmSync(t,{force:!0});let a={filePath:i,variableCount:o.length,unsetStatements:s,purged:e};return{content:w(JSON.stringify(a,null,2)),structuredContent:a}},mc=k({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. When `infra-kit setup` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:en.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:en.string().describe("Path to the file that must be sourced to apply"),variableCount:en.number().describe("Number of variables cleared"),unsetStatements:en.array(en.string()).describe("Unset statements generated"),purged:en.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>Ss()});import Rb from"node:path";import ot from"node:process";import{z as xr}from"zod";var xs=async()=>{l.info("Environment session status:");let e=z(),r=ot.env[Ge],t=Rb.join(e,te),n=0,o=0,s=ot.env[pr]??null,i=ot.env[ur]??null,a=ot.env[ht]??null,c=ot.env[Ne]==="1",d=!!ot.env[mr];if(s){let u=To(t);u.length>0&&(o=u.length,n=u.filter(f=>f in ot.env).length);let m=a?.replace(/\.\d{3}Z$/,"")??null,v=c?"auto-loaded":"manually loaded";if(l.info(` ${s}: ${n} of ${o} vars loaded (${v}, project: ${i}, loadedAt: ${m}, session: ${r})
395
- `),o>0&&n<o){let f=o-n;l.warn(` ${f} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else{let u=d?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";l.info(` Session ${r}: no env loaded${u}
396
- `)}let p={sessionId:r,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a,autoLoaded:c,cleared:d};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}},fc=k({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. 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:xr.string().describe("Current terminal session ID"),sessionLoadedCount:xr.number().describe("Number of cached vars active in the current session"),sessionTotalCount:xr.number().describe("Total number of cached var names"),sessionConfig:xr.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:xr.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:xr.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:xr.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:xr.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:xs});import Eb from"node:process";import{z as Tr}from"zod";var Em="****",rn=e=>typeof e!="string"||e.length<8?Em:`${Em}${e.slice(-4)}`;var Pm=(e,r,t)=>e.map(n=>{let o=t||r[n];return o?{env:n,source:t?`env:${X}`:"store",redactedToken:rn(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),Pb=["ENV","SOURCE","TOKEN","PRESENT"],Sm=(e,r)=>{let t=[...Pb,...r?["CHECK"]:[]],n=e.map(s=>[s.env,s.source,s.redactedToken,s.present?"yes":"no",...r?[s.status??"-"]:[]]),o=t.map((s,i)=>Math.max(s.length,...n.map(a=>(a[i]??"").length)));return[t,...n].map(s=>s.map((i,a)=>i.padEnd(o[a])).join(" ").trimEnd())},Ts=async({check:e}={})=>{let r=await Hr(),t=await oe(),n=Eb.env[X],o=Pm(r,t?.envs??{},n);if(e){let a=await Ae();for(let c of o){if(!c.present)continue;let d=n||t.envs[c.env],p=await _n({childEnv:kr(d),project:a,config:c.env});c.status=p.outcome}}for(let a of Sm(o,!!e))l.info(a);let s=o.filter(a=>!a.present);s.length>0&&l.info(`
397
- No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:w(JSON.stringify(i,null,2)),structuredContent:i}},gc=k({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:Tr.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Tr.array(Tr.object({env:Tr.string().describe("Environment / Doppler config name"),source:Tr.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Tr.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Tr.boolean().describe("Whether a token is configured for this environment"),status:Tr.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Ts});import{z as x}from"zod";import{$ as Wb}from"zx";import{$ as xj}from"zx";import{$ as nn}from"zx";import{$ as xm}from"zx";var hc=async e=>{let{operation:r}=e;try{await xm({quiet:!0})`git rev-parse --git-dir`}catch(t){throw new g(t,{operation:r,remediation:"run this from inside a git repository"})}try{await xm({quiet:!0})`git remote get-url origin`}catch(t){throw new g(t,{operation:r,remediation:"this repository has no `origin` remote to fetch from or push to"})}},xb=4,tn=async e=>{let{operation:r}=e,t=await Nd();if(t.length===0)return;l.error(`working tree has uncommitted changes:
398
- ${t.join(`
399
- `)}`);let n=t.slice(0,xb),o=t.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:r,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},zn=async e=>{let{operation:r,base:t}=e;if(await kt()===t)return;let n=(await yt(await b())).find(o=>o.branch===t);if(n)throw new g(void 0,{operation:r,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${t}" is checked out in the worktree at ${n.path}`})},ge=async e=>{let{operation:r}=e;if(await jd())throw new g(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await tn({operation:r})};import{$ as Tm}from"zx";var Am="dev",Ar=e=>e==="hotfix"?"main":"dev",Yn=(e,r)=>(r??"").trim()!==""?`${e}
400
-
401
- ${r}`:`${e}
402
- `,vc=async(e="regular")=>{let r=Ar(e),t=Tm({quiet:!0});await t`git fetch origin`,await t`git switch ${r}`;try{await t`git pull --ff-only origin ${r}`}catch(n){let o=await Tm({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${r}...${r}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new g(n,{operation:`fast-forward ${r} onto origin/${r}`,remediation:a?`your local ${r} has diverged \u2014 rebase or reset it to origin/${r}, then retry`:`check your access to origin and that ${r} tracks it, then retry`,...a?{stderrExcerpt:`local ${r} is ${i} commit(s) ahead and ${s} behind origin/${r}`}:{}})}return(await t`git rev-parse HEAD`).stdout.trim()},Tb=async e=>{let{versionName:r,jiraConfig:t,description:n}=e,o=await tr(r,t);if(!o)return(await Za({name:r,projectId:t.projectId,description:n||"",released:!1,archived:!1},t)).version;if(o.released||o.archived)throw new g(void 0,{operation:`reuse Jira fix version "${r}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${r}" is already ${o.released?"released":"archived"}`});let s=n||"";return s!==""&&s!==(o.description??"")?(await zt({versionId:o.id,description:s},t),{...o,description:s}):o},yc=async e=>{let{id:r,jiraConfig:t,description:n,type:o="regular",baseSha:s}=e,i=Y(r),a=await Tb({versionName:i,jiraConfig:t,description:n}),c=Rr(t,a),d=await Cs({id:r,jiraVersionUrl:c,type:o,description:n,baseSha:s});return{version:B(r),type:o,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:c}},U=async()=>{let e=new Map,r=await nr();if(!r)return e;try{let t=await Ht(r);for(let n of t)n.description&&e.set(n.name,n.description)}catch(t){l.warn({err:t},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},Zn=(e,r,t)=>{let n=t?" ".repeat(t-e.length+3):" ",o=`[${r}]`.padEnd(11);return`${e}${n}${o}`},D=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",As=e=>e.flatMap(r=>{let t=L(r);return t?[{branch:r,id:t,label:B(t)}]:[]}),or=e=>{try{return Me(xe(e))}catch(r){throw new g(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},Xn=e=>{if(e===Am)return Am;let r=L(e);return r?B(r):e},st=e=>e.flatMap(r=>{let t=L(r);return t?[B(t)]:[]}),Ab=(e,r)=>r?r.get(e)||"regular":void 0,le=e=>{let{branches:r,descriptions:t,types:n}=e;return As(r).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:t.get(Y(s)),type:Ab(o,n)}))};var Cb=e=>e.map(r=>({pr:r,id:L(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>Dd(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),Qn=200,Cm=(e,r)=>{e.length<Qn||l.warn({source:r,limit:Qn},`\u26A0\uFE0F ${r} returned ${Qn} PRs \u2014 the page is full, so older release PRs may be missing`)},Ib=async()=>{let[e,r]=await Promise.all([nn`gh pr list --limit ${Qn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,nn`gh pr list --limit ${Qn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),t=JSON.parse(e.stdout),n=JSON.parse(r.stdout);Cm(t,"release PR discovery (base dev)"),Cm(n,"hotfix PR discovery (base main)");let o=[...t,...n],s=new Set;return o.filter(i=>s.has(i.headRefName)?!1:(s.add(i.headRefName),!0))},eo="find open release PRs",Im=async()=>{try{let e=await Ib();if(e.length===0)throw new g(void 0,{operation:eo,remediation:"open a release PR first, or check you are in the right repo"});return Cb(e)}catch(e){throw e instanceof g?e:(l.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},Is=async()=>(await Im()).map(r=>r.headRefName),_=async()=>(await Im()).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt})),$s=async e=>{let{branch:r,body:t}=e;try{await nn({quiet:!0})`gh pr edit ${r} --body ${t}`}catch(n){throw l.error({error:n,branch:r},`Error updating release PR body for ${r}`),n}},$b=async(e,r)=>{let t=nn({quiet:!0,nothrow:!0}),n=await t`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){l.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 t`git switch ${r}`,(await t`git branch -D ${e}`).exitCode!==0&&l.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Cs=async e=>{let{id:r,jiraVersionUrl:t,type:n,description:o,baseSha:s}=e,i=Od(r,n),a=Ar(n),c=nn({quiet:!0}),d=Me(r),p=Yn(t,o);try{await tn({operation:`create release branch ${d}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new g(void 0,{operation:`create release branch ${d}`,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 ${d}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${d}`;let m=await c`gh pr create --title ${i} --body ${p} --base ${a} --head ${d}`;return{branchName:d,prUrl:m.stdout.trim()}}catch(m){throw await $b(d,a),m}}catch(u){throw l.error({error:u,branchName:d},`Error creating release branch ${d}`),u}finally{await nn({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as _b}from"zx";var it=async e=>{let r=await _b`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null};import Ob from"node:process";var ro=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var $m=e=>{let r={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(we())throw new A({status:"argument_required",argument:e,agentMode:I.source},2,r);if(!Ob.stdin.isTTY)throw new g(void 0,r)},Cr=async e=>{$m("version");let{runBranchPicker:r}=await import("./boot-XLDVLQEG.js"),t=await r(e);if(t===null)throw new ro;return t},on=async(e,r)=>{$m("versions");let{runBranchMultiPicker:t}=await import("./boot-XLDVLQEG.js"),n=await t(e,r);if(n===null)throw new ro;return n};import{$ as at}from"zx";var Db="Merge remote-tracking branch 'origin/dev' into ",_m=e=>String(e.stderr??e.message??e).trim(),Nb=async e=>{try{return(await at({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
403
- `).map(t=>t.trim()).filter(t=>t.length>0)}catch{return[]}},Mb=async(e,r)=>{let t=_m(r),n=await Nb(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:t}:await Wd(e)?{status:"hook-failed",reason:t}:{status:"error",reason:t}},Om=async e=>{let{cwd:r,worktreePath:t,branches:n}=e,o=[],s=await hn(r,"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 jb({cwd:r,worktreePath:t,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},jb=async e=>{let{cwd:r,worktreePath:t,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await hn(r,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Ei(r,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await Pi(t),await at({cwd:t,quiet:!0})`git checkout --detach ${s}`;let i=`${Db}${n}`;await at({cwd:t,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await at({cwd:t,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 Mb(t,i)}}finally{await Si(t)}},Dm=e=>e.flatMap(r=>r.mergeSha?[{branch:r.branch,sha:r.mergeSha}]:[]),Nm="pnpm install --frozen-lockfile",Mm=async e=>{let{worktreePath:r,refs:t,command:n}=e,o=[],s=new Map;for(let i of t)try{await Pi(r),await at({cwd:r,quiet:!0})`git checkout --detach ${i.sha}`,await at({cwd:r,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,_m(a))}finally{await Si(r)}return{kept:o,failed:s}},wc=async(e,r)=>{await at({cwd:e,quiet:!0})`git fetch origin --prune`;let t=[],n=[];for(let o of r)await Ei(e,"origin/dev",`origin/${o.branch}`)?n.push(o.branch):t.push(o);return{kept:t,nowUpToDate:n}};import kc from"node:process";var _s=new Set,jm=e=>(_s.add(e),()=>{_s.delete(e)}),Fb=async()=>{for(let e of[..._s])try{await e()}catch(r){l.warn({error:r,msg:"cleanup failed during shutdown"})}_s.clear()},Lb=["SIGINT","SIGTERM"],Fm=async(e,r={})=>{let{register:t=(i,a)=>{kc.on(i,a)},unregister:n=(i,a)=>{kc.off(i,a)},exit:o=i=>{kc.exit(i)}}=r,s=new Map;for(let i of Lb){let a=()=>{Fb().then(()=>{o(gp(i))})};s.set(i,a),t(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var Vb=e=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[]}),Wm=e=>({content:w(JSON.stringify(e,null,2)),structuredContent:e}),Lm=new Set(["up-to-date","fast-forward","merged"]),Jb=(e,r)=>{let t=(Array.isArray(e)?e:e.split(",")).map(s=>s.trim()).filter(s=>s.length>0),n=new Set(r),o=new Set;for(let s of t){let i;try{i=Me(xe(s))}catch(a){throw new g(a,{operation:`resolve release selector "${s}"`,remediation:`pass one of: ${r.join(", ")}`})}if(!n.has(i))throw new g(void 0,{operation:`select release branch for "${s}"`,stderrExcerpt:`${i} is not an open regular release branch`,remediation:`pass one of: ${r.join(", ")}`});o.add(i)}return r.filter(s=>o.has(s))},Bb={"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"},Vm=e=>{let r=Bb[e.status];if(e.status==="conflict"){let t=e.conflictPaths?.length??0;return`${r}: ${t} file(s)`}return e.reason?`${r}: ${e.reason}`:r},Gb=e=>{l.info(`
404
- \u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${Vm(r)}`)},Ub=(e,r)=>{let t=r.find(n=>n.branch===e);return t?`git -C ${t.path} merge origin/dev`:`git switch ${e} && git merge origin/dev`},Kb=async e=>{let{entries:r,toPlan:t,all:n,explicit:o}=e;if(o||n)return t;h.setInteractive();let s=new Map(r.flatMap(i=>{let a=L(i.branch);return a?[[Y(a),Vm(i)]]:[]}));return on(le({branches:t,descriptions:s}),{required:!0})},qb=async e=>{let{cwd:r,worktreePath:t,entries:n,selected:o,verify:s}=e,i=n.filter(f=>o.includes(f.branch)),a=f=>{for(let T of f)l.info(`\u2139\uFE0F ${T} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await wc(r,Dm(i));a(c.nowUpToDate);let d=c.kept,p=new Map;if(s&&d.length>0){l.info(`
405
- \u{1F50E} Verifying ${d.length} merge(s) with: ${s}`);let f=await Mm({worktreePath:t,refs:d,command:s});p=f.failed;for(let[C,ee]of f.failed)l.info(`\u2717 ${C} failed verification \u2014 not pushing it. ${ee.split(`
406
- `)[0]??""}`);let T=await wc(r,f.kept);a(T.nowUpToDate),d=T.kept}if(d.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:p};l.info(`
407
- \u2B06\uFE0F Pushing atomically: ${d.map(f=>f.branch).join(", ")}`);let u=await Ld(r,d);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:p};let v=(await Promise.all(d.map(async f=>({branch:f.branch,landed:await Mo(r,f.branch)===f.sha})))).filter(f=>f.landed);return v.length>0&&l.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${v.map(f=>f.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
408
- `)[0],observedLanded:v.map(f=>f.branch)}},Os=async e=>{let{all:r,versions:t,dryRun:n=!1,verify:o,confirmedCommand:s}=e,i=o===!0?Nm:o||void 0;await hc({operation:"merge dev into release branches"});let c=(await _()).filter(R=>D(R.title)==="regular").map(R=>R.branch);if(c.length===0)return l.info("\u2139\uFE0F No open release branches found"),h.print(),Wm(Vb(n));let d=await wt();try{await Wb({cwd:d,quiet:!0})`git fetch origin --prune`}catch(R){throw new g(R,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=t===void 0?c:Jb(t,c),u=await Vd({cwd:d},async R=>{let Nr=jm(R.remove);try{return await Hb({cwd:d,worktree:R,toPlan:p,candidates:c,all:r,versions:t,dryRun:n,verify:i,confirmedCommand:s})}finally{Nr()}}),{entries:m,selected:v,pushed:f,pushAborted:T,abortedBy:C,declined:ee,verifyFailed:re}=u,O=await yt(d).catch(()=>[]);return zb({entries:m,selected:v,pushed:f,pushAborted:T,abortedBy:C,declined:ee,verifyFailed:re,dryRun:n,worktrees:O})},Hb=async e=>{let{cwd:r,worktree:t,toPlan:n,candidates:o,all:s,versions:i,dryRun:a,verify:c,confirmedCommand:d}=e,p=await Om({cwd:r,worktreePath:t.path,branches:n}),u={entries:p,pushed:!1,pushAborted:!1,declined:!1};if(Gb(p),a)return{...u,selected:n};let m=await Kb({entries:p,toPlan:n,all:s,explicit:i!==void 0});m.length===o.length?h.addOption("--all",!0):h.addOption("--versions",m);let v=p.filter(f=>m.includes(f.branch)&&f.mergeSha).length;v>0&&l.info(`
409
- \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 se(d,`Are you sure you want to merge dev into these branches: ${m.join(", ")}?`,{throwOnDecline:!0})}catch(f){if(!Vo(f))throw f;return{...u,selected:m,declined:!0}}return d||h.addOption("--yes",!0),{entries:p,selected:m,declined:!1,...await qb({cwd:r,worktreePath:t.path,entries:p,selected:m,verify:c})}},zb=e=>{let{entries:r,selected:t,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:d}=e,p=new Set(n?r.filter(f=>t.includes(f.branch)&&f.mergeSha&&!d?.has(f.branch)).map(f=>f.branch):[]),u=r.filter(f=>t.includes(f.branch)).map(f=>{let T=!!f.mergeSha,C=e.verifyFailed?.get(f.branch),ee=o&&T?"push-aborted":f.status,re=C?"verify-failed":ee;return{branch:f.branch,status:re,mergeSha:f.mergeSha,conflictPaths:f.conflictPaths,pushed:p.has(f.branch),reason:C??f.reason}}),m=u.filter(f=>!Lm.has(f.status));for(let f of u){let T=r.find(C=>C.branch===f.branch);l.info({branch:f.branch,status:f.status,mergeSha:f.mergeSha,conflictCount:f.conflictPaths?.length??0,durationMs:T?.durationMs,pushed:f.pushed,msg:"merge-dev branch result"})}if(i||a)l.info(i?`
361
+ `,a=or(),c=ab.resolve(a,er);return ib.mkdirSync(a,{recursive:!0,mode:448}),wo(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},um=ec(),hs=async e=>{let{config:t}=e;await ke({provider:um,params:e,operation:"env-load",argument:"config"});let r="";if(t)r=t;else{if(Z())throw new T({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 jt();g.setInteractive(),r=await x(i=>ob({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:tc.stderr,whenHeadless:"refuse"})}g.addOption("--config",r);let n=await pm({config:r});g.print();let o={filePath:n.filePath,variableCount:n.variableCount,project:n.project,config:n.config,sessionId:tc.env[Rt]??null};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},lm=1024*1024,pb=3e4,ub=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],Br=(e,t=tc.env)=>{let r={...t};for(let n of ub)delete r[n];return r.DOPPLER_TOKEN=e,r},mb=async(e,t)=>{let{token:r}=await Rn(t),n=Br(r),o=gs.quiet;gs.quiet=!0;try{let s;try{s=await gs({env:n})`doppler secrets download --no-file --format json --project ${e} --config ${t}`.timeout(pb)}catch(a){throw fb(a,e,t)}gb(s.stdout);let i=ys(s.stdout);return vs(i,t),i}finally{gs.quiet=o}},vs=(e,t)=>{let r=e.find(([n])=>n===cb)?.[1];if(!(r===void 0||r===t))throw new xr(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.
362
+ Fix: run \`infra-kit env-token-set ${t}\` with a token scoped to "${t}".`)},fb=(e,t,r)=>{let n=sr(e)??(e instanceof Error?e.message:String(e)),o=It(n);return o==="auth"?new xr(r,Dt(n)):o==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(xa({kind:o,project:t,config:r,available:null}))},gb=e=>{let t=sb.byteLength(e,"utf-8");if(t>lm)throw new Error(`doppler returned unexpectedly large output (${t} bytes > ${lm}) \u2014 refusing to write to disk`)},Vr=e=>`'${e.replaceAll("'","'\\''")}'`,hb=/^[A-Z_]\w*$/i,ys=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(!hb.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},rc=b({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:Jr.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:um,outputSchema:{filePath:Jr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Jr.number().describe("Number of variables loaded"),project:Jr.string().describe("Doppler project name"),config:Jr.string().describe("Doppler config name"),sessionId:Jr.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:hs});import vb from"node:path";import Jn from"node:process";import{z as Wr}from"zod";var ws=async()=>{l.info("Environment session status:");let e=or(),t=Jn.env[Rt],r=vb.join(e,er),n=0,o=0,s=Jn.env[tr]??null,i=Jn.env[rr]??null,a=Jn.env[nr]??null;if(s){let d=yo(r);d.length>0&&(o=d.length,n=d.filter(u=>u in Jn.env).length);let p=a?.replace(/\.\d{3}Z$/,"")??null;if(l.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${p}, session: ${t})
363
+ `),o>0&&n<o){let u=o-n;l.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 l.info(` Session ${t}: no env loaded
364
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},nc=b({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:Wr.string().describe("Current terminal session ID"),sessionLoadedCount:Wr.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Wr.number().describe("Total number of cached var names"),sessionConfig:Wr.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Wr.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Wr.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:ws});import yb from"node:process";import{z as ht}from"zod";var mm="****",Gr=e=>typeof e!="string"||e.length<8?mm:`${mm}${e.slice(-4)}`;var fm=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${te}`:"store",redactedToken:Gr(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),wb=["ENV","SOURCE","TOKEN","PRESENT"],gm=(e,t)=>{let r=[...wb,...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())},ks=async({check:e}={})=>{let t=await jt(),r=await ne(),n=yb.env[te],o=fm(t,r?.envs??{},n);if(e){let a=await xe();for(let c of o){if(!c.present)continue;let d=n||r.envs[c.env],p=await Ta({childEnv:Br(d),project:a,config:c.env});c.status=p.outcome}}for(let a of gm(o,!!e))l.info(a);let s=o.filter(a=>!a.present);s.length>0&&l.info(`
365
+ 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}},oc=b({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:ht.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:ht.array(ht.object({env:ht.string().describe("Environment / Doppler config name"),source:ht.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:ht.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:ht.boolean().describe("Whether a token is configured for this environment"),status:ht.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ks});import{z as S}from"zod";import{$ as _b}from"zx";import{$ as oj}from"zx";import{$ as Kr}from"zx";import{$ as hm}from"zx";var sc=async e=>{let{operation:t}=e;try{await hm({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 hm({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"})}},bb=4,Ur=async e=>{let{operation:t}=e,r=await Ed();if(r.length===0)return;l.error(`working tree has uncommitted changes:
366
+ ${r.join(`
367
+ `)}`);let n=r.slice(0,bb),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}`})},Vn=async e=>{let{operation:t,base:r}=e;if(await cr()===r)return;let n=(await ir(await R())).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}`})},ue=async e=>{let{operation:t}=e;if(await xd())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 Ur({operation:t})};import{$ as vm}from"zx";var ym="dev",wm={regular:"dev",hotfix:"main"},Je=e=>wm[e],Bn=e=>{let t=Object.entries(wm).find(([,r])=>r===e);return t?t[0]:null},Wn=(e,t)=>(t??"").trim()!==""?`${e}
368
+
369
+ ${t}`:`${e}
370
+ `,ic=async(e="regular")=>{let t=Je(e),r=vm({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 vm({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()},Rb=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await Xe(t,r);if(!s)return(await _a({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 _r({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},ac=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=Y(t),c=await Rb({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),d=Ft(r,c),p=await Ps({id:t,jiraVersionUrl:d,type:s,description:n,baseSha:i});return{version:B(t),type:s,branchName:p.branchName,prUrl:p.prUrl,jiraVersionUrl:d,releaseDate:c.releaseDate||null}},bs=async()=>{let e=new Map,t=await Ze();if(!t)return e;try{let r=await Nr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){l.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},X=async()=>{let e=await bs();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Gn=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},cc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Rs=e=>e.flatMap(t=>{let r=L(t);return r?[{branch:t,id:r,label:B(r)}]:[]}),Qe=e=>{try{return De(Ee(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)})}},Un=e=>{if(e===ym)return ym;let t=L(e);return t?B(t):e},Ut=e=>e.flatMap(t=>{let r=L(t);return r?[B(r)]:[]}),Pb=(e,t)=>t?t.get(e)||"regular":void 0,se=e=>{let{branches:t,descriptions:r,types:n}=e;return Rs(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(Y(s)),type:Pb(o,n)}))};var Eb=e=>e.map(t=>({pr:t,id:L(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Pd(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Kn=200,km=(e,t)=>{e.length<Kn||l.warn({source:t,limit:Kn},`\u26A0\uFE0F ${t} returned ${Kn} PRs \u2014 the page is full, so older release PRs may be missing`)},Sb=async()=>{let[e,t]=await Promise.all([Kr`gh pr list --limit ${Kn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Kr`gh pr list --limit ${Kn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);km(r,"release PR discovery (base dev)"),km(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)}))},qn="find open release PRs",bm=async()=>{try{let e=await Sb();if(e.length===0)throw new f(void 0,{operation:qn,remediation:"open a release PR first, or check you are in the right repo"});return Eb(e)}catch(e){throw e instanceof f?e:(l.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Es=async()=>(await bm()).map(t=>t.headRefName),xb=e=>{let t=Bn(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=cc(e.title)!==t;return(r||e.dualBase)&&l.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}},O=async()=>(await bm()).map(xb),Ss=async e=>{let{branch:t,body:r}=e;try{await Kr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw l.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},Tb=async(e,t)=>{let r=Kr({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){l.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&&l.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Ps=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Rd(t,n),a=Je(n),c=Kr({quiet:!0}),d=De(t),p=Wn(r,o);try{await Ur({operation:`create release branch ${d}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new f(void 0,{operation:`create release branch ${d}`,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 ${d}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${d}`;let m=await c`gh pr create --title ${i} --body ${p} --base ${a} --head ${d}`;return{branchName:d,prUrl:m.stdout.trim()}}catch(m){throw await Tb(d,a),m}}catch(u){throw l.error({error:u,branchName:d},`Error creating release branch ${d}`),u}finally{await Kr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as lc}from"zx";var qr=async e=>{let t=await lc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},dc=async e=>{let t=await lc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},pc=async e=>{try{let t=await lc`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 Cb from"node:process";var Hn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Rm=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(ae())throw new T({status:"argument_required",argument:e,agentMode:A.source},2,t);if(!Cb.stdin.isTTY)throw new f(void 0,t)},vt=async e=>{Rm("version");let{runBranchPicker:t}=await import("./boot-XLDVLQEG.js"),r=await t(e);if(r===null)throw new Hn;return r},Hr=async(e,t)=>{Rm("versions");let{runBranchMultiPicker:r}=await import("./boot-XLDVLQEG.js"),n=await r(e,t);if(n===null)throw new Hn;return n};import{$ as Kt}from"zx";var Ab="Merge remote-tracking branch 'origin/dev' into ",Pm=e=>String(e.stderr??e.message??e).trim(),$b=async e=>{try{return(await Kt({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
371
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},Ib=async(e,t)=>{let r=Pm(t),n=await $b(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await Ad(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Em=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await nn(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 Db({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},Db=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await nn(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await mi(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await fi(r),await Kt({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Ab}${n}`;await Kt({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await Kt({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 Ib(r,i)}}finally{await gi(r)}},Sm=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),xm="pnpm install --frozen-lockfile",Tm=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await fi(t),await Kt({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await Kt({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,Pm(a))}finally{await gi(t)}return{kept:o,failed:s}},uc=async(e,t)=>{await Kt({cwd:e,quiet:!0})`git fetch origin --prune`;let r=[],n=[];for(let o of t)await mi(e,"origin/dev",`origin/${o.branch}`)?n.push(o.branch):r.push(o);return{kept:r,nowUpToDate:n}};import mc from"node:process";var xs=new Set,Cm=e=>(xs.add(e),()=>{xs.delete(e)}),Ob=async()=>{for(let e of[...xs])try{await e()}catch(t){l.warn({error:t,msg:"cleanup failed during shutdown"})}xs.clear()},Nb=["SIGINT","SIGTERM"],Am=async(e,t={})=>{let{register:r=(i,a)=>{mc.on(i,a)},unregister:n=(i,a)=>{mc.off(i,a)},exit:o=i=>{mc.exit(i)}}=t,s=new Map;for(let i of Nb){let a=()=>{Ob().then(()=>{o(np(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var Mb=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),jb=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,Fb=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(", ")},Im=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),$m=new Set(["up-to-date","fast-forward","merged"]),Lb=(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=De(Ee(a))}catch(d){throw new f(d,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let d=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:d?`${c} is skipped: ${d}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},Jb={"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"},Dm=e=>{let t=Jb[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},Vb=(e,t)=>{l.info(`
372
+ \u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${Dm(r)}`);for(let r of t)l.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},Bb=(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`},Wb=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;g.setInteractive();let s=new Map(t.flatMap(i=>{let a=L(i.branch);return a?[[Y(a),Dm(i)]]:[]}));return Hr(se({branches:r,descriptions:s}),{required:!0})},Gb=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 v of y)l.info(`\u2139\uFE0F ${v} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await uc(t,Sm(i));a(c.nowUpToDate);let d=c.kept,p=new Map;if(s&&d.length>0){l.info(`
373
+ \u{1F50E} Verifying ${d.length} merge(s) with: ${s}`);let y=await Tm({worktreePath:r,refs:d,command:s});p=y.failed;for(let[I,j]of y.failed)l.info(`\u2717 ${I} failed verification \u2014 not pushing it. ${j.split(`
374
+ `)[0]??""}`);let v=await uc(t,y.kept);a(v.nowUpToDate),d=v.kept}if(d.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:p};l.info(`
375
+ \u2B06\uFE0F Pushing atomically: ${d.map(y=>y.branch).join(", ")}`);let u=await Cd(t,d);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:p};let h=(await Promise.all(d.map(async y=>({branch:y.branch,landed:await Ao(t,y.branch)===y.sha})))).filter(y=>y.landed);return h.length>0&&l.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${h.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
376
+ `)[0],observedLanded:h.map(y=>y.branch)}},Ts=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,confirmedCommand:s}=e,i=o===!0?xm:o||void 0;await sc({operation:"merge dev into release branches"});let a=[],c=[];for(let P of await O()){let W=jb(P);W?c.push({branch:P.branch,reason:W}):a.push(P.branch)}if(a.length===0)return l.info(c.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${c.length} skipped (${Fb(c)})`),g.print(),Im(Mb(n,c));let d=await ar();try{await _b({cwd:d,quiet:!0})`git fetch origin --prune`}catch(P){throw new f(P,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?a:Lb(r,a,c),u=await $d({cwd:d},async P=>{let W=Cm(P.remove);try{return await Ub({cwd:d,worktree:P,toPlan:p,candidates:a,skipped:c,all:t,versions:r,dryRun:n,verify:i,confirmedCommand:s})}finally{W()}}),{entries:m,selected:h,pushed:y,pushAborted:v,abortedBy:I,declined:j,verifyFailed:F}=u,C=await ir(d).catch(()=>[]);return Kb({entries:m,selected:h,pushed:y,pushAborted:v,abortedBy:I,declined:j,verifyFailed:F,dryRun:n,worktrees:C,skipped:c})},Ub=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:d,confirmedCommand:p}=e,u=await Em({cwd:t,worktreePath:r.path,branches:n}),m={entries:u,pushed:!1,pushAborted:!1,declined:!1};if(Vb(u,s),c)return{...m,selected:n};let h=await Wb({entries:u,toPlan:n,all:i,explicit:a!==void 0});h.length===o.length?g.addOption("--all",!0):g.addOption("--versions",h);let y=u.filter(v=>h.includes(v.branch)&&v.mergeSha).length;y>0&&l.info(`
377
+ \u2139\uFE0F This will push ${y} branch(es), re-running CI on ${y} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await Q(p,`Are you sure you want to merge dev into these branches: ${h.join(", ")}?`,{throwOnDecline:!0})}catch(v){if(!Mo(v))throw v;return{...m,selected:h,declined:!0}}return p||g.addOption("--yes",!0),{entries:u,selected:h,declined:!1,...await Gb({cwd:t,worktreePath:r.path,entries:u,selected:h,verify:d})}},Kb=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:d,skipped:p}=e,u=new Set(n?t.filter(v=>r.includes(v.branch)&&v.mergeSha&&!d?.has(v.branch)).map(v=>v.branch):[]),m=t.filter(v=>r.includes(v.branch)).map(v=>{let I=!!v.mergeSha,j=e.verifyFailed?.get(v.branch),F=o&&I?"push-aborted":v.status,C=j?"verify-failed":F;return{branch:v.branch,status:C,mergeSha:v.mergeSha,conflictPaths:v.conflictPaths,pushed:u.has(v.branch),reason:j??v.reason}}),h=m.filter(v=>!$m.has(v.status));for(let v of m){let I=t.find(j=>j.branch===v.branch);l.info({branch:v.branch,status:v.status,mergeSha:v.mergeSha,conflictCount:v.conflictPaths?.length??0,durationMs:I?.durationMs,pushed:v.pushed,msg:"merge-dev branch result"})}if(i||a)l.info(i?`
410
378
  Operation cancelled \u2014 nothing was pushed.
411
379
  `:`
412
380
  \u{1F50D} Dry run \u2014 nothing was pushed.
413
- `);else if(m.length>0){l.info(`
414
- \u26A0\uFE0F ${m.length} branch(es) did not merge.
415
- `);for(let f of m)l.info(`# ${f.branch} \u2014 ${f.status}
416
- ${Ub(f.branch,c)}
381
+ `);else if(h.length>0){l.info(`
382
+ \u26A0\uFE0F ${h.length} branch(es) did not merge.
383
+ `);for(let v of h)l.info(`# ${v.branch} \u2014 ${v.status}
384
+ ${Bb(v.branch,c)}
417
385
  `)}else l.info(`\u2705 All merges completed successfully!
418
- `);h.print();let v=a||i;return Wm({successfulMerges:v?0:u.filter(f=>Lm.has(f.status)).length,failedMerges:v?0:m.length,failedBranches:v?[]:m.map(f=>f.branch),totalBranches:u.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:u.map(f=>v?{...f,pushed:!1}:f)})},bc=k({name:"gh-merge-dev",description:"Merge origin/dev into open regular (non-hotfix) release branches and push them in one atomic push. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:x.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:x.union([x.string(),x.array(x.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error \u2014 hotfix branches cannot be selected. Takes precedence over `all`.'),dryRun:x.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:x.union([x.boolean(),x.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push."),confirm:x.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:x.number().describe("Number of branches that reached their desired state"),failedMerges:x.number().describe("Number of branches that did not"),failedBranches:x.array(x.string()).describe("List of branches that did not merge"),totalBranches:x.number().describe("Total number of branches processed"),dryRun:x.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:x.object({attempted:x.boolean(),aborted:x.boolean(),abortedBy:x.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:x.array(x.object({branch:x.string(),status:x.string(),mergeSha:x.string().optional(),conflictPaths:x.array(x.string()).optional(),pushed:x.boolean(),reason:x.string().optional()})).describe("Per-branch terminal state")},handler:Os});import{z as so}from"zod";import{$ as Se}from"zx";var Jm=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},Ir=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let n=r.exitCode;(typeof n=="number"||n===null)&&(t.exitCode=n);let o=Jm(r.stderr,500);o&&(t.stderr=o);let s=Jm(r.stdout,200);return s&&(t.stdout=s),t};var to=e=>{let{removed:r,failed:t}=e;if(r.length>0){l.info("\u274C Removed worktrees:");for(let n of r)l.info(n);l.info("")}if(t.length>0){l.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of t)l.warn(`${n} \u2014 ${o}`);l.warn("")}r.length===0&&t.length===0&&l.info("\u2139\uFE0F No worktrees to remove")};var no=e=>{let{result:r,operation:t}=e,n={removedWorktrees:r.removed,failedWorktrees:r.failed.map(i=>i.branch),count:r.removed.length},o=w(JSON.stringify(n,null,2));if(r.failed.length===0)return{content:o,structuredContent:n};let s={operation:t,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:r.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw ne()?new A({status:"partial_failure",...n},1,s):new g(void 0,s)};import Ns from"node:fs/promises";import{$ as Km}from"zx";var Yb=new Set([".omc",".DS_Store"]),Zb=new Set(["state","sessions"]),Xb=2e3,Qb="check 'git worktree list' for the path; uncommitted changes block removal",eR=e=>new Promise(r=>{setTimeout(r,e)}),Rc=e=>typeof e=="object"&&e!==null?e.code:void 0,Bm=e=>{let r=e.length;for(;r>1&&e[r-1]==="/";)r-=1;return e.slice(0,r)},Gm=async e=>{try{return Bm(await Ns.realpath(e))}catch{return Bm(e)}},rR=async e=>{let{projectRoot:r,worktreePath:t}=e;try{let n=await yt(r),o=await Gm(t);for(let s of n)if(await Gm(s.path)===o)return!0;return!1}catch{return!0}},tR=async e=>{let r;try{r=await Ns.readdir(e)}catch(n){return{kind:Rc(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!r.every(n=>Yb.has(n)))return{kind:"not-sweepable",entries:r};if(!r.includes(".omc"))return{kind:"sweepable",entries:r};try{return{kind:(await Ns.readdir(`${e}/.omc`)).every(s=>Zb.has(s))?"sweepable":"not-sweepable",entries:r}}catch(n){return{kind:Rc(n)==="ENOENT"?"sweepable":"not-sweepable",entries:r}}},Um=async e=>{try{return await Ns.rm(e,{recursive:!0,force:!0}),"removed"}catch(r){return Rc(r)==="ENOTEMPTY"?"busy":"failed"}},nR=async e=>{let{worktreePath:r,sleep:t}=e,n=await Um(r);return n!=="busy"?n==="removed":(await t(Xb),await Um(r)==="removed")},Ds=(e,r,t)=>{let n=new g(r,{operation:`remove worktree for ${e}`,remediation:t});return l.error({error:r,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},oR=async e=>{let{branch:r,worktreePath:t,projectRoot:n,error:o,sleep:s}=e;if(await rR({projectRoot:n,worktreePath:t}))return Ds(r,o,Qb);let i=await tR(t);if(i.kind==="gone")return{branch:r,status:"removed"};let a=`git already unregistered this worktree; inspect and remove it manually: rm -r ${t}`;return i.kind==="not-sweepable"||!await nR({worktreePath:t,sleep:s})?Ds(r,o,a):(l.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${t}: 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:r,status:"removed"})},sR=async e=>{let{branch:r,worktreeDir:t,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${t}/${r}`,a=await ap(i,o);if(!a.closed&&"error"in a)return Ds(r,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await Km`git worktree remove ${i}`,{branch:r,status:"removed"}}catch(c){return oR({branch:r,worktreePath:i,projectRoot:n,error:c,sleep:s})}},ct=async e=>{let{branches:r,worktreeDir:t,projectRoot:n,pruneFolder:o=!1,sleep:s=eR}=e,i=r.length>0?await bt():"unreachable",a=await Promise.all(r.map(d=>sR({branch:d,worktreeDir:t,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let d of a)d.status==="removed"?c.removed.push(d.branch):c.failed.push({branch:d.branch,reason:d.reason});return o&&c.removed.length===r.length&&await Km`git worktree prune`,c};var oo=async(e,r)=>{if(!(await ke("release")).includes(e))return[];let n=await b(),o=`${n}${ye}`,{removed:s,failed:i}=await ct({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...r,stderrExcerpt:a?.reason})}return s};var sn=async(e,r,t)=>{try{return await t()}catch(n){throw l.debug({err:Ir(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:r})}},iR=async e=>{let r=Ri(e),t=await Se`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},qm=async()=>{let e=await Se`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},aR=async e=>{let r=or(e),t=await it(r);if(!t)throw l.error(`\u274C No PR found for branch ${r}.`),new g(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},cR=async()=>{let e=await _(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,D(i.title)]));h.setInteractive();let n=await U(),o=await Cr(le({branches:r,descriptions:n,types:t})),s=e.find(i=>i.branch===o);if(!s)throw l.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});return{selectedReleaseBranch:o,releasePrTitle:s.title}},lR=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,n=t==="hotfix"?"main":"dev",o=await it(r);if(!o)throw new g(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(o.state==="MERGED"){l.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(o.state==="CLOSED")throw new g(void 0,{operation:`merge release PR ${r} into ${n}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await sn(`merge release PR ${r} into ${n}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await Se`gh pr merge ${r} --squash --admin --delete-branch`})},dR=async e=>{let r=B(e),t=Ri(e),n=await qm();if(n){let s=n.number;return n.title!==t&&(l.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${r}`),await sn(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await Se`gh pr edit ${s} --title ${t}`})),s}await sn(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await Se`gh pr create --base main --head dev --title ${t} --body ""`});let o=await qm();if(!o)throw new g(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},pR=async e=>{let r=B(e);if(await iR(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let n=await dR(e);await sn(`merge RC PR #${n} (dev \u2192 main) for ${r}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Se`gh pr merge ${n} --squash --admin`})},uR=async()=>{Se.quiet=!1,await sn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await Se`gh workflow run deploy-all.yml --ref main -f environment=prod`}),Se.quiet=!0},mR=async()=>{await sn("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 Se`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},fR=async e=>{try{await Do(e)}catch(r){l.warn({err:Ir(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await No(e)}catch(r){l.warn({err:Ir(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},gR=async e=>{let r=await nr();if(!r){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=Y(e);await Xa({versionName:t},r)}catch(t){let n=Un(t)&&t.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";l.error({err:Ir(t)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ms=async e=>{let{version:r,confirmedCommand:t}=e;await ge({operation:"deliver release"});let{selectedReleaseBranch:n,releasePrTitle:o}=r?await aR(r):await cR(),s=L(n);if(!s)throw new g(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=B(s);h.addOption("--version",i),l.info(`Delivering ${s.kind==="name"?"named release":"version"} ${n}`);let a=D(o);if(ne())throw new A({status:"refused",agentMode:I.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 se(t,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),Se.quiet=!0;let d=`${await b()}${ye}`;await oo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${d}/${n} (use --force if uncommitted changes)`}),await lR({selectedReleaseBranch:n,releaseType:a}),a!=="hotfix"&&await pR(s),await uR(),await mR(),await fR(n),Se.quiet=!1,await gR(s),l.info(`Successfully delivered ${n} to production!`),h.print();let p={releaseBranch:n,version:i,type:a,success:!0};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}},Ec=k({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:so.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:so.string().describe("The release branch that was delivered"),version:so.string().describe("The version that was delivered"),type:so.enum(["regular","hotfix"]).describe("Release type"),success:so.boolean().describe("Whether the delivery was successful")},handler:Ms});import{z as sr}from"zod";import{$ as Oc}from"zx";import{z as co}from"zod";import Hm from"node:fs/promises";import Pc from"node:path";var zm=".github/workflows",hR=/script_name:\s*(?<service>[a-z0-9-]+)/,vR=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,yR=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Sc=async e=>{let r=Pc.resolve(e,zm),t;try{t=await Hm.readdir(r)}catch{return new Map}return Ym(r,t.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},io=async(e,r)=>Ym(Pc.resolve(e,zm),[r]),Ym=async(e,r)=>{let t=new Map;for(let n of r){let o;try{o=await Hm.readFile(Pc.resolve(e,n),"utf-8")}catch{continue}wR(o,t)}return t},wR=(e,r)=>{for(let t of e.split(/\n(?= {2}[\w-]+:)/i)){let n=hR.exec(t)?.groups?.service??vR.exec(t)?.groups?.service;if(n===void 0||t.trimStart().startsWith("#"))continue;let o=[...t.matchAll(yR)].map(s=>s.groups?.env??"");o.length!==0&&r.set(n,[...new Set([...r.get(n)??[],...o])])}},xc=(e,r)=>e===null?r??null:r===void 0?e:e.filter(t=>r.includes(t));import kR from"node:fs/promises";import bR from"node:path";import RR from"yaml";var ER=".github/workflows",PR="skip_terraform_deploy",ao=async(e,r)=>{let t=bR.resolve(e,ER,r),n;try{n=RR.parse(await kR.readFile(t,"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!==PR).map(([i])=>i)};var Zm="dev",Tc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Xm=(e,r)=>e[r]===void 0,Qm=(e,r)=>{let t=e[r];return typeof t=="string"&&t.length>0?t:void 0},Ac=async e=>{try{return await e}catch{return[]}},SR=async()=>{let e=await _();return st(e.map(r=>r.branch))},xR=(e,r)=>{let t=e.filter(o=>r.get(o)!==void 0);if(t.length===0)return"none declared.";let n=t.map(o=>`${o}: ${(r.get(o)??[]).join(", ")} only.`).join(" ");return t.length<e.length?`${n} Others: any environment.`:n},lt=e=>{let{workflowFile:r,fields:t,toolName:n}=e,o=c=>(l.info({msg:`Tool execution form options empty (${r}): ${n}`,emptyList:c}),null),s=async c=>{let d=await Ac(SR());if(d.length===0)return null;let p=Qm(c,"version");return co.enum([...new Set([...d,Zm])]).optional().describe(`Which release to deploy from. "${Zm}" deploys from the dev branch instead of a release branch. ${p===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 "${p}".`}`)},i=async c=>{let d=Ze(await Ac(Qe(r)),await Xe());if(d.length===0)return null;let p=d.filter(jt),u=d.filter(v=>!jt(v)),m=Qm(c,"env");return co.enum(d).optional().describe(`Target environment. Shared with the whole team: ${p.length>0?p.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${r} 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 b(),d=await Ac(ao(c,r));if(d.length===0)return null;let p=await io(c,r);return co.array(co.enum(d)).optional().describe(`Services to deploy. Environment gates declared by ${r} \u2014 ${xR(d,p)} 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=>Tc(c)?t.some(d=>Xm(c,d)):!1,buildRequestedSchema:async c=>{let d=Tc(c)?c:{},p={};if(t.includes("version")){let u=await s(d);if(u===null)return o("releases");p.version=u}if(t.includes("env")){let u=await i(d);if(u===null)return o("envs");p.env=u}if(t.includes("services")&&Xm(d,"services")){let u=await a();if(u===null)return o("services");p.services=u}return Object.keys(p).length===0?o("fields"):co.object(p)},toArgs:(c,d)=>{let p={...Tc(d)?d:{}};for(let u of t){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;p[u]=m}}return p}}};import TR from"@inquirer/select";var an=async(e,r)=>{if(e.length===0)throw new g(void 0,{operation:r,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return S(t=>TR({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},t),{whenHeadless:"refuse"})};import AR from"@inquirer/confirm";var lo=async e=>{let{confirmedCommand:r,branch:t,env:n}=e;if(r)return!0;let o=`Deploy ${t} \u2192 ${n} via GitHub Actions?`;we()&&Jo(o,{branch:t,env:n}),h.setInteractive();let s=await S(i=>AR({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import CR from"@inquirer/select";import IR from"node:process";var Cc=()=>!we()&&IR.stdin.isTTY===!0,$R={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Ic=async()=>S(e=>CR({message:"\u{1F680} Where should this deploy run?",choices:$r.map(r=>({name:r,value:r,description:$R[r]}))},e),{whenHeadless:"refuse"});var $r=["ci","local"],_R={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},ef=e=>{if(!e){let t={operation:"resolve the deploy source",remediation:`pass --from with one of: ${$r.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw we()?new A({status:"argument_required",argument:"from",agentMode:I.source},2,t):new g(void 0,t)}let r=$r.find(t=>t===e);if(!r)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${$r.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return r},$c=(e,r)=>{let n=_R[e==="ci"?"local":"ci"].filter(o=>{let s=r[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},_c=async e=>e||!Cc()?ef(e):Ic();var po=async e=>{if(e)return e==="dev"?"dev":or(e);h.setInteractive();let r=await _(),t=r.map(s=>s.branch),n=new Map(r.map(s=>[s.branch,D(s.title)])),o=await U();return Cr([{value:"dev",label:"dev"},...le({branches:t,descriptions:o,types:n})])};var rf="deploy-all.yml",tf=lt({workflowFile:rf,fields:["version","env"],toolName:"gh-release-deploy-all"}),js=async e=>{let{version:r,env:t,skipTerraform:n,confirmedCommand:o}=e;await Ee({provider:tf,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await po(r),i=Xn(s);h.addOption("--version",i);let a=await Xe(),c=Ze(await Qe(rf),a),d="";t?d=t:(h.setInteractive(),d=await an(c,"launch deploy-all workflow")),h.addOption("--env",d),qr(d,"launch deploy-all workflow",a),On({env:d,branch:s});let p=n??!1;if(p&&h.addOption("--skip-terraform",!0),!await lo({confirmedCommand:o,branch:s,env:d})){l.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:d,skipTerraformDeploy:p,success:!1};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}}try{Oc.quiet=!0,await Oc`gh workflow run deploy-all.yml --ref ${s} -f environment=${d} ${p?["-f","skip_terraform_deploy=true"]:[]}`,Oc.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${d}`),h.print();let m={releaseBranch:s,version:i,environment:d,skipTerraformDeploy:p,success:!0};return{content:w(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw l.error({error:u},"\u274C Error launching workflow"),new g(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Dc=k({name:"gh-release-deploy-all",formProvider:tf,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:sr.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:sr.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:sr.boolean().optional().describe("Skip the terraform deployment stage."),confirm:sr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:sr.string().describe("The release branch that was deployed"),version:sr.string().describe("The version that was deployed"),environment:sr.string().describe("The environment deployed to"),skipTerraformDeploy:sr.boolean().describe("Whether terraform deployment was skipped"),success:sr.boolean().describe("Whether the deployment was successful")},handler:js});import OR from"@inquirer/checkbox";import{z as he}from"zod";import{$ as Nc}from"zx";var dt="deploy-selected-services.yml",nf=lt({workflowFile:dt,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Fs=async e=>{let{version:r,env:t,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ee({provider:nf,params:e,operation:"launch deploy-selected workflow",argument:O=>O[0]??"version"});let i=await po(r),a=Xn(i);h.addOption("--version",a);let c=await Xe(),d=Ze(await Qe(dt),c),p="";t?p=t:(h.setInteractive(),p=await an(d,"launch deploy-selected workflow")),h.addOption("--env",p),qr(p,"launch deploy-selected workflow",c),On({env:p,branch:i});let u=await b(),m=await ao(u,dt);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${dt}`,stderrExcerpt:`no services found in .github/workflows/${dt}`});let v=[];if(n&&n.length>0?v=n:(h.setInteractive(),v=await S(O=>OR({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(R=>({name:R,value:R}))},O),{whenHeadless:"refuse"})),h.addOption("--services",v),v.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let f=v.filter(O=>!m.includes(O));if(f.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${f.join(", ")}`});let T=await io(u,dt),C=v.filter(O=>{let R=T.get(O);return R!==void 0&&!R.includes(p)});if(C.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:C.map(O=>`${O} deploys only to: ${(T.get(O)??[]).join(", ")}`).join("; "),stderrExcerpt:`${dt} gates these services out of ${p}: ${C.join(", ")}`});let ee=o??!1;ee&&h.addOption("--skip-terraform",!0);let re=O=>{let R={releaseBranch:i,version:a,environment:p,services:v,skipTerraformDeploy:ee,success:O};return{content:w(JSON.stringify(R,null,2)),structuredContent:R}};if(!await lo({confirmedCommand:s,branch:i,env:p}))return l.info("Deployment cancelled"),re(!1);try{Nc.quiet=!0;let O=v.flatMap(Nr=>["-f",`${Nr}=true`]);return await Nc`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${O} ${ee?["-f","skip_terraform_deploy=true"]:[]}`,Nc.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${v.join(", ")}`),h.print(),re(!0)}catch(O){throw l.error({error:O},"\u274C Error launching workflow"),new g(O,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Mc=k({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:nf,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:he.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:he.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:he.array(he.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:he.boolean().optional().describe("Skip the terraform deployment stage."),confirm:he.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:he.string().describe("The release branch that was deployed"),version:he.string().describe("The version that was deployed"),environment:he.string().describe("The environment deployed to"),services:he.array(he.string()).describe("The services that were deployed"),skipTerraformDeploy:he.boolean().describe("Whether terraform deployment was skipped"),success:he.boolean().describe("Whether the deployment was successful")},handler:Fs});import{z as cn}from"zod";var Ls=async()=>{let r=(await _()).flatMap(i=>{let a=L(i.branch);return a?[{version:B(a),jiraKey:Y(a),type:D(i.title)}]:[]}),t=await U(),n=Math.max(...r.map(i=>i.version.length)),o=r.map(i=>{let a=Zn(i.version,i.type,n),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
386
+ `);g.print();let y=a||i;return Im({successfulMerges:y?0:m.filter(v=>$m.has(v.status)).length,failedMerges:y?0:h.length,failedBranches:y?[]:h.map(v=>v.branch),totalBranches:m.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:m.map(v=>y?{...v,pushed:!1}:v),skipped:p})},fc=b({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:S.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:S.union([S.string(),S.array(S.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:S.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:S.union([S.boolean(),S.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push."),confirm:S.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:S.number().describe("Number of branches that reached their desired state"),failedMerges:S.number().describe("Number of branches that did not"),failedBranches:S.array(S.string()).describe("List of branches that did not merge"),totalBranches:S.number().describe("Total number of branches processed"),dryRun:S.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:S.object({attempted:S.boolean(),aborted:S.boolean(),abortedBy:S.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:S.array(S.object({branch:S.string(),status:S.string(),mergeSha:S.string().optional(),conflictPaths:S.array(S.string()).optional(),pushed:S.boolean(),reason:S.string().optional()})).describe("Per-branch terminal state"),skipped:S.array(S.object({branch:S.string(),reason:S.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:Ts});import{z as Zn}from"zod";import{$ as be}from"zx";var Om=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},yt=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=Om(t.stderr,500);o&&(r.stderr=o);let s=Om(t.stdout,200);return s&&(r.stdout=s),r};var Yn=e=>{let{removed:t,failed:r}=e;if(t.length>0){l.info("\u274C Removed worktrees:");for(let n of t)l.info(n);l.info("")}if(r.length>0){l.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)l.warn(`${n} \u2014 ${o}`);l.warn("")}t.length===0&&r.length===0&&l.info("\u2139\uFE0F No worktrees to remove")};var zn=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 Z()?new T({status:"partial_failure",...n},1,s):new f(void 0,s)};import As from"node:fs/promises";import{$ as jm}from"zx";var qb=new Set([".omc",".DS_Store"]),Hb=new Set(["state","sessions"]),Yb=2e3,zb="check 'git worktree list' for the path; uncommitted changes block removal",Xb=e=>new Promise(t=>{setTimeout(t,e)}),gc=e=>typeof e=="object"&&e!==null?e.code:void 0,Nm=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},_m=async e=>{try{return Nm(await As.realpath(e))}catch{return Nm(e)}},Zb=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await ir(t),o=await _m(r);for(let s of n)if(await _m(s.path)===o)return!0;return!1}catch{return!0}},Qb=async e=>{let t;try{t=await As.readdir(e)}catch(n){return{kind:gc(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>qb.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await As.readdir(`${e}/.omc`)).every(s=>Hb.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:gc(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Mm=async e=>{try{return await As.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return gc(t)==="ENOTEMPTY"?"busy":"failed"}},eR=async e=>{let{worktreePath:t,sleep:r}=e,n=await Mm(t);return n!=="busy"?n==="removed":(await r(Yb),await Mm(t)==="removed")},Cs=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return l.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},tR=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await Zb({projectRoot:n,worktreePath:r}))return Cs(t,o,zb);let i=await Qb(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 eR({worktreePath:r,sleep:s})?Cs(t,o,a):(l.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"})},rR=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await Kd(i,o);if(!a.closed&&"error"in a)return Cs(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await jm`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return tR({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},qt=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=Xb}=e,i=t.length>0?await lr():"unreachable",a=await Promise.all(t.map(d=>rR({branch:d,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let d of a)d.status==="removed"?c.removed.push(d.branch):c.failed.push({branch:d.branch,reason:d.reason});return o&&c.removed.length===t.length&&await jm`git worktree prune`,c};var Xn=async(e,t)=>{if(!(await ve("release")).includes(e))return[];let n=await R(),o=`${n}${he}`,{removed:s,failed:i}=await qt({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 Yr=async(e,t,r)=>{try{return await r()}catch(n){throw l.debug({err:yt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},nR=async e=>{let t=ui(e),r=await be`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},Fm=async()=>{let e=await be`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},oR=async e=>{let t=Qe(e),r=await dc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await qr(t);if(!n)throw l.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=Bn(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}},sR=async()=>{let e=await O(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));g.setInteractive();let n=await X(),o=await vt(se({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw l.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}},iR=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Je(r),s=await pc(n);if(s.state==="MERGED"){l.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 Yr(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await be`gh pr merge ${n} --squash --admin --delete-branch`})},aR=async e=>{let t=B(e),r=ui(e),n=await Fm();if(n){let s=n.number;return n.title!==r&&(l.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Yr(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await be`gh pr edit ${s} --title ${r}`})),s}await Yr(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await be`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Fm();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},cR=async e=>{let t=B(e);if(await nR(e)){l.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await aR(e);await Yr(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await be`gh pr merge ${n} --squash --admin`})},lR=async()=>{be.quiet=!1,await Yr("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await be`gh workflow run deploy-all.yml --ref main -f environment=prod`}),be.quiet=!0},dR=async()=>{await Yr("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await be`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},pR=async e=>{try{await To(e)}catch(t){l.warn({err:yt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Co(e)}catch(t){l.warn({err:yt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},uR=async e=>{let t=await Ze();if(!t){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=Y(e);await Ma({versionName:r},t)}catch(r){let n=In(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";l.error({err:yt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},$s=async e=>{let{version:t,confirmedCommand:r}=e;await ue({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await oR(t):await sR(),i=L(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=B(i);if(g.addOption("--version",a),l.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),Z())throw new T({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 Q(r,`Are you sure you want to deliver version ${n} to production?`),g.addOption("--yes",!0),be.quiet=!0;let d=`${await R()}${he}`;await Xn(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${d}/${n} (use --force if uncommitted changes)`}),await iR({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await cR(i),await lR(),await dR(),await pR(n),be.quiet=!1,await uR(i),l.info(`Successfully delivered ${n} to production!`),g.print();let p={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},hc=b({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:Zn.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:Zn.string().describe("The release branch that was delivered"),version:Zn.string().describe("The version that was delivered"),type:Zn.enum(["regular","hotfix"]).describe("Release type"),success:Zn.boolean().describe("Whether the delivery was successful")},handler:$s});import{z as et}from"zod";import{$ as xc}from"zx";import{z as to}from"zod";import Lm from"node:fs/promises";import vc from"node:path";var Jm=".github/workflows",mR=/script_name:\s*(?<service>[a-z0-9-]+)/,fR=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,gR=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,yc=async e=>{let t=vc.resolve(e,Jm),r;try{r=await Lm.readdir(t)}catch{return new Map}return Vm(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Qn=async(e,t)=>Vm(vc.resolve(e,Jm),[t]),Vm=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await Lm.readFile(vc.resolve(e,n),"utf-8")}catch{continue}hR(o,r)}return r},hR=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=mR.exec(r)?.groups?.service??fR.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(gR)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},wc=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import vR from"node:fs/promises";import yR from"node:path";import wR from"yaml";var kR=".github/workflows",bR="skip_terraform_deploy",eo=async(e,t)=>{let r=yR.resolve(e,kR,t),n;try{n=wR.parse(await vR.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!==bR).map(([i])=>i)};var Bm="dev",kc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wm=(e,t)=>e[t]===void 0,Gm=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},bc=async e=>{try{return await e}catch{return[]}},RR=async()=>{let e=await O();return Ut(e.map(t=>t.branch))},PR=(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},Ht=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(l.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let d=await bc(RR());if(d.length===0)return null;let p=Gm(c,"version");return to.enum([...new Set([...d,Bm])]).optional().describe(`Which release to deploy from. "${Bm}" deploys from the dev branch instead of a release branch. ${p===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 "${p}".`}`)},i=async c=>{let d=He(await bc(ze(t)),await Ye());if(d.length===0)return null;let p=d.filter(Ar),u=d.filter(h=>!Ar(h)),m=Gm(c,"env");return to.enum(d).optional().describe(`Target environment. Shared with the whole team: ${p.length>0?p.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 R(),d=await bc(eo(c,t));if(d.length===0)return null;let p=await Qn(c,t);return to.array(to.enum(d)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${PR(d,p)} 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=>kc(c)?r.some(d=>Wm(c,d)):!1,buildRequestedSchema:async c=>{let d=kc(c)?c:{},p={};if(r.includes("version")){let u=await s(d);if(u===null)return o("releases");p.version=u}if(r.includes("env")){let u=await i(d);if(u===null)return o("envs");p.env=u}if(r.includes("services")&&Wm(d,"services")){let u=await a();if(u===null)return o("services");p.services=u}return Object.keys(p).length===0?o("fields"):to.object(p)},toArgs:(c,d)=>{let p={...kc(d)?d:{}};for(let u of r){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;p[u]=m}}return p}}};import ER from"@inquirer/select";var zr=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 x(r=>ER({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import SR from"@inquirer/confirm";var ro=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ae()&&jo(o,{branch:r,env:n}),g.setInteractive();let s=await x(i=>SR({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&g.addOption("--yes",!0),s};import xR from"@inquirer/select";import TR from"node:process";var Rc=()=>!ae()&&TR.stdin.isTTY===!0,CR={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Pc=async()=>x(e=>xR({message:"\u{1F680} Where should this deploy run?",choices:wt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:CR[t]}))},e),{whenHeadless:"refuse"});var wt=["ci","local"],AR={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Um=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${wt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ae()?new T({status:"argument_required",argument:"from",agentMode:A.source},2,r):new f(void 0,r)}let t=wt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${wt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Ec=(e,t)=>{let n=AR[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}`})},Sc=async e=>e||!Rc()?Um(e):Pc();var no=async e=>{if(e)return e==="dev"?"dev":Qe(e);g.setInteractive();let t=await O(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await X();return vt([{value:"dev",label:"dev"},...se({branches:r,descriptions:o,types:n})])};var Km="deploy-all.yml",qm=Ht({workflowFile:Km,fields:["version","env"],toolName:"gh-release-deploy-all"}),Is=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await ke({provider:qm,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await no(t),i=Un(s);g.addOption("--version",i);let a=await Ye(),c=He(await ze(Km),a),d="";r?d=r:(g.setInteractive(),d=await zr(c,"launch deploy-all workflow")),g.addOption("--env",d),Mt(d,"launch deploy-all workflow",a),$n({env:d,branch:s});let p=n??!1;if(p&&g.addOption("--skip-terraform",!0),!await ro({confirmedCommand:o,branch:s,env:d})){l.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:d,skipTerraformDeploy:p,success:!1};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}try{xc.quiet=!0,await xc`gh workflow run deploy-all.yml --ref ${s} -f environment=${d} ${p?["-f","skip_terraform_deploy=true"]:[]}`,xc.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${d}`),g.print();let m={releaseBranch:s,version:i,environment:d,skipTerraformDeploy:p,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw l.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"})}},Tc=b({name:"gh-release-deploy-all",formProvider:qm,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:et.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:et.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:et.boolean().optional().describe("Skip the terraform deployment stage."),confirm:et.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:et.string().describe("The release branch that was deployed"),version:et.string().describe("The version that was deployed"),environment:et.string().describe("The environment deployed to"),skipTerraformDeploy:et.boolean().describe("Whether terraform deployment was skipped"),success:et.boolean().describe("Whether the deployment was successful")},handler:Is});import $R from"@inquirer/checkbox";import{z as me}from"zod";import{$ as Cc}from"zx";var Yt="deploy-selected-services.yml",Hm=Ht({workflowFile:Yt,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Ds=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await ke({provider:Hm,params:e,operation:"launch deploy-selected workflow",argument:C=>C[0]??"version"});let i=await no(t),a=Un(i);g.addOption("--version",a);let c=await Ye(),d=He(await ze(Yt),c),p="";r?p=r:(g.setInteractive(),p=await zr(d,"launch deploy-selected workflow")),g.addOption("--env",p),Mt(p,"launch deploy-selected workflow",c),$n({env:p,branch:i});let u=await R(),m=await eo(u,Yt);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Yt}`,stderrExcerpt:`no services found in .github/workflows/${Yt}`});let h=[];if(n&&n.length>0?h=n:(g.setInteractive(),h=await x(C=>$R({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},C),{whenHeadless:"refuse"})),g.addOption("--services",h),h.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=h.filter(C=>!m.includes(C));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 v=await Qn(u,Yt),I=h.filter(C=>{let P=v.get(C);return P!==void 0&&!P.includes(p)});if(I.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:I.map(C=>`${C} deploys only to: ${(v.get(C)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Yt} gates these services out of ${p}: ${I.join(", ")}`});let j=o??!1;j&&g.addOption("--skip-terraform",!0);let F=C=>{let P={releaseBranch:i,version:a,environment:p,services:h,skipTerraformDeploy:j,success:C};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await ro({confirmedCommand:s,branch:i,env:p}))return l.info("Deployment cancelled"),F(!1);try{Cc.quiet=!0;let C=h.flatMap(W=>["-f",`${W}=true`]);return await Cc`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${C} ${j?["-f","skip_terraform_deploy=true"]:[]}`,Cc.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${h.join(", ")}`),g.print(),F(!0)}catch(C){throw l.error({error:C},"\u274C Error launching workflow"),new f(C,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Ac=b({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Hm,description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:me.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:me.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:me.array(me.string()).optional().describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:me.boolean().optional().describe("Skip the terraform deployment stage."),confirm:me.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:me.string().describe("The release branch that was deployed"),version:me.string().describe("The version that was deployed"),environment:me.string().describe("The environment deployed to"),services:me.array(me.string()).describe("The services that were deployed"),skipTerraformDeploy:me.boolean().describe("Whether terraform deployment was skipped"),success:me.boolean().describe("Whether the deployment was successful")},handler:Ds});import{z as kt}from"zod";var Os=async()=>{let t=(await O()).flatMap(i=>{let a=L(i.branch);return a?[{version:B(a),jiraKey:Y(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await bs(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Gn(i.version,i.type,n),c=r.get(i.jiraKey),d=c?.description?` ${c.description}`:"",p=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",u=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${d}${p}${u}`});l.info(`All release branches:
419
387
  `),l.info(`
420
388
  ${o.join(`
421
389
  `)}
422
- `);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:w(JSON.stringify(s,null,2)),structuredContent:s}},jc=k({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:cn.array(cn.object({version:cn.string().describe("Release version"),type:cn.enum(["regular","hotfix"]).describe("Release type"),description:cn.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:cn.number().describe("Number of release branches")},handler:Ls});import DR from"node:process";var Fc=e=>({...e}),Lc=e=>{let{env:r,branch:t,sha:n,isClean:o,ambient:s=DR.env}=e,i={VITE_DOMAIN_ENV:r,VITE_BRANCH_NAME:t,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[d,p]of Object.entries(s)){if(d.startsWith("VITE_")){c.push(d);continue}a[d]=p}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:r,DEPLOY_BRANCH:t,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},Ws=e=>{let r=Object.entries(e.contract).map(([t,n])=>` ${t.padEnd(17)}= ${n}`);return e.stripped.length>0&&r.push(` stripped from shell: ${e.stripped.join(", ")}`),r.join(`
423
- `)};import HR from"@inquirer/checkbox";import zR from"@inquirer/confirm";import YR from"@inquirer/select";import{spawn as ZR}from"node:child_process";import XR from"node:process";import{z as J}from"zod";import{$ as mo}from"zx";import{$ as uo}from"zx";var NR=async e=>{let r=uo.quiet;uo.quiet=!0;try{let t=`/${e}/environment`,n=await uo`aws sts get-caller-identity --query Account --output text`,o=await uo`aws ssm get-parameter --name ${t} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(t){throw new g(t,{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{uo.quiet=r}},of=(e,r)=>{if(r.stage!==e)throw new g(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${r.accountId} reports "${r.stage}" \u2014 refusing to deploy to an environment you did not name`})},sf=e=>{let{env:r,isShared:t,isClean:n}=e;if(!(!t||n))throw new g(void 0,{operation:`deploy to shared environment "${r}"`,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"})},af=(e,r)=>{if(r.includes(e))throw new g(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Wc=async e=>{let{env:r,project:t,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;qr(r,`deploy to "${r}"`,i),af(r,s),sf({env:r,isShared:n,isClean:o});let a=await NR(t);return of(r,a),{identity:a}};import cf from"node:fs/promises";import Vs from"node:path";var MR="devops/scripts",jR=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,FR=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,LR=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,WR=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Vc=async e=>{let r=Vs.resolve(e,MR),t;try{t=await cf.readdir(r)}catch{return[]}let n=await Sc(e);return(await Promise.all(t.map(s=>({entry:s,match:jR.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Vs.resolve(r,s),c=i?.groups?.service??"",d=JR(await VR(a));return{name:c,scriptPath:a,allowedEnvs:xc(BR(d),n.get(c)),ssmPrefix:UR(d)}}))).sort((s,i)=>s.name.localeCompare(i.name))},VR=async e=>{try{return await cf.readFile(e,"utf-8")}catch{return""}},JR=e=>e.split(`
424
- `).map((r,t)=>({line:t+1,text:r})).filter(({text:r})=>!r.trimStart().startsWith("#")),BR=e=>{let r=e.reduce((n,{text:o})=>n??FR.exec(o)?.groups?.envs,void 0);if(r===void 0)return null;let t=r.split(/\s+/).filter(Boolean);return t.length>0?t:null},GR=e=>{let r=e.replaceAll(/["']/g,"");return r.includes("$")&&(r.includes("/environment")||r.startsWith("$"))},UR=e=>{for(let{line:r,text:t}of e){let n=WR.exec(t)?.groups?.prefix;if(n!==void 0)return n;let o=LR.exec(t)?.groups?.arg;if(o!==void 0&&GR(o))return{unparseable:{line:r,text:t.trim()}}}return null},KR=e=>{let r=new Map;for(let t of e)typeof t.ssmPrefix=="string"&&r.set(t.ssmPrefix,[...r.get(t.ssmPrefix)??[],Vs.basename(t.scriptPath)]);return r},qR=e=>{let r=e.flatMap(t=>{if(t.ssmPrefix===null||typeof t.ssmPrefix=="string")return[];let{line:n,text:o}=t.ssmPrefix.unparseable;return[`${Vs.basename(t.scriptPath)}:${n}: ${o}`]});if(r.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:r.join("; ")})},lf=e=>{qR(e);let r=KR(e),[t,...n]=r.keys();if(t===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...r.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${r.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return t},Js=(e,r)=>e.allowedEnvs===null||e.allowedEnvs.includes(r),Jc=(e,r)=>e.filter(t=>Js(t,r));var Gc="deploy-all.yml",pf="/bin/sh",QR=async()=>{let e=mo.quiet;mo.quiet=!0;try{let r=await mo`gh run list --workflow=${Gc} --status=in_progress --json displayTitle`;return JSON.parse(r.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{mo.quiet=e}},eE=async(e,r)=>{let t=e.map(o=>({name:o.name,value:o.name})),n=await S(o=>HR({message:`Deploy which services to ${r}?`,choices:t,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},rE=async e=>{let{env:r,isShared:t,names:n,accountId:o}=e,s=n.length,i=t?`"${r}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${r} from this machine?`;return we()&&Jo(i,{env:r,services:n,accountId:o,shared:t}),t?S(a=>YR({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${r}`,value:!0}]},a),{whenHeadless:"refuse"}):S(a=>zR({message:i,default:!1},a),{whenHeadless:"refuse"})},tE=(e,r,t)=>new Promise((n,o)=>{let s=ZR(pf,[e.scriptPath],{cwd:t,env:r,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),nE=async e=>{let{chosen:r,childEnv:t,cwd:n,env:o}=e,s=[],i=[];for(let a of r){l.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await tE(a,t,n);if(c!==0){i.push(a.name),l.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),l.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},oE=e=>{let{names:r,services:t,env:n}=e,o=new Map(t.map(a=>[a.name,a])),s=r.filter(a=>!o.has(a));if(s.length>0)throw new g(void 0,{operation:"resolve the requested services",remediation:`known services: ${t.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=r.filter(a=>{let c=o.get(a);return c!==void 0&&!Js(c,n)});if(i.length>0)throw new g(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return r.map(a=>o.get(a))},Bc=e=>{let{env:r,accountId:t,names:n,built:o,deployed:s,failed:i,dryRun:a,success:c}=e,d={environment:r,accountId:t,services:n,deployed:s,failed:i,contract:Fc(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:w(JSON.stringify(d,null,2)),structuredContent:d}},sE=async e=>{let{selection:r,eligible:t,service:n,env:o}=e;return r==="all"?t.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),eE(t,o))},uf=async(e,r)=>{let{env:t,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await b(),c=await Vc(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let d=lf(c);await Ee({provider:Uc[r],params:e,operation:"deploy locally",argument:"env"});let p=await Xe(),u=Ze(await Qe(Gc),p),m=t??"";m||(h.setInteractive(),m=await an(u,"deploy locally")),h.addOption("--env",m);let v=Jc(c,m);if(v.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let f=await sE({selection:r,eligible:v,service:n,env:m}),T=oE({names:f,services:c,env:m});if(r==="selected")for(let De of f)h.addOption("--service",De);let C=jt(m),ee=await kt(),re=(await mo`git rev-parse HEAD`.quiet()).stdout.trim(),O=await Md(),R=Lc({env:m,branch:ee,sha:re,isClean:O});i&&l.info(`Deploy contract for ${m}:
425
- ${Ws(R)}`);let lr=(await Wc({env:m,project:d,isShared:C,isClean:O,runningEnvs:await QR(),protectedEnvAccess:p})).identity.accountId;if(s)return l.info([`Would deploy to "${m}" (AWS account ${lr}) from this machine`,`Preflight parameter: /${d}/environment`,Ws(R),"Commands:",...T.map(De=>` ${pf} ${De.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
426
- `)),Bc({env:m,accountId:lr,names:f,built:R,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await rE({env:m,isShared:C,names:f,accountId:lr}))return l.info("Deployment cancelled"),Bc({env:m,accountId:lr,names:f,built:R,deployed:[],failed:[],dryRun:!1,success:!1});R.stripped.length>0&&l.info(`Stripped ambient VITE_* from the build env: ${R.stripped.join(", ")}`);let{deployed:Be,failed:dr}=await nE({chosen:T,childEnv:R.childEnv,cwd:a,env:m});return dr.length>0&&(l.error(`Partial deploy to "${m}": succeeded [${Be.join(", ")||"none"}], failed [${dr.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),XR.exitCode=1),h.print(),Bc({env:m,accountId:lr,names:f,built:R,deployed:Be,failed:dr,dryRun:!1,success:dr.length===0})},Bs=async e=>uf(e,"all"),Gs=async e=>uf(e,"selected"),mf='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.',ff={env:J.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:J.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:J.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},gf={environment:J.string().describe("Environment deployed to"),accountId:J.string().describe("AWS account the deploy targeted"),services:J.array(J.string()).describe("Services requested"),deployed:J.array(J.string()).describe("Services that completed successfully"),failed:J.array(J.string()).describe("Services that failed"),contract:J.record(J.string(),J.string()).describe("Build contract passed to the scripts"),strippedVars:J.array(J.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:J.boolean().describe("Whether this was a dry run"),success:J.boolean().describe("Whether every requested service deployed")},df=e=>lt({workflowFile:Gc,fields:["env"],toolName:e}),Uc={all:df("local-deploy-all"),selected:df("local-deploy-selected")},Kc=k({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${mf}`,requiresHumanConfirm:!0,formProvider:Uc.all,inputSchema:ff,outputSchema:gf,handler:Bs}),qc=k({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${mf}`,requiresHumanConfirm:!0,formProvider:Uc.selected,inputSchema:{...ff,service:J.array(J.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:gf,handler:Gs});import cE from"@inquirer/confirm";import Zc from"@inquirer/input";import yf from"@inquirer/select";import zc from"node:process";import{z as j}from"zod";import{z as Us}from"zod";var ln=async(e,r)=>new Promise(t=>{let n=setTimeout(()=>{t(null)},r);e.then(o=>{clearTimeout(n),t(o)},()=>{clearTimeout(n),t(null)})});var vf=2500,hf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iE=async()=>{let e=await qn();return{regular:Xt(e,"regular"),hotfix:Xt(e,"hotfix")}},aE=(e,r)=>e===null?(l.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${r/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(l.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).`,Hc=(e={})=>{let r=e.hintBudgetMs??vf;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:t=>hf(t)&&(t.releases===void 0||Array.isArray(t.releases)&&t.releases.length===0),buildRequestedSchema:async()=>{let t=await ln(iE(),r);return Us.object({type:Us.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Us.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign". ${aE(t,r)}`),description:Us.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none.")})},toArgs:(t,n)=>{let o=typeof t.release=="string"?t.release.trim():"";if(o==="")return null;let s=t.type==="hotfix"?"hotfix":"regular",i=typeof t.description=="string"&&t.description.trim()!==""?t.description.trim():void 0,a=Rs(o);return{...hf(n)?n:{},releases:[{...a,type:s,...i===void 0?{}:{description:i}}]}}}};var lE='"1.2.5" or "next"',Yc=(e,r)=>{try{return ac(e,r)}catch(t){throw t instanceof rt?new g(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof _d?new g(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},dE=async(e,r)=>{let t=Xt(e,r),n=t?` [${t}]`:"",o=(await S(i=>Zc({message:` Version (e.g. ${lE})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?t??"":o;return s===""&&(l.error("No version provided. Exiting..."),zc.exit(1)),s},pE=async()=>{let e=(await S(r=>Zc({message:' Name (kebab-case, e.g. "checkout-redesign"): '},r),{whenHeadless:"refuse"})).trim();e===""&&(l.error("No name provided. Exiting..."),zc.exit(1));try{_o(e)}catch(r){let t=r instanceof Error?r.message:String(r);l.error(`${t} Exiting...`),zc.exit(1)}return e},uE=async e=>{h.setInteractive();let r=null,t=[],n=async()=>(r===null&&(r=await e(),t.push(...r)),t),o=[],s=!0;for(;s;){let i=o.length+1,a=await S(u=>yf({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},u),{whenHeadless:"refuse"}),c=await S(u=>yf({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},u),{whenHeadless:"refuse"}),d;if(a==="name"){let u=await pE();d=Yc([{name:u,type:c}],[])[0]}else{let u=await dE(await n(),c);d=Yc([{version:u,type:c}],t)[0],d.id.kind==="version"&&t.push(Er(`v${d.id.raw}`))}let p=(await S(u=>Zc({message:" Description (optional, press Enter to skip): "},u),{whenHeadless:"refuse"})).trim();o.push({...d,...p!==""?{description:p}:{}}),s=await S(u=>cE({message:"Add another release?",default:!1},u),{whenHeadless:"refuse"})}return o},mE=e=>{let t=[e.id.kind==="version"?`v${e.id.raw}`:e.id.name,e.type];return e.description&&t.push(e.description),t.join(" \xB7 ")},wf=e=>{for(let r of e)h.addOption("--release",ic(r))},fE=async(e,r)=>{if(e&&e.length>0){let n=cc(e)?await r():[],o=Yc(e,n);return wf(o),o}if(ne())throw new A({status:"argument_required",argument:"release",agentMode:I.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 t=await uE(r);return wf(t),t},gE=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new g(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},hE=async(e,r)=>{let t=e.map(mE).join(`
427
- - `);await se(r,`Create the following ${e.length} release(s)?
428
- - ${t}
429
- `),h.addOption("--yes",!0)},vE=async e=>{let{entry:r,jiraConfig:t}=e,n=B(r.id),o=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await tn({operation:`create release ${o}`});let s=await vc(r.type),i=await yc({id:r.id,jiraConfig:t,description:r.description,type:r.type,baseSha:s});return l.info(`\u2705 Successfully created release: ${o} (${r.type})`),l.info(`\u{1F517} GitHub PR: ${i.prUrl}`),l.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
430
- `),{result:i}}catch(s){let i=Un(s)?s:void 0,a=new g(s,{operation:`create release ${o} (${r.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 l.error(`\u274C ${a.message}
431
- `),{failure:{version:n,error:a.message}}}},yE=(e,r,t)=>{r===e?l.info(`\u2705 All ${e} release branch(es) were created successfully.`):r>0?(l.warn(`\u26A0\uFE0F ${r} of ${e} release branches were created successfully.`),l.warn(`\u274C ${t} release(s) failed.`)):l.error(`\u274C All ${e} release branch(es) failed to create.`)},kf=Hc(),Ks=async e=>{let{releases:r,confirmedCommand:t}=e;await ge({operation:"create release"}),await Ee({provider:kf,params:e,operation:"create release",argument:"release"});let n=await Yt(),o=null,i=await fE(r,async()=>(o===null&&(o=await qn()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});gE(i),await zn({operation:"create release",base:Ar(i[0].type)}),await hE(i,!!t);let a=[],c=[];for(let p of i){let{result:u,failure:m}=await vE({entry:p,jiraConfig:n});u&&a.push(u),m&&c.push(m)}yE(i.length,a.length,c.length),h.print();let d={createdBranches:a.map(p=>p.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:w(JSON.stringify(d,null,2)),structuredContent:d}},Xc=k({name:"release-create",requiresHumanConfirm:!0,formProvider:kf,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.")}).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=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).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")})).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:Ks});import wE from"@inquirer/input";import{z as _r}from"zod";var kE=async()=>{let e=await _(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,D(s.title)])),n=await U(),o=await Cr(le({branches:r,descriptions:n,types:t}));return{branch:o,type:t.get(o)||"regular"}},bE=async e=>{let t=(await _()).find(n=>n.branch===e);if(!t)throw new g(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return D(t.title)},RE=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,n=(await S(o=>wE({message:` New description ${r} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},qs=async e=>{let{version:r,description:t,confirmedCommand:n}=e,o=await Yt(),s;r?(s=or(r),await bE(s)):(h.setInteractive(),s=(await kE()).branch);let i=L(s);if(!i)throw new g(void 0,{operation:`edit description for ${s}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=B(i);h.addOption("--version",a);let c=Y(i),d=await tr(c,o);if(!d)throw new g(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let p=d.description??"",u;t!==void 0?(u=t,h.addOption("--description",u)):(h.setInteractive(),u=await RE(p));let m=T=>{let C={version:a,branch:s,jiraVersionUrl:Rr(o,d),previousDescription:p,newDescription:u,changed:T};return{content:w(JSON.stringify(C,null,2)),structuredContent:C}};if(u===p)return l.info(`No change \u2014 description for ${c} is already: "${p}"`),h.print(),m(!1);await se(n,`Update description for ${c}?
432
- from: "${p}"
433
- to: "${u}"
434
- `),h.addOption("--yes",!0),await zt({versionId:d.id,description:u},o);let v=Rr(o,d),f=Yn(v,u);return await $s({branch:s,body:f}),l.info(`\u2705 Updated description for ${c}`),l.info(`\u{1F517} Jira Version: ${v}`),l.info(`\u{1F517} PR branch: ${s}
435
- `),h.print(),m(!0)},Qc=k({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching 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. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:_r.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:_r.string().describe("New description. Empty string clears the description.")},outputSchema:{version:_r.string().describe("Release version"),branch:_r.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:_r.string().describe("Jira fix version URL"),previousDescription:_r.string().describe("The description before the update"),newDescription:_r.string().describe("The description after the update"),changed:_r.boolean().describe("Whether the description actually changed")},handler:qs});import{z as $}from"zod";import{$ as al}from"zx";import bf from"node:fs/promises";import Hs from"node:path";var el=async e=>{let{workspacePath:r,folderPaths:t}=e,n=Hs.dirname(r),o;try{o=await bf.readFile(r,"utf-8")}catch(p){throw new Error(`Cursor workspace file not found at ${r}: ${p.message}`)}let s;try{s=JSON.parse(o)}catch(p){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${p.message}`)}let i=s.folders??[],a=new Set(i.map(p=>Hs.resolve(n,p.path))),c=[],d=[];for(let p of t){let u=Hs.resolve(p);if(a.has(u)){d.push(p);continue}let m=Hs.relative(n,u);i.push({path:m}),a.add(u),c.push(p)}return s.folders=i,await bf.writeFile(r,`${JSON.stringify(s,null,2)}
436
- `,"utf-8"),{added:c,skipped:d}};import{$ as EE}from"zx";var rl=async e=>{await EE`cursor ${e}`};import Rf from"node:fs/promises";import zs from"node:path";var tl=async e=>{let{workspacePath:r,folderPaths:t}=e,n=zs.dirname(r),o;try{o=await Rf.readFile(r,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${r}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(t.map(m=>zs.resolve(m))),c=new Set,d=i.filter(m=>{let v=zs.resolve(n,m.path);return a.has(v)?(c.add(v),!1):!0});s.folders=d,await Rf.writeFile(r,`${JSON.stringify(s,null,2)}
437
- `,"utf-8");let p=[],u=[];for(let m of t){let v=zs.resolve(m);c.has(v)?p.push(m):u.push(m)}return{removed:p,notFound:u}};import Ef from"node:path";var fo=(e,r)=>Ef.isAbsolute(e)?e:Ef.resolve(r,e);import{$ as PE}from"zx";var nl=async e=>{let{folderPaths:r}=e;for(let t of r)await PE`zed --add ${t}`;return{added:r}};import{$ as SE}from"zx";var ol=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:n}=e,o=[r,...n.map(s=>`${t}/${s}`)];try{return await SE`zed --reuse ${o}`,l.info(`\u21BB Refreshed Zed workspace to root + ${n.length} release worktree(s) (other folders in the focused window are not preserved)`),{ran:!0}}catch(s){return l.warn({error:s},"\u26A0\uFE0F Failed to refresh Zed workspace"),{ran:!1}}};var Or=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var sl=async e=>{let{projectRoot:r,worktreeDir:t,branches:n}=e,o=await P(),s=hr(o),i=n.map(c=>`${t}/${c}`),a=[];for(let c of s)switch(c.provider){case"cursor":{if(!c.config.workspaceConfigPath){l.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),a.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let d=fo(c.config.workspaceConfigPath,r),{added:p,skipped:u}=await el({workspacePath:d,folderPaths:i}),m=u.length>0?` (${u.length} already present)`:"";l.info(`\u2705 Added ${p.length} folder(s) to ${d}${m}`),await rl(d),a.push({ran:!0,provider:"cursor",added:p.length,skipped:u.length});break}case"zed":{let{added:d}=await nl({folderPaths:i});l.info(`\u2705 Added ${d.length} folder(s) to Zed workspace`),a.push({ran:!0,provider:"zed",added:d.length,skipped:0});break}default:Or(c)}return a};var pt=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:n,removedWorktrees:o,allowEditorRelaunch:s}=e;if(o.length===0)return[];let i=await P(),a=hr(i),c=o.map(u=>`${t}/${u}`),d=n.filter(u=>!o.includes(u)),p=[];for(let u of a)switch(u.provider){case"cursor":{p.push(await xE({ide:u,projectRoot:r,folderPaths:c}));break}case"zed":{p.push(await TE({projectRoot:r,worktreeDir:t,remainingBranches:d,allowEditorRelaunch:s}));break}default:Or(u)}return p},xE=async e=>{let{ide:r,projectRoot:t,folderPaths:n}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=fo(r.config.workspaceConfigPath,t);try{let{removed:s}=await tl({workspacePath:o,folderPaths:n});return s.length>0&&l.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return l.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}},TE=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:n,allowEditorRelaunch:o}=e;return o?(await ol({projectRoot:r,worktreeDir:t,remainingBranches:n}),{provider:"zed",supported:!0,removed:[]}):(l.info("\u2139\uFE0F Zed folder removal skipped (no interactive session); close removed worktree folders in Zed manually if needed."),{provider:"zed",supported:!0,removed:[]})};var ut=["workspace","none"];import{z as Pf}from"zod";var Tf=2500,Ys="release-remove",Sf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),AE=e=>e.version===void 0||e.version==="",CE=async()=>{try{return{outcome:"listed",prs:await _()}}catch(e){return e instanceof g&&e.operation===eo?{outcome:"empty"}:{outcome:"failed"}}},xf=(e,r)=>(e===null?l.info({msg:`Tool execution form enumeration timed out (gh pr list, ${r/1e3} s): ${Ys}`}):e.outcome==="failed"?l.info({msg:`Tool execution form enumeration failed (gh pr list): ${Ys}`}):l.info({msg:`Tool execution form options empty (open release PRs): ${Ys}`}),null),IE=(e,r)=>{let t=new Map(e.map(n=>[n.branch,D(n.title)]));return As(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=r?.get(Y(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${t.get(n)??"regular"}]${a}`}})},$E=(e,r,t)=>{let n=e.map(o=>o.prose).join("; ");return r!==null?`Open release PRs right now: ${n}. `:(l.info({msg:`Tool execution form descriptions unavailable (timeout): ${Ys}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${t/1e3} s. `)},il=(e={})=>{let r=e.fetchBudgetMs??Tf;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:t=>Sf(t)&&AE(t),buildRequestedSchema:async()=>{let[t,n]=await Promise.all([ln(CE(),r),ln(U(),r)]);if(t===null||t.outcome!=="listed")return xf(t,r);let o=IE(t.prs,n);return o.length===0?xf({outcome:"empty"},r):Pf.object({version:Pf.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${$E(o,n,r)}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:(t,n)=>typeof t.version!="string"?null:{...Sf(n)?n:{},version:t.version}}};var Af=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],Xs={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"},mt="remove a release",Ie=e=>{throw l.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Cf=(e,r)=>{throw l.warn({operation:r.operation},`\u26D4 ${r.stderrExcerpt??r.operation}`),new A({...e,agentMode:I.source},2,r)},_E=e=>{ne()&&(e.version||Cf({status:"argument_required",argument:"version"},{operation:mt,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&&Cf({status:"refused"},{operation:mt,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"}))},$f=e=>{e.pr?.state==="MERGED"&&Ie({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`})},OE=(e,r)=>{if(r.skipJira||(e.jiraConfig||Ie({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:t,fixCount:n,affectsCount:o}=e.jira;(t.released||t.archived)&&Ie({operation:`remove Jira fix version "${t.name}"`,remediation:"un-release it in Jira first, or remove the release without it via --skip-jira",stderrExcerpt:`fix version "${t.name}" is already ${t.released?"released":"archived"}`}),!(n===0&&o===0)&&(e.moveIssuesTo||Ie({operation:`remove Jira fix version "${t.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:`${t.name} is set as fixVersion on ${n} issue(s) and as affectsVersion on ${o} issue(s)`}))},DE=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ie({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"})},NE=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ie({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(", ")}`})},ME=async e=>(await al`git -C ${e} status --porcelain`).stdout.split(`
438
- `).map(t=>t.trimEnd()).filter(t=>t.length>0),jE=async e=>{try{let{terminals:r}=await ip(e);return r.filter(t=>t.connected).length}catch(r){return l.debug({error:r,worktreePath:e},"release remove: orca terminal probe failed"),0}},FE=async e=>{let r=await Go([e]);if(r!==null)throw l.warn({operation:mt},`\u26D4 this command runs inside an Orca terminal of ${r}`),new A({status:"refused",reason:"orca_caller_inside_target",agentMode:I.source},2,{operation:mt,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`})},LE=async(e,r)=>{let t={jiraConfig:null,jira:null,moveIssuesTo:null};if(r.skipJira)return t;let n=await nr();if(!n)return t;let o=await tr(Y(e),n),s=r.moveIssuesTo?await WE(r.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)}}},WE=async(e,r)=>{let t=await tr(e,r);return t||Ie({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}"`})},VE=async(e,r)=>{let t=L(e);t||Ie({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 b(),o=`${n}${ye}`,s=`${o}/${e}`,[i,a,c,d]=await Promise.all([ke("release"),it(e),hn(n,`refs/heads/${e}`),Mo(n,e)]),p=i.includes(e);return p&&await FE(s),{...await LE(t,r),branch:e,id:t,label:B(t),baseBranch:Ar(D(a?.title??"")),projectRoot:n,worktreeDir:o,worktreePath:s,currentWorktrees:i,worktreePresent:p,orcaTerminalCount:p?await jE(s):0,worktreeDirty:p?await ME(s):null,localTipSha:c,remoteTipSha:d,pr:a}},If=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}),JE=(e,r)=>{if(r)return"skipped (--skip-jira)";if(!e.jiraConfig)return"skipped (Jira not configured)";if(!e.jira)return"none found";let{version:t,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`${t.name} \u2014 ${s}${i}`},BE=(e,r)=>{let t=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: ${t}`,` \u2022 local branch: ${e.localTipSha??"absent"} (switching to ${e.baseBranch} first)`,` \u2022 remote branch: ${e.remoteTipSha??"absent"}`,` \u2022 Jira version: ${JE(e,r)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
439
- `)},Zs=class extends Error{constructor(t,n){super(`step ${t} failed`,{cause:n});this.step=t;this.reason=n;this.name="StepFailure"}step;reason},GE=e=>typeof e=="string"?e:e.outcome;async function go(e,r,t){try{let n=await t(),o=GE(n);return r.push({step:e}),l.info({step:e,outcome:o},`\u2705 ${Xs[e]} \u2014 ${o}`),n}catch(n){throw new Zs(e,n)}}var UE=async(e,r,t)=>{try{await t(),r.push({step:e})}catch(n){r.push({step:e,detail:"attempted"}),l.warn({err:Ir(n),step:e},`\u26A0\uFE0F ${Xs[e]} failed (non-blocking)`)}},KE=(e,r)=>r.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:r.detail?`${r.step} (${r.detail})`:r.step,qE=e=>{let{plan:r,step:t,done:n,cause:o}=e,s=n.map(u=>KE(r,u)).join(", ")||"nothing",i=r.jira?`The Jira fix version ${r.jira.version.name} was NOT removed. `:"",a=r.localTipSha?`Restore the branch with \`git branch ${r.branch} ${r.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${r.label}\` to finish; completed steps are skipped.`,d=`completed: ${s}. ${i}${a}${c}`,p=o instanceof g?o.remediation:void 0;return new g(o,{operation:`remove release ${r.label} \u2014 step ${Af.indexOf(t)+1} of ${Af.length} (${Xs[t]})`,remediation:p?`${p} \u2014 ${d}`:d})},HE=async e=>{let r=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:r.includes(e.branch)?"removed":"absent",removedBranches:r}},zE=e=>{let r=e.map(s=>({provider:s.provider,outcome:YE(s),removed:s.removed})),t=r.some(s=>s.outcome==="verified"),o=r.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:t?"verified":o,providers:r}},YE=e=>e.provider==="zed"?"skipped":e.removed.length>0?"verified":"attempted",ZE=async(e,r,t)=>{let n={outcome:"attempted",providers:[]};return await UE("ide-folders",t,async()=>{let o=await pt({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,currentWorktrees:e.currentWorktrees,removedWorktrees:r,allowEditorRelaunch:!1});n=zE(o)}),l.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${Xs["ide-folders"]} \u2014 ${n.outcome}`),n},XE=async e=>{let r=await it(e.branch);if($f({...e,pr:r}),!r)return{outcome:"absent",number:null};if(r.state==="CLOSED")return{outcome:"already-closed",number:r.number};let t=`Closed by \`infra-kit release remove\`: release ${e.label} was torn down.`;return await al`gh pr close ${String(r.number)} --comment ${t}`,{outcome:"closed",number:r.number}},QE=async e=>(await kt()===e.branch&&await al`git switch ${e.baseBranch}`,await Do(e.branch),await Fd(e.branch)?Ie({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"),eP=async e=>(await No(e.branch),e.remoteTipSha?"deleted":"absent"),rP=async(e,r,t)=>{let n=await bs(r.version.id,t);if(n.issuesFixedCount===r.fixCount&&n.issuesAffectedCount===r.affectsCount)return;let o=`re-run \`infra-kit release remove --version ${e.label}\``;Ie({operation:`remove Jira fix version "${r.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 ${r.fixCount} \u2192 ${n.issuesFixedCount}, affectsVersion ${r.affectsCount} \u2192 ${n.issuesAffectedCount}`})},tP=async(e,r)=>r.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await rP(e,e.jira,e.jiraConfig),l.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Qa({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),nP=(e,r)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:r.worktree.outcome,ideFolders:r.ideFolders,pr:r.pr.outcome,prNumber:r.pr.number,localBranch:r.localBranch,localTipSha:e.localTipSha,remoteBranch:r.remoteBranch,remoteTipSha:e.remoteTipSha,jira:r.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),oP=async(e,r,t)=>{let n=await go("worktree",t,()=>HE(e)),o=await ZE(e,n.removedBranches,t),s=await go("pr",t,()=>XE(e));l.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await go("local-branch",t,()=>QE(e)),a=await go("remote-branch",t,()=>eP(e)),c=await go("jira",t,()=>tP(e,r));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},sP=async(e,r)=>{let t=[];try{return nP(e,await oP(e,r,t))}catch(n){throw n instanceof Zs?qE({plan:e,step:n.step,done:t,cause:n.reason}):n}},iP=async e=>{if(e)return or(e);h.setInteractive();let[r,t]=await Promise.all([U(),_()]),n=t.map(s=>s.branch);n.length===0&&Ie({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(t.map(s=>[s.branch,D(s.title)]));try{return await Cr(le({branches:n,descriptions:r,types:o}))}catch(s){throw ue(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},_f=il(),Qs=async e=>{let{confirmedCommand:r,version:t,moveIssuesTo:n,skipJira:o}=e;await ge({operation:mt}),await P(),await Ee({provider:_f,params:e,operation:mt,argument:"version"}),_E(e);try{let s=await VE(await iP(t),e);l.debug({plan:If(s)},"release remove: resolved plan"),$f(s),OE(s,e),DE(s),await zn({operation:`remove release ${s.label}`,base:s.baseBranch}),NE(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await se(r,BE(s,!!o),{throwOnDecline:!0,plan:{...If(s),skipJira:!!o}}),r||h.addOption("--yes",!0);let i=await sP(s,e);return h.print(),{content:w(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw ue(s)||Vo(s)||s instanceof g?s:(l.error({err:Ir(s)},"\u274C Error removing release"),new g(s,{operation:mt,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},cl=k({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:_f,inputSchema:{version:$.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:$.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:$.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:$.string().describe("The release branch that was targeted"),version:$.string().describe('The release label (e.g. "1.2.5")'),baseBranch:$.string().describe("The branch HEAD was moved to before the local delete"),worktree:$.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:$.object({outcome:$.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; Zed is always a declared skip'),providers:$.array($.object({provider:$.string(),outcome:$.enum(["verified","attempted","skipped"]),removed:$.array($.string()).describe("Folder paths confirmed removed; always empty for Zed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:$.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:$.number().nullable().describe("The pull request number, or null when none exists"),localBranch:$.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:$.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:$.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:$.string().nullable().describe("The origin tip before deletion"),jira:$.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:$.object({id:$.string(),name:$.string(),url:$.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Qs});import{spawnSync as dP}from"node:child_process";import{homedir as pP}from"node:os";import uP from"node:process";var aP=e=>{let r=new Set(e.steps.map(t=>t[0]));return r.has("brew")?"homebrew":r.has("npm")?"npm":null},cP=e=>{let r=[];return e.needsSudo&&r.push("needs-sudo"),e.fetchesNetworkScript&&r.push("fetches-network-script"),r},lP=(e,r)=>{let t=aP(e);if(t===null)return[];let n=[];return r.present.includes(t)||n.push("manager-absent"),r.owner!==null&&r.owner!==t&&n.push("manager-mismatch"),n},ho=(e,r)=>{let t=[...cP(e),...lP(e,r)];return t.length===0?{executable:!0}:{executable:!1,reasons:t}},vo=e=>e.steps.map(hd);var mP=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],fP=e=>{let r={...gd(e)};for(let t of mP)delete r[t];return r},ll=(e,r,t={})=>{let n=t.spawnSync??dP,o=t.env??uP.env,s=(t.agentMode??ne)(),i=vo(e),a=ho(e,r);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:vP({recipe:e,spawn:n,env:o,commands:i,notify:t.notify??gP}):{ran:!1,commands:i,refusedBecause:a.reasons}},gP=e=>{l.info(e)},Df=64,hP=Df*1024*1024,vP=({recipe:e,spawn:r,env:t,commands:n,notify:o})=>{let s=fP(t);for(let[i,a]of e.steps.entries()){o(` ${"running".padEnd(9)} ${n[i]}`);let c=r(a[0],a.slice(1),{stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:hP,cwd:pP(),env:s}),d=EP(c);if(d!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:d}}return{ran:!0,ok:!0,commands:n}},yP=5,wP=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Of=e=>e==null?[]:String(e).split(`
440
- `).map(r=>r.trim()).filter(r=>r.length>0),kP=e=>{let r=Of(e.stderr),t=Of(e.stdout),n=[...r,...t].filter(s=>wP.test(s)),o=r.length>0?r:t;return(n.length>0?n:o).slice(-yP).join(" / ")},bP="ENOBUFS",RP=e=>e.error?.code===bP,EP=e=>{if(RP(e))return`terminated after exceeding the ${Df} 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 r=kP(e),t=r===""?"":`: ${r}`;return`exited ${e.status??"unknown"}${t}`};var PP=e=>{let r=[];return e.some(n=>n.id==="brew"&&n.present)&&r.push("homebrew"),r.push("npm"),r},SP=e=>{let r=Ce(e.id);return e.present?r.updateFor(e.binRealPath):r.bootstrapInstall},xP=(e,r)=>{let t=SP(e),n={...r,owner:e.present?e.manager:null};if(t===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=ho(t,n);return{state:e,action:e.present?"update":"install",recipe:t,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:vo(t),context:n}},ei=async(e=et,r=Wn())=>{let t=await Gn(et,r),n={owner:null,present:PP(t)},o=Ya(e),s=new Map(t.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>xP(s.get(a),n)),context:n}};var dl=(e,r)=>({...yo(e),action:"skipped",commands:e.commands,detail:r}),yo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Nf=(e,r)=>e.action==="none"?dl(e,`nothing to do: ${e.state.manager} installs are not managed from here`):r==="update"&&e.action==="install"?dl(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...yo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},TP=(e,r)=>r.ran?r.ok?{...yo(e),action:e.action==="install"?"installed":"updated",commands:r.commands,detail:e.action==="install"?"installed":"updated"}:{...yo(e),action:"failed",commands:r.commands,detail:`${r.failedStep??"a step"} ${r.detail??"failed"}`}:{...yo(e),action:"refused",commands:r.commands,detail:`refused (${r.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},pl=async e=>{let r=e.run??ll,{plans:t}=await ei(e.ids,e.probeDeps),n=[];for(let o of t){let s=Nf(o,e.mode);if(s!==null){n.push(s);continue}n.push(TP(o,r(o.recipe,o.context)))}return n},ul=async(e,r)=>{let{plans:t}=await ei(e,r);return t.map(n=>Nf(n,"converge")??dl(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import AP from"node:process";import{z as N}from"zod";var CP=()=>{let e=Cd();return{link:e,target:{home:e.home,processStartTime:()=>null}}},IP=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 Or(e)}},$P=async e=>{let r=Ad(e.link);l.info(` ${r.outcome.padEnd(9)} portless link \u2014 ${IP(r.outcome)}`);let t=Io(e.link.home,e.target.exists)??e.link.resolveBin();t!==null&&await bm(e.target,t)!=="converged"&&(l.info("Run this yourself to finish the portless service:"),l.info(` ${jr(t,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath})}`))},jf="--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.",_P=e=>{let r=Array.isArray(e.update)?e.update:void 0,t=e.update===!0||r!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||t))throw new Error(jf);return{ids:e.tools??r??et,mode:t?"update":"converge",skipTools:n}},Mf=(e,r)=>e instanceof Ut?e.step:r.at(-1)?.step??"zshrc",OP=async()=>{let e=[],r=t=>{e.push(t),t.message!==jn&&vs(t)};try{return await Ba(r),{entries:e,failed:!1}}catch(t){let n={step:Mf(t,e),outcome:"warned",message:`The ${Mf(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"};return vs(n),e.push(n),{entries:e,failed:!0}}},DP=async(e,r,t)=>{for(let n of e)l.info(` ${n.action.padEnd(9)} ${n.id} \u2014 ${n.detail}`);for(let n of e)if(NP(n,r)){l.info(`Run these yourself to ${r?"set up":"finish"} ${n.id}:`);for(let o of n.commands)l.info(` ${o}`)}await $P(t),l.info(jn)},NP=(e,r)=>e.commands.length===0?!1:e.action==="refused"||r&&e.action==="skipped",MP=e=>({step:e.step,outcome:e.outcome,message:e.message}),ri=async(e={})=>{let r=_P(e),t=await OP(),n=r.skipTools?await ul(r.ids,e.probeDeps):await pl({ids:r.ids,mode:r.mode,probeDeps:e.probeDeps,run:e.run});await DP(n,r.skipTools,e.portlessDeps??CP());let o={init:t.entries.map(MP),tools:n,converged:!r.skipTools,changed:n.some(s=>s.action==="installed"||s.action==="updated"),allSucceeded:n.every(s=>s.action!=="failed")};return(t.failed||!o.allSucceeded)&&(AP.exitCode=1),{content:w(JSON.stringify(o,null,2)),structuredContent:o}},jP=N.object({step:N.enum(["zshrc","zshenv","migrations","user-config","guidance","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:N.enum(["written","unchanged","skipped","warned"]).describe("What that step did: changed something, found nothing to change, did not run, or failed non-fatally"),message:N.string().describe("The same line a human running this would have read")}),FP=N.object({id:N.string().describe("Dependency id"),action:N.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:N.object({present:N.boolean(),onPath:N.boolean(),version:N.string().nullable(),manager:N.string()}).describe("The tool\u2019s state before this run"),commands:N.array(N.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:N.string().describe("Why, in one line")}),LP={init:N.array(jP).describe("One entry per init step, in the order they ran"),tools:N.array(FP).describe("One result per requested dependency"),converged:N.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:N.boolean().describe("Whether anything was installed or updated"),allSucceeded:N.boolean().describe("Whether no tool failed (a refusal is not a failure)")},WP={tools:N.array(N.enum(et)).optional().describe("Which tools to act on. Omit for all five."),mode:N.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:N.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},ml=k({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, 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:WP,outputSchema:LP,requiresHumanConfirm:!0,handler:e=>ri({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Wf}from"node:fs";import Vf from"node:path";import YP from"node:process";import{z as cr}from"zod";import{createHash as VP}from"node:crypto";import{readFileSync as JP}from"node:fs";var fl=e=>VP("sha256").update(JP(e)).digest("hex");import{readFileSync as HP,writeFileSync as PG}from"node:fs";import Lf from"node:path";import{z as Je}from"zod";var ir="vendor",BP=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),GP=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),UP=[".tsbuildinfo"],gl=e=>BP.has(e),hl=e=>GP.has(e)?!0:UP.some(r=>e.endsWith(r)),Ff=e=>{let r=e.split("/"),t=r.pop()??"";return r.some(o=>gl(o))||hl(t)};import{readdirSync as KP}from"node:fs";import vl from"node:path";var qP=e=>e.split(vl.sep).join("/"),yl=e=>{let r=[],t=n=>{for(let o of KP(n,{withFileTypes:!0})){let s=vl.join(n,o.name);if(o.isDirectory()){if(gl(o.name))continue;t(s);continue}hl(o.name)||r.push(qP(vl.relative(e,s)))}};return t(e),r.sort()};var ar=".sync-manifest.json",wl=1,zP=Je.object({schemaVersion:Je.number().optional(),source:Je.string(),commit:Je.string(),syncedAt:Je.string(),fileCount:Je.number(),files:Je.record(Je.string(),Je.string())}),kl=e=>(e.schemaVersion??wl)>wl;var bl=e=>{let r=Lf.join(e,ar),t;try{t=HP(r,"utf8")}catch{throw new Error(`Missing ${ar} at ${r}`)}let n=zP.safeParse(JSON.parse(t));if(!n.success)throw new Error(`Invalid ${ar} at ${r}: ${Je.prettifyError(n.error)}`);return n.data};var Rl=(e,r)=>{let t=Object.fromEntries(Object.entries(r.files).filter(([c])=>!Ff(c))),n=yl(e),o=[],s=[];for(let c of n){if(!(c in t)){s.push(c);continue}fl(Lf.join(e,c))!==t[c]&&o.push(c)}let i=new Set(n),a=Object.keys(t).filter(c=>!i.has(c));return{modified:o,added:s,removed:a}};var El=30,Pl=(e,r)=>{if(r.length!==0){l.info(`
441
- ${e} (${r.length}):`);for(let t of r.slice(0,El))l.info(` ${t}`);r.length>El&&l.info(` \u2026and ${r.length-El} more`)}},ti=async(e={})=>{let r=e.cwd??await b(),t=Vf.join(r,ir),n={modified:[],added:[],removed:[],fileCount:0};if(!Wf(t)){l.info(`\u2139\uFE0F No ${ir}/ folder found \u2014 nothing to check.`);let p={status:"skipped",ok:!0,...n};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}}if(!Wf(Vf.join(t,ar))){l.error(`\u274C Missing ${ir}/${ar}. Re-run the vendor sync to generate it.`);let p={status:"missing-manifest",ok:!1,...n};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}}let o=bl(t);if(kl(o)){l.error(`\u274C ${ir}/${ar} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let p={status:"unknown-schema",ok:!1,...n};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}}let{modified:s,added:i,removed:a}=Rl(t,o),c=s.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${ir}/ has drifted from ${ir}/${ar}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Pl("Modified",s),Pl("Added (not in manifest)",i),Pl("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${ir}/ matches manifest (${o.fileCount} files).`);let d={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:w(JSON.stringify(d,null,2)),structuredContent:d}},ZP={status:cr.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:cr.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:cr.number(),modified:cr.array(cr.string()),added:cr.array(cr.string()),removed:cr.array(cr.string())},Sl=k({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:ZP,handler:()=>ti({cwd:YP.cwd()})});import Jf from"node:process";import{z as wo}from"zod";var Bf=async e=>{try{return await e()}catch{return null}},ni=async()=>{let e=H.version;l.info(e);let r=await Bf(b),t=r===null?null:await Bf(()=>wt(r)),n={version:e,cwd:Jf.cwd(),repoRoot:r,mainRepoRoot:t,projectDir:Jf.env.CLAUDE_PROJECT_DIR||null};return{content:w(JSON.stringify(n,null,2)),structuredContent:n}},xl=k({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:ni});import Uf from"@inquirer/confirm";import XP from"node:path";import{z as M}from"zod";import{$ as ko}from"zx";var QP="feature",eS="release",oi="create worktrees",rS=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Tl=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),si=async e=>{let{confirmedCommand:r,all:t,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await ge({operation:oi});try{let a=await ke("release"),c=await b(),d=`${c}${ye}`;await Gf(`${d}/${eS}`),await Gf(`${d}/${QP}`);let p=[];if(n)p=n.split(",").map(Be=>Me(xe(Be.trim())));else{let Be=await _(),dr=Be.map(De=>De.branch);if(dr.length===0){l.info("\u2139\uFE0F No open release branches found"),h.print();let De={createdWorktrees:[],count:0,...Tl()};return{content:w(JSON.stringify(De,null,2)),structuredContent:De}}if(t)p=dr;else{h.setInteractive();let De=new Map(Be.map(cd=>[cd.branch,D(cd.title)])),Fg=await U();p=await on(le({branches:dr,descriptions:Fg,types:De}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",st(p));let u=await P(),m=i??(hr(u).length>0?"workspace":"none");h.addOption("--ide",m);let v=await tS(o,u),f=await nS(s,u),T=await wt(c),C=XP.basename(T),ee=f?await oS({explicit:s!==void 0,mainRepoRoot:T}):null;await se(r,sS(ee,C)),r||h.addOption("--yes",!0);let re=ee?await iS(ee,T):null,{branchesToCreate:O}=dS({selectedReleaseBranches:p,currentWorktrees:a}),R=await pS(O,d);if(uS(R),m==="workspace"&&await sl({projectRoot:c,worktreeDir:d,branches:R}),v)for(let Be of R)await ko`github ${d}/${Be}`,await ko`sleep 5`;let Nr=re?await cS({registration:re,createdWorktrees:R,worktreeDir:d,mainRepoRoot:T,repoName:C,config:u}):Tl();lS(Nr),h.print();let lr={createdWorktrees:R,count:R.length,...Nr};return{content:w(JSON.stringify(lr,null,2)),structuredContent:lr}}catch(a){throw ue(a)||a instanceof A?a:(l.debug({err:a},"Error managing worktrees"),new g(a,{operation:oi,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},tS=async(e,r)=>{let t=r.worktrees?.openInGithubDesktop,n=e??t??await S(o=>Uf({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&t===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},nS=async(e,r)=>{let t=r.worktrees?.openInOrca,n=e??t??await S(o=>Uf({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&t===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},Kf=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"},oS=async e=>{let{explicit:r,mainRepoRoot:t}=e,n=await bt();if(n!=="ready"){let{reason:s,text:i}=Kf(n);if(r)throw l.warn({operation:oi},`\u26D4 --orca was passed but ${i}`),new A({status:"refused",reason:s,agentMode:I.source},2,{operation:oi,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 l.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await cp(t);return{probe:n,registered:o.registered,visibility:o.visibility}},sS=(e,r)=>{let t=["Are you sure you want to proceed with these worktree changes?"];return e?.probe==="ready"&&!e.registered&&t.push(` \u2022 will register ${r} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),t.join(`
442
- `)},iS=async(e,r)=>{if(e.probe!=="ready")return{kind:"skip",reason:Kf(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:t}=await lp(r);return{kind:"ready",visibility:t}}catch(t){return l.warn({error:t},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:t instanceof Bo?t.code:void 0}}},aS=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,cS=async e=>{let{registration:r,createdWorktrees:t,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Tl();if(r.kind==="skip"){for(let u of t)a.orcaSkipped.push({branch:u,reason:r.reason,code:r.code});return a}let c=Kd(i),d=t.length===1&&r.visibility!=="hide",p=pp();for(let u of t){let m=`${n}/${u}`;try{let{layout:v}=await up({cwd:m,title:mp({branch:u}),focus:d,layout:"full",panes:c,poll:p});await dp(o,m)?a.orcaOpened.push({branch:u,layout:v}):a.orcaHidden.push({branch:u,path:m,fix:aS(s)})}catch(v){l.warn({error:v,branch:u},`\u26A0\uFE0F Failed to open Orca terminals for ${u}`),v instanceof Bo&&v.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:u,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:u,reason:"orca_error",code:v instanceof Bo?v.code:void 0})}}return a},lS=e=>{for(let r of e.orcaOpened)l.info(`\u{1FA9F} Opened ${r.branch} in Orca (${r.layout})`);for(let r of e.orcaHidden)l.info(`\u{1F648} ${r.branch} opened in Orca but its row is hidden (${r.path}) \u2014 ${r.fix}`);for(let r of e.orcaSkipped){let t=r.code?` (${r.code})`:"";l.info(`\u21A9\uFE0F ${r.branch} not opened in Orca: ${r.reason}${t}`)}},Gf=async e=>{await ko`mkdir -p ${e}`},dS=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,n=t.filter(s=>Oo(s));return{branchesToCreate:r.filter(s=>!n.includes(s))}},pS=async(e,r)=>{let t=await Promise.allSettled(e.map(async o=>{let s=`${r}/${o}`;return await ko`git worktree add ${s} ${o}`,await ko({cwd:s})`pnpm install`,o})),n=[];for(let[o,s]of t.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o],a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});l.error({error:s.reason,msg:a.message})}return n},uS=e=>{if(e.length>0){l.info("\u2705 Created git worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No new git worktrees to create")},Al=k({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:M.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:M.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:M.enum(ut).optional().describe('Editor open mode for created worktrees, applied to all configured editors (Cursor and/or Zed, per the "ide" config). "workspace" (the only attach style) adds each worktree to every configured editor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when at least one "ide" is configured \u2192 "none" otherwise.'),cursor:M.enum(ut).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:M.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:M.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{createdWorktrees:M.array(M.string()).describe("List of created git worktree branches"),count:M.number().describe("Number of git worktrees created"),orcaOpened:M.array(M.object({branch:M.string(),layout:M.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:M.array(M.object({branch:M.string(),reason:M.enum(rS),code:M.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:M.array(M.object({branch:M.string(),path:M.string(),fix:M.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:si});import{z as dn}from"zod";var ii=async()=>{await P();let e=await ke("release");if(e.length===0)return l.info("\u2139\uFE0F No active worktrees found"),{content:w(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([_(),U()]),n=new Map(r.map(c=>[c.branch,D(c.title)])),o=e.flatMap(c=>{let d=L(c);if(!d)return[];let p=B(d),u=n.get(c)||"regular",m=t.get(Y(d))||null;return[{version:p,type:u,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let d=Zn(c.version,c.type,s);return c.description?`${d} ${c.description}`:d});l.info(`\u{1F33F} Active worktrees:
390
+ `);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}},$c=b({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:kt.array(kt.object({version:kt.string().describe("Release version"),type:kt.enum(["regular","hotfix"]).describe("Release type"),description:kt.string().nullable().describe("Jira version description"),releaseDate:kt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:kt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:kt.number().describe("Number of release branches")},handler:Os});import IR from"node:process";var Ic=e=>({...e}),Dc=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=IR.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[d,p]of Object.entries(s)){if(d.startsWith("VITE_")){c.push(d);continue}a[d]=p}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}},Ns=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(`
391
+ `)};import UR from"@inquirer/checkbox";import KR from"@inquirer/confirm";import qR from"@inquirer/select";import{spawn as HR}from"node:child_process";import YR from"node:process";import{z as V}from"zod";import{$ as so}from"zx";import{$ as oo}from"zx";var DR=async e=>{let t=oo.quiet;oo.quiet=!0;try{let r=`/${e}/environment`,n=await oo`aws sts get-caller-identity --query Account --output text`,o=await oo`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{oo.quiet=t}},Ym=(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`})},zm=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"})},Xm=(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`})},Oc=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Mt(t,`deploy to "${t}"`,i),Xm(t,s),zm({env:t,isShared:n,isClean:o});let a=await DR(r);return Ym(t,a),{identity:a}};import Zm from"node:fs/promises";import _s from"node:path";var OR="devops/scripts",NR=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,_R=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,MR=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,jR=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Nc=async e=>{let t=_s.resolve(e,OR),r;try{r=await Zm.readdir(t)}catch{return[]}let n=await yc(e);return(await Promise.all(r.map(s=>({entry:s,match:NR.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=_s.resolve(t,s),c=i?.groups?.service??"",d=LR(await FR(a));return{name:c,scriptPath:a,allowedEnvs:wc(JR(d),n.get(c)),ssmPrefix:BR(d)}}))).sort((s,i)=>s.name.localeCompare(i.name))},FR=async e=>{try{return await Zm.readFile(e,"utf-8")}catch{return""}},LR=e=>e.split(`
392
+ `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),JR=e=>{let t=e.reduce((n,{text:o})=>n??_R.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},VR=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},BR=e=>{for(let{line:t,text:r}of e){let n=jR.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=MR.exec(r)?.groups?.arg;if(o!==void 0&&VR(o))return{unparseable:{line:t,text:r.trim()}}}return null},WR=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],_s.basename(r.scriptPath)]);return t},GR=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${_s.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("; ")})},Qm=e=>{GR(e);let t=WR(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},Ms=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),_c=(e,t)=>e.filter(r=>Ms(r,t));var jc="deploy-all.yml",tf="/bin/sh",zR=async()=>{let e=so.quiet;so.quiet=!0;try{let t=await so`gh run list --workflow=${jc} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{so.quiet=e}},XR=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await x(o=>UR({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},ZR=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 ae()&&jo(i,{env:t,services:n,accountId:o,shared:r}),r?x(a=>qR({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):x(a=>KR({message:i,default:!1},a),{whenHeadless:"refuse"})},QR=(e,t,r)=>new Promise((n,o)=>{let s=HR(tf,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),eP=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){l.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await QR(a,r,n);if(c!==0){i.push(a.name),l.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),l.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},tP=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&&!Ms(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))},Mc=e=>{let{env:t,accountId:r,names:n,built:o,deployed:s,failed:i,dryRun:a,success:c}=e,d={environment:t,accountId:r,services:n,deployed:s,failed:i,contract:Ic(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},rP=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:(g.setInteractive(),XR(r,o))},rf=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await R(),c=await Nc(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 d=Qm(c);await ke({provider:Fc[t],params:e,operation:"deploy locally",argument:"env"});let p=await Ye(),u=He(await ze(jc),p),m=r??"";m||(g.setInteractive(),m=await zr(u,"deploy locally")),g.addOption("--env",m);let h=_c(c,m);if(h.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 rP({selection:t,eligible:h,service:n,env:m}),v=tP({names:y,services:c,env:m});if(t==="selected")for(let Ie of y)g.addOption("--service",Ie);let I=Ar(m),j=await cr(),F=(await so`git rev-parse HEAD`.quiet()).stdout.trim(),C=await Sd(),P=Dc({env:m,branch:j,sha:F,isClean:C});i&&l.info(`Deploy contract for ${m}:
393
+ ${Ns(P)}`);let Pe=(await Oc({env:m,project:d,isShared:I,isClean:C,runningEnvs:await zR(),protectedEnvAccess:p})).identity.accountId;if(s)return l.info([`Would deploy to "${m}" (AWS account ${Pe}) from this machine`,`Preflight parameter: /${d}/environment`,Ns(P),"Commands:",...v.map(Ie=>` ${tf} ${Ie.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
394
+ `)),Mc({env:m,accountId:Pe,names:y,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await ZR({env:m,isShared:I,names:y,accountId:Pe}))return l.info("Deployment cancelled"),Mc({env:m,accountId:Pe,names:y,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&l.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:Be,failed:ot}=await eP({chosen:v,childEnv:P.childEnv,cwd:a,env:m});return ot.length>0&&(l.error(`Partial deploy to "${m}": succeeded [${Be.join(", ")||"none"}], failed [${ot.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),YR.exitCode=1),g.print(),Mc({env:m,accountId:Pe,names:y,built:P,deployed:Be,failed:ot,dryRun:!1,success:ot.length===0})},nf=async e=>rf(e,"all"),of=async e=>rf(e,"selected"),sf='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.',af={env:V.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:V.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:V.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},cf={environment:V.string().describe("Environment deployed to"),accountId:V.string().describe("AWS account the deploy targeted"),services:V.array(V.string()).describe("Services requested"),deployed:V.array(V.string()).describe("Services that completed successfully"),failed:V.array(V.string()).describe("Services that failed"),contract:V.record(V.string(),V.string()).describe("Build contract passed to the scripts"),strippedVars:V.array(V.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:V.boolean().describe("Whether this was a dry run"),success:V.boolean().describe("Whether every requested service deployed")},ef=e=>Ht({workflowFile:jc,fields:["env"],toolName:e}),Fc={all:ef("local-deploy-all"),selected:ef("local-deploy-selected")},Lc=b({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${sf}`,requiresHumanConfirm:!0,formProvider:Fc.all,inputSchema:af,outputSchema:cf,handler:nf}),Jc=b({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${sf}`,requiresHumanConfirm:!0,formProvider:Fc.selected,inputSchema:{...af,service:V.array(V.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:cf,handler:of});import sP from"@inquirer/confirm";import js from"@inquirer/input";import uf from"@inquirer/select";import Bc from"node:process";import{z as _}from"zod";import{z as io}from"zod";var Xr=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var pf=2500,lf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),df=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,nP=async()=>{let e=await _n();return{regular:Lr(e,"regular"),hotfix:Lr(e,"hotfix")}},oP=(e,t)=>e===null?(l.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?(l.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).`,Vc=(e={})=>{let t=e.hintBudgetMs??pf;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=>lf(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Xr(nP(),t);return io.object({type:io.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:io.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. ${oP(r,t)}`),description:io.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:io.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=df(r.description),a=df(r.releaseDate),c=ls(o);return{...lf(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var iP='"1.2.5" or "next"',Wc=(e,t)=>{try{return Ka(e,t)}catch(r){throw r instanceof Jt?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 bd?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}},aP=async(e,t)=>{let r=Lr(e,t),n=r?` [${r}]`:"",o=(await x(i=>js({message:` Version (e.g. ${iP})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(l.error("No version provided. Exiting..."),Bc.exit(1)),s},cP=async()=>{let e=(await x(t=>js({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(l.error("No name provided. Exiting..."),Bc.exit(1));try{So(e)}catch(t){let r=t instanceof Error?t.message:String(t);l.error(`${r} Exiting...`),Bc.exit(1)}return e},lP=async()=>(await x(e=>js({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Nn},e),{whenHeadless:"refuse"})).trim(),dP=async e=>{g.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 x(m=>uf({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 x(m=>uf({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),d;if(a==="name"){let m=await cP();d=Wc([{name:m,type:c}],[])[0]}else{let m=await aP(await n(),c);d=Wc([{version:m,type:c}],r)[0],d.id.kind==="version"&&r.push(mt(`v${d.id.raw}`))}let p=(await x(m=>js({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),u=await lP();o.push({...d,...p!==""?{description:p}:{},...u!==""?{releaseDate:u}:{}}),s=await x(m=>sP({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},pP=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 ")},mf=e=>{for(let t of e)g.addOption("--release",Ua(t))},uP=async(e,t)=>{if(e&&e.length>0){let n=qa(e)?await t():[],o=Wc(e,n);return mf(o),o}if(Z())throw new T({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 dP(t);return mf(r),r},mP=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"})},fP=async(e,t)=>{let r=e.map(pP).join(`
395
+ - `);await Q(t,`Create the following ${e.length} release(s)?
396
+ - ${r}
397
+ `),g.addOption("--yes",!0)},gP=async e=>{let{entry:t,jiraConfig:r}=e,n=B(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Ur({operation:`create release ${o}`});let s=await ic(t.type),i=await ac({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return l.info(`\u2705 Successfully created release: ${o} (${t.type})`),l.info(`\u{1F517} GitHub PR: ${i.prUrl}`),l.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
398
+ `),{result:i}}catch(s){let i=In(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 l.error(`\u274C ${a.message}
399
+ `),{failure:{version:n,error:a.message}}}},hP=(e,t,r)=>{t===e?l.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(l.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),l.warn(`\u274C ${r} release(s) failed.`)):l.error(`\u274C All ${e} release branch(es) failed to create.`)},ff=Vc(),Fs=async e=>{let{releases:t,confirmedCommand:r}=e;await ue({operation:"create release"}),await ke({provider:ff,params:e,operation:"create release",argument:"release"});let n=await Mr(),o=null,i=await uP(t,async()=>(o===null&&(o=await _n()),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"});mP(i),await Vn({operation:"create release",base:Je(i[0].type)}),await fP(i,!!r);let a=[],c=[];for(let p of i){let{result:u,failure:m}=await gP({entry:p,jiraConfig:n});u&&a.push(u),m&&c.push(m)}hP(i.length,a.length,c.length),g.print();let d={createdBranches:a.map(p=>p.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Gc=b({name:"release-create",requiresHumanConfirm:!0,formProvider:ff,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:_.array(_.object({version:_.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:_.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:_.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:_.string().optional().describe("Optional description for the Jira version."),releaseDate:Fa.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:_.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:_.array(_.string()).describe("List of created release branch names"),successCount:_.number().describe("Number of releases created successfully"),failureCount:_.number().describe("Number of releases that failed"),releases:_.array(_.object({version:_.string().describe("Version number"),type:_.enum(["regular","hotfix"]).describe("Release type"),branchName:_.string().describe("Release branch name"),prUrl:_.string().describe("GitHub PR URL"),jiraVersionUrl:_.string().describe("Jira version URL"),releaseDate:_.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:_.array(_.object({version:_.string().describe("Version number that failed"),error:_.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Fs});import gf from"@inquirer/input";import{z as Re}from"zod";var hf=["description","releaseDate"],vP=async()=>{let e=await O(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await X(),o=await vt(se({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},yP=async e=>{let r=(await O()).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},wP=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await x(o=>gf({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},kP=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await x(o=>gf({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Nn},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Lt(n)},bP=e=>{if(e!==void 0)return e===""?null:e},RP=async e=>(g.setInteractive(),{description:await wP(e.description),releaseDate:await kP(e.releaseDate)}),Uc=e=>e??"(none)",PP=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Uc(t.releaseDate)} \u2192 ${Uc(r.releaseDate)}`,Ls=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=bP(n),i=await Mr(),a;t?(a=Qe(t),await yP(a)):(g.setInteractive(),a=(await vP()).branch);let c=L(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 d=B(c);g.addOption("--version",d);let p=Y(c),u=await Xe(p,i);if(!u)throw new f(void 0,{operation:`edit release ${p}`,remediation:`create the Jira fix version "${p}" first or pick a different release`});let m={description:u.description??"",releaseDate:u.releaseDate||null},h=r!==void 0||s!==void 0;if(!h&&ae())throw new T({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=h?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await RP(m),v=hf.filter(W=>y[W]!==m[W]),I=v.includes("description"),j=v.includes("releaseDate"),F=Ft(i,u),C=W=>{let Pe={version:d,branch:a,jiraVersionUrl:F,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:v,changed:W};return{content:k(JSON.stringify(Pe,null,2)),structuredContent:Pe}};if(v.length===0)return l.info(`No change \u2014 ${p} already has description "${m.description}" and release date ${Uc(m.releaseDate)}`),g.print(),C(!1);I&&g.addOption("--description",y.description),j&&g.addOption("--release-date",y.releaseDate??"");let P=v.map(W=>PP(W,m,y));return await Q(o,`Update ${p}?
400
+ ${P.join(`
401
+ `)}
402
+ `),g.addOption("--yes",!0),await _r({versionId:u.id,...I?{description:y.description}:{},...j?{releaseDate:y.releaseDate}:{}},i),I&&await Ss({branch:a,body:Wn(F,y.description)}),l.info(`\u2705 Updated ${v.join(" and ")} for ${p}`),l.info(`\u{1F517} Jira Version: ${F}`),l.info(`\u{1F517} PR branch: ${a}
403
+ `),g.print(),C(!0)},Kc=b({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:Re.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Re.string().optional().describe("New description. Empty string clears the description."),releaseDate:La.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Re.string().describe("Release version"),branch:Re.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Re.string().describe("Jira fix version URL"),previousDescription:Re.string().describe("The description before the update"),newDescription:Re.string().describe("The description after the update"),previousReleaseDate:Re.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Re.string().nullable().describe("The planned release date after the update, or null"),changedFields:Re.array(Re.enum(hf)).describe("The fields whose value actually changed"),changed:Re.boolean().describe("Whether anything actually changed")},handler:Ls});import{z as D}from"zod";import{$ as Zc}from"zx";import vf from"node:fs/promises";import Js from"node:path";var qc=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Js.dirname(t),o;try{o=await vf.readFile(t,"utf-8")}catch(p){throw new Error(`Cursor workspace file not found at ${t}: ${p.message}`)}let s;try{s=JSON.parse(o)}catch(p){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${p.message}`)}let i=s.folders??[],a=new Set(i.map(p=>Js.resolve(n,p.path))),c=[],d=[];for(let p of r){let u=Js.resolve(p);if(a.has(u)){d.push(p);continue}let m=Js.relative(n,u);i.push({path:m}),a.add(u),c.push(p)}return s.folders=i,await vf.writeFile(t,`${JSON.stringify(s,null,2)}
404
+ `,"utf-8"),{added:c,skipped:d}};import{$ as EP}from"zx";var Hc=async e=>{await EP`cursor ${e}`};import yf from"node:fs/promises";import Vs from"node:path";var Yc=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Vs.dirname(t),o;try{o=await yf.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=>Vs.resolve(m))),c=new Set,d=i.filter(m=>{let h=Vs.resolve(n,m.path);return a.has(h)?(c.add(h),!1):!0});s.folders=d,await yf.writeFile(t,`${JSON.stringify(s,null,2)}
405
+ `,"utf-8");let p=[],u=[];for(let m of r){let h=Vs.resolve(m);c.has(h)?p.push(m):u.push(m)}return{removed:p,notFound:u}};import wf from"node:path";var ao=(e,t)=>wf.isAbsolute(e)?e:wf.resolve(t,e);var zc=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await $(),s=ct(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await SP({ide:c,projectRoot:t,folderPaths:i}));return a},SP=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return l.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=ao(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await qc({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return l.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await Hc(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var zt=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await $(),s=ct(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await xP({ide:c,projectRoot:t,folderPaths:i}));return a},xP=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=ao(t.config.workspaceConfigPath,r);try{let{removed:s}=await Yc({workspacePath:o,folderPaths:n});return s.length>0&&l.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return l.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var Xt=["workspace","none"];import{z as kf}from"zod";var Pf=2500,Bs="release-remove",bf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),TP=e=>e.version===void 0||e.version==="",CP=async()=>{try{return{outcome:"listed",prs:await O()}}catch(e){return e instanceof f&&e.operation===qn?{outcome:"empty"}:{outcome:"failed"}}},Rf=(e,t)=>(e===null?l.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Bs}`}):e.outcome==="failed"?l.info({msg:`Tool execution form enumeration failed (gh pr list): ${Bs}`}):l.info({msg:`Tool execution form options empty (open release PRs): ${Bs}`}),null),AP=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Rs(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(Y(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},$P=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(l.info({msg:`Tool execution form descriptions unavailable (timeout): ${Bs}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Xc=(e={})=>{let t=e.fetchBudgetMs??Pf;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=>bf(r)&&TP(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Xr(CP(),t),Xr(X(),t)]);if(r===null||r.outcome!=="listed")return Rf(r,t);let o=AP(r.prs,n);return o.length===0?Rf({outcome:"empty"},t):kf.object({version:kf.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${$P(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:{...bf(n)?n:{},version:r.version}}};var Ef=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],Gs={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"},Zt="remove a release",Ce=e=>{throw l.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},Sf=(e,t)=>{throw l.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new T({...e,agentMode:A.source},2,t)},IP=e=>{Z()&&(e.version||Sf({status:"argument_required",argument:"version"},{operation:Zt,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&&Sf({status:"refused"},{operation:Zt,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"}))},Tf=e=>{e.pr?.state==="MERGED"&&Ce({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`})},DP=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ce({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)&&Ce({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||Ce({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)`}))},OP=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ce({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"})},NP=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ce({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(", ")}`})},_P=async e=>(await Zc`git -C ${e} status --porcelain`).stdout.split(`
406
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),MP=async e=>{try{let{terminals:t}=await Ud(e);return t.filter(r=>r.connected).length}catch(t){return l.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},jP=async e=>{let t=await _o([e]);if(t!==null)throw l.warn({operation:Zt},`\u26D4 this command runs inside an Orca terminal of ${t}`),new T({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:Zt,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`})},FP=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await Ze();if(!n)return r;let o=await Xe(Y(e),n),s=t.moveIssuesTo?await LP(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await as(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:Ft(n,o)}}},LP=async(e,t)=>{let r=await Xe(e,t);return r||Ce({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}"`})},JP=async(e,t)=>{let r=L(e);r||Ce({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 R(),o=`${n}${he}`,s=`${o}/${e}`,[i,a,c,d]=await Promise.all([ve("release"),qr(e),nn(n,`refs/heads/${e}`),Ao(n,e)]),p=i.includes(e);return p&&await jP(s),{...await FP(r,t),branch:e,id:r,label:B(r),baseBranch:a?.baseRefName??Je("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:p,orcaTerminalCount:p?await MP(s):0,worktreeDirty:p?await _P(s):null,localTipSha:c,remoteTipSha:d,pr:a}},xf=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}),VP=(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}`},BP=(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: ${VP(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
407
+ `)},Ws=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},WP=e=>typeof e=="string"?e:e.outcome;async function co(e,t,r){try{let n=await r(),o=WP(n);return t.push({step:e}),l.info({step:e,outcome:o},`\u2705 ${Gs[e]} \u2014 ${o}`),n}catch(n){throw new Ws(e,n)}}var GP=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),l.warn({err:yt(n),step:e},`\u26A0\uFE0F ${Gs[e]} failed (non-blocking)`)}},UP=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,KP=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(u=>UP(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.`,d=`completed: ${s}. ${i}${a}${c}`,p=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Ef.indexOf(r)+1} of ${Ef.length} (${Gs[r]})`,remediation:p?`${p} \u2014 ${d}`:d})},qP=async e=>{let t=await Xn(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}},HP=e=>{let t=e.map(s=>({provider:s.provider,outcome:YP(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}},YP=e=>e.removed.length>0?"verified":"attempted",zP=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await GP("ide-folders",r,async()=>{let o=await zt({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=HP(o)}),l.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${Gs["ide-folders"]} \u2014 ${n.outcome}`),n},XP=async e=>{let t=await qr(e.branch);if(Tf({...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 Zc`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},ZP=async e=>(await cr()===e.branch&&await Zc`git switch ${e.baseBranch}`,await To(e.branch),await Td(e.branch)?Ce({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"),QP=async e=>(await Co(e.branch),e.remoteTipSha?"deleted":"absent"),eE=async(e,t,r)=>{let n=await as(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}\``;Ce({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}`})},tE=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await eE(e,e.jira,e.jiraConfig),l.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await ja({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),rE=(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}),nE=async(e,t,r)=>{let n=await co("worktree",r,()=>qP(e)),o=await zP(e,n.removedBranches,r),s=await co("pr",r,()=>XP(e));l.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await co("local-branch",r,()=>ZP(e)),a=await co("remote-branch",r,()=>QP(e)),c=await co("jira",r,()=>tE(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},oE=async(e,t)=>{let r=[];try{return rE(e,await nE(e,t,r))}catch(n){throw n instanceof Ws?KP({plan:e,step:n.step,done:r,cause:n.reason}):n}},sE=async e=>{if(e)return Qe(e);g.setInteractive();let[t,r]=await Promise.all([X(),O()]),n=r.map(s=>s.branch);n.length===0&&Ce({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 vt(se({branches:n,descriptions:t,types:o}))}catch(s){throw le(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"})}},Cf=Xc(),Us=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await ue({operation:Zt}),await $(),await ke({provider:Cf,params:e,operation:Zt,argument:"version"}),IP(e);try{let s=await JP(await sE(r),e);l.debug({plan:xf(s)},"release remove: resolved plan"),Tf(s),DP(s,e),OP(s),await Vn({operation:`remove release ${s.label}`,base:s.baseBranch}),NP(s),g.addOption("--version",s.label),n&&g.addOption("--move-issues-to",n),o&&g.addOption("--skip-jira",!0),await Q(t,BP(s,!!o),{throwOnDecline:!0,plan:{...xf(s),skipJira:!!o}}),t||g.addOption("--yes",!0);let i=await oE(s,e);return g.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw le(s)||Mo(s)||s instanceof f?s:(l.error({err:yt(s)},"\u274C Error removing release"),new f(s,{operation:Zt,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Qc=b({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:Cf,inputSchema:{version:D.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:D.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:D.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:D.string().describe("The release branch that was targeted"),version:D.string().describe('The release label (e.g. "1.2.5")'),baseBranch:D.string().describe("The branch HEAD was moved to before the local delete"),worktree:D.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:D.object({outcome:D.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:D.array(D.object({provider:D.string(),outcome:D.enum(["verified","attempted","skipped"]),removed:D.array(D.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:D.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:D.number().nullable().describe("The pull request number, or null when none exists"),localBranch:D.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:D.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:D.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:D.string().nullable().describe("The origin tip before deletion"),jira:D.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:D.object({id:D.string(),name:D.string(),url:D.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Us});import{spawnSync as lE}from"node:child_process";import{homedir as dE}from"node:os";import pE from"node:process";var iE=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},aE=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},cE=(e,t)=>{let r=iE(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},lo=(e,t)=>{let r=[...aE(e),...cE(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},po=e=>e.steps.map(nd);var uE=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],mE=e=>{let t={...rd(e)};for(let r of uE)delete t[r];return t},el=(e,t,r={})=>{let n=r.spawnSync??lE,o=r.env??pE.env,s=(r.agentMode??Z)(),i=po(e),a=lo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:hE({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??fE}):{ran:!1,commands:i,refusedBecause:a.reasons}},fE=e=>{l.info(e)},$f=64,gE=$f*1024*1024,hE=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=mE(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:gE,cwd:dE(),env:s}),d=RE(c);if(d!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:d}}return{ran:!0,ok:!0,commands:n}},vE=5,yE=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Af=e=>e==null?[]:String(e).split(`
408
+ `).map(t=>t.trim()).filter(t=>t.length>0),wE=e=>{let t=Af(e.stderr),r=Af(e.stdout),n=[...t,...r].filter(s=>yE.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-vE).join(" / ")},kE="ENOBUFS",bE=e=>e.error?.code===kE,RE=e=>{if(bE(e))return`terminated after exceeding the ${$f} 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=wE(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var PE=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},EE=e=>{let t=Te(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},SE=(e,t)=>{let r=EE(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=lo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:po(r),context:n}},Ks=async(e=_t,t=Sn())=>{let r=await An(_t,t),n={owner:null,present:PE(r)},o=Da(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>SE(s.get(a),n)),context:n}};var tl=(e,t)=>({...uo(e),action:"skipped",commands:e.commands,detail:t}),uo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),If=(e,t)=>e.action==="none"?tl(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?tl(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...uo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},xE=(e,t)=>t.ran?t.ok?{...uo(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...uo(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...uo(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},rl=async e=>{let t=e.run??el,{plans:r}=await Ks(e.ids,e.probeDeps),n=[];for(let o of r){let s=If(o,e.mode);if(s!==null){n.push(s);continue}n.push(xE(o,t(o.recipe,o.context)))}return n},nl=async(e,t)=>{let{plans:r}=await Ks(e,t);return r.map(n=>If(n,"converge")??tl(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import TE from"node:process";import{z as N}from"zod";var CE=()=>{let{link:e,node:t}=Po();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},AE=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 yi(e)}},$E=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 yi(e.outcome)}},IE=async e=>{let t=yd(e.link);l.info(` ${t.outcome.padEnd(9)} portless link \u2014 ${AE(t.outcome)}`);let r=vd(e.node);l.info(` ${r.outcome.padEnd(9)} portless node \u2014 ${$E(r)}`);let n=Ro(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return;let{state:o,stableNode:s}=await em(e.target,n);o!=="converged"&&(l.info("Run this yourself to finish the portless service:"),l.info(` ${st(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s})}`))},Of="--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.",DE=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(Of);return{ids:e.tools??t??_t,mode:r?"update":"converge",skipTools:n}},Df=(e,t)=>e instanceof Sr?e.step:t.at(-1)?.step??"zshrc",OE=async()=>{let e=[],t=r=>{e.push(r),r.message!==bn&&rs(r)};try{return await Pa(t),{entries:e,failed:!1}}catch(r){let n={step:Df(r,e),outcome:"warned",message:`The ${Df(r,e)} step failed: ${r instanceof Error?r.message:String(r)}`,level:"warn"};return rs(n),e.push(n),{entries:e,failed:!0}}},NE=async(e,t,r)=>{for(let n of e)l.info(` ${n.action.padEnd(9)} ${n.id} \u2014 ${n.detail}`);for(let n of e)if(_E(n,t)){l.info(`Run these yourself to ${t?"set up":"finish"} ${n.id}:`);for(let o of n.commands)l.info(` ${o}`)}await IE(r),l.info(bn)},_E=(e,t)=>e.commands.length===0?!1:e.action==="refused"||t&&e.action==="skipped",ME=e=>({step:e.step,outcome:e.outcome,message:e.message}),qs=async(e={})=>{let t=DE(e),r=await OE(),n=t.skipTools?await nl(t.ids,e.probeDeps):await rl({ids:t.ids,mode:t.mode,probeDeps:e.probeDeps,run:e.run});await NE(n,t.skipTools,e.portlessDeps??CE());let o={init:r.entries.map(ME),tools:n,converged:!t.skipTools,changed:n.some(s=>s.action==="installed"||s.action==="updated"),allSucceeded:n.every(s=>s.action!=="failed")};return(r.failed||!o.allSucceeded)&&(TE.exitCode=1),{content:k(JSON.stringify(o,null,2)),structuredContent:o}},jE=N.object({step:N.enum(["zshrc","zshenv","migrations","user-config","guidance","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:N.enum(["written","unchanged","skipped","warned"]).describe("What that step did: changed something, found nothing to change, did not run, or failed non-fatally"),message:N.string().describe("The same line a human running this would have read")}),FE=N.object({id:N.string().describe("Dependency id"),action:N.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:N.object({present:N.boolean(),onPath:N.boolean(),version:N.string().nullable(),manager:N.string()}).describe("The tool\u2019s state before this run"),commands:N.array(N.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:N.string().describe("Why, in one line")}),LE={init:N.array(jE).describe("One entry per init step, in the order they ran"),tools:N.array(FE).describe("One result per requested dependency"),converged:N.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:N.boolean().describe("Whether anything was installed or updated"),allSucceeded:N.boolean().describe("Whether no tool failed (a refusal is not a failure)")},JE={tools:N.array(N.enum(_t)).optional().describe("Which tools to act on. Omit for all five."),mode:N.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:N.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},ol=b({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, 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:JE,outputSchema:LE,requiresHumanConfirm:!0,handler:e=>qs({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Mf}from"node:fs";import jf from"node:path";import zE from"node:process";import{z as nt}from"zod";import{createHash as VE}from"node:crypto";import{readFileSync as BE}from"node:fs";var sl=e=>VE("sha256").update(BE(e)).digest("hex");import{readFileSync as HE,writeFileSync as W0}from"node:fs";import _f from"node:path";import{z as Ve}from"zod";var tt="vendor",WE=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),GE=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),UE=[".tsbuildinfo"],il=e=>WE.has(e),al=e=>GE.has(e)?!0:UE.some(t=>e.endsWith(t)),Nf=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>il(o))||al(r)};import{readdirSync as KE}from"node:fs";import cl from"node:path";var qE=e=>e.split(cl.sep).join("/"),ll=e=>{let t=[],r=n=>{for(let o of KE(n,{withFileTypes:!0})){let s=cl.join(n,o.name);if(o.isDirectory()){if(il(o.name))continue;r(s);continue}al(o.name)||t.push(qE(cl.relative(e,s)))}};return r(e),t.sort()};var rt=".sync-manifest.json",dl=1,YE=Ve.object({schemaVersion:Ve.number().optional(),source:Ve.string(),commit:Ve.string(),syncedAt:Ve.string(),fileCount:Ve.number(),files:Ve.record(Ve.string(),Ve.string())}),pl=e=>(e.schemaVersion??dl)>dl;var ul=e=>{let t=_f.join(e,rt),r;try{r=HE(t,"utf8")}catch{throw new Error(`Missing ${rt} at ${t}`)}let n=YE.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${rt} at ${t}: ${Ve.prettifyError(n.error)}`);return n.data};var ml=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Nf(c))),n=ll(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}sl(_f.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 fl=30,gl=(e,t)=>{if(t.length!==0){l.info(`
409
+ ${e} (${t.length}):`);for(let r of t.slice(0,fl))l.info(` ${r}`);t.length>fl&&l.info(` \u2026and ${t.length-fl} more`)}},Hs=async(e={})=>{let t=e.cwd??await R(),r=jf.join(t,tt),n={modified:[],added:[],removed:[],fileCount:0};if(!Mf(r)){l.info(`\u2139\uFE0F No ${tt}/ folder found \u2014 nothing to check.`);let p={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}if(!Mf(jf.join(r,rt))){l.error(`\u274C Missing ${tt}/${rt}. Re-run the vendor sync to generate it.`);let p={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}let o=ul(r);if(pl(o)){l.error(`\u274C ${tt}/${rt} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let p={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}let{modified:s,added:i,removed:a}=ml(r,o),c=s.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${tt}/ has drifted from ${tt}/${rt}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),gl("Modified",s),gl("Added (not in manifest)",i),gl("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${tt}/ matches manifest (${o.fileCount} files).`);let d={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},XE={status:nt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:nt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:nt.number(),modified:nt.array(nt.string()),added:nt.array(nt.string()),removed:nt.array(nt.string())},hl=b({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:XE,handler:()=>Hs({cwd:zE.cwd()})});import Ff from"node:process";import{z as mo}from"zod";var Lf=async e=>{try{return await e()}catch{return null}},Ys=async()=>{let e=U.version;l.info(e);let t=await Lf(R),r=t===null?null:await Lf(()=>ar(t)),n={version:e,cwd:Ff.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Ff.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},vl=b({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:mo.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:mo.string().describe("The working directory of this process"),repoRoot:mo.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:mo.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:mo.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ys});import Vf from"@inquirer/confirm";import ZE from"node:path";import{z as M}from"zod";import{$ as fo}from"zx";var QE="feature",eS="release",zs="create worktrees",tS=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],yl=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Xs=async e=>{let{confirmedCommand:t,all:r,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await ue({operation:zs});try{let a=await ve("release"),c=await R(),d=`${c}${he}`;await Jf(`${d}/${eS}`),await Jf(`${d}/${QE}`);let p=[];if(n)p=n.split(",").map(Be=>De(Ee(Be.trim())));else{let Be=await O(),ot=Be.map(Ie=>Ie.branch);if(ot.length===0){l.info("\u2139\uFE0F No open release branches found"),g.print();let Ie={createdWorktrees:[],count:0,...yl()};return{content:k(JSON.stringify(Ie,null,2)),structuredContent:Ie}}if(r)p=ot;else{g.setInteractive();let Ie=new Map(Be.map(Hl=>[Hl.branch,Hl.type])),$g=await X();p=await Hr(se({branches:ot,descriptions:$g,types:Ie}),{required:!0})}}r?g.addOption("--all",!0):g.addOption("--versions",Ut(p));let u=await $(),m=i??(ct(u).length>0?"workspace":"none");g.addOption("--ide",m);let h=await rS(o,u),y=await nS(s,u),v=await ar(c),I=ZE.basename(v),j=y?await oS({explicit:s!==void 0,mainRepoRoot:v}):null;await Q(t,sS(j,I)),t||g.addOption("--yes",!0);let F=j?await iS(j,v):null,{branchesToCreate:C}=dS({selectedReleaseBranches:p,currentWorktrees:a}),P=await pS(C,d);if(uS(P),m==="workspace"&&await zc({projectRoot:c,worktreeDir:d,branches:P}),h)for(let Be of P)await fo`github ${d}/${Be}`,await fo`sleep 5`;let W=F?await cS({registration:F,createdWorktrees:P,worktreeDir:d,mainRepoRoot:v,repoName:I,config:u}):yl();lS(W),g.print();let Pe={createdWorktrees:P,count:P.length,...W};return{content:k(JSON.stringify(Pe,null,2)),structuredContent:Pe}}catch(a){throw le(a)||a instanceof T?a:(l.debug({err:a},"Error managing worktrees"),new f(a,{operation:zs,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},rS=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await x(o=>Vf({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&g.setInteractive(),g.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},nS=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await x(o=>Vf({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&g.setInteractive(),g.addOption(n?"--orca":"--no-orca",!0),n},Bf=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"},oS=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await lr();if(n!=="ready"){let{reason:s,text:i}=Bf(n);if(t)throw l.warn({operation:zs},`\u26D4 --orca was passed but ${i}`),new T({status:"refused",reason:s,agentMode:A.source},2,{operation:zs,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 l.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await qd(r);return{probe:n,registered:o.registered,visibility:o.visibility}},sS=(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(`
410
+ `)},iS=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Bf(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Hd(t);return{kind:"ready",visibility:r}}catch(r){return l.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 No?r.code:void 0}}},aS=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,cS=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=yl();if(t.kind==="skip"){for(let u of r)a.orcaSkipped.push({branch:u,reason:t.reason,code:t.code});return a}let c=_d(i),d=r.length===1&&t.visibility!=="hide",p=zd();for(let u of r){let m=`${n}/${u}`;try{let{layout:h}=await Xd({cwd:m,title:Zd({branch:u}),focus:d,layout:"full",panes:c,poll:p});await Yd(o,m)?a.orcaOpened.push({branch:u,layout:h}):a.orcaHidden.push({branch:u,path:m,fix:aS(s)})}catch(h){l.warn({error:h,branch:u},`\u26A0\uFE0F Failed to open Orca terminals for ${u}`),h instanceof No&&h.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:u,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:u,reason:"orca_error",code:h instanceof No?h.code:void 0})}}return a},lS=e=>{for(let t of e.orcaOpened)l.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)l.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})`:"";l.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},Jf=async e=>{await fo`mkdir -p ${e}`},dS=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>xo(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},pS=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o}`;return await fo`git worktree add ${s} ${o}`,await fo({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"});l.error({error:s.reason,msg:a.message})}return n},uS=e=>{if(e.length>0){l.info("\u2705 Created git worktrees:");for(let t of e)l.info(t);l.info("")}else l.info("\u2139\uFE0F No new git worktrees to create")},wl=b({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:M.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:M.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:M.enum(Xt).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:M.enum(Xt).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:M.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:M.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{createdWorktrees:M.array(M.string()).describe("List of created git worktree branches"),count:M.number().describe("Number of git worktrees created"),orcaOpened:M.array(M.object({branch:M.string(),layout:M.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:M.array(M.object({branch:M.string(),reason:M.enum(tS),code:M.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:M.array(M.object({branch:M.string(),path:M.string(),fix:M.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:Xs});import{z as Zr}from"zod";var Zs=async()=>{await $();let e=await ve("release");if(e.length===0)return l.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([O(),X()]),n=new Map(t.map(c=>[c.branch,c.type])),o=e.flatMap(c=>{let d=L(c);if(!d)return[];let p=B(d),u=n.get(c)||"regular",m=r.get(Y(d))||null;return[{version:p,type:u,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let d=Gn(c.version,c.type,s);return c.description?`${d} ${c.description}`:d});l.info(`\u{1F33F} Active worktrees:
443
411
 
444
412
  ${i.join(`
445
- `)}`);let a={worktrees:o,count:o.length};return{content:w(JSON.stringify(a,null,2)),structuredContent:a}},Cl=k({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:dn.array(dn.object({version:dn.string().describe("Release version"),type:dn.enum(["regular","hotfix"]).describe("Release type"),description:dn.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:dn.number().describe("Number of worktrees")},handler:ii});import{z as ft}from"zod";var mS=e=>{if(ne()){if(e.all)throw new A({status:"refused",agentMode:I.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 A({status:"argument_required",argument:"versions",agentMode:I.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"})}},fS=(e,r)=>{let t=e.filter(n=>!r.includes(n));if(t.length>0)throw new g(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${t.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${t.join(", ")}`})},gS=async(e,r)=>{let t=await Go(r.map(n=>`${e}/${n}`));if(t!==null)throw new A({status:"refused",reason:"orca_caller_inside_target",agentMode:I.source},2,{operation:"remove worktrees",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`})},ai=async e=>{let{confirmedCommand:r,all:t,versions:n}=e;await ge({operation:"remove worktrees"}),await P(),mS({all:t,versions:n});try{let o=await ke("release");if(o.length===0){l.info("\u2139\uFE0F No active worktrees to remove"),h.print();let p={removedWorktrees:[],failedWorktrees:[],count:0};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}}let s=await b(),i=`${s}${ye}`,a=[];if(t)a=o;else if(n)a=n.split(",").map(p=>Me(xe(p.trim())));else{h.setInteractive();let[p,u]=await Promise.all([U(),_()]),m=new Map(u.map(v=>[v.branch,D(v.title)]));a=await on(le({branches:o,descriptions:p,types:m}),{required:!0})}fS(a,o);let c=a.length===o.length;c?h.addOption("--all",!0):h.addOption("--versions",st(a)),await gS(i,a),await se(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let d=await ct({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await pt({projectRoot:s,worktreeDir:i,currentWorktrees:o,removedWorktrees:d.removed,allowEditorRelaunch:!r}),to(d),h.print(),no({result:d,operation:"remove worktrees"})}catch(o){throw ue(o)||o instanceof g?o:(l.error({error:o},"\u274C Error managing worktrees"),new g(o,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Il=k({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:ft.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:ft.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:ft.array(ft.string()).describe("List of removed git worktree branches"),failedWorktrees:ft.array(ft.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ft.number().describe("Number of git worktrees removed")},handler:ai});import{z as bo}from"zod";var ci=async e=>{let{confirmedCommand:r}=e;await ge({operation:"sync worktrees"}),await P();try{let t=await ke("release"),n=await b(),o=`${n}${ye}`,s=await Is();await se(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let{branchesToRemove:i}=hS({releasePRsList:s,currentWorktrees:t}),a=await ct({branches:i,worktreeDir:o,projectRoot:n});return await pt({projectRoot:n,worktreeDir:o,currentWorktrees:t,removedWorktrees:a.removed,allowEditorRelaunch:!1}),to(a),h.print(),no({result:a,operation:"sync worktrees"})}catch(t){throw ue(t)||t instanceof g?t:(l.error({error:t},"\u274C Error managing worktrees"),new g(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},hS=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>Oo(s)).filter(s=>!r.includes(s))}},$l=k({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:bo.array(bo.string()).describe("List of removed worktree branches"),failedWorktrees:bo.array(bo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:bo.number().describe("Number of worktrees removed during sync")},handler:ci});var _l=[{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"}],tt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:va,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:bc,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:jc,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Xc,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:Qc,mcpExposed:!0,mutating:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Dc,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Mc,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Ec,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:cl,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Kc,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:qc,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Al,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Cl,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Il,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:$l,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:fc,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Sa,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:_a,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:mc,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:gc,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:fa,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:Sl,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"setup",menuGroup:"setup",mcpTool:ml,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:pc,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:ma,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:xl,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-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-autoload"]},{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 Ol=e=>tt.filter(r=>r.menuGroup===e),Dl=e=>tt.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);var vS=(e,r)=>{let t=e,n;for(let o of r){if(n=t.find(s=>s.name()===o),!n)return;t=n.commands}return n},qf=e=>_l.flatMap(({key:r,label:t})=>Ol(r).flatMap(n=>{let o=vS(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:t}]:[]}));import Nl from"node:process";var yS="MODULE_TYPELESS_PACKAGE_JSON",wS=(e,r)=>typeof e=="object"&&e!==null?e.code:r,Hf=!1,Ml=()=>{if(Hf)return;Hf=!0;let e=Nl.emitWarning.bind(Nl);Nl.emitWarning=((r,...t)=>{wS(t[0],t[1])!==yS&&e(r,...t)})};import{Command as KS}from"commander";import{resolve as qS}from"node:path";import _e from"node:process";import{cd as HS}from"zx";import zf from"node:process";import{$ as kS}from"zx";var jl=async()=>{let e=await V(),r=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 G(i.path)}))),t=r.at(-1)?.exists===!0,n=await Fn(e.userProject,t),o=t?Ln(n):"";l.info(`Project name: ${e.projectName}
413
+ `)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},kl=b({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:Zr.array(Zr.object({version:Zr.string().describe("Release version"),type:Zr.enum(["regular","hotfix"]).describe("Release type"),description:Zr.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Zr.number().describe("Number of worktrees")},handler:Zs});import{z as Qt}from"zod";var mS=e=>{if(Z()){if(e.all)throw new T({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 T({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"})}},fS=(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(", ")}`})},gS=async(e,t)=>{let r=await _o(t.map(n=>`${e}/${n}`));if(r!==null)throw new T({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`})},Qs=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await ue({operation:"remove worktrees"}),await $(),mS({all:r,versions:n});try{let o=await ve("release");if(o.length===0){l.info("\u2139\uFE0F No active worktrees to remove"),g.print();let p={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}let s=await R(),i=`${s}${he}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(p=>De(Ee(p.trim())));else{g.setInteractive();let[p,u]=await Promise.all([X(),O()]),m=new Map(u.map(h=>[h.branch,h.type]));a=await Hr(se({branches:o,descriptions:p,types:m}),{required:!0})}fS(a,o);let c=a.length===o.length;c?g.addOption("--all",!0):g.addOption("--versions",Ut(a)),await gS(i,a),await Q(t,"Are you sure you want to proceed with these worktree changes?"),t||g.addOption("--yes",!0);let d=await qt({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await zt({projectRoot:s,worktreeDir:i,removedWorktrees:d.removed}),Yn(d),g.print(),zn({result:d,operation:"remove worktrees"})}catch(o){throw le(o)||o instanceof f?o:(l.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"}))}},bl=b({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:Qt.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:Qt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Qt.array(Qt.string()).describe("List of removed git worktree branches"),failedWorktrees:Qt.array(Qt.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Qt.number().describe("Number of git worktrees removed")},handler:Qs});import{z as go}from"zod";var ei=async e=>{let{confirmedCommand:t}=e;await ue({operation:"sync worktrees"}),await $();try{let r=await ve("release"),n=await R(),o=`${n}${he}`,s=await Es();await Q(t,"Are you sure you want to proceed with these worktree changes?"),t||g.addOption("--yes",!0);let{branchesToRemove:i}=hS({releasePRsList:s,currentWorktrees:r}),a=await qt({branches:i,worktreeDir:o,projectRoot:n});return await zt({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),Yn(a),g.print(),zn({result:a,operation:"sync worktrees"})}catch(r){throw le(r)||r instanceof f?r:(l.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"}))}},hS=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>xo(s)).filter(s=>!t.includes(s))}},Rl=b({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:go.array(go.string()).describe("List of removed worktree branches"),failedWorktrees:go.array(go.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:go.number().describe("Number of worktrees removed during sync")},handler:ei});var Pl=[{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"}],Vt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:ca,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:fc,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:$c,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Gc,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Kc,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Tc,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ac,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:hc,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Qc,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Lc,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Jc,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:wl,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:kl,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:bl,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Rl,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:nc,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Qa,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:rc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Za,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:oc,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:sa,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:hl,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"setup",menuGroup:"setup",mcpTool:ol,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:za,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:oa,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:vl,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 El=e=>Vt.filter(t=>t.menuGroup===e),Sl=e=>Vt.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var vS=(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},Wf=e=>Pl.flatMap(({key:t,label:r})=>El(t).flatMap(n=>{let o=vS(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import xl from"node:process";var yS="MODULE_TYPELESS_PACKAGE_JSON",wS=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Gf=!1,Tl=()=>{if(Gf)return;Gf=!0;let e=xl.emitWarning.bind(xl);xl.emitWarning=((t,...r)=>{wS(r[0],r[1])!==yS&&e(t,...r)})};import{Command as MS,InvalidArgumentError as jS}from"commander";import{resolve as FS}from"node:path";import Ae from"node:process";import{cd as LS}from"zx";import Uf from"node:process";import{$ as kS}from"zx";var Cl=async()=>{let e=await q(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await K(i.path)}))),r=t.at(-1)?.exists===!0,n=await Pn(e.userProject,r),o=r?En(n):"";l.info(`Project name: ${e.projectName}
446
414
  `),l.info(`Config merge chain (later overrides earlier):
447
- `);for(let i of r){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";l.info(`${a} ${i.label.padEnd(22)} ${y(i.path)}${c}`)}let s={projectName:e.projectName,layers:r.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}},Fl=async()=>{let e=await V(),r=zf.env.EDITOR||zf.env.VISUAL||"vi",t=await Vt(e);t.createdConfig&&l.info(Jt(t)),l.info(`Opening ${y(e.userProject)} in ${r} (per-machine override \u2014 every key except "mcp")`),await kS({stdio:"inherit"})`${r} ${e.userProject}`,Ke();let n={path:e.userProject,editor:r};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Ll=e=>{if(typeof e!="object"||e===null)return null;let{config:r,reason:t,at:n}=e;return typeof r!="string"||r.length===0||typeof t!="string"||typeof n!="number"||!Number.isFinite(n)?null:{config:r,reason:t,at:n}},Ro=e=>`infra-kit: Doppler token for env "${e}" is missing, invalid, or unreadable \u2014 env auto-load is not running. Fix: run \`infra-kit env-token-set ${e}\` (mint one at https://dashboard.doppler.com under this config's Access tab).`;import K from"node:fs";import $e from"node:path";import Eo from"node:process";var bS="autoload-warn-fail.flag",Wl="autoload-warn-auth-fail.flag",Vl="autoload-fail.flag",Jl="autoload-auth-fail.json",RS=3e4,Zf=async(e=!0)=>{let r;try{r=await P()}catch{return null}let t=r.envAutoLoad;if(!t)return null;let n={trigger:t.trigger,config:t.config,project:r.envManagement.config.name};try{if(await au(t.config))return n}catch{return n}return Qf({config:t.config,reason:`No Doppler service token for env "${t.config}"`,at:Date.now()}),e&&li(Ro(t.config),Wl),null},Xf=e=>{let{trigger:r,expectedTrigger:t,targetConfig:n,targetProject:o,env:s,force:i}=e;return r!==t||!s.session||s.cleared||s.currentConfig&&!s.autoLoadedMarker||!i&&s.autoLoadedMarker&&s.currentConfig===n&&s.currentProject===o?"skip":"load"},Po=async({expectedTrigger:e,projectDir:r,force:t,isAuthFailure:n=ep})=>{let o=e==="cli-invocation";o&&di();let s=null;try{if(s=await Zf(o),!s||Xf({trigger:s.trigger,expectedTrigger:e,targetConfig:s.config,targetProject:s.project,env:SS(),force:t})==="skip"||Yf()||AS())return null;let a=xS(),c=await cs({config:s.config,autoLoaded:!0,projectDir:r,beforeWrite:()=>!Yf()&&!TS(a)});return c?(IS(),PS(),c.filePath):null}catch(i){let a=i.message,c=n(i);return CS(),c&&s&&Qf({config:s.config,reason:a,at:Date.now()}),o&&c&&s?(li(Ro(s.config),Wl),l.debug(`env auto-load auth failure: ${a}`)):o?li(`infra-kit: env auto-load failed \u2014 ${a} (will retry later)`,bS):l.debug(`env auto-load skipped: ${a}`),null}},di=()=>{let e=ES();e&&(li(Ro(e.config),Wl),l.debug(`env auto-load auth failure (recorded ${new Date(e.at).toISOString()}): ${e.reason}`))},ES=()=>{try{let e=K.readFileSync($e.join(z(),Jl),"utf-8");return Ll(JSON.parse(e))}catch{return null}},Qf=e=>{try{let r=z();K.mkdirSync(r,{recursive:!0,mode:448}),Ue($e.join(r,Jl),JSON.stringify(e),384)}catch{}},PS=()=>{try{K.rmSync($e.join(z(),Jl),{force:!0})}catch{}},SS=()=>({session:Eo.env[Ge],cleared:Eo.env[mr],currentConfig:Eo.env[pr],currentProject:Eo.env[ur],autoLoadedMarker:Eo.env[Ne]}),xS=()=>{try{return K.statSync($e.join(z(),te)).mtimeMs}catch{return null}},TS=e=>{try{let r=$e.join(z(),te);if(!K.existsSync(r))return!1;let t=K.statSync(r).mtimeMs;return e!==null&&t<=e?!1:new RegExp(`^unset ${Ne}$`,"m").test(K.readFileSync(r,"utf-8"))}catch{return!1}},Yf=()=>{try{let e=z(),r=$e.join(e,gt);if(!K.existsSync(r))return!1;let t=$e.join(e,te);return K.existsSync(t)?K.statSync(r).mtimeMs>=K.statSync(t).mtimeMs:!0}catch{return!1}},AS=()=>{try{let e=$e.join(z(),Vl);return K.existsSync(e)?Date.now()-K.statSync(e).mtimeMs<RS:!1}catch{return!1}},CS=()=>{try{let e=z();K.mkdirSync(e,{recursive:!0,mode:448}),K.writeFileSync($e.join(e,Vl),"",{mode:384})}catch{}},IS=()=>{try{K.rmSync($e.join(z(),Vl),{force:!0})}catch{}},li=(e,r)=>{try{let t=z(),n=$e.join(t,r);if(K.existsSync(n))return;K.mkdirSync(t,{recursive:!0,mode:448}),K.writeFileSync(n,"",{mode:384})}catch{}l.warn(e)};var Bl=async({projectDir:e}={})=>{await Po({expectedTrigger:"shell-startup",projectDir:e,force:!0})};var eg="https://dashboard.doppler.com/workplace/projects",$S=(e,r)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${r}"): ${eg}/${e}`],Gl=async({env:e})=>{let t=!!(await oe())?.envs[e];await tp(e);let n=await Nn(),o=await Ae(),s=await qe();t?l.info(`Removed the "${e}" service token from ${y(s)}.`):l.info(`No "${e}" service token was stored in ${y(s)} \u2014 nothing to remove.`),n.length>0&&l.info(`Purged ${n.length} warm cache(s) across this repo's worktrees.`);for(let a of $S(o,e))l.warn(a);let i={env:e,removed:t,storePath:s,warmCachesPurged:n.length,revokeUrl:`${eg}/${o}`};return{content:w(JSON.stringify(i,null,2)),structuredContent:i}};import _S from"@inquirer/password";import ui from"node:process";import{$ as pi}from"zx";var OS=async({stdin:e,fromEnv:r})=>{if(e)return{token:await DS(),source:"stdin"};if(r){let n=ui.env[r];if(!n)throw new Error(`${r} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return h.setInteractive(),{token:(await S(n=>_S({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:ui.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},DS=async()=>{let e=[];ui.stdin.setEncoding("utf8");for await(let r of ui.stdin)e.push(r);return e.join("").trim()},Ul="DOPPLER_CONFIG",NS=3e4,MS=async(e,r,t)=>{let n=pi.quiet;pi.quiet=!0;let o;try{o=(await pi({env:kr(e)})`doppler secrets download --no-file --format json --project ${r} --config ${t}`.timeout(NS)).stdout}catch(s){throw jS(s,t)}finally{pi.quiet=n}return ps(o)},jS=(e,r)=>{let t=vt(e)??(e instanceof Error?e.message:String(e));if(Ur(t)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Kr(t)==="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 "${r}" \u2014 ${n}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
448
- `))},FS=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Ul}.`,"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(`
449
- `),Kl=async({env:e,stdin:r,fromEnv:t,force:n})=>{let o=await Ae(),{token:s,source:i}=await OS({stdin:r,fromEnv:t});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await MS(s,o,e);ds(a,e);let c=a.some(([m])=>m===Ul);if(!c&&!n)throw new Error(FS(e));await rp(e,s);let d=await Nn(),p=await qe();l.info(`Stored the "${e}" service token (${rn(s)}) in ${y(p)} (mode 0600).`),c||l.warn(`Scope was NOT verified (no ${Ul} in the payload) \u2014 written because --force was given.`),d.length>0&&l.info(`Purged ${d.length} warm cache(s) so the next shell cannot serve secrets fetched with an old token.`);let u={env:e,source:i,redactedToken:rn(s),storePath:p,scopeVerified:c,warmCachesPurged:d.length};return h.print(),{content:w(JSON.stringify(u,null,2)),structuredContent:u}};var ql=async(e,r,t=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:d,printEnv:p}=e,u=await _c(n);return t&&h.addOption("--from",u),$c(u,{"--version":o,"--skip-terraform":a,"--dry-run":d,"--print-env":p}),u==="local"?r==="all"?Bs({env:s,confirmedCommand:c,dryRun:d,printEnv:p}):Gs({env:s,service:i,confirmedCommand:c,dryRun:d,printEnv:p}):r==="all"?js({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Fs({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Hl=async e=>ql(e,"all"),zl=async e=>ql(e,"selected"),mi=async(e,r)=>{let t=`release deploy-${r} --from local`;return l.warn(`\`local deploy-${r}\` is deprecated and will be removed \u2014 use \`${t}\` instead.`),ql({...e,from:"local"},r,!1)};import{VENDOR_CONFIG_FILE as tg}from"@slip-stream-kit/config/internal";import Yl from"node:fs/promises";import Zl from"node:path";import rg from"node:process";import{pathToFileURL as LS}from"node:url";var ng="~/projects",Xl=async(e={})=>{if(e.init){await VS(e.cwd);return}await WS()},WS=async()=>{let e=Gt(),r=await G(e);if(l.info(`Factory config: ${y(e)} ${r?"[\u2713]":"[ ]"}`),!r){l.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),rg.exitCode=1;return}let{workspaceDir:t,targets:n}=await Ou(),o=_u(t),s=await G(o);l.info(`workspaceDir: ${t} (resolved: ${o}) ${s?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=s;for(let a of n){let c=Zl.join(o,a),d=await G(c);d||(i=!1);let p=d?"[\u2713]":"[ ]",u=d?"":" (not found \u2014 clone or remove)";l.info(` ${p} ${a} ${y(c)}${u}`)}i||(rg.exitCode=1)},VS=async e=>{let r=Gt();if(await G(r)){l.info(`Factory config already exists at ${y(r)} \u2014 leaving it untouched.`);return}let t=e??await b(),n=await JS(t);await Yl.mkdir(Zl.dirname(r),{recursive:!0}),await Yl.writeFile(r,BS(n),"utf-8"),l.info(`\u2713 Created ${y(r)}`),n.length>0&&l.info(` Seeded ${n.length} target(s) from the source ${tg}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${ng}) to point at where your repos live.`),n.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},JS=async e=>{try{let r=Zl.join(e,tg),t=await Yl.stat(r),s=(await import(`${LS(r).href}?mtime=${Number(t.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[]},BS=e=>`${JSON.stringify({workspaceDir:ng,targets:e},null,2)}
450
- `;var fi=(e,r=!0)=>({line:e,reproducible:r});import gi from"node:fs";import GS from"node:os";import US from"node:path";import ag from"node:process";var hi="INFRA_KIT_SESSION_REPORT",Ql=null,og=!1,sg=[],cg=(e=ag.env)=>{og||(Ql=e[hi]??null,og=!0,delete e[hi])};var lg=(e,r)=>{if(!Ql)return;let t=e.summary??(sg.length>0?[...sg]:void 0),n={...e,...t?{summary:t}:{}},o=r?.write??((s,i)=>{gi.writeFileSync(s,i)});try{o(Ql,JSON.stringify(n))}catch{}},ig=0,dg=e=>{let r=e?.tmpdir?.()??GS.tmpdir(),t=e?.pid??ag.pid;return ig+=1,US.join(r,`infra-kit-session-${t}-${ig}.json`)},pg=(e,r)=>{if(!(r?.exists??(i=>gi.existsSync(i)))(e))return null;let n=r?.read??(i=>gi.readFileSync(i,"utf-8")),o=r?.unlink??(i=>gi.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var ed=e=>{e.options.some(t=>t.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(ed)};var rd=e=>{e.options.some(t=>t.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(rd)};var zS=(e,r)=>[...r,e],ug=(e,r)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&ut.includes(e))return e;throw new Error(`Invalid ${r} value "${String(e)}". Expected one of: ${ut.join(", ")}.`)}},YS=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").action(async r=>{let t=await Fm(()=>Os({all:r.all,versions:r.versions,dryRun:r.dryRun,verify:r.verify,confirmedCommand:r.yes}));E(t),t.structuredContent.failedMerges>0&&(_e.exitCode=1)}),mg=e=>(_e.stdout.write(`${e.structuredContent.filePath}
451
- `),E(e)),ZS=e=>e.description("List all release branches").action(async()=>{E(await Ls())}),XS=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>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',zS,[]).option("-y, --yes","Skip confirmation prompt").action(async r=>{let n=r.release.map(sc),o=n.length>0?n:void 0;E(await Ks({releases:o,confirmedCommand:r.yes}))}),QS=e=>e.description("Edit a release's description in Jira and 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("-y, --yes","Skip confirmation prompt").action(async r=>{E(await qs({version:r.version,description:r.description,confirmedCommand:r.yes}))}),fg=e=>e.option("-f, --from <where>",`Where the deploy runs: ${$r.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"),ex=e=>fg(e).description("Deploy every service to any environment, in CI or from this machine").action(async r=>{E(await Hl({from:r.from,version:r.version,env:r.env,skipTerraform:r.skipTerraform,yes:r.yes,dryRun:r.dryRun,printEnv:r.printEnv}))}),rx=e=>fg(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 r=>{E(await zl({from:r.from,version:r.version,env:r.env,services:r.services,skipTerraform:r.skipTerraform,yes:r.yes,dryRun:r.dryRun,printEnv:r.printEnv}))}),tx=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 r=>{E(await Ms({version:r.version,confirmedCommand:r.yes}))}),nx=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 r=>{E(await Qs({version:r.version,moveIssuesTo:r.moveIssuesTo,skipJira:r.skipJira,confirmedCommand:r.yes}))}),ox=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async r=>{E(await ci({confirmedCommand:r.yes}))}),sx=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 r=>{let t=ug(r.ide,"--ide")??ug(r.cursor,"--cursor");E(await si({confirmedCommand:r.yes,all:r.all,versions:r.versions,ide:t,githubDesktop:r.githubDesktop,orca:r.orca}))}),ix=e=>e.description("List all git worktrees with detailed information").action(async()=>{E(await ii())}),ax=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 r=>{E(await ai({confirmedCommand:r.yes,all:r.all,versions:r.versions}))}),cx=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 r=>{E(await Xl({init:r.init}))}),lx=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let r=await ti();E(r),r.structuredContent.ok||(_e.exitCode=1)}),dx=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{E(await jl())}),px=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{E(await Fl())}),ux=new Set(["setup","doctor","version","dev"]),mx=e=>e.startsWith("env-")||ux.has(e),fx=new Set(["env-autoload","version"]),vi=e=>{let r=[];for(let t=e;t&&t.parent;t=t.parent)r.unshift(t.name());return r.join(" ")},td=()=>{let e=new KS().option("-C <dir>","Run as if infra-kit was started in <dir> instead of the current working directory"),r=e.command("release").description("Release management commands");YS(r.command("merge-dev")),ZS(r.command("list")),XS(r.command("create")),QS(r.command("desc-edit")),ex(r.command("deploy-all")),rx(r.command("deploy-selected")),tx(r.command("deliver")),nx(r.command("remove"));let t=e.command("worktrees").description("Git worktree management commands");sx(t.command("add")),ix(t.command("list")),ax(t.command("remove")),ox(t.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");dx(n.command("path")),px(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{E(await rs())});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=>{E(await mi({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=>{E(await mi({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){l.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),_e.exitCode=1;return}let c=await es({all:a.all,root:a.root,fix:a.fix,design:a.design});E(c);let{allPassed:d,fixed:p}=c.structuredContent,u=(p??[]).some(m=>m.action==="failed");(!d||u)&&(_e.exitCode=1)});let i=e.command("vendor").description("Verify the mirrored vendor/ tree");return lx(i.command("check")),cx(i.command("config")),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 Ps({fix:!!a.fix});gn.enabled||ba(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(p=>p.name==="plugin installed"&&p.status==="fail")&&(_e.exitCode=1),E(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").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:d}=await import("./dev-server.js"),p=!!(_e.stdout.isTTY&&_e.stdin.isTTY);await d({...c,preset:a},p,gn.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{E(await ns())}),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, 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").action(async a=>{E(await ri({tools:a.tools,update:a.update,skipTools:a.skipTools}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{E(await ni())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{E(await xs())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{E(await is())}),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=>{mg(await ls({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").option("--purge","Also delete this project's warm cache outright (durable disable)").action(async a=>{mg(await Ss({purge:!!a.purge}))}),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)=>{E(await Kl({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=>{E(await Ts({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=>{E(await Gl({env:a}))}),e.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").option("--project-dir <dir>","Canonical project dir for the warm-cache key (shell-startup only)").action(async a=>{await Bl({projectDir:a.projectDir})}),e.commands.forEach($d),ed(e),rd(e),e.hook("preAction",async(a,c)=>{let{C:d}=e.opts();d!==void 0&&HS(qS(_e.cwd(),d)),h.start(vi(c)),gn.enabled=!!c.optsWithGlobals().json,gn.enabled&&(l.level="warn"),I.source=$o({env:_e.env,stdinIsTTY:_e.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),fx.has(vi(c))||await Ma(),di(),mx(c.name())||await Po({expectedTrigger:"cli-invocation"})}),e.hook("postAction",(a,c)=>{let d=vi(c);if(Dl(d))return;let u=h.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",v=`infra-kit ${d}${m}`;lg({equivalent:fi(v,!0)})}),e};import gx from"node:process";var hx={exit:gx.exit,emit:E,logger:l},gg=(e,r=hx)=>ue(e)?(r.logger.info("Operation cancelled."),r.exit(0)):e instanceof A?(r.emit({structuredContent:e.structuredContent}),r.logger.error(e.message),r.exit(e.exitCode)):(r.logger.error(e instanceof Error?e.message:String(e)),r.exit(1));var nd=(e,r=" ")=>{let t=e.reduce((n,[o])=>Math.max(n,o.length),0);return e.map(([n,o])=>`${n.padEnd(t)}${r}${o}`)};import{chalkStderr as jx}from"chalk";import{spawn as Fx}from"node:child_process";import ve from"node:process";import{Chalk as vx}from"chalk";var pn=new vx({level:1}),Oe={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},yx={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"}},hg={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},vg={unicode:"\u2500",ascii:"-"},wx=3,od=e=>e,kx={ok:e=>pn.green(e),findings:e=>pn.yellow(e),failed:e=>pn.red(e),cancelled:e=>pn.gray(e)},id=e=>e?{dim:r=>pn.dim(r),bold:r=>pn.bold(r)}:{dim:od,bold:od},bx=(e,r)=>e?kx[r]:od,sd=e=>[...e].length,Rx=(e,r)=>{if(r==null)return e;let t=Math.max(0,r-1);return sd(e)<=t?e:[...e].slice(0,t).join("")},yg=e=>{let r=id(e.color===!0).dim,t=yx[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?t.ascii:t.unicode;return r(Rx(n,e.width))},wg=(e,r={})=>{let t=id(r.color===!0);return`${t.dim(Oe.reproPrefix.trim())} ${t.bold(e)}`},Ex=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,Px=(e,r)=>e==="findings"?r!=null?`${r} ${Oe.findingsSuffix}`:Oe.findingsPlain:{ok:Oe.ok,failed:Oe.failed,cancelled:Oe.cancelled}[e],Sx=(e,r,t,n)=>{if(r==null)return"";let o=r-2-e;return o<wx?"":` ${n(t.repeat(o))}`},kg=e=>{let r=e.color===!0,t=id(r),n=bx(r,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Oe.reproPrefix:Oe.nonReproPrefix,i=o?hg[e.outcome].ascii:hg[e.outcome].unicode,a=Px(e.outcome,e.findingsCount),c=[Ex(e.durationMs)],d=e.summary?.[0]?.split(`
452
- `)[0];d!=null&&d.length>0&&c.push(d);let p=`${i} ${a}`,u=`${Oe.sep}${c.join(Oe.sep)}`,m=sd(p)+sd(u),v=Sx(m,e.width,o?vg.ascii:vg.unicode,t.dim),f=[`${n(p)}${t.dim(u)}${v}`];return e.showEquivalent!==!1&&f.unshift(`${t.dim(s.trim())} ${t.bold(e.equivalent.line)}`),e.envNotice===!0&&f.push(t.dim(Oe.envNotice)),f.join(`
453
- `)};var xx=new Set([130,143]),bg=(e,r,t,n=!1)=>t?r!=null||e===0?"ok":"findings":n&&e!=null&&xx.has(e)||r==="SIGINT"||e===0?"cancelled":"failed";import Tx from"node:process";var Ax={3:"quit",4:"quit",26:"suspend",27:"quit"},Cx=e=>{if(e.length!==1)return"continue";let r=typeof e=="string"?e.charCodeAt(0):e[0];return r===void 0||Number.isNaN(r)?"continue":Ax[r]??"continue"},Ix=150,$x="\r\x1B[2K",_x=`\r
454
- `,Rg=(e,r)=>{Eg(e),e.stdin.on("data",r),e.listener=r},Eg=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},Pg=(e,r)=>{op(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Rg(e,r)},Sg=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write($x)),Eg(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),sp()},Ox=e=>{e.settled||(e.settled=!0,Sg(e))},xg=(e,r)=>{let t=yg({canSuspend:e.deps.suspend!==void 0,ascii:e.deps.ascii,color:e.deps.color,width:e.deps.columns()});e.deps.write(r+t),e.hintOnScreen=!0},Dx=async e=>{await new Promise(r=>{setTimeout(r,e)})},Nx=(e,r,t)=>{Sg(e),r(),Pg(e,t),xg(e,_x)},Mx=async e=>new Promise(r=>{let t=n=>{let o=Cx(n),s=e.deps.suspend;if(o==="quit"){r("quit");return}if(o==="suspend"&&s!==void 0){Nx(e,s,t);return}r("palette")};Rg(e,t),xg(e,"")}),Tg=async(e,r)=>{if(e.quitRequested())return"quit";let t=r.stdin??Tx.stdin;if(t.isTTY!==!0)return"palette";let n={deps:r,stdin:t,listener:null,hintOnScreen:!1,settled:!1};try{return Pg(n,()=>{}),e.armed(),await Dx(r.drainMs??Ix),await Mx(n)}finally{Ox(n)}};import Ag from"node:process";var Dr={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Cg=(e,r)=>{let t=r?.write??(s=>{Ag.stderr.write(s)}),n=r?.stdin??Ag.stdin,o=[Dr.saveCursor,Dr.scrollRegion,Dr.restoreCursor,Dr.column,Dr.sgr,Dr.cursor,Dr.wrap];e.entersAltScreen===!0&&o.push(Dr.primaryBuffer),t(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var Ig=e=>`infra-kit ${e.groupPath.join(" ")}`,Lx=()=>{Wx();let e=ve.stderr.columns;return e!=null&&e>0?e:void 0},Wx=()=>{let e=ve.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},Vx=e=>new Promise(r=>{e.on("exit",(t,n)=>{r({code:t,signal:n})}),e.on("error",()=>{r({code:1,signal:null})})}),Jx=async(e,r,t)=>{let n=dg(),o={...r.env,[hi]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=r.now(),i={code:1,signal:null};t();try{let u=r.spawn(ve.execPath,[r.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await Vx(u)}catch{i={code:1,signal:null}}finally{r.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=pg(n),c=bg(i.code,i.signal,a!=null,e.longRunning),d=Ig(e),p=a?.equivalent??fi(d,!0);return kg({equivalent:p,outcome:c,durationMs:r.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:r.ascii,color:r.color,width:r.columns(),showEquivalent:!(p.reproducible&&p.line===d)})},Bx=1e3,Gx=(e,r)=>e!=null&&r-e<=Bx,ad=e=>{e.resetTerminal(),e.exit(0)},Ux=(e,r)=>{let t=null,n=!1,o=()=>{let c=e();if(c==="child"){t=r.now();return}c!=="pause"&&ad(r)},s=()=>{let c=e();if(c==="palette"){ad(r);return}if(!Gx(t,r.now())){if(c==="pause"){ad(r);return}n=!0}},i=()=>{r.exit(129)},a=()=>{e()==="child"&&r.raise("SIGSTOP")};return r.register("SIGINT",o),r.register("SIGTERM",s),r.register("SIGHUP",i),r.register("SIGTSTP",a),{dispose:()=>{r.unregister("SIGINT",o),r.unregister("SIGTERM",s),r.unregister("SIGHUP",i),r.unregister("SIGTSTP",a)},childStarted:()=>{t=null},quitRequested:()=>n}},$g=(e,r)=>!!(r.stdoutIsTTY&&r.stdinIsTTY&&r.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),Kx=ve.platform==="win32"?void 0:()=>{fp()},qx=(e,r)=>t=>Tg(t,{write:e,columns:r.columns,ascii:r.ascii,color:r.color,suspend:Kx}),_g=async(e,r)=>{let t={spawn:r.spawn??Fx,now:r.now??(()=>Date.now()),env:r.env??ve.env,cliPath:r.cliPath,ascii:r.ascii??!(ve.stdout.isTTY&&ve.env.TERM!=="dumb"),color:r.color??jx.level>0,columns:r.columns??Lx,resetTerminal:r.resetTerminal??(p=>{Cg(p)})},n=r.write??(p=>ve.stderr.write(p)),o="palette",s=r.signals??{register:(p,u)=>{ve.on(p,u)},unregister:(p,u)=>{ve.off(p,u)},exit:p=>{ve.exit(p)},raise:p=>{ve.kill(ve.pid,p)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),t.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=r.installSignals===!1?i:Ux(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},d=r.afterRun??qx(n,t);try{for(;;){if(a.quitRequested())return;o="palette";let p=await r.renderPalette(e);if(p==null)return;let u=r.resolveCommand(p);if(!u)continue;let m=wg(Ig(u),{color:t.color});n(`
415
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";l.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}},Al=async()=>{let e=await q(),t=Uf.env.EDITOR||Uf.env.VISUAL||"vi",r=await br(e);r.createdConfig&&l.info(Rr(r)),l.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await kS({stdio:"inherit"})`${t} ${e.userProject}`,lt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Kf="https://dashboard.doppler.com/workplace/projects",bS=(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}"): ${Kf}/${e}`],$l=async({env:e})=>{let r=!!(await ne())?.envs[e];await Gd(e);let n=await xe(),o=await We();r?l.info(`Removed the "${e}" service token from ${w(o)}.`):l.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of bS(n,e))l.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Kf}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import RS from"@inquirer/password";import ri from"node:process";import{$ as ti}from"zx";var PS=async({stdin:e,fromEnv:t})=>{if(e)return{token:await ES(),source:"stdin"};if(t){let n=ri.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return g.setInteractive(),{token:(await x(n=>RS({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:ri.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},ES=async()=>{let e=[];ri.stdin.setEncoding("utf8");for await(let t of ri.stdin)e.push(t);return e.join("").trim()},Il="DOPPLER_CONFIG",SS=3e4,xS=async(e,t,r)=>{let n=ti.quiet;ti.quiet=!0;let o;try{o=(await ti({env:Br(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(SS)).stdout}catch(s){throw TS(s,r)}finally{ti.quiet=n}return ys(o)},TS=(e,t)=>{let r=sr(e)??(e instanceof Error?e.message:String(e));if(It(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Dt(r)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${n}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
416
+ `))},CS=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Il}.`,"Refusing to store a credential whose scope is unknown (a token for the wrong environment would load","the wrong secrets into every shell).","Re-run with --force if you are certain the token is scoped to this config."].join(`
417
+ `),Dl=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await xe(),{token:s,source:i}=await PS({stdin:t,fromEnv:r});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await xS(s,o,e);vs(a,e);let c=a.some(([u])=>u===Il);if(!c&&!n)throw new Error(CS(e));await Wd(e,s);let d=await We();l.info(`Stored the "${e}" service token (${Gr(s)}) in ${w(d)} (mode 0600).`),c||l.warn(`Scope was NOT verified (no ${Il} in the payload) \u2014 written because --force was given.`);let p={env:e,source:i,redactedToken:Gr(s),storePath:d,scopeVerified:c};return g.print(),{content:k(JSON.stringify(p,null,2)),structuredContent:p}};var Ol=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:d,printEnv:p}=e,u=await Sc(n);if(r&&g.addOption("--from",u),Ec(u,{"--version":o,"--skip-terraform":a,"--dry-run":d,"--print-env":p}),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"?Is({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Ds({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Nl=async e=>Ol(e,"all"),_l=async e=>Ol(e,"selected"),ni=async(e,t)=>{let r=`release deploy-${t} --from local`;return l.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),Ol({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Hf}from"@slip-stream-kit/config/internal";import Ml from"node:fs/promises";import jl from"node:path";import qf from"node:process";import{pathToFileURL as AS}from"node:url";var Yf="~/projects",Fl=async(e={})=>{if(e.init){await IS(e.cwd);return}await $S()},$S=async()=>{let e=Er(),t=await K(e);if(l.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){l.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),qf.exitCode=1;return}let{workspaceDir:r,targets:n}=await eu(),o=Qp(r),s=await K(o);l.info(`workspaceDir: ${r} (resolved: ${o}) ${s?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=s;for(let a of n){let c=jl.join(o,a),d=await K(c);d||(i=!1);let p=d?"[\u2713]":"[ ]",u=d?"":" (not found \u2014 clone or remove)";l.info(` ${p} ${a} ${w(c)}${u}`)}i||(qf.exitCode=1)},IS=async e=>{let t=Er();if(await K(t)){l.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await R(),n=await DS(r);await Ml.mkdir(jl.dirname(t),{recursive:!0}),await Ml.writeFile(t,OS(n),"utf-8"),l.info(`\u2713 Created ${w(t)}`),n.length>0&&l.info(` Seeded ${n.length} target(s) from the source ${Hf}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${Yf}) to point at where your repos live.`),n.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},DS=async e=>{try{let t=jl.join(e,Hf),r=await Ml.stat(t),s=(await import(`${AS(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[]},OS=e=>`${JSON.stringify({workspaceDir:Yf,targets:e},null,2)}
418
+ `;var oi=(e,t=!0)=>({line:e,reproducible:t});import si from"node:fs";import NS from"node:os";import _S from"node:path";import Qf from"node:process";var ii="INFRA_KIT_SESSION_REPORT",Ll=null,zf=!1,Xf=[],eg=(e=Qf.env)=>{zf||(Ll=e[ii]??null,zf=!0,delete e[ii])};var tg=(e,t)=>{if(!Ll)return;let r=e.summary??(Xf.length>0?[...Xf]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{si.writeFileSync(s,i)});try{o(Ll,JSON.stringify(n))}catch{}},Zf=0,rg=e=>{let t=e?.tmpdir?.()??NS.tmpdir(),r=e?.pid??Qf.pid;return Zf+=1,_S.join(t,`infra-kit-session-${r}-${Zf}.json`)},ng=(e,t)=>{if(!(t?.exists??(i=>si.existsSync(i)))(e))return null;let n=t?.read??(i=>si.readFileSync(i,"utf-8")),o=t?.unlink??(i=>si.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Jl=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(Jl)};var Vl=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Vl)};var JS=(e,t)=>[...t,e],og=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&Xt.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${Xt.join(", ")}.`)}},VS=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").action(async t=>{let r=await Am(()=>Ts({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,confirmedCommand:t.yes}));E(r),r.structuredContent.failedMerges>0&&(Ae.exitCode=1)}),sg=e=>(Ae.stdout.write(`${e.structuredContent.filePath}
419
+ `),E(e)),BS=e=>e.description("List all release branches").action(async()=>{E(await Os())}),WS=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".',JS,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Ga),o=n.length>0?n:void 0;E(await Fs({releases:o,confirmedCommand:t.yes}))}),GS=e=>{if(e==="")return e;try{return Lt(e)}catch(t){throw t instanceof jr?new jS(t.message):t}},US=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)',GS).option("-y, --yes","Skip confirmation prompt").action(async t=>{E(await Ls({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),ig=e=>e.option("-f, --from <where>",`Where the deploy runs: ${wt.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"),KS=e=>ig(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{E(await Nl({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),qS=e=>ig(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=>{E(await _l({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),HS=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=>{E(await $s({version:t.version,confirmedCommand:t.yes}))}),YS=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=>{E(await Us({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),zS=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{E(await ei({confirmedCommand:t.yes}))}),XS=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=og(t.ide,"--ide")??og(t.cursor,"--cursor");E(await Xs({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),ZS=e=>e.description("List all git worktrees with detailed information").action(async()=>{E(await Zs())}),QS=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=>{E(await Qs({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),ex=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=>{E(await Fl({init:t.init}))}),tx=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Hs();E(t),t.structuredContent.ok||(Ae.exitCode=1)}),rx=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{E(await Cl())}),nx=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{E(await Al())}),ox=new Set(["version"]),ai=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Bl=()=>{let e=new MS().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");VS(t.command("merge-dev")),BS(t.command("list")),WS(t.command("create")),US(t.command("edit")),KS(t.command("deploy-all")),qS(t.command("deploy-selected")),HS(t.command("deliver")),YS(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");XS(r.command("add")),ZS(r.command("list")),QS(r.command("remove")),zS(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");rx(n.command("path")),nx(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{E(await Ho())});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=>{E(await ni({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=>{E(await ni({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){l.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Ae.exitCode=1;return}let c=await qo({all:a.all,root:a.root,fix:a.fix,design:a.design});E(c);let{allPassed:d,fixed:p}=c.structuredContent,u=(p??[]).some(m=>m.action==="failed");(!d||u)&&(Ae.exitCode=1)});let i=e.command("vendor").description("Verify the mirrored vendor/ tree");return tx(i.command("check")),ex(i.command("config")),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 ps({fix:!!a.fix});rn.enabled||ua(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(p=>p.name==="plugin installed"&&p.status==="fail")&&(Ae.exitCode=1),E(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").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:d}=await import("./dev-server.js"),p=!!(Ae.stdout.isTTY&&Ae.stdin.isTTY);await d({...c,preset:a},p,rn.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{E(await zo())}),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, 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").action(async a=>{E(await qs({tools:a.tools,update:a.update,skipTools:a.skipTools}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{E(await Ys())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{E(await ws())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{E(await fs())}),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=>{sg(await hs({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{sg(await us())}),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)=>{E(await Dl({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=>{E(await ks({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=>{E(await $l({env:a}))}),e.commands.forEach(kd),Jl(e),Vl(e),e.hook("preAction",async(a,c)=>{let{C:d}=e.opts();d!==void 0&&LS(FS(Ae.cwd(),d)),g.start(ai(c)),rn.enabled=!!c.optsWithGlobals().json,rn.enabled&&(l.level="warn"),A.source=Eo({env:Ae.env,stdinIsTTY:Ae.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),ox.has(ai(c))||await ha()}),e.hook("postAction",(a,c)=>{let d=ai(c);if(Sl(d))return;let u=g.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",h=`infra-kit ${d}${m}`;tg({equivalent:oi(h,!0)})}),e};import sx from"node:process";var ix={exit:sx.exit,emit:E,logger:l},ag=(e,t=ix)=>le(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof T?(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 Wl=(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{chalkStderr as Tx}from"chalk";import{spawn as Cx}from"node:child_process";import fe from"node:process";import{Chalk as ax}from"chalk";var Qr=new ax({level:1}),$e={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},cx={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"}},cg={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},lg={unicode:"\u2500",ascii:"-"},lx=3,Gl=e=>e,dx={ok:e=>Qr.green(e),findings:e=>Qr.yellow(e),failed:e=>Qr.red(e),cancelled:e=>Qr.gray(e)},Kl=e=>e?{dim:t=>Qr.dim(t),bold:t=>Qr.bold(t)}:{dim:Gl,bold:Gl},px=(e,t)=>e?dx[t]:Gl,Ul=e=>[...e].length,ux=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Ul(e)<=r?e:[...e].slice(0,r).join("")},dg=e=>{let t=Kl(e.color===!0).dim,r=cx[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(ux(n,e.width))},pg=(e,t={})=>{let r=Kl(t.color===!0);return`${r.dim($e.reproPrefix.trim())} ${r.bold(e)}`},mx=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,fx=(e,t)=>e==="findings"?t!=null?`${t} ${$e.findingsSuffix}`:$e.findingsPlain:{ok:$e.ok,failed:$e.failed,cancelled:$e.cancelled}[e],gx=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<lx?"":` ${n(r.repeat(o))}`},ug=e=>{let t=e.color===!0,r=Kl(t),n=px(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?$e.reproPrefix:$e.nonReproPrefix,i=o?cg[e.outcome].ascii:cg[e.outcome].unicode,a=fx(e.outcome,e.findingsCount),c=[mx(e.durationMs)],d=e.summary?.[0]?.split(`
420
+ `)[0];d!=null&&d.length>0&&c.push(d);let p=`${i} ${a}`,u=`${$e.sep}${c.join($e.sep)}`,m=Ul(p)+Ul(u),h=gx(m,e.width,o?lg.ascii:lg.unicode,r.dim),y=[`${n(p)}${r.dim(u)}${h}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim($e.envNotice)),y.join(`
421
+ `)};var hx=new Set([130,143]),mg=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&hx.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import vx from"node:process";var yx={3:"quit",4:"quit",26:"suspend",27:"quit"},wx=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":yx[t]??"continue"},kx=150,bx="\r\x1B[2K",Rx=`\r
422
+ `,fg=(e,t)=>{gg(e),e.stdin.on("data",t),e.listener=t},gg=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},hg=(e,t)=>{ep(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),fg(e,t)},vg=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(bx)),gg(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),tp()},Px=e=>{e.settled||(e.settled=!0,vg(e))},yg=(e,t)=>{let r=dg({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},Ex=async e=>{await new Promise(t=>{setTimeout(t,e)})},Sx=(e,t,r)=>{vg(e),t(),hg(e,r),yg(e,Rx)},xx=async e=>new Promise(t=>{let r=n=>{let o=wx(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){Sx(e,s,r);return}t("palette")};fg(e,r),yg(e,"")}),wg=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??vx.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return hg(n,()=>{}),e.armed(),await Ex(t.drainMs??kx),await xx(n)}finally{Px(n)}};import kg from"node:process";var bt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},bg=(e,t)=>{let r=t?.write??(s=>{kg.stderr.write(s)}),n=t?.stdin??kg.stdin,o=[bt.saveCursor,bt.scrollRegion,bt.restoreCursor,bt.column,bt.sgr,bt.cursor,bt.wrap];e.entersAltScreen===!0&&o.push(bt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var Rg=e=>`infra-kit ${e.groupPath.join(" ")}`,Ax=()=>{$x();let e=fe.stderr.columns;return e!=null&&e>0?e:void 0},$x=()=>{let e=fe.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},Ix=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),Dx=async(e,t,r)=>{let n=rg(),o={...t.env,[ii]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let u=t.spawn(fe.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await Ix(u)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=ng(n),c=mg(i.code,i.signal,a!=null,e.longRunning),d=Rg(e),p=a?.equivalent??oi(d,!0);return ug({equivalent:p,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(p.reproducible&&p.line===d)})},Ox=1e3,Nx=(e,t)=>e!=null&&t-e<=Ox,ql=e=>{e.resetTerminal(),e.exit(0)},_x=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&ql(t)},s=()=>{let c=e();if(c==="palette"){ql(t);return}if(!Nx(r,t.now())){if(c==="pause"){ql(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}},Pg=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),Mx=fe.platform==="win32"?void 0:()=>{rp()},jx=(e,t)=>r=>wg(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:Mx}),Eg=async(e,t)=>{let r={spawn:t.spawn??Cx,now:t.now??(()=>Date.now()),env:t.env??fe.env,cliPath:t.cliPath,ascii:t.ascii??!(fe.stdout.isTTY&&fe.env.TERM!=="dumb"),color:t.color??Tx.level>0,columns:t.columns??Ax,resetTerminal:t.resetTerminal??(p=>{bg(p)})},n=t.write??(p=>fe.stderr.write(p)),o="palette",s=t.signals??{register:(p,u)=>{fe.on(p,u)},unregister:(p,u)=>{fe.off(p,u)},exit:p=>{fe.exit(p)},raise:p=>{fe.kill(fe.pid,p)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:_x(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},d=t.afterRun??jx(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let p=await t.renderPalette(e);if(p==null)return;let u=t.resolveCommand(p);if(!u)continue;let m=pg(Rg(u),{color:r.color});n(`
455
423
  ${m}
456
- `),a.childStarted();let v=await Jx(u,t,()=>{o="child"});if(n(`
457
- ${v}
458
- `),await d(c)==="quit")return}}finally{a.dispose()}};Ml();cg();var Mg=td(),Dg=async(e=ae.argv)=>{np(e);try{await Mg.parseAsync(e)}catch(r){gg(r)}},Xx=()=>{try{if(ae.env.INFRA_KIT_NO_LOCATION_WARN||ae.argv.includes("--json"))return;fd({selfRealPath:Yx(Ng(import.meta.url)),cwd:ae.cwd(),env:ae.env,realpath:de,home:Zx(),exists:zx})&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};ae.argv[2]==="mcp"&&(ae.stderr.write(`The "mcp" subcommand was retired in infra-kit 0.10.0: the Claude Code plugin's skills drive the CLI directly. Delete the "infra-kit" entry from .mcp.json (infra-kit doctor names the key).
459
- `),ae.exit(0));Xx();Id((e,r)=>{l.debug(e,r)});Fa(H.version);var jg=()=>qf(Mg.commands),Qx=async()=>{let e=jg(),r=null;try{if(ae.stdout.isTTY&&ae.stdin.isTTY){let{runCommandPalette:t}=await import("./boot-XLDVLQEG.js");r=await t(e)}else{let t=nd(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new Og(" "),new Og(`\u2014 ${o.group} \u2014`)],{name:t[s]??o.name,value:o.name}]);r=await S(o=>Hx({message:"Select a command to run",choices:n},o),{output:ae.stderr})}}catch(t){if(!ue(t))throw t}return r},eT=async()=>{let{runCommandPalette:e}=await import("./boot-XLDVLQEG.js"),r=Ng(import.meta.url),t=new Map(tt.map(n=>[n.groupPath.join(" "),n]));await _g(jg(),{renderPalette:e,resolveCommand:n=>{let o=t.get(n);return o?{groupPath:o.groupPath,entersAltScreen:o.entersAltScreen,sessionEnvNotice:o.sessionEnvNotice,longRunning:o.longRunning}:void 0},cliPath:r})};if(ae.argv.length<=2){let e={stdoutIsTTY:!!ae.stdout.isTTY,stdinIsTTY:!!ae.stdin.isTTY,stderrIsTTY:!!ae.stderr.isTTY};if($g(ae.env,e))await eT();else{let r=await Qx();r&&await Dg(["node","infra-kit",...r.split(" ")])}}else await Dg();
424
+ `),a.childStarted();let h=await Dx(u,r,()=>{o="child"});if(n(`
425
+ ${h}
426
+ `),await d(c)==="quit")return}}finally{a.dispose()}};Tl();eg();var Cg=Bl(),xg=async(e=ge.argv)=>{Qd(e);try{await Cg.parseAsync(e)}catch(t){ag(t)}},Bx=()=>{try{if(ge.env.INFRA_KIT_NO_LOCATION_WARN||ge.argv.includes("--json"))return;td({selfRealPath:Jx(Tg(import.meta.url)),cwd:ge.cwd(),env:ge.env,realpath:ie,home:Vx(),exists:Lx})&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};Bx();wd((e,t)=>{l.debug(e,t)});ya(U.version);var Ag=()=>Wf(Cg.commands),Wx=async()=>{let e=Ag(),t=null;try{if(ge.stdout.isTTY&&ge.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-XLDVLQEG.js");t=await r(e)}else{let r=Wl(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new Sg(" "),new Sg(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await x(o=>Fx({message:"Select a command to run",choices:n},o),{output:ge.stderr})}}catch(r){if(!le(r))throw r}return t},Gx=async()=>{let{runCommandPalette:e}=await import("./boot-XLDVLQEG.js"),t=Tg(import.meta.url),r=new Map(Vt.map(n=>[n.groupPath.join(" "),n]));await Eg(Ag(),{renderPalette:e,resolveCommand:n=>{let o=r.get(n);return o?{groupPath:o.groupPath,entersAltScreen:o.entersAltScreen,sessionEnvNotice:o.sessionEnvNotice,longRunning:o.longRunning}:void 0},cliPath:t})};if(ge.argv.length<=2){let e={stdoutIsTTY:!!ge.stdout.isTTY,stdinIsTTY:!!ge.stdin.isTTY,stderrIsTTY:!!ge.stderr.isTTY};if(Pg(ge.env,e))await Gx();else{let t=await Wx();t&&await xg(["node","infra-kit",...t.split(" ")])}}else await xg();
460
427
  //# sourceMappingURL=cli.js.map