infra-kit 0.14.0 → 0.15.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 (41) hide show
  1. package/dist/{chunk-MFHYIQ7B.js → chunk-3UE375II.js} +2 -2
  2. package/dist/{chunk-MFHYIQ7B.js.map → chunk-3UE375II.js.map} +1 -1
  3. package/dist/chunk-4RZM53X7.js +7 -0
  4. package/dist/{chunk-DW2SQ2XU.js.map → chunk-4RZM53X7.js.map} +3 -3
  5. package/dist/{chunk-VDBJ73LS.js → chunk-DVXTZPQ5.js} +1 -1
  6. package/dist/chunk-DVXTZPQ5.js.map +7 -0
  7. package/dist/{chunk-FRBNA6VH.js → chunk-EZ4DIT5A.js} +3 -3
  8. package/dist/{chunk-FRBNA6VH.js.map → chunk-EZ4DIT5A.js.map} +1 -1
  9. package/dist/chunk-I23MDR4X.js +5 -0
  10. package/dist/chunk-I23MDR4X.js.map +7 -0
  11. package/dist/{chunk-CMF7HEVU.js → chunk-IT6XJWTW.js} +2 -2
  12. package/dist/chunk-IT6XJWTW.js.map +7 -0
  13. package/dist/{chunk-BQPSXIH2.js → chunk-MH37P7W4.js} +2 -2
  14. package/dist/chunk-PP3ZZKB3.js +12 -0
  15. package/dist/chunk-PP3ZZKB3.js.map +7 -0
  16. package/dist/{chunk-EAUGQ3ZU.js → chunk-ZTAUGYJF.js} +2 -2
  17. package/dist/cli.js +117 -109
  18. package/dist/cli.js.map +4 -4
  19. package/dist/dev-server.js +21 -21
  20. package/dist/dev-server.js.map +3 -3
  21. package/dist/{dev-wizard-run-3DNKOVPD.js → dev-wizard-run-6PLC5YEW.js} +2 -2
  22. package/dist/env-load-NURS7WNH.js +2 -0
  23. package/dist/mcp-proxy.js +7 -7
  24. package/dist/mcp-proxy.js.map +3 -3
  25. package/dist/{persistent-ink-dev-ui-P65EJCC6.js → persistent-ink-dev-ui-ZSOS3CF4.js} +2 -2
  26. package/dist/update-check.js +1 -1
  27. package/package.json +3 -3
  28. package/readme.md +5 -2
  29. package/dist/chunk-CMF7HEVU.js.map +0 -7
  30. package/dist/chunk-DW2SQ2XU.js +0 -7
  31. package/dist/chunk-QSTGO43H.js +0 -4
  32. package/dist/chunk-QSTGO43H.js.map +0 -7
  33. package/dist/chunk-UD6VVXUY.js +0 -10
  34. package/dist/chunk-UD6VVXUY.js.map +0 -7
  35. package/dist/chunk-VDBJ73LS.js.map +0 -7
  36. package/dist/env-load-MF26WMDL.js +0 -2
  37. /package/dist/{chunk-BQPSXIH2.js.map → chunk-MH37P7W4.js.map} +0 -0
  38. /package/dist/{chunk-EAUGQ3ZU.js.map → chunk-ZTAUGYJF.js.map} +0 -0
  39. /package/dist/{dev-wizard-run-3DNKOVPD.js.map → dev-wizard-run-6PLC5YEW.js.map} +0 -0
  40. /package/dist/{env-load-MF26WMDL.js.map → env-load-NURS7WNH.js.map} +0 -0
  41. /package/dist/{persistent-ink-dev-ui-P65EJCC6.js.map → persistent-ink-dev-ui-ZSOS3CF4.js.map} +0 -0
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{a as gp,d as bp,f as cs,h as Rr,i as ls,j as Cp,k as $p,l as Ap,m as Op,n as Ip,o as Dp,p as Np,q as _p,t as pa,u as jp,v as ve}from"./chunk-EAUGQ3ZU.js";import{b as up,d as pp,k as mp,n as fp}from"./chunk-Y3RW74TE.js";import{a as mt,b as xu,c as ta,d as Tu,e as Cu,f as $u,g as Au,h as vn,i as Ou,j as Iu,k as Du,l as Nu,m as _u,n as wn,o as Mu,p as ju,q as Fu,r as Lu,s as ra,t as zo,u as ft,v as Bu,w as Xo,x as Vu}from"./chunk-CMF7HEVU.js";import{a as ae,b as K,c as wt,d as os,e as aa,f as ss,g as ca,h as bn,i as Ft,j as is,k as dp,l as Rn,m as Sn,n as la,o as da,q as ua}from"./chunk-BQPSXIH2.js";import{b as yn,c as qo,d as ea,e as bu,f as Yo,g as Ru,i as Su,k as Pu,m as me,o as Eu}from"./chunk-AWFGP6GY.js";import{a as kp}from"./chunk-TVG47UHG.js";import{D as ga,E as ha,a as k,b as S,c as Rp,d as Sp,e as br,f as Pp,g as Vt,h as Tp,i as Mp,j as Pn,k as kt,l as Sr,m as Ue,n as ds,o as bt,p as us,q as Fp,r as Lp,s as Je,v as ma,x as En,z as fa}from"./chunk-UD6VVXUY.js";import{a as h,b as nt,c as hp,d as yp,e as O,f as as,g as B,i as Lt,j as Bt,k as Ep,l as xp}from"./chunk-DW2SQ2XU.js";import{$ as ap,A as qu,B as Yu,C as zu,D as ts,E as rs,F as Ce,G as kn,H as kr,I as ns,J as Xu,K as Zu,L as Qu,M as oa,N as sa,O as ep,P as u,Q as We,R as X,S as v,T as tp,U as rp,V as np,W as sp,X as ht,Y as ip,Z as ia,_ as yt,a as rt,aa as cp,b as C,ba as ee,c as Wu,ca as M,d as I,da as lp,e as fe,ea as vt,f as ge,fa as x,g as Zo,h as Uu,i as f,j as Ju,k as Qo,l as J,m as ye,n as xe,o as Gu,p as na,q as te,r as z,s as es,t as Ku,u as gt,v as Te,w as E,x as je,y as wr,z as Hu}from"./chunk-FRBNA6VH.js";import{a as op}from"./chunk-MFAFQVTW.js";import{a as G}from"./chunk-MFHYIQ7B.js";import{a as gr,b as Uo,c as hn,d as gu,e as hr,f as Jo,g as Go,h as hu,i as Ko,j as Ho,k as yu,l as vu,m as wu,n as yr,o as ku,p as pe,q as vr}from"./chunk-QSTGO43H.js";import{a as vp,b as wp}from"./chunk-QWVLAZ6N.js";import _O,{Separator as nv}from"@inquirer/select";import{existsSync as MO,realpathSync as jO}from"node:fs";import{homedir as FO}from"node:os";import Ee from"node:process";import{fileURLToPath as sv}from"node:url";import xm from"node:process";import{z as Oe}from"zod";import Hp from"node:fs";import xr from"node:path";import{packageConfigSchema as Wp}from"@slip-stream-kit/config/internal";import Up from"node:fs/promises";import ps from"node:path";import{pathToFileURL as gv}from"node:url";import{z as Jp}from"zod";import Bp from"node:path";var xn=["frontend","backend","lib","e2e","mobile"],lv={ui:"frontend",api:"backend",tests:"e2e"},dv="mobile-app",uv=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],pv=(e,t)=>{let r=Bp.relative(t,e).split(Bp.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=lv[o];if(s)return s}return r.at(-1)===dv?"mobile":null},mv=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of uv)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Tn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??pv(e,t)??mv(r)??"lib";var Rt={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Vp=2e3,ya={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Vp}} pnpm exec playwright test --ui --headed --workers=1`,"e2e-test-chrome":"pnpm exec playwright test --project=chromium","e2e-test-debug":"pnpm exec playwright test --debug","e2e-test-codegen":"pnpm exec playwright codegen","playwright-install":"pnpm exec playwright install --with-deps"},Cn={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"]},$n=(e,t=Rt)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import fv from"node:fs/promises";var we=async e=>{try{return await fv.access(e),!0}catch{return!1}};var re="infra-kit.config.ts",Wt=async e=>{try{let t=await Up.readFile(ps.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},va=async e=>{let t=await Up.stat(e),o=(await import(`${gv(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${re} at ${e} has no default export`);return typeof o=="function"?await o():o},Ut=async e=>{let t=ps.join(e,re);if(await we(t))try{let n=(await va(t))?.type;return xn.find(o=>o===n)}catch{return}},An=async(e,t=Rt)=>{let r=ps.join(e,re);if(!await we(r))throw new Error(`${re} not found at ${r}`);let n=await va(r),o=Wp.safeParse(n);if(!o.success)throw new Error(`Invalid ${re} at ${r}: ${Jp.prettifyError(o.error)}`);return $n(o.data,t)},Pr=async e=>{let t=ps.join(e,re);if(!await we(t))return;let r=Wp.safeParse(await va(t));if(!r.success)throw new Error(`Invalid ${re} at ${t}: ${Jp.prettifyError(r.error)}`);return r.data};import Gp from"node:fs/promises";import ms from"node:path";import hv from"yaml";var yv="pnpm-workspace.yaml",vv=async e=>(await Gp.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>ms.join(e,r.name)),wv=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await vv(n));continue}let o=ms.join(n,t);await we(o)&&r.push(o)}return r},kv=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await wv(r,n);return r},ke=async e=>{let t=await Gp.readFile(ms.join(e,yv),"utf-8"),n=((hv.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await kv(e,s);for(let a of i)await we(ms.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import On from"node:path";var In=async e=>{let t=On.resolve(e);for(;t!==On.dirname(t);){if(await we(On.join(t,"package.json")))return t;t=On.dirname(t)}if(await we(On.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 Ge=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},St=(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}`:"")},wa=(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},Kp=(e,t,r)=>`${e}
2
+ import{a as Up,d as Yp,f as bs,h as xr,i as Rs,j as tm,k as rm,l as nm,m as om,n as sm,o as im,p as am,q as cm,t as Ta,u as um,v as be}from"./chunk-ZTAUGYJF.js";import{b as Lp,d as Bp,k as Wp,n as Vp}from"./chunk-Y3RW74TE.js";import{a as mt,b as ep,c as ga,d as tp,e as rp,f as np,g as op,h as Pn,i as sp,j as ip,k as ap,l as cp,m as lp,n as En,o as dp,p as up,q as pp,r as mp,s as ha,t as ls,u as ft,v as fp,w as ds,x as gp}from"./chunk-IT6XJWTW.js";import{a as de,b as q,c as wt,d as ys,e as ba,f as vs,g as Ra,h as Cn,i as Gt,j as ws,k as Fp,l as $n,m as An,n as Sa,o as Pa,q as Ea}from"./chunk-MH37P7W4.js";import{b as Sn,c as as,d as fa,e as Yu,f as cs,g as zu,i as Xu,k as Zu,m as he,o as Qu}from"./chunk-AWFGP6GY.js";import{a as qp}from"./chunk-TVG47UHG.js";import{B as $a,F as Aa,G as Oa,a as k,b as S,c as zp,d as Xp,e as Kt,f as Zp,g as Ht,h as em,i as lm,j as On,k as bt,l as Tr,m as Je,n as Ss,o as Rt,p as dm,q as Ps,r as pm,s as mm,t as Ge,x as Ca,z as In}from"./chunk-PP3ZZKB3.js";import{a as h,b as ot,c as Jp,d as Gp,e as O,f as ks,g as V,i as kt,j as Be,k as xa,l as Qp}from"./chunk-4RZM53X7.js";import{$ as yt,A as Rp,B as Sp,C as Pp,D as fs,E as gs,F as $e,G as xn,H as Er,I as hs,J as Ep,K as xp,L as Tp,M as va,N as wa,O as Cp,P as u,Q as Ae,R as Z,S as v,T as $p,U as Ap,V as Op,W as Dp,X as Np,Y as ht,Z as _p,_ as ka,a as Jt,aa as Mp,b as A,ba as jp,c as hp,ca as H,d as N,da as M,e as ye,ea as Tn,f as J,fa as vt,g as us,ga as x,h as yp,i as f,j as vp,k as ps,l as G,m as pe,n as ve,o as wp,p as ya,q as re,r as X,s as ms,t as kp,u as gt,v as me,w as T,x as Le,y as Pr,z as bp}from"./chunk-EZ4DIT5A.js";import{a as Ip}from"./chunk-MFAFQVTW.js";import{a as K}from"./chunk-3UE375II.js";import{a as kr,b as ts,c as rs,d as bn,e as Uu,f as br,g as ns,h as os,i as Ju,j as ss,k as is,l as Gu,m as Ku,n as Hu,o as Rr,p as Rn,q as ge,r as qu,s as Sr}from"./chunk-I23MDR4X.js";import{a as Kp,b as Hp}from"./chunk-QWVLAZ6N.js";import bD,{Separator as Qv}from"@inquirer/select";import{existsSync as RD,realpathSync as SD}from"node:fs";import{homedir as PD}from"node:os";import Ce from"node:process";import{fileURLToPath as tw}from"node:url";import rf from"node:process";import{z as De}from"zod";import bm from"node:fs";import Ar from"node:path";import{packageConfigSchema as hm}from"@slip-stream-kit/config/internal";import ym from"node:fs/promises";import Es from"node:path";import{pathToFileURL as dw}from"node:url";import{z as vm}from"zod";import fm from"node:path";var Dn=["frontend","backend","lib","e2e","mobile"],ow={ui:"frontend",api:"backend",tests:"e2e"},sw="mobile-app",iw=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],aw=(e,t)=>{let r=fm.relative(t,e).split(fm.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=ow[o];if(s)return s}return r.at(-1)===sw?"mobile":null},cw=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of iw)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Nn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??aw(e,t)??cw(r)??"lib";var St={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},gm=2e3,Ia={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${gm}} pnpm exec playwright test --ui --headed --workers=1`,"e2e-test-chrome":"pnpm exec playwright test --project=chromium","e2e-test-debug":"pnpm exec playwright test --debug","e2e-test-codegen":"pnpm exec playwright codegen","playwright-install":"pnpm exec playwright install --with-deps"},_n={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"]},Mn=(e,t=St)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import lw from"node:fs/promises";var Re=async e=>{try{return await lw.access(e),!0}catch{return!1}};var ne="infra-kit.config.ts",qt=async e=>{try{let t=await ym.readFile(Es.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Da=async e=>{let t=await ym.stat(e),o=(await import(`${dw(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ne} at ${e} has no default export`);return typeof o=="function"?await o():o},Yt=async e=>{let t=Es.join(e,ne);if(await Re(t))try{let n=(await Da(t))?.type;return Dn.find(o=>o===n)}catch{return}},jn=async(e,t=St)=>{let r=Es.join(e,ne);if(!await Re(r))throw new Error(`${ne} not found at ${r}`);let n=await Da(r),o=hm.safeParse(n);if(!o.success)throw new Error(`Invalid ${ne} at ${r}: ${vm.prettifyError(o.error)}`);return Mn(o.data,t)},Cr=async e=>{let t=Es.join(e,ne);if(!await Re(t))return;let r=hm.safeParse(await Da(t));if(!r.success)throw new Error(`Invalid ${ne} at ${t}: ${vm.prettifyError(r.error)}`);return r.data};import wm from"node:fs/promises";import xs from"node:path";import uw from"yaml";var pw="pnpm-workspace.yaml",mw=async e=>(await wm.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>xs.join(e,r.name)),fw=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await mw(n));continue}let o=xs.join(n,t);await Re(o)&&r.push(o)}return r},gw=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await fw(r,n);return r},Se=async e=>{let t=await wm.readFile(xs.join(e,pw),"utf-8"),n=((uw.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await gw(e,s);for(let a of i)await Re(xs.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Fn from"node:path";var Ln=async e=>{let t=Fn.resolve(e);for(;t!==Fn.dirname(t);){if(await Re(Fn.join(t,"package.json")))return t;t=Fn.dirname(t)}if(await Re(Fn.join(t,"package.json")))return t;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var Ke=(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}`:"")},Na=(e,t)=>{let r=e.indexOf(t);if(r===-1)return null;let o=e.slice(r+t.length).match(/^([^\s>]+)/);return o?o[1]:null},km=(e,t,r)=>`${e}
4
4
  ${t}
5
- ${r}`,Er=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Kp(r,t,n),i=Ge(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?St(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${r}`,$r=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=km(r,t,n),i=Ke(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?Pt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
6
6
  ${s}
7
7
  `:`${s}
8
- `};var $e="<!-- infra-kit:begin -->",Ke="<!-- infra-kit:end -->",ka="<!-- infra-kit:version ",He="<!-- infra-kit:package:begin -->",ot="<!-- infra-kit:package:end -->",Jt="<!-- infra-kit:package:version ";var bv=e=>{let t=e.indexOf(He)+He.length;return e.slice(t,e.indexOf(ot))},Rv=e=>{let t=e.indexOf(Jt);if(t===-1)return null;let r=e.slice(t+Jt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return xn.find(n=>n===r)??null},Gt=e=>{if(e===null)return{state:"missing"};if(!Ge(e,He,ot))return e.includes(He)||e.includes(ot)?{state:"malformed"}:Ge(e,$e,Ke)?{state:"foreign-block"}:{state:"no-block"};let t=bv(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=wa(t,Jt),o=Rv(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Sv from"node:fs";var Kt=e=>{try{return Sv.readFileSync(e,"utf-8")}catch{return null}};var qp="pnpm-workspace.yaml",Pv="CLAUDE.md",Ra=e=>{let t=xr.resolve(e);for(;t!==xr.dirname(t);){if(Hp.existsSync(xr.join(t,qp)))return t;t=xr.dirname(t)}return Hp.existsSync(xr.join(t,qp))?t:null},ba=new Map,fs=()=>{ba.clear()},Ev=async e=>{let t;try{t=await ke(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=xr.join(r,Pv),o=Kt(n);if(o!==null&&Gt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Tr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=ba.get(e);if(t)return t;let r=await Ev(e);return ba.set(e,r),r};import Ht from"node:fs";import Pt from"node:path";var Yp=`---
8
+ `};var Oe="<!-- infra-kit:begin -->",He="<!-- infra-kit:end -->",_a="<!-- infra-kit:version ",qe="<!-- infra-kit:package:begin -->",st="<!-- infra-kit:package:end -->",zt="<!-- infra-kit:package:version ";var hw=e=>{let t=e.indexOf(qe)+qe.length;return e.slice(t,e.indexOf(st))},yw=e=>{let t=e.indexOf(zt);if(t===-1)return null;let r=e.slice(t+zt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Dn.find(n=>n===r)??null},Xt=e=>{if(e===null)return{state:"missing"};if(!Ke(e,qe,st))return e.includes(qe)||e.includes(st)?{state:"malformed"}:Ke(e,Oe,He)?{state:"foreign-block"}:{state:"no-block"};let t=hw(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Na(t,zt),o=yw(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import vw from"node:fs";var Zt=e=>{try{return vw.readFileSync(e,"utf-8")}catch{return null}};var Rm="pnpm-workspace.yaml",ww="CLAUDE.md",ja=e=>{let t=Ar.resolve(e);for(;t!==Ar.dirname(t);){if(bm.existsSync(Ar.join(t,Rm)))return t;t=Ar.dirname(t)}return bm.existsSync(Ar.join(t,Rm))?t:null},Ma=new Map,Ts=()=>{Ma.clear()},kw=async e=>{let t;try{t=await Se(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Ar.join(r,ww),o=Zt(n);if(o!==null&&Xt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Or=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Ma.get(e);if(t)return t;let r=await kw(e);return Ma.set(e,r),r};import Qt from"node:fs";import Et from"node:path";var Sm=`---
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 zp=`# {{packageName}}
77
+ `;var Pm=`# {{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 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- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- `playwright.config.ts` takes `baseURL`, `ignoreHTTPSErrors` and `webServer` from `infraKitE2e()` (`@slip-stream-kit/config/playwright`). Every run is local by default \u2014 this worktree's dev server, reused or started for the run \u2014 and cloud only with `INFRA_KIT_E2E=cloud` (`infra-kit e2e --cloud`) or on CI, against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL.\n- Never point a run at a production environment.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test or skip it with a linked issue.\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n";var Zp="# {{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 Qp=`# {{packageName}}
98
+ `;var Em="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the shared CI job exports. Pass them to `use.httpCredentials`; never invent a per-app name (`E2E_CLIENT_BASIC_AUTH_*`) or fall back to one. `infra-kit audit` fails the package otherwise.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- `playwright.config.ts` takes `baseURL`, `ignoreHTTPSErrors` and `webServer` from `infraKitE2e()` (`@slip-stream-kit/config/playwright`). Every run is local by default \u2014 this worktree's dev server, reused or started for the run \u2014 and cloud only with `INFRA_KIT_E2E=cloud` (`infra-kit e2e --cloud`) or on CI, against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test, or skip it with a linked issue once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var xm="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `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- A loaded env var that breaks local dev \u2014 one meant for another build mode, e.g. a mobile-only absolute origin that bypasses the proxy \u2014 goes in `dev.env.unset` (or `dev.env.set` to override it) in `infra-kit.config.ts`. Never remove it from Doppler or patch it out in `vite.config.ts`.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var Tm=`# {{packageName}}
99
99
 
100
100
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
101
101
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -117,7 +117,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
117
117
  - Changing that map is a breaking change for every dependent package.
118
118
  - Run \`pnpm run build\` before a dependent package can see a change.
119
119
  - No app-specific logic belongs here.
120
- `;var em=`# {{packageName}}
120
+ `;var Cm=`# {{packageName}}
121
121
 
122
122
  Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
123
123
  This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
@@ -139,39 +139,41 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
139
139
  - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
140
140
  - The web build feeds the native shell, so a device run needs a rebuild first.
141
141
  - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
142
- `;var tm="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.\n- `ik dev [preset|app]` / `ik dev-status` \u2014 run this worktree's dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; a `devServersPresets` name runs that preset; no name runs every app. Names are per-repo: an unknown one is refused with the presets and apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite locally: against this worktree's dev server when it runs, otherwise the package's `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app's `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against their `infra-kit.config.ts` rules (`--root`: the repo root against the `audit` block in `infra-kit.json`).\n- `ik audit --fix` \u2014 regenerate this repo's infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, git, aws, gh, doppler, portless).\n\n## Conventions\n\n- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.\n- Config is split by level: repo-wide settings live in the root `infra-kit.json` (personal overrides in `~/.infra-kit/`), per-package settings in that package's `infra-kit.config.ts`. The root has no `infra-kit.config.ts`.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host's prompt on the argv is the approval. `release deliver` and `vendor sync` are human-only and are refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root's `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n";var Cr={"root/body":tm.trimEnd(),"package/frontend":Zp.trimEnd(),"package/backend":zp.trimEnd(),"package/lib":Qp.trimEnd(),"package/e2e":Xp.trimEnd(),"package/mobile":em.trimEnd(),"design/skeleton":Yp.trimEnd()};var Sa=/\{\{(\w+)\}\}/g,Dv=/^- \{\{(\w+)\}\}$/,Nv=e=>new Set([...e.matchAll(Sa)].map(t=>t[1])),_v=(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(", ")}`)},Mv=(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(", ")}`)},jv=(e,t)=>e.filter(r=>{let n=Dv.exec(r);return n===null||t[n[1]]!==""}),Fv=(e,t)=>{for(let r of e)for(let n of r.matchAll(Sa)){let o=t[n[1]];if(o!==void 0&&o.includes(`
143
- `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},$r=(e,t)=>{let r=Nv(e);Mv(r,t),_v(r,t);let n=jv(e.split(`
144
- `),t);return Fv(n,t),n.join(`
145
- `).replace(Sa,(o,s)=>t[s])};var Lv="name: TODO",Pa=e=>{let t=$r(Cr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(Lv,()=>r)}
146
- `};var Bv=(e,t)=>`${Jt}${e} ${t} -->`,Vv="`README.md` \u2014 what this package is and how to run it.",Ea="docs/e2e-playwright.md",Wv=`\`${Ea}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,xa=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=$r(Cr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?Vv:"",...r==="e2e"?{e2eDocBullet:i?Wv:""}:{}});return[Bv(t,r),"",a].join(`
147
- `)};var Uv=e=>`${ka}${e} -->`,Ta=e=>{let t=$r(Cr["root/body"],{});return[Uv(e),"",t].join(`
148
- `)};import Ar from"node:fs";import Jv from"node:path";var gs=e=>{let t;try{t=Ar.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Dn=(e,t)=>{gs(e);let r=Ar.existsSync(e)?Ar.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(Ar.mkdirSync(Jv.dirname(e),{recursive:!0}),Ar.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Ca=(e,t,r)=>{let n=Ar.readFileSync(e,"utf-8");if(!Ge(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},rm=(e,t,r)=>Ge(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,$a=(e,t,r,n)=>{let o=rm(e,r,n),s=rm(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 ys="<!-- infra-kit:import:begin -->",vs="<!-- infra-kit:import:end -->",Gv="AGENTS.md",nm="CLAUDE.md",Kv="README.md",Aa="DESIGN.md",Hv=["frontend","mobile"],qv=e=>Ht.existsSync(e)?Ht.readFileSync(e,"utf-8"):null,Oa=(e,t)=>{try{return Ht.readdirSync(e).includes(t)}catch{return!1}},hs=(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},om=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=qv(e),i=s===null?"":o?.(s)??s,a=Er({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=Dn(e,a);return Ca(e,r,n),s!==null&&$a(i,a,r,n),c},Yv=e=>{if(!Ht.existsSync(e))return"unchanged";gs(e);let t=Ht.readFileSync(e,"utf-8"),r=St(t,$e,Ke);return r===null?"unchanged":r.trim()===""?(Ht.rmSync(e),"removed"):Dn(e,r)},zv=(e,t)=>om({filePath:e,body:Ta(t),startMarker:$e,endMarker:Ke,prepare:r=>St(r,ys,vs)??r}),Nn=async(e,{version:t})=>{let r=Pt.join(e,nm),n=Pt.join(e,Gv),o=[];try{o.push({path:r,action:zv(r,t)})}catch(s){o.push(hs(r,s))}try{o.push({path:n,action:Yv(n)})}catch(s){o.push(hs(n,s))}return o},Xv=(e,t,r)=>{if(!Hv.includes(r)||Oa(e,Aa))return null;let n=Pt.join(e,Aa);try{return{path:n,action:Dn(n,Pa(t)),type:r}}catch(o){return hs(n,o,r)}},_n=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Pt.join(e,nm),i=await Wt(e),a=i.name??Pt.basename(e),c=Tn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=xa({version:r,type:c,packageName:a,relDir:Pt.relative(t,e).split(Pt.sep).join("/"),hasReadme:Oa(e,Kv),hasDesign:Oa(e,Aa),hasE2eDoc:Ht.existsSync(Pt.join(t,Ea))}),d=[];try{d.push({path:s,action:om({filePath:s,body:l,startMarker:He,endMarker:ot}),type:c})}catch(p){d.push(hs(s,p,c))}if(n){let p=Xv(e,a,c);p&&d.push(p)}return d};import dw from"node:path";import sm from"node:path";var Ia="agent-guidance",Mn="CLAUDE.md",Zv="\u2014 run: infra-kit audit --fix",Qv={missing:`${Mn} missing`,"no-block":`${Mn} has no infra-kit block (expected ${He} \u2026 ${ot})`,malformed:`${Mn} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Mn} carries the ROOT infra-kit block (${$e}); a package needs the package block`},ew=e=>e.adopted?` (workspace adopted: ${sm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Da=(e,t)=>{let r=Gt(Kt(sm.join(e,Mn)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ia,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${Qv[r.state]} ${Zv}`,o=r.state==="missing"?`${n}${ew(t)}`:n;return t.adopted?{name:Ia,status:"fail",message:o}:{name:Ia,status:"pass",message:`not yet adopted \u2014 ${o}`}};import tw from"node:path";var Na=async(e,t=Rt)=>{try{let r=await An(e,t);return{check:{name:re,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:re,status:"fail",message:r.message},rules:null}}},im="infra-kit.json",rw=async e=>await we(tw.join(e,re))?{name:re,status:"fail",message:'retired at the repo root \u2014 root audit rules live in infra-kit.json "audit". Run `infra-kit audit --fix --root` to move them and delete the file'}:null,_a=async(e,t=Cn)=>{let r=await rw(e),n=r?[r]:[];try{let{audit:o={}}=await M();return{checks:[{name:im,status:"pass",message:"present and valid"},...n],rules:$n(o,t)}}catch(o){return{checks:[{name:im,status:"fail",message:o.message},...n],rules:null}}};import nw from"node:fs/promises";import ow from"node:path";var ws="playwright.config.ts",sw=[{name:"slow-mo",pattern:/process\.env\.E2E_SLOW_MO/u,expected:"const SLOW_MO = Number(process.env.E2E_SLOW_MO ?? 0)"},{name:"launch-options",pattern:/launchOptions:\s*\{[^}]*\bslowMo\b/u,expected:"use.launchOptions: { slowMo: SLOW_MO }"},{name:"timeout-headroom",pattern:/\btimeout:[^\n]*\bSLOW_MO\b/u,expected:"timeout: <base> + SLOW_MO * 100"},{name:"trace",pattern:/trace:\s*process\.env\.CI\s*\?\s*'on-first-retry'\s*:\s*'retain-on-failure'/u,expected:"use.trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure'"}],am=e=>Object.entries(ya).map(([t,r])=>{let n=`e2e-script:${t}`,o=e[t];return typeof o!="string"||o.trim().length===0?{name:n,status:"fail",message:`missing "${t}" in package.json scripts \u2014 expected: ${r}`}:o.trim()!==r?{name:n,status:"fail",message:`"${t}" drifts from the shared e2e scripts \u2014 expected: ${r}`}:{name:n,status:"pass",message:"matches the shared e2e scripts"}}),cm=async e=>{let t=ow.join(e,ws),r=await nw.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${ws}`,status:"fail",message:`missing ${ws}`}]:sw.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${ws} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},Ma=async(e,t)=>[...am(t),...await cm(e)];import iw from"node:fs/promises";import aw from"node:path";var ja=async(e,t)=>Promise.all(t.map(async r=>{let n=await iw.stat(aw.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 Fa=(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 cw from"node:fs/promises";import lw from"node:path";var Or="turbo.json",La=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await cw.readFile(lw.join(e,Or),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Or,status:"fail",message:`cannot read/parse ${Or}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Or,status:"fail",message:`no "tasks" object defined in ${Or}`}]: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 ${Or}`}})};var uw=async(e,t)=>{let{check:r,rules:n}=await Na(e,t);return{checks:[r],rules:n}},pw={adopted:!1,workspaceRoot:null},mw=async(e,t,r)=>Tn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Ut(e)}),Ba=async(e,t=Rt,r={})=>{let n=await Wt(e),o=n.name??dw.basename(e),{checks:s,rules:i}=r.isRoot?await _a(e,t):await uw(e,t);r.isRoot||s.push(Da(e,r.adoption??pw)),i&&(s.push(...Fa(n.scripts??{},i.requiredScripts)),s.push(...await ja(e,i.requiredFiles)),s.push(...await La(e,i.turboTasks))),!r.isRoot&&await mw(e,n,r.repoRoot)==="e2e"&&s.push(...await Ma(e,n.scripts??{}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var Va=["plugin","marketplace","add",wt],Wa=["plugin","install",K,"--scope","project"],lm=(e,t)=>Ft({projectPath:e,home:t}).kind==="installed",Ua=e=>((e??"").split(`
149
- `).find(r=>r.trim().length>0)??"").trim(),fw=(e,t)=>{if(bn(t))return null;u.debug({msg:`Running: ${os} ${Va.join(" ")}`});let r=e({args:Va});return r.ok?null:{step:"marketplace",error:Ua(r.output)}},gw=(e,t)=>{u.debug({msg:`Running: ${os} ${ss.join(" ")}`});let r=e({args:ss,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:Ua(r.output)}},Ja=e=>{let{projectRoot:t,home:r}=e,n=e.run??ca;if(!n({args:aa}).ok)return{status:"claude-missing"};if(lm(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:gw(n,t);let o=fw(n,r);if(o!==null)return{status:"failed",...o};u.debug({msg:`Running: ${os} ${Wa.join(" ")}`});let s=n({args:Wa,cwd:t});return s.ok?lm(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:Ua(s.output)}};import hw from"node:fs";import yw from"node:path";var Ae=".mcp.json",qe="mcpServers",vw="infra-kit",ww=["mcp"],kw="/infra-kit/dist/mcp.js",Ga=" ",qt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),dm=e=>{if(!qt(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===vw&&r[0]===ww[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(kw)):!1},um=e=>/\n([ \t]+)"/.exec(e)?.[1]??Ga,Ka=e=>{try{return{kind:"raw",raw:hw.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Ha=e=>{try{return JSON.parse(e)}catch{return}},qa=e=>e instanceof Error?e.message:String(e),jn=e=>{let t=Ka(yw.join(e,Ae));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Ha(t.raw);if(!qt(r)||!qt(r[qe]))return{kind:"unparseable"};let n=r[qe];if(ae in n)return{kind:"stale"};let o=Object.keys(n).find(s=>dm(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import ks from"node:fs";import bw from"node:path";var st=`claude plugin install ${K} --scope project`,Ir=`claude plugin update ${K} --scope project`,Ya=`claude plugin marketplace add ${wt}`,mm=" ",fm=()=>({source:{source:"github",repo:wt}}),Rw=()=>({extraKnownMarketplaces:{[ae]:fm()},enabledPlugins:{[K]:!0}}),gm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sw=e=>/\n([ \t]+)"/.exec(e)?.[1]??mm,pm=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!gm(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Pw=e=>[pm(e,"extraKnownMarketplaces",ae,fm()),pm(e,"enabledPlugins",K,!0)].filter(r=>r!==null),Ew=e=>{try{return ks.readFileSync(e,"utf-8")}catch{return null}},xw=e=>(ks.mkdirSync(bw.dirname(e),{recursive:!0}),ks.writeFileSync(e,`${JSON.stringify(Rw(),null,mm)}
150
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ae}`,`enabledPlugins.${K}`]}),za=e=>{let t=Ew(e);if(t===null)return xw(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!gm(r))return u.warn(`Could not parse ${e} \u2014 left it untouched. Add "${K}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Pw(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=Sw(t),s=t.endsWith(`
142
+ `;var $m="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.\n- `ik dev [preset|app]` / `ik dev-status` \u2014 run this worktree's dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; a `devServersPresets` name runs that preset; no name runs every app. Names are per-repo: an unknown one is refused with the presets and apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite locally: against this worktree's dev server when it runs, otherwise the package's `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app's `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees. `ik worktrees add --feature <name> [--base <dev|main|release>]` creates `feature/<name>` at `<root>-worktrees/feature/<name>`, cut from `dev` by default (the default branch in a repo without `dev`); `worktrees remove --feature <name>` removes it. The `/infra-kit:worktrees` skill is the agent entry point for feature worktrees \u2014 never create one with raw `git worktree add` or Claude Code's `EnterWorktree`, which skip `pnpm install`, the editor/Orca wiring and the `feature/` layout.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\n- `ik audit` \u2014 audit packages against their `infra-kit.config.ts` rules (`--root`: the repo root against the `audit` block in `infra-kit.json`).\n- `ik audit --fix` \u2014 regenerate this repo's infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, git, aws, gh, doppler, portless).\n\n## Conventions\n\n- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.\n- Config is split by level: repo-wide settings live in the root `infra-kit.json` (personal overrides in `~/.infra-kit/`), per-package settings in that package's `infra-kit.config.ts`. The root has no `infra-kit.config.ts`.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `release merge-dev --continue|--abort`, `worktrees add|remove|sync`, `vendor sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host's prompt on the argv is the approval. `release deliver` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root's `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n";var Ir={"root/body":$m.trimEnd(),"package/frontend":xm.trimEnd(),"package/backend":Pm.trimEnd(),"package/lib":Tm.trimEnd(),"package/e2e":Em.trimEnd(),"package/mobile":Cm.trimEnd(),"design/skeleton":Sm.trimEnd()};var Fa=/\{\{(\w+)\}\}/g,Cw=/^- \{\{(\w+)\}\}$/,$w=e=>new Set([...e.matchAll(Fa)].map(t=>t[1])),Aw=(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(", ")}`)},Ow=(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(", ")}`)},Iw=(e,t)=>e.filter(r=>{let n=Cw.exec(r);return n===null||t[n[1]]!==""}),Dw=(e,t)=>{for(let r of e)for(let n of r.matchAll(Fa)){let o=t[n[1]];if(o!==void 0&&o.includes(`
143
+ `)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},Dr=(e,t)=>{let r=$w(e);Ow(r,t),Aw(r,t);let n=Iw(e.split(`
144
+ `),t);return Dw(n,t),n.join(`
145
+ `).replace(Fa,(o,s)=>t[s])};var Nw="name: TODO",La=e=>{let t=Dr(Ir["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(Nw,()=>r)}
146
+ `};var _w=(e,t)=>`${zt}${e} ${t} -->`,Mw="`README.md` \u2014 what this package is and how to run it.",Ba="docs/e2e-playwright.md",jw=`\`${Ba}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Wa=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=Dr(Ir[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?Mw:"",...r==="e2e"?{e2eDocBullet:i?jw:""}:{}});return[_w(t,r),"",a].join(`
147
+ `)};var Fw=e=>`${_a}${e} -->`,Va=e=>{let t=Dr(Ir["root/body"],{});return[Fw(e),"",t].join(`
148
+ `)};import Nr from"node:fs";import Lw from"node:path";var Cs=e=>{let t;try{t=Nr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Bn=(e,t)=>{Cs(e);let r=Nr.existsSync(e)?Nr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(Nr.mkdirSync(Lw.dirname(e),{recursive:!0}),Nr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Ua=(e,t,r)=>{let n=Nr.readFileSync(e,"utf-8");if(!Ke(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Am=(e,t,r)=>Ke(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Ja=(e,t,r,n)=>{let o=Am(e,r,n),s=Am(t,r,n);if(!(o===null||s===null)&&(o.before!==s.before||o.after!==s.after))throw new Error("Post-write validation failed: content outside the managed markers changed")};var As="<!-- infra-kit:import:begin -->",Os="<!-- infra-kit:import:end -->",Bw="AGENTS.md",Om="CLAUDE.md",Ww="README.md",Ga="DESIGN.md",Vw=["frontend","mobile"],Uw=e=>Qt.existsSync(e)?Qt.readFileSync(e,"utf-8"):null,Ka=(e,t)=>{try{return Qt.readdirSync(e).includes(t)}catch{return!1}},$s=(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},Im=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=Uw(e),i=s===null?"":o?.(s)??s,a=$r({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=Bn(e,a);return Ua(e,r,n),s!==null&&Ja(i,a,r,n),c},Jw=e=>{if(!Qt.existsSync(e))return"unchanged";Cs(e);let t=Qt.readFileSync(e,"utf-8"),r=Pt(t,Oe,He);return r===null?"unchanged":r.trim()===""?(Qt.rmSync(e),"removed"):Bn(e,r)},Gw=(e,t)=>Im({filePath:e,body:Va(t),startMarker:Oe,endMarker:He,prepare:r=>Pt(r,As,Os)??r}),Wn=async(e,{version:t})=>{let r=Et.join(e,Om),n=Et.join(e,Bw),o=[];try{o.push({path:r,action:Gw(r,t)})}catch(s){o.push($s(r,s))}try{o.push({path:n,action:Jw(n)})}catch(s){o.push($s(n,s))}return o},Kw=(e,t,r)=>{if(!Vw.includes(r)||Ka(e,Ga))return null;let n=Et.join(e,Ga);try{return{path:n,action:Bn(n,La(t)),type:r}}catch(o){return $s(n,o,r)}},Vn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Et.join(e,Om),i=await qt(e),a=i.name??Et.basename(e),c=Nn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=Wa({version:r,type:c,packageName:a,relDir:Et.relative(t,e).split(Et.sep).join("/"),hasReadme:Ka(e,Ww),hasDesign:Ka(e,Ga),hasE2eDoc:Qt.existsSync(Et.join(t,Ba))}),d=[];try{d.push({path:s,action:Im({filePath:s,body:l,startMarker:qe,endMarker:st}),type:c})}catch(p){d.push($s(s,p,c))}if(n){let p=Kw(e,a,c);p&&d.push(p)}return d};import mk from"node:path";import Dm from"node:path";var Ha="agent-guidance",Un="CLAUDE.md",Hw="\u2014 run: infra-kit audit --fix",qw={missing:`${Un} missing`,"no-block":`${Un} has no infra-kit block (expected ${qe} \u2026 ${st})`,malformed:`${Un} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Un} carries the ROOT infra-kit block (${Oe}); a package needs the package block`},Yw=e=>e.adopted?` (workspace adopted: ${Dm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",qa=(e,t)=>{let r=Xt(Zt(Dm.join(e,Un)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ha,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${qw[r.state]} ${Hw}`,o=r.state==="missing"?`${n}${Yw(t)}`:n;return t.adopted?{name:Ha,status:"fail",message:o}:{name:Ha,status:"pass",message:`not yet adopted \u2014 ${o}`}};import zw from"node:path";var Ya=async(e,t=St)=>{try{let r=await jn(e,t);return{check:{name:ne,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ne,status:"fail",message:r.message},rules:null}}},Nm="infra-kit.json",Xw=async e=>await Re(zw.join(e,ne))?{name:ne,status:"fail",message:'retired at the repo root \u2014 root audit rules live in infra-kit.json "audit". Run `infra-kit audit --fix --root` to move them and delete the file'}:null,za=async(e,t=_n)=>{let r=await Xw(e),n=r?[r]:[];try{let{audit:o={}}=await M();return{checks:[{name:Nm,status:"pass",message:"present and valid"},...n],rules:Mn(o,t)}}catch(o){return{checks:[{name:Nm,status:"fail",message:o.message},...n],rules:null}}};import Is from"node:fs/promises";import _r from"node:path";import{$ as Zw}from"zx";var Jn="playwright.config.ts",Qw=[{name:"slow-mo",pattern:/process\.env\.E2E_SLOW_MO/u,expected:"const SLOW_MO = Number(process.env.E2E_SLOW_MO ?? 0)"},{name:"launch-options",pattern:/launchOptions:\s*\{[^}]*\bslowMo\b/u,expected:"use.launchOptions: { slowMo: SLOW_MO }"},{name:"timeout-headroom",pattern:/\btimeout:[^\n]*\bSLOW_MO\b/u,expected:"timeout: <base> + SLOW_MO * 100"},{name:"trace",pattern:/trace:\s*process\.env\.CI\s*\?\s*'on-first-retry'\s*:\s*'retain-on-failure'/u,expected:"use.trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure'"},{name:"infra-kit-e2e",pattern:/\binfraKitE2e\b/u,expected:"baseURL, ignoreHTTPSErrors and webServer from infraKitE2e() ('@slip-stream-kit/config/playwright')"}],_m=e=>Object.entries(Ia).map(([t,r])=>{let n=`e2e-script:${t}`,o=e[t];return typeof o!="string"||o.trim().length===0?{name:n,status:"fail",message:`missing "${t}" in package.json scripts \u2014 expected: ${r}`}:o.trim()!==r?{name:n,status:"fail",message:`"${t}" drifts from the shared e2e scripts \u2014 expected: ${r}`}:{name:n,status:"pass",message:"matches the shared e2e scripts"}}),Mm=async e=>{let t=_r.join(e,Jn),r=await Is.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${Jn}`,status:"fail",message:`missing ${Jn}`}]:Qw.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${Jn} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},ek=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,tk=/\.[cm]?[jt]sx?$/u,Xa=async(e,t)=>(await Is.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&tk.test(n.name)).map(n=>_r.join(n.parentPath,n.name)),rk=async e=>{let t=await Xa(_r.join(e,"src"),!0);for(let r of[_r.join(e,Jn),...t]){let n=await Is.readFile(r,"utf-8").catch(()=>"");if(ek.test(n))return!0}return!1},jm=async e=>{let t="e2e-auth:gitignored";if(!await rk(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await Zw({cwd:e,quiet:!0,nothrow:!0})`git -c core.excludesFile=/dev/null check-ignore -q .auth/storage-state.json`;if(r.exitCode===0)return{name:t,status:"pass",message:".auth/ is gitignored"};if(r.exitCode===1)return{name:t,status:"fail",message:"the suite saves auth state under .auth/, which git would commit \u2014 add `.auth/` to .gitignore"};let n=r.stderr.trim()||`exit ${r.exitCode}`;return{name:t,status:"fail",message:`could not ask git whether .auth/ is ignored: ${n}`}},Za="E2E__BASIC_AUTH_USERNAME",Qa="E2E__BASIC_AUTH_PASSWORD",nk=/\bE2E_\w*BASIC_AUTH_\w+/gu,ok=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,sk=/\/\*[\s\S]*?\*\//gu,ik=/(^|[^:])\/\/[^\n]*/gu,ak=e=>/USER(?:NAME)?$/u.test(e)?Za:Qa,ck=e=>e.replace(sk,"").replace(ik,"$1"),Fm=async e=>{let t="e2e-env:basic-auth",r=[...await Xa(e,!1),...await Xa(_r.join(e,"src"),!0)],n=[];for(let o of r){let s=await Is.readFile(o,"utf-8").catch(()=>""),i=new Set([...ck(s).matchAll(nk)].map(a=>a[0]).filter(a=>ok.test(a)&&a!==Za&&a!==Qa));for(let a of i)n.push(`${a} \u2192 ${ak(a)} (${_r.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${Za} / ${Qa}`}:{name:t,status:"fail",message:`basic auth has one name pair in every suite \u2014 rename, with no fallback to the old name: ${n.join("; ")}`}},ec=async(e,t)=>[..._m(t),...await Mm(e),await jm(e),await Fm(e)];import lk from"node:fs/promises";import dk from"node:path";var tc=async(e,t)=>Promise.all(t.map(async r=>{let n=await lk.stat(dk.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 rc=(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 uk from"node:fs/promises";import pk from"node:path";var Mr="turbo.json",nc=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await uk.readFile(pk.join(e,Mr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Mr,status:"fail",message:`cannot read/parse ${Mr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Mr,status:"fail",message:`no "tasks" object defined in ${Mr}`}]: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 ${Mr}`}})};var fk=async(e,t)=>{let{check:r,rules:n}=await Ya(e,t);return{checks:[r],rules:n}},gk={adopted:!1,workspaceRoot:null},hk=async(e,t,r)=>Nn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Yt(e)}),oc=async(e,t=St,r={})=>{let n=await qt(e),o=n.name??mk.basename(e),{checks:s,rules:i}=r.isRoot?await za(e,t):await fk(e,t);r.isRoot||s.push(qa(e,r.adoption??gk)),i&&(s.push(...rc(n.scripts??{},i.requiredScripts)),s.push(...await tc(e,i.requiredFiles)),s.push(...await nc(e,i.turboTasks))),!r.isRoot&&await hk(e,n,r.repoRoot)==="e2e"&&s.push(...await ec(e,n.scripts??{}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var sc=["plugin","marketplace","add",wt],ic=["plugin","install",q,"--scope","project"],Lm=(e,t)=>Gt({projectPath:e,home:t}).kind==="installed",ac=e=>((e??"").split(`
149
+ `).find(r=>r.trim().length>0)??"").trim(),yk=(e,t)=>{if(Cn(t))return null;u.debug({msg:`Running: ${ys} ${sc.join(" ")}`});let r=e({args:sc});return r.ok?null:{step:"marketplace",error:ac(r.output)}},vk=(e,t)=>{u.debug({msg:`Running: ${ys} ${vs.join(" ")}`});let r=e({args:vs,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:ac(r.output)}},cc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Ra;if(!n({args:ba}).ok)return{status:"claude-missing"};if(Lm(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:vk(n,t);let o=yk(n,r);if(o!==null)return{status:"failed",...o};u.debug({msg:`Running: ${ys} ${ic.join(" ")}`});let s=n({args:ic,cwd:t});return s.ok?Lm(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:ac(s.output)}};import wk from"node:fs";import kk from"node:path";var Ie=".mcp.json",Ye="mcpServers",bk="infra-kit",Rk=["mcp"],Sk="/infra-kit/dist/mcp.js",lc=" ",er=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bm=e=>{if(!er(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===bk&&r[0]===Rk[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Sk)):!1},Wm=e=>/\n([ \t]+)"/.exec(e)?.[1]??lc,dc=e=>{try{return{kind:"raw",raw:wk.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},uc=e=>{try{return JSON.parse(e)}catch{return}},pc=e=>e instanceof Error?e.message:String(e),Gn=e=>{let t=dc(kk.join(e,Ie));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=uc(t.raw);if(!er(r)||!er(r[Ye]))return{kind:"unparseable"};let n=r[Ye];if(de in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Bm(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ds from"node:fs";import Pk from"node:path";var it=`claude plugin install ${q} --scope project`,jr=`claude plugin update ${q} --scope project`,mc=`claude plugin marketplace add ${wt}`,Um=" ",Jm=()=>({source:{source:"github",repo:wt}}),Ek=()=>({extraKnownMarketplaces:{[de]:Jm()},enabledPlugins:{[q]:!0}}),Gm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xk=e=>/\n([ \t]+)"/.exec(e)?.[1]??Um,Vm=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Gm(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Tk=e=>[Vm(e,"extraKnownMarketplaces",de,Jm()),Vm(e,"enabledPlugins",q,!0)].filter(r=>r!==null),Ck=e=>{try{return Ds.readFileSync(e,"utf-8")}catch{return null}},$k=e=>(Ds.mkdirSync(Pk.dirname(e),{recursive:!0}),Ds.writeFileSync(e,`${JSON.stringify(Ek(),null,Um)}
150
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${de}`,`enabledPlugins.${q}`]}),fc=e=>{let t=Ck(e);if(t===null)return $k(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!Gm(r))return u.warn(`Could not parse ${e} \u2014 left it untouched. Add "${q}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Tk(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=xk(t),s=t.endsWith(`
151
151
  `)?`
152
- `:"";return ks.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};import $w from"node:path";import Aw from"node:process";import Xa from"node:fs/promises";import hm from"node:path";var Tw="infra-kit.json",ym=["requiredScripts","requiredFiles","turbo"],Fn=(e,t)=>[{path:e,action:"failed",message:t}],Cw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vm=async e=>{let t=hm.join(e,re),r=hm.join(e,Tw),n;try{n=await Pr(e)}catch(c){return Fn(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!ym.includes(c));if(s.length>0)return Fn(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(ym.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await Xa.stat(r),l=await Xa.readFile(r,"utf8"),d=JSON.parse(l);if(!Cw(d))return Fn(r,"is not a JSON object");if("audit"in d)return Fn(r,`already has an "audit" block \u2014 merge ${re}'s rules into it by hand, then delete ${re}`);await rp({path:r,raw:l,migrated:{...d,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return Fn(r,c.message)}try{await Xa.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var Ow=["unchanged","created"],Iw=["unchanged","created","updated","removed","failed"],wm=async(e,t,r)=>{let n=await Ut(e);return _n(e,{repoRoot:t,version:G.version,design:r,declaredType:n})},Dw=async(e,t)=>{if(e.root)return[...await vm(t),...await Nn(t,{version:G.version})];if(e.all){let n=[];for(let o of await ke(t))n.push(...await wm(o,t,e.design));return n}let r=await In(e.cwd??Aw.cwd());return wm(r,t,e.design)},Nw=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 ${Iw.filter(n=>Ow.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${G.version})`},_w=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=$w.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";u.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}u.info(Nw(e))},Mw=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},km=async(e,t)=>{let r=await E();fs();let n=await Tr(t),o=await Dw(e,r);_w(o,r),fs();let s=await Tr(t),i=!e.all&&!e.root;return{fixed:o.map(Mw),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Rm from"node:fs";import Sm from"node:path";var Za="ik-mcp",bm=(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:Za,args:r}};var bs="run `infra-kit setup` (or `infra-kit audit --root --fix`)",jw=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),Qa=e=>qt(e)&&e.command===Za,Fw=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Lw=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=bm(i,a),l=e[i];if(l!==void 0&&!Qa(l)){n.push({name:i,status:"conflict",message:`"${i}" is configured under mcp but .mcp.json already has a hand-written "${i}" server that is not ik-mcp \u2014 left it untouched. Remove that entry (or rename it) and ${bs}, or drop mcp.${i} from infra-kit.json`});continue}if(Qa(l)&&l.type===c.type&&jw(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Fw(l,c),s=!0,n.push({name:i,status:"written",message:""});continue}n.push({name:i,status:"drifted",message:l===void 0?`"${i}" is configured under mcp in infra-kit.json but has no .mcp.json entry \u2014 the entry is generated from that config: ${bs}`:`"${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: ${bs}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!Qa(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}},Bw=(e,t,r)=>{let n=r===null?Ga:um(r),o=r===null||r.endsWith(`
152
+ `:"";return Ds.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};import Ik from"node:path";import Dk from"node:process";import gc from"node:fs/promises";import Km from"node:path";var Ak="infra-kit.json",Hm=["requiredScripts","requiredFiles","turbo"],Kn=(e,t)=>[{path:e,action:"failed",message:t}],Ok=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qm=async e=>{let t=Km.join(e,ne),r=Km.join(e,Ak),n;try{n=await Cr(e)}catch(c){return Kn(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Hm.includes(c));if(s.length>0)return Kn(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Hm.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await gc.stat(r),l=await gc.readFile(r,"utf8"),d=JSON.parse(l);if(!Ok(d))return Kn(r,"is not a JSON object");if("audit"in d)return Kn(r,`already has an "audit" block \u2014 merge ${ne}'s rules into it by hand, then delete ${ne}`);await Ap({path:r,raw:l,migrated:{...d,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return Kn(r,c.message)}try{await gc.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var Nk=["unchanged","created"],_k=["unchanged","created","updated","removed","failed"],Ym=async(e,t,r)=>{let n=await Yt(e);return Vn(e,{repoRoot:t,version:K.version,design:r,declaredType:n})},Mk=async(e,t)=>{if(e.root)return[...await qm(t),...await Wn(t,{version:K.version})];if(e.all){let n=[];for(let o of await Se(t))n.push(...await Ym(o,t,e.design));return n}let r=await Ln(e.cwd??Dk.cwd());return Ym(r,t,e.design)},jk=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 ${_k.filter(n=>Nk.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${K.version})`},Fk=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Ik.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";u.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}u.info(jk(e))},Lk=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},zm=async(e,t)=>{let r=await T();Ts();let n=await Or(t),o=await Mk(e,r);Fk(o,r),Ts();let s=await Or(t),i=!e.all&&!e.root;return{fixed:o.map(Lk),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Zm from"node:fs";import Qm from"node:path";var hc="ik-mcp",Xm=(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:hc,args:r}};var Ns="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Bk=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),yc=e=>er(e)&&e.command===hc,Wk=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Vk=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Xm(i,a),l=e[i];if(l!==void 0&&!yc(l)){n.push({name:i,status:"conflict",message:`"${i}" is configured under mcp but .mcp.json already has a hand-written "${i}" server that is not ik-mcp \u2014 left it untouched. Remove that entry (or rename it) and ${Ns}, or drop mcp.${i} from infra-kit.json`});continue}if(yc(l)&&l.type===c.type&&Bk(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Wk(l,c),s=!0,n.push({name:i,status:"written",message:""});continue}n.push({name:i,status:"drifted",message:l===void 0?`"${i}" is configured under mcp in infra-kit.json but has no .mcp.json entry \u2014 the entry is generated from that config: ${Ns}`:`"${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: ${Ns}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!yc(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}},Uk=(e,t,r)=>{let n=r===null?lc:Wm(r),o=r===null||r.endsWith(`
153
153
  `)?`
154
- `:"";try{return Rm.mkdirSync(Sm.dirname(e),{recursive:!0}),Rm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return u.warn(`Could not write ${e} (${qa(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Rs=({projectRoot:e,proxies:t,write:r})=>{let n=Sm.join(e,Ae),o=Ka(n);if(o.kind==="unreadable")return u.warn(`Could not read ${n} (${qa(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Ha(s);if(!qt(i))return u.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${bs}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[qe];if(a!==void 0&&!qt(a))return u.warn(`${n} has a "${qe}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Lw(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Bw(n,{...i,[qe]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Pm=async(e,t)=>{let r;try{r=(await M()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Rs({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 Vw=(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}))],Em=async e=>{let t=(await M()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=mp(t);if(r.length>0){let d=r.map(p=>({name:`devServersPresets:${p.preset}`,status:"fail",message:p.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=up(e),o=pp(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await gp(e,t,s,n),c=Vw(fp(t,i),a),l=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:l,passed:c.length===0}};var Ww="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Uw=async e=>e.root?[{dir:await E(),baseline:Cn,isRoot:!0}]:e.all?(await ke(await E())).map(r=>({dir:r})):[{dir:await In(e.cwd??xm.cwd())}],Jw=async e=>e.root||e.all?await E():e.cwd??xm.cwd(),Gw=async()=>{try{return await E()}catch{return}},Kw=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,u.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 u.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},Hw=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await km(e,t);return n&&u.info(Ww),r},qw=e=>{if(jn(e).kind!=="stale")return null;let t=`${Ae} still registers "${ae}" \u2014 delete this key: the plugin no longer serves an MCP server and the entry spawns a retired subcommand that exits immediately (Claude Code lists it as failed). Delete the "${ae}" entry by hand in a PR, keeping its siblings`;return u.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Ss=async(e={})=>{let t=Ra(await Jw(e)),r=e.fix?await Hw(e,t):void 0,n=await Uw(e),o=await Tr(t),s=await Gw(),i=[];for(let l of n)i.push(await Ba(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await Em(n[0].dir);l&&i.push(l);let d=await Pm(n[0].dir,e.fix===!0);d&&i.push(d);let p=qw(n[0].dir);p&&i.push(p)}let c={allPassed:Kw(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Yw={all:Oe.boolean().optional().describe("Audit every non-vendor workspace package"),root:Oe.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},zw={allPassed:Oe.boolean().describe("Whether every audited package passed all checks"),packages:Oe.array(Oe.object({name:Oe.string(),passed:Oe.boolean(),checks:Oe.array(Oe.object({name:Oe.string(),status:Oe.enum(["pass","fail"]),message:Oe.string()}))})).describe("Per-package check results")},ec=S({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:Yw,outputSchema:zw,handler:e=>Ss({all:e.all,root:e.root})});import{z as Ln}from"zod";var Ps=async()=>{let[e,t]=await Promise.all([M(),ee()]),r=Object.keys(e).sort();u.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),u.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Xw={config:Ln.record(Ln.string(),Ln.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:Ln.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:Ln.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},tc=S({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:Xw,handler:()=>Ps()});import nk from"node:fs";import{z as ce}from"zod";import Bn from"node:fs";import Dr from"node:path";import Zw from"node:process";var Qw=Dr.join(".infra-kit","dev-context"),ek=".infra-kit",Tm=(e,t)=>{let r=Dr.resolve(e);for(;;){let n=Dr.join(r,t);if(Bn.existsSync(n))return n;let o=Dr.dirname(r);if(o===r)return;r=o}},tk=e=>{let t=Tm(e,Qw);if(t)return t;let r=Tm(e,ek);return r?Dr.join(r,"dev-context"):void 0},rc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Es=e=>typeof e=="string"?e:"",rk=(e,t,r)=>{let n=Dr.join(e,t);try{let o=Bn.statSync(n),s=JSON.parse(Bn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Es(i.package),port:rc(i.port),alias:Es(i.alias),origin:Es(i.origin),release:Es(i.release),pid:rc(i.pid),writtenAt:rc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},nc=(e=Zw.cwd())=>{let t=Date.now(),r=tk(e);if(!r||!Bn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Bn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>rk(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 xs=async(e={})=>{let t=e.now??Date.now,r=e.isListening??vn,n=nc(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),g=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(nk.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){u.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",g=`written ${p.ageSeconds}s ago`;u.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${g}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";u.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},ok={active:ce.boolean().describe("True when at least one dev-context fragment exists on disk (an infra-kit dev session has apps registered). False means no active dev session was found \u2014 this is a clean result, NOT an error."),contextDir:ce.string().nullable().describe("The RESOLVED dev-context fragment directory \u2014 found by searching UPWARD from the working directory. This is where the read looked, NOT proof anything is there: when no fragment directory exists the resolver derives one from an up-tree `.infra-kit`, so this can name a path (even under $HOME) that was never written to. Check contextDirExists before drawing any conclusion from it. Null when no `.infra-kit` anchor exists up-tree at all."),contextDirExists:ce.boolean().describe('Whether contextDir actually exists on disk. False with a non-null contextDir means the path was DERIVED, not read \u2014 the usual state in a repo where `infra-kit dev` has never run. Distinguishes "looked and found nothing" from "had nowhere to look".'),apps:ce.array(ce.object({app:ce.string().describe("App folder name (the fragment filename without .json)."),package:ce.string().describe("The app package name the vite helper reads to decide a local route."),port:ce.number().describe("The actual bound port the dev server is listening on."),pid:ce.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ce.string().describe("Registered portless hostname for the app."),origin:ce.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ce.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ce.string().nullable().describe("ISO 8601 time the runner self-reported writing the fragment (writer clock \u2014 may be wrong; prefer fragmentMtime). Null when the fragment did not record it."),fragmentMtime:ce.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ce.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ce.boolean().describe("Whether a TCP connection to the app port succeeds RIGHT NOW (a real engine liveness probe, not an inference). A fresh fragment with live:false is a crashed or killed dev server whose fragment was not cleaned up.")})).describe("One entry per dev-context fragment on disk, sorted by app name. Empty when no dev session is active.")},oc=S({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:ok,handler:()=>xs()});import{spawnSync as ug}from"node:child_process";import H from"node:fs";import al from"node:os";import ie from"node:path";import Fe from"node:process";import{z as se}from"zod";import{execFileSync as sk}from"node:child_process";var Cm=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},ik=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],ak=e=>ik.some(t=>t.test(e)),ck="/bin/ps",lk=()=>sk(ck,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
155
- `),$m=(e=lk)=>{try{return e().some(ak)}catch{return!0}};import{Chalk as dk}from"chalk";import sc from"node:process";var ic={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},uk=new Set(["warn","fail"]),pk=24,Nr=" ",Am=" ",mk=(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:[""]},Om=e=>{let t={ok:0,changed:0,skipped:0,manual:0,warn:0,fail:0};for(let r of e)t[r.status]+=1;return t},fk=e=>{let t=new dk({level:e?1:0});return{header:r=>t.bold.cyan(r),ok:r=>t.green(r),changed:r=>t.green(r),skipped:r=>t.gray(r),manual:r=>t.cyan(r),fail:r=>t.red(r),warn:r=>t.yellow(r),dim:r=>t.dim(r),bold:r=>t.bold(r)}},Im=(e,t)=>[{status:"changed",plain:`${e.changed} changed`},{status:"skipped",plain:`${e.skipped} skipped`},{status:"manual",plain:`${e.manual} to run yourself`},{status:"fail",plain:`${e.fail} failed`},{status:"warn",plain:`${e.warn} ${t(e.warn)}`}].filter(n=>e[n.status]>0),gk=(e,t,r,n)=>{if(e.ok===t){let c=`${t}/${t} ok`;return{text:r.ok(c),plainWidth:c.length}}let o=`${e.ok+e.changed}/${t}`,s=Im(e,c=>`warning${c===1?"":"s"}`),i=[r.dim(o),...s.map(c=>r[c.status](c.plain))].join(` ${n.separator} `),a=s.reduce((c,l)=>c+l.plain.length+3,o.length);return{text:i,plainWidth:a}},hk=(e,t,r,n)=>{let o=gk(Om(e.rows),e.rows.length,t,r),s=Math.max(1,n-Nr.length-e.label.length-o.plainWidth);return`${Nr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},yk=(e,t,r,n,o)=>{let s=uk.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=Am.length+i+1+t+2,p=Math.max(pk,o-d),[m,...g]=mk(e.message,p),y=" ".repeat(d),R=$=>s?$:r.dim($);return[`${Am}${c(n[e.status])} ${l} ${R(m??"")}`.trimEnd(),...g.map($=>`${y}${R($)}`),...(e.notes??[]).map($=>`${y}${$}`.trimEnd())]},vk=(e,t,r,n,o)=>{let s=Om(t),i=n.rule.repeat(Math.max(12,Math.min(o-Nr.length,56))),a=Im(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Nr}${r.dim(i)}`,`${Nr}${c}${l.join("")}`]},ac=(e,t={})=>{let r=t.width??80,n=fk(t.color??!1),o=t.unicode??!0?ic.unicode:ic.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Nr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[hk(d,n,o,r),...d.rows.flatMap(p=>yk(p,c,n,o,r)),""]);return[a,"",...l,...vk(e,i,n,o,r)]},wk=new Set(["","0","false","none"]),kk=["LC_ALL","LC_CTYPE","LANG"],bk=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!wk.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,Rk=(e,t)=>{if(t)return!1;let r=kk.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},cc=(e={})=>{let t=e.env??sc.env,r=e.stream??sc.stderr;return{color:bk(t,r),unicode:Rk(t,e.ascii??!1),width:r.columns??80}},Ye=(e,t={})=>{(t.write??(n=>{sc.stderr.write(n)}))(`${ac(e,cc(t)).join(`
154
+ `:"";try{return Zm.mkdirSync(Qm.dirname(e),{recursive:!0}),Zm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return u.warn(`Could not write ${e} (${pc(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},_s=({projectRoot:e,proxies:t,write:r})=>{let n=Qm.join(e,Ie),o=dc(n);if(o.kind==="unreadable")return u.warn(`Could not read ${n} (${pc(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:uc(s);if(!er(i))return u.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ns}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Ye];if(a!==void 0&&!er(a))return u.warn(`${n} has a "${Ye}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Vk(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Uk(n,{...i,[Ye]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var ef=async(e,t)=>{let r;try{r=(await M()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=_s({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 Jk=(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}))],tf=async e=>{let t=(await M()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Wp(t);if(r.length>0){let d=r.map(p=>({name:`devServersPresets:${p.preset}`,status:"fail",message:p.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=Lp(e),o=Bp(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await Up(e,t,s,n),c=Jk(Vp(t,i),a),l=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:l,passed:c.length===0}};var Gk="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Kk=async e=>e.root?[{dir:await T(),baseline:_n,isRoot:!0}]:e.all?(await Se(await T())).map(r=>({dir:r})):[{dir:await Ln(e.cwd??rf.cwd())}],Hk=async e=>e.root||e.all?await T():e.cwd??rf.cwd(),qk=async()=>{try{return await T()}catch{return}},Yk=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,u.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 u.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},zk=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await zm(e,t);return n&&u.info(Gk),r},Xk=e=>{if(Gn(e).kind!=="stale")return null;let t=`${Ie} still registers "${de}" \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 "${de}" entry by hand in a PR, keeping its siblings`;return u.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Ms=async(e={})=>{let t=ja(await Hk(e)),r=e.fix?await zk(e,t):void 0,n=await Kk(e),o=await Or(t),s=await qk(),i=[];for(let l of n)i.push(await oc(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await tf(n[0].dir);l&&i.push(l);let d=await ef(n[0].dir,e.fix===!0);d&&i.push(d);let p=Xk(n[0].dir);p&&i.push(p)}let c={allPassed:Yk(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Zk={all:De.boolean().optional().describe("Audit every non-vendor workspace package"),root:De.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Qk={allPassed:De.boolean().describe("Whether every audited package passed all checks"),packages:De.array(De.object({name:De.string(),passed:De.boolean(),checks:De.array(De.object({name:De.string(),status:De.enum(["pass","fail"]),message:De.string()}))})).describe("Per-package check results")},vc=S({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:Zk,outputSchema:Qk,handler:e=>Ms({all:e.all,root:e.root})});import{z as xt}from"zod";import wc from"node:fs/promises";import eb from"node:path";var Fr=()=>Object.keys(Np.shape),tb=new Set(["protectedEnvs"]),Hn={project:"per-project override",global:"user-global override"},js=(e,t)=>{if(ye()&&tb.has(e))throw new x({status:"refused",agentMode:N.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!Fr().includes(e)){if(e.includes(".")){let r=e.split(".")[0]??e;throw new Error(`Nested keys are not supported: override layers merge per top-level key, so "${e}" would replace the whole "${r}" section. Set "${r}" to its full JSON value instead, or use \`infra-kit config edit\`.`)}throw new Error(`Unknown config key "${e}". Top-level keys: ${Fr().join(", ")}.`)}},nf=e=>{try{return JSON.parse(e)}catch{return e}},rb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nb=async e=>{let t;try{t=await wc.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${v(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!rb(r))throw new Error(`${v(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},ob=async(e,t)=>{t===null?await wc.rm(e,{force:!0}):Rn(e,t,420),Tn()},Fs=async(e,t,r)=>{let n=await H(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await nb(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await wc.mkdir(eb.dirname(o),{recursive:!0}),Rn(o,`${JSON.stringify(c,null,2)}
155
+ `,420),Tn();try{await M({autoMigrate:"off"})}catch(l){throw await ob(o,s),new Error(`${l.message}
156
+ ${v(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},kc=async({key:e,value:t,global:r})=>{js(e,"config-set");let n=r?"global":"project",o=nf(t),{file:s,previous:i}=await Fs(n,e,c=>({...c,[e]:o}));u.info(`Set ${e} = ${JSON.stringify(o)} in the ${Hn[n]} (${v(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}};var Ls=async({key:e}={})=>{let[t,r]=await Promise.all([M(),H()]),n=t;if(e===void 0){let s=Object.keys(t).sort();u.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),u.info(` source: ${r.main}`)}else{if(!Fr().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Fr().join(", ")}.`);u.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},sb={config:xt.record(xt.string(),xt.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:xt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:xt.string().optional().describe("The top-level key asked for, when one was."),value:xt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:xt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},bc=S({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config-set` / `config-unset` (top-level keys) or `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{key:xt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:sb,handler:e=>Ls(e)});import ub from"node:fs";import{z as oe}from"zod";import Yn from"node:fs";import Lr from"node:path";import ib from"node:process";var ab=Lr.join(".infra-kit","dev-context"),cb=".infra-kit",of=(e,t)=>{let r=Lr.resolve(e);for(;;){let n=Lr.join(r,t);if(Yn.existsSync(n))return n;let o=Lr.dirname(r);if(o===r)return;r=o}},lb=e=>{let t=of(e,ab);if(t)return t;let r=of(e,cb);return r?Lr.join(r,"dev-context"):void 0},Rc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,qn=e=>typeof e=="string"?e:"",db=(e,t,r)=>{let n=Lr.join(e,t);try{let o=Yn.statSync(n),s=JSON.parse(Yn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:qn(i.package),port:Rc(i.port),alias:qn(i.alias),origin:qn(i.origin),release:qn(i.release),env:qn(i.env),pid:Rc(i.pid),writtenAt:Rc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},zn=(e=ib.cwd())=>{let t=Date.now(),r=lb(e);if(!r||!Yn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Yn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>db(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 Bs=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Pn,n=zn(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),g=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(ub.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){u.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",g=`written ${p.ageSeconds}s ago`;u.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${g}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";u.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},pb={active:oe.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:oe.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:oe.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:oe.array(oe.object({app:oe.string().describe("App folder name (the fragment filename without .json)."),package:oe.string().describe("The app package name the vite helper reads to decide a local route."),port:oe.number().describe("The actual bound port the dev server is listening on."),pid:oe.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:oe.string().describe("Registered portless hostname for the app."),origin:oe.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:oe.string().describe("Release slug the runner recorded for this worktree."),env:oe.string().nullable().describe("INFRA_KIT_ENV the dev session runs with \u2014 where its UIs proxy cloud routes. Null when none was loaded, or the fragment predates the field."),writtenAt:oe.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:oe.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:oe.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:oe.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.")},Sc=S({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:pb,handler:()=>Bs()});import{spawnSync as Vg}from"node:child_process";import Y from"node:fs";import xl from"node:os";import ce from"node:path";import We from"node:process";import{z as ae}from"zod";import{execFileSync as mb}from"node:child_process";var sf=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},fb=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],gb=e=>fb.some(t=>t.test(e)),hb="/bin/ps",yb=()=>mb(hb,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
157
+ `),af=(e=yb)=>{try{return e().some(gb)}catch{return!0}};import{Chalk as vb}from"chalk";import Pc from"node:process";var Ec={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},wb=new Set(["warn","fail"]),kb=24,Br=" ",cf=" ",bb=(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:[""]},lf=e=>{let t={ok:0,changed:0,skipped:0,manual:0,warn:0,fail:0};for(let r of e)t[r.status]+=1;return t},Rb=e=>{let t=new vb({level:e?1:0});return{header:r=>t.bold.cyan(r),ok:r=>t.green(r),changed:r=>t.green(r),skipped:r=>t.gray(r),manual:r=>t.cyan(r),fail:r=>t.red(r),warn:r=>t.yellow(r),dim:r=>t.dim(r),bold:r=>t.bold(r)}},df=(e,t)=>[{status:"changed",plain:`${e.changed} changed`},{status:"skipped",plain:`${e.skipped} skipped`},{status:"manual",plain:`${e.manual} to run yourself`},{status:"fail",plain:`${e.fail} failed`},{status:"warn",plain:`${e.warn} ${t(e.warn)}`}].filter(n=>e[n.status]>0),Sb=(e,t,r,n)=>{if(e.ok===t){let c=`${t}/${t} ok`;return{text:r.ok(c),plainWidth:c.length}}let o=`${e.ok+e.changed}/${t}`,s=df(e,c=>`warning${c===1?"":"s"}`),i=[r.dim(o),...s.map(c=>r[c.status](c.plain))].join(` ${n.separator} `),a=s.reduce((c,l)=>c+l.plain.length+3,o.length);return{text:i,plainWidth:a}},Pb=(e,t,r,n)=>{let o=Sb(lf(e.rows),e.rows.length,t,r),s=Math.max(1,n-Br.length-e.label.length-o.plainWidth);return`${Br}${t.header(e.label)}${" ".repeat(s)}${o.text}`},Eb=(e,t,r,n,o)=>{let s=wb.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=cf.length+i+1+t+2,p=Math.max(kb,o-d),[m,...g]=bb(e.message,p),y=" ".repeat(d),R=$=>s?$:r.dim($);return[`${cf}${c(n[e.status])} ${l} ${R(m??"")}`.trimEnd(),...g.map($=>`${y}${R($)}`),...(e.notes??[]).map($=>`${y}${$}`.trimEnd())]},xb=(e,t,r,n,o)=>{let s=lf(t),i=n.rule.repeat(Math.max(12,Math.min(o-Br.length,56))),a=df(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Br}${r.dim(i)}`,`${Br}${c}${l.join("")}`]},xc=(e,t={})=>{let r=t.width??80,n=Rb(t.color??!1),o=t.unicode??!0?Ec.unicode:Ec.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Br}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[Pb(d,n,o,r),...d.rows.flatMap(p=>Eb(p,c,n,o,r)),""]);return[a,"",...l,...xb(e,i,n,o,r)]},Tb=new Set(["","0","false","none"]),Cb=["LC_ALL","LC_CTYPE","LANG"],$b=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Tb.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,Ab=(e,t)=>{if(t)return!1;let r=Cb.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Tc=(e={})=>{let t=e.env??Pc.env,r=e.stream??Pc.stderr;return{color:$b(t,r),unicode:Ab(t,e.ascii??!1),width:r.columns??80}},ze=(e,t={})=>{(t.write??(n=>{Pc.stderr.write(n)}))(`${xc(e,Tc(t)).join(`
156
158
  `)}
157
- `)};var Sk="Tools & CLIs",Pk="Shell & integration",Ek="Project config",xk="Doppler env tokens",Tk="Dev proxy (portless)",Ck="Claude Code plugin",$k=`portless serving TLS on :${ht}`,lc=[[Sk,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Pk,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Ek,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[xk,["tokens.json present","env tokens configured","tokens.json perms"]],[Tk,["portless installed","portless node","portless service target",$k,"portless CA chain valid","portless CA trusted","portless routes"]],[Ck,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","claude in chrome","Agent mode","Agent allowlist"]]],Dm="Other",Ak=lc.map(([e])=>e),Ok=new Map(lc.flatMap(([e,t])=>t.map(r=>[r,e]))),iM=lc.flatMap(([,e])=>e),dc=new Set(["portless routes","tokens.json perms"]),Ik=e=>{let t=new Map;for(let n of e){let o=Ok.get(n.name)??Dm,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Ak,Dm].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Dk=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return We(e)}},Nk=e=>{let t=e.filter(r=>r.status==="fail"&&dc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Ik(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Dk(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var uc=(e,t={})=>{Ye(Nk(e),t)};var _k=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),Mk=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>_k(t[1])),jk=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Mk(t[1])},Fk=e=>{let t=[],r="",n=!1,o=!1,s=!1,i=[...e];for(let[a,c]of i.entries()){if(s){s=!1;continue}if(c==='"'){n=!n,o=!0;continue}let l=i[a+1];if(c==="\\"&&(l==='"'||l==="\\")){r+=l,o=!0,s=!0;continue}if(/\s/.test(c)&&!n){o&&(t.push(r),r="",o=!1);continue}r+=c,o=!0}return o&&t.push(r),t},Lk=e=>{let t=e.split(`
158
- `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:Fk(t.slice(10))},Nm=(e,t)=>{try{return e==="darwin"?jk(t):e==="linux"?Lk(t):null}catch{return null}};import{Buffer as ef}from"node:buffer";import Re from"node:fs/promises";import Xe from"node:path";import tf from"node:process";import{$ as js}from"zx";import Bk from"node:process";var Vn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var _m=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(ge())throw new x({status:"argument_required",argument:e,agentMode:I.source},2,t);if(!Bk.stdin.isTTY)throw new f(void 0,t)},Et=async e=>{_m("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new Vn;return r},xt=async(e,t)=>{_m("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new Vn;return n};import{$ as Wm}from"zx";import{$ as yM}from"zx";import{$ as Mr}from"zx";import{$ as Mm}from"zx";var pc=async e=>{let{operation:t}=e;try{await Mm({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 Mm({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"})}},Wk=4,_r=async e=>{let{operation:t}=e,r=await Hu();if(r.length===0)return;u.error(`working tree has uncommitted changes:
159
+ `)};var Ob="Tools & CLIs",Ib="Shell & integration",Db="Project config",Nb="Doppler env tokens",_b="Dev proxy (portless)",Mb="Claude Code plugin",jb=`portless serving TLS on :${ht}`,Cc=[[Ob,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Ib,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Db,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Nb,["tokens.json present","env tokens configured","tokens.json perms"]],[_b,["portless installed","portless node","portless service target",jb,"portless CA chain valid","portless CA trusted","portless routes"]],[Mb,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","claude in chrome","Agent mode","Agent allowlist"]]],uf="Other",Fb=Cc.map(([e])=>e),Lb=new Map(Cc.flatMap(([e,t])=>t.map(r=>[r,e]))),iF=Cc.flatMap(([,e])=>e),$c=new Set(["portless routes","tokens.json perms"]),Bb=e=>{let t=new Map;for(let n of e){let o=Lb.get(n.name)??uf,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Fb,uf].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Wb=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ae(e)}},Vb=e=>{let t=e.filter(r=>r.status==="fail"&&$c.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Bb(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Wb(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Ac=(e,t={})=>{ze(Vb(e),t)};var Ub=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),Jb=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>Ub(t[1])),Gb=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Jb(t[1])},Kb=e=>{let t=[],r="",n=!1,o=!1,s=!1,i=[...e];for(let[a,c]of i.entries()){if(s){s=!1;continue}if(c==='"'){n=!n,o=!0;continue}let l=i[a+1];if(c==="\\"&&(l==='"'||l==="\\")){r+=l,o=!0,s=!0;continue}if(/\s/.test(c)&&!n){o&&(t.push(r),r="",o=!1);continue}r+=c,o=!0}return o&&t.push(r),t},Hb=e=>{let t=e.split(`
160
+ `).find(r=>r.startsWith("ExecStart="));return t===void 0?null:Kb(t.slice(10))},pf=(e,t)=>{try{return e==="darwin"?Gb(t):e==="linux"?Hb(t):null}catch{return null}};import{Buffer as If}from"node:buffer";import Ee from"node:fs/promises";import Ze from"node:path";import Df from"node:process";import{$ as Xs}from"zx";import qb from"node:process";var Xn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var mf=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(J())throw new x({status:"argument_required",argument:e,agentMode:N.source},2,t);if(!qb.stdin.isTTY)throw new f(void 0,t)},Tt=async e=>{mf("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new Xn;return r},Ct=async(e,t)=>{mf("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new Xn;return n};import{$ as kf}from"zx";import{$ as yF}from"zx";import{$ as Vr}from"zx";import{$ as ff}from"zx";var Oc=async e=>{let{operation:t}=e;try{await ff({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 ff({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"})}},zb=4,Wr=async e=>{let{operation:t}=e,r=await bp();if(r.length===0)return;u.error(`working tree has uncommitted changes:
159
161
  ${r.join(`
160
- `)}`);let n=r.slice(0,Wk),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}`})},Wn=async e=>{let{operation:t,base:r}=e;if(await wr()===r)return;let n=(await gt(await E())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},be=async e=>{let{operation:t}=e;if(await Yu())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 _r({operation:t})};var Uk=e=>e.map(t=>({pr:t,id:J(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Ku(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Un=200,jm=(e,t)=>{e.length<Un||u.warn({source:t,limit:Un},`\u26A0\uFE0F ${t} returned ${Un} PRs \u2014 the page is full, so older release PRs may be missing`)},Jk=async()=>{let[e,t]=await Promise.all([Mr`gh pr list --limit ${Un} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Mr`gh pr list --limit ${Un} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);jm(r,"release PR discovery (base dev)"),jm(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)}))},Jn="find open release PRs",Fm=async()=>{try{let e=await Jk();if(e.length===0)throw new f(void 0,{operation:Jn,remediation:"open a release PR first, or check you are in the right repo"});return Uk(e)}catch(e){throw e instanceof f?e:(u.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Ts=async()=>(await Fm()).map(t=>t.headRefName),Gk=e=>{let t=Gn(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=mc(e.title)!==t;return(r||e.dualBase)&&u.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await Fm()).map(Gk),Cs=async e=>{let{branch:t,body:r}=e;try{await Mr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw u.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},Kk=async(e,t)=>{let r=Mr({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){u.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&&u.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},$s=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Gu(t,n),a=ze(n),c=Mr({quiet:!0}),l=xe(t),d=Kn(r,o);try{await _r({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await Kk(l,a),m}}catch(p){throw u.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Mr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as fc}from"zx";var jr=async e=>{let t=await fc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},gc=async e=>{let t=await fc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},hc=async e=>{try{let t=await fc`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 qn from"node:process";var Hk="x-seraph-loginreason",qk="AUTHENTICATED_FAILED",Yk=(e,t=160)=>{let r=e.split(`
161
- `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Bm=(e,t)=>t===qk||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Lm=(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}`,Fr=class extends Error{status;kind;body;context;constructor(t){let r=Bm(t.status,t.seraphLoginReason),n=Yk(t.body);super(n===""?`${t.context}: ${Lm(r,t.status)}`:`${t.context}: ${Lm(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Hn=e=>e instanceof Fr,Vm=e=>e.headers.get(Hk);var Lr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Fr({status:e.status,seraphLoginReason:Vm(e),body:r,context:t});throw u.debug({status:e.status,kind:n.kind,body:r},t),n},Yt=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,yc=async(e,t)=>{let{baseUrl:r,token:n,email:o,projectId:s}=t,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1,...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}},a=`${r}/rest/api/3/version`,c=btoa(`${o}:${n}`),l=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Lr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Br=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 Lr(a,"Failed to get Jira project versions"),await a.json()},it=async(e,t)=>(await Br(t)).find(o=>o.name===e)||null,Vr=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 Lr(c,"Failed to update Jira version");let l=await c.json();if(e.releaseDate===null&&(l.releaseDate||null)!==null)throw new Error(`Jira accepted the update (the write happened) but still reports releaseDate=${l.releaseDate}; the clear payload in updateJiraVersion needs revisiting`);return{success:!0,version:l}},vc=async(e,t)=>{let{versionName:r}=e,n=await it(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Vr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Wr=async()=>{let e=qn.env.JIRA_BASE_URL,t=qn.env.JIRA_TOKEN||qn.env.JIRA_API_TOKEN,r=qn.env.JIRA_PROJECT_ID,n=qn.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
162
- `);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},at=async()=>{try{return await Wr()}catch(e){return u.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 Lr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},wc=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 Lr(c,"Failed to remove Jira version")};var Um="dev",Jm={regular:"dev",hotfix:"main"},ze=e=>Jm[e],Gn=e=>{let t=Object.entries(Jm).find(([,r])=>r===e);return t?t[0]:null},Kn=(e,t)=>(t??"").trim()!==""?`${e}
162
+ `)}`);let n=r.slice(0,zb),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},Zn=async e=>{let{operation:t,base:r}=e;if(await Pr()===r)return;let n=(await gt(await T())).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}`})},Pe=async e=>{let{operation:t}=e;if(await Sp())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 Wr({operation:t})};var Xb=e=>e.map(t=>({pr:t,id:G(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>kp(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Qn=200,gf=(e,t)=>{e.length<Qn||u.warn({source:t,limit:Qn},`\u26A0\uFE0F ${t} returned ${Qn} PRs \u2014 the page is full, so older release PRs may be missing`)},Zb=async()=>{let[e,t]=await Promise.all([Vr`gh pr list --limit ${Qn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Vr`gh pr list --limit ${Qn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);gf(r,"release PR discovery (base dev)"),gf(n,"hotfix PR discovery (base main)");let o=new Set(r.map(c=>c.headRefName)),s=new Set(n.filter(c=>o.has(c.headRefName)).map(c=>c.headRefName)),i=[...n,...r],a=new Set;return i.filter(c=>a.has(c.headRefName)?!1:(a.add(c.headRefName),!0)).map(c=>({...c,dualBase:s.has(c.headRefName)}))},eo="find open release PRs",hf=async()=>{try{let e=await Zb();if(e.length===0)throw new f(void 0,{operation:eo,remediation:"open a release PR first, or check you are in the right repo"});return Xb(e)}catch(e){throw e instanceof f?e:(u.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Ws=async()=>(await hf()).map(t=>t.headRefName),Qb=e=>{let t=to(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Ic(e.title)!==t;return(r||e.dualBase)&&u.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},F=async()=>(await hf()).map(Qb),Vs=async e=>{let{branch:t,body:r}=e;try{await Vr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw u.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},eR=async(e,t)=>{let r=Vr({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){u.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&&u.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Us=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=wp(t,n),a=Xe(n),c=Vr({quiet:!0}),l=ve(t),d=ro(r,o);try{await Wr({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new f(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await eR(l,a),m}}catch(p){throw u.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Vr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Dc}from"zx";var Ur=async e=>{let t=await Dc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Nc=async e=>{let t=await Dc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},_c=async e=>{try{let t=await Dc`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import oo from"node:process";var tR="x-seraph-loginreason",rR="AUTHENTICATED_FAILED",nR=(e,t=160)=>{let r=e.split(`
163
+ `,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},vf=(e,t)=>t===rR||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",yf=(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}`,Jr=class extends Error{status;kind;body;context;constructor(t){let r=vf(t.status,t.seraphLoginReason),n=nR(t.body);super(n===""?`${t.context}: ${yf(r,t.status)}`:`${t.context}: ${yf(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},no=e=>e instanceof Jr,wf=e=>e.headers.get(tR);var Gr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Jr({status:e.status,seraphLoginReason:wf(e),body:r,context:t});throw u.debug({status:e.status,kind:n.kind,body:r},t),n},tr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Mc=async(e,t)=>{let{baseUrl:r,token:n,email:o,projectId:s}=t,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1,...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}},a=`${r}/rest/api/3/version`,c=btoa(`${o}:${n}`),l=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Gr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Kr=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 Gr(a,"Failed to get Jira project versions"),await a.json()},at=async(e,t)=>(await Kr(t)).find(o=>o.name===e)||null,Hr=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 Gr(c,"Failed to update Jira version");let l=await c.json();if(e.releaseDate===null&&(l.releaseDate||null)!==null)throw new Error(`Jira accepted the update (the write happened) but still reports releaseDate=${l.releaseDate}; the clear payload in updateJiraVersion needs revisiting`);return{success:!0,version:l}},jc=async(e,t)=>{let{versionName:r}=e,n=await at(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Hr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},qr=async()=>{let e=oo.env.JIRA_BASE_URL,t=oo.env.JIRA_TOKEN||oo.env.JIRA_API_TOKEN,r=oo.env.JIRA_PROJECT_ID,n=oo.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
164
+ `);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}},ct=async()=>{try{return await qr()}catch(e){return u.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Js=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 Gr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Fc=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 Gr(c,"Failed to remove Jira version")};var bf="dev",Rf={regular:"dev",hotfix:"main"},Xe=e=>Rf[e],to=e=>{let t=Object.entries(Rf).find(([,r])=>r===e);return t?t[0]:null},ro=(e,t)=>(t??"").trim()!==""?`${e}
163
165
 
164
166
  ${t}`:`${e}
165
- `,kc=async(e="regular")=>{let t=ze(e),r=Wm({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 Wm({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()},zk=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await it(t,r);if(!s)return(await yc({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 Vr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},bc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=te(t),c=await zk({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=Yt(r,c),d=await $s({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:z(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Os=async()=>{let e=new Map,t=await at();if(!t)return e;try{let r=await Br(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){u.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},ne=async()=>{let e=await Os();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Yn=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},mc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Is=e=>e.flatMap(t=>{let r=J(t);return r?[{branch:t,id:r,label:z(r)}]:[]}),ct=e=>{try{return xe(ye(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)})}},zn=e=>{if(e===Um)return Um;let t=J(e);return t?z(t):e},zt=e=>e.flatMap(t=>{let r=J(t);return r?[z(r)]:[]}),Xk=(e,t)=>t?t.get(e)||"regular":void 0,oe=e=>{let{branches:t,descriptions:r,types:n}=e;return Is(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(te(s)),type:Xk(o,n)}))};import Gm from"node:fs/promises";import Zk from"node:path";import{$ as Rc}from"zx";var L="pnpm-lock.yaml",Qk=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Hm=async(e,t)=>{let r=Zk.join(e,L),n=`${t}:${L}`;try{let o=await Rc({cwd:e,quiet:!0})`git show ${n}`;await Gm.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${L} to start from: ${Km(o)}`}}try{await Rc({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${L}: ${Km(o)}`}}return Qk.test(await Gm.readFile(r,"utf8"))?{ok:!1,reason:`${L} still carries conflict markers after pnpm ran`}:(await Rc({cwd:e,quiet:!0})`git add -- ${L}`,{ok:!0})},Km=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as Xt}from"zx";var Sc="Merge remote-tracking branch 'origin/dev' into ",qm=e=>String(e.stderr??e.message??e).trim(),eb=async e=>{try{return(await Xt({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
166
- `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},tb=async(e,t)=>{let r=qm(t),n=await eb(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await Qu(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Ym=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await Ce(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 rb({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},rb=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await Ce(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await kn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await oa(r),await Xt({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Sc}${n}`;await Xt({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await Xt({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 tb(r,i)}}finally{await sa(r)}},zm=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Xm="pnpm install --frozen-lockfile",Zm=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await oa(t),await Xt({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await Xt({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,qm(a))}finally{await sa(t)}return{kept:o,failed:s}},Xn=async(e,t,r="origin/dev")=>{await Xt({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await kn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import Pc from"node:process";var Ds=new Set,Ns=e=>(Ds.add(e),()=>{Ds.delete(e)}),nb=async()=>{for(let e of[...Ds])try{await e()}catch(t){u.warn({error:t,msg:"cleanup failed during shutdown"})}Ds.clear()},ob=["SIGINT","SIGTERM"],Qm=async(e,t={})=>{let{register:r=(i,a)=>{Pc.on(i,a)},unregister:n=(i,a)=>{Pc.off(i,a)},exit:o=i=>{Pc.exit(i)}}=t,s=new Map;for(let i of ob){let a=()=>{nb().then(()=>{o(bp(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var sb="pnpm install --frozen-lockfile --ignore-scripts",ib="pnpm install --frozen-lockfile",rf=64*1024,cf=4096,Qn=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-cf)},N=async(e,t)=>(await js({cwd:e,quiet:!0})`git ${t}`).stdout,Ec=e=>e.split(`
167
- `).map(t=>t.trim()).filter(t=>t.length>0),Fs=e=>e.split("\0").filter(t=>t.length>0),_s=async(e,t)=>{try{return(await N(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},lf=async e=>Xe.resolve(e,(await N(e,["rev-parse","--git-common-dir"])).trim()),xc=e=>e.then(()=>!0,()=>!1),Zn=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Tc=e=>e?.length===1&&e[0]===L,df=async e=>Xe.join(await lf(e),"infra-kit","merge-dev-resolutions"),Cc=async(e,t)=>Xe.join(await df(e),`${Xu(t)}.json`),uf=async e=>{try{return JSON.parse(await Re.readFile(e,"utf8"))}catch{return null}},Jr=async(e,t)=>{let r=await Cc(e,t.branch);await Re.mkdir(Xe.dirname(r),{recursive:!0}),await Re.writeFile(r,`${JSON.stringify(t,null,2)}
168
- `)},pf=async e=>{let t=await df(e),r=await Re.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>uf(Xe.join(t,o))))).filter(o=>o!==null)},mf=async e=>Promise.all((await pf(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await xc(Re.stat(t.worktreePath))}))),nf=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),$c=async(e,t,r)=>{await N(e,["worktree","remove","--force",r]).catch(()=>Re.rm(r,{recursive:!0,force:!0})),await Re.rm(await Cc(e,t),{force:!0}).catch(()=>{}),await N(e,["worktree","prune"]).catch(()=>{})},ff=async e=>Fs(await N(e,["diff","--name-only","-z","--diff-filter=U"])),Ms=async e=>Fs(await N(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),ab=async(e,t)=>{let r=(await N(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await xc(Re.stat(Xe.join(await lf(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Ec(await N(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},gf=e=>e.split("/").includes("node_modules"),Ls=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=Fs(await N(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await cb(e),...o].filter(a=>!r.has(a)),i=(await Ms(e)).filter(a=>!n.has(a)&&!gf(a));return[...new Set([...s,...i,...await lb(e)])].sort()},cb=async e=>{let t=Fs(await N(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},lb=async e=>(await N(e,["ls-files","-v"])).split(`
169
- `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),db=async e=>{let t=`:(exclude)${L}`;try{return await N(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
170
- `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},ub=async(e,t)=>{let r=[];for(let n of t)(await xc(Re.lstat(Xe.join(e,n)))||(await N(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await N(e,["--literal-pathspecs","add","-A","--",...r])},of=async e=>(await N(e,["write-tree"])).trim(),hf=async e=>(await N(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),pb=e=>e?`${ib} && ${e}`:sb,mb=async(e,t)=>{try{return await js({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Qn(r)}}},yf=async(e,t)=>{let r=(await N(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await N(e,["diff","--cached","--stat",l,"--",L])).trim(),o=t.conflictPaths.includes(L)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await N(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${L}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
171
- ${l}`:l}).join(""),c=ef.byteLength(a)>rf;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?ef.from(a).subarray(0,rf).toString():a,resolutionDiffTruncated:c}},vf=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await fb(t,s,n));return o},fb=async(e,t,r)=>{let n=await uf(await Cc(e,t));if(n)return{resolution:nf(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await Ce(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=Zu(e,t),i=()=>$c(e,t,s),a=Ns(i);try{await N(e,["worktree","prune"]),await Re.mkdir(Xe.dirname(s),{recursive:!0}),await N(e,["worktree","add","--detach",s,o]),await js({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${Sc+t}`.catch(()=>{});let c=await ff(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await _s(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await N(e,["--version"])).trim()})`};let d=await ab(s,c),p=Tc(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await Ms(s),lockfileOnly:p,cliVersion:G.version,createdAt:new Date().toISOString()};return await Jr(e,m),{resolution:nf(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:Qn(c)}}finally{a()}},wf=async e=>{let{cwd:t,versions:r,all:n}=e,o=await pf(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=xe(ye(c)),d=o.find(p=>p.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await xt(oe({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},gb=async(e,t)=>{let r=await Re.realpath(t).catch(()=>null);if(!r)return!1;let n=await gt(e);for(let o of n)if(await Re.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Ur=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),kf=async(e,t,r)=>{let n=t.worktreePath,o={branch:t.branch,worktreePath:n,baseSha:t.baseSha,devSha:t.devSha,conflictPaths:t.conflictPaths,lockfileMerged:!1,rerereFiles:t.rererePreResolved};if(!await gb(e,n))return Ur(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await _s(n,"HEAD"),i=await _s(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?kb(e,t,o,r):hb(t,o,s,i)},hb=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Ur(t,"tree-changed",`commit ${r} carries a tree a commit hook rewrote after approval \u2014 run --abort, then hand off again`);let s=n?[]:await hf(o),i=n?null:await _s(o,"HEAD^{tree}");if(!(s.length===2&&s[0]===e.baseSha&&s[1]===e.devSha&&i!==null&&i===e.previewedTree)||!r||!i){let l=n?`HEAD ${r??"none"} merging ${n}`:`HEAD ${r??"none"}`;return Ur(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Ls(o,e);return c.length>0?Ur(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(L),...await yf(o,e)}},sf=async(e,t)=>{let r=Ec(await N(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},yb=async(e,t)=>{let r=t.worktreePath,n=await sf(r,L),o=t.lockfileBlob,s=await Hm(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[L]};let i=await sf(r,L);if(i!==null&&i!==o&&(t.lockfileBlob=i,await Jr(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${L} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[L]}:{code:"out-of-scope-edit",detail:`${L} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[L]};let a=await Ls(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},vb=async(e,t)=>{let r=t.worktreePath;await ub(r,t.conflictPaths.filter(i=>i!==L));let n=await Ls(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await ff(r)).filter(i=>i!==L);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await db(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${Qn(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(L)?yb(e,t):null},wb=async(e,t,r,n)=>{if(t.verified?.treeSha===r&&t.verified.command===n)return{command:n,ok:!0,reused:!0};let o=t.worktreePath,s=new Set(await Ms(o)),i=await mb(o,n);if(!i.ok)return i;let a=(await Ms(o)).filter(c=>!s.has(c)&&!gf(c)&&Xe.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await Jr(e,t),i},kb=async(e,t,r,n)=>{let o=t.worktreePath,s=await vb(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(L),a=await of(o),c=await wb(e,t,a,pb(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Ur(l,"verify-failed",c.reason??"the verify command failed");let d=await Ls(o,t),p=Ec(await N(o,["diff","--name-only"]));return d.length>0||p.length>0||await of(o)!==a?Ur(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await Jr(e,t)),{...l,...await yf(o,t)})},bb=12e4,Rb=async(e,t=bb)=>{let r=js({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...tf.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&tf.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Qn(s)};let i=(await N(e,["rev-parse","--git-path","index.lock"])).trim();return await Re.rm(Xe.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},Sb={"verify-failed":"verify-failed","tree-changed":"tree-changed"},Pb=e=>{let t=e.blocked;return{branch:e.branch,status:Sb[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},Eb=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,p,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:p,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await Rb(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await N(o,["rev-parse","HEAD"])).trim(),c=(await N(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await Jr(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await hf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},xb=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await Xn(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Qn(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await Ce(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await kn(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},Tb=e=>{u.info(`
172
- \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?u.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):u.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},bf=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await wf({cwd:t,versions:r,all:n});if(a.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),Zn();if(i)return af(t,a,o,s);let c=[];for(let m of a){let g=await kf(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await Jr(t,m)),c.push(g)}Tb(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new x({status:"refused",plan:l,agentMode:I.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(d.map(m=>[m.branch,m.treeSha]));try{await B(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Cb(p)})}catch(m){if(!nt(m))throw m;return{...Zn(),declined:!0}}return af(t,a,o,p)},Rf=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},Cb=e=>{let t=[],r=!1;for(let o of yp())r?r=!1:o==="--tree"?r=!0:o!=="--yes"&&o!=="-y"&&!o.startsWith("--tree=")&&t.push(o);let n=[...e].map(([o,s])=>`${o}=${s}`);return[...t,"--tree",n.join(","),"--yes"]},$b=async(e,t,r,n)=>{let o=await kf(e,t,r);if(o.blocked)return Pb(o);let s=await Eb(e,o,t,n);if(!("sha"in s))return s;let i=await xb(e,t,s.sha);return i==="keep"?s:i},Ab=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));u.info(`
173
- \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await ns(e,r),o=[];for(let s of t){let i=n.pushed||await kr(e,s.record.branch)===s.sha;o.push({branch:s.record.branch,status:i?"merged":"push-aborted",mergeSha:s.sha,conflictPaths:s.record.conflictPaths,pushed:i,...i?{}:{reason:n.stderr?.trim().slice(-cf)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
174
- `)[0]}}},af=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let p=await $b(e,d,r,n.get(d.branch));"sha"in p?s.push({record:d,sha:p.sha}):o.push(p)}let i=await Ab(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(p=>p.branch===d.branch&&(p.pushed||p.status==="up-to-date")));for(let d of c)await $c(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,p)=>l.indexOf(d.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},Sf=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await wf({cwd:t,versions:r,all:n});if(s.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),Zn();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await B(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!nt(a))throw a;return{...Zn(),declined:!0}}for(let a of s)await $c(t,a.branch,a.worktreePath),u.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Zn(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Ob from"node:fs";import Ib from"node:os";import Db from"node:path";var Nb="infra-kit.json",_b="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)",Mb="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",eo=async()=>{let e;try{e=await E()}catch{return null}let t=e.trim();return t===""||t===Ib.homedir()?null:t},Pf=async()=>{let e=await eo();return e===null&&u.info(_b),e},jb=async()=>{let e=await eo();return e===null?null:Ob.existsSync(Db.join(e,Nb))?e:(u.info(Mb),null)};var Fb=async e=>{try{return await ke(e)}catch(t){return u.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Ef=async()=>{let e=await jb(),t=G.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Nn(e,{version:t})];for(let n of await Fb(e)){let o=await Ut(n);r.push(...await _n(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import le from"node:fs";import Fc from"node:os";import de from"node:path";import Lc from"node:process";import Vs from"node:fs/promises";import Lb from"node:path";import Bb from"node:process";var xf=` // "envManagement": { // required in layer 1; provider-tagged
167
+ `,Lc=async(e="regular")=>{let t=Xe(e),r=kf({quiet:!0});await r`git fetch origin`,await r`git switch ${t}`;try{await r`git pull --ff-only origin ${t}`}catch(n){let o=await kf({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},oR=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await at(t,r);if(!s)return(await Mc({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 Hr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Bc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=re(t),c=await oR({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=tr(r,c),d=await Us({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:X(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Gs=async()=>{let e=new Map,t=await ct();if(!t)return e;try{let r=await Kr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){u.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},se=async()=>{let e=await Gs();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},so=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Ic=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Ks=e=>e.flatMap(t=>{let r=G(t);return r?[{branch:t,id:r,label:X(r)}]:[]}),lt=e=>{try{return ve(pe(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},io=e=>{if(e===bf)return bf;let t=G(e);return t?X(t):e},rr=e=>e.flatMap(t=>{let r=G(t);return r?[X(r)]:[]}),sR=(e,t)=>t?t.get(e)||"regular":void 0,ie=e=>{let{branches:t,descriptions:r,types:n}=e;return Ks(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(re(s)),type:sR(o,n)}))};import Sf from"node:fs/promises";import iR from"node:path";import{$ as Wc}from"zx";var W="pnpm-lock.yaml",aR=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Ef=async(e,t)=>{let r=iR.join(e,W),n=`${t}:${W}`;try{let o=await Wc({cwd:e,quiet:!0})`git show ${n}`;await Sf.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${W} to start from: ${Pf(o)}`}}try{await Wc({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${W}: ${Pf(o)}`}}return aR.test(await Sf.readFile(r,"utf8"))?{ok:!1,reason:`${W} still carries conflict markers after pnpm ran`}:(await Wc({cwd:e,quiet:!0})`git add -- ${W}`,{ok:!0})},Pf=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as nr}from"zx";var Vc="Merge remote-tracking branch 'origin/dev' into ",xf=e=>String(e.stderr??e.message??e).trim(),cR=async e=>{try{return(await nr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
168
+ `).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},lR=async(e,t)=>{let r=xf(t),n=await cR(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await Tp(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Tf=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await $e(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await dR({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},dR=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await $e(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await xn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await va(r),await nr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Vc}${n}`;await nr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await nr({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 lR(r,i)}}finally{await wa(r)}},Cf=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),$f="pnpm install --frozen-lockfile",Af=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await va(t),await nr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await nr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,xf(a))}finally{await wa(t)}return{kept:o,failed:s}},ao=async(e,t,r="origin/dev")=>{await nr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await xn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import Uc from"node:process";var Hs=new Set,qs=e=>(Hs.add(e),()=>{Hs.delete(e)}),uR=async()=>{for(let e of[...Hs])try{await e()}catch(t){u.warn({error:t,msg:"cleanup failed during shutdown"})}Hs.clear()},pR=["SIGINT","SIGTERM"],Of=async(e,t={})=>{let{register:r=(i,a)=>{Uc.on(i,a)},unregister:n=(i,a)=>{Uc.off(i,a)},exit:o=i=>{Uc.exit(i)}}=t,s=new Map;for(let i of pR){let a=()=>{uR().then(()=>{o(Yp(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var mR="pnpm install --frozen-lockfile --ignore-scripts",fR="pnpm install --frozen-lockfile",Nf=64*1024,Lf=4096,lo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Lf)},j=async(e,t)=>(await Xs({cwd:e,quiet:!0})`git ${t}`).stdout,Jc=e=>e.split(`
169
+ `).map(t=>t.trim()).filter(t=>t.length>0),Zs=e=>e.split("\0").filter(t=>t.length>0),Ys=async(e,t)=>{try{return(await j(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Bf=async e=>Ze.resolve(e,(await j(e,["rev-parse","--git-common-dir"])).trim()),Gc=e=>e.then(()=>!0,()=>!1),co=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Kc=e=>e?.length===1&&e[0]===W,Wf=async e=>Ze.join(await Bf(e),"infra-kit","merge-dev-resolutions"),Hc=async(e,t)=>Ze.join(await Wf(e),`${Ep(t)}.json`),Vf=async e=>{try{return JSON.parse(await Ee.readFile(e,"utf8"))}catch{return null}},zr=async(e,t)=>{let r=await Hc(e,t.branch);await Ee.mkdir(Ze.dirname(r),{recursive:!0}),await Ee.writeFile(r,`${JSON.stringify(t,null,2)}
170
+ `)},Uf=async e=>{let t=await Wf(e),r=await Ee.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Vf(Ze.join(t,o))))).filter(o=>o!==null)},Jf=async e=>Promise.all((await Uf(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await Gc(Ee.stat(t.worktreePath))}))),_f=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),qc=async(e,t,r)=>{await j(e,["worktree","remove","--force",r]).catch(()=>Ee.rm(r,{recursive:!0,force:!0})),await Ee.rm(await Hc(e,t),{force:!0}).catch(()=>{}),await j(e,["worktree","prune"]).catch(()=>{})},Gf=async e=>Zs(await j(e,["diff","--name-only","-z","--diff-filter=U"])),zs=async e=>Zs(await j(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),gR=async(e,t)=>{let r=(await j(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await Gc(Ee.stat(Ze.join(await Bf(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Jc(await j(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},Kf=e=>e.split("/").includes("node_modules"),Qs=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=Zs(await j(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await hR(e),...o].filter(a=>!r.has(a)),i=(await zs(e)).filter(a=>!n.has(a)&&!Kf(a));return[...new Set([...s,...i,...await yR(e)])].sort()},hR=async e=>{let t=Zs(await j(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},yR=async e=>(await j(e,["ls-files","-v"])).split(`
171
+ `).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),vR=async e=>{let t=`:(exclude)${W}`;try{return await j(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
172
+ `)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},wR=async(e,t)=>{let r=[];for(let n of t)(await Gc(Ee.lstat(Ze.join(e,n)))||(await j(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await j(e,["--literal-pathspecs","add","-A","--",...r])},Mf=async e=>(await j(e,["write-tree"])).trim(),Hf=async e=>(await j(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),kR=e=>e?`${fR} && ${e}`:mR,bR=async(e,t)=>{try{return await Xs({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:lo(r)}}},qf=async(e,t)=>{let r=(await j(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await j(e,["diff","--cached","--stat",l,"--",W])).trim(),o=t.conflictPaths.includes(W)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await j(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${W}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
173
+ ${l}`:l}).join(""),c=If.byteLength(a)>Nf;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?If.from(a).subarray(0,Nf).toString():a,resolutionDiffTruncated:c}},Yf=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await RR(t,s,n));return o},RR=async(e,t,r)=>{let n=await Vf(await Hc(e,t));if(n)return{resolution:_f(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await $e(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=xp(e,t),i=()=>qc(e,t,s),a=qs(i);try{await j(e,["worktree","prune"]),await Ee.mkdir(Ze.dirname(s),{recursive:!0}),await j(e,["worktree","add","--detach",s,o]),await Xs({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${Vc+t}`.catch(()=>{});let c=await Gf(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await Ys(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await j(e,["--version"])).trim()})`};let d=await gR(s,c),p=Kc(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await zs(s),lockfileOnly:p,cliVersion:K.version,createdAt:new Date().toISOString()};return await zr(e,m),{resolution:_f(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:lo(c)}}finally{a()}},zf=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Uf(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=ve(pe(c)),d=o.find(p=>p.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await Ct(ie({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},SR=async(e,t)=>{let r=await Ee.realpath(t).catch(()=>null);if(!r)return!1;let n=await gt(e);for(let o of n)if(await Ee.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Yr=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Xf=async(e,t,r)=>{let n=t.worktreePath,o={branch:t.branch,worktreePath:n,baseSha:t.baseSha,devSha:t.devSha,conflictPaths:t.conflictPaths,lockfileMerged:!1,rerereFiles:t.rererePreResolved};if(!await SR(e,n))return Yr(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Ys(n,"HEAD"),i=await Ys(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?CR(e,t,o,r):PR(t,o,s,i)},PR=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Yr(t,"tree-changed",`commit ${r} carries a tree a commit hook rewrote after approval \u2014 run --abort, then hand off again`);let s=n?[]:await Hf(o),i=n?null:await Ys(o,"HEAD^{tree}");if(!(s.length===2&&s[0]===e.baseSha&&s[1]===e.devSha&&i!==null&&i===e.previewedTree)||!r||!i){let l=n?`HEAD ${r??"none"} merging ${n}`:`HEAD ${r??"none"}`;return Yr(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Qs(o,e);return c.length>0?Yr(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(W),...await qf(o,e)}},jf=async(e,t)=>{let r=Jc(await j(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},ER=async(e,t)=>{let r=t.worktreePath,n=await jf(r,W),o=t.lockfileBlob,s=await Ef(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[W]};let i=await jf(r,W);if(i!==null&&i!==o&&(t.lockfileBlob=i,await zr(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${W} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[W]}:{code:"out-of-scope-edit",detail:`${W} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[W]};let a=await Qs(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},xR=async(e,t)=>{let r=t.worktreePath;await wR(r,t.conflictPaths.filter(i=>i!==W));let n=await Qs(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await Gf(r)).filter(i=>i!==W);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await vR(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${lo(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(W)?ER(e,t):null},TR=async(e,t,r,n)=>{if(t.verified?.treeSha===r&&t.verified.command===n)return{command:n,ok:!0,reused:!0};let o=t.worktreePath,s=new Set(await zs(o)),i=await bR(o,n);if(!i.ok)return i;let a=(await zs(o)).filter(c=>!s.has(c)&&!Kf(c)&&Ze.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await zr(e,t),i},CR=async(e,t,r,n)=>{let o=t.worktreePath,s=await xR(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(W),a=await Mf(o),c=await TR(e,t,a,kR(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Yr(l,"verify-failed",c.reason??"the verify command failed");let d=await Qs(o,t),p=Jc(await j(o,["diff","--name-only"]));return d.length>0||p.length>0||await Mf(o)!==a?Yr(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await zr(e,t)),{...l,...await qf(o,t)})},$R=12e4,AR=async(e,t=$R)=>{let r=Xs({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Df.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Df.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:lo(s)};let i=(await j(e,["rev-parse","--git-path","index.lock"])).trim();return await Ee.rm(Ze.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},OR={"verify-failed":"verify-failed","tree-changed":"tree-changed"},IR=e=>{let t=e.blocked;return{branch:e.branch,status:OR[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},DR=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,p,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:p,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await AR(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await j(o,["rev-parse","HEAD"])).trim(),c=(await j(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await zr(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await Hf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},NR=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await ao(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${lo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await $e(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await xn(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},_R=e=>{u.info(`
174
+ \u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?u.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):u.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Zf=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await zf({cwd:t,versions:r,all:n});if(a.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),co();if(i)return Ff(t,a,o,s);let c=[];for(let m of a){let g=await Xf(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await zr(t,m)),c.push(g)}_R(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new x({status:"refused",plan:l,agentMode:N.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(d.map(m=>[m.branch,m.treeSha]));try{await V(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:MR(p)})}catch(m){if(!ot(m))throw m;return{...co(),declined:!0}}return Ff(t,a,o,p)},Qf=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},MR=e=>{let t=[],r=!1;for(let o of Gp())r?r=!1:o==="--tree"?r=!0:o!=="--yes"&&o!=="-y"&&!o.startsWith("--tree=")&&t.push(o);let n=[...e].map(([o,s])=>`${o}=${s}`);return[...t,"--tree",n.join(","),"--yes"]},jR=async(e,t,r,n)=>{let o=await Xf(e,t,r);if(o.blocked)return IR(o);let s=await DR(e,o,t,n);if(!("sha"in s))return s;let i=await NR(e,t,s.sha);return i==="keep"?s:i},FR=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));u.info(`
175
+ \u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await hs(e,r),o=[];for(let s of t){let i=n.pushed||await Er(e,s.record.branch)===s.sha;o.push({branch:s.record.branch,status:i?"merged":"push-aborted",mergeSha:s.sha,conflictPaths:s.record.conflictPaths,pushed:i,...i?{}:{reason:n.stderr?.trim().slice(-Lf)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
176
+ `)[0]}}},Ff=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let p=await jR(e,d,r,n.get(d.branch));"sha"in p?s.push({record:d,sha:p.sha}):o.push(p)}let i=await FR(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(p=>p.branch===d.branch&&(p.pushed||p.status==="up-to-date")));for(let d of c)await qc(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,p)=>l.indexOf(d.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},eg=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await zf({cwd:t,versions:r,all:n});if(s.length===0)return u.info("\u2139\uFE0F No merge-dev resolutions in progress"),co();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await V(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!ot(a))throw a;return{...co(),declined:!0}}for(let a of s)await qc(t,a.branch,a.worktreePath),u.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...co(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import LR from"node:fs";import BR from"node:os";import WR from"node:path";var VR="infra-kit.json",UR="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)",JR="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",uo=async()=>{let e;try{e=await T()}catch{return null}let t=e.trim();return t===""||t===BR.homedir()?null:t},tg=async()=>{let e=await uo();return e===null&&u.info(UR),e},GR=async()=>{let e=await uo();return e===null?null:LR.existsSync(WR.join(e,VR))?e:(u.info(JR),null)};var KR=async e=>{try{return await Se(e)}catch(t){return u.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},rg=async()=>{let e=await GR(),t=K.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Wn(e,{version:t})];for(let n of await KR(e)){let o=await Yt(n);r.push(...await Vn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import ue from"node:fs";import nl from"node:os";import fe from"node:path";import ol from"node:process";import ti from"node:fs/promises";import HR from"node:path";import qR from"node:process";var ng=` // "envManagement": { // required in layer 1; provider-tagged
175
177
  // "provider": "doppler",
176
178
  // "config": { "name": "my-doppler-project" }
177
179
  // },
@@ -289,7 +291,7 @@ ${l}`:l}).join(""),c=ef.byteLength(a)>rf;return{diffStat:r,...o?{lockfileDiffSta
289
291
  // // also fixes its modes), or by hand: both are supported, which is why the store carries no
290
292
  // // repo-identity field and no mandatory version. Pasting a token into an
291
293
  // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
292
- // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Ac=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
294
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Yc=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
293
295
  //
294
296
  // Merge chain (later layers override earlier ones at top-level keys):
295
297
  // 1. <repo>/infra-kit.json \u2014 committed project config (required)
@@ -310,9 +312,9 @@ ${l}`:l}).join(""),c=ef.byteLength(a)>rf;return{diffStat:r,...o?{lockfileDiffSta
310
312
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
311
313
  // user-global layer \u2014 it is shown here only to document the full, valid config shape.
312
314
  {
313
- ${xf}
315
+ ${ng}
314
316
  }
315
- `,Oc=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
317
+ `,zc=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
316
318
  //
317
319
  // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
318
320
  // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
@@ -329,9 +331,9 @@ ${xf}
329
331
  // the committed project infra-kit.json (layer 1) and is usually NOT set in this
330
332
  // override layer \u2014 it is shown here only to document the full, valid config shape.
331
333
  {
332
- ${xf}
334
+ ${ng}
333
335
  }
334
- `,Ic=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
336
+ `,Xc=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
335
337
  //
336
338
  // Machine-local registry the vendor commands (sync/manifest/diff) read to know
337
339
  // where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
@@ -343,86 +345,92 @@ ${xf}
343
345
  // "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
344
346
  // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
345
347
  }
346
- `;var Tf=!1,Vb=e=>e.replace(/\.json$/,".example.jsonc"),Wb=async e=>{try{return await Vs.readFile(e,"utf-8")}catch{return null}},Gr=async e=>{let t=e.userProject,r=Vb(t);await Vs.mkdir(Lb.dirname(t),{recursive:!0});let n=!await X(t);n&&await Vs.writeFile(t,`{}
347
- `,"utf-8");let o=Oc(e.projectName),s=await Wb(r)!==o;return s&&await Vs.writeFile(r,o,"utf-8"),n&&lp(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Kr=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,Dc=async()=>{if(Bb.env.INFRA_KIT_NO_SEED||Tf)return;Tf=!0;let e;try{e=await ee()}catch{return}if(await X(e.main))try{let t=await Gr(e);t.createdConfig?u.info(Kr(t)):t.refreshedExample&&u.debug(`Refreshed ${v(t.examplePath)} to match the current schema.`)}catch(t){u.debug({err:t,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import{spawn as Ub}from"node:child_process";import $f from"node:fs";import Hr from"node:process";import{fileURLToPath as Af}from"node:url";var Cf=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Nc=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Cf.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Su(o,s,i)?"local-install":null:"not-a-tty"};var Jb=e=>{Ub(Hr.execPath,[e,"--parent-pid",String(Hr.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Gb=()=>Af(new URL("./update-check.js",import.meta.url)),Kb=()=>$f.realpathSync(Af(new URL("./cli.js",import.meta.url))),Hb=/^[\w@./+ -]+$/i,qb=e=>Hb.test(e),Yb=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Rn(e.latestVersion,t)&&e.updateCommand.every(qb)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Yo(e.updateCommand)}`)},_c=(e,t={})=>{try{let r=t.argv??Hr.argv,n=t.env??Hr.env,o=t.isTty??!!Hr.stdout.isTTY,s=t.cwd??Hr.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??Kb(),c=t.readCache??Sn,l=t.spawnChild??Jb,d=t.fileExists??(y=>$f.existsSync(y)),p=t.notify??(y=>{u.info(y)});if(Nc({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:me})!==null)return;let m=c();if(Yb(m,e,p),!la(m,i))return;let g=t.childPath??Gb();if(!d(g))return;l(g)}catch{}};import Qe from"node:fs/promises";import Ze from"node:path";import{pathToFileURL as Zb}from"node:url";import Qb from"yaml";import{z as zr}from"zod";import zb from"node:fs/promises";import Mc from"node:os";import jc from"node:path";import{z as Xb}from"zod";import{z as to}from"zod";var Of="vendor.json",If=to.object({workspaceDir:to.string().min(1),source:to.string().min(1),targets:to.array(to.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var qr=()=>jc.join(Mc.homedir(),gu,Of),Yr=e=>{if(e==="~")return Mc.homedir();if(e.startsWith("~/"))return jc.join(Mc.homedir(),e.slice(2));if(jc.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Ws=async()=>{let e=qr(),t;try{t=await zb.readFile(e,"utf-8")}catch{throw new Error(`Factory config not found at ${e}. infra-kit needs a machine-local factory registry to know where your project repos live, which one is the source and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
348
+ `;var og=!1,YR=e=>e.replace(/\.json$/,".example.jsonc"),zR=async e=>{try{return await ti.readFile(e,"utf-8")}catch{return null}},Xr=async e=>{let t=e.userProject,r=YR(t);await ti.mkdir(HR.dirname(t),{recursive:!0});let n=!await Z(t);n&&await ti.writeFile(t,`{}
349
+ `,"utf-8");let o=zc(e.projectName),s=await zR(r)!==o;return s&&await ti.writeFile(r,o,"utf-8"),n&&Tn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Zr=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,Zc=async()=>{if(qR.env.INFRA_KIT_NO_SEED||og)return;og=!0;let e;try{e=await H()}catch{return}if(await Z(e.main))try{let t=await Xr(e);t.createdConfig?u.info(Zr(t)):t.refreshedExample&&u.debug(`Refreshed ${v(t.examplePath)} to match the current schema.`)}catch(t){u.debug({err:t,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import{spawn as XR}from"node:child_process";import ig from"node:fs";import Qr from"node:process";import{fileURLToPath as ag}from"node:url";var sg=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Qc=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return sg.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Xu(o,s,i)?"local-install":null:"not-a-tty"};var ZR=e=>{XR(Qr.execPath,[e,"--parent-pid",String(Qr.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},QR=()=>ag(new URL("./update-check.js",import.meta.url)),eS=()=>ig.realpathSync(ag(new URL("./cli.js",import.meta.url))),tS=/^[\w@./+ -]+$/i,rS=e=>tS.test(e),nS=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||$n(e.latestVersion,t)&&e.updateCommand.every(rS)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${cs(e.updateCommand)}`)},el=(e,t={})=>{try{let r=t.argv??Qr.argv,n=t.env??Qr.env,o=t.isTty??!!Qr.stdout.isTTY,s=t.cwd??Qr.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??eS(),c=t.readCache??An,l=t.spawnChild??ZR,d=t.fileExists??(y=>ig.existsSync(y)),p=t.notify??(y=>{u.info(y)});if(Qc({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:he})!==null)return;let m=c();if(nS(m,e,p),!Sa(m,i))return;let g=t.childPath??QR();if(!d(g))return;l(g)}catch{}};import et from"node:fs/promises";import Qe from"node:path";import{pathToFileURL as iS}from"node:url";import aS from"yaml";import{z as rn}from"zod";import oS from"node:fs/promises";import tl from"node:os";import rl from"node:path";import{z as sS}from"zod";import{z as po}from"zod";var cg="vendor.json",lg=po.object({workspaceDir:po.string().min(1),source:po.string().min(1),targets:po.array(po.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var en=()=>rl.join(tl.homedir(),Uu,cg),tn=e=>{if(e==="~")return tl.homedir();if(e.startsWith("~/"))return rl.join(tl.homedir(),e.slice(2));if(rl.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},ri=async()=>{let e=en(),t;try{t=await oS.readFile(e,"utf-8")}catch{throw new Error(`Factory config not found at ${e}. infra-kit needs a machine-local factory registry to know where your project repos live, which one is the source and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
348
350
 
349
351
  {
350
352
  "workspaceDir": "~/projects",
351
353
  "source": "my-starter",
352
354
  "targets": ["my-repo"]
353
355
  }
354
- `)}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=If.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${Xb.prettifyError(n.error)}`);return n.data};var Df=e=>e.replace(/\.json$/,".yml"),Nf=async()=>{let e;try{e=await ee()}catch{return}let t=[{label:"infra-kit.json",yml:Df(e.main),json:e.main,schema:ip},{label:"~/.infra-kit/infra-kit.json",yml:Ze.join(Ze.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:ia},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Df(e.userProject),json:e.userProject,schema:ia}],r=0;for(let n of t){let[o,s]=await Promise.all([X(n.yml),X(n.json)]);if(o){if(s){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 ${v(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await Qe.readFile(n.yml,"utf-8"),a=Qb.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 invalid config: ${zr.prettifyError(c.error)}`);continue}await Qe.mkdir(Ze.dirname(n.json),{recursive:!0}),await Qe.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
355
- `,"utf-8"),await Qe.rm(n.yml,{force:!0}),u.info(`\u2713 Migrated ${v(n.yml)} \u2192 ${v(n.json)}`),r++}catch(i){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 ${i.message}`)}}}r>0&&vt()},_f=async()=>{let e;try{e=await ee()}catch{return}let t=Ze.dirname(e.userGlobal),r=[{from:Ze.join(t,"config.json"),to:e.userGlobal},{from:Ze.join(t,"config.example.jsonc"),to:Ze.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([X(o),X(s)]);if(i){if(a){u.info(`\u26A0 Skipped ${v(o)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await Qe.mkdir(Ze.dirname(s),{recursive:!0}),await Qe.rename(o,s),u.info(`\u2713 Renamed ${v(o)} \u2192 ${v(s)}`),n++}catch(c){u.info(`\u26A0 Skipped ${v(o)} \u2014 ${c.message}`)}}}n>0&&vt()},eR=zr.object({workspaceDir:zr.string().min(1),targets:zr.array(zr.string()).min(1)}).strict(),Mf=async()=>{let e=qr(),t=Ze.dirname(e),r=Ze.join(t,"vendor.config.ts"),[n,o]=await Promise.all([X(r),X(e)]);if(n){if(o){u.info(`\u26A0 Skipped ${v(r)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await Qe.stat(r),c=(await import(`${Zb(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,p=eR.safeParse(d);if(!p.success){u.info(`\u26A0 Skipped ${v(r)} \u2014 invalid factory config: ${zr.prettifyError(p.error)}`);return}await Qe.mkdir(t,{recursive:!0}),await Qe.writeFile(e,`${JSON.stringify(p.data,null,2)}
356
- `,"utf-8"),await Qe.rm(r,{force:!0}),l?u.info(`\u26A0 Migrated ${v(r)} \u2192 ${v(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${v(e)} directly to change them.`):u.info(`\u2713 Migrated ${v(r)} \u2192 ${v(e)}`)}catch(s){u.info(`\u26A0 Skipped ${v(r)} \u2014 ${s.message}`)}}},jf=async()=>{let e=await tR(),t=0;for(let r of e)if(await X(r))try{let n=await np(r);if(!n.changed)continue;u.info(`\u2713 Migrated ${v(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof tp?"changed while migrating":n.message;u.info(`\u26A0 Skipped ${v(r)} \u2014 ${o}`)}t>0&&vt()},tR=async()=>{try{let e=await ee();return[e.main,e.userGlobal,e.userProject]}catch{return[cp()]}};var Zt="# -- infra-kit:begin --",Tt="# -- infra-kit:end --",rR=[["# region infra-kit","# endregion infra-kit"]],nR="# infra-kit shell functions",Xr=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},Zr="Run `source ~/.zshrc` or open a new terminal to activate.",oR={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},et=async(e,t)=>{try{return await t()}catch(r){throw new Xr(e,r)}},Bc=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await et("zshrc",()=>{r(sR())}),await et("zshenv",()=>{r(iR())}),await et("migrations",async()=>{await cR(),aR(),r(oR)}),await et("user-config",()=>{r(dR())});let n=await et("guidance",async()=>{let{entries:s,root:i}=await mR();return r(...s),i}),o=await et("plugin-pointer",async()=>Pf());return r(...hR(o,n)),await et("worktrees",async()=>{r(...await bR(o))}),await et("plugin-pointer",async()=>{await RR(o,r)}),await et("mcp-proxies",async()=>{r(...await PR(o))}),await et("project-config",async()=>{r(...await uR())}),r(...lR()),t};var sR=()=>{let e=de.join(Fc.homedir(),".zshrc"),t=le.existsSync(e)?xR(le.readFileSync(e,"utf-8")):"",r=Er({content:t,body:Lf(),startMarker:Zt,endMarker:Tt,placement:"append-end"});return le.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},iR=()=>{let e=de.join(Fc.homedir(),".zshenv"),t=le.existsSync(e)?le.readFileSync(e,"utf-8"):"",r=Er({content:t,body:Vc(),startMarker:Zt,endMarker:Tt});return le.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},aR=()=>{le.rmSync(de.join(wu(),"projects"),{recursive:!0,force:!0})},cR=async()=>{await Nf(),await _f(),await jf(),await Mf()},lR=()=>{let e=Lc.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:Zr,level:"info"}),t},dR=()=>{let e=de.join(Fc.homedir(),".infra-kit"),t=de.join(e,"infra-kit.json");return le.mkdirSync(e,{recursive:!0}),le.writeFileSync(de.join(e,"infra-kit.example.jsonc"),Ac(),"utf-8"),le.writeFileSync(de.join(e,"vendor.example.jsonc"),Ic(),"utf-8"),le.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(le.writeFileSync(t,`{}
357
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},uR=async()=>{if(Lc.env.INFRA_KIT_NO_SEED)return[Us("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await ee();if(!le.existsSync(e.main))return[Us("skipped",`no project config at ${e.main}`)];let t=await Gr(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:Kr(t),level:"info"}]:[Us("unchanged","the user-project config was already present")]}catch(e){return u.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[Us("warned",e instanceof Error?e.message:String(e))]}},Us=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),pR=(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)} ${de.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},mR=async()=>{let{skipped:e,root:t,version:r,written:n}=await Ef();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:pR(t,r,n)}},fR=(e,t)=>{let r=de.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"}},gR=(e,t)=>{let r=Ae;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?ae:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${qe} from ${de.join(e,Ae)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: none wanted \u2014 the plugin is skills-only (${t.kind==="absent"?`${r} carries no "${ae}" key`:`no ${r}`})`,level:"info"}},hR=(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 ${K} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],yR=()=>[Ya,st].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),vR=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${G.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${G.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"};return e.stale?[r,{step:"plugin-pointer",outcome:"manual",message:Yo(e.updateCommand),level:"info"}]:[r]},wR=(e,t)=>e.status==="skipped-cli-stale"?vR(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${K} 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: ${Ir}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${K} (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"},...yR()]:[{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: ${st}`,level:"warn"}],Ff={stale:!1},kR=async()=>{let e=Sn(),t=e===null?await da(Lc.env):e.latestVersion;return t===null||!ua(t,G.version)?Ff:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Ru(t)}},bR=async e=>{if(e===null)return[];let r=`${await je(e)}${pe}`,n=Object.values(vr).filter(o=>!le.existsSync(de.join(r,o)));for(let o of Object.values(vr))le.mkdirSync(de.join(r,o),{recursive:!0});return n.length===0?[{step:"worktrees",outcome:"unchanged",message:`Worktree directories already present at ${r}`,level:"info"}]:[{step:"worktrees",outcome:"written",message:`Created worktree directories at ${r} (${n.join(", ")})`,level:"info"}]},RR=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(fR(e,za(de.join(e,".claude","settings.json"))));let n=Ft({projectPath:e}).kind==="installed"?await kR():Ff;t(...wR(Ja({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(gR(e,jn(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: ${st}`,level:"warn"})}},SR=(e,t)=>{let r=de.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},PR=async e=>{if(e===null)return[];if(!le.existsSync(de.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 M()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
358
- `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:SR(e,Rs({projectRoot:e,proxies:t,write:!0}))},ER=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"),xR=e=>{let t=St(e,Zt,Tt);if(t!==null)return t;for(let[a,c]of rR){let l=St(e,a,c);if(l!==null)return l}let r=e.indexOf(nR);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
359
- `),s=0;for(;s<o.length&&ER(o[s]);)s++;let i=o.slice(s).join(`
356
+ `)}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=lg.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${sS.prettifyError(n.error)}`);return n.data};var dg=e=>e.replace(/\.json$/,".yml"),ug=async()=>{let e;try{e=await H()}catch{return}let t=[{label:"infra-kit.json",yml:dg(e.main),json:e.main,schema:_p},{label:"~/.infra-kit/infra-kit.json",yml:Qe.join(Qe.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:ka},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:dg(e.userProject),json:e.userProject,schema:ka}],r=0;for(let n of t){let[o,s]=await Promise.all([Z(n.yml),Z(n.json)]);if(o){if(s){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 ${v(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await et.readFile(n.yml,"utf-8"),a=aS.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 invalid config: ${rn.prettifyError(c.error)}`);continue}await et.mkdir(Qe.dirname(n.json),{recursive:!0}),await et.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
357
+ `,"utf-8"),await et.rm(n.yml,{force:!0}),u.info(`\u2713 Migrated ${v(n.yml)} \u2192 ${v(n.json)}`),r++}catch(i){u.info(`\u26A0 Skipped ${v(n.yml)} \u2014 ${i.message}`)}}}r>0&&vt()},pg=async()=>{let e;try{e=await H()}catch{return}let t=Qe.dirname(e.userGlobal),r=[{from:Qe.join(t,"config.json"),to:e.userGlobal},{from:Qe.join(t,"config.example.jsonc"),to:Qe.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([Z(o),Z(s)]);if(i){if(a){u.info(`\u26A0 Skipped ${v(o)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await et.mkdir(Qe.dirname(s),{recursive:!0}),await et.rename(o,s),u.info(`\u2713 Renamed ${v(o)} \u2192 ${v(s)}`),n++}catch(c){u.info(`\u26A0 Skipped ${v(o)} \u2014 ${c.message}`)}}}n>0&&vt()},cS=rn.object({workspaceDir:rn.string().min(1),targets:rn.array(rn.string()).min(1)}).strict(),mg=async()=>{let e=en(),t=Qe.dirname(e),r=Qe.join(t,"vendor.config.ts"),[n,o]=await Promise.all([Z(r),Z(e)]);if(n){if(o){u.info(`\u26A0 Skipped ${v(r)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await et.stat(r),c=(await import(`${iS(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,p=cS.safeParse(d);if(!p.success){u.info(`\u26A0 Skipped ${v(r)} \u2014 invalid factory config: ${rn.prettifyError(p.error)}`);return}await et.mkdir(t,{recursive:!0}),await et.writeFile(e,`${JSON.stringify(p.data,null,2)}
358
+ `,"utf-8"),await et.rm(r,{force:!0}),l?u.info(`\u26A0 Migrated ${v(r)} \u2192 ${v(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${v(e)} directly to change them.`):u.info(`\u2713 Migrated ${v(r)} \u2192 ${v(e)}`)}catch(s){u.info(`\u26A0 Skipped ${v(r)} \u2014 ${s.message}`)}}},fg=async()=>{let e=await lS(),t=0;for(let r of e)if(await Z(r))try{let n=await Op(r);if(!n.changed)continue;u.info(`\u2713 Migrated ${v(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof $p?"changed while migrating":n.message;u.info(`\u26A0 Skipped ${v(r)} \u2014 ${o}`)}t>0&&vt()},lS=async()=>{try{let e=await H();return[e.main,e.userGlobal,e.userProject]}catch{return[jp()]}};var or="# -- infra-kit:begin --",$t="# -- infra-kit:end --",dS=[["# region infra-kit","# endregion infra-kit"]],uS="# infra-kit shell functions",nn=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},on="Run `source ~/.zshrc` or open a new terminal to activate.",pS={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},tt=async(e,t)=>{try{return await t()}catch(r){throw new nn(e,r)}},sl=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await tt("zshrc",()=>{r(mS())}),await tt("zshenv",()=>{r(fS())}),await tt("migrations",async()=>{await hS(),gS(),r(pS)}),await tt("user-config",()=>{r(vS())});let n=await tt("guidance",async()=>{let{entries:s,root:i}=await bS();return r(...s),i}),o=await tt("plugin-pointer",async()=>tg());return r(...PS(o,n)),await tt("worktrees",async()=>{r(...await $S(o))}),await tt("plugin-pointer",async()=>{await AS(o,r)}),await tt("mcp-proxies",async()=>{r(...await IS(o))}),await tt("project-config",async()=>{r(...await wS())}),r(...yS()),t};var mS=()=>{let e=fe.join(nl.homedir(),".zshrc"),t=ue.existsSync(e)?NS(ue.readFileSync(e,"utf-8")):"",r=$r({content:t,body:hg(),startMarker:or,endMarker:$t,placement:"append-end"});return ue.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},fS=()=>{let e=fe.join(nl.homedir(),".zshenv"),t=ue.existsSync(e)?ue.readFileSync(e,"utf-8"):"",r=$r({content:t,body:il(),startMarker:or,endMarker:$t});return ue.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},gS=()=>{ue.rmSync(fe.join(Hu(),"projects"),{recursive:!0,force:!0})},hS=async()=>{await ug(),await pg(),await fg(),await mg()},yS=()=>{let e=ol.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:on,level:"info"}),t},vS=()=>{let e=fe.join(nl.homedir(),".infra-kit"),t=fe.join(e,"infra-kit.json");return ue.mkdirSync(e,{recursive:!0}),ue.writeFileSync(fe.join(e,"infra-kit.example.jsonc"),Yc(),"utf-8"),ue.writeFileSync(fe.join(e,"vendor.example.jsonc"),Xc(),"utf-8"),ue.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ue.writeFileSync(t,`{}
359
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},wS=async()=>{if(ol.env.INFRA_KIT_NO_SEED)return[ni("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await H();if(!ue.existsSync(e.main))return[ni("skipped",`no project config at ${e.main}`)];let t=await Xr(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:Zr(t),level:"info"}]:[ni("unchanged","the user-project config was already present")]}catch(e){return u.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[ni("warned",e instanceof Error?e.message:String(e))]}},ni=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),kS=(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)} ${fe.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},bS=async()=>{let{skipped:e,root:t,version:r,written:n}=await rg();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:kS(t,r,n)}},RS=(e,t)=>{let r=fe.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"}},SS=(e,t)=>{let r=Ie;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?de: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 ${Ye} from ${fe.join(e,Ie)} \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 "${de}" key`:`no ${r}`})`,level:"info"}},PS=(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 ${q} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],ES=()=>[mc,it].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),xS=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${K.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${K.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"};return e.stale?[r,{step:"plugin-pointer",outcome:"manual",message:cs(e.updateCommand),level:"info"}]:[r]},TS=(e,t)=>e.status==="skipped-cli-stale"?xS(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${q} 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: ${jr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${q} (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"},...ES()]:[{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: ${it}`,level:"warn"}],gg={stale:!1},CS=async()=>{let e=An(),t=e===null?await Pa(ol.env):e.latestVersion;return t===null||!Ea(t,K.version)?gg:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??zu(t)}},$S=async e=>{if(e===null)return[];let r=`${await Le(e)}${ge}`,n=Object.values(Sr).filter(o=>!ue.existsSync(fe.join(r,o)));for(let o of Object.values(Sr))ue.mkdirSync(fe.join(r,o),{recursive:!0});return n.length===0?[{step:"worktrees",outcome:"unchanged",message:`Worktree directories already present at ${r}`,level:"info"}]:[{step:"worktrees",outcome:"written",message:`Created worktree directories at ${r} (${n.join(", ")})`,level:"info"}]},AS=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(RS(e,fc(fe.join(e,".claude","settings.json"))));let n=Gt({projectPath:e}).kind==="installed"?await CS():gg;t(...TS(cc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(SS(e,Gn(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: ${it}`,level:"warn"})}},OS=(e,t)=>{let r=fe.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},IS=async e=>{if(e===null)return[];if(!ue.existsSync(fe.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 M()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
360
+ `)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:OS(e,_s({projectRoot:e,proxies:t,write:!0}))},DS=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"),NS=e=>{let t=Pt(e,or,$t);if(t!==null)return t;for(let[a,c]of dS){let l=Pt(e,a,c);if(l!==null)return l}let r=e.indexOf(uS);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
361
+ `),s=0;for(;s<o.length&&DS(o[s]);)s++;let i=o.slice(s).join(`
360
362
  `);return n+(i?`
361
- ${i}`:"")},Lf=()=>{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(`
362
- `)},Bf=()=>`${Zt}
363
- ${Lf()}
364
- ${Tt}`,Vc=()=>["# 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(`
365
- `),Wc=()=>`${Zt}
366
- ${Vc()}
367
- ${Tt}`;import TR from"node:fs/promises";var ro=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await TR.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}}},no=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import $R from"node:fs";import AR from"node:os";import Vf from"node:path";import OR from"node:process";import{$ as CR}from"zx";var Qt=()=>CR({quiet:!0});var IR=()=>[Vf.join(AR.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],DR=async e=>{try{return(await Qt()`command -v ${e}`).stdout.trim()||null}catch{return null}},oo=()=>({runCommand:async e=>{let t=await Qt()`${e}`;return{stdout:`${t.stdout}
368
- ${t.stderr}`}},resolveBinPath:async e=>{let t=await DR(e);return t!==null?t:IR().map(r=>Vf.join(r,e)).find(r=>$R.existsSync(r))??null},realpath:me,platform:OR.platform});var Ct=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Qr=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,en=["darwin","linux"],Hs=e=>t=>ea(t,e)?"homebrew":"unknown",qs=(e,t)=>r=>r===null?null:t(e(r),r),Jc=e=>qs(Hs(e.kegName),t=>t==="homebrew"?Ct(["brew","upgrade",e.brewFormula]):null),Wf=e=>qo(e,"Homebrew")||qo(e,"homebrew")?"homebrew":"unknown",NR={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Qr,platforms:en,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Wf,updateFor:qs(Wf,e=>e==="homebrew"?Ct(["brew","update"]):null)},Uc={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Gf="https://awscli.amazonaws.com/v2/install.sh",Kf={steps:[["/bin/bash","-c",`curl -fsSL ${Gf} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},_R="/usr/local/aws-cli",MR=e=>yn(_R,e,me)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Gf} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Kf,Uf=e=>ea(e,Uc.kegName)?"homebrew":qo(e,"aws-cli")?"script":"unknown",jR={id:"aws",binName:"aws",...Uc,probeArgv:["aws","--version"],versionFrom:Qr,platforms:en,prerequisites:[],bootstrapInstall:Kf,identify:Uf,updateFor:qs(Uf,(e,t)=>e==="homebrew"?Ct(["brew","upgrade",Uc.brewFormula]):e==="script"?MR(t):null)},Js={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},FR={id:"git",binName:"git",...Js,probeArgv:["git","--version"],versionFrom:Qr,platforms:en,prerequisites:["brew"],bootstrapInstall:Ct(["brew","install",Js.brewInstallSpec]),identify:Hs(Js.kegName),updateFor:Jc(Js)},Gs={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},LR={id:"gh",binName:"gh",...Gs,probeArgv:["gh","--version"],versionFrom:Qr,platforms:en,prerequisites:["brew"],bootstrapInstall:Ct(["brew","install",Gs.brewInstallSpec]),identify:Hs(Gs.kegName),updateFor:Jc(Gs)},Ks={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},BR={id:"doppler",binName:"doppler",...Ks,probeArgv:["doppler","--version"],versionFrom:Qr,platforms:en,prerequisites:["brew"],bootstrapInstall:Ct(["brew","install","gnupg"],["brew","install",Ks.brewInstallSpec]),identify:Hs(Ks.kegName),updateFor:Jc(Ks)},so="portless",Jf=e=>bu(e,so)===null?"unknown":"npm",VR={id:"portless",binName:so,npmPackage:so,probeArgv:["portless","--version"],versionFrom:Qr,platforms:[...en,"win32"],prerequisites:[],bootstrapInstall:Ct(["npm","install","-g",so]),identify:Jf,updateFor:qs(Jf,e=>e==="npm"?Ct(["npm","install","-g",`${so}@latest`]):null)},Gc={brew:NR,git:FR,aws:jR,gh:LR,doppler:BR,portless:VR},er=Object.keys(Gc),Ie=e=>Gc[e],Kc=(e,t)=>e.platforms.includes(t),Hc=e=>{let t=[],r=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!r.has(o)){r.add(o);for(let i of Ie(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Hf=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),qf=async(e,t)=>{try{return await e(t)}catch{return null}},WR=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Yf=async(e,t)=>{if(!Kc(e,t.platform))return Hf(e.id);let r=await qf(t.runCommand,e.probeArgv),n=await WR(t,e.binName);if(r==null&&n==null)return Hf(e.id);let o=r??(n==null?null:await qf(t.runCommand,[n,...e.probeArgv.slice(1)]));return{id:e.id,present:!0,onPath:r!=null,binRealPath:n,version:o==null?null:e.versionFrom(o.stdout),manager:n==null?"unknown":e.identify(n)}},io=async(e,t)=>Promise.all(e.map(r=>Yf(Ie(r),t)));import{$ as qR}from"zx";import{z as zf}from"zod";var Xf=/^\d{4}-\d{2}-\d{2}$/,ao=e=>{if(!Xf.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},Zf=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,tn=class extends Error{constructor(t){super(Zf(t)),this.name="InvalidReleaseDateError"}},tr=e=>{let t=e.trim();if(!ao(t))throw new tn(t);return t},co=e=>{let t=e.trim();return t===""||ao(t)?!0:Zf(t)},qc=zf.string().refine(ao,{message:"Expected a calendar date in yyyy-mm-dd form."}),Yc=zf.string().refine(e=>e===""||ao(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var $t=e=>e.slice(1).split(".").map(Number),rn=e=>[...e].sort((t,r)=>{let[n,o,s]=$t(t),[i,a,c]=$t(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var eg="next",UR=/^v?(\d+)\.(\d+)\.(\d+)$/,JR=e=>e.replace(/^.*release\//,""),zc=e=>{let t=JR(e.trim()),r=UR.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Qf=e=>`${e[0]}.${e[1]}.${e[2]}`,Xc=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=zc(o);if(!s)continue;let i=Qf(s);n.has(i)||(n.add(i),r.push(s))}return rn(r.map(o=>Qf(o))).map(o=>$t(`v${o}`))},rr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Zc=(e,t)=>{if(e.length===0)throw new rr;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},nn=(e,t)=>{try{return Zc(e,t)}catch(r){if(r instanceof rr)return null;throw r}},Qc=e=>e.trim().toLowerCase()===eg,zs=e=>Qc(e)||zc(e)!==null?{version:e}:{name:e},GR=e=>e==="regular"||e==="hotfix",tg=e=>"name"in e,KR=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:tr(n)}},el=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=KR(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!GR(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return Ys({...zs(n),type:s},{description:i,releaseDate:o})},tl=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},Ys=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},HR=e=>{let t=e.name.trim();return Qo(t),Ys({id:{kind:"name",name:t,raw:t},type:e.type},e)},rl=(e,t)=>{let r=[...t];return e.map(n=>{if(tg(n))return HR(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Qc(o)){let a=Zc(r,n.type);return r.push($t(`v${a}`)),Ys({id:ye(a),type:n.type},n)}let s=zc(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),Ys({id:ye(i),type:n.type},n)})},nl=e=>e.some(t=>!tg(t)&&Qc(t.version));var YR=e=>e.split(`
369
- `).map(t=>{let r=t.indexOf(" ");return r===-1?null:J(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),zR=async()=>{let e=await qR({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return YR(e.stdout)},XR=async()=>{let e=await at();return e?(await Br(e)).map(r=>r.name):[]},lo=async()=>{let[e,t]=await Promise.allSettled([zR(),XR()]);return e.status==="rejected"&&u.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&u.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Xc({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import ZR from"node:fs";import QR from"node:path";var ol=[".claude/settings.json",".claude/settings.local.json"],eS=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],tS=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),rS=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},nS=(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(tS).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},oS=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},sS=()=>nr.filter(e=>e.mutating),iS=e=>{let t=rS(e);return t===null?[]:sS().filter(r=>eS.some(n=>oS(r).some(o=>nS(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},aS=(e,t)=>{let r;try{r=ZR.readFileSync(QR.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}},rg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of ol){let n=aS(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=iS(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var cS=e=>e.every(t=>t.status!=="fail"),lS=["brew","git","gh","doppler","aws"],dS=async e=>{let t=await io(lS,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},lt=async(e,t,r,n)=>{try{return await Qt()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},uS=async()=>{let e="orca installed",t=await Rr();return t==="absent"?{name:e,status:"fail",message:"orca is not on PATH. Install with: brew install --cask stablyai/orca/orca, then register the CLI in Orca \u2192 Settings \u2192 Experimental \u2192 CLI"}:t==="unreachable"?{name:e,status:"warn",message:"orca is installed but the app is not running \u2014 start it with: orca open"}:{name:e,status:"pass",message:"Installed: orca (app running, runtime reachable)"}},pg=(e,t,r,n)=>{let o=ie.join(al.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(Zt),c=i.indexOf(Tt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Tt.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`}},pS=()=>pg("zshrc init block",".zshrc","shell",Bf()),mS=()=>pg("zshenv session block",".zshenv","session-env",Wc()),fS=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await E(),r=ie.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}`}}},gS=async()=>{try{return vt(),{config:await M(),error:null}}catch(e){return{config:null,error:e}}},hS=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)"}},yS=384,sl=448,vS=e=>e.length===0?"no envs declared":e.map(t=>{let r=t.source===null?"no token":`token (${t.source})`;return`${t.env}: ${r}`}).join(", "),wS=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}}})),kS=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Bt,o=t.resolveToken??Tp;if(!e.config)return{name:r,status:"skip",message:"infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await wS(await us(),o);return{name:r,status:"pass",message:vS(s)}},bS=()=>Fe.env[Vt]||void 0,RS=async(e={})=>{let t="tokens.json present",r=e.readStore??Bt,n=e.storePath??Lt;if((e.readEnvToken??bS)())return{name:t,status:"skip",message:`${Vt} is set; that channel takes precedence over the store`};let s;try{s=v(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${Vt} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},uo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},SS=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Lt,o=t.statPath??PS,s=t.chmodPath??H.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(uo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=ie.dirname(i),c=ie.dirname(a),l=ie.dirname(c),p=[{target:l,expected:sl,actual:uo(l,o)},{target:c,expected:sl,actual:uo(c,o)},{target:a,expected:sl,actual:uo(a,o)},{target:i,expected:yS,actual:uo(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(g=>`${v(g.target)} is ${ng(g.actual)}, expected ${ng(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of p)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},ng=e=>`0${e.toString(8).padStart(3,"0")}`,PS=e=>{try{return H.statSync(e)}catch{return null}},ES=async()=>{let e="user override path";try{let t=await ee(),r=H.existsSync(t.userProject),n=await ro(t.userProject,r),o=r?no(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${v(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},xS=async()=>{let e="legacy user-global config",t;try{t=await ee()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ie.join(ie.dirname(t.userGlobal),"config.json");return H.existsSync(r)?H.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${v(r)} \u2014 ${v(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${v(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},TS={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},CS=async e=>{let t=TS[e];try{return await Qt()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},$S=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=yt(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=>CS(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("; ")}},og=/^\d+\.\d+\.\d+$/,AS=(e,t)=>e===t||!og.test(e)||!og.test(t)?!1:rn([`v${e}`,`v${t}`])[0]===`v${e}`,OS=async(e,t)=>{let r;try{r=await ke(e)}catch{return[]}let n=[];for(let o of r){let s=Gt(Kt(ie.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&AS(s.version,t)&&n.push(s.version)}return n},IS=async(e,t)=>{let r=await OS(e,t);if(r.length===0)return"";let n=rn(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`},DS=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await ee()).main}catch{return e}if(!H.existsSync(t))return e;let r=ie.dirname(t),n=ie.join(r,"CLAUDE.md"),o=H.existsSync(n)?H.readFileSync(n,"utf-8"):"",s=Ge(o,$e,Ke),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await IS(r,G.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},NS=async()=>{try{let e=(await ee()).main;return H.existsSync(e)?ie.dirname(e):null}catch{return null}},_S=e=>{let t=dp();return t===null||!Rn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Ir}`},MS=e=>{let t=e.kind==="installed"?is(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 ${K} version ${t}${_S(t)}`}},sg=3,ig=(e,t)=>me(e)===me(t),jS=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(ig(e.projectDir,e.gitRoot))return"";let r=yn(e.gitRoot,me(e.projectDir),me)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${v(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return ig(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${v(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},FS=(e,t)=>{let r="plugin installed",n=jS(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${K} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${K} is not installed. Run: ${st}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-sg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,sg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${K} is installed for ${a} only, not this project. Run: ${st}${n}`}},LS=()=>lt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),on="claude in chrome",BS="com.anthropic.claude_code_browser_extension",Xs="run `/chrome` inside Claude Code to set up Claude in Chrome",VS={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},WS=e=>{try{return H.accessSync(e,H.constants.X_OK),!0}catch{return!1}},US=e=>{try{return JSON.parse(e)}catch{return null}},JS=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,GS=(e={})=>{let t=e.platform??Fe.platform,r=e.home??al.homedir(),n=e.readText??il,o=e.isExecutable??WS,s=VS[t];if(s===void 0)return{name:on,status:"skip",message:`no Chrome native host location known for ${t}`};let i=ie.join(r,...s,`${BS}.json`),a=n(i);if(a===null)return{name:on,status:"warn",message:`Chrome native host not registered \u2014 ${Xs}`};let c=se.object({path:se.string().min(1)}).safeParse(US(a));if(!c.success)return{name:on,status:"fail",message:`${v(i)} has no host path \u2014 ${Xs} again`};let l=c.data.path;if(!o(l))return{name:on,status:"fail",message:`Chrome native host ${v(l)} is missing or not executable \u2014 ${Xs} again`};let d=JS.exec(n(l)??"")?.groups?.target;return d!==void 0&&!o(d)?{name:on,status:"fail",message:`Chrome native host runs ${v(d)}, which no longer exists \u2014 ${Xs} again`}:{name:on,status:"pass",message:`Native host registered (${v(l)}); /infra-kit:doctor checks the live connection`}},KS=(e,...t)=>{try{return JSON.parse(H.readFileSync(ie.join(e,...t),"utf-8"))}catch{return null}},HS=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=is(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=KS(r,Ae),o=n!==null&&typeof n=="object"?n[qe]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},ag=e=>`Plugin ${K} ${e===null?"(version unreadable)":e}`,qS=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: ${st}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${ag(e.version)} still carries an MCP server in its ${Ae}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Ir}), then restart Claude Code`}}return{name:t,status:"pass",message:`${ag(e.version)} is skills-only \u2014 no ${Ae}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},YS=(e,t)=>{let r=Ft(e===null?{}:{projectPath:e}),n=bn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ae} is known to Claude Code`:`Marketplace ${ae} is not registered. Run: claude plugin marketplace add ${wt}`},FS(r,t),MS(r),qS(HS(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${G.version}`}]},zS=({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(", ")},XS=e=>{let t="Agent mode",r=Zo(e),n=zS(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})`}},cg=4,ZS=e=>{let t=e.slice(0,cg).join(", "),r=e.length-cg;return r>0?`${t} +${r} more`:t},QS=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=rg(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"} (${ZS(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 ${ol.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`}},eP=(e,t)=>{let r=Math.floor((t-Date.parse(e))/36e5);return Number.isNaN(r)?"age unknown":r>=24?`${Math.floor(r/24)}d old`:`${Math.max(r,0)}h old`},tP=async(e,t=Date.now())=>{let r="merge-dev resolutions";if(e===null)return{name:r,status:"skip",message:"no git root"};let n;try{n=await mf(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?v(i.worktreePath):"worktree missing";return`${i.branch} (${eP(i.createdAt,t)}, ${a})`}),s=n.map(i=>i.branch).join(",");return{name:r,status:"warn",message:`${n.length} unfinished merge-dev hand-off${n.length===1?"":"s"}: ${o.join("; ")} \u2014 finish with: infra-kit release merge-dev --continue --versions ${s}, or drop with --abort`}},mg=e=>ta(["trust"],{bin:e}),rP=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),lg="ERR_TLS_CERT_ALTNAME_INVALID",fg=()=>`portless serving TLS on :${ht}`,nP=async(e,t,r)=>{let n=fg();return await e(ht,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${ht}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${ht}. Install it once (needs root): \`${ft(t,r)}\`.`}},oP=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(ht,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(lg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${lg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>rP.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${mg(n)}\`, or reinstall: \`${ft(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},sP=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${v(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${mg(r)}\` (no sudo needed).`}},iP=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 \`${ta(["alias","--remove","<name>"],{bin:r})}\`.`}},At="portless service target",mo=e=>({name:At,status:"warn",message:e}),gg=e=>e==="darwin"?Cu:e==="linux"?$u:null,aP=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Tu}`:`sudo systemctl restart ${Au}`,cP="/bin/ps",lP=e=>{try{let t=ug(cP,["-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}},il=e=>{try{return H.readFileSync(e,"utf-8")}catch{return null}},dP=e=>{try{return H.statSync(e).mtime}catch{return null}},uP=2e3,pP=e=>{try{let t=ug(e,["-p","process.version"],{encoding:"utf-8",timeout:uP}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},mP=(e,t)=>({platform:e.platform??Fe.platform,readServiceFile:e.readServiceFile??il,readFile:e.readFile??il,exists:e.exists??H.existsSync,realpath:e.realpath??me,mtime:e.mtime??dP,execPath:e.execPath??Fe.execPath,home:e.home??al.homedir(),cwd:e.cwd??Fe.cwd(),repoRoot:e.repoRoot??eo,stateDir:(e.stateDir??Iu)(),processStartTime:e.processStartTime??lP,version:e.version??Fe.version,arch:e.arch??Fe.arch,nodeVersionOf:e.nodeVersionOf??pP,isGlobal:e.isGlobal??Xo().node.isGlobal,nodeFs:e.nodeFs??H,stableNode:null,stableNodeSidecar:null,bin:t}),fo="portless node",or="~/.infra-kit/node",po=e=>({row:{name:fo,status:"fail",message:e},stableNode:null,sidecar:null}),dg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},fP=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,gP=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,hP=e=>{let t=ju(e.home),r=dg(e.nodeFs.lstatSync,t);if(r===void 0)return po(`${or} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return po(`${or} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Fu(e.home,e.nodeFs);if(n===null)return po(`${or} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=dg(e.nodeFs.statSync,e.execPath),s=n.version===e.version&&n.arch===e.arch&&n.platform===e.platform,i=o!==void 0&&r.ino===o.ino&&r.dev===o.dev,a=n.method==="copy"&&o!==void 0&&n.sourceSize===o.size;if(!s||!(i||a))return po(`${or} is Node ${n.version} (${n.method} of ${v(n.source)}); infra-kit runs ${e.version} at ${v(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!gP(c,e))return po(`${or} does not run as Node ${e.version} (${fP(c)}). Re-run through the current Node: \`${ft(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:fo,status:"pass",message:`${or} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},yP=e=>{if(gg(e.platform)===null)return{row:{name:fo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=hP(e);return e.isGlobal()?t:{...t,row:{name:fo,status:"skip",message:`not a global install; the global infra-kit keeps ${or} current`}}},hg=(e,t)=>{let r=mP(e,t),n=yP(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},vP=(e,t)=>{let r=t.readFile(ie.join(e,"package.json"));try{let n=r===null?null:se.object({version:se.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},wP=e=>{let t=Number.parseInt(e.readFile(ie.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},kP=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},bP=(e,t,r)=>{let n=wP(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(kP(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ie.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},RP=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:yn(await t.repoRoot()??r,e,t.realpath)},sr=e=>({state:"drifted",row:e}),SP=async(e,t,r)=>{let n=ft(r.bin,r);if(!r.exists(e))return sr({name:At,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=ie.join(ra(r.home),"dist","cli.js");if(t!==o)return sr(mo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(zo(r.home,r.exists)===null)return sr({name:At,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(ra(r.home));if(await RP(s,r))return sr({name:At,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=PP(e,n,r);if(i!==null)return i;let a=vP(s,r),c=bP(s,a,r);return c!==null?{state:"converged",row:mo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${aP(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:At,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},PP=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:sr(mo(`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:sr(mo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),yg=async e=>{let t=gg(e.platform);if(t===null)return{state:"absent",row:{name:At,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:At,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Nm(e.platform,r)??[];return n===void 0||o===void 0?sr(mo(`could not parse ${t} \u2014 re-run \`${ft(e.bin,e)}\` to rewrite it.`)):SP(n,o,e)},vg=async(e,t)=>{let{seams:r}=hg(e,t);return{state:(await yg(r)).state,stableNode:r.stableNode}},EP=()=>[fo,At,fg(),"portless CA chain valid","portless CA trusted","portless routes"],xP=async(e={})=>{let t=e.resolveBin??xu,r=e.isProxyServing??Ou,n=e.handshake??_u,o=e.caTrusted??Nu,s=e.routes??wn,i=e.isListening??vn,a=(e.caPath??Du)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...EP().map(R=>({name:R,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:p}=hg(e,c),m=s(),g=await nP(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await oP(n,m,a,c,d);return[l,p,(await yg(d)).row,g,y,sP(o(),a,c),await iP(m,i,c)]},TP=async(e={})=>{let t="portless routes",r=e.routes??wn,n=e.isListening??vn,o=e.devSessionRunning??$m,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=Cm(i,o());if(c.length>0)return{name:t,status:"fail",message:`${c.length} route(s) look stale (${c.join(", ")}), but a dev session is running \u2014 a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. Stop dev and re-run \`infra-kit doctor --fix\`.`};if(a.length===0)return{name:t,status:"pass",message:`${s.length} portless route(s), all live`};let l=e.removeAlias??Mu().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Zs=async(e={})=>{let t=await gS(),r=dS(e.probeDeps??oo()),n=async(m,g)=>{let[y,R]=await Promise.all([g,r]),w=R.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",lt("brew installed",Ie("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",lt("git installed",Ie("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",lt("gh installed",Ie("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),lt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",lt("doppler installed",Ie("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",lt("aws installed",Ie("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),lt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),lt("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"),uS(),Promise.resolve(pS()),Promise.resolve(mS()),fS(),Promise.resolve(hS(t)),RS(),kS(t),SS(e.fix??!1),ES(),xS(),$S(t)]),s=await xP(e.portlessDeps);if(e.fix){let m=await TP(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await NS(),a=await eo(),c={projectDir:Fe.env.CLAUDE_PROJECT_DIR||null,cwd:Fe.cwd(),gitRoot:a},l=[await LS(),...YS(i,c),GS(),XS({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:I.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:QS(a)],d=[...o,await tP(a),...s,...await DS(),...l],p={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:dc.has(m.name),detail:m.detail})),allPassed:cS(d),cliVersion:G.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},cl=S({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:se.array(se.object({name:se.string().describe("Name of the check"),status:se.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:se.string().describe("Details about the check result"),fixable:se.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:se.object({manager:se.string().describe("Which package manager owns this install, read from its resolved path"),version:se.string().nullable().describe("The version the tool reported, or null"),present:se.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:se.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:se.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:se.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Zs()});import{E2E_MODE_ENV as _P}from"@slip-stream-kit/config/internal";import{spawn as MP}from"node:child_process";import jP from"node:fs";import FP from"node:path";import Pg from"node:process";import{z as _}from"zod";import{describeProxyRoutes as CP,loadDev as $P,readCloudOrigin as AP,readLocalContext as bg,slugifyHostLabel as wg}from"@slip-stream-kit/config/internal";import kg from"node:fs";import ir from"node:path";import Qs from"node:process";import{z as ll}from"zod";var OP=async e=>{let t=ir.join(e,"apps"),r=kg.existsSync(t)?kg.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=ir.join(t,o,"tests"),i=await Pr(s);i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},IP=(e,t)=>{let[r,n]=ir.relative(e,t).split(ir.sep);return r==="apps"&&n?n:void 0},DP=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(IP(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new x({status:"argument_required",argument:a,choices:ll.toJSONSchema(ll.object({app:ll.enum(i)})),agentMode:I.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},NP=async(e,t,r)=>Promise.all(e.map(async n=>{if(n.source==="cloud")return{...n,live:null};let o=t.get(n.packageName)??0,s=o>0&&await r({tag:`${n.packageName}`,port:o,kind:"api"})==="ok";return{...n,live:s}})),dl=async(e,t={})=>{let r=t.cwd??Qs.cwd(),n=t.projectRoot??await E(),o=(t.env??Qs.env)[hr]||null,s=t.healthProbe??pa,i=DP(await OP(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),d=ir.join(n,"apps",c,l),p=(await Wt(d)).name,m=(await Pr(d))?.deployedUrlEnv??null;if(!p)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${ir.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${d} has no package.json name`});let g=jp(d),y=`${g}.${wg(p)}.localhost`,R=`https://${y}`,w=0;if(l==="ui")w=(t.listRoutes??wn)().find(D=>D.name===y||D.name===`${g}.${wg(p)}`)?.port??0;else{let D=bg(d).info.get(p);w=D?.port??0,R=D?.origin??R}let $=w>0&&await s({tag:a,port:w,kind:l})==="ok";return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:d,packageName:p,deployedUrlEnv:m,release:g,env:o,localUrl:R,served:$}},Rg=e=>{let{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,localUrl:c}=e;return{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,localUrl:c}},ul=async(e,t={})=>{let r=t.healthProbe??pa,n=bg(e.targetDir),o=e.kind==="ui"?await $P(e.targetDir):void 0,s=o?.proxy?CP({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:AP(e.deployedUrlEnv??void 0,t.env??Qs.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Rg(e),mode:"local",baseUrl:e.localUrl,routes:await NP(s,i,r)}},pl=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${ir.join(e.targetDir,"infra-kit.config.ts")} and keep the URL per environment in Doppler`,stderrExcerpt:`${o} names no variable holding its deployed URL`});let s=(t.env??Qs.env)[n];if(!r||!s)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${hr}, and ${s?hr:n} is not set`});return{...Rg(e),mode:"cloud",baseUrl:s,routes:[]}};var LP=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],BP=e=>LP.some(t=>{try{return jP.readFileSync(FP.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),Eg=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,VP=(e,t)=>{let r=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl}`];e.mode==="cloud"?r.push(` deployed app at env "${e.env}"`):t?r.push(` dev server for ${e.target} on release "${e.release}", already running`):r.push(` nothing serves ${e.target} yet; the Playwright config starts it and stops it after the run`);for(let n of e.routes){let o="";n.live!==null&&(o=n.live?" \u2014 live":" \u2014 NOT responding"),r.push(` ${n.path.padEnd(24)} ${n.source.padEnd(5)} ${n.target??"(unresolved)"}${o}`)}return r.join(`
370
- `)},WP=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},UP=async(e,t)=>{if(e.env===null||!Mp(e.env))return;let r=await(t.protectedEnvAccess??Ue)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new x({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},JP=async(e,t)=>{if(e.served){let d=await ul(e,t);return WP(d),d}if(!BP(e.testsDir))throw new f(void 0,{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${Eg(e)}\`), or wire \`infraKitE2e()\` from @slip-stream-kit/config/playwright into its playwright.config.ts`,stderrExcerpt:`nothing serves ${e.target} and ${e.testsDir}'s Playwright config does not start it`});let{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,localUrl:l}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,localUrl:l,mode:"local",baseUrl:l,routes:[]}},GP=(e,t)=>new Promise((r,n)=>{let o=MP("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Pg.env,[_P]:e.mode},stdio:["inherit",rt.enabled||ge()?2:"inherit","inherit"]});o.once("error",n),o.once("close",s=>{r(s??1)})}),ei=async(e,t={})=>{let r=await dl(e.app,t),n=e.cloud?pl(r,t):await JP(r,t);u.info(VP(n,r.served)),n.mode==="cloud"&&await UP(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?Eg(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Sg({...o,ran:!1,exitCode:null});n.mode==="cloud"&&await B(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=await(t.runPlaywright??GP)(n,e.playwrightArgs??[]);return s!==0&&(Pg.exitCode=s),Sg({...o,ran:!0,exitCode:s})},Sg=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),KP={app:_.string(),testsDir:_.string(),target:_.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:_.string(),mode:_.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:_.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:_.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:_.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:_.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),localUrl:_.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:_.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:_.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:_.array(_.object({path:_.string(),packageName:_.string(),source:_.enum(["local","cloud"]),target:_.string().nullable(),live:_.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:_.array(_.string()),ran:_.boolean().describe("False for --dry-run."),exitCode:_.number().nullable().describe("Playwright\u2019s exit code; null when it did not run.")},ml=S({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:_.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:_.boolean().optional(),yes:_.boolean().optional(),cloud:_.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree.")},outputSchema:KP,handler:e=>ei(e)});import fl from"node:fs";import xg from"node:path";import{z as go}from"zod";var HP=e=>[...e.map(t=>`unset ${t}`),`unset ${hr}`,`unset ${Jo}`,`unset ${Go}`,`unset ${hu}`,`unset ${Ko}`],ti=async()=>{let e=yr(),t=xg.join(e,gr);if(!fl.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Ho(t),n=HP(r),o=xg.resolve(e,Uo);fl.mkdirSync(e,{recursive:!0,mode:448}),ku(o,`${n.join(`
363
+ ${i}`:"")},hg=()=>{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(`
364
+ `)},yg=()=>`${or}
365
+ ${hg()}
366
+ ${$t}`,il=()=>["# Inherit this terminal's infra-kit session env into every zsh it spawns, interactive or not.","# A fresh terminal has no session yet (it is minted in .zshrc, after this file) and skips.","# Only the canonical 8-hex id .zshrc mints is honoured. Load wins a tie with clear.","# A load applies only at or under a directory its env-load.root names (no file: anywhere).","# Prints nothing of its own.",'if [[ -n "${INFRA_KIT_SESSION:-}" ]]; then'," () {"," emulate -L zsh -o extendedglob",' [[ "${INFRA_KIT_SESSION:-}" == [0-9a-f](#c8) ]] || return',' local _ik_dir="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit/$INFRA_KIT_SESSION"',' local _ik_load="$_ik_dir/env-load.sh" _ik_clear="$_ik_dir/env-clear.sh"',' if [[ -r "$_ik_load" && ! "$_ik_clear" -nt "$_ik_load" ]]; then',' local _ik_roots="$_ik_dir/env-load.root" _ik_pwd=${PWD:A} _ik_root',' if [[ -r "$_ik_roots" ]]; then',' for _ik_root in "${(@f)$(<$_ik_roots)}"; do',' [[ -n "$_ik_root" && ( "$_ik_pwd" == "$_ik_root" || "$_ik_pwd" == "$_ik_root"/* ) ]] && break'," _ik_root="," done",' [[ -n "$_ik_root" ]] || return'," fi",' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
367
+ `),al=()=>`${or}
368
+ ${il()}
369
+ ${$t}`;import _S from"node:fs/promises";var mo=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await _S.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}}},fo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import jS from"node:fs";import FS from"node:os";import vg from"node:path";import LS from"node:process";import{$ as MS}from"zx";var sr=()=>MS({quiet:!0});var BS=()=>[vg.join(FS.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],WS=async e=>{try{return(await sr()`command -v ${e}`).stdout.trim()||null}catch{return null}},go=()=>({runCommand:async e=>{let t=await sr()`${e}`;return{stdout:`${t.stdout}
370
+ ${t.stderr}`}},resolveBinPath:async e=>{let t=await WS(e);return t!==null?t:BS().map(r=>vg.join(r,e)).find(r=>jS.existsSync(r))??null},realpath:he,platform:LS.platform});var At=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),sn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,an=["darwin","linux"],ai=e=>t=>fa(t,e)?"homebrew":"unknown",ci=(e,t)=>r=>r===null?null:t(e(r),r),ll=e=>ci(ai(e.kegName),t=>t==="homebrew"?At(["brew","upgrade",e.brewFormula]):null),wg=e=>as(e,"Homebrew")||as(e,"homebrew")?"homebrew":"unknown",VS={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:sn,platforms:an,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:wg,updateFor:ci(wg,e=>e==="homebrew"?At(["brew","update"]):null)},cl={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Rg="https://awscli.amazonaws.com/v2/install.sh",Sg={steps:[["/bin/bash","-c",`curl -fsSL ${Rg} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},US="/usr/local/aws-cli",JS=e=>Sn(US,e,he)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Rg} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Sg,kg=e=>fa(e,cl.kegName)?"homebrew":as(e,"aws-cli")?"script":"unknown",GS={id:"aws",binName:"aws",...cl,probeArgv:["aws","--version"],versionFrom:sn,platforms:an,prerequisites:[],bootstrapInstall:Sg,identify:kg,updateFor:ci(kg,(e,t)=>e==="homebrew"?At(["brew","upgrade",cl.brewFormula]):e==="script"?JS(t):null)},oi={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},KS={id:"git",binName:"git",...oi,probeArgv:["git","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:At(["brew","install",oi.brewInstallSpec]),identify:ai(oi.kegName),updateFor:ll(oi)},si={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},HS={id:"gh",binName:"gh",...si,probeArgv:["gh","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:At(["brew","install",si.brewInstallSpec]),identify:ai(si.kegName),updateFor:ll(si)},ii={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},qS={id:"doppler",binName:"doppler",...ii,probeArgv:["doppler","--version"],versionFrom:sn,platforms:an,prerequisites:["brew"],bootstrapInstall:At(["brew","install","gnupg"],["brew","install",ii.brewInstallSpec]),identify:ai(ii.kegName),updateFor:ll(ii)},ho="portless",bg=e=>Yu(e,ho)===null?"unknown":"npm",YS={id:"portless",binName:ho,npmPackage:ho,probeArgv:["portless","--version"],versionFrom:sn,platforms:[...an,"win32"],prerequisites:[],bootstrapInstall:At(["npm","install","-g",ho]),identify:bg,updateFor:ci(bg,e=>e==="npm"?At(["npm","install","-g",`${ho}@latest`]):null)},dl={brew:VS,git:KS,aws:GS,gh:HS,doppler:qS,portless:YS},ir=Object.keys(dl),Ne=e=>dl[e],ul=(e,t)=>e.platforms.includes(t),pl=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 Ne(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Pg=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Eg=async(e,t)=>{try{return await e(t)}catch{return null}},zS=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},xg=async(e,t)=>{if(!ul(e,t.platform))return Pg(e.id);let r=await Eg(t.runCommand,e.probeArgv),n=await zS(t,e.binName);if(r==null&&n==null)return Pg(e.id);let o=r??(n==null?null:await Eg(t.runCommand,[n,...e.probeArgv.slice(1)]));return{id:e.id,present:!0,onPath:r!=null,binRealPath:n,version:o==null?null:e.versionFrom(o.stdout),manager:n==null?"unknown":e.identify(n)}},yo=async(e,t)=>Promise.all(e.map(r=>xg(Ne(r),t)));import{$ as rP}from"zx";import{z as Tg}from"zod";var Cg=/^\d{4}-\d{2}-\d{2}$/,vo=e=>{if(!Cg.test(e))return!1;let[t,r,n]=e.split("-").map(Number),o=new Date(Date.UTC(t,r-1,n));return o.getUTCFullYear()===t&&o.getUTCMonth()===r-1&&o.getUTCDate()===n},$g=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,cn=class extends Error{constructor(t){super($g(t)),this.name="InvalidReleaseDateError"}},ar=e=>{let t=e.trim();if(!vo(t))throw new cn(t);return t},wo=e=>{let t=e.trim();return t===""||vo(t)?!0:$g(t)},ml=Tg.string().refine(vo,{message:"Expected a calendar date in yyyy-mm-dd form."}),fl=Tg.string().refine(e=>e===""||vo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Ot=e=>e.slice(1).split(".").map(Number),ln=e=>[...e].sort((t,r)=>{let[n,o,s]=Ot(t),[i,a,c]=Ot(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var Og="next",XS=/^v?(\d+)\.(\d+)\.(\d+)$/,ZS=e=>e.replace(/^.*release\//,""),gl=e=>{let t=ZS(e.trim()),r=XS.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Ag=e=>`${e[0]}.${e[1]}.${e[2]}`,hl=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=gl(o);if(!s)continue;let i=Ag(s);n.has(i)||(n.add(i),r.push(s))}return ln(r.map(o=>Ag(o))).map(o=>Ot(`v${o}`))},cr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},yl=(e,t)=>{if(e.length===0)throw new cr;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},dn=(e,t)=>{try{return yl(e,t)}catch(r){if(r instanceof cr)return null;throw r}},vl=e=>e.trim().toLowerCase()===Og,di=e=>vl(e)||gl(e)!==null?{version:e}:{name:e},QS=e=>e==="regular"||e==="hotfix",Ig=e=>"name"in e,eP=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:ar(n)}},wl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=eP(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!QS(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return li({...di(n),type:s},{description:i,releaseDate:o})},kl=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},li=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},tP=e=>{let t=e.name.trim();return ps(t),li({id:{kind:"name",name:t,raw:t},type:e.type},e)},bl=(e,t)=>{let r=[...t];return e.map(n=>{if(Ig(n))return tP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(vl(o)){let a=yl(r,n.type);return r.push(Ot(`v${a}`)),li({id:pe(a),type:n.type},n)}let s=gl(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),li({id:pe(i),type:n.type},n)})},Rl=e=>e.some(t=>!Ig(t)&&vl(t.version));var nP=e=>e.split(`
371
+ `).map(t=>{let r=t.indexOf(" ");return r===-1?null:G(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),oP=async()=>{let e=await rP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return nP(e.stdout)},sP=async()=>{let e=await ct();return e?(await Kr(e)).map(r=>r.name):[]},ko=async()=>{let[e,t]=await Promise.allSettled([oP(),sP()]);return e.status==="rejected"&&u.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&u.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),hl({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import iP from"node:fs";import aP from"node:path";var Sl=[".claude/settings.json",".claude/settings.local.json"],cP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],lP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),dP=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},uP=(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(lP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},pP=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},mP=()=>lr.filter(e=>e.mutating),fP=e=>{let t=dP(e);return t===null?[]:mP().filter(r=>cP.some(n=>pP(r).some(o=>uP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},gP=(e,t)=>{let r;try{r=iP.readFileSync(aP.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}},Dg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Sl){let n=gP(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=fP(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var hP=e=>e.every(t=>t.status!=="fail"),yP=["brew","git","gh","doppler","aws"],vP=async e=>{let t=await yo(yP,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},dt=async(e,t,r,n)=>{try{return await sr()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},wP=async()=>{let e="orca installed",t=await xr();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)"}},Ug=(e,t,r,n)=>{let o=ce.join(xl.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!Y.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=Y.readFileSync(o,"utf-8"),a=i.indexOf(or),c=i.indexOf($t);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+$t.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},kP=()=>Ug("zshrc init block",".zshrc","shell",yg()),bP=()=>Ug("zshenv session block",".zshenv","session-env",al()),RP=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await T(),r=ce.join(t,"pnpm-workspace.yaml");if(!Y.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=Y.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}`}}},SP=async()=>{try{return vt(),{config:await M(),error:null}}catch(e){return{config:null,error:e}}},PP=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)"}},EP=384,Pl=448,xP=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(", "),TP=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}}})),CP=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Be,o=t.resolveToken??em;if(!e.config)return{name:r,status:"skip",message:"infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await TP(await Ps(),o);return{name:r,status:"pass",message:xP(s)}},$P=()=>We.env[Ht]||void 0,AP=async(e={})=>{let t="tokens.json present",r=e.readStore??Be,n=e.storePath??kt;if((e.readEnvToken??$P)())return{name:t,status:"skip",message:`${Ht} is set; that channel takes precedence over the store`};let s;try{s=v(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${Ht} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},bo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},OP=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??kt,o=t.statPath??IP,s=t.chmodPath??Y.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(bo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=ce.dirname(i),c=ce.dirname(a),l=ce.dirname(c),p=[{target:l,expected:Pl,actual:bo(l,o)},{target:c,expected:Pl,actual:bo(c,o)},{target:a,expected:Pl,actual:bo(a,o)},{target:i,expected:EP,actual:bo(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(g=>`${v(g.target)} is ${Ng(g.actual)}, expected ${Ng(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of p)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},Ng=e=>`0${e.toString(8).padStart(3,"0")}`,IP=e=>{try{return Y.statSync(e)}catch{return null}},DP=async()=>{let e="user override path";try{let t=await H(),r=Y.existsSync(t.userProject),n=await mo(t.userProject,r),o=r?fo(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${v(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},NP=async()=>{let e="legacy user-global config",t;try{t=await H()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ce.join(ce.dirname(t.userGlobal),"config.json");return Y.existsSync(r)?Y.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${v(r)} \u2014 ${v(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${v(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},_P={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},MP=async e=>{let t=_P[e];try{return await sr()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},jP=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=yt(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=>MP(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("; ")}},_g=/^\d+\.\d+\.\d+$/,FP=(e,t)=>e===t||!_g.test(e)||!_g.test(t)?!1:ln([`v${e}`,`v${t}`])[0]===`v${e}`,LP=async(e,t)=>{let r;try{r=await Se(e)}catch{return[]}let n=[];for(let o of r){let s=Xt(Zt(ce.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&FP(s.version,t)&&n.push(s.version)}return n},BP=async(e,t)=>{let r=await LP(e,t);if(r.length===0)return"";let n=ln(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`},WP=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await H()).main}catch{return e}if(!Y.existsSync(t))return e;let r=ce.dirname(t),n=ce.join(r,"CLAUDE.md"),o=Y.existsSync(n)?Y.readFileSync(n,"utf-8"):"",s=Ke(o,Oe,He),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await BP(r,K.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},VP=async()=>{try{let e=(await H()).main;return Y.existsSync(e)?ce.dirname(e):null}catch{return null}},UP=e=>{let t=Fp();return t===null||!$n(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${jr}`},JP=e=>{let t=e.kind==="installed"?ws(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 ${q} version ${t}${UP(t)}`}},Mg=3,jg=(e,t)=>he(e)===he(t),GP=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(jg(e.projectDir,e.gitRoot))return"";let r=Sn(e.gitRoot,he(e.projectDir),he)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${v(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return jg(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${v(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},KP=(e,t)=>{let r="plugin installed",n=GP(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${q} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${q} is not installed. Run: ${it}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-Mg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Mg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${q} is installed for ${a} only, not this project. Run: ${it}${n}`}},HP=()=>dt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),un="claude in chrome",qP="com.anthropic.claude_code_browser_extension",ui="run `/chrome` inside Claude Code to set up Claude in Chrome",YP={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},zP=e=>{try{return Y.accessSync(e,Y.constants.X_OK),!0}catch{return!1}},XP=e=>{try{return JSON.parse(e)}catch{return null}},ZP=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,QP=(e={})=>{let t=e.platform??We.platform,r=e.home??xl.homedir(),n=e.readText??El,o=e.isExecutable??zP,s=YP[t];if(s===void 0)return{name:un,status:"skip",message:`no Chrome native host location known for ${t}`};let i=ce.join(r,...s,`${qP}.json`),a=n(i);if(a===null)return{name:un,status:"warn",message:`Chrome native host not registered \u2014 ${ui}`};let c=ae.object({path:ae.string().min(1)}).safeParse(XP(a));if(!c.success)return{name:un,status:"fail",message:`${v(i)} has no host path \u2014 ${ui} again`};let l=c.data.path;if(!o(l))return{name:un,status:"fail",message:`Chrome native host ${v(l)} is missing or not executable \u2014 ${ui} again`};let d=ZP.exec(n(l)??"")?.groups?.target;return d!==void 0&&!o(d)?{name:un,status:"fail",message:`Chrome native host runs ${v(d)}, which no longer exists \u2014 ${ui} again`}:{name:un,status:"pass",message:`Native host registered (${v(l)}); /infra-kit:doctor checks the live connection`}},eE=(e,...t)=>{try{return JSON.parse(Y.readFileSync(ce.join(e,...t),"utf-8"))}catch{return null}},tE=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ws(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=eE(r,Ie),o=n!==null&&typeof n=="object"?n[Ye]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Fg=e=>`Plugin ${q} ${e===null?"(version unreadable)":e}`,rE=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: ${it}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Fg(e.version)} still carries an MCP server in its ${Ie}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${jr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Fg(e.version)} is skills-only \u2014 no ${Ie}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},nE=(e,t)=>{let r=Gt(e===null?{}:{projectPath:e}),n=Cn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${de} is known to Claude Code`:`Marketplace ${de} is not registered. Run: claude plugin marketplace add ${wt}`},KP(r,t),JP(r),rE(tE(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${K.version}`}]},oE=({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(", ")},sE=e=>{let t="Agent mode",r=us(e),n=oE(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})`}},Lg=4,iE=e=>{let t=e.slice(0,Lg).join(", "),r=e.length-Lg;return r>0?`${t} +${r} more`:t},aE=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Dg(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"} (${iE(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 ${Sl.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`}},cE=(e,t)=>{let r=Math.floor((t-Date.parse(e))/36e5);return Number.isNaN(r)?"age unknown":r>=24?`${Math.floor(r/24)}d old`:`${Math.max(r,0)}h old`},lE=async(e,t=Date.now())=>{let r="merge-dev resolutions";if(e===null)return{name:r,status:"skip",message:"no git root"};let n;try{n=await Jf(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?v(i.worktreePath):"worktree missing";return`${i.branch} (${cE(i.createdAt,t)}, ${a})`}),s=n.map(i=>i.branch).join(",");return{name:r,status:"warn",message:`${n.length} unfinished merge-dev hand-off${n.length===1?"":"s"}: ${o.join("; ")} \u2014 finish with: infra-kit release merge-dev --continue --versions ${s}, or drop with --abort`}},Jg=e=>ga(["trust"],{bin:e}),dE=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Bg="ERR_TLS_CERT_ALTNAME_INVALID",Gg=()=>`portless serving TLS on :${ht}`,uE=async(e,t,r)=>{let n=Gg();return await e(ht,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${ht}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${ht}. Install it once (needs root): \`${ft(t,r)}\`.`}},pE=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(ht,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(Bg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Bg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>dE.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${Jg(n)}\`, or reinstall: \`${ft(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},mE=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${v(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Jg(r)}\` (no sudo needed).`}},fE=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 \`${ga(["alias","--remove","<name>"],{bin:r})}\`.`}},It="portless service target",So=e=>({name:It,status:"warn",message:e}),Kg=e=>e==="darwin"?rp:e==="linux"?np:null,gE=e=>e==="darwin"?`sudo launchctl kickstart -k system/${tp}`:`sudo systemctl restart ${op}`,hE="/bin/ps",yE=e=>{try{let t=Vg(hE,["-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}},El=e=>{try{return Y.readFileSync(e,"utf-8")}catch{return null}},vE=e=>{try{return Y.statSync(e).mtime}catch{return null}},wE=2e3,kE=e=>{try{let t=Vg(e,["-p","process.version"],{encoding:"utf-8",timeout:wE}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},bE=(e,t)=>({platform:e.platform??We.platform,readServiceFile:e.readServiceFile??El,readFile:e.readFile??El,exists:e.exists??Y.existsSync,realpath:e.realpath??he,mtime:e.mtime??vE,execPath:e.execPath??We.execPath,home:e.home??xl.homedir(),cwd:e.cwd??We.cwd(),repoRoot:e.repoRoot??uo,stateDir:(e.stateDir??ip)(),processStartTime:e.processStartTime??yE,version:e.version??We.version,arch:e.arch??We.arch,nodeVersionOf:e.nodeVersionOf??kE,isGlobal:e.isGlobal??ds().node.isGlobal,nodeFs:e.nodeFs??Y,stableNode:null,stableNodeSidecar:null,bin:t}),Po="portless node",dr="~/.infra-kit/node",Ro=e=>({row:{name:Po,status:"fail",message:e},stableNode:null,sidecar:null}),Wg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},RE=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,SE=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,PE=e=>{let t=up(e.home),r=Wg(e.nodeFs.lstatSync,t);if(r===void 0)return Ro(`${dr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Ro(`${dr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=pp(e.home,e.nodeFs);if(n===null)return Ro(`${dr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Wg(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 Ro(`${dr} is Node ${n.version} (${n.method} of ${v(n.source)}); infra-kit runs ${e.version} at ${v(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!SE(c,e))return Ro(`${dr} does not run as Node ${e.version} (${RE(c)}). Re-run through the current Node: \`${ft(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Po,status:"pass",message:`${dr} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},EE=e=>{if(Kg(e.platform)===null)return{row:{name:Po,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=PE(e);return e.isGlobal()?t:{...t,row:{name:Po,status:"skip",message:`not a global install; the global infra-kit keeps ${dr} current`}}},Hg=(e,t)=>{let r=bE(e,t),n=EE(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},xE=(e,t)=>{let r=t.readFile(ce.join(e,"package.json"));try{let n=r===null?null:ae.object({version:ae.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},TE=e=>{let t=Number.parseInt(e.readFile(ce.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},CE=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},$E=(e,t,r)=>{let n=TE(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(CE(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ce.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},AE=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Sn(await t.repoRoot()??r,e,t.realpath)},ur=e=>({state:"drifted",row:e}),OE=async(e,t,r)=>{let n=ft(r.bin,r);if(!r.exists(e))return ur({name:It,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=ce.join(ha(r.home),"dist","cli.js");if(t!==o)return ur(So(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(ls(r.home,r.exists)===null)return ur({name:It,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(ha(r.home));if(await AE(s,r))return ur({name:It,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=IE(e,n,r);if(i!==null)return i;let a=xE(s,r),c=$E(s,a,r);return c!==null?{state:"converged",row:So(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${gE(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:It,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},IE=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:ur(So(`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:ur(So(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),qg=async e=>{let t=Kg(e.platform);if(t===null)return{state:"absent",row:{name:It,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:It,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=pf(e.platform,r)??[];return n===void 0||o===void 0?ur(So(`could not parse ${t} \u2014 re-run \`${ft(e.bin,e)}\` to rewrite it.`)):OE(n,o,e)},Yg=async(e,t)=>{let{seams:r}=Hg(e,t);return{state:(await qg(r)).state,stableNode:r.stableNode}},DE=()=>[Po,It,Gg(),"portless CA chain valid","portless CA trusted","portless routes"],NE=async(e={})=>{let t=e.resolveBin??ep,r=e.isProxyServing??sp,n=e.handshake??lp,o=e.caTrusted??cp,s=e.routes??En,i=e.isListening??Pn,a=(e.caPath??ap)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...DE().map(R=>({name:R,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:p}=Hg(e,c),m=s(),g=await uE(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await pE(n,m,a,c,d);return[l,p,(await qg(d)).row,g,y,mE(o(),a,c),await fE(m,i,c)]},_E=async(e={})=>{let t="portless routes",r=e.routes??En,n=e.isListening??Pn,o=e.devSessionRunning??af,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=sf(i,o());if(c.length>0)return{name:t,status:"fail",message:`${c.length} route(s) look stale (${c.join(", ")}), but a dev session is running \u2014 a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. Stop dev and re-run \`infra-kit doctor --fix\`.`};if(a.length===0)return{name:t,status:"pass",message:`${s.length} portless route(s), all live`};let l=e.removeAlias??dp().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},pi=async(e={})=>{let t=await SP(),r=vP(e.probeDeps??go()),n=async(m,g)=>{let[y,R]=await Promise.all([g,r]),w=R.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",dt("brew installed",Ne("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",dt("git installed",Ne("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",dt("gh installed",Ne("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),dt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",dt("doppler installed",Ne("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",dt("aws installed",Ne("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),dt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),dt("typescript-language-server installed",["typescript-language-server","--version"],"typescript-language-server is installed","typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing"),wP(),Promise.resolve(kP()),Promise.resolve(bP()),RP(),Promise.resolve(PP(t)),AP(),CP(t),OP(e.fix??!1),DP(),NP(),jP(t)]),s=await NE(e.portlessDeps);if(e.fix){let m=await _E(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await VP(),a=await uo(),c={projectDir:We.env.CLAUDE_PROJECT_DIR||null,cwd:We.cwd(),gitRoot:a},l=[await HP(),...nE(i,c),QP(),sE({env:We.env,stdinIsTTY:We.stdin.isTTY===!0,flag:N.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:aE(a)],d=[...o,await lE(a),...s,...await WP(),...l],p={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:$c.has(m.name),detail:m.detail})),allPassed:hP(d),cliVersion:K.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},Tl=S({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:ae.array(ae.object({name:ae.string().describe("Name of the check"),status:ae.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:ae.string().describe("Details about the check result"),fixable:ae.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ae.object({manager:ae.string().describe("Which package manager owns this install, read from its resolved path"),version:ae.string().nullable().describe("The version the tool reported, or null"),present:ae.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ae.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:ae.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:ae.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>pi()});import{E2E_MODE_ENV as QE}from"@slip-stream-kit/config/internal";import{spawn as ex}from"node:child_process";import _l from"node:fs";import tx from"node:os";import Ml from"node:path";import jl from"node:process";import{z as E}from"zod";import{describeProxyRoutes as ME,loadDev as jE,readAppAliasName as FE,readCloudOrigin as LE,readLocalContext as Xg}from"@slip-stream-kit/config/internal";import zg from"node:fs";import pr from"node:path";import mi from"node:process";import{z as Cl}from"zod";var BE=async e=>{let t=pr.join(e,"apps"),r=zg.existsSync(t)?zg.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=pr.join(t,o,"tests"),i=await Cr(s);i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},WE=(e,t)=>{let[r,n]=pr.relative(e,t).split(pr.sep);return r==="apps"&&n?n:void 0},VE=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(WE(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new x({status:"argument_required",argument:a,choices:Cl.toJSONSchema(Cl.object({app:Cl.enum(i)})),agentMode:N.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},UE=async(e,t,r)=>Promise.all(e.map(async n=>{if(n.source==="cloud")return{...n,live:null};let o=t.get(n.packageName)??0,s=o>0&&await r({tag:`${n.packageName}`,port:o,kind:"api"})==="ok";return{...n,live:s}})),JE=e=>zn(e).apps.find(t=>t.env!=="")?.env??null,$l=async(e,t={})=>{let r=t.cwd??mi.cwd(),n=t.projectRoot??await T(),o=(t.env??mi.env)[br]||null,s=t.healthProbe??Ta,i=VE(await BE(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),d=pr.join(n,"apps",c,l),p=(await qt(d)).name,m=(await Cr(d))?.deployedUrlEnv??null;if(!p)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${pr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${d} has no package.json name`});let g=um(d),y=FE(p,d),R=`${y}.localhost`,w=`https://${R}`,$=0;if(l==="ui")$=(t.listRoutes??En)().find(P=>P.name===R||P.name===y)?.port??0;else{let P=Xg(d).info.get(p);$=P?.port??0,w=P?.origin??w}let B=$>0&&await s({tag:a,port:$,kind:l})==="ok",I=B?JE(d):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:d,packageName:p,deployedUrlEnv:m,release:g,env:o,servedEnv:I,localUrl:w,served:B}},Zg=e=>{let{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}=e;return{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}},Al=async(e,t={})=>{let r=t.healthProbe??Ta,n=Xg(e.targetDir),o=e.kind==="ui"?await jE(e.targetDir):void 0,s=o?.proxy?ME({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:LE(e.deployedUrlEnv??void 0,t.env??mi.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Zg(e),mode:"local",baseUrl:e.localUrl,routes:await UE(s,i,r)}},Ol=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${pr.join(e.targetDir,"infra-kit.config.ts")} and keep the URL per environment in Doppler`,stderrExcerpt:`${o} names no variable holding its deployed URL`});let s=(t.env??mi.env)[n];if(!r||!s)throw new f(void 0,{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${br}, and ${s?br:n} is not set`});return{...Zg(e),mode:"cloud",baseUrl:s,routes:[]}};import GE from"node:fs";import KE from"node:path";import{stripVTControlCharacters as HE}from"node:util";import{z as D}from"zod";var Qg=2e3,eh="--reporter=line,json",th=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),rh=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Il=D.object({message:D.string().optional()}),qE=D.object({status:D.string(),retry:D.number(),error:Il.optional(),errors:D.array(Il).optional(),attachments:D.array(D.object({name:D.string(),path:D.string().optional()})).optional()}),YE=D.object({title:D.string(),file:D.string(),line:D.number().optional(),tests:D.array(D.object({projectName:D.string(),status:D.string(),results:D.array(qE)}))}),nh=D.lazy(()=>D.object({title:D.string(),specs:D.array(YE).optional(),suites:D.array(nh).optional()})),zE=D.object({config:D.object({rootDir:D.string().optional()}).optional(),suites:D.array(nh),errors:D.array(Il).optional(),stats:D.object({expected:D.number(),unexpected:D.number(),flaky:D.number(),skipped:D.number()})}),oh=e=>{let t=HE(e);return t.length>Qg?`${t.slice(0,Qg)}\u2026`:t},XE=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:oh(t)},ZE=e=>{let t=zE.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=(c,l)=>{for(let d of c.specs??[])for(let p of d.tests){if(p.status!=="unexpected"&&p.status!=="flaky")continue;let m=p.results.findLast(g=>g.status!=="passed"&&g.status!=="skipped");i.push({title:[...l,d.title].join(" \u203A "),file:r?.rootDir?KE.resolve(r.rootDir,d.file):d.file,line:d.line??null,project:p.projectName,status:p.status,retry:m?.retry??0,error:m?XE(m):"Expected to fail, but passed.",tracePath:m?.attachments?.find(g=>g.name==="trace")?.path??null})}for(let d of c.suites??[])a(d,[...l,d.title])};for(let c of n)a(c,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped},failures:i,errors:(o??[]).flatMap(c=>c.message===void 0?[]:[oh(c.message)])}},sh=e=>{try{return ZE(JSON.parse(GE.readFileSync(e,"utf8")))}catch{return null}};var rx=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],nx=e=>rx.some(t=>{try{return _l.readFileSync(Ml.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),ih=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,ox=(e,t)=>{let r=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl}`];e.mode==="cloud"?r.push(` deployed app at env "${e.env}"`):t?r.push(` dev server for ${e.target} on release "${e.release}", already running`):r.push(` nothing serves ${e.target} yet; the Playwright config starts it and stops it after the run`);for(let n of e.routes){let o="";n.live!==null&&(o=n.live?" \u2014 live":" \u2014 NOT responding"),r.push(` ${n.path.padEnd(24)} ${n.source.padEnd(5)} ${n.target??"(unresolved)"}${o}`)}return r.join(`
372
+ `)},sx=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},ix=async(e,t)=>{if(e.env===null||!lm(e.env))return;let r=await(t.protectedEnvAccess??Je)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new x({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},ax=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:`load the same env (\`infra-kit env-load -c ${e.servedEnv}\`), or restart \`infra-kit dev\` under "${e.env??"none"}"`,stderrExcerpt:`the dev server serving ${e.target} runs with env "${e.servedEnv}", this shell with "${e.env??"none"}"`})},cx=async(e,t)=>{if(e.served){ax(e);let p=await Al(e,t);return sx(p),p}if(!nx(e.testsDir))throw new f(void 0,{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${ih(e)}\`), or wire \`infraKitE2e()\` from @slip-stream-kit/config/playwright into its playwright.config.ts`,stderrExcerpt:`nothing serves ${e.target} and ${e.testsDir}'s Playwright config does not start it`});let{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:d}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:d,mode:"local",baseUrl:d,routes:[]}},lx=(e,t,r)=>new Promise((n,o)=>{let s=ex("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...jl.env,...r,[QE]:e.mode},stdio:["inherit",Jt.enabled||J()?2:"inherit","inherit"]});s.once("error",o),s.once("close",i=>{n(i??1)})}),fi=async(e,t={})=>{let r=await $l(e.app,t),n=e.cloud?Ol(r,t):await cx(r,t);u.info(ox(n,r.served)),n.mode==="cloud"&&await ix(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?ih(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Nl({...o,ran:!1,exitCode:null,...Dl});n.mode==="cloud"&&await V(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=t.runPlaywright??lx;if(!J()||rh(o.playwrightArgs)){let c=await s(n,o.playwrightArgs,{});return c!==0&&(jl.exitCode=c),Nl({...o,ran:!0,exitCode:c,...Dl,report:J()?"caller-reporter":"off"})}let i=_l.mkdtempSync(Ml.join(tx.tmpdir(),"ik-e2e-report-")),a=Ml.join(i,"report.json");try{let c=await s(n,[eh,...o.playwrightArgs],th(a));c!==0&&(jl.exitCode=c);let l=sh(a);return Nl({...o,ran:!0,exitCode:c,...l?{report:"collected",...l}:{...Dl,report:"unavailable"}})}finally{_l.rmSync(i,{recursive:!0,force:!0})}},Dl={report:"off",summary:null,failures:[],errors:[]},Nl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),dx={app:E.string(),testsDir:E.string(),target:E.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:E.string(),mode:E.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:E.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:E.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:E.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:E.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:E.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:E.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:E.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:E.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:E.array(E.object({path:E.string(),packageName:E.string(),source:E.enum(["local","cloud"]),target:E.string().nullable(),live:E.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:E.array(E.string()),ran:E.boolean().describe("False for --dry-run."),exitCode:E.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:E.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),summary:E.object({expected:E.number(),unexpected:E.number(),flaky:E.number(),skipped:E.number()}).nullable().describe("Test counts by outcome; null unless report is collected."),failures:E.array(E.object({title:E.string().describe("Describe path and test title, joined with \u203A."),file:E.string(),line:E.number().nullable(),project:E.string(),status:E.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry."),retry:E.number().describe("The retry index of the failed attempt reported here."),error:E.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:E.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("Every test that failed or needed a retry; empty unless report is collected."),errors:E.array(E.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},Fl=S({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:E.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:E.boolean().optional(),yes:E.boolean().optional(),cloud:E.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:E.array(E.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:dx,handler:e=>fi(e)});import gi from"node:fs";import Ll from"node:path";import{z as Eo}from"zod";var ux=e=>[...e.map(t=>`unset ${t}`),`unset ${br}`,`unset ${ns}`,`unset ${os}`,`unset ${Ju}`,`unset ${ss}`],hi=async()=>{let e=Rr(),t=Ll.join(e,kr);if(!gi.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=is(t),n=ux(r),o=Ll.resolve(e,ts);gi.mkdirSync(e,{recursive:!0,mode:448}),Rn(o,`${n.join(`
371
373
  `)}
372
- `,384),fl.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},gl=S({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:go.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:go.string().describe("Path to the file that must be sourced to apply"),variableCount:go.number().describe("Number of variables cleared"),unsetStatements:go.array(go.string()).describe("Unset statements generated")},handler:()=>ti()});import qP from"node:path";import ho from"node:process";import{z as sn}from"zod";var ri=async()=>{u.info("Environment session status:");let e=yr(),t=ho.env[hn],r=qP.join(e,gr),n=0,o=0,s=ho.env[Jo]??null,i=ho.env[Go]??null,a=ho.env[Ko]??null;if(s){let l=Ho(r);l.length>0&&(o=l.length,n=l.filter(p=>p in ho.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(u.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
374
+ `,384),gi.rmSync(t,{force:!0}),gi.rmSync(Ll.join(e,rs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Bl=S({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:Eo.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Eo.string().describe("Path to the file that must be sourced to apply"),variableCount:Eo.number().describe("Number of variables cleared"),unsetStatements:Eo.array(Eo.string()).describe("Unset statements generated")},handler:()=>hi()});import px from"node:path";import xo from"node:process";import{z as pn}from"zod";var yi=async()=>{u.info("Environment session status:");let e=Rr(),t=xo.env[bn],r=px.join(e,kr),n=0,o=0,s=xo.env[ns]??null,i=xo.env[os]??null,a=xo.env[ss]??null;if(s){let l=is(r);l.length>0&&(o=l.length,n=l.filter(p=>p in xo.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(u.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
373
375
  `),o>0&&n<o){let p=o-n;u.warn(` ${p} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else u.info(` Session ${t}: no env loaded
374
- `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},hl=S({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:sn.string().describe("Current terminal session ID"),sessionLoadedCount:sn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:sn.number().describe("Total number of cached var names"),sessionConfig:sn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:sn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:sn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:ri});import YP from"node:process";import{z as Ot}from"zod";var Tg="****",an=e=>typeof e!="string"||e.length<8?Tg:`${Tg}${e.slice(-4)}`;var Cg=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Vt}`:"store",redactedToken:an(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),zP=["ENV","SOURCE","TOKEN","PRESENT"],$g=(e,t)=>{let r=[...zP,...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())},ni=async({check:e}={})=>{let t=await us(),r=await Bt(),n=YP.env[Vt],o=Cg(t,r?.envs??{},n);if(e){let a=await br();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await Pp({childEnv:En(l),project:a,config:c.env});c.status=d.outcome}}for(let a of $g(o,!!e))u.info(a);let s=o.filter(a=>!a.present);s.length>0&&u.info(`
375
- 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}},yl=S({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:Ot.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Ot.array(Ot.object({env:Ot.string().describe("Environment / Doppler config name"),source:Ot.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Ot.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Ot.boolean().describe("Whether a token is configured for this environment"),status:Ot.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ni});import{z as b}from"zod";import{$ as XP}from"zx";var ZP=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),QP=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,eE=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(", ")},wl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),vl=new Set(["up-to-date","fast-forward","merged"]),tE=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=xe(ye(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},rE={"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"},Og=e=>{let t=rE[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},nE=(e,t)=>{u.info(`
376
- \u{1F4CB} Merge plan:`);for(let r of e)u.info(` ${r.branch} \u2014 ${Og(r)}`);for(let r of t)u.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},oE=(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`},sE=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=J(i.branch);return a?[[te(a),Og(i)]]:[]}));return xt(oe({branches:r,descriptions:s}),{required:!0})},iE=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 R of y)u.info(`\u2139\uFE0F ${R} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await Xn(t,zm(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){u.info(`
377
- \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await Zm({worktreePath:r,refs:l,command:s});d=y.failed;for(let[w,$]of y.failed)u.info(`\u2717 ${w} failed verification \u2014 not pushing it. ${$.split(`
378
- `)[0]??""}`);let R=await Xn(t,y.kept);a(R.nowUpToDate),l=R.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};u.info(`
379
- \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await ns(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await kr(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&u.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:p.stderr?.split(`
380
- `)[0],observedLanded:g.map(y=>y.branch)}},aE=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Ag=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
381
- `)[0];u.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!vl.has(i.status));return wl({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},cE=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await je();if(e.abort)return Ag(await Sf({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Ag(await bf({cwd:s,versions:r,all:t,verify:i,trees:Rf(e.tree),confirmedCommand:o}))},oi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;aE(e);let a=o===!0?Xm:o||void 0;if(await pc({operation:"merge dev into release branches"}),e.continue||e.abort)return cE(e);let c=[],l=[];for(let U of await F()){let ue=QP(U);ue?l.push({branch:U.branch,reason:ue}):c.push(U.branch)}if(c.length===0)return u.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${eE(l)})`),h.print(),wl(ZP(n,l));let d=await je();try{await XP({cwd:d,quiet:!0})`git fetch origin --prune`}catch(U){throw new f(U,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:tE(r,c,l),m=await ep({cwd:d},async U=>{let ue=Ns(U.remove);try{return await lE({cwd:d,worktree:U,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{ue()}}),{entries:g,selected:y,pushed:R,pushAborted:w,abortedBy:$,declined:D,verifyFailed:A,handOffs:P}=m,Y=await gt(d).catch(()=>[]);return pE({entries:g,selected:y,pushed:R,pushAborted:w,abortedBy:$,declined:D,verifyFailed:A,handOffs:P,dryRun:n,worktrees:Y,skipped:l})},lE=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:p}=e,m=d?await Ce(t,"origin/dev"):null,g=await Ym({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(nE(g,s),c)return{...y,selected:n};let R=await sE({entries:g,toPlan:n,all:i,explicit:a!==void 0});R.length===o.length?h.addOption("--all",!0):h.addOption("--versions",R);let w=g.filter(P=>R.includes(P.branch)&&P.mergeSha).length;w>0&&u.info(`
382
- \u2139\uFE0F This will push ${w} branch(es), re-running CI on ${w} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await B(p,`Are you sure you want to merge dev into these branches: ${R.join(", ")}?`,{throwOnDecline:!0,plan:dE(g,R,s)})}catch(P){if(!nt(P))throw P;return{...y,selected:R,declined:!0}}p||h.addOption("--yes",!0);let $=await iE({cwd:t,worktreePath:r.path,entries:g,selected:R,verify:l}),D=g.filter(P=>R.includes(P.branch)&&P.status==="conflict").map(P=>P.branch),A=d&&m&&D.length>0?await vf({cwd:t,branches:D,devSha:m}):void 0;return{entries:g,selected:R,declined:!1,...$,handOffs:A}},dE=(e,t,r)=>({entries:e.filter(n=>t.includes(n.branch)).map(n=>({branch:n.branch,status:n.status,...n.conflictPaths?{conflictPaths:n.conflictPaths}:{},...n.status==="conflict"?{lockfileOnly:Tc(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),uE=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
376
+ `);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Wl=S({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:pn.string().describe("Current terminal session ID"),sessionLoadedCount:pn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:pn.number().describe("Total number of cached var names"),sessionConfig:pn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:pn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:pn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:yi});import mx from"node:process";import{z as Dt}from"zod";var ah="****",we=e=>typeof e!="string"||e.length<8?ah:`${ah}${e.slice(-4)}`;var ch=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Ht}`:"store",redactedToken:we(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),fx=["ENV","SOURCE","TOKEN","PRESENT"],lh=(e,t)=>{let r=[...fx,...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())},vi=async({check:e}={})=>{let t=await Ps(),r=await Be(),n=mx.env[Ht],o=ch(t,r?.envs??{},n);if(e){let a=await Kt();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await Zp({childEnv:In(l),project:a,config:c.env});c.status=d.outcome}}for(let a of lh(o,!!e))u.info(a);let s=o.filter(a=>!a.present);s.length>0&&u.info(`
377
+ 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}},Vl=S({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:Dt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Dt.array(Dt.object({env:Dt.string().describe("Environment / Doppler config name"),source:Dt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Dt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Dt.boolean().describe("Whether a token is configured for this environment"),status:Dt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:vi});import{z as b}from"zod";import{$ as gx}from"zx";var hx=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),yx=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,vx=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(", ")},Jl=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),Ul=new Set(["up-to-date","fast-forward","merged"]),wx=(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=ve(pe(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},kx={"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"},uh=e=>{let t=kx[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},bx=(e,t)=>{u.info(`
378
+ \u{1F4CB} Merge plan:`);for(let r of e)u.info(` ${r.branch} \u2014 ${uh(r)}`);for(let r of t)u.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},Rx=(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`},Sx=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=G(i.branch);return a?[[re(a),uh(i)]]:[]}));return Ct(ie({branches:r,descriptions:s}),{required:!0})},Px=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 R of y)u.info(`\u2139\uFE0F ${R} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await ao(t,Cf(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){u.info(`
379
+ \u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await Af({worktreePath:r,refs:l,command:s});d=y.failed;for(let[w,$]of y.failed)u.info(`\u2717 ${w} failed verification \u2014 not pushing it. ${$.split(`
380
+ `)[0]??""}`);let R=await ao(t,y.kept);a(R.nowUpToDate),l=R.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};u.info(`
381
+ \u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await hs(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Er(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&u.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:p.stderr?.split(`
382
+ `)[0],observedLanded:g.map(y=>y.branch)}},Ex=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},dh=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
383
+ `)[0];u.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!Ul.has(i.status));return Jl({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},xx=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Le();if(e.abort)return dh(await eg({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return dh(await Zf({cwd:s,versions:r,all:t,verify:i,trees:Qf(e.tree),confirmedCommand:o}))},wi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;Ex(e);let a=o===!0?$f:o||void 0;if(await Oc({operation:"merge dev into release branches"}),e.continue||e.abort)return xx(e);let c=[],l=[];for(let te of await F()){let Ut=yx(te);Ut?l.push({branch:te.branch,reason:Ut}):c.push(te.branch)}if(c.length===0)return u.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${vx(l)})`),h.print(),Jl(hx(n,l));let d=await Le();try{await gx({cwd:d,quiet:!0})`git fetch origin --prune`}catch(te){throw new f(te,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:wx(r,c,l),m=await Cp({cwd:d},async te=>{let Ut=qs(te.remove);try{return await Tx({cwd:d,worktree:te,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{Ut()}}),{entries:g,selected:y,pushed:R,pushAborted:w,abortedBy:$,declined:B,verifyFailed:I,handOffs:P}=m,le=await gt(d).catch(()=>[]);return Ax({entries:g,selected:y,pushed:R,pushAborted:w,abortedBy:$,declined:B,verifyFailed:I,handOffs:P,dryRun:n,worktrees:le,skipped:l})},Tx=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:p}=e,m=d?await $e(t,"origin/dev"):null,g=await Tf({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(bx(g,s),c)return{...y,selected:n};let R=await Sx({entries:g,toPlan:n,all:i,explicit:a!==void 0});R.length===o.length?h.addOption("--all",!0):h.addOption("--versions",R);let w=g.filter(P=>R.includes(P.branch)&&P.mergeSha).length;w>0&&u.info(`
384
+ \u2139\uFE0F This will push ${w} branch(es), re-running CI on ${w} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await V(p,`Are you sure you want to merge dev into these branches: ${R.join(", ")}?`,{throwOnDecline:!0,plan:Cx(g,R,s)})}catch(P){if(!ot(P))throw P;return{...y,selected:R,declined:!0}}p||h.addOption("--yes",!0);let $=await Px({cwd:t,worktreePath:r.path,entries:g,selected:R,verify:l}),B=g.filter(P=>R.includes(P.branch)&&P.status==="conflict").map(P=>P.branch),I=d&&m&&B.length>0?await Yf({cwd:t,branches:B,devSha:m}):void 0;return{entries:g,selected:R,declined:!1,...$,handOffs:I}},Cx=(e,t,r)=>({entries:e.filter(n=>t.includes(n.branch)).map(n=>({branch:n.branch,status:n.status,...n.conflictPaths?{conflictPaths:n.conflictPaths}:{},...n.status==="conflict"?{lockfileOnly:Kc(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),$x=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
383
385
  `:`# ${e.branch} \u2014 ${e.status}
384
- ${oE(e.branch,t)}
385
- `,pE=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:p}=e,m=new Set(n?t.filter(w=>r.includes(w.branch)&&w.mergeSha&&!l?.has(w.branch)).map(w=>w.branch):[]),g=t.filter(w=>r.includes(w.branch)).map(w=>{let $=!!w.mergeSha,D=e.verifyFailed?.get(w.branch),A=o&&$?"push-aborted":w.status,P=D?"verify-failed":A,Y=d?.get(w.branch);return{branch:w.branch,status:P,mergeSha:w.mergeSha,conflictPaths:w.conflictPaths,pushed:m.has(w.branch),reason:D??Y?.reason??w.reason,...Y?.resolution?{resolution:Y.resolution}:{}}}),y=g.filter(w=>!vl.has(w.status));for(let w of g){let $=t.find(D=>D.branch===w.branch);u.info({branch:w.branch,status:w.status,mergeSha:w.mergeSha,conflictCount:w.conflictPaths?.length??0,durationMs:$?.durationMs,pushed:w.pushed,msg:"merge-dev branch result"})}if(i||a)u.info(i?`
386
+ ${Rx(e.branch,t)}
387
+ `,Ax=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:p}=e,m=new Set(n?t.filter(w=>r.includes(w.branch)&&w.mergeSha&&!l?.has(w.branch)).map(w=>w.branch):[]),g=t.filter(w=>r.includes(w.branch)).map(w=>{let $=!!w.mergeSha,B=e.verifyFailed?.get(w.branch),I=o&&$?"push-aborted":w.status,P=B?"verify-failed":I,le=d?.get(w.branch);return{branch:w.branch,status:P,mergeSha:w.mergeSha,conflictPaths:w.conflictPaths,pushed:m.has(w.branch),reason:B??le?.reason??w.reason,...le?.resolution?{resolution:le.resolution}:{}}}),y=g.filter(w=>!Ul.has(w.status));for(let w of g){let $=t.find(B=>B.branch===w.branch);u.info({branch:w.branch,status:w.status,mergeSha:w.mergeSha,conflictCount:w.conflictPaths?.length??0,durationMs:$?.durationMs,pushed:w.pushed,msg:"merge-dev branch result"})}if(i||a)u.info(i?`
386
388
  Operation cancelled \u2014 nothing was pushed.
387
389
  `:`
388
390
  \u{1F50D} Dry run \u2014 nothing was pushed.
389
391
  `);else if(y.length>0){u.info(`
390
392
  \u26A0\uFE0F ${y.length} branch(es) did not merge.
391
- `);for(let w of y)u.info(uE(w,c))}else u.info(`\u2705 All merges completed successfully!
392
- `);h.print();let R=a||i;return wl({successfulMerges:R?0:g.filter(w=>vl.has(w.status)).length,failedMerges:R?0:y.length,failedBranches:R?[]:y.map(w=>w.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(w=>R?{...w,pushed:!1}:w),skipped:p})},kl=S({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:b.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:b.union([b.string(),b.array(b.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:oi});import{z as ko}from"zod";import{$ as De}from"zx";var Ig=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},It=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=Ig(t.stderr,500);o&&(r.stderr=o);let s=Ig(t.stdout,200);return s&&(r.stdout=s),r};var yo=e=>{let{removed:t,failed:r}=e;if(t.length>0){u.info("\u274C Removed worktrees:");for(let n of t)u.info(n);u.info("")}if(r.length>0){u.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)u.warn(`${n} \u2014 ${o}`);u.warn("")}t.length===0&&r.length===0&&u.info("\u2139\uFE0F No worktrees to remove")};var vo=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 fe()?new x({status:"partial_failure",...n},1,s):new f(void 0,s)};import ii from"node:fs/promises";import{$ as Mg}from"zx";var mE=new Set([".omc",".DS_Store"]),fE=new Set(["state","sessions"]),gE=2e3,hE="check 'git worktree list' for the path; uncommitted changes block removal",yE=e=>new Promise(t=>{setTimeout(t,e)}),bl=e=>typeof e=="object"&&e!==null?e.code:void 0,Dg=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Ng=async e=>{try{return Dg(await ii.realpath(e))}catch{return Dg(e)}},vE=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await gt(t),o=await Ng(r);for(let s of n)if(await Ng(s.path)===o)return!0;return!1}catch{return!0}},wE=async e=>{let t;try{t=await ii.readdir(e)}catch(n){return{kind:bl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>mE.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await ii.readdir(`${e}/.omc`)).every(s=>fE.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:bl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},_g=async e=>{try{return await ii.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return bl(t)==="ENOTEMPTY"?"busy":"failed"}},kE=async e=>{let{worktreePath:t,sleep:r}=e,n=await _g(t);return n!=="busy"?n==="removed":(await r(gE),await _g(t)==="removed")},si=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return u.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},bE=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await vE({projectRoot:n,worktreePath:r}))return si(t,o,hE);let i=await wE(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 kE({worktreePath:r,sleep:s})?si(t,o,a):(u.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"})},RE=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await $p(i,o);if(!a.closed&&"error"in a)return si(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await Mg`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return bE({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},ar=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=yE}=e,i=t.length>0?await Rr():"unreachable",a=await Promise.all(t.map(l=>RE({branch:l,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let l of a)l.status==="removed"?c.removed.push(l.branch):c.failed.push({branch:l.branch,reason:l.reason});return o&&c.removed.length===t.length&&await Mg`git worktree prune`,c};var wo=async(e,t)=>{if(!(await Te("release")).includes(e))return[];let n=await E(),o=`${n}${pe}`,{removed:s,failed:i}=await ar({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var cn=async(e,t,r)=>{try{return await r()}catch(n){throw u.debug({err:It(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},SE=async e=>{let t=na(e),r=await De`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},jg=async()=>{let e=await De`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},PE=async e=>{let t=ct(e),r=await gc(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 jr(t);if(!n)throw u.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=Gn(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}},EE=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await ne(),o=await Et(oe({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw u.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}},xE=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=ze(r),s=await hc(n);if(s.state==="MERGED"){u.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 cn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await De`gh pr merge ${n} --squash --admin --delete-branch`})},TE=async e=>{let t=z(e),r=na(e),n=await jg();if(n){let s=n.number;return n.title!==r&&(u.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await cn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await De`gh pr edit ${s} --title ${r}`})),s}await cn(`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 De`gh pr create --base main --head dev --title ${r} --body ""`});let o=await jg();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},CE=async e=>{let t=z(e);if(await SE(e)){u.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await TE(e);await cn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await De`gh pr merge ${n} --squash --admin`})},$E=async()=>{De.quiet=!1,await cn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await De`gh workflow run deploy-all.yml --ref main -f environment=prod`}),De.quiet=!0},AE=async()=>{await cn("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 De`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},OE=async e=>{try{await ts(e)}catch(t){u.warn({err:It(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await rs(e)}catch(t){u.warn({err:It(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},IE=async e=>{let t=await at();if(!t){u.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=te(e);await vc({versionName:r},t)}catch(r){let n=Hn(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";u.error({err:It(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},ai=async e=>{let{version:t,confirmedCommand:r}=e;await be({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await PE(t):await EE(),i=J(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=z(i);if(h.addOption("--version",a),u.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),fe())throw new x({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 B(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),De.quiet=!0;let l=`${await E()}${pe}`;await wo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await xE({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await CE(i),await $E(),await AE(),await OE(n),De.quiet=!1,await IE(i),u.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Rl=S({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:ko.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:ko.string().describe("The release branch that was delivered"),version:ko.string().describe("The version that was delivered"),type:ko.enum(["regular","hotfix"]).describe("Release type"),success:ko.boolean().describe("Whether the delivery was successful")},handler:ai});import{z as dt}from"zod";import{$ as Il}from"zx";import{z as So}from"zod";import Fg from"node:fs/promises";import Sl from"node:path";var Lg=".github/workflows",DE=/script_name:\s*(?<service>[a-z0-9-]+)/,NE=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,_E=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Pl=async e=>{let t=Sl.resolve(e,Lg),r;try{r=await Fg.readdir(t)}catch{return new Map}return Bg(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},bo=async(e,t)=>Bg(Sl.resolve(e,Lg),[t]),Bg=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await Fg.readFile(Sl.resolve(e,n),"utf-8")}catch{continue}ME(o,r)}return r},ME=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=DE.exec(r)?.groups?.service??NE.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(_E)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},El=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import jE from"node:fs/promises";import FE from"node:path";import LE from"yaml";var BE=".github/workflows",VE="skip_terraform_deploy",Ro=async(e,t)=>{let r=FE.resolve(e,BE,t),n;try{n=LE.parse(await jE.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!==VE).map(([i])=>i)};var Vg="dev",xl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wg=(e,t)=>e[t]===void 0,Ug=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Tl=async e=>{try{return await e}catch{return[]}},WE=async()=>{let e=await F();return zt(e.map(t=>t.branch))},UE=(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},cr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(u.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Tl(WE());if(l.length===0)return null;let d=Ug(c,"version");return So.enum([...new Set([...l,Vg])]).optional().describe(`Which release to deploy from. "${Vg}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=kt(await Tl(bt(t)),await Ue());if(l.length===0)return null;let d=l.filter(Pn),p=l.filter(g=>!Pn(g)),m=Ug(c,"env");return So.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await E(),l=await Tl(Ro(c,t));if(l.length===0)return null;let d=await bo(c,t);return So.array(So.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${UE(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>xl(c)?r.some(l=>Wg(c,l)):!1,buildRequestedSchema:async c=>{let l=xl(c)?c:{},d={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");d.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");d.env=p}if(r.includes("services")&&Wg(l,"services")){let p=await a();if(p===null)return o("services");d.services=p}return Object.keys(d).length===0?o("fields"):So.object(d)},toArgs:(c,l)=>{let d={...xl(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;d[p]=m}}return d}}};import JE from"@inquirer/select";var ln=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 O(r=>JE({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import GE from"@inquirer/confirm";var Po=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ge()&&as(o,{branch:r,env:n}),h.setInteractive();let s=await O(i=>GE({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import KE from"@inquirer/select";import HE from"node:process";var Cl=()=>!ge()&&HE.stdin.isTTY===!0,qE={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},$l=async()=>O(e=>KE({message:"\u{1F680} Where should this deploy run?",choices:Dt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:qE[t]}))},e),{whenHeadless:"refuse"});var Dt=["ci","local"],YE={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Jg=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Dt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ge()?new x({status:"argument_required",argument:"from",agentMode:I.source},2,r):new f(void 0,r)}let t=Dt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Dt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Al=(e,t)=>{let n=YE[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}`})},Ol=async e=>e||!Cl()?Jg(e):$l();var Eo=async e=>{if(e)return e==="dev"?"dev":ct(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await ne();return Et([{value:"dev",label:"dev"},...oe({branches:r,descriptions:o,types:n})])};var Gg="deploy-all.yml",Kg=cr({workflowFile:Gg,fields:["version","env"],toolName:"gh-release-deploy-all"}),ci=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Je({provider:Kg,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await Eo(t),i=zn(s);h.addOption("--version",i);let a=await Ue(),c=kt(await bt(Gg),a),l="";r?l=r:(h.setInteractive(),l=await ln(c,"launch deploy-all workflow")),h.addOption("--env",l),Sr(l,"launch deploy-all workflow",a),ds({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await Po({confirmedCommand:o,branch:s,env:l})){u.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{Il.quiet=!0,await Il`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Il.quiet=!1,u.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw u.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Dl=S({name:"gh-release-deploy-all",formProvider:Kg,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:dt.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:dt.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:dt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:dt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:dt.string().describe("The release branch that was deployed"),version:dt.string().describe("The version that was deployed"),environment:dt.string().describe("The environment deployed to"),skipTerraformDeploy:dt.boolean().describe("Whether terraform deployment was skipped"),success:dt.boolean().describe("Whether the deployment was successful")},handler:ci});import zE from"@inquirer/checkbox";import{z as Se}from"zod";import{$ as Nl}from"zx";var lr="deploy-selected-services.yml",Hg=cr({workflowFile:lr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),li=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Je({provider:Hg,params:e,operation:"launch deploy-selected workflow",argument:A=>A[0]??"version"});let i=await Eo(t),a=zn(i);h.addOption("--version",a);let c=await Ue(),l=kt(await bt(lr),c),d="";r?d=r:(h.setInteractive(),d=await ln(l,"launch deploy-selected workflow")),h.addOption("--env",d),Sr(d,"launch deploy-selected workflow",c),ds({env:d,branch:i});let p=await E(),m=await Ro(p,lr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${lr}`,stderrExcerpt:`no services found in .github/workflows/${lr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await O(A=>zE({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},A),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(A=>!m.includes(A));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 R=await bo(p,lr),w=g.filter(A=>{let P=R.get(A);return P!==void 0&&!P.includes(d)});if(w.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(A=>`${A} deploys only to: ${(R.get(A)??[]).join(", ")}`).join("; "),stderrExcerpt:`${lr} gates these services out of ${d}: ${w.join(", ")}`});let $=o??!1;$&&h.addOption("--skip-terraform",!0);let D=A=>{let P={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:$,success:A};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await Po({confirmedCommand:s,branch:i,env:d}))return u.info("Deployment cancelled"),D(!1);try{Nl.quiet=!0;let A=g.flatMap(Y=>["-f",`${Y}=true`]);return await Nl`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${A} ${$?["-f","skip_terraform_deploy=true"]:[]}`,Nl.quiet=!1,u.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),D(!0)}catch(A){throw u.error({error:A},"\u274C Error launching workflow"),new f(A,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},_l=S({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Hg,description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:Se.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:Se.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:Se.array(Se.string()).optional().describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:Se.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Se.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Se.string().describe("The release branch that was deployed"),version:Se.string().describe("The version that was deployed"),environment:Se.string().describe("The environment deployed to"),services:Se.array(Se.string()).describe("The services that were deployed"),skipTerraformDeploy:Se.boolean().describe("Whether terraform deployment was skipped"),success:Se.boolean().describe("Whether the deployment was successful")},handler:li});import{z as Nt}from"zod";var di=async()=>{let t=(await F()).flatMap(i=>{let a=J(i.branch);return a?[{version:z(a),jiraKey:te(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Os(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Yn(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${p}`});u.info(`All release branches:
393
+ `);for(let w of y)u.info($x(w,c))}else u.info(`\u2705 All merges completed successfully!
394
+ `);h.print();let R=a||i;return Jl({successfulMerges:R?0:g.filter(w=>Ul.has(w.status)).length,failedMerges:R?0:y.length,failedBranches:R?[]:y.map(w=>w.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(w=>R?{...w,pushed:!1}:w),skipped:p})},Gl=S({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:b.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:b.union([b.string(),b.array(b.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:wi});import{z as Ao}from"zod";import{$ as _e}from"zx";var ph=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Nt=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=ph(t.stderr,500);o&&(r.stderr=o);let s=ph(t.stdout,200);return s&&(r.stdout=s),r};var To=e=>{let{removed:t,failed:r}=e;if(t.length>0){u.info("\u274C Removed worktrees:");for(let n of t)u.info(n);u.info("")}if(r.length>0){u.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)u.warn(`${n} \u2014 ${o}`);u.warn("")}t.length===0&&r.length===0&&u.info("\u2139\uFE0F No worktrees to remove")};var Co=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 ye()?new x({status:"partial_failure",...n},1,s):new f(void 0,s)};import bi from"node:fs/promises";import{$ as hh}from"zx";var Ox=new Set([".omc",".DS_Store"]),Ix=new Set(["state","sessions"]),Dx=2e3,Nx="check 'git worktree list' for the path; uncommitted changes block removal",_x=e=>new Promise(t=>{setTimeout(t,e)}),Kl=e=>typeof e=="object"&&e!==null?e.code:void 0,mh=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},fh=async e=>{try{return mh(await bi.realpath(e))}catch{return mh(e)}},Mx=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await gt(t),o=await fh(r);for(let s of n)if(await fh(s.path)===o)return!0;return!1}catch{return!0}},jx=async e=>{let t;try{t=await bi.readdir(e)}catch(n){return{kind:Kl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>Ox.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await bi.readdir(`${e}/.omc`)).every(s=>Ix.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Kl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},gh=async e=>{try{return await bi.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Kl(t)==="ENOTEMPTY"?"busy":"failed"}},Fx=async e=>{let{worktreePath:t,sleep:r}=e,n=await gh(t);return n!=="busy"?n==="removed":(await r(Dx),await gh(t)==="removed")},ki=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return u.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},Lx=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await Mx({projectRoot:n,worktreePath:r}))return ki(t,o,Nx);let i=await jx(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 Fx({worktreePath:r,sleep:s})?ki(t,o,a):(u.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"})},Bx=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await rm(i,o);if(!a.closed&&"error"in a)return ki(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await hh`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return Lx({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},mr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=_x}=e,i=t.length>0?await xr():"unreachable",a=await Promise.all(t.map(l=>Bx({branch:l,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let l of a)l.status==="removed"?c.removed.push(l.branch):c.failed.push({branch:l.branch,reason:l.reason});return o&&c.removed.length===t.length&&await hh`git worktree prune`,c};var $o=async(e,t)=>{if(!(await me("release")).includes(e))return[];let n=await T(),o=`${n}${ge}`,{removed:s,failed:i}=await mr({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 mn=async(e,t,r)=>{try{return await r()}catch(n){throw u.debug({err:Nt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},Wx=async e=>{let t=ya(e),r=await _e`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},yh=async()=>{let e=await _e`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},Vx=async e=>{let t=lt(e),r=await Nc(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 Ur(t);if(!n)throw u.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=to(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},Ux=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await se(),o=await Tt(ie({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw u.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}},Jx=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Xe(r),s=await _c(n);if(s.state==="MERGED"){u.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 mn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin --delete-branch`})},Gx=async e=>{let t=X(e),r=ya(e),n=await yh();if(n){let s=n.number;return n.title!==r&&(u.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await mn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await _e`gh pr edit ${s} --title ${r}`})),s}await mn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await _e`gh pr create --base main --head dev --title ${r} --body ""`});let o=await yh();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},Kx=async e=>{let t=X(e);if(await Wx(e)){u.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await Gx(e);await mn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin`})},Hx=async()=>{_e.quiet=!1,await mn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await _e`gh workflow run deploy-all.yml --ref main -f environment=prod`}),_e.quiet=!0},qx=async()=>{await mn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await _e`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Yx=async e=>{try{await fs(e)}catch(t){u.warn({err:Nt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await gs(e)}catch(t){u.warn({err:Nt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},zx=async e=>{let t=await ct();if(!t){u.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=re(e);await jc({versionName:r},t)}catch(r){let n=no(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";u.error({err:Nt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ri=async e=>{let{version:t,confirmedCommand:r}=e;await Pe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await Vx(t):await Ux(),i=G(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=X(i);if(h.addOption("--version",a),u.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ye())throw new x({status:"refused",agentMode:N.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 V(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),_e.quiet=!0;let l=`${await T()}${ge}`;await $o(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await Jx({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await Kx(i),await Hx(),await qx(),await Yx(n),_e.quiet=!1,await zx(i),u.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Hl=S({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:Ao.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:Ao.string().describe("The release branch that was delivered"),version:Ao.string().describe("The version that was delivered"),type:Ao.enum(["regular","hotfix"]).describe("Release type"),success:Ao.boolean().describe("Whether the delivery was successful")},handler:Ri});import{z as ut}from"zod";import{$ as nd}from"zx";import{z as Do}from"zod";import vh from"node:fs/promises";import ql from"node:path";var wh=".github/workflows",Xx=/script_name:\s*(?<service>[a-z0-9-]+)/,Zx=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,Qx=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Yl=async e=>{let t=ql.resolve(e,wh),r;try{r=await vh.readdir(t)}catch{return new Map}return kh(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Oo=async(e,t)=>kh(ql.resolve(e,wh),[t]),kh=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await vh.readFile(ql.resolve(e,n),"utf-8")}catch{continue}eT(o,r)}return r},eT=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=Xx.exec(r)?.groups?.service??Zx.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(Qx)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},zl=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import tT from"node:fs/promises";import rT from"node:path";import nT from"yaml";var oT=".github/workflows",sT="skip_terraform_deploy",Io=async(e,t)=>{let r=rT.resolve(e,oT,t),n;try{n=nT.parse(await tT.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!==sT).map(([i])=>i)};var bh="dev",Xl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rh=(e,t)=>e[t]===void 0,Sh=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Zl=async e=>{try{return await e}catch{return[]}},iT=async()=>{let e=await F();return rr(e.map(t=>t.branch))},aT=(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},fr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(u.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Zl(iT());if(l.length===0)return null;let d=Sh(c,"version");return Do.enum([...new Set([...l,bh])]).optional().describe(`Which release to deploy from. "${bh}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=bt(await Zl(Rt(t)),await Je());if(l.length===0)return null;let d=l.filter(On),p=l.filter(g=>!On(g)),m=Sh(c,"env");return Do.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await T(),l=await Zl(Io(c,t));if(l.length===0)return null;let d=await Oo(c,t);return Do.array(Do.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${aT(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Xl(c)?r.some(l=>Rh(c,l)):!1,buildRequestedSchema:async c=>{let l=Xl(c)?c:{},d={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");d.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");d.env=p}if(r.includes("services")&&Rh(l,"services")){let p=await a();if(p===null)return o("services");d.services=p}return Object.keys(d).length===0?o("fields"):Do.object(d)},toArgs:(c,l)=>{let d={...Xl(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;d[p]=m}}return d}}};import cT from"@inquirer/select";var fn=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 O(r=>cT({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import lT from"@inquirer/confirm";var No=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;J()&&ks(o,{branch:r,env:n}),h.setInteractive();let s=await O(i=>lT({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import dT from"@inquirer/select";import uT from"node:process";var Ql=()=>!J()&&uT.stdin.isTTY===!0,pT={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},ed=async()=>O(e=>dT({message:"\u{1F680} Where should this deploy run?",choices:_t.filter(t=>t!=="local").map(t=>({name:t,value:t,description:pT[t]}))},e),{whenHeadless:"refuse"});var _t=["ci","local"],mT={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Ph=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${_t.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw J()?new x({status:"argument_required",argument:"from",agentMode:N.source},2,r):new f(void 0,r)}let t=_t.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${_t.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},td=(e,t)=>{let n=mT[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}`})},rd=async e=>e||!Ql()?Ph(e):ed();var _o=async e=>{if(e)return e==="dev"?"dev":lt(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await se();return Tt([{value:"dev",label:"dev"},...ie({branches:r,descriptions:o,types:n})])};var Eh="deploy-all.yml",xh=fr({workflowFile:Eh,fields:["version","env"],toolName:"gh-release-deploy-all"}),Si=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Ge({provider:xh,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await _o(t),i=io(s);h.addOption("--version",i);let a=await Je(),c=bt(await Rt(Eh),a),l="";r?l=r:(h.setInteractive(),l=await fn(c,"launch deploy-all workflow")),h.addOption("--env",l),Tr(l,"launch deploy-all workflow",a),Ss({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await No({confirmedCommand:o,branch:s,env:l})){u.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{nd.quiet=!0,await nd`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,nd.quiet=!1,u.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw u.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},od=S({name:"gh-release-deploy-all",formProvider:xh,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:ut.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:ut.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:ut.boolean().optional().describe("Skip the terraform deployment stage."),confirm:ut.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:ut.string().describe("The release branch that was deployed"),version:ut.string().describe("The version that was deployed"),environment:ut.string().describe("The environment deployed to"),skipTerraformDeploy:ut.boolean().describe("Whether terraform deployment was skipped"),success:ut.boolean().describe("Whether the deployment was successful")},handler:Si});import fT from"@inquirer/checkbox";import{z as xe}from"zod";import{$ as sd}from"zx";var gr="deploy-selected-services.yml",Th=fr({workflowFile:gr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Pi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ge({provider:Th,params:e,operation:"launch deploy-selected workflow",argument:I=>I[0]??"version"});let i=await _o(t),a=io(i);h.addOption("--version",a);let c=await Je(),l=bt(await Rt(gr),c),d="";r?d=r:(h.setInteractive(),d=await fn(l,"launch deploy-selected workflow")),h.addOption("--env",d),Tr(d,"launch deploy-selected workflow",c),Ss({env:d,branch:i});let p=await T(),m=await Io(p,gr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${gr}`,stderrExcerpt:`no services found in .github/workflows/${gr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await O(I=>fT({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},I),{whenHeadless:"refuse"})),h.addOption("--services",g),g.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=g.filter(I=>!m.includes(I));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 R=await Oo(p,gr),w=g.filter(I=>{let P=R.get(I);return P!==void 0&&!P.includes(d)});if(w.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(I=>`${I} deploys only to: ${(R.get(I)??[]).join(", ")}`).join("; "),stderrExcerpt:`${gr} gates these services out of ${d}: ${w.join(", ")}`});let $=o??!1;$&&h.addOption("--skip-terraform",!0);let B=I=>{let P={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:$,success:I};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await No({confirmedCommand:s,branch:i,env:d}))return u.info("Deployment cancelled"),B(!1);try{sd.quiet=!0;let I=g.flatMap(le=>["-f",`${le}=true`]);return await sd`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${I} ${$?["-f","skip_terraform_deploy=true"]:[]}`,sd.quiet=!1,u.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),B(!0)}catch(I){throw u.error({error:I},"\u274C Error launching workflow"),new f(I,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},id=S({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Th,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:xe.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:xe.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:xe.array(xe.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:xe.boolean().optional().describe("Skip the terraform deployment stage."),confirm:xe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:xe.string().describe("The release branch that was deployed"),version:xe.string().describe("The version that was deployed"),environment:xe.string().describe("The environment deployed to"),services:xe.array(xe.string()).describe("The services that were deployed"),skipTerraformDeploy:xe.boolean().describe("Whether terraform deployment was skipped"),success:xe.boolean().describe("Whether the deployment was successful")},handler:Pi});import{z as Mt}from"zod";var Ei=async()=>{let t=(await F()).flatMap(i=>{let a=G(i.branch);return a?[{version:X(a),jiraKey:re(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Gs(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=so(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${p}`});u.info(`All release branches:
393
395
  `),u.info(`
394
396
  ${o.join(`
395
397
  `)}
396
- `);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}},Ml=S({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:Nt.array(Nt.object({version:Nt.string().describe("Release version"),type:Nt.enum(["regular","hotfix"]).describe("Release type"),description:Nt.string().nullable().describe("Jira version description"),releaseDate:Nt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Nt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Nt.number().describe("Number of release branches")},handler:di});import XE from"node:process";var jl=e=>({...e}),Fl=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=XE.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},ui=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(`
397
- `)};import ux from"@inquirer/checkbox";import px from"@inquirer/confirm";import mx from"@inquirer/select";import{spawn as fx}from"node:child_process";import gx from"node:process";import{z as q}from"zod";import{$ as To}from"zx";import{$ as xo}from"zx";var ZE=async e=>{let t=xo.quiet;xo.quiet=!0;try{let r=`/${e}/environment`,n=await xo`aws sts get-caller-identity --query Account --output text`,o=await xo`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{xo.quiet=t}},qg=(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`})},Yg=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"})},zg=(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`})},Ll=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Sr(t,`deploy to "${t}"`,i),zg(t,s),Yg({env:t,isShared:n,isClean:o});let a=await ZE(r);return qg(t,a),{identity:a}};import Xg from"node:fs/promises";import pi from"node:path";var QE="devops/scripts",ex=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,tx=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,rx=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,nx=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Bl=async e=>{let t=pi.resolve(e,QE),r;try{r=await Xg.readdir(t)}catch{return[]}let n=await Pl(e);return(await Promise.all(r.map(s=>({entry:s,match:ex.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=pi.resolve(t,s),c=i?.groups?.service??"",l=sx(await ox(a));return{name:c,scriptPath:a,allowedEnvs:El(ix(l),n.get(c)),ssmPrefix:cx(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},ox=async e=>{try{return await Xg.readFile(e,"utf-8")}catch{return""}},sx=e=>e.split(`
398
- `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),ix=e=>{let t=e.reduce((n,{text:o})=>n??tx.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},ax=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},cx=e=>{for(let{line:t,text:r}of e){let n=nx.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=rx.exec(r)?.groups?.arg;if(o!==void 0&&ax(o))return{unparseable:{line:t,text:r.trim()}}}return null},lx=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],pi.basename(r.scriptPath)]);return t},dx=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${pi.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("; ")})},Zg=e=>{dx(e);let t=lx(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},mi=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Vl=(e,t)=>e.filter(r=>mi(r,t));var Ul="deploy-all.yml",eh="/bin/sh",hx=async()=>{let e=To.quiet;To.quiet=!0;try{let t=await To`gh run list --workflow=${Ul} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{To.quiet=e}},yx=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await O(o=>ux({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},vx=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return ge()&&as(i,{env:t,services:n,accountId:o,shared:r}),r?O(a=>mx({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):O(a=>px({message:i,default:!1},a),{whenHeadless:"refuse"})},wx=(e,t,r)=>new Promise((n,o)=>{let s=fx(eh,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),kx=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){u.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await wx(a,r,n);if(c!==0){i.push(a.name),u.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),u.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},bx=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&&!mi(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))},Wl=e=>{let{env:t,accountId:r,names:n,built:o,deployed:s,failed:i,dryRun:a,success:c}=e,l={environment:t,accountId:r,services:n,deployed:s,failed:i,contract:jl(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Rx=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),yx(r,o))},th=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await E(),c=await Bl(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=Zg(c);await Je({provider:Jl[t],params:e,operation:"deploy locally",argument:"env"});let d=await Ue(),p=kt(await bt(Ul),d),m=r??"";m||(h.setInteractive(),m=await ln(p,"deploy locally")),h.addOption("--env",m);let g=Vl(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await Rx({selection:t,eligible:g,service:n,env:m}),R=bx({names:y,services:c,env:m});if(t==="selected")for(let Ve of y)h.addOption("--service",Ve);let w=Pn(m),$=await wr(),D=(await To`git rev-parse HEAD`.quiet()).stdout.trim(),A=await qu(),P=Fl({env:m,branch:$,sha:D,isClean:A});i&&u.info(`Deploy contract for ${m}:
399
- ${ui(P)}`);let U=(await Ll({env:m,project:l,isShared:w,isClean:A,runningEnvs:await hx(),protectedEnvAccess:d})).identity.accountId;if(s)return u.info([`Would deploy to "${m}" (AWS account ${U}) from this machine`,`Preflight parameter: /${l}/environment`,ui(P),"Commands:",...R.map(Ve=>` ${eh} ${Ve.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
400
- `)),Wl({env:m,accountId:U,names:y,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await vx({env:m,isShared:w,names:y,accountId:U}))return u.info("Deployment cancelled"),Wl({env:m,accountId:U,names:y,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&u.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:ue,failed:pt}=await kx({chosen:R,childEnv:P.childEnv,cwd:a,env:m});return pt.length>0&&(u.error(`Partial deploy to "${m}": succeeded [${ue.join(", ")||"none"}], failed [${pt.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),gx.exitCode=1),h.print(),Wl({env:m,accountId:U,names:y,built:P,deployed:ue,failed:pt,dryRun:!1,success:pt.length===0})},rh=async e=>th(e,"all"),nh=async e=>th(e,"selected"),oh='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.',sh={env:q.string().optional().describe('Target environment, e.g. "dev" or a personal env like "arthur". Omit it to be offered the environments this project may reach.'),dryRun:q.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:q.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},ih={environment:q.string().describe("Environment deployed to"),accountId:q.string().describe("AWS account the deploy targeted"),services:q.array(q.string()).describe("Services requested"),deployed:q.array(q.string()).describe("Services that completed successfully"),failed:q.array(q.string()).describe("Services that failed"),contract:q.record(q.string(),q.string()).describe("Build contract passed to the scripts"),strippedVars:q.array(q.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:q.boolean().describe("Whether this was a dry run"),success:q.boolean().describe("Whether every requested service deployed")},Qg=e=>cr({workflowFile:Ul,fields:["env"],toolName:e}),Jl={all:Qg("local-deploy-all"),selected:Qg("local-deploy-selected")},Gl=S({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${oh}`,requiresHumanConfirm:!0,formProvider:Jl.all,inputSchema:sh,outputSchema:ih,handler:rh}),Kl=S({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${oh}`,requiresHumanConfirm:!0,formProvider:Jl.selected,inputSchema:{...sh,service:q.array(q.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:ih,handler:nh});import Ex from"@inquirer/confirm";import fi from"@inquirer/input";import dh from"@inquirer/select";import ql from"node:process";import{z as V}from"zod";import{z as Co}from"zod";var dn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var lh=2500,ah=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ch=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,Sx=async()=>{let e=await lo();return{regular:nn(e,"regular"),hotfix:nn(e,"hotfix")}},Px=(e,t)=>e===null?(u.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?(u.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).`,Hl=(e={})=>{let t=e.hintBudgetMs??lh;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=>ah(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await dn(Sx(),t);return Co.object({type:Co.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Co.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. ${Px(r,t)}`),description:Co.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Co.string().optional().describe("Optional. Planned production date, yyyy-mm-dd. Becomes the Jira fix version's release date; delivery overwrites it with the actual date. On the re-run it is passed as <token>@yyyy-mm-dd inside -r.")})},toArgs:(r,n)=>{let o=typeof r.release=="string"?r.release.trim():"";if(o==="")return null;let s=r.type==="hotfix"?"hotfix":"regular",i=ch(r.description),a=ch(r.releaseDate),c=zs(o);return{...ah(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var xx='"1.2.5" or "next"',Yl=(e,t)=>{try{return rl(e,t)}catch(r){throw r instanceof rr?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 Ju?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}},Tx=async(e,t)=>{let r=nn(e,t),n=r?` [${r}]`:"",o=(await O(i=>fi({message:` Version (e.g. ${xx})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(u.error("No version provided. Exiting..."),ql.exit(1)),s},Cx=async()=>{let e=(await O(t=>fi({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(u.error("No name provided. Exiting..."),ql.exit(1));try{Qo(e)}catch(t){let r=t instanceof Error?t.message:String(t);u.error(`${r} Exiting...`),ql.exit(1)}return e},$x=async()=>(await O(e=>fi({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:co},e),{whenHeadless:"refuse"})).trim(),Ax=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await O(m=>dh({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 O(m=>dh({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),l;if(a==="name"){let m=await Cx();l=Yl([{name:m,type:c}],[])[0]}else{let m=await Tx(await n(),c);l=Yl([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push($t(`v${l.id.raw}`))}let d=(await O(m=>fi({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await $x();o.push({...l,...d!==""?{description:d}:{},...p!==""?{releaseDate:p}:{}}),s=await O(m=>Ex({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},Ox=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 ")},uh=e=>{for(let t of e)h.addOption("--release",tl(t))},Ix=async(e,t)=>{if(e&&e.length>0){let n=nl(e)?await t():[],o=Yl(e,n);return uh(o),o}if(fe())throw new x({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 r=await Ax(t);return uh(r),r},Dx=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"})},Nx=async(e,t)=>{let r=e.map(Ox).join(`
401
- - `);await B(t,`Create the following ${e.length} release(s)?
398
+ `);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}},ad=S({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:Mt.array(Mt.object({version:Mt.string().describe("Release version"),type:Mt.enum(["regular","hotfix"]).describe("Release type"),description:Mt.string().nullable().describe("Jira version description"),releaseDate:Mt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Mt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Mt.number().describe("Number of release branches")},handler:Ei});import gT from"node:process";var cd=e=>({...e}),ld=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=gT.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},xi=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(`
399
+ `)};import $T from"@inquirer/checkbox";import AT from"@inquirer/confirm";import OT from"@inquirer/select";import{spawn as IT}from"node:child_process";import DT from"node:process";import{z}from"zod";import{$ as jo}from"zx";import{$ as Mo}from"zx";var hT=async e=>{let t=Mo.quiet;Mo.quiet=!0;try{let r=`/${e}/environment`,n=await Mo`aws sts get-caller-identity --query Account --output text`,o=await Mo`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{Mo.quiet=t}},Ch=(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`})},$h=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"})},Ah=(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`})},dd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Tr(t,`deploy to "${t}"`,i),Ah(t,s),$h({env:t,isShared:n,isClean:o});let a=await hT(r);return Ch(t,a),{identity:a}};import Oh from"node:fs/promises";import Ti from"node:path";var yT="devops/scripts",vT=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,wT=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,kT=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,bT=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,ud=async e=>{let t=Ti.resolve(e,yT),r;try{r=await Oh.readdir(t)}catch{return[]}let n=await Yl(e);return(await Promise.all(r.map(s=>({entry:s,match:vT.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ti.resolve(t,s),c=i?.groups?.service??"",l=ST(await RT(a));return{name:c,scriptPath:a,allowedEnvs:zl(PT(l),n.get(c)),ssmPrefix:xT(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},RT=async e=>{try{return await Oh.readFile(e,"utf-8")}catch{return""}},ST=e=>e.split(`
400
+ `).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),PT=e=>{let t=e.reduce((n,{text:o})=>n??wT.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},ET=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},xT=e=>{for(let{line:t,text:r}of e){let n=bT.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=kT.exec(r)?.groups?.arg;if(o!==void 0&&ET(o))return{unparseable:{line:t,text:r.trim()}}}return null},TT=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ti.basename(r.scriptPath)]);return t},CT=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ti.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("; ")})},Ih=e=>{CT(e);let t=TT(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},Ci=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),pd=(e,t)=>e.filter(r=>Ci(r,t));var fd="deploy-all.yml",Nh="/bin/sh",NT=async()=>{let e=jo.quiet;jo.quiet=!0;try{let t=await jo`gh run list --workflow=${fd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{jo.quiet=e}},_T=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await O(o=>$T({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},MT=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return J()&&ks(i,{env:t,services:n,accountId:o,shared:r}),r?O(a=>OT({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):O(a=>AT({message:i,default:!1},a),{whenHeadless:"refuse"})},jT=(e,t,r)=>new Promise((n,o)=>{let s=IT(Nh,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),FT=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){u.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await jT(a,r,n);if(c!==0){i.push(a.name),u.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),u.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},LT=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&&!Ci(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))},md=e=>{let{env:t,accountId:r,names:n,built:o,deployed:s,failed:i,dryRun:a,success:c}=e,l={environment:t,accountId:r,services:n,deployed:s,failed:i,contract:cd(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},BT=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),_T(r,o))},_h=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await T(),c=await ud(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=Ih(c);await Ge({provider:gd[t],params:e,operation:"deploy locally",argument:"env"});let d=await Je(),p=bt(await Rt(fd),d),m=r??"";m||(h.setInteractive(),m=await fn(p,"deploy locally")),h.addOption("--env",m);let g=pd(c,m);if(g.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await BT({selection:t,eligible:g,service:n,env:m}),R=LT({names:y,services:c,env:m});if(t==="selected")for(let ma of y)h.addOption("--service",ma);let w=On(m),$=await Pr(),B=(await jo`git rev-parse HEAD`.quiet()).stdout.trim(),I=await Rp(),P=ld({env:m,branch:$,sha:B,isClean:I});i&&u.info(`Deploy contract for ${m}:
401
+ ${xi(P)}`);let te=(await dd({env:m,project:l,isShared:w,isClean:I,runningEnvs:await NT(),protectedEnvAccess:d})).identity.accountId;if(s)return u.info([`Would deploy to "${m}" (AWS account ${te}) from this machine`,`Preflight parameter: /${l}/environment`,xi(P),"Commands:",...R.map(ma=>` ${Nh} ${ma.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
402
+ `)),md({env:m,accountId:te,names:y,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await MT({env:m,isShared:w,names:y,accountId:te}))return u.info("Deployment cancelled"),md({env:m,accountId:te,names:y,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&u.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:Ut,failed:es}=await FT({chosen:R,childEnv:P.childEnv,cwd:a,env:m});return es.length>0&&(u.error(`Partial deploy to "${m}": succeeded [${Ut.join(", ")||"none"}], failed [${es.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),DT.exitCode=1),h.print(),md({env:m,accountId:te,names:y,built:P,deployed:Ut,failed:es,dryRun:!1,success:es.length===0})},Mh=async e=>_h(e,"all"),jh=async e=>_h(e,"selected"),Fh='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.',Lh={env:z.string().optional().describe('Target environment, e.g. "dev" or a personal env like "arthur". Omit it to be offered the environments this project may reach.'),dryRun:z.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:z.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Bh={environment:z.string().describe("Environment deployed to"),accountId:z.string().describe("AWS account the deploy targeted"),services:z.array(z.string()).describe("Services requested"),deployed:z.array(z.string()).describe("Services that completed successfully"),failed:z.array(z.string()).describe("Services that failed"),contract:z.record(z.string(),z.string()).describe("Build contract passed to the scripts"),strippedVars:z.array(z.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:z.boolean().describe("Whether this was a dry run"),success:z.boolean().describe("Whether every requested service deployed")},Dh=e=>fr({workflowFile:fd,fields:["env"],toolName:e}),gd={all:Dh("local-deploy-all"),selected:Dh("local-deploy-selected")},hd=S({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Fh}`,requiresHumanConfirm:!0,formProvider:gd.all,inputSchema:Lh,outputSchema:Bh,handler:Mh}),yd=S({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Fh}`,requiresHumanConfirm:!0,formProvider:gd.selected,inputSchema:{...Lh,service:z.array(z.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Bh,handler:jh});import UT from"@inquirer/confirm";import $i from"@inquirer/input";import Jh from"@inquirer/select";import wd from"node:process";import{z as U}from"zod";import{z as Fo}from"zod";var gn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Uh=2500,Wh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Vh=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,WT=async()=>{let e=await ko();return{regular:dn(e,"regular"),hotfix:dn(e,"hotfix")}},VT=(e,t)=>e===null?(u.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?(u.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,vd=(e={})=>{let t=e.hintBudgetMs??Uh;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=>Wh(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await gn(WT(),t);return Fo.object({type:Fo.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Fo.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. ${VT(r,t)}`),description:Fo.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Fo.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=Vh(r.description),a=Vh(r.releaseDate),c=di(o);return{...Wh(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var JT='"1.2.5" or "next"',kd=(e,t)=>{try{return bl(e,t)}catch(r){throw r instanceof cr?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 vp?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}},GT=async(e,t)=>{let r=dn(e,t),n=r?` [${r}]`:"",o=(await O(i=>$i({message:` Version (e.g. ${JT})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(u.error("No version provided. Exiting..."),wd.exit(1)),s},KT=async()=>{let e=(await O(t=>$i({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(u.error("No name provided. Exiting..."),wd.exit(1));try{ps(e)}catch(t){let r=t instanceof Error?t.message:String(t);u.error(`${r} Exiting...`),wd.exit(1)}return e},HT=async()=>(await O(e=>$i({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:wo},e),{whenHeadless:"refuse"})).trim(),qT=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await O(m=>Jh({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 O(m=>Jh({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),l;if(a==="name"){let m=await KT();l=kd([{name:m,type:c}],[])[0]}else{let m=await GT(await n(),c);l=kd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Ot(`v${l.id.raw}`))}let d=(await O(m=>$i({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await HT();o.push({...l,...d!==""?{description:d}:{},...p!==""?{releaseDate:p}:{}}),s=await O(m=>UT({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},YT=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 ")},Gh=e=>{for(let t of e)h.addOption("--release",kl(t))},zT=async(e,t)=>{if(e&&e.length>0){let n=Rl(e)?await t():[],o=kd(e,n);return Gh(o),o}if(ye())throw new x({status:"argument_required",argument:"release",agentMode:N.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await qT(t);return Gh(r),r},XT=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"})},ZT=async(e,t)=>{let r=e.map(YT).join(`
403
+ - `);await V(t,`Create the following ${e.length} release(s)?
402
404
  - ${r}
403
- `),h.addOption("--yes",!0)},_x=async e=>{let{entry:t,jiraConfig:r}=e,n=z(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await _r({operation:`create release ${o}`});let s=await kc(t.type),i=await bc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return u.info(`\u2705 Successfully created release: ${o} (${t.type})`),u.info(`\u{1F517} GitHub PR: ${i.prUrl}`),u.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
404
- `),{result:i}}catch(s){let i=Hn(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 u.error(`\u274C ${a.message}
405
- `),{failure:{version:n,error:a.message}}}},Mx=(e,t,r)=>{t===e?u.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(u.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),u.warn(`\u274C ${r} release(s) failed.`)):u.error(`\u274C All ${e} release branch(es) failed to create.`)},ph=Hl(),gi=async e=>{let{releases:t,confirmedCommand:r}=e;await be({operation:"create release"}),await Je({provider:ph,params:e,operation:"create release",argument:"release"});let n=await Wr(),o=null,i=await Ix(t,async()=>(o===null&&(o=await lo()),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"});Dx(i),await Wn({operation:"create release",base:ze(i[0].type)}),await Nx(i,!!r);let a=[],c=[];for(let d of i){let{result:p,failure:m}=await _x({entry:d,jiraConfig:n});p&&a.push(p),m&&c.push(m)}Mx(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},zl=S({name:"release-create",requiresHumanConfirm:!0,formProvider:ph,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:V.array(V.object({version:V.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:V.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:V.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:V.string().optional().describe("Optional description for the Jira version."),releaseDate:qc.optional().describe('Optional planned production date, yyyy-mm-dd. Written to the Jira fix version as its release date; "release deliver" overwrites it with the actual date. Rides in the CLI spec as "<token>@yyyy-mm-dd".')}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>{let t={...e.description?{description:e.description}:{},...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}};return e.name!==void 0?{name:e.name,type:e.type,...t}:{version:e.version,type:e.type,...t}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description. Optional over MCP: omit it to have the human fill one release from a form.').optional(),confirm:V.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:V.array(V.string()).describe("List of created release branch names"),successCount:V.number().describe("Number of releases created successfully"),failureCount:V.number().describe("Number of releases that failed"),releases:V.array(V.object({version:V.string().describe("Version number"),type:V.enum(["regular","hotfix"]).describe("Release type"),branchName:V.string().describe("Release branch name"),prUrl:V.string().describe("GitHub PR URL"),jiraVersionUrl:V.string().describe("Jira version URL"),releaseDate:V.string().nullable().describe("The release date the Jira fix version now carries (yyyy-mm-dd), or null when it has none")})).describe("Detailed information for each created release with URLs"),failedReleases:V.array(V.object({version:V.string().describe("Version number that failed"),error:V.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:gi});import mh from"@inquirer/input";import{z as Ne}from"zod";var fh=["description","releaseDate"],jx=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await ne(),o=await Et(oe({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},Fx=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},Lx=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await O(o=>mh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},Bx=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await O(o=>mh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:co},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:tr(n)},Vx=e=>{if(e!==void 0)return e===""?null:e},Wx=async e=>(h.setInteractive(),{description:await Lx(e.description),releaseDate:await Bx(e.releaseDate)}),Xl=e=>e??"(none)",Ux=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Xl(t.releaseDate)} \u2192 ${Xl(r.releaseDate)}`,hi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=Vx(n),i=await Wr(),a;t?(a=ct(t),await Fx(a)):(h.setInteractive(),a=(await jx()).branch);let c=J(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=z(c);h.addOption("--version",l);let d=te(c),p=await it(d,i);if(!p)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&ge())throw new x({status:"argument_required",argument:"description",agentMode:I.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await Wx(m),R=fh.filter(Y=>y[Y]!==m[Y]),w=R.includes("description"),$=R.includes("releaseDate"),D=Yt(i,p),A=Y=>{let U={version:l,branch:a,jiraVersionUrl:D,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:R,changed:Y};return{content:k(JSON.stringify(U,null,2)),structuredContent:U}};if(R.length===0)return u.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${Xl(m.releaseDate)}`),h.print(),A(!1);w&&h.addOption("--description",y.description),$&&h.addOption("--release-date",y.releaseDate??"");let P=R.map(Y=>Ux(Y,m,y));return await B(o,`Update ${d}?
405
+ `),h.addOption("--yes",!0)},QT=async e=>{let{entry:t,jiraConfig:r}=e,n=X(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Wr({operation:`create release ${o}`});let s=await Lc(t.type),i=await Bc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return u.info(`\u2705 Successfully created release: ${o} (${t.type})`),u.info(`\u{1F517} GitHub PR: ${i.prUrl}`),u.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
406
+ `),{result:i}}catch(s){let i=no(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return u.error(`\u274C ${a.message}
407
+ `),{failure:{version:n,error:a.message}}}},eC=(e,t,r)=>{t===e?u.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(u.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),u.warn(`\u274C ${r} release(s) failed.`)):u.error(`\u274C All ${e} release branch(es) failed to create.`)},Kh=vd(),Ai=async e=>{let{releases:t,confirmedCommand:r}=e;await Pe({operation:"create release"}),await Ge({provider:Kh,params:e,operation:"create release",argument:"release"});let n=await qr(),o=null,i=await zT(t,async()=>(o===null&&(o=await ko()),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"});XT(i),await Zn({operation:"create release",base:Xe(i[0].type)}),await ZT(i,!!r);let a=[],c=[];for(let d of i){let{result:p,failure:m}=await QT({entry:d,jiraConfig:n});p&&a.push(p),m&&c.push(m)}eC(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},bd=S({name:"release-create",requiresHumanConfirm:!0,formProvider:Kh,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:U.array(U.object({version:U.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:U.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:U.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:U.string().optional().describe("Optional description for the Jira version."),releaseDate:ml.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:U.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:U.array(U.string()).describe("List of created release branch names"),successCount:U.number().describe("Number of releases created successfully"),failureCount:U.number().describe("Number of releases that failed"),releases:U.array(U.object({version:U.string().describe("Version number"),type:U.enum(["regular","hotfix"]).describe("Release type"),branchName:U.string().describe("Release branch name"),prUrl:U.string().describe("GitHub PR URL"),jiraVersionUrl:U.string().describe("Jira version URL"),releaseDate:U.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:U.array(U.object({version:U.string().describe("Version number that failed"),error:U.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Ai});import Hh from"@inquirer/input";import{z as Me}from"zod";var qh=["description","releaseDate"],tC=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await se(),o=await Tt(ie({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},rC=async e=>{let r=(await F()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},nC=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await O(o=>Hh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},oC=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await O(o=>Hh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:wo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:ar(n)},sC=e=>{if(e!==void 0)return e===""?null:e},iC=async e=>(h.setInteractive(),{description:await nC(e.description),releaseDate:await oC(e.releaseDate)}),Rd=e=>e??"(none)",aC=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Rd(t.releaseDate)} \u2192 ${Rd(r.releaseDate)}`,Oi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=sC(n),i=await qr(),a;t?(a=lt(t),await rC(a)):(h.setInteractive(),a=(await tC()).branch);let c=G(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=X(c);h.addOption("--version",l);let d=re(c),p=await at(d,i);if(!p)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&J())throw new x({status:"argument_required",argument:"description",agentMode:N.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await iC(m),R=qh.filter(le=>y[le]!==m[le]),w=R.includes("description"),$=R.includes("releaseDate"),B=tr(i,p),I=le=>{let te={version:l,branch:a,jiraVersionUrl:B,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:R,changed:le};return{content:k(JSON.stringify(te,null,2)),structuredContent:te}};if(R.length===0)return u.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${Rd(m.releaseDate)}`),h.print(),I(!1);w&&h.addOption("--description",y.description),$&&h.addOption("--release-date",y.releaseDate??"");let P=R.map(le=>aC(le,m,y));return await V(o,`Update ${d}?
406
408
  ${P.join(`
407
409
  `)}
408
- `),h.addOption("--yes",!0),await Vr({versionId:p.id,...w?{description:y.description}:{},...$?{releaseDate:y.releaseDate}:{}},i),w&&await Cs({branch:a,body:Kn(D,y.description)}),u.info(`\u2705 Updated ${R.join(" and ")} for ${d}`),u.info(`\u{1F517} Jira Version: ${D}`),u.info(`\u{1F517} PR branch: ${a}
409
- `),h.print(),A(!0)},Zl=S({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:Ne.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ne.string().optional().describe("New description. Empty string clears the description."),releaseDate:Yc.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ne.string().describe("Release version"),branch:Ne.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ne.string().describe("Jira fix version URL"),previousDescription:Ne.string().describe("The description before the update"),newDescription:Ne.string().describe("The description after the update"),previousReleaseDate:Ne.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ne.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ne.array(Ne.enum(fh)).describe("The fields whose value actually changed"),changed:Ne.boolean().describe("Whether anything actually changed")},handler:hi});import{z as j}from"zod";import{$ as od}from"zx";import gh from"node:fs/promises";import yi from"node:path";var Ql=async e=>{let{workspacePath:t,folderPaths:r}=e,n=yi.dirname(t),o;try{o=await gh.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>yi.resolve(n,d.path))),c=[],l=[];for(let d of r){let p=yi.resolve(d);if(a.has(p)){l.push(d);continue}let m=yi.relative(n,p);i.push({path:m}),a.add(p),c.push(d)}return s.folders=i,await gh.writeFile(t,`${JSON.stringify(s,null,2)}
410
- `,"utf-8"),{added:c,skipped:l}};import{$ as Jx}from"zx";var ed=async e=>{await Jx`cursor ${e}`};import hh from"node:fs/promises";import vi from"node:path";var td=async e=>{let{workspacePath:t,folderPaths:r}=e,n=vi.dirname(t),o;try{o=await hh.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=>vi.resolve(m))),c=new Set,l=i.filter(m=>{let g=vi.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await hh.writeFile(t,`${JSON.stringify(s,null,2)}
411
- `,"utf-8");let d=[],p=[];for(let m of r){let g=vi.resolve(m);c.has(g)?d.push(m):p.push(m)}return{removed:d,notFound:p}};import yh from"node:path";var $o=(e,t)=>yh.isAbsolute(e)?e:yh.resolve(t,e);var rd=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await M(),s=yt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await Gx({ide:c,projectRoot:t,folderPaths:i}));return a},Gx=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return u.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=$o(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await Ql({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return u.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await ed(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var dr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await M(),s=yt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await Kx({ide:c,projectRoot:t,folderPaths:i}));return a},Kx=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=$o(t.config.workspaceConfigPath,r);try{let{removed:s}=await td({workspacePath:o,folderPaths:n});return s.length>0&&u.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return u.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var ur=["workspace","none"];import{z as vh}from"zod";var bh=2500,wi="release-remove",wh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hx=e=>e.version===void 0||e.version==="",qx=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===Jn?{outcome:"empty"}:{outcome:"failed"}}},kh=(e,t)=>(e===null?u.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${wi}`}):e.outcome==="failed"?u.info({msg:`Tool execution form enumeration failed (gh pr list): ${wi}`}):u.info({msg:`Tool execution form options empty (open release PRs): ${wi}`}),null),Yx=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Is(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(te(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},zx=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(u.info({msg:`Tool execution form descriptions unavailable (timeout): ${wi}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},nd=(e={})=>{let t=e.fetchBudgetMs??bh;return{message:"Choose the release to remove. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:r=>wh(r)&&Hx(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([dn(qx(),t),dn(ne(),t)]);if(r===null||r.outcome!=="listed")return kh(r,t);let o=Yx(r.prs,n);return o.length===0?kh({outcome:"empty"},t):vh.object({version:vh.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${zx(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:{...wh(n)?n:{},version:r.version}}};var Rh=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],bi={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"},pr="remove a release",Le=e=>{throw u.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},Sh=(e,t)=>{throw u.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new x({...e,agentMode:I.source},2,t)},Xx=e=>{fe()&&(e.version||Sh({status:"argument_required",argument:"version"},{operation:pr,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&&Sh({status:"refused"},{operation:pr,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"}))},Eh=e=>{e.pr?.state==="MERGED"&&Le({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`})},Zx=(e,t)=>{if(t.skipJira||(e.jiraConfig||Le({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)&&Le({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||Le({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)`}))},Qx=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Le({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"})},eT=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Le({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(", ")}`})},tT=async e=>(await od`git -C ${e} status --porcelain`).stdout.split(`
412
- `).map(r=>r.trimEnd()).filter(r=>r.length>0),rT=async e=>{try{let{terminals:t}=await Cp(e);return t.filter(r=>r.connected).length}catch(t){return u.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},nT=async e=>{let t=await ls([e]);if(t!==null)throw u.warn({operation:pr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new x({status:"refused",reason:"orca_caller_inside_target",agentMode:I.source},2,{operation:pr,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`})},oT=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await at();if(!n)return r;let o=await it(te(e),n),s=t.moveIssuesTo?await sT(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:Yt(n,o)}}},sT=async(e,t)=>{let r=await it(e,t);return r||Le({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}"`})},iT=async(e,t)=>{let r=J(e);r||Le({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 E(),o=`${n}${pe}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([Te("release"),jr(e),Ce(n,`refs/heads/${e}`),kr(n,e)]),d=i.includes(e);return d&&await nT(s),{...await oT(r,t),branch:e,id:r,label:z(r),baseBranch:a?.baseRefName??ze("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await rT(s):0,worktreeDirty:d?await tT(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Ph=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}),aT=(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}`},cT=(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: ${aT(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
413
- `)},ki=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},lT=e=>typeof e=="string"?e:e.outcome;async function Ao(e,t,r){try{let n=await r(),o=lT(n);return t.push({step:e}),u.info({step:e,outcome:o},`\u2705 ${bi[e]} \u2014 ${o}`),n}catch(n){throw new ki(e,n)}}var dT=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),u.warn({err:It(n),step:e},`\u26A0\uFE0F ${bi[e]} failed (non-blocking)`)}},uT=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,pT=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>uT(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Rh.indexOf(r)+1} of ${Rh.length} (${bi[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},mT=async e=>{let t=await wo(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}},fT=e=>{let t=e.map(s=>({provider:s.provider,outcome:gT(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}},gT=e=>e.removed.length>0?"verified":"attempted",hT=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await dT("ide-folders",r,async()=>{let o=await dr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=fT(o)}),u.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${bi["ide-folders"]} \u2014 ${n.outcome}`),n},yT=async e=>{let t=await jr(e.branch);if(Eh({...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 od`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},vT=async e=>(await wr()===e.branch&&await od`git switch ${e.baseBranch}`,await ts(e.branch),await zu(e.branch)?Le({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"),wT=async e=>(await rs(e.branch),e.remoteTipSha?"deleted":"absent"),kT=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}\``;Le({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}`})},bT=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await kT(e,e.jira,e.jiraConfig),u.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await wc({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),RT=(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}),ST=async(e,t,r)=>{let n=await Ao("worktree",r,()=>mT(e)),o=await hT(e,n.removedBranches,r),s=await Ao("pr",r,()=>yT(e));u.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Ao("local-branch",r,()=>vT(e)),a=await Ao("remote-branch",r,()=>wT(e)),c=await Ao("jira",r,()=>bT(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},PT=async(e,t)=>{let r=[];try{return RT(e,await ST(e,t,r))}catch(n){throw n instanceof ki?pT({plan:e,step:n.step,done:r,cause:n.reason}):n}},ET=async e=>{if(e)return ct(e);h.setInteractive();let[t,r]=await Promise.all([ne(),F()]),n=r.map(s=>s.branch);n.length===0&&Le({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 Et(oe({branches:n,descriptions:t,types:o}))}catch(s){throw ve(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"})}},xh=nd(),Ri=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await be({operation:pr}),await M(),await Je({provider:xh,params:e,operation:pr,argument:"version"}),Xx(e);try{let s=await iT(await ET(r),e);u.debug({plan:Ph(s)},"release remove: resolved plan"),Eh(s),Zx(s,e),Qx(s),await Wn({operation:`remove release ${s.label}`,base:s.baseBranch}),eT(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await B(t,cT(s,!!o),{throwOnDecline:!0,plan:{...Ph(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await PT(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw ve(s)||nt(s)||s instanceof f?s:(u.error({err:It(s)},"\u274C Error removing release"),new f(s,{operation:pr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},sd=S({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:xh,inputSchema:{version:j.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:j.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:j.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:j.string().describe("The release branch that was targeted"),version:j.string().describe('The release label (e.g. "1.2.5")'),baseBranch:j.string().describe("The branch HEAD was moved to before the local delete"),worktree:j.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:j.object({outcome:j.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:j.array(j.object({provider:j.string(),outcome:j.enum(["verified","attempted","skipped"]),removed:j.array(j.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:j.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:j.number().nullable().describe("The pull request number, or null when none exists"),localBranch:j.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:j.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:j.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:j.string().nullable().describe("The origin tip before deletion"),jira:j.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:j.object({id:j.string(),name:j.string(),url:j.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Ri});import{spawnSync as $T}from"node:child_process";import{homedir as AT}from"node:os";import OT from"node:process";var xT=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},TT=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},CT=(e,t)=>{let r=xT(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},Oo=(e,t)=>{let r=[...TT(e),...CT(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Io=e=>e.steps.map(mt);var IT=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],DT=e=>{let t={...Eu(e)};for(let r of IT)delete t[r];return t},id=(e,t,r={})=>{let n=r.spawnSync??$T,o=r.env??OT.env,s=(r.agentMode??fe)(),i=Io(e),a=Oo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:MT({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??NT}):{ran:!1,commands:i,refusedBecause:a.reasons}},NT=e=>{u.info(e)},Ch=64,_T=Ch*1024*1024,MT=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=DT(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:_T,cwd:AT(),env:s}),l=WT(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},jT=5,FT=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Th=e=>e==null?[]:String(e).split(`
414
- `).map(t=>t.trim()).filter(t=>t.length>0),LT=e=>{let t=Th(e.stderr),r=Th(e.stdout),n=[...t,...r].filter(s=>FT.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-jT).join(" / ")},BT="ENOBUFS",VT=e=>e.error?.code===BT,WT=e=>{if(VT(e))return`terminated after exceeding the ${Ch} 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=LT(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var UT=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},JT=e=>{let t=Ie(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},GT=(e,t)=>{let r=JT(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=Oo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Io(r),context:n}},Si=async(e=er,t=oo())=>{let r=await io(er,t),n={owner:null,present:UT(r)},o=Hc(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>GT(s.get(a),n)),context:n}};var ad=(e,t)=>({...Do(e),action:"skipped",commands:e.commands,detail:t}),Do=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),$h=(e,t)=>e.action==="none"?ad(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?ad(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Do(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},KT=(e,t)=>t.ran?t.ok?{...Do(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Do(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Do(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},cd=async e=>{let t=e.run??id,{plans:r}=await Si(e.ids,e.probeDeps),n=[];for(let o of r){let s=$h(o,e.mode);if(s!==null){n.push(s);continue}n.push(KT(o,t(o.recipe,o.context)))}return n},ld=async(e,t)=>{let{plans:r}=await Si(e,t);return r.map(n=>$h(n,"converge")??ad(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import cC from"node:process";import{z as T}from"zod";var dd={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},HT=Object.keys(dd).sort((e,t)=>dd[e]-dd[t]),Ah={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},Oh=new Set(["manual","warn","fail"]),ud=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return We(e)}},qT=e=>e.reduce((t,r)=>Ah[r]>Ah[t]?r:t,"skipped"),Dh=e=>e.message.trim(),YT=e=>["written","unchanged","skipped"].map(r=>{let n=e.filter(o=>o.outcome===r).length;return n>0?`${n} ${r}`:""}).filter(r=>r.length>0).join(" \xB7 "),Ih=e=>e.message===Zr,zT=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Dh(r):e.length>1?YT(e):t?"activate with the last line below":"see below"},XT=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>ud(i.outcome)),n=t.filter(i=>Oh.has(ud(i.outcome))).map(Dh),o=t.filter(i=>!Oh.has(ud(i.outcome))&&!Ih(i)),s={name:e,status:qT(r),message:zT(o,t.some(Ih))};return n.length>0?{...s,notes:n}:s},ZT=e=>({label:"Local setup",rows:HT.map(t=>XT(t,e.filter(r=>r.step===t)))}),QT=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return We(e.action)}},eC=(e,t)=>{let r=QT(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},tC=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>eC(r,t))}),rC=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return We(e)}},nC=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return We(e)}},oC=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 We(e)}},sC=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 We(e.outcome)}},iC=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return We(e)}},aC=e=>({label:"Portless service",rows:[{name:"link",status:rC(e.link),message:oC(e.link)},{name:"node",status:nC(e.node.outcome),message:sC(e.node)},iC(e.service,e.command)]}),Nh=(e,t)=>[ZT(e.init),tC(e.tools,t),aC(e.portless)],_h=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var lC=()=>{let{link:e,node:t}=Xo();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},dC=async e=>{let t=Bu(e.link).outcome,r=Lu(e.node),n=zo(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return{link:t,node:r,service:"skipped",command:null};let{state:o,stableNode:s}=await vg(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=ft(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},jh="--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.",uC=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(jh);return{ids:e.tools??t??er,mode:r?"update":"converge",skipTools:n}},Mh=(e,t)=>e instanceof Xr?e.step:t.at(-1)?.step??"zshrc",pC=async()=>{let e=[];try{await Bc(t=>{e.push(t)})}catch(t){e.push({step:Mh(t,e),outcome:"failed",message:`The ${Mh(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},mC=(e,t)=>{let r=t instanceof Error?t.message:String(t);return e.map(n=>({id:n,action:"failed",before:{present:!1,onPath:!1,version:null,manager:"unknown"},commands:[],detail:`the dependency step failed before reaching this tool: ${r}`}))},fC=async(e,t)=>{try{return e.skipTools?await ld(e.ids,t.probeDeps):await cd({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return mC(e.ids,r)}},gC=e=>({step:e.step,outcome:e.outcome,message:e.message}),Pi=async(e={})=>{let t=uC(e),r=await pC(),n=await fC(t,e),o=await dC(e.portlessDeps??lC()),s=Nh({init:r,tools:n,portless:o},{skipTools:t.skipTools});Ye({title:"infra-kit setup",sections:s},{ascii:e.ascii}),u.info(Zr),_h(s)&&(cC.exitCode=1);let i={init:r.map(gC),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},hC=T.object({step:T.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:T.enum(["written","unchanged","skipped","manual","warned","failed"]).describe("What that step did: changed something, found nothing to change, did not run, left a command for a human to run (the message carries it), failed non-fatally, or threw and ended the init half (setup exits 1)"),message:T.string().describe("The same line a human running this would have read")}),yC=T.object({id:T.string().describe("Dependency id"),action:T.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:T.object({present:T.boolean(),onPath:T.boolean(),version:T.string().nullable(),manager:T.string()}).describe("The tool\u2019s state before this run"),commands:T.array(T.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:T.string().describe("Why, in one line")}),vC=T.object({link:T.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:T.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:T.enum(["absent","converged","drifted","skipped"]).describe("The installed portless system service against the link and node: not installed, already running through both, installed but pointing elsewhere, or not judged because portless is not installed"),command:T.string().nullable().describe("The sudo `service install` command a human has to run; present if and only if service is absent or drifted, null otherwise")}),wC={init:T.array(hC).describe("One entry per init step, in the order they ran"),tools:T.array(yC).describe("One result per requested dependency"),portlessService:vC.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:T.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:T.boolean().describe("Whether anything was installed or updated"),report:T.array(T.object({label:T.string().describe("Section heading"),rows:T.array(T.object({name:T.string().describe("Init step, tool id, or portless part"),status:T.enum(["ok","changed","skipped","manual","warn","fail"]).describe("ok: nothing to change; changed: changed something; skipped: did not run; manual: not run by the CLI, the notes hold the command a human runs; warn: advisory problem; fail: failed (setup exits 1)"),message:T.string().describe("The row message, as printed"),notes:T.array(T.string()).optional().describe("Lines printed under the row, verbatim: the manual commands, warnings and failures")}))})).describe("The exact rows of the table printed on stderr; setup exits 1 iff a row is fail"),allSucceeded:T.boolean().describe("Whether no tool failed (a refusal is not a failure)")},kC={tools:T.array(T.enum(er)).optional().describe("Which tools to act on. Omit for all six."),mode:T.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:T.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},pd=S({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:kC,outputSchema:wC,requiresHumanConfirm:!0,handler:e=>Pi({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Lh}from"node:fs";import Bh from"node:path";import OC from"node:process";import{z as ut}from"zod";import{createHash as bC}from"node:crypto";import{readFileSync as RC}from"node:fs";var mr=e=>bC("sha256").update(RC(e)).digest("hex");import{readFileSync as CC,writeFileSync as $C}from"node:fs";import Ci from"node:path";import{z as tt}from"zod";var Z="vendor",SC=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),PC=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),EC=[".tsbuildinfo"],md=e=>SC.has(e),fd=e=>PC.has(e)?!0:EC.some(t=>e.endsWith(t)),Ei=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>md(o))||fd(r)};import{readdirSync as xC}from"node:fs";import gd from"node:path";var TC=e=>e.split(gd.sep).join("/"),xi=e=>{let t=[],r=n=>{for(let o of xC(n,{withFileTypes:!0})){let s=gd.join(n,o.name);if(o.isDirectory()){if(md(o.name))continue;r(s);continue}fd(o.name)||t.push(TC(gd.relative(e,s)))}};return r(e),t.sort()};var _e=".sync-manifest.json",Ti=1,AC=tt.object({schemaVersion:tt.number().optional(),source:tt.string(),commit:tt.string(),syncedAt:tt.string(),fileCount:tt.number(),files:tt.record(tt.string(),tt.string())}),hd=e=>(e.schemaVersion??Ti)>Ti,Fh=(e,t)=>{let r={},n=t?[...new Set(t)].sort():xi(e);for(let o of n)try{r[o]=mr(Ci.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},No=e=>{let t=Ci.join(e,_e),r;try{r=CC(t,"utf8")}catch{throw new Error(`Missing ${_e} at ${t}`)}let n=AC.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${_e} at ${t}: ${tt.prettifyError(n.error)}`);return n.data},yd=(e,t,r)=>{let n=Fh(e,r),o={schemaVersion:Ti,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return $C(Ci.join(e,_e),`${JSON.stringify(o,null,2)}
415
- `),o},vd=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Ei(c))),n=xi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}mr(Ci.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 wd=30,kd=(e,t)=>{if(t.length!==0){u.info(`
416
- ${e} (${t.length}):`);for(let r of t.slice(0,wd))u.info(` ${r}`);t.length>wd&&u.info(` \u2026and ${t.length-wd} more`)}},$i=async(e={})=>{let t=e.cwd??await E(),r=Bh.join(t,Z),n={modified:[],added:[],removed:[],fileCount:0};if(!Lh(r)){u.info(`\u2139\uFE0F No ${Z}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!Lh(Bh.join(r,_e))){u.error(`\u274C Missing ${Z}/${_e}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=No(r);if(hd(o)){u.error(`\u274C ${Z}/${_e} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=vd(r,o),c=s.length>0||i.length>0||a.length>0;c?(u.error(`\u274C ${Z}/ has drifted from ${Z}/${_e}.`),u.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),kd("Modified",s),kd("Added (not in manifest)",i),kd("Removed (in manifest, now missing)",a)):u.info(`\u2705 ${Z}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},IC={status:ut.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:ut.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:ut.number(),modified:ut.array(ut.string()),added:ut.array(ut.string()),removed:ut.array(ut.string())},bd=S({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:IC,handler:()=>$i({cwd:OC.cwd()})});import Vh from"node:process";import{z as _o}from"zod";var Wh=async e=>{try{return await e()}catch{return null}},Ai=async()=>{let e=G.version;u.info(e);let t=await Wh(E),r=t===null?null:await Wh(()=>je(t)),n={version:e,cwd:Vh.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Vh.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Rd=S({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:_o.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:_o.string().describe("The working directory of this process"),repoRoot:_o.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:_o.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:_o.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ai});import Jh from"@inquirer/confirm";import DC from"node:path";import{z as W}from"zod";import{$ as Mo}from"zx";var Oi="create worktrees",NC=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Sd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Ii=async e=>{let{confirmedCommand:t,all:r,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await be({operation:Oi});try{let a=await Te("release"),c=await E(),l=`${c}${pe}`;await Uh(`${l}/${vr.release}`),await Uh(`${l}/${vr.feature}`);let d=[];if(n)d=n.split(",").map(ue=>xe(ye(ue.trim())));else{let ue=await F(),pt=ue.map(Ve=>Ve.branch);if(pt.length===0){u.info("\u2139\uFE0F No open release branches found"),h.print();let Ve={createdWorktrees:[],count:0,...Sd()};return{content:k(JSON.stringify(Ve,null,2)),structuredContent:Ve}}if(r)d=pt;else{h.setInteractive();let Ve=new Map(ue.map(fu=>[fu.branch,fu.type])),cv=await ne();d=await xt(oe({branches:pt,descriptions:cv,types:Ve}),{required:!0})}}r?h.addOption("--all",!0):h.addOption("--versions",zt(d));let p=await M(),m=i??(yt(p).length>0?"workspace":"none");h.addOption("--ide",m);let g=await _C(o,p),y=await MC(s,p),R=await je(c),w=DC.basename(R),$=y?await jC({explicit:s!==void 0,mainRepoRoot:R}):null;await B(t,FC($,w)),t||h.addOption("--yes",!0);let D=$?await LC($,R):null,{branchesToCreate:A}=UC({selectedReleaseBranches:d,currentWorktrees:a}),P=await JC(A,l);if(GC(P),m==="workspace"&&await rd({projectRoot:c,worktreeDir:l,branches:P}),g)for(let ue of P)await Mo`github ${l}/${ue}`,await Mo`sleep 5`;let Y=D?await VC({registration:D,createdWorktrees:P,worktreeDir:l,mainRepoRoot:R,repoName:w,config:p}):Sd();WC(Y),h.print();let U={createdWorktrees:P,count:P.length,...Y};return{content:k(JSON.stringify(U,null,2)),structuredContent:U}}catch(a){throw ve(a)||a instanceof x?a:(u.debug({err:a},"Error managing worktrees"),new f(a,{operation:Oi,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},_C=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await O(o=>Jh({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},MC=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await O(o=>Jh({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},Gh=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"},jC=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Rr();if(n!=="ready"){let{reason:s,text:i}=Gh(n);if(t)throw u.warn({operation:Oi},`\u26D4 --orca was passed but ${i}`),new x({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 u.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await Ap(r);return{probe:n,registered:o.registered,visibility:o.visibility}},FC=(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(`
417
- `)},LC=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Gh(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Op(t);return{kind:"ready",visibility:r}}catch(r){return u.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 cs?r.code:void 0}}},BC=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,VC=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Sd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=ap(i),l=r.length===1&&t.visibility!=="hide",d=Dp();for(let p of r){let m=`${n}/${p}`;try{let{layout:g}=await Np({cwd:m,title:_p({branch:p}),focus:l,layout:"full",panes:c,poll:d});await Ip(o,m)?a.orcaOpened.push({branch:p,layout:g}):a.orcaHidden.push({branch:p,path:m,fix:BC(s)})}catch(g){u.warn({error:g,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),g instanceof cs&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:g instanceof cs?g.code:void 0})}}return a},WC=e=>{for(let t of e.orcaOpened)u.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)u.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})`:"";u.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},Uh=async e=>{await Mo`mkdir -p ${e}`},UC=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>es(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},JC=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o}`;return await Mo`git worktree add ${s} ${o}`,await Mo({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"});u.error({error:s.reason,msg:a.message})}return n},GC=e=>{if(e.length>0){u.info("\u2705 Created git worktrees:");for(let t of e)u.info(t);u.info("")}else u.info("\u2139\uFE0F No new git worktrees to create")},Pd=S({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:W.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:W.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:W.enum(ur).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:W.enum(ur).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:W.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:W.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:W.array(W.string()).describe("List of created git worktree branches"),count:W.number().describe("Number of git worktrees created"),orcaOpened:W.array(W.object({branch:W.string(),layout:W.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:W.array(W.object({branch:W.string(),reason:W.enum(NC),code:W.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:W.array(W.object({branch:W.string(),path:W.string(),fix:W.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:Ii});import{z as un}from"zod";var Di=async()=>{await M();let e=await Te("release");if(e.length===0)return u.info("\u2139\uFE0F No active worktrees found"),{content:k(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[t,r]=await Promise.all([F(),ne()]),n=new Map(t.map(c=>[c.branch,c.type])),o=e.flatMap(c=>{let l=J(c);if(!l)return[];let d=z(l),p=n.get(c)||"regular",m=r.get(te(l))||null;return[{version:d,type:p,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let l=Yn(c.version,c.type,s);return c.description?`${l} ${c.description}`:l});u.info(`\u{1F33F} Active worktrees:
418
-
419
- ${i.join(`
420
- `)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},Ed=S({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:un.array(un.object({version:un.string().describe("Release version"),type:un.enum(["regular","hotfix"]).describe("Release type"),description:un.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:un.number().describe("Number of worktrees")},handler:Di});import{z as fr}from"zod";var KC=e=>{if(fe()){if(e.all)throw new x({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 x({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"})}},HC=(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(", ")}`})},qC=async(e,t)=>{let r=await ls(t.map(n=>`${e}/${n}`));if(r!==null)throw new x({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 ${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`})},Ni=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await be({operation:"remove worktrees"}),await M(),KC({all:r,versions:n});try{let o=await Te("release");if(o.length===0){u.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let s=await E(),i=`${s}${pe}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(d=>xe(ye(d.trim())));else{h.setInteractive();let[d,p]=await Promise.all([ne(),F()]),m=new Map(p.map(g=>[g.branch,g.type]));a=await xt(oe({branches:o,descriptions:d,types:m}),{required:!0})}HC(a,o);let c=a.length===o.length;c?h.addOption("--all",!0):h.addOption("--versions",zt(a)),await qC(i,a),await B(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let l=await ar({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await dr({projectRoot:s,worktreeDir:i,removedWorktrees:l.removed}),yo(l),h.print(),vo({result:l,operation:"remove worktrees"})}catch(o){throw ve(o)||o instanceof f?o:(u.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"}))}},xd=S({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:fr.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:fr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:fr.array(fr.string()).describe("List of removed git worktree branches"),failedWorktrees:fr.array(fr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:fr.number().describe("Number of git worktrees removed")},handler:Ni});import{z as jo}from"zod";var _i=async e=>{let{confirmedCommand:t}=e;await be({operation:"sync worktrees"}),await M();try{let r=await Te("release"),n=await E(),o=`${n}${pe}`,s=await Ts();await B(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=YC({releasePRsList:s,currentWorktrees:r}),a=await ar({branches:i,worktreeDir:o,projectRoot:n});return await dr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),yo(a),h.print(),vo({result:a,operation:"sync worktrees"})}catch(r){throw ve(r)||r instanceof f?r:(u.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"}))}},YC=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>es(s)).filter(s=>!t.includes(s))}},Td=S({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:jo.array(jo.string()).describe("List of removed worktree branches"),failedWorktrees:jo.array(jo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:jo.number().describe("Number of worktrees removed during sync")},handler:_i});var Cd=[{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"}],nr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:oc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:ml,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:kl,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Ml,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:zl,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Zl,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Dl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:_l,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Rl,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:sd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Gl,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Kl,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Pd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Ed,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:xd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Td,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:hl,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Lp,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:ha,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:gl,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:yl,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:tc,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:bd,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:pd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:cl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:ec,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Rd,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 $d=e=>nr.filter(t=>t.menuGroup===e),Ad=e=>nr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var zC=(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},Kh=e=>Cd.flatMap(({key:t,label:r})=>$d(t).flatMap(n=>{let o=zC(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Od from"node:process";var XC="MODULE_TYPELESS_PACKAGE_JSON",ZC=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Hh=!1,Id=()=>{if(Hh)return;Hh=!0;let e=Od.emitWarning.bind(Od);Od.emitWarning=((t,...r)=>{ZC(r[0],r[1])!==XC&&e(t,...r)})};import{Command as RA,InvalidArgumentError as SA}from"commander";import{resolve as PA}from"node:path";import Me from"node:process";import{cd as EA}from"zx";import qh from"node:process";import{$ as QC}from"zx";var Dd=async()=>{let e=await ee(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await X(i.path)}))),r=t.at(-1)?.exists===!0,n=await ro(e.userProject,r),o=r?no(n):"";u.info(`Project name: ${e.projectName}
410
+ `),h.addOption("--yes",!0),await Hr({versionId:p.id,...w?{description:y.description}:{},...$?{releaseDate:y.releaseDate}:{}},i),w&&await Vs({branch:a,body:ro(B,y.description)}),u.info(`\u2705 Updated ${R.join(" and ")} for ${d}`),u.info(`\u{1F517} Jira Version: ${B}`),u.info(`\u{1F517} PR branch: ${a}
411
+ `),h.print(),I(!0)},Sd=S({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Me.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Me.string().optional().describe("New description. Empty string clears the description."),releaseDate:fl.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Me.string().describe("Release version"),branch:Me.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Me.string().describe("Jira fix version URL"),previousDescription:Me.string().describe("The description before the update"),newDescription:Me.string().describe("The description after the update"),previousReleaseDate:Me.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Me.string().nullable().describe("The planned release date after the update, or null"),changedFields:Me.array(Me.enum(qh)).describe("The fields whose value actually changed"),changed:Me.boolean().describe("Whether anything actually changed")},handler:Oi});import{z as L}from"zod";import{$ as $d}from"zx";import Yh from"node:fs/promises";import Ii from"node:path";var Pd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Ii.dirname(t),o;try{o=await Yh.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>Ii.resolve(n,d.path))),c=[],l=[];for(let d of r){let p=Ii.resolve(d);if(a.has(p)){l.push(d);continue}let m=Ii.relative(n,p);i.push({path:m}),a.add(p),c.push(d)}return s.folders=i,await Yh.writeFile(t,`${JSON.stringify(s,null,2)}
412
+ `,"utf-8"),{added:c,skipped:l}};import{$ as cC}from"zx";var Ed=async e=>{await cC`cursor ${e}`};import zh from"node:fs/promises";import Di from"node:path";var xd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Di.dirname(t),o;try{o=await zh.readFile(t,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${t}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(r.map(m=>Di.resolve(m))),c=new Set,l=i.filter(m=>{let g=Di.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await zh.writeFile(t,`${JSON.stringify(s,null,2)}
413
+ `,"utf-8");let d=[],p=[];for(let m of r){let g=Di.resolve(m);c.has(g)?d.push(m):p.push(m)}return{removed:d,notFound:p}};import Xh from"node:path";var Lo=(e,t)=>Xh.isAbsolute(e)?e:Xh.resolve(t,e);var Td=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await M(),s=yt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await lC({ide:c,projectRoot:t,folderPaths:i}));return a},lC=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return u.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=Lo(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await Pd({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return u.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await Ed(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var hr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await M(),s=yt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await dC({ide:c,projectRoot:t,folderPaths:i}));return a},dC=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=Lo(t.config.workspaceConfigPath,r);try{let{removed:s}=await xd({workspacePath:o,folderPaths:n});return s.length>0&&u.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return u.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var yr=["workspace","none"];import{z as Zh}from"zod";var ty=2500,Ni="release-remove",Qh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),uC=e=>e.version===void 0||e.version==="",pC=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===eo?{outcome:"empty"}:{outcome:"failed"}}},ey=(e,t)=>(e===null?u.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Ni}`}):e.outcome==="failed"?u.info({msg:`Tool execution form enumeration failed (gh pr list): ${Ni}`}):u.info({msg:`Tool execution form options empty (open release PRs): ${Ni}`}),null),mC=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Ks(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(re(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},fC=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(u.info({msg:`Tool execution form descriptions unavailable (timeout): ${Ni}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Cd=(e={})=>{let t=e.fetchBudgetMs??ty;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=>Qh(r)&&uC(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([gn(pC(),t),gn(se(),t)]);if(r===null||r.outcome!=="listed")return ey(r,t);let o=mC(r.prs,n);return o.length===0?ey({outcome:"empty"},t):Zh.object({version:Zh.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${fC(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:{...Qh(n)?n:{},version:r.version}}};var ry=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],Mi={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"},vr="remove a release",Ve=e=>{throw u.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},ny=(e,t)=>{throw u.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new x({...e,agentMode:N.source},2,t)},gC=e=>{ye()&&(e.version||ny({status:"argument_required",argument:"version"},{operation:vr,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&&ny({status:"refused"},{operation:vr,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"}))},sy=e=>{e.pr?.state==="MERGED"&&Ve({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`})},hC=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ve({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)&&Ve({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||Ve({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)`}))},yC=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ve({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"})},vC=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ve({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(", ")}`})},wC=async e=>(await $d`git -C ${e} status --porcelain`).stdout.split(`
414
+ `).map(r=>r.trimEnd()).filter(r=>r.length>0),kC=async e=>{try{let{terminals:t}=await tm(e);return t.filter(r=>r.connected).length}catch(t){return u.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},bC=async e=>{let t=await Rs([e]);if(t!==null)throw u.warn({operation:vr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new x({status:"refused",reason:"orca_caller_inside_target",agentMode:N.source},2,{operation:vr,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`})},RC=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await ct();if(!n)return r;let o=await at(re(e),n),s=t.moveIssuesTo?await SC(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Js(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:tr(n,o)}}},SC=async(e,t)=>{let r=await at(e,t);return r||Ve({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}"`})},PC=async(e,t)=>{let r=G(e);r||Ve({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 T(),o=`${n}${ge}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([me("release"),Ur(e),$e(n,`refs/heads/${e}`),Er(n,e)]),d=i.includes(e);return d&&await bC(s),{...await RC(r,t),branch:e,id:r,label:X(r),baseBranch:a?.baseRefName??Xe("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await kC(s):0,worktreeDirty:d?await wC(s):null,localTipSha:c,remoteTipSha:l,pr:a}},oy=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}),EC=(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}`},xC=(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: ${EC(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
415
+ `)},_i=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},TC=e=>typeof e=="string"?e:e.outcome;async function Bo(e,t,r){try{let n=await r(),o=TC(n);return t.push({step:e}),u.info({step:e,outcome:o},`\u2705 ${Mi[e]} \u2014 ${o}`),n}catch(n){throw new _i(e,n)}}var CC=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),u.warn({err:Nt(n),step:e},`\u26A0\uFE0F ${Mi[e]} failed (non-blocking)`)}},$C=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,AC=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>$C(t,p)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${ry.indexOf(r)+1} of ${ry.length} (${Mi[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},OC=async e=>{let t=await $o(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}},IC=e=>{let t=e.map(s=>({provider:s.provider,outcome:DC(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}},DC=e=>e.removed.length>0?"verified":"attempted",NC=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await CC("ide-folders",r,async()=>{let o=await hr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=IC(o)}),u.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${Mi["ide-folders"]} \u2014 ${n.outcome}`),n},_C=async e=>{let t=await Ur(e.branch);if(sy({...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 $d`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},MC=async e=>(await Pr()===e.branch&&await $d`git switch ${e.baseBranch}`,await fs(e.branch),await Pp(e.branch)?Ve({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"),jC=async e=>(await gs(e.branch),e.remoteTipSha?"deleted":"absent"),FC=async(e,t,r)=>{let n=await Js(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}\``;Ve({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}`})},LC=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await FC(e,e.jira,e.jiraConfig),u.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Fc({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),BC=(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}),WC=async(e,t,r)=>{let n=await Bo("worktree",r,()=>OC(e)),o=await NC(e,n.removedBranches,r),s=await Bo("pr",r,()=>_C(e));u.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Bo("local-branch",r,()=>MC(e)),a=await Bo("remote-branch",r,()=>jC(e)),c=await Bo("jira",r,()=>LC(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},VC=async(e,t)=>{let r=[];try{return BC(e,await WC(e,t,r))}catch(n){throw n instanceof _i?AC({plan:e,step:n.step,done:r,cause:n.reason}):n}},UC=async e=>{if(e)return lt(e);h.setInteractive();let[t,r]=await Promise.all([se(),F()]),n=r.map(s=>s.branch);n.length===0&&Ve({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 Tt(ie({branches:n,descriptions:t,types:o}))}catch(s){throw be(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"})}},iy=Cd(),ji=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Pe({operation:vr}),await M(),await Ge({provider:iy,params:e,operation:vr,argument:"version"}),gC(e);try{let s=await PC(await UC(r),e);u.debug({plan:oy(s)},"release remove: resolved plan"),sy(s),hC(s,e),yC(s),await Zn({operation:`remove release ${s.label}`,base:s.baseBranch}),vC(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await V(t,xC(s,!!o),{throwOnDecline:!0,plan:{...oy(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await VC(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw be(s)||ot(s)||s instanceof f?s:(u.error({err:Nt(s)},"\u274C Error removing release"),new f(s,{operation:vr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Ad=S({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:iy,inputSchema:{version:L.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:L.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:L.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:L.string().describe("The release branch that was targeted"),version:L.string().describe('The release label (e.g. "1.2.5")'),baseBranch:L.string().describe("The branch HEAD was moved to before the local delete"),worktree:L.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:L.object({outcome:L.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:L.array(L.object({provider:L.string(),outcome:L.enum(["verified","attempted","skipped"]),removed:L.array(L.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:L.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:L.number().nullable().describe("The pull request number, or null when none exists"),localBranch:L.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:L.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:L.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:L.string().nullable().describe("The origin tip before deletion"),jira:L.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:L.object({id:L.string(),name:L.string(),url:L.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:ji});import{spawnSync as HC}from"node:child_process";import{homedir as qC}from"node:os";import YC from"node:process";var JC=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},GC=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},KC=(e,t)=>{let r=JC(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},Wo=(e,t)=>{let r=[...GC(e),...KC(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Vo=e=>e.steps.map(mt);var zC=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],XC=e=>{let t={...Qu(e)};for(let r of zC)delete t[r];return t},Od=(e,t,r={})=>{let n=r.spawnSync??HC,o=r.env??YC.env,s=(r.agentMode??ye)(),i=Vo(e),a=Wo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:e$({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??ZC}):{ran:!1,commands:i,refusedBecause:a.reasons}},ZC=e=>{u.info(e)},cy=64,QC=cy*1024*1024,e$=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=XC(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:QC,cwd:qC(),env:s}),l=i$(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},t$=5,r$=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,ay=e=>e==null?[]:String(e).split(`
416
+ `).map(t=>t.trim()).filter(t=>t.length>0),n$=e=>{let t=ay(e.stderr),r=ay(e.stdout),n=[...t,...r].filter(s=>r$.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-t$).join(" / ")},o$="ENOBUFS",s$=e=>e.error?.code===o$,i$=e=>{if(s$(e))return`terminated after exceeding the ${cy} 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=n$(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var a$=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},c$=e=>{let t=Ne(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},l$=(e,t)=>{let r=c$(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=Wo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Vo(r),context:n}},Fi=async(e=ir,t=go())=>{let r=await yo(ir,t),n={owner:null,present:a$(r)},o=pl(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>l$(s.get(a),n)),context:n}};var Id=(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}}),ly=(e,t)=>e.action==="none"?Id(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?Id(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`},d$=(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`},Dd=async e=>{let t=e.run??Od,{plans:r}=await Fi(e.ids,e.probeDeps),n=[];for(let o of r){let s=ly(o,e.mode);if(s!==null){n.push(s);continue}n.push(d$(o,t(o.recipe,o.context)))}return n},Nd=async(e,t)=>{let{plans:r}=await Fi(e,t);return r.map(n=>ly(n,"converge")??Id(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import x$ from"node:process";import{z as C}from"zod";var _d={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},u$=Object.keys(_d).sort((e,t)=>_d[e]-_d[t]),dy={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},uy=new Set(["manual","warn","fail"]),Md=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return Ae(e)}},p$=e=>e.reduce((t,r)=>dy[r]>dy[t]?r:t,"skipped"),my=e=>e.message.trim(),m$=e=>["written","unchanged","skipped"].map(r=>{let n=e.filter(o=>o.outcome===r).length;return n>0?`${n} ${r}`:""}).filter(r=>r.length>0).join(" \xB7 "),py=e=>e.message===on,f$=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?my(r):e.length>1?m$(e):t?"activate with the last line below":"see below"},g$=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Md(i.outcome)),n=t.filter(i=>uy.has(Md(i.outcome))).map(my),o=t.filter(i=>!uy.has(Md(i.outcome))&&!py(i)),s={name:e,status:p$(r),message:f$(o,t.some(py))};return n.length>0?{...s,notes:n}:s},h$=e=>({label:"Local setup",rows:u$.map(t=>g$(t,e.filter(r=>r.step===t)))}),y$=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return Ae(e.action)}},v$=(e,t)=>{let r=y$(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},w$=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>v$(r,t))}),k$=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return Ae(e)}},b$=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return Ae(e)}},R$=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 Ae(e)}},S$=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 Ae(e.outcome)}},P$=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return Ae(e)}},E$=e=>({label:"Portless service",rows:[{name:"link",status:k$(e.link),message:R$(e.link)},{name:"node",status:b$(e.node.outcome),message:S$(e.node)},P$(e.service,e.command)]}),fy=(e,t)=>[h$(e.init),w$(e.tools,t),E$(e.portless)],gy=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var T$=()=>{let{link:e,node:t}=ds();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},C$=async e=>{let t=fp(e.link).outcome,r=mp(e.node),n=ls(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return{link:t,node:r,service:"skipped",command:null};let{state:o,stableNode:s}=await Yg(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=ft(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},yy="--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.",$$=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(yy);return{ids:e.tools??t??ir,mode:r?"update":"converge",skipTools:n}},hy=(e,t)=>e instanceof nn?e.step:t.at(-1)?.step??"zshrc",A$=async()=>{let e=[];try{await sl(t=>{e.push(t)})}catch(t){e.push({step:hy(t,e),outcome:"failed",message:`The ${hy(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},O$=(e,t)=>{let r=t instanceof Error?t.message:String(t);return e.map(n=>({id:n,action:"failed",before:{present:!1,onPath:!1,version:null,manager:"unknown"},commands:[],detail:`the dependency step failed before reaching this tool: ${r}`}))},I$=async(e,t)=>{try{return e.skipTools?await Nd(e.ids,t.probeDeps):await Dd({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return O$(e.ids,r)}},D$=e=>({step:e.step,outcome:e.outcome,message:e.message}),Li=async(e={})=>{let t=$$(e),r=await A$(),n=await I$(t,e),o=await C$(e.portlessDeps??T$()),s=fy({init:r,tools:n,portless:o},{skipTools:t.skipTools});ze({title:"infra-kit setup",sections:s},{ascii:e.ascii}),u.info(on),gy(s)&&(x$.exitCode=1);let i={init:r.map(D$),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},N$=C.object({step:C.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:C.enum(["written","unchanged","skipped","manual","warned","failed"]).describe("What that step did: changed something, found nothing to change, did not run, left a command for a human to run (the message carries it), failed non-fatally, or threw and ended the init half (setup exits 1)"),message:C.string().describe("The same line a human running this would have read")}),_$=C.object({id:C.string().describe("Dependency id"),action:C.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:C.object({present:C.boolean(),onPath:C.boolean(),version:C.string().nullable(),manager:C.string()}).describe("The tool\u2019s state before this run"),commands:C.array(C.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:C.string().describe("Why, in one line")}),M$=C.object({link:C.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:C.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:C.enum(["absent","converged","drifted","skipped"]).describe("The installed portless system service against the link and node: not installed, already running through both, installed but pointing elsewhere, or not judged because portless is not installed"),command:C.string().nullable().describe("The sudo `service install` command a human has to run; present if and only if service is absent or drifted, null otherwise")}),j$={init:C.array(N$).describe("One entry per init step, in the order they ran"),tools:C.array(_$).describe("One result per requested dependency"),portlessService:M$.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:C.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:C.boolean().describe("Whether anything was installed or updated"),report:C.array(C.object({label:C.string().describe("Section heading"),rows:C.array(C.object({name:C.string().describe("Init step, tool id, or portless part"),status:C.enum(["ok","changed","skipped","manual","warn","fail"]).describe("ok: nothing to change; changed: changed something; skipped: did not run; manual: not run by the CLI, the notes hold the command a human runs; warn: advisory problem; fail: failed (setup exits 1)"),message:C.string().describe("The row message, as printed"),notes:C.array(C.string()).optional().describe("Lines printed under the row, verbatim: the manual commands, warnings and failures")}))})).describe("The exact rows of the table printed on stderr; setup exits 1 iff a row is fail"),allSucceeded:C.boolean().describe("Whether no tool failed (a refusal is not a failure)")},F$={tools:C.array(C.enum(ir)).optional().describe("Which tools to act on. Omit for all six."),mode:C.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:C.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},jd=S({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:F$,outputSchema:j$,requiresHumanConfirm:!0,handler:e=>Li({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as wy}from"node:fs";import ky from"node:path";import Y$ from"node:process";import{z as pt}from"zod";import{createHash as L$}from"node:crypto";import{readFileSync as B$}from"node:fs";var wr=e=>L$("sha256").update(B$(e)).digest("hex");import{readFileSync as K$,writeFileSync as H$}from"node:fs";import Ui from"node:path";import{z as rt}from"zod";var Q="vendor",W$=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),V$=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),U$=[".tsbuildinfo"],Fd=e=>W$.has(e),Ld=e=>V$.has(e)?!0:U$.some(t=>e.endsWith(t)),Bi=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Fd(o))||Ld(r)};import{readdirSync as J$}from"node:fs";import Bd from"node:path";var G$=e=>e.split(Bd.sep).join("/"),Wi=e=>{let t=[],r=n=>{for(let o of J$(n,{withFileTypes:!0})){let s=Bd.join(n,o.name);if(o.isDirectory()){if(Fd(o.name))continue;r(s);continue}Ld(o.name)||t.push(G$(Bd.relative(e,s)))}};return r(e),t.sort()};var je=".sync-manifest.json",Vi=1,q$=rt.object({schemaVersion:rt.number().optional(),source:rt.string(),commit:rt.string(),syncedAt:rt.string(),fileCount:rt.number(),files:rt.record(rt.string(),rt.string())}),Wd=e=>(e.schemaVersion??Vi)>Vi,vy=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Wi(e);for(let o of n)try{r[o]=wr(Ui.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},Jo=e=>{let t=Ui.join(e,je),r;try{r=K$(t,"utf8")}catch{throw new Error(`Missing ${je} at ${t}`)}let n=q$.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${je} at ${t}: ${rt.prettifyError(n.error)}`);return n.data},Vd=(e,t,r)=>{let n=vy(e,r),o={schemaVersion:Vi,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return H$(Ui.join(e,je),`${JSON.stringify(o,null,2)}
417
+ `),o},Ud=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Bi(c))),n=Wi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}wr(Ui.join(e,c))!==r[c]&&o.push(c)}let i=new Set(n),a=Object.keys(r).filter(c=>!i.has(c));return{modified:o,added:s,removed:a}};var Jd=30,Gd=(e,t)=>{if(t.length!==0){u.info(`
418
+ ${e} (${t.length}):`);for(let r of t.slice(0,Jd))u.info(` ${r}`);t.length>Jd&&u.info(` \u2026and ${t.length-Jd} more`)}},Ji=async(e={})=>{let t=e.cwd??await T(),r=ky.join(t,Q),n={modified:[],added:[],removed:[],fileCount:0};if(!wy(r)){u.info(`\u2139\uFE0F No ${Q}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!wy(ky.join(r,je))){u.error(`\u274C Missing ${Q}/${je}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=Jo(r);if(Wd(o)){u.error(`\u274C ${Q}/${je} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=Ud(r,o),c=s.length>0||i.length>0||a.length>0;c?(u.error(`\u274C ${Q}/ has drifted from ${Q}/${je}.`),u.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Gd("Modified",s),Gd("Added (not in manifest)",i),Gd("Removed (in manifest, now missing)",a)):u.info(`\u2705 ${Q}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},z$={status:pt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:pt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:pt.number(),modified:pt.array(pt.string()),added:pt.array(pt.string()),removed:pt.array(pt.string())},Kd=S({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:z$,handler:()=>Ji({cwd:Y$.cwd()})});import by from"node:process";import{z as Go}from"zod";var Ry=async e=>{try{return await e()}catch{return null}},Gi=async()=>{let e=K.version;u.info(e);let t=await Ry(T),r=t===null?null:await Ry(()=>Le(t)),n={version:e,cwd:by.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:by.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Hd=S({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:Go.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Go.string().describe("The working directory of this process"),repoRoot:Go.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Go.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Go.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Gi});import _y from"@inquirer/confirm";import rA from"node:path";import{z as _}from"zod";import{$ as Ho}from"zx";import X$ from"@inquirer/input";import Py from"@inquirer/select";import{$ as jt}from"zx";var Ko="dev",Z$="main",qd="feature/",Ey=["new","local","remote"],Ki=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${qd}${t}`},xy=async()=>{let e=await jt({nothrow:!0,quiet:!0})`git symbolic-ref --quiet --short refs/remotes/origin/HEAD`,t=e.exitCode===0?e.stdout.trim().replace(/^origin\//,""):"";return t===""?null:t},Q$=2,Yd=async()=>{let e=await jt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Ko}`;if(e.exitCode===0)return Ko;if(e.exitCode!==Q$)throw new f(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${Ko} exists`});return await xy()??Ko},Ty=async e=>{let t=e?.trim();return t?t===Ko||t===Z$||t===await xy()?t:ve(pe(t)):Yd()},Cy=async()=>O(e=>Py({message:"What kind of worktree?",choices:[{name:"Release \u2014 worktrees for open release branches",value:"release"},{name:"Feature \u2014 a new or existing feature/* branch",value:"feature"}]},e),{whenHeadless:{value:"release"}}),$y=async()=>O(e=>X$({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Ki(t)===qd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Ay=async(e,t)=>e.length===0?t:O(r=>Py({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),eA=async e=>{let t=await jt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===qd||t.exitCode!==0)throw new f(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},Sy=async e=>(await jt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,tA=async e=>(await jt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Oy=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Ki))];for(let s of n)await eA(s);if(!await Sy(r))throw new f(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await tA(s)?o.push({branch:s,base:r,source:"local"}):await Sy(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Iy=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await jt`git worktree add ${t} ${r}`:o==="remote"?await jt`git worktree add --track -b ${r} ${t} origin/${r}`:await jt`git worktree add --no-track -b ${r} ${t} origin/${n}`},Dy=e=>e.source==="new"?` \u2022 ${e.branch}: new branch from origin/${e.base}`:` \u2022 ${e.branch}: existing ${e.source==="local"?"local":"remote"} branch (base not applied)`;var qo="create worktrees",nA=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],zd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Hi=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e,o=e.ide??e.cursor;await Pe({operation:qo}),oA(e);try{let s=await T(),i=`${s}${ge}`;await Ny(`${i}/${Sr.release}`),await Ny(`${i}/${Sr.feature}`);let a=await sA(e),c=a==="feature"?await aA(e):await iA(e);if(c===null){u.info("\u2139\uFE0F No open release branches found"),h.print();let P={kind:a,createdWorktrees:[],count:0,features:[],...zd()};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}}let l=await M(),d=o??(yt(l).length>0?"workspace":"none");h.addOption("--ide",d);let p=await cA(r,l),m=await lA(n,l),g=await Le(s),y=rA.basename(g),R=m?await dA({explicit:n!==void 0,mainRepoRoot:g}):null;await V(t,uA(R,y,c.previewLines)),t||h.addOption("--yes",!0);let w=R?await pA(R,g):null,$=await yA(c.targets,i);if(vA($),d==="workspace"&&await Td({projectRoot:s,worktreeDir:i,branches:$}),p)for(let P of $)await Ho`github ${i}/${P}`,await Ho`sleep 5`;let B=w?await fA({registration:w,createdWorktrees:$,worktreeDir:i,mainRepoRoot:g,repoName:y,config:l}):zd();gA(B),h.print();let I={kind:a,createdWorktrees:$,count:$.length,features:c.features.filter(P=>$.includes(P.branch)),...B};return{content:k(JSON.stringify(I,null,2)),structuredContent:I}}catch(s){throw be(s)||s instanceof x?s:(u.debug({err:s},"Error managing worktrees"),new f(s,{operation:qo,remediation:s instanceof f&&s.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},oA=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new f(void 0,{operation:qo,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},sA=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Cy()),iA=async e=>{let{all:t,versions:r}=e,n=await me("release"),o=[];if(r)o=r.split(",").map(a=>ve(pe(a.trim())));else{let a=await F(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{h.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),d=await se();o=await Ct(ie({branches:c,descriptions:d,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",rr(o));let{branchesToCreate:s}=hA({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>Ho`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},aA=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await $y()],n===void 0)){let l=(await F()).map(d=>d.branch);n=await Ay(l,await Yd())}let o=await Ty(n),s=await Oy({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await me("feature"),a=s.filter(l=>i.includes(l.branch)?(u.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:d=>Iy(l,d)})),features:a,previewLines:a.map(Dy)}},cA=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await O(o=>_y({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},lA=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await O(o=>_y({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},My=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"},dA=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await xr();if(n!=="ready"){let{reason:s,text:i}=My(n);if(t)throw u.warn({operation:qo},`\u26D4 --orca was passed but ${i}`),new x({status:"refused",reason:s,agentMode:N.source},2,{operation:qo,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 u.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await nm(r);return{probe:n,registered:o.registered,visibility:o.visibility}},uA=(e,t,r)=>{let n=["Are you sure you want to proceed with these worktree changes?",...r];return e?.probe==="ready"&&!e.registered&&n.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),n.join(`
419
+ `)},pA=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:My(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await om(t);return{kind:"ready",visibility:r}}catch(r){return u.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof bs?r.code:void 0}}},mA=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,fA=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=zd();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=Mp(i),l=r.length===1&&t.visibility!=="hide",d=im();for(let p of r){let m=`${n}/${p}`;try{let{layout:g}=await am({cwd:m,title:cm({branch:p}),focus:l,layout:"full",panes:c,poll:d});await sm(o,m)?a.orcaOpened.push({branch:p,layout:g}):a.orcaHidden.push({branch:p,path:m,fix:mA(s)})}catch(g){u.warn({error:g,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),g instanceof bs&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:g instanceof bs?g.code:void 0})}}return a},gA=e=>{for(let t of e.orcaOpened)u.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)u.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})`:"";u.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},Ny=async e=>{await Ho`mkdir -p ${e}`},hA=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>ms(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},yA=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await Ho({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});u.error({error:s.reason,msg:a.message})}return n},vA=e=>{if(e.length>0){u.info("\u2705 Created git worktrees:");for(let t of e)u.info(t);u.info("")}else u.info("\u2139\uFE0F No new git worktrees to create")},Xd=S({name:"worktrees-add",description:`Create local git worktrees under the worktrees directory and run "pnpm install" in each: release worktrees for open release branches ("versions" / all=true), or feature worktrees ("feature", optional "base") \u2014 each name becomes a feature/<name> branch at <root>-worktrees/feature/<name>, cut from origin/<base> (default dev, or the default branch of a repo without dev; main; or any release branch) with no upstream, or checked out as-is when the branch already exists locally or on origin. Mutates the local filesystem. When invoked via MCP, pass "versions" (comma-separated), all=true, or "feature" \u2014 the branch picker and "open in Cursor / GitHub Desktop / Orca" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls. With "orca" true each created worktree gets an Orca terminal tab laid out per "worktrees.orca.layout"; the result reports orcaOpened, orcaSkipped (with a reason) and orcaHidden (a worktree Orca's sidebar hides, with the UI steps to reveal it). An unregistered repo is registered in Orca first (orca repo add).`,inputSchema:{feature:_.string().optional().describe('Comma-separated feature names (e.g. "checkout-v2" or "feature/checkout-v2"); each becomes a feature/<name> worktree. Cannot be combined with "versions" or "all".'),base:_.string().optional().describe(`Base for NEW feature branches: "dev" (default; the repo's default branch when it has no dev), "main", or a release ref ("1.4.0", "release/v1.4.0", "release/<name>"). Not applied to a feature branch that already exists. Implies a feature run.`),all:_.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:_.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:_.enum(yr).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:_.enum(yr).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:_.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:_.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:_.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:_.array(_.object({branch:_.string(),base:_.string(),source:_.enum(Ey)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:_.array(_.string()).describe("List of created git worktree branches"),count:_.number().describe("Number of git worktrees created"),orcaOpened:_.array(_.object({branch:_.string(),layout:_.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:_.array(_.object({branch:_.string(),reason:_.enum(nA),code:_.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:_.array(_.object({branch:_.string(),path:_.string(),fix:_.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:Hi});import{z as Ft}from"zod";var qi=async()=>{await M();let[e,t]=await Promise.all([me("release"),me("feature")]);if(e.length===0&&t.length===0){u.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await wA(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
420
+
421
+ ${kA(r).join(`
422
+ `)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
423
+
424
+ ${t.join(`
425
+ `)}`),u.info(n.join(`
426
+
427
+ `));let o={worktrees:r,count:r.length,features:t};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},wA=async e=>{let[t,r]=await Promise.all([F(),se()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=G(o);if(!s)return[];let i=X(s),a=n.get(o)||"regular",c=r.get(re(s))||null;return[{version:i,type:a,description:c}]})},kA=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=so(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Zd=S({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description, plus feature worktrees (feature/* branches). Read-only.",inputSchema:{},outputSchema:{worktrees:Ft.array(Ft.object({version:Ft.string().describe("Release version"),type:Ft.enum(["regular","hotfix"]).describe("Release type"),description:Ft.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:Ft.number().describe("Number of release worktrees"),features:Ft.array(Ft.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:qi});import{z as Lt}from"zod";var bA=e=>{if(ye()){if(e.all)throw new x({status:"refused",agentMode:N.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions&&!e.feature)throw new x({status:"argument_required",argument:"versions",agentMode:N.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},RA=(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(", ")}`})},SA=async(e,t)=>{let r=await Rs(t.map(n=>`${e}/${n}`));if(r!==null)throw new x({status:"refused",reason:"orca_caller_inside_target",agentMode:N.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},PA=e=>e?e.split(",").map(t=>ve(pe(t.trim()))):[],EA=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Ki):[],xA=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",rr(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Yi=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o}=e;await Pe({operation:"remove worktrees"}),await M(),bA({all:r,versions:n,feature:o});try{let[s,i]=await Promise.all([me("release"),me("feature")]),a=[...s,...i];if(a.length===0){u.info("\u2139\uFE0F No active worktrees to remove"),h.print();let g={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(g,null,2)),structuredContent:g}}let c=await T(),l=`${c}${ge}`,d=[];if(r)d=a;else if(n||o)d=[...PA(n),...EA(o)];else{h.setInteractive();let[g,y]=await Promise.all([se(),F()]),R=new Map(y.map(w=>[w.branch,w.type]));d=await Ct([...ie({branches:s,descriptions:g,types:R}),...i.map(w=>({value:w,label:w,type:"feature"}))],{required:!0})}RA(d,a);let p=d.length===a.length;p?h.addOption("--all",!0):xA(d),await SA(l,d),await V(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let m=await mr({branches:d,worktreeDir:l,projectRoot:c,pruneFolder:p});return await hr({projectRoot:c,worktreeDir:l,removedWorktrees:m.removed}),To(m),h.print(),Co({result:m,operation:"remove worktrees"})}catch(s){throw be(s)||s instanceof f?s:(u.error({error:s},"\u274C Error managing worktrees"),new f(s,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Qd=S({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches ("versions") and/or feature branches ("feature"). Over MCP you MUST pass "versions" or "feature" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named target must be an active worktree, or the call errors without removing anything. What survives: the release and feature branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically. Every Orca terminal open in a removed worktree is closed first; a call made from an Orca terminal INSIDE one of the targets is refused (orca_caller_inside_target) before anything is removed \u2014 re-run it from a terminal that is not an Orca pane of that worktree.',requiresHumanConfirm:!0,inputSchema:{versions:Lt.string().optional().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). This or "feature" is required: each must name an active worktree, or the call errors before removing anything.'),feature:Lt.string().optional().describe('Comma-separated feature names to remove (e.g. "checkout-v2" or "feature/checkout-v2"). This or "versions" is required; each must name an active feature worktree.'),confirm:Lt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Lt.array(Lt.string()).describe("List of removed git worktree branches"),failedWorktrees:Lt.array(Lt.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Lt.number().describe("Number of git worktrees removed")},handler:Yi});import{z as Yo}from"zod";var zi=async e=>{let{confirmedCommand:t}=e;await Pe({operation:"sync worktrees"}),await M();try{let r=await me("release"),n=await T(),o=`${n}${ge}`,s=await Ws();await V(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=TA({releasePRsList:s,currentWorktrees:r}),a=await mr({branches:i,worktreeDir:o,projectRoot:n});return await hr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),To(a),h.print(),Co({result:a,operation:"sync worktrees"})}catch(r){throw be(r)||r instanceof f?r:(u.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"}))}},TA=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>ms(s)).filter(s=>!t.includes(s))}},eu=S({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:Yo.array(Yo.string()).describe("List of removed worktree branches"),failedWorktrees:Yo.array(Yo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Yo.number().describe("Number of worktrees removed during sync")},handler:zi});var tu=[{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"}],lr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Sc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:Fl,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:Gl,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:ad,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:bd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Sd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:od,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:id,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Hl,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Ad,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:hd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Xd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Zd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Qd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:eu,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Wl,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:mm,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Oa,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Bl,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Vl,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:bc,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{cliName:"config-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-set"]},{cliName:"config-unset",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-unset"]},{cliName:"config-path",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config","path"]},{cliName:"config-edit",menuGroup:"configuration",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config","edit"],entersAltScreen:!0},{cliName:"vendor-check",menuGroup:"vendor",mcpTool:Kd,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:jd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Tl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:vc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Hd,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-token-set",menuGroup:"environment",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]}];var ru=e=>lr.filter(t=>t.menuGroup===e),nu=e=>lr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var CA=(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},jy=e=>tu.flatMap(({key:t,label:r})=>ru(t).flatMap(n=>{let o=CA(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import ou from"node:process";var $A="MODULE_TYPELESS_PACKAGE_JSON",AA=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Fy=!1,su=()=>{if(Fy)return;Fy=!0;let e=ou.emitWarning.bind(ou);ou.emitWarning=((t,...r)=>{AA(r[0],r[1])!==$A&&e(t,...r)})};import{Command as cI,InvalidArgumentError as lI}from"commander";import{resolve as dI}from"node:path";import Fe from"node:process";import{cd as uI}from"zx";import Ly from"node:process";import{$ as OA}from"zx";var iu=async()=>{let e=await H(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await Z(i.path)}))),r=t.at(-1)?.exists===!0,n=await mo(e.userProject,r),o=r?fo(n):"";u.info(`Project name: ${e.projectName}
421
428
  `),u.info(`Config merge chain (later overrides earlier):
422
- `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";u.info(`${a} ${i.label.padEnd(22)} ${v(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Nd=async()=>{let e=await ee(),t=qh.env.EDITOR||qh.env.VISUAL||"vi",r=await Gr(e);r.createdConfig&&u.info(Kr(r)),u.info(`Opening ${v(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await QC({stdio:"inherit"})`${t} ${e.userProject}`,vt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Yh="https://dashboard.doppler.com/workplace/projects",e$=(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}"): ${Yh}/${e}`],_d=async({env:e})=>{let r=!!(await Bt())?.envs[e];await xp(e);let n=await br(),o=await Lt();r?u.info(`Removed the "${e}" service token from ${v(o)}.`):u.info(`No "${e}" service token was stored in ${v(o)} \u2014 nothing to remove.`);for(let i of e$(n,e))u.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Yh}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import t$ from"@inquirer/password";import ji from"node:process";import{$ as Mi}from"zx";var r$=async({stdin:e,fromEnv:t})=>{if(e)return{token:await n$(),source:"stdin"};if(t){let n=ji.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return h.setInteractive(),{token:(await O(n=>t$({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:ji.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},n$=async()=>{let e=[];ji.stdin.setEncoding("utf8");for await(let t of ji.stdin)e.push(t);return e.join("").trim()},Md="DOPPLER_CONFIG",o$=3e4,s$=async(e,t,r)=>{let n=Mi.quiet;Mi.quiet=!0;let o;try{o=(await Mi({env:En(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(o$)).stdout}catch(s){throw i$(s,r)}finally{Mi.quiet=n}return ga(o)},i$=(e,t)=>{let r=Uu(e)??(e instanceof Error?e.message:String(e));if(Rp(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Sp(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(`
423
- `))},a$=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Md}.`,"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(`
424
- `),jd=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await br(),{token:s,source:i}=await r$({stdin:t,fromEnv:r});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await s$(s,o,e);fa(a,e);let c=a.some(([p])=>p===Md);if(!c&&!n)throw new Error(a$(e));await Ep(e,s);let l=await Lt();u.info(`Stored the "${e}" service token (${an(s)}) in ${v(l)} (mode 0600).`),c||u.warn(`Scope was NOT verified (no ${Md} in the payload) \u2014 written because --force was given.`);let d={env:e,source:i,redactedToken:an(s),storePath:l,scopeVerified:c};return h.print(),{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var Fd=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,p=await Ol(n);if(r&&h.addOption("--from",p),Al(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),p==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?ci({version:o,env:s,skipTerraform:a,confirmedCommand:c}):li({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Ld=async e=>Fd(e,"all"),Bd=async e=>Fd(e,"selected"),Fi=async(e,t)=>{let r=`release deploy-${t} --from local`;return u.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),Fd({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Xh}from"@slip-stream-kit/config/internal";import Vd from"node:fs/promises";import pn from"node:path";import zh from"node:process";import{pathToFileURL as c$}from"node:url";var Zh="~/projects",Wd=async(e={})=>{if(e.init){await d$(e.cwd);return}await l$()},l$=async()=>{let e=qr(),t=await X(e);if(u.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){u.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),zh.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await Ws(),s=Yr(r),i=await X(s),a=pn.join(s,n),c=await X(a);u.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),u.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),u.info("Targets:");let l=i&&c;for(let d of o){let p=pn.join(s,d),m=await X(p);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";u.info(` ${g} ${d} ${v(p)}${y}`)}l||(zh.exitCode=1)},d$=async e=>{let t=qr();if(await X(t)){u.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await E(),n=await u$(r);await Vd.mkdir(pn.dirname(t),{recursive:!0}),await Vd.writeFile(t,p$(pn.basename(r),n),"utf-8"),u.info(`\u2713 Created ${v(t)}`),n.length>0&&u.info(` Seeded ${n.length} target(s) from the source ${Xh}.`),u.info(` Edit \`workspaceDir\` (placeholder: ${Zh}) to point at where your repos live.`),u.info(` \`source\` is seeded with ${pn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&u.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},u$=async e=>{try{let t=pn.join(e,Xh),r=await Vd.stat(t),s=(await import(`${c$(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[]},p$=(e,t)=>`${JSON.stringify({workspaceDir:Zh,source:e,targets:t},null,2)}
425
- `;import{existsSync as lA}from"node:fs";import dA from"node:fs/promises";import by from"node:path";import tu from"node:process";import{z as uA}from"zod";import{chmodSync as k$,copyFileSync as b$,lstatSync as R$,mkdirSync as cy,readdirSync as S$,readlinkSync as P$,rmdirSync as ly,symlinkSync as E$,unlinkSync as x$,writeFileSync as T$}from"node:fs";import he from"node:path";import{lstatSync as m$,readlinkSync as Qh}from"node:fs";import f$ from"node:path";var g$=new Set(["ENOENT","ENOTDIR"]),Li=e=>{let t;try{t=m$(e)}catch(r){if(g$.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:Qh(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:mr(e)}:{kind:"other"}},ey=(e,t)=>{let r=f$.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:Qh(r)}:{kind:"file",executable:t.mode==="100755",sha:mr(r)};return{...t,fingerprint:n}},ty=(e,t)=>t===null||e.kind!==t.kind?!1:e.kind==="link"&&t.kind==="link"?e.text===t.text:e.kind==="file"&&t.kind==="file"?e.executable===t.executable&&e.sha===t.sha:!1;import{$ as h$}from"zx";var Q=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await h$({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},Bi=e=>e.slice(0,7),_t=e=>e.split("\0").filter(t=>t.length>0);import y$ from"node:path";var Ud=`${Z}/`,Mt=`${Z}/README.md`,Fo=`${Z}/${_e}`,ny=e=>e.startsWith(Ud),ry=e=>{let t=y$.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},oy=e=>{let t=ry(e.path),r=e.target===void 0?t:ry(e.target);return{path:t,target:r,vendored:ny(r)}},sy=e=>e.copy.map(oy),Lo=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Bo=(e,t)=>e.filter(r=>!Lo(r.path,t)),Vi=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,mn=e=>[...new Set(e)].sort(),iy=e=>e.startsWith(Ud)?e.slice(Ud.length):null;var Wi=e=>`# vendor/ \u2014 mirrored from ${e}
429
+ `);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";u.info(`${a} ${i.label.padEnd(22)} ${v(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},au=async()=>{let e=await H(),t=Ly.env.EDITOR||Ly.env.VISUAL||"vi",r=await Xr(e);r.createdConfig&&u.info(Zr(r)),u.info(`Opening ${v(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await OA({stdio:"inherit"})`${t} ${e.userProject}`,vt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var cu=async({key:e,global:t})=>{js(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Fs(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);u.info(s?`Removed ${e} from the ${Hn[r]} (${v(n)})`:`${e} is not set in the ${Hn[r]} (${v(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}};var By="https://dashboard.doppler.com/workplace/projects",IA=(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}"): ${By}/${e}`],lu=async({env:e})=>{let r=!!(await Be())?.envs[e];await Qp(e);let n=await Kt(),o=await kt();r?u.info(`Removed the "${e}" service token from ${v(o)}.`):u.info(`No "${e}" service token was stored in ${v(o)} \u2014 nothing to remove.`);for(let i of IA(n,e))u.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${By}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import DA from"@inquirer/confirm";import NA from"@inquirer/input";import _A from"@inquirer/password";import MA from"@inquirer/select";import jA from"node:fs/promises";import nt from"node:process";import{$ as Xi}from"zx";var FA=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Wy(),source:"stdin"};if(t){let n=nt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!nt.stdin.isTTY){let n=await Wy();if(n)return{token:n,source:"stdin"};if(!J())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return h.setInteractive(),{token:(await O(n=>_A({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:nt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Wy=async()=>{let e=[];nt.stdin.setEncoding("utf8");for await(let t of nt.stdin)e.push(t);return e.join("").trim()},du="DOPPLER_CONFIG",LA=3e4,BA=async(e,t,r)=>{let n=Xi.quiet;Xi.quiet=!0;let o;try{o=(await Xi({env:In(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(LA)).stdout}catch(s){throw WA(s,r)}finally{Xi.quiet=n}return Aa(o)},WA=(e,t)=>{let r=yp(e)??(e instanceof Error?e.message:String(e));if(zp(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Xp(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(`
430
+ `))},VA=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${du}.`,"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(`
431
+ `),Uy=async(e,t,r,n)=>{let o=await BA(e,t,r);$a(o,r);let s=o.some(([i])=>i===du);if(!s&&!n)throw new Error(VA(r));return s},Vy="\0new-env",UA=async()=>{if(J()||!nt.stdin.isTTY)throw new x({status:"argument_required",argument:"env",agentMode:N.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([dm(),Be()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await O(s=>MA({message:"Which environment is the token for?",choices:[...e.map(({env:i})=>({name:`${i.padEnd(r)} ${t?.envs[i]?"set \u2014 replace":"not set"}`,value:i})),{name:"+ new env\u2026",value:Vy}]},s),{output:nt.stderr,whenHeadless:"refuse"});return n!==Vy?n:(await O(s=>NA({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:nt.stderr,whenHeadless:"refuse"})).trim()},JA=async(e,t,r)=>O(n=>DA({message:`Replace the "${e}" token ${we(t)} with ${we(r)}?`,default:!0},n),{output:nt.stderr,whenHeadless:"refuse"}),GA=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${we(r)})`;case"replaced":return`Replaced the "${e}" service token ${we(n??"")} \u2192 ${we(r)}`;case"unchanged":return`The "${e}" service token is already ${we(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${we(n??"")} \u2014 nothing was written`;default:return Ae(t)}},uu=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Kt(),s=e??await UA(),{token:i,source:a}=await FA({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Uy(i,o,s,n),l=(await Be())?.envs[s],d;l===i?d="unchanged":l!==void 0&&a==="prompt"&&!await JA(s,l,i)?d="kept":(await xa({[s]:i}),d=l===void 0?"stored":"replaced");let p=await kt();u.info(`${GA(s,d,i,l)} in ${v(p)} (mode 0600).`),c||u.warn(`Scope was NOT verified (no ${du} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:d,source:a,redactedToken:we(i),previousRedactedToken:l===void 0?null:we(l),storePath:p,scopeVerified:c};return h.print(),{content:k(JSON.stringify(m,null,2)),structuredContent:m}},KA=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,Jy=e=>{let t=e.split(/\r?\n/).flatMap((n,o)=>{let s=n.trim();if(s===""||s.startsWith("#"))return[];let i=s.indexOf("="),a=i>0?s.slice(0,i).trim():"",c=i>0?KA(s.slice(i+1).trim()):"";if(!/^\S+$/.test(a)||c==="")throw new Error(`Token file line ${o+1} is not \`<env>=<token>\` \u2014 nothing was written.`);return[{env:a,token:c}]});if(t.length===0)throw new Error("The token file holds no `<env>=<token>` lines \u2014 nothing was written.");let r=new Set;for(let{env:n}of t){if(r.has(n))throw new Error(`"${n}" appears twice in the token file \u2014 nothing was written.`);r.add(n)}return t},HA=e=>(e instanceof Error?e.message:String(e)).split(`
432
+ `)[0]??"",qA=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",YA=async(e,t,r,n)=>{let o=we(e.token);try{let s=await Uy(e.token,t,e.env,n);return{env:e.env,status:qA(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:HA(s)}}},pu=async({fromFile:e,force:t})=>{let r=await Kt(),n=Jy(await jA.readFile(e,"utf8")),o=await Be(),s=await Promise.all(n.map(p=>YA(p,r,o?.envs[p.env],t))),i=Object.fromEntries(n.filter((p,m)=>s[m]?.status==="stored"||s[m]?.status==="replaced").map(({env:p,token:m})=>[p,m]));Object.keys(i).length>0&&await xa(i);let a=await kt(),c=Math.max(...s.map(({env:p})=>p.length));u.info(`Token import from ${v(e)} \u2192 ${v(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";u.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}u.warn(`${v(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(nt.exitCode=1);let d={storePath:a,rows:s,failedCount:l};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var mu=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,p=await rd(n);if(r&&h.addOption("--from",p),td(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),p==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?Si({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Pi({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},fu=async e=>mu(e,"all"),gu=async e=>mu(e,"selected"),Zi=async(e,t)=>{let r=`release deploy-${t} --from local`;return u.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),mu({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Ky}from"@slip-stream-kit/config/internal";import hu from"node:fs/promises";import hn from"node:path";import Gy from"node:process";import{pathToFileURL as zA}from"node:url";var Hy="~/projects",yu=async(e={})=>{if(e.init){await ZA(e.cwd);return}await XA()},XA=async()=>{let e=en(),t=await Z(e);if(u.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){u.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Gy.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await ri(),s=tn(r),i=await Z(s),a=hn.join(s,n),c=await Z(a);u.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),u.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),u.info("Targets:");let l=i&&c;for(let d of o){let p=hn.join(s,d),m=await Z(p);m||(l=!1);let g=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";u.info(` ${g} ${d} ${v(p)}${y}`)}l||(Gy.exitCode=1)},ZA=async e=>{let t=en();if(await Z(t)){u.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await T(),n=await QA(r);await hu.mkdir(hn.dirname(t),{recursive:!0}),await hu.writeFile(t,eO(hn.basename(r),n),"utf-8"),u.info(`\u2713 Created ${v(t)}`),n.length>0&&u.info(` Seeded ${n.length} target(s) from the source ${Ky}.`),u.info(` Edit \`workspaceDir\` (placeholder: ${Hy}) to point at where your repos live.`),u.info(` \`source\` is seeded with ${hn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&u.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},QA=async e=>{try{let t=hn.join(e,Ky),r=await hu.stat(t),s=(await import(`${zA(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[]},eO=(e,t)=>`${JSON.stringify({workspaceDir:Hy,source:e,targets:t},null,2)}
433
+ `;import{existsSync as XO}from"node:fs";import ZO from"node:fs/promises";import hv from"node:path";import yv from"node:process";import{z as QO}from"zod";import{chmodSync as cO,copyFileSync as lO,lstatSync as dO,mkdirSync as nv,readdirSync as uO,readlinkSync as pO,rmdirSync as ov,symlinkSync as mO,unlinkSync as fO,writeFileSync as gO}from"node:fs";import ke from"node:path";import{lstatSync as tO,readlinkSync as qy}from"node:fs";import rO from"node:path";var nO=new Set(["ENOENT","ENOTDIR"]),Qi=e=>{let t;try{t=tO(e)}catch(r){if(nO.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:qy(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:wr(e)}:{kind:"other"}},Yy=(e,t)=>{let r=rO.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:qy(r)}:{kind:"file",executable:t.mode==="100755",sha:wr(r)};return{...t,fingerprint:n}},zy=(e,t)=>t===null||e.kind!==t.kind?!1:e.kind==="link"&&t.kind==="link"?e.text===t.text:e.kind==="file"&&t.kind==="file"?e.executable===t.executable&&e.sha===t.sha:!1;import{$ as oO}from"zx";var ee=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await oO({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ea=e=>e.slice(0,7),Bt=e=>e.split("\0").filter(t=>t.length>0);import sO from"node:path";var vu=`${Q}/`,Wt=`${Q}/README.md`,zo=`${Q}/${je}`,Zy=e=>e.startsWith(vu),Xy=e=>{let t=sO.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},Qy=e=>{let t=Xy(e.path),r=e.target===void 0?t:Xy(e.target);return{path:t,target:r,vendored:Zy(r)}},ev=e=>e.copy.map(Qy),Xo=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Zo=(e,t)=>e.filter(r=>!Xo(r.path,t)),ta=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,yn=e=>[...new Set(e)].sort(),tv=e=>e.startsWith(vu)?e.slice(vu.length):null;var ra=e=>`# vendor/ \u2014 mirrored from ${e}
426
434
 
427
435
  **DO NOT EDIT files in this folder here.**
428
436
 
@@ -433,19 +441,19 @@ fail \`ik vendor check\` in CI.
433
441
  To change a vendored package, edit it in \`${e}\` and re-run the sync there.
434
442
 
435
443
  See \`.sync-manifest.json\` for the source commit and per-file checksums.
436
- `;var v$=new Set(["100644","100755","120000"]),w$=(e,t)=>{let r=new Map;for(let n of _t(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!v$.has(s)||Lo(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},Jd=async(e,t,r)=>{let n=await Q(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return w$(n,r)},ay=async e=>_t(await Q(e,["--literal-pathspecs","ls-files","-z","--",Z]));var fn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],dy=e=>{let t=Li(e);t!==null&&(t.kind==="other"?ly(e):x$(e))},C$=(e,t,r)=>{let n=he.join(e,r.source),o=he.join(t,r.target);if(cy(he.dirname(o),{recursive:!0}),dy(o),r.mode==="120000"){E$(P$(n),o);return}b$(n,o),k$(o,r.mode==="100755"?493:420)},$$=async(e,t)=>{let r=new Set;for(let n of _t(await Q(e,["ls-files","-z"]))){if(t.has(n))continue;let o=he.posix.dirname(n);for(;o!==".";)r.add(o),o=he.posix.dirname(o)}return r},A$=async(e,t)=>{if(t.length===0)return;let r=await $$(e,new Set(t)),n=[...new Set(t.map(o=>he.dirname(he.join(e,o))))];n.sort((o,s)=>s.length-o.length);for(let o of n){let s=o;for(;s!==e&&s.startsWith(e)&&!(!R$(s,{throwIfNoEntry:!1})?.isDirectory()||S$(s).length>0||r.has(he.relative(e,s).split(he.sep).join("/")));)ly(s),s=he.dirname(s)}},uy=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Mt,...s].map(iy).filter(a=>a!==null&&!Ei(a));return mn(i)},py=async(e,t,r,n)=>{let o=he.join(e,Z);cy(o,{recursive:!0}),T$(he.join(e,Mt),Wi(t.name));let s=uy(r,await ay(e),n);yd(o,{source:t.name,commit:t.headSha},s)},Gd=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(fn(t));let n=he.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)dy(he.join(n,a));await A$(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)C$(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await py(n,e,t.entries,o),{touched:mn([...o,...i,Mt,Fo]),manifestWritten:!0}):{touched:mn([...o,...i]),manifestWritten:!1}},Kd=async(e,t)=>(await py(e,t,[],[]),[Mt,Fo]);var Hd=(e,t)=>`[ROOT] vendor: sync from ${e}@${Bi(t)}`,O$=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
437
- `).trim()||String(e)},qd=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Q(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Q(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:O$(s)}}};var I$=20,D$=20,my=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],fy=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of Bo(e.files,r)){let p=Vi(d.path,n);if(s.push(p),ty(d.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:d.path,target:p,mode:d.mode,change:m})}let a=new Set(s),c=Bo(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},Vo=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Yd=e=>e.entries.map(t=>t.entry.target),N$=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...Yd(e)];return Vo(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...my(r,I$),mt(n)])},_$=(e,t)=>{if(e.kind==="unknown-sha")return{notes:[],warnings:["no manifest commit recorded, so the source commits since the last sync are unknown"]};let r=Bi(e.sha);return e.kind==="unresolvable"?{notes:[],warnings:[`manifest commit ${r} is not in ${t}, so the changelog is unknown`]}:{notes:[`${e.lines.length} ${t} commit(s) since ${r}`,...my(e.lines,D$)],warnings:[]}},M$=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},j$=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},F$=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return mn([...n,...r?t.headVendorMeta:[]])},L$=(e,t)=>{if(t.dirty.length>0)return N$(e,t,t.dirty);let r=e.entries.map((d,p)=>{let m=t.entries[p]??{target:d.entry.target,tracked:[],onDisk:{}};return fy(d,m,e.exclude)}),n=r.some(d=>d.vendored),o=r.some(d=>d.writes.length+d.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...Vo(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=_$(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(M$).filter(d=>d!==null);return{...i,status:"changed",message:`${j$(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:F$(r,t,n)}},Ui=(e,t)=>{switch(t.kind){case"missing":return Vo(t,"skipped",`not checked out at ${t.root}`);case"source":return Vo(t,"skipped","this is the source repo");case"not-git":return Vo(t,"fail",`not a git repo: ${t.reason}`);case"repo":return L$(e,t)}};import{existsSync as B$,readFileSync as V$,realpathSync as Ji}from"node:fs";import Gi from"node:path";var zd=async(e,t)=>{let r=t.exclude??[],n=(await Q(e,["rev-parse","HEAD"])).trim(),o=await je(e),s=await Promise.all(sy(t).map(async i=>{let a=await Jd(e,i.path,r);return{entry:i,files:a.map(c=>ey(e,c))}}));return{root:e,selfRoots:[...new Set([Ji(e),Ji(o)])],name:Gi.basename(o),headSha:n,entries:s,exclude:r}},Ki=e=>{let t=_t(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},W$=async(e,t)=>{let r=await Q(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...Yd(e)]);return Ki(r).filter(n=>!Lo(n,e.exclude))},U$=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await Jd(t,r.target,e.exclude),s={};for(let i of Bo(n,e.exclude)){let a=Vi(i.path,r);s[a]=Li(Gi.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),J$=async e=>{try{return _t(await Q(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Mt,Fo]))}catch{return[]}},G$=e=>{try{let{commit:t,source:r}=No(Gi.join(e,Z));return{commit:t,source:r}}catch{return null}},K$=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await Ce(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await Q(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
438
- `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},H$=(e,t)=>{try{return V$(Gi.join(e,Mt),"utf8")===Wi(t)}catch{return!1}},q$=async e=>{try{return{toplevel:(await Q(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
439
- `)[0]??"git rev-parse failed"}}},Y$=async e=>{try{return(await Q(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},Hi=async(e,t)=>{if(!B$(t.root))return{...t,kind:"missing"};let r=Ji(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await q$(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Ji(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=G$(t.root),s=o?.commit??null,[i,a,c,l,d]=await Promise.all([Y$(t.root),W$(e,t.root),U$(e,t.root),J$(t.root),K$(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:H$(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:d}};var z$=20,X$=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],Z$=(e,t)=>{let{plan:r}=e,n=t.manifestOnly?"manifest":"sync";if(e.error!==void 0)return{name:n,status:"fail",message:`apply failed: ${e.error}`,notes:["restore the tracked paths with:",mt(fn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:X$(r,t)}},Q$=e=>e.ok?{name:"commit",status:"ok",message:"committed the synced paths"}:{name:"commit",status:"fail",message:"git refused the commit; the files stay written",notes:e.output.split(`
440
- `).slice(0,z$)},eA=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[Z$(e,t),...r,...e.commit?[Q$(e.commit)]:[]]}},tA={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},Xd=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:tA[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>eA(o,r))],hints:n}},gy=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),hy=(e,t,r)=>{let n=new Set(e.sections.flatMap(s=>s.rows.map(i=>`${s.label}\0${i.name}\0${i.status}`))),o=t.sections.map(s=>({label:s.label,rows:s.rows.filter(i=>!n.has(`${s.label}\0${i.name}\0${i.status}`))}));return{...t,sections:o,emptyMessage:`synced ${r.join(", ")}`}};var rA=20,Zd=async(e,t)=>(await Q(e,t,{allowFailure:!0})).trim(),nA=async e=>Ki(await Q(e,["status","--porcelain","-z","--untracked-files=normal"])),oA=async e=>(await Zd(e,["for-each-ref","--contains","HEAD","--format=%(refname)","refs/remotes/origin/"])).length>0?null:{name:"HEAD pushed",status:"warn",message:"HEAD is on no origin/* ref, so every target will record a commit nobody else can resolve",notes:["git push"]},sA=async e=>{let[t,r]=await Promise.all([Zd(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),Zd(e,["rev-parse","--abbrev-ref","HEAD"])]);if(t.length===0)return{name:"default branch",status:"warn",message:"origin has no default branch recorded (origin/HEAD)"};let n=t.replace(/^origin\//u,"");return r===n?null:{name:"default branch",status:"warn",message:`syncing from ${r||"a detached HEAD"}, not the origin default branch ${n}`}},yy=async e=>{let t=await nA(e);if(t.length>0){let n=t.slice(0,rA),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new x({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([oA(e),sA(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import iA from"node:path";var vy=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new x({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=Yr(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:iA.join(n,s)}))},aA="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",cA=async(e,t)=>{let r=await Hi(e,t),n=Ui(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${aA} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},wy=async(e,t,r)=>Promise.all(t.map(async n=>r?cA(e,n):Ui(e,await Hi(e,n))));var qi="sync vendored files",pA=()=>{if(fe())throw new x({status:"refused",agentMode:I.source},2,{operation:qi,stderrExcerpt:"vendor sync is human-only: refused in agent mode regardless of --yes",remediation:"ask a human to run `infra-kit vendor sync` from their own shell \u2014 a sync is never confirmed by an agent"})},mA=()=>{if(!tu.stdin.isTTY)throw new x({status:"refused",reason:"no-tty"},2,{operation:qi,stderrExcerpt:"the apply needs a real terminal on stdin",remediation:"run `infra-kit vendor sync --yes` from a real terminal; Claude Code's `!` prefix is not one"})},fA=e=>{let t=by.join(Yr(e.workspaceDir),e.source);if(lA(t))return t;throw new x({status:"refused",reason:"source-missing",source:t},1,{operation:qi,stderrExcerpt:`the source repo ${e.source} is not checked out at ${t}`,remediation:'clone it there, or fix "source" / "workspaceDir" in ~/.infra-kit/vendor.json'})},Qd=(e,t)=>new x({status:"refused",reason:"not-a-vendor-source"},1,{operation:qi,stderrExcerpt:`${e} ${t}`,remediation:`add a vendorSource block to the source repo's committed infra-kit.json, or point "source" at the repo that has one`}),gA=async e=>{let t=by.join(e,"infra-kit.json"),r;try{r=JSON.parse(await dA.readFile(t,"utf8"))}catch(s){throw Qd(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw Qd(t,"has no vendorSource block");let o=sp.safeParse(n);if(!o.success)throw Qd(t,`has an invalid vendorSource: ${uA.prettifyError(o.error)}`);return o.data},ky=(e,t)=>{tu.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
444
+ `;var iO=new Set(["100644","100755","120000"]),aO=(e,t)=>{let r=new Map;for(let n of Bt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!iO.has(s)||Xo(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},wu=async(e,t,r)=>{let n=await ee(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return aO(n,r)},rv=async e=>Bt(await ee(e,["--literal-pathspecs","ls-files","-z","--",Q]));var vn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],sv=e=>{let t=Qi(e);t!==null&&(t.kind==="other"?ov(e):fO(e))},hO=(e,t,r)=>{let n=ke.join(e,r.source),o=ke.join(t,r.target);if(nv(ke.dirname(o),{recursive:!0}),sv(o),r.mode==="120000"){mO(pO(n),o);return}lO(n,o),cO(o,r.mode==="100755"?493:420)},yO=async(e,t)=>{let r=new Set;for(let n of Bt(await ee(e,["ls-files","-z"]))){if(t.has(n))continue;let o=ke.posix.dirname(n);for(;o!==".";)r.add(o),o=ke.posix.dirname(o)}return r},vO=async(e,t)=>{if(t.length===0)return;let r=await yO(e,new Set(t)),n=[...new Set(t.map(o=>ke.dirname(ke.join(e,o))))];n.sort((o,s)=>s.length-o.length);for(let o of n){let s=o;for(;s!==e&&s.startsWith(e)&&!(!dO(s,{throwIfNoEntry:!1})?.isDirectory()||uO(s).length>0||r.has(ke.relative(e,s).split(ke.sep).join("/")));)ov(s),s=ke.dirname(s)}},iv=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Wt,...s].map(tv).filter(a=>a!==null&&!Bi(a));return yn(i)},av=async(e,t,r,n)=>{let o=ke.join(e,Q);nv(o,{recursive:!0}),gO(ke.join(e,Wt),ra(t.name));let s=iv(r,await rv(e),n);Vd(o,{source:t.name,commit:t.headSha},s)},ku=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(vn(t));let n=ke.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)sv(ke.join(n,a));await vO(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)hO(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await av(n,e,t.entries,o),{touched:yn([...o,...i,Wt,zo]),manifestWritten:!0}):{touched:yn([...o,...i]),manifestWritten:!1}},bu=async(e,t)=>(await av(e,t,[],[]),[Wt,zo]);var Ru=(e,t)=>`[ROOT] vendor: sync from ${e}@${ea(t)}`,wO=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
445
+ `).trim()||String(e)},Su=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await ee(e,["--literal-pathspecs","add","-A",...o],{input:n}),await ee(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:wO(s)}}};var kO=20,bO=20,cv=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],lv=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of Zo(e.files,r)){let p=ta(d.path,n);if(s.push(p),zy(d.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:d.path,target:p,mode:d.mode,change:m})}let a=new Set(s),c=Zo(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},Qo=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Pu=e=>e.entries.map(t=>t.entry.target),RO=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...Pu(e)];return Qo(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...cv(r,kO),mt(n)])},SO=(e,t)=>{if(e.kind==="unknown-sha")return{notes:[],warnings:["no manifest commit recorded, so the source commits since the last sync are unknown"]};let r=ea(e.sha);return e.kind==="unresolvable"?{notes:[],warnings:[`manifest commit ${r} is not in ${t}, so the changelog is unknown`]}:{notes:[`${e.lines.length} ${t} commit(s) since ${r}`,...cv(e.lines,bO)],warnings:[]}},PO=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},EO=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},xO=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return yn([...n,...r?t.headVendorMeta:[]])},TO=(e,t)=>{if(t.dirty.length>0)return RO(e,t,t.dirty);let r=e.entries.map((d,p)=>{let m=t.entries[p]??{target:d.entry.target,tracked:[],onDisk:{}};return lv(d,m,e.exclude)}),n=r.some(d=>d.vendored),o=r.some(d=>d.writes.length+d.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...Qo(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=SO(t.changelog,e.name),c=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],l=r.map(PO).filter(d=>d!==null);return{...i,status:"changed",message:`${EO(r)} on ${t.branch}`,notes:[...l,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:[...c,...a.warnings],recoveryPaths:xO(r,t,n)}},na=(e,t)=>{switch(t.kind){case"missing":return Qo(t,"skipped",`not checked out at ${t.root}`);case"source":return Qo(t,"skipped","this is the source repo");case"not-git":return Qo(t,"fail",`not a git repo: ${t.reason}`);case"repo":return TO(e,t)}};import{existsSync as CO,readFileSync as $O,realpathSync as oa}from"node:fs";import sa from"node:path";var Eu=async(e,t)=>{let r=t.exclude??[],n=(await ee(e,["rev-parse","HEAD"])).trim(),o=await Le(e),s=await Promise.all(ev(t).map(async i=>{let a=await wu(e,i.path,r);return{entry:i,files:a.map(c=>Yy(e,c))}}));return{root:e,selfRoots:[...new Set([oa(e),oa(o)])],name:sa.basename(o),headSha:n,entries:s,exclude:r}},ia=e=>{let t=Bt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},AO=async(e,t)=>{let r=await ee(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...Pu(e)]);return ia(r).filter(n=>!Xo(n,e.exclude))},OO=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await wu(t,r.target,e.exclude),s={};for(let i of Zo(n,e.exclude)){let a=ta(i.path,r);s[a]=Qi(sa.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),IO=async e=>{try{return Bt(await ee(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Wt,zo]))}catch{return[]}},DO=e=>{try{let{commit:t,source:r}=Jo(sa.join(e,Q));return{commit:t,source:r}}catch{return null}},NO=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await $e(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await ee(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
446
+ `).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},_O=(e,t)=>{try{return $O(sa.join(e,Wt),"utf8")===ra(t)}catch{return!1}},MO=async e=>{try{return{toplevel:(await ee(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
447
+ `)[0]??"git rev-parse failed"}}},jO=async e=>{try{return(await ee(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},aa=async(e,t)=>{if(!CO(t.root))return{...t,kind:"missing"};let r=oa(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await MO(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(oa(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=DO(t.root),s=o?.commit??null,[i,a,c,l,d]=await Promise.all([jO(t.root),AO(e,t.root),OO(e,t.root),IO(t.root),NO(e,s)]);return{...t,kind:"repo",branch:i,dirty:a,entries:c,headVendorMeta:l,readmeCurrent:_O(t.root,e.name),manifestPresent:o!==null,manifestSource:o?.source??null,changelog:d}};var FO=20,LO=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],BO=(e,t)=>{let{plan:r}=e,n=t.manifestOnly?"manifest":"sync";if(e.error!==void 0)return{name:n,status:"fail",message:`apply failed: ${e.error}`,notes:["restore the tracked paths with:",mt(vn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:LO(r,t)}},WO=e=>e.ok?{name:"commit",status:"ok",message:"committed the synced paths"}:{name:"commit",status:"fail",message:"git refused the commit; the files stay written",notes:e.output.split(`
448
+ `).slice(0,FO)},VO=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[BO(e,t),...r,...e.commit?[WO(e.commit)]:[]]}},UO={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},xu=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:UO[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>VO(o,r))],hints:n}},dv=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),uv=(e,t,r)=>{let n=new Set(e.sections.flatMap(s=>s.rows.map(i=>`${s.label}\0${i.name}\0${i.status}`))),o=t.sections.map(s=>({label:s.label,rows:s.rows.filter(i=>!n.has(`${s.label}\0${i.name}\0${i.status}`))}));return{...t,sections:o,emptyMessage:`synced ${r.join(", ")}`}};var JO=20,Tu=async(e,t)=>(await ee(e,t,{allowFailure:!0})).trim(),GO=async e=>ia(await ee(e,["status","--porcelain","-z","--untracked-files=normal"])),KO=async e=>(await Tu(e,["for-each-ref","--contains","HEAD","--format=%(refname)","refs/remotes/origin/"])).length>0?null:{name:"HEAD pushed",status:"warn",message:"HEAD is on no origin/* ref, so every target will record a commit nobody else can resolve",notes:["git push"]},HO=async e=>{let[t,r]=await Promise.all([Tu(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),Tu(e,["rev-parse","--abbrev-ref","HEAD"])]);if(t.length===0)return{name:"default branch",status:"warn",message:"origin has no default branch recorded (origin/HEAD)"};let n=t.replace(/^origin\//u,"");return r===n?null:{name:"default branch",status:"warn",message:`syncing from ${r||"a detached HEAD"}, not the origin default branch ${n}`}},pv=async e=>{let t=await GO(e);if(t.length>0){let n=t.slice(0,JO),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new x({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([KO(e),HO(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import qO from"node:path";var mv=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new x({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=tn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:qO.join(n,s)}))},YO="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",zO=async(e,t)=>{let r=await aa(e,t),n=na(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${YO} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},fv=async(e,t,r)=>Promise.all(t.map(async n=>r?zO(e,n):na(e,await aa(e,n))));var vv="sync vendored files",eI=e=>{let t=hv.join(tn(e.workspaceDir),e.source);if(XO(t))return t;throw new x({status:"refused",reason:"source-missing",source:t},1,{operation:vv,stderrExcerpt:`the source repo ${e.source} is not checked out at ${t}`,remediation:'clone it there, or fix "source" / "workspaceDir" in ~/.infra-kit/vendor.json'})},Cu=(e,t)=>new x({status:"refused",reason:"not-a-vendor-source"},1,{operation:vv,stderrExcerpt:`${e} ${t}`,remediation:`add a vendorSource block to the source repo's committed infra-kit.json, or point "source" at the repo that has one`}),tI=async e=>{let t=hv.join(e,"infra-kit.json"),r;try{r=JSON.parse(await ZO.readFile(t,"utf8"))}catch(s){throw Cu(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw Cu(t,"has no vendorSource block");let o=Dp.safeParse(n);if(!o.success)throw Cu(t,`has an invalid vendorSource: ${QO.prettifyError(o.error)}`);return o.data},gv=(e,t)=>{yv.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
441
449
  ${mt(t)}
442
- `)},hA=async(e,t,r)=>r?(ky(t,fn(t)),Kd(t.root,e)):(await Gd({source:e,plan:t,onBeforeFirstWrite:o=>{ky(t,o)}})).touched,yA=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await hA(e,t,!!r.manifestOnly)}catch(s){return{plan:t,applied:!1,error:s instanceof Error?s.message:String(s)}}if(!r.commit)return{plan:t,applied:!0};let o=await qd(t.root,n,Hd(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},vA=async(e,t,r)=>{let n=[];for(let o of t)n.push(await yA(e,o,r));return n},Ry=e=>e.map(t=>({name:t.name,root:t.root,status:t.status,message:t.message,notes:t.notes,warnings:t.warnings,branch:t.branch})),eu=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&Ye(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:Ry(s).map((a,c)=>{let l=r[c];return{...a,applied:l.applied,error:l.error,commit:l.commit}}),changed:s.some(a=>a.status==="changed"),failed:gy(t),report:t.sections}}},wA=async e=>{let t=await Ws(),r=fA(t),n=await yy(r),o=await gA(r),s=vy(t,e.targets??[]),i=await zd(r,o),a=await wy(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},ru=async(e={})=>{pA();let{source:t,sourceRows:r,plans:n}=await wA(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=Xd(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return eu({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!rt.enabled;if(l&&!tu.stdin.isTTY)return Ye(a),eu({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&Ye({...a,hints:[]}),await B(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:Ry(n),throwOnDecline:!0}),mA();let d=await vA(t,n,e),p=Xd(r,d,{...s,mode:"applied"});if(l){let m=d.filter(g=>g.applied).map(g=>g.plan.name);Ye(hy(a,p,m))}return eu({mode:"applied",report:p,outcomes:d,source:t,print:!l})};var Yi=(e,t=!0)=>({line:e,reproducible:t});import zi from"node:fs";import kA from"node:os";import bA from"node:path";import xy from"node:process";var Xi="INFRA_KIT_SESSION_REPORT",nu=null,Sy=!1,Py=[],Ty=(e=xy.env)=>{Sy||(nu=e[Xi]??null,Sy=!0,delete e[Xi])};var Cy=(e,t)=>{if(!nu)return;let r=e.summary??(Py.length>0?[...Py]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{zi.writeFileSync(s,i)});try{o(nu,JSON.stringify(n))}catch{}},Ey=0,$y=e=>{let t=e?.tmpdir?.()??kA.tmpdir(),r=e?.pid??xy.pid;return Ey+=1,bA.join(t,`infra-kit-session-${r}-${Ey}.json`)},Ay=(e,t)=>{if(!(t?.exists??(i=>zi.existsSync(i)))(e))return null;let n=t?.read??(i=>zi.readFileSync(i,"utf-8")),o=t?.unlink??(i=>zi.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var ou=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(ou)};var su=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(su)};var xA=(e,t)=>[...t,e],Oy=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&ur.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${ur.join(", ")}.`)}},TA=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").option("--keep-conflicts","On the confirmed run, leave each conflicted branch mid-merge in <root>-worktrees/merge-dev/ for resolution").option("--continue","Check, preview, then commit and push the selected resolutions left by --keep-conflicts").option("--abort","Discard the selected resolutions left by --keep-conflicts").option("--tree <branch=sha>","With --continue --yes: the approved tree per branch, as a --continue preview prints it (repeatable)",(t,r)=>[...r??[],t]).action(async t=>{let r=await Qm(()=>oi({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));C(r),r.structuredContent.failedMerges>0&&(Me.exitCode=1)}),Iy=e=>(Me.stdout.write(`${e.structuredContent.filePath}
443
- `),C(e)),CA=e=>e.description("List all release branches").action(async()=>{C(await di())}),$A=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".',xA,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(el),o=n.length>0?n:void 0;C(await gi({releases:o,confirmedCommand:t.yes}))}),AA=e=>{if(e==="")return e;try{return tr(e)}catch(t){throw t instanceof tn?new SA(t.message):t}},OA=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)',AA).option("-y, --yes","Skip confirmation prompt").action(async t=>{C(await hi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Dy=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Dt.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"),IA=e=>Dy(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{C(await Ld({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),DA=e=>Dy(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=>{C(await Bd({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),NA=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=>{C(await ai({version:t.version,confirmedCommand:t.yes}))}),_A=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=>{C(await Ri({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),MA=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{C(await _i({confirmedCommand:t.yes}))}),jA=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=Oy(t.ide,"--ide")??Oy(t.cursor,"--cursor");C(await Ii({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),FA=e=>e.description("List all git worktrees with detailed information").action(async()=>{C(await Di())}),LA=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=>{C(await Ni({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),BA=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=>{C(await Wd({init:t.init}))}),VA=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await $i();C(t),t.structuredContent.ok||(Me.exitCode=1)}),WA=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory (human-only)").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan (needs a real terminal on stdin)").option("--check","Preview only; exit 1 when any target would change").option("--commit","Commit exactly the synced paths in each target after it syncs").option("--manifest-only","Rewrite vendor/README.md and vendor/.sync-manifest.json only; copy nothing").action(async(t,r)=>{let n;try{n=await ru({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!nt(a))throw a;u.info("Operation cancelled.");return}C(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Me.exitCode=1)}),UA=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{C(await Dd())}),JA=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{C(await Nd())}),GA=new Set(["version"]),Zi=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},iu=()=>{let e=new RA().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");TA(t.command("merge-dev")),CA(t.command("list")),$A(t.command("create")),OA(t.command("edit")),IA(t.command("deploy-all")),DA(t.command("deploy-selected")),NA(t.command("deliver")),_A(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");jA(r.command("add")),FA(r.command("list")),LA(r.command("remove")),MA(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");UA(n.command("path")),JA(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{C(await Ps())});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=>{C(await Fi({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=>{C(await Fi({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){u.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Me.exitCode=1;return}let c=await Ss({all:a.all,root:a.root,fix:a.fix,design:a.design});C(c);let{allPassed:l,fixed:d}=c.structuredContent,p=(d??[]).some(m=>m.action==="failed");(!l||p)&&(Me.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return VA(i.command("check")),BA(i.command("config")),WA(i.command("sync")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async a=>{let c=await Zs({fix:!!a.fix});rt.enabled||uc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Me.exitCode=1),C(c)}),e.command("dev").description("Run local dev servers for a preset or an app (or every app); api + ui").argument("[preset]","A devServersPresets name, or an app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),d=!!(Me.stdout.isTTY&&Me.stdin.isTTY);await l({...c,preset:a},d,rt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{C(await xs())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{C(await ei({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{C(await Pi({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{C(await Ai())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{C(await ri())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{C(await Fp())}),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=>{Iy(await ma({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Iy(await ti())}),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)=>{C(await jd({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=>{C(await ni({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=>{C(await _d({env:a}))}),e.commands.forEach(Wu),ou(e),su(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&EA(PA(Me.cwd(),l)),h.start(Zi(c)),rt.enabled=!!c.optsWithGlobals().json,rt.enabled&&(u.level="warn"),I.source=Zo({env:Me.env,stdinIsTTY:Me.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),GA.has(Zi(c))||await Dc()}),e.hook("postAction",(a,c)=>{let l=Zi(c);if(Ad(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",g=`infra-kit ${l}${m}`;Cy({equivalent:Yi(g,!0)})}),e};import KA from"node:process";var HA={exit:KA.exit,emit:C,logger:u},Ny=(e,t=HA)=>ve(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof x?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var au=(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 qA from"node:fs";import _y from"node:path";import Wo from"node:process";var Fy=new Set([...op,hn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Ly=null,Qi=new Set,cu=null,My=!1;var jy=e=>{try{return qA.statSync(e)}catch{return null}},YA=()=>{if(My)return null;try{return yr()}catch{return My=!0,u.debug(`session-env: ${hn} unset \u2014 no overlay`),null}},zA=e=>{let t=_y.join(e,gr),r=_y.join(e,Uo),n=jy(t),o=jy(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},XA=e=>e.kind==="load"?{kind:"load",vars:yu(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:vu(e.file),signature:e.signature}:e;var ZA=()=>{let e=YA();if(e===null)return{kind:"no-session"};let t=zA(e);return t.signature===cu?null:XA(t)},QA=()=>{for(let e of Qi){let t=Ly[e];t===void 0?delete Wo.env[e]:Wo.env[e]=t}Qi.clear()},eO=(e,t,r)=>{if(Fy.has(t)){e.skipped.push(t);return}Wo.env[t]=r,Qi.add(t),e.set.push(t)},tO=(e,t)=>{if(Fy.has(t)){e.skipped.push(t);return}delete Wo.env[t],Qi.add(t),e.unset.push(t)},rO=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))eO(t,r,n);if(e.kind==="clear")for(let r of e.unset)tO(t,r);return t},nO=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,lu=(e=ZA())=>{if(Ly??={...Wo.env},e===null||e.kind==="no-session"||e.signature===cu)return{set:[],unset:[],changed:!1};QA();let{set:t,unset:r,skipped:n}=rO(e);return cu=e.signature,n.length>0&&u.warn(`session-env: skipped protected names [${n.join(", ")}]`),u.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${nO(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as PO}from"chalk";import{spawn as EO}from"node:child_process";import Pe from"node:process";import{Chalk as oO}from"chalk";var gn=new oO({level:1}),Be={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},sO={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},By={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Vy={unicode:"\u2500",ascii:"-"},iO=3,du=e=>e,aO={ok:e=>gn.green(e),findings:e=>gn.yellow(e),failed:e=>gn.red(e),cancelled:e=>gn.gray(e)},pu=e=>e?{dim:t=>gn.dim(t),bold:t=>gn.bold(t)}:{dim:du,bold:du},cO=(e,t)=>e?aO[t]:du,uu=e=>[...e].length,lO=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return uu(e)<=r?e:[...e].slice(0,r).join("")},Wy=e=>{let t=pu(e.color===!0).dim,r=sO[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(lO(n,e.width))},Uy=(e,t={})=>{let r=pu(t.color===!0);return`${r.dim(Be.reproPrefix.trim())} ${r.bold(e)}`},dO=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,uO=(e,t)=>e==="findings"?t!=null?`${t} ${Be.findingsSuffix}`:Be.findingsPlain:{ok:Be.ok,failed:Be.failed,cancelled:Be.cancelled}[e],pO=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<iO?"":` ${n(r.repeat(o))}`},Jy=e=>{let t=e.color===!0,r=pu(t),n=cO(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Be.reproPrefix:Be.nonReproPrefix,i=o?By[e.outcome].ascii:By[e.outcome].unicode,a=uO(e.outcome,e.findingsCount),c=[dO(e.durationMs)],l=e.summary?.[0]?.split(`
444
- `)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,p=`${Be.sep}${c.join(Be.sep)}`,m=uu(d)+uu(p),g=pO(m,e.width,o?Vy.ascii:Vy.unicode,r.dim),y=[`${n(d)}${r.dim(p)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Be.envNotice)),y.join(`
445
- `)};var mO=new Set([130,143]),Gy=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&mO.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import fO from"node:process";var gO={3:"quit",4:"quit",26:"suspend",27:"quit"},hO=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":gO[t]??"continue"},yO=150,vO="\r\x1B[2K",wO=`\r
446
- `,Ky=(e,t)=>{Hy(e),e.stdin.on("data",t),e.listener=t},Hy=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},qy=(e,t)=>{vp(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Ky(e,t)},Yy=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(vO)),Hy(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),wp()},kO=e=>{e.settled||(e.settled=!0,Yy(e))},zy=(e,t)=>{let r=Wy({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},bO=async e=>{await new Promise(t=>{setTimeout(t,e)})},RO=(e,t,r)=>{Yy(e),t(),qy(e,r),zy(e,wO)},SO=async e=>new Promise(t=>{let r=n=>{let o=hO(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){RO(e,s,r);return}t("palette")};Ky(e,r),zy(e,"")}),Xy=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??fO.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return qy(n,()=>{}),e.armed(),await bO(t.drainMs??yO),await SO(n)}finally{kO(n)}};import Zy from"node:process";var jt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Qy=(e,t)=>{let r=t?.write??(s=>{Zy.stderr.write(s)}),n=t?.stdin??Zy.stdin,o=[jt.saveCursor,jt.scrollRegion,jt.restoreCursor,jt.column,jt.sgr,jt.cursor,jt.wrap];e.entersAltScreen===!0&&o.push(jt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var ev=e=>`infra-kit ${e.groupPath.join(" ")}`,xO=()=>{TO();let e=Pe.stderr.columns;return e!=null&&e>0?e:void 0},TO=()=>{let e=Pe.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},CO=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),$O=async(e,t,r)=>{let n=$y(),o={...t.env,[Xi]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Pe.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await CO(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Ay(n),c=Gy(i.code,i.signal,a!=null,e.longRunning),l=ev(e),d=a?.equivalent??Yi(l,!0);return Jy({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},AO=1e3,OO=(e,t)=>e!=null&&t-e<=AO,mu=e=>{e.resetTerminal(),e.exit(0)},IO=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&mu(t)},s=()=>{let c=e();if(c==="palette"){mu(t);return}if(!OO(r,t.now())){if(c==="pause"){mu(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}},tv=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),DO=Pe.platform==="win32"?void 0:()=>{kp()},NO=(e,t)=>r=>Xy(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:DO}),rv=async(e,t)=>{let r={spawn:t.spawn??EO,now:t.now??(()=>Date.now()),env:t.env??Pe.env,cliPath:t.cliPath,ascii:t.ascii??!(Pe.stdout.isTTY&&Pe.env.TERM!=="dumb"),color:t.color??PO.level>0,columns:t.columns??xO,resetTerminal:t.resetTerminal??(d=>{Qy(d)})},n=t.write??(d=>Pe.stderr.write(d)),o="palette",s=t.signals??{register:(d,p)=>{Pe.on(d,p)},unregister:(d,p)=>{Pe.off(d,p)},exit:d=>{Pe.exit(d)},raise:d=>{Pe.kill(Pe.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:IO(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??NO(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let p=t.resolveCommand(d);if(!p)continue;let m=Uy(ev(p),{color:r.color});n(`
450
+ `)},rI=async(e,t,r)=>r?(gv(t,vn(t)),bu(t.root,e)):(await ku({source:e,plan:t,onBeforeFirstWrite:o=>{gv(t,o)}})).touched,nI=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await rI(e,t,!!r.manifestOnly)}catch(s){return{plan:t,applied:!1,error:s instanceof Error?s.message:String(s)}}if(!r.commit)return{plan:t,applied:!0};let o=await Su(t.root,n,Ru(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},oI=async(e,t,r)=>{let n=[];for(let o of t)n.push(await nI(e,o,r));return n},wv=e=>e.map(t=>({name:t.name,root:t.root,status:t.status,message:t.message,notes:t.notes,warnings:t.warnings,branch:t.branch})),$u=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&ze(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:wv(s).map((a,c)=>{let l=r[c];return{...a,applied:l.applied,error:l.error,commit:l.commit}}),changed:s.some(a=>a.status==="changed"),failed:dv(t),report:t.sections}}},sI=async e=>{let t=await ri(),r=eI(t),n=await pv(r),o=await tI(r),s=mv(t,e.targets??[]),i=await Eu(r,o),a=await fv(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},Au=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await sI(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=xu(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return $u({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!J();if(l&&!yv.stdin.isTTY)return ze(a),$u({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&ze({...a,hints:[]}),await V(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:wv(n),throwOnDecline:!0});let d=await oI(t,n,e),p=xu(r,d,{...s,mode:"applied"});if(l){let m=d.filter(g=>g.applied).map(g=>g.plan.name);ze(uv(a,p,m))}return $u({mode:"applied",report:p,outcomes:d,source:t,print:!l})};var ca=(e,t=!0)=>({line:e,reproducible:t});import la from"node:fs";import iI from"node:os";import aI from"node:path";import Sv from"node:process";var da="INFRA_KIT_SESSION_REPORT",Ou=null,kv=!1,bv=[],Pv=(e=Sv.env)=>{kv||(Ou=e[da]??null,kv=!0,delete e[da])};var Ev=(e,t)=>{if(!Ou)return;let r=e.summary??(bv.length>0?[...bv]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{la.writeFileSync(s,i)});try{o(Ou,JSON.stringify(n))}catch{}},Rv=0,xv=e=>{let t=e?.tmpdir?.()??iI.tmpdir(),r=e?.pid??Sv.pid;return Rv+=1,aI.join(t,`infra-kit-session-${r}-${Rv}.json`)},Tv=(e,t)=>{if(!(t?.exists??(i=>la.existsSync(i)))(e))return null;let n=t?.read??(i=>la.readFileSync(i,"utf-8")),o=t?.unlink??(i=>la.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Iu=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(Iu)};var Du=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Du)};var pI=(e,t)=>[...t,e],Cv=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&yr.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${yr.join(", ")}.`)}},mI=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").option("--keep-conflicts","On the confirmed run, leave each conflicted branch mid-merge in <root>-worktrees/merge-dev/ for resolution").option("--continue","Check, preview, then commit and push the selected resolutions left by --keep-conflicts").option("--abort","Discard the selected resolutions left by --keep-conflicts").option("--tree <branch=sha>","With --continue --yes: the approved tree per branch, as a --continue preview prints it (repeatable)",(t,r)=>[...r??[],t]).action(async t=>{let r=await Of(()=>wi({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));A(r),r.structuredContent.failedMerges>0&&(Fe.exitCode=1)}),$v=e=>(Fe.stdout.write(`${e.structuredContent.filePath}
451
+ `),A(e)),fI=e=>e.description("List all release branches").action(async()=>{A(await Ei())}),gI=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".',pI,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(wl),o=n.length>0?n:void 0;A(await Ai({releases:o,confirmedCommand:t.yes}))}),hI=e=>{if(e==="")return e;try{return ar(e)}catch(t){throw t instanceof cn?new lI(t.message):t}},yI=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)',hI).option("-y, --yes","Skip confirmation prompt").action(async t=>{A(await Oi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Av=e=>e.option("-f, --from <where>",`Where the deploy runs: ${_t.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"),vI=e=>Av(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{A(await fu({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),wI=e=>Av(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=>{A(await gu({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),kI=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=>{A(await Ri({version:t.version,confirmedCommand:t.yes}))}),bI=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=>{A(await ji({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),RI=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{A(await zi({confirmedCommand:t.yes}))}),SI=e=>e.description("Add git worktrees for release branches or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").option("-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=Cv(t.ide,"--ide")??Cv(t.cursor,"--cursor");A(await Hi({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),PI=e=>e.description("List all git worktrees with detailed information").action(async()=>{A(await qi())}),EI=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").action(async t=>{A(await Yi({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature}))}),xI=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=>{A(await yu({init:t.init}))}),TI=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ji();A(t),t.structuredContent.ok||(Fe.exitCode=1)}),CI=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan").option("--check","Preview only; exit 1 when any target would change").option("--commit","Commit exactly the synced paths in each target after it syncs").option("--manifest-only","Rewrite vendor/README.md and vendor/.sync-manifest.json only; copy nothing").action(async(t,r)=>{let n;try{n=await Au({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!ot(a))throw a;u.info("Operation cancelled.");return}A(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),$I=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{A(await iu())}),AI=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{A(await au())}),OI=new Set(["version"]),ua=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Nu=()=>{let e=new cI().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");mI(t.command("merge-dev")),fI(t.command("list")),gI(t.command("create")),yI(t.command("edit")),vI(t.command("deploy-all")),wI(t.command("deploy-selected")),kI(t.command("deliver")),bI(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");SI(r.command("add")),PI(r.command("list")),EI(r.command("remove")),RI(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");$I(n.command("path")),AI(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. ide)").action(async a=>{A(await Ls({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, ide)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '[{"provider":"orca"}]')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{A(await kc({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{A(await cu({key:a,global:c.global}))});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{A(await Zi({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{A(await Zi({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){u.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await Ms({all:a.all,root:a.root,fix:a.fix,design:a.design});A(c);let{allPassed:l,fixed:d}=c.structuredContent,p=(d??[]).some(m=>m.action==="failed");(!l||p)&&(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return TI(i.command("check")),xI(i.command("config")),CI(i.command("sync")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async a=>{let c=await pi({fix:!!a.fix});Jt.enabled||Ac(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Fe.exitCode=1),A(c)}),e.command("dev").description("Run local dev servers for a preset or an app (or every app); api + ui").argument("[preset]","A devServersPresets name, or an app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),d=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,preset:a},d,Jt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{A(await Bs())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{A(await fi({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,playwrightArgs:a}))}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{A(await Li({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{A(await Gi())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{A(await yi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{A(await pm())}),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=>{$v(await Ca({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{$v(await hi())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");A(await pu({fromFile:c.fromFile,force:c.force}));return}A(await uu({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=>{A(await vi({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=>{A(await lu({env:a}))}),e.commands.forEach(hp),Iu(e),Du(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&uI(dI(Fe.cwd(),l)),h.start(ua(c)),Jt.enabled=!!c.optsWithGlobals().json,Jt.enabled&&(u.level="warn"),N.source=us({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),OI.has(ua(c))||await Zc()}),e.hook("postAction",(a,c)=>{let l=ua(c);if(nu(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",g=`infra-kit ${l}${m}`;Ev({equivalent:ca(g,!0)})}),e};import II from"node:process";var DI={exit:II.exit,emit:A,logger:u},Ov=(e,t=DI)=>be(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof x?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var _u=(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 NI from"node:fs";import Mu from"node:path";import wn from"node:process";var Nv=new Set([...Ip,bn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),_v=null,pa=new Set,ju=null,Iv=!1;var Dv=e=>{try{return NI.statSync(e)}catch{return null}},_I=()=>{if(Iv)return null;try{return Rr()}catch{return Iv=!0,u.debug(`session-env: ${bn} unset \u2014 no overlay`),null}},MI=e=>{let t=Mu.join(e,kr),r=Mu.join(e,ts),n=Dv(t),o=Dv(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?qu(Mu.join(e,rs),wn.cwd())?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:{kind:"none",signature:"none"}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},jI=e=>e.kind==="load"?{kind:"load",vars:Gu(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Ku(e.file),signature:e.signature}:e;var FI=()=>{let e=_I();if(e===null)return{kind:"no-session"};let t=MI(e);return t.signature===ju?null:jI(t)},LI=()=>{for(let e of pa){let t=_v[e];t===void 0?delete wn.env[e]:wn.env[e]=t}pa.clear()},BI=(e,t,r)=>{if(Nv.has(t)){e.skipped.push(t);return}wn.env[t]=r,pa.add(t),e.set.push(t)},WI=(e,t)=>{if(Nv.has(t)){e.skipped.push(t);return}delete wn.env[t],pa.add(t),e.unset.push(t)},VI=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))BI(t,r,n);if(e.kind==="clear")for(let r of e.unset)WI(t,r);return t},UI=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Fu=(e=FI())=>{if(_v??={...wn.env},e===null||e.kind==="no-session"||e.signature===ju)return{set:[],unset:[],changed:!1};LI();let{set:t,unset:r,skipped:n}=VI(e);return ju=e.signature,n.length>0&&u.warn(`session-env: skipped protected names [${n.join(", ")}]`),u.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${UI(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as dD}from"chalk";import{spawn as uD}from"node:child_process";import Te from"node:process";import{Chalk as JI}from"chalk";var kn=new JI({level:1}),Ue={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},GI={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"}},Mv={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},jv={unicode:"\u2500",ascii:"-"},KI=3,Lu=e=>e,HI={ok:e=>kn.green(e),findings:e=>kn.yellow(e),failed:e=>kn.red(e),cancelled:e=>kn.gray(e)},Wu=e=>e?{dim:t=>kn.dim(t),bold:t=>kn.bold(t)}:{dim:Lu,bold:Lu},qI=(e,t)=>e?HI[t]:Lu,Bu=e=>[...e].length,YI=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Bu(e)<=r?e:[...e].slice(0,r).join("")},Fv=e=>{let t=Wu(e.color===!0).dim,r=GI[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(YI(n,e.width))},Lv=(e,t={})=>{let r=Wu(t.color===!0);return`${r.dim(Ue.reproPrefix.trim())} ${r.bold(e)}`},zI=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,XI=(e,t)=>e==="findings"?t!=null?`${t} ${Ue.findingsSuffix}`:Ue.findingsPlain:{ok:Ue.ok,failed:Ue.failed,cancelled:Ue.cancelled}[e],ZI=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<KI?"":` ${n(r.repeat(o))}`},Bv=e=>{let t=e.color===!0,r=Wu(t),n=qI(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ue.reproPrefix:Ue.nonReproPrefix,i=o?Mv[e.outcome].ascii:Mv[e.outcome].unicode,a=XI(e.outcome,e.findingsCount),c=[zI(e.durationMs)],l=e.summary?.[0]?.split(`
452
+ `)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,p=`${Ue.sep}${c.join(Ue.sep)}`,m=Bu(d)+Bu(p),g=ZI(m,e.width,o?jv.ascii:jv.unicode,r.dim),y=[`${n(d)}${r.dim(p)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Ue.envNotice)),y.join(`
453
+ `)};var QI=new Set([130,143]),Wv=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&QI.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import eD from"node:process";var tD={3:"quit",4:"quit",26:"suspend",27:"quit"},rD=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":tD[t]??"continue"},nD=150,oD="\r\x1B[2K",sD=`\r
454
+ `,Vv=(e,t)=>{Uv(e),e.stdin.on("data",t),e.listener=t},Uv=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},Jv=(e,t)=>{Kp(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Vv(e,t)},Gv=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(oD)),Uv(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Hp()},iD=e=>{e.settled||(e.settled=!0,Gv(e))},Kv=(e,t)=>{let r=Fv({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},aD=async e=>{await new Promise(t=>{setTimeout(t,e)})},cD=(e,t,r)=>{Gv(e),t(),Jv(e,r),Kv(e,sD)},lD=async e=>new Promise(t=>{let r=n=>{let o=rD(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){cD(e,s,r);return}t("palette")};Vv(e,r),Kv(e,"")}),Hv=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??eD.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return Jv(n,()=>{}),e.armed(),await aD(t.drainMs??nD),await lD(n)}finally{iD(n)}};import qv from"node:process";var Vt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Yv=(e,t)=>{let r=t?.write??(s=>{qv.stderr.write(s)}),n=t?.stdin??qv.stdin,o=[Vt.saveCursor,Vt.scrollRegion,Vt.restoreCursor,Vt.column,Vt.sgr,Vt.cursor,Vt.wrap];e.entersAltScreen===!0&&o.push(Vt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var zv=e=>`infra-kit ${e.groupPath.join(" ")}`,pD=()=>{mD();let e=Te.stderr.columns;return e!=null&&e>0?e:void 0},mD=()=>{let e=Te.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},fD=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),gD=async(e,t,r)=>{let n=xv(),o={...t.env,[da]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Te.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await fD(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Tv(n),c=Wv(i.code,i.signal,a!=null,e.longRunning),l=zv(e),d=a?.equivalent??ca(l,!0);return Bv({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},hD=1e3,yD=(e,t)=>e!=null&&t-e<=hD,Vu=e=>{e.resetTerminal(),e.exit(0)},vD=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Vu(t)},s=()=>{let c=e();if(c==="palette"){Vu(t);return}if(!yD(r,t.now())){if(c==="pause"){Vu(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}},Xv=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),wD=Te.platform==="win32"?void 0:()=>{qp()},kD=(e,t)=>r=>Hv(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:wD}),Zv=async(e,t)=>{let r={spawn:t.spawn??uD,now:t.now??(()=>Date.now()),env:t.env??Te.env,cliPath:t.cliPath,ascii:t.ascii??!(Te.stdout.isTTY&&Te.env.TERM!=="dumb"),color:t.color??dD.level>0,columns:t.columns??pD,resetTerminal:t.resetTerminal??(d=>{Yv(d)})},n=t.write??(d=>Te.stderr.write(d)),o="palette",s=t.signals??{register:(d,p)=>{Te.on(d,p)},unregister:(d,p)=>{Te.off(d,p)},exit:d=>{Te.exit(d)},raise:d=>{Te.kill(Te.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:vD(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??kD(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let p=t.resolveCommand(d);if(!p)continue;let m=Lv(zv(p),{color:r.color});n(`
447
455
  ${m}
448
- `),a.childStarted();let g=await $O(p,r,()=>{o="child"});if(n(`
456
+ `),a.childStarted();let g=await gD(p,r,()=>{o="child"});if(n(`
449
457
  ${g}
450
- `),await l(c)==="quit")return}}finally{a.dispose()}};Id();Ty();var iv=iu(),ov=async(e=Ee.argv)=>{lu(),hp(e);try{await iv.parseAsync(e)}catch(t){Ny(t)}},LO=()=>{try{if(Ee.env.INFRA_KIT_NO_LOCATION_WARN||Ee.argv.includes("--json"))return;Pu({selfRealPath:jO(sv(import.meta.url)),cwd:Ee.cwd(),env:Ee.env,realpath:me,home:FO(),exists:MO})&&u.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};LO();Vu((e,t)=>{u.debug(e,t)});_c(G.version);var av=()=>Kh(iv.commands),BO=async()=>{let e=av(),t=null;try{if(Ee.stdout.isTTY&&Ee.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=au(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new nv(" "),new nv(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await O(o=>_O({message:"Select a command to run",choices:n},o),{output:Ee.stderr})}}catch(r){if(!ve(r))throw r}return t},VO=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=sv(import.meta.url),r=new Map(nr.map(n=>[n.groupPath.join(" "),n]));await rv(av(),{renderPalette:e,resolveCommand:n=>{let o=r.get(n);return o?{groupPath:o.groupPath,entersAltScreen:o.entersAltScreen,sessionEnvNotice:o.sessionEnvNotice,longRunning:o.longRunning}:void 0},cliPath:t})};if(Ee.argv.length<=2){let e={stdoutIsTTY:!!Ee.stdout.isTTY,stdinIsTTY:!!Ee.stdin.isTTY,stderrIsTTY:!!Ee.stderr.isTTY};if(tv(Ee.env,e))await VO();else{let t=await BO();t&&await ov(["node","infra-kit",...t.split(" ")])}}else await ov();
458
+ `),await l(c)==="quit")return}}finally{a.dispose()}};su();Pv();var rw=Nu(),ew=async(e=Ce.argv)=>{Fu(),Jp(e);try{await rw.parseAsync(e)}catch(t){Ov(t)}},ED=()=>{try{if(Ce.env.INFRA_KIT_NO_LOCATION_WARN||Ce.argv.includes("--json"))return;Zu({selfRealPath:SD(tw(import.meta.url)),cwd:Ce.cwd(),env:Ce.env,realpath:he,home:PD(),exists:RD})&&u.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};ED();gp((e,t)=>{u.debug(e,t)});el(K.version);var nw=()=>jy(rw.commands),xD=async()=>{let e=nw(),t=null;try{if(Ce.stdout.isTTY&&Ce.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=_u(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new Qv(" "),new Qv(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await O(o=>bD({message:"Select a command to run",choices:n},o),{output:Ce.stderr})}}catch(r){if(!be(r))throw r}return t},TD=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=tw(import.meta.url),r=new Map(lr.map(n=>[n.groupPath.join(" "),n]));await Zv(nw(),{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(Ce.argv.length<=2){let e={stdoutIsTTY:!!Ce.stdout.isTTY,stdinIsTTY:!!Ce.stdin.isTTY,stderrIsTTY:!!Ce.stderr.isTTY};if(Xv(Ce.env,e))await TD();else{let t=await xD();t&&await ew(["node","infra-kit",...t.split(" ")])}}else await ew();
451
459
  //# sourceMappingURL=cli.js.map