infra-kit 0.3.13 → 0.3.15

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/LICENSE +21 -0
  2. package/dist/chunk-KATIE633.js +247 -0
  3. package/dist/chunk-KATIE633.js.map +7 -0
  4. package/dist/chunk-MKMT6KQT.js +10 -0
  5. package/dist/chunk-MKMT6KQT.js.map +7 -0
  6. package/dist/chunk-OKO3DKIM.js +7 -0
  7. package/dist/{chunk-QLAQ7F4M.js.map → chunk-OKO3DKIM.js.map} +4 -4
  8. package/dist/{chunk-RVTI3AL2.js → chunk-VDBJ73LS.js} +5 -5
  9. package/dist/chunk-VDBJ73LS.js.map +7 -0
  10. package/dist/{chunk-DPCWCXJD.js → chunk-VFU2USJG.js} +2 -2
  11. package/dist/{chunk-DPCWCXJD.js.map → chunk-VFU2USJG.js.map} +2 -2
  12. package/dist/chunk-XR6HR4LL.js +6 -0
  13. package/dist/{chunk-SSBYKOHY.js.map → chunk-XR6HR4LL.js.map} +4 -4
  14. package/dist/chunk-YDW6324A.js +2 -0
  15. package/dist/chunk-YDW6324A.js.map +7 -0
  16. package/dist/cli.js +9 -9
  17. package/dist/cli.js.map +3 -3
  18. package/dist/dev-server.js +24 -32
  19. package/dist/dev-server.js.map +4 -4
  20. package/dist/dev-wizard-run-AU7SZJV7.js +2 -0
  21. package/dist/{dev-wizard-run-XM5L23UP.js.map → dev-wizard-run-AU7SZJV7.js.map} +1 -1
  22. package/dist/mcp.js +1 -1
  23. package/dist/mcp.js.map +4 -4
  24. package/dist/persistent-ink-dev-ui-QNFTO2B2.js +2 -0
  25. package/dist/persistent-ink-dev-ui-QNFTO2B2.js.map +7 -0
  26. package/dist/update-check.js +1 -1
  27. package/dist/update-check.js.map +1 -1
  28. package/package.json +28 -28
  29. package/readme.md +1 -1
  30. package/dist/chunk-2QJAIOPI.js +0 -2
  31. package/dist/chunk-2QJAIOPI.js.map +0 -7
  32. package/dist/chunk-LMAO6FEM.js +0 -238
  33. package/dist/chunk-LMAO6FEM.js.map +0 -7
  34. package/dist/chunk-QLAQ7F4M.js +0 -7
  35. package/dist/chunk-RVTI3AL2.js.map +0 -7
  36. package/dist/chunk-SHFPI4QA.js +0 -2
  37. package/dist/chunk-SHFPI4QA.js.map +0 -7
  38. package/dist/chunk-SSBYKOHY.js +0 -4
  39. package/dist/dev-wizard-run-XM5L23UP.js +0 -2
  40. package/dist/persistent-ink-dev-ui-PLLSRSGL.js +0 -2
  41. package/dist/persistent-ink-dev-ui-PLLSRSGL.js.map +0 -7
@@ -0,0 +1,247 @@
1
+ import{a as Ns,b as Fs,c as Rt,d as _r,e as Ls,f as Ws,g as Vs,h as Bs,i as go,j as Js,m as zs,o as Nr,p as ar,q as cr,r as At,s as It,w as lr,x as _t,y as pr}from"./chunk-MKMT6KQT.js";import{a as $t}from"./chunk-VFU2USJG.js";import{a as Et,c as Q,d as b,e as Ct,f as ee,i as g,j as Us,k as C,l as B}from"./chunk-OKO3DKIM.js";import{$ as fo,A as po,B as Ts,C as Ss,D as Cs,E as uo,F as mo,G as $s,J as l,L as As,N as Is,U as _s,X as Os,Y as Ds,Z as Te,_ as Ms,a as yt,aa as se,b as h,ca as j,d as er,da as T,e as ys,ea as js,f as wt,fa as rr,g as N,h as X,i as oe,j as ws,k as co,l as G,m as D,n as Me,o as ks,p as kt,q as ne,r as x,s as Pe,t as bs,u as bt,v as Rs,w as Es,x as xs,y as Ps,z as lo}from"./chunk-XR6HR4LL.js";import{a as q,b as xt,c as Or,d as Ks,e as Pt,f as tr,g as or,h as Tt,i as nr,j as je,k as sr,l as St,n as ir,o as Gs,p as Fe,q as Le,r as ie}from"./chunk-CHETBZ6M.js";import jr from"node:path";import Mc from"node:process";import{z as H}from"zod";var Se={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},ho={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"]},vo=(e,r=Se)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import bc from"node:fs/promises";var pe=async e=>{try{return await bc.access(e),!0}catch{return!1}};import Nc from"node:path";import{packageConfigSchema as Rc}from"@slip-stream-kit/config/internal";import qs from"node:fs/promises";import Hs from"node:path";import{pathToFileURL as Ec}from"node:url";import{z as xc}from"zod";var Ce="infra-kit.config.ts",yo=async e=>{try{let r=await qs.readFile(Hs.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},Dr=async(e,r=Se)=>{let t=Hs.join(e,Ce);if(!await pe(t))throw new Error(`${Ce} not found at ${t}`);let o=await qs.stat(t),i=(await import(`${Ec(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${Ce} at ${t} has no default export`);let a=typeof i=="function"?await i():i,c=Rc.safeParse(a);if(!c.success)throw new Error(`Invalid ${Ce} at ${t}: ${xc.prettifyError(c.error)}`);return vo(c.data,r)};import Ys from"node:fs/promises";import Ot from"node:path";import Pc from"yaml";var Tc="pnpm-workspace.yaml",Sc=async e=>(await Ys.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Ot.join(e,t.name)),Cc=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await Sc(o));continue}let s=Ot.join(o,r);await pe(s)&&t.push(s)}return t},$c=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await Cc(t,o);return t},Mr=async e=>{let r=await Ys.readFile(Ot.join(e,Tc),"utf-8"),o=((Pc.parse(r)??{}).packages??[]).filter(n=>!n.startsWith("!")&&!n.startsWith("vendor")),s=new Set;for(let n of o){let i=await $c(e,n);for(let a of i)await pe(Ot.join(a,"package.json"))&&s.add(a)}return[...s].sort()};var wo=async(e,r=Se)=>{try{let t=await Dr(e,r);return{check:{name:Ce,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:Ce,status:"fail",message:t.message},rules:null}}};import Ac from"node:fs/promises";import Ic from"node:path";var ko=async(e,r)=>Promise.all(r.map(async t=>{let o=await Ac.stat(Ic.join(e,t)).catch(()=>null);return o?o.isFile()?{name:`file:${t}`,status:"pass",message:"exists"}:{name:`file:${t}`,status:"fail",message:`not a file: ${t} (found a directory)`}:{name:`file:${t}`,status:"fail",message:`missing file: ${t}`}}));var bo=(e,r)=>r.map(t=>{let o=e[t];return typeof o!="string"?{name:`script:${t}`,status:"fail",message:`missing "${t}" in package.json scripts`}:o.trim().length===0?{name:`script:${t}`,status:"fail",message:`"${t}" is empty in package.json scripts`}:{name:`script:${t}`,status:"pass",message:"defined"}});import _c from"node:fs/promises";import Oc from"node:path";var dr="turbo.json",Ro=async(e,r)=>{if(r.length===0)return[];let t;try{let s=await _c.readFile(Oc.join(e,dr),"utf-8");t=JSON.parse(s)}catch(s){return[{name:dr,status:"fail",message:`cannot read/parse ${dr}: ${s.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:dr,status:"fail",message:`no "tasks" object defined in ${dr}`}]:r.map(s=>{let n=s in o||`//#${s}`in o;return{name:`turbo:${s}`,status:n?"pass":"fail",message:n?"defined":`missing turbo task "${s}" in ${dr}`}})};var Eo=async(e,r=Se)=>{let t=await yo(e),o=t.name??Nc.basename(e),{check:s,rules:n}=await wo(e,r),i=[s];n&&(i.push(...bo(t.scripts??{},n.requiredScripts)),i.push(...await ko(e,n.requiredFiles)),i.push(...await Ro(e,n.turboTasks)));let a=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:a}};var w=e=>[{type:"text",text:e}],k=e=>e;var Dc=(e,r)=>[...r.map(t=>({name:`devServersPresets:config:${t.app}`,status:"fail",message:`could not load apps/${t.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${t.message}`})),...e.map(t=>({name:`devServersPresets:${t.preset}`,status:"fail",message:t.message}))],Zs=async e=>{let r=(await T()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=_s(r);if(t.length>0){let u=t.map(d=>({name:`devServersPresets:${d.preset}`,status:"fail",message:d.message}));return{packageDir:e,packageName:"devServersPresets",checks:u,passed:!1}}let o=As(e),s=Is(e),n={api:o.map(u=>u.name),ui:s.map(u=>u.name)},{ctx:i,loadErrors:a}=await Ns(e,r,n,o),c=Dc(Os(r,i),a),p=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:p,passed:c.length===0}};var jc=async e=>{let r=jr.resolve(e);for(;r!==jr.dirname(r);){if(await pe(jr.join(r,"package.json")))return r;r=jr.dirname(r)}if(await pe(jr.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)},Fc=async e=>e.root?[{dir:await x(),baseline:ho}]:e.all?(await Mr(await x())).map(t=>({dir:t})):[{dir:await jc(e.cwd??Mc.cwd())}],Lc=e=>{let r=0,t=0;for(let i of e)for(let a of i.checks)r+=1,a.status!=="pass"&&(t+=1,l.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let o=e.every(i=>i.passed),s=(i,a)=>`${i} ${a}${i===1?"":"s"}`,n=`${s(r,"check")}, ${s(e.length,"target")}`;return l.info(o?`\u2705 audit passed \u2014 ${n}`:`\u274C audit failed \u2014 ${t}/${n}`),o},Xs=async(e={})=>{let r=await Fc(e),t=[];for(let n of r)t.push(await Eo(n.dir,n.baseline));if(e.root){let n=await Zs(r[0].dir);n&&t.push(n)}let s={allPassed:Lc(t),packages:t.map(n=>({name:n.packageName,passed:n.passed,checks:n.checks}))};return{content:w(JSON.stringify(s,null,2)),structuredContent:s}},Wc={all:H.boolean().optional().describe("Audit every non-vendor workspace package"),root:H.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Vc={allPassed:H.boolean().describe("Whether every audited package passed all checks"),packages:H.array(H.object({name:H.string(),passed:H.boolean(),checks:H.array(H.object({name:H.string(),status:H.enum(["pass","fail"]),message:H.string()}))})).describe("Per-package check results")},xo=k({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:Wc,outputSchema:Vc,handler:e=>Xs({all:e.all,root:e.root})});import{z as Fr}from"zod";var Qs=async()=>{let[e,r]=await Promise.all([T(),j()]),t=Object.keys(e).sort();l.info(`Merged config for ${r.projectName} \u2014 ${t.length} section(s): ${t.join(", ")}`),l.info(` source: ${r.main}`);let o={config:e,configPath:r.main,projectName:r.projectName};return{content:w(JSON.stringify(o,null,2)),structuredContent:o}},Bc={config:Fr.record(Fr.string(),Fr.unknown()).describe("The fully resolved infra-kit configuration \u2014 the same object every command sees at runtime, after the project infra-kit.json, the user-global, and the user-scope per-project override layers are merged (later layers win). Top-level sections include envManagement, ide, worktrees, envAutoLoad, dev, devServersPresets, and devProxy."),configPath:Fr.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:Fr.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Po=k({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config edit` (CLI-only) to modify the override file. Fails with the loader error when run outside a configured infra-kit repo.",inputSchema:{},outputSchema:Bc,handler:()=>Qs()});import qc from"node:fs";import{z as F}from"zod";import Lr from"node:fs";import ur from"node:path";import Jc from"node:process";var Kc=ur.join(".infra-kit","dev-context"),Gc=".infra-kit",ei=(e,r)=>{let t=ur.resolve(e);for(;;){let o=ur.join(t,r);if(Lr.existsSync(o))return o;let s=ur.dirname(t);if(s===t)return;t=s}},Uc=e=>{let r=ei(e,Kc);if(r)return r;let t=ei(e,Gc);return t?ur.join(t,"dev-context"):void 0},To=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Nt=e=>typeof e=="string"?e:"",zc=(e,r,t)=>{let o=ur.join(e,r);try{let s=Lr.statSync(o),n=JSON.parse(Lr.readFileSync(o,"utf-8"));if(typeof n!="object"||n===null)return null;let i=n;return{app:r.replace(/\.json$/,""),package:Nt(i.package),port:To(i.port),alias:Nt(i.alias),origin:Nt(i.origin),release:Nt(i.release),pid:To(i.pid),writtenAt:To(i.writtenAt),mtimeMs:Math.round(s.mtimeMs),ageMs:Math.max(0,Math.round(t-s.mtimeMs))}}catch{return null}},So=(e=Jc.cwd())=>{let r=Date.now(),t=Uc(e);if(!t||!Lr.existsSync(t))return{session:"none",fragmentDir:t,readAt:r,apps:[]};let o;try{o=Lr.readdirSync(t).filter(n=>n.endsWith(".json"))}catch{return{session:"none",fragmentDir:t,readAt:r,apps:[]}}let s=o.map(n=>zc(t,n,r)).filter(n=>n!==null).sort((n,i)=>n.app.localeCompare(i.app));return{session:s.length>0?"active":"none",fragmentDir:t,readAt:r,apps:s}};var ri=async(e={})=>{let r=e.now??Date.now,t=e.isListening??_r,o=So(e.cwd),s=r(),n=await Promise.all(o.apps.map(async d=>{let f=Math.max(0,Math.round((s-d.mtimeMs)/1e3)),v=await t(d.port);return{app:d.app,package:d.package,port:d.port,pid:d.pid,alias:d.alias,origin:d.origin,release:d.release,writtenAt:d.writtenAt>0?new Date(d.writtenAt).toISOString():null,fragmentMtime:new Date(d.mtimeMs).toISOString(),ageSeconds:f,live:v}})),i=n.length>0,a=o.fragmentDir??null,c=a!==null&&(qc.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),p=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){l.info(`infra-kit dev: ${n.length} app(s) with a dev-context fragment in ${p}:`);for(let d of n){let f=d.live?"live":"NOT responding",v=`written ${d.ageSeconds}s ago`;l.info(` ${d.app} (${d.package}) \u2192 ${d.origin} on :${d.port} \u2014 ${f}, ${v}`)}}else{let d=c?"no readable fragment found there":"that directory does not exist";l.info(`No active infra-kit dev session \u2014 searched ${p} (${d}).`)}let u={active:i,apps:n,contextDir:a,contextDirExists:c};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}},Hc={active:F.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:F.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:F.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:F.array(F.object({app:F.string().describe("App folder name (the fragment filename without .json)."),package:F.string().describe("The app package name the vite helper reads to decide a local route."),port:F.number().describe("The actual bound port the dev server is listening on."),pid:F.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:F.string().describe("Registered portless hostname for the app."),origin:F.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:F.string().describe("Release slug the runner recorded for this worktree."),writtenAt:F.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:F.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:F.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:F.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.")},Co=k({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:Hc,handler:()=>ri()});import K from"node:fs";import Zl from"node:os";import ce from"node:path";import{z as kr}from"zod";import{$ as Bi}from"zx";import{execFileSync as Yc}from"node:child_process";var ti=(e,r)=>{let t=e.filter(o=>!o.live).map(o=>o.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},Zc=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],Xc=e=>Zc.some(r=>r.test(e)),Qc="/bin/ps",el=()=>Yc(Qc,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
2
+ `),oi=(e=el)=>{try{return e().some(Xc)}catch{return!0}};import pl from"@inquirer/select";import{Buffer as dl}from"node:buffer";import ul from"node:fs";import ml from"node:path";import Mo from"node:process";import{z as Gr}from"zod";import{$ as jt}from"zx";var rl="Could not find requested project",tl="Could not find requested config",ni="Invalid Auth token",si="does not have access to requested config",Wr=e=>e.includes(ni)||e.includes(si)?"auth":e.includes(rl)?"project":e.includes(tl)?"config":"unknown",Vr=e=>e.includes(si)?"mis-scoped":e.includes(ni)?"revoked":null;var ii=e=>[`Doppler rejected the service token for env "${e}" \u2014 it is invalid, revoked, or scoped to a different config.`,`Fix: run \`infra-kit env-token-set ${e}\` with a token scoped to that config.`,"CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config."].join(`
3
+ `),mr=class extends Et{authKind;constructor(r,t=null,o){super(o??ii(r),r),this.name="DopplerAuthError",this.authKind=t}};var $o=({kind:e,project:r,config:t,available:o})=>{let s=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}".`];if(o&&o.length>0){let n=e==="project"?"Available projects":`Available configs in "${r}"`;s.push(`${n}: ${o.join(", ")}.`)}return s.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: pass an existing config, or create it in Doppler."),s.join(`
4
+ `)};import{$ as Dt}from"zx";var ol=5e3,nl="DOPPLER_CONFIG",We=async()=>{let{envManagement:e}=await T();return e.config.name},Br=async({childEnv:e,project:r,config:t})=>{let o=Dt.quiet;Dt.quiet=!0;try{let n=(await Dt({env:e})`doppler secrets get ${nl} --plain --project ${r} --config ${t}`.timeout(ol)).stdout.trim();return n!==t?{outcome:"mis-scoped",scopedTo:n}:{outcome:"valid",scopedTo:n}}catch(s){return{outcome:sl(s)}}finally{Dt.quiet=o}},sl=e=>{let r=yt(e)??(e instanceof Error?e.message:String(e));return Wr(r)!=="auth"?"unreachable":Vr(r)??"unreachable"};import ai from"node:process";var re="INFRA_KIT_ENV_TOKEN",fr=async e=>{let r=ai.env[re];if(r)return{token:r,source:"env"};let o=(await ee())?.envs[e];if(o)return{token:o,source:"store"};throw new Et(il(e,await Ct()),e)},Vg=async e=>ai.env[re]?!0:!!(await ee())?.envs[e],il=(e,r)=>[`No Doppler service token for env "${e}".`,`Mint one at https://dashboard.doppler.com \u2014 this project \u2192 config "${e}" \u2192 Access tab \u2192 "Generate Service Token".`,`Fix: run \`infra-kit env-token-set ${e}\` and paste it.`,`It is stored in ${b(r)} (mode 0600, never in the repo).`,`CI / agents: set ${re} instead \u2014 it takes precedence and needs no home config.`].join(`
5
+ `);var ci=["prod"],gr={allowed:!1,reason:"disallow"},de=e=>ci.includes(e),Ve=(e,r=gr)=>r.allowed?e:e.filter(t=>!de(t)),Be=(e,r,t=gr)=>{if(!t.allowed&&de(e))throw t.reason==="mcp-blocked"?new h(void 0,{operation:r,remediation:`run it yourself in a terminal \u2014 this project sets \`protectedEnvs: "cli-only"\`, which deliberately withholds "${e}" from agents while allowing it on the CLI`,stderrExcerpt:`"${e}" is not reachable over MCP in this project`}):new h(void 0,{operation:r,remediation:`use \`infra-kit release deliver\` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var Je=async()=>{let e;try{e=(await T()).protectedEnvs??"disallow"}catch{return gr}return e==="disallow"?gr:e==="cli-only"&&er()?{allowed:!1,reason:"mcp-blocked"}:{allowed:!0,reason:"allowed"}};var Jr=e=>{let{env:r,branch:t}=e;de(r)&&l.warn([`\u26A0\uFE0F "${r}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${t}" ships ${r} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
6
+ `))};import li from"node:fs/promises";import Ao from"node:path";import al from"yaml";var pi=".github/workflows",Ke=async e=>{let r=await x();return di(Ao.resolve(r,pi,e))},Io=async()=>{let e=await x(),r=Ao.resolve(e,pi),t;try{t=await li.readdir(r)}catch{return[]}let o=t.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")).sort(),s=await Promise.all(o.map(n=>di(Ao.resolve(r,n))));return[...new Set(s.flat())]},di=async e=>{let r;try{r=al.parse(await li.readFile(e,"utf-8"))}catch{return[]}let t=hr(r,"on")??hr(r,"true"),o=hr(hr(hr(hr(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(o)?o.filter(s=>typeof s=="string"&&s.length>0):[]},hr=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var Mt=async()=>{let e=await Io(),r=await ee(),t=e.map(n=>({env:n,source:"gh-workflow"})),o=new Set(e),s=Object.keys(r?.envs??{}).filter(n=>!o.has(n)).sort().map(n=>({env:n,source:"token-only"}));return[...t,...s]},Ge=async()=>(await Mt()).map(r=>r.env);import ui from"node:fs";import{$ as cl}from"zx";import Ue from"node:fs";import Kr from"node:path";var _o=({autoLoaded:e,projectDir:r,canonicalProjectRoot:t})=>!e||!r||!t?!1:t===r,ue=e=>{if(!e)return"";try{return Ue.realpathSync(e)}catch{return""}},Oo=(e,r)=>{try{let t=Fe(e);Ue.mkdirSync(t,{recursive:!0,mode:448}),Le(Kr.join(t,q),r,384)}catch(t){l.debug(`warm-cache write skipped: ${t.message}`)}},No=(e=Date.now(),r=Or)=>{let t=Gs(),o;try{o=Ue.readdirSync(t,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory())continue;let n=Kr.join(t,s.name);try{let{mtimeMs:i}=Ue.statSync(Kr.join(n,q));e-i>=r*1e3&&Ue.rmSync(n,{recursive:!0,force:!0})}catch{}}},Do=(e,r)=>{try{let t=Fe(e);if(r){Ue.rmSync(t,{recursive:!0,force:!0});return}if(!Ue.existsSync(Kr.join(t,q)))return;Le(Kr.join(t,xt),`# infra-kit warm cache cleared
7
+ `,384)}catch(t){l.debug(`warm-cache invalidate skipped: ${t.message}`)}};var mi=e=>e.split(`
8
+ `).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),ll=async()=>{let e;try{e=(await cl({quiet:!0})`git worktree list --porcelain`).stdout}catch(t){return l.debug(`warm-cache purge skipped (not a git repo?): ${t.message}`),[]}let r=[];for(let t of mi(e)){let o=ue(t);if(!o)continue;let s=Fe(o);try{if(!ui.existsSync(s))continue;ui.rmSync(s,{recursive:!0,force:!0}),r.push(s)}catch(n){l.debug(`warm-cache purge skipped for ${s}: ${n.message}`)}}return r};var fl=e=>e?[`${je}=${ze("1")}`]:[`unset ${je}`,`unset ${sr}`],gl="DOPPLER_CONFIG",fi=new Set(["DOPPLER_TOKEN",re]),gi=!1,hl=e=>{e.length===0||gi||(gi=!0,l.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},vi=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:s,autoLoaded:n})=>{let i=e.filter(([a])=>!fi.has(a));return hl(e.filter(([a])=>fi.has(a)).map(([a])=>a)),["set -a",...i.map(([a,c])=>`${a}=${ze(c)}`),`${Pt}=${ze(r)}`,`${tr}=${ze(r)}`,`${or}=${ze(t)}`,`${Tt}=${ze(o)}`,`${nr}=${ze(s)}`,...fl(n),"set +a"]},vl=async()=>{try{return await x()}catch{return""}},yi=async({config:e,autoLoaded:r=!1,beforeWrite:t,projectDir:o})=>{let s=await We(),n=await vl(),i=await kl(s,e),a=new Date().toISOString(),p=`${vi({pairs:i,config:e,project:s,projectRoot:n,loadedAt:a,autoLoaded:r}).join(`
9
+ `)}
10
+ `,u=ir(),d=ml.resolve(u,q);if(t&&!t())return null;ul.mkdirSync(u,{recursive:!0,mode:448}),Le(d,p,384);let f=ue(n);return _o({autoLoaded:r,projectDir:o,canonicalProjectRoot:f})&&(Oo(o,p),No()),{filePath:d,variableCount:i.length,project:s,config:e}},wi=async e=>{let{config:r}=e,t="";if(r)t=r;else{let n=await Ge();g.setInteractive(),t=await C(i=>pl({message:"Select environment config",choices:n.map(a=>({name:a,value:a}))},i),{output:Mo.stderr})}g.addOption("--config",t);let o=await yi({config:t,autoLoaded:!1});if(!o)throw new Error("env-load: write was unexpectedly aborted");Mo.stdout.write(`${o.filePath}
11
+ `),g.print();let s={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config};return{content:w(JSON.stringify(s,null,2)),structuredContent:s}},hi=1024*1024,yl=3e4,wl=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],vr=(e,r=Mo.env)=>{let t={...r};for(let o of wl)delete t[o];return t.DOPPLER_TOKEN=e,t},kl=async(e,r)=>{let{token:t}=await fr(r),o=vr(t),s=jt.quiet;jt.quiet=!0;try{let n;try{n=await jt({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(yl)}catch(a){throw bl(a,e,r)}Rl(n.stdout);let i=bi(n.stdout);return ki(i,r),i}finally{jt.quiet=s}},ki=(e,r)=>{let t=e.find(([o])=>o===gl)?.[1];if(!(t===void 0||t===r))throw new mr(r,null,`Doppler returned secrets for config "${t}" but "${r}" was requested \u2014 the service token for env "${r}" is scoped to the wrong config. Refusing to load another environment's secrets.
12
+ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},bl=(e,r,t)=>{let o=yt(e)??(e instanceof Error?e.message:String(e)),s=Wr(o);return s==="auth"?new mr(t,Vr(o)):s==="unknown"?e instanceof Error?e:new Error(String(e)):new Error($o({kind:s,project:r,config:t,available:null}))},Rl=e=>{let r=dl.byteLength(e,"utf-8");if(r>hi)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${hi}) \u2014 refusing to write to disk`)},ze=e=>`'${e.replaceAll("'","'\\''")}'`,El=/^[A-Z_]\w*$/i,bi=e=>{let r;try{r=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let t=[];for(let[o,s]of Object.entries(r)){if(!El.test(o))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(o.slice(0,80))})`);if(typeof s!="string")throw new TypeError(`doppler returned a non-string value for "${o}" (got ${typeof s})`);t.push([o,s])}if(t.length===0)throw new Error("doppler returned empty output for env-load");return t},jo=k({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. "config" is required when invoked via MCP (the CLI interactive picker is unreachable without a TTY).',inputSchema:{config:Gr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:Gr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Gr.number().describe("Number of variables loaded"),project:Gr.string().describe("Doppler project name"),config:Gr.string().describe("Doppler config name")},handler:wi});import J from"node:fs";import zr from"node:path";var yr=(e,r,t)=>{let o=e.indexOf(r),s=e.indexOf(t);return o!==-1&&s!==-1&&s>=o},$e=(e,r,t)=>{let o=e.indexOf(r),s=e.indexOf(t);if(o===-1||s===-1||s<o)return null;let n=e.slice(0,o).replace(/\n+$/,""),i=e.slice(s+t.length).replace(/^\n+/,"");return n+(i?`
13
+ ${i}`:"")};var Ri=(e,r,t)=>`${e}
14
+ ${r}
15
+ ${t}`,Ur=({content:e,body:r,startMarker:t,endMarker:o,placement:s="replace-in-place"})=>{let n=Ri(t,r,o),i=yr(e,t,o);if(s==="replace-in-place"&&i){let p=e.indexOf(t),u=e.indexOf(o)+o.length;return e.slice(0,p)+n+e.slice(u)}let c=(i?$e(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
16
+ ${n}
17
+ `:`${n}
18
+ `};var qr="<!-- infra-kit:begin -->",Hr="<!-- infra-kit:end -->",xl="<!-- infra-kit:version ",Pl="<!-- infra-kit:import:begin -->",Tl="<!-- infra-kit:import:end -->",Sl="AGENTS.md",Cl="CLAUDE.md",$l=e=>`${xl}${e} -->`,Al=e=>[$l(e),"","# infra-kit","","This repository uses the **infra-kit** CLI for environment, worktree, and release workflows.","This block is generated by `infra-kit init` \u2014 edit text *outside* the markers, never inside.","","## Commands (`ik` = `pnpm exec infra-kit`)","","- `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.","- `ik worktrees add` / `worktrees list` / `reopen` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees.","- `ik release create` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release desc-edit` \u2014 release-branch and deploy flow.","- `ik release merge-dev` \u2014 merge the dev branch into every release branch.","- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.","- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.","- `ik init` \u2014 (re)install shell integration and regenerate these agent-instruction files.","","## Conventions","","- 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.","- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets."].join(`
19
+ `),Ei=e=>{if(J.existsSync(e)&&J.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},xi=e=>{let r=new Date().toISOString().replace(/[:.]/g,"-");J.copyFileSync(e,`${e}.backup.${r}`)},Pi=(e,r)=>{Ei(e);let t=J.existsSync(e);return(t?J.readFileSync(e,"utf-8"):null)===r?"unchanged":(t&&xi(e),J.mkdirSync(zr.dirname(e),{recursive:!0}),J.writeFileSync(e,r,"utf-8"),t?"updated":"created")},Il=(e,r)=>J.existsSync(e)?J.readFileSync(e,"utf-8"):r,_l=(e,r,t)=>{let o=J.readFileSync(e,"utf-8");if(!yr(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Ol=e=>{if(!J.existsSync(e))return"unchanged";Ei(e);let r=J.readFileSync(e,"utf-8"),t=$e(r,qr,Hr);return t===null?"unchanged":t.trim()===""?(xi(e),J.rmSync(e),"removed"):Pi(e,t)},Ti=async()=>{let e;try{e=(await j()).main}catch{return l.info("Skipped agent-instruction files \u2014 not inside an infra-kit repo"),{skipped:!0,root:null,written:[]}}if(!J.existsSync(e))return l.info("Skipped agent-instruction files \u2014 no infra-kit.json at the repo root"),{skipped:!0,root:null,written:[]};let r=zr.dirname(e),t=$t.version,o=Al(t),s=zr.join(r,Sl),n=zr.join(r,Cl),i=Il(n,"");i=$e(i,Pl,Tl)??i,i=Ur({content:i,body:o,startMarker:qr,endMarker:Hr,placement:"replace-in-place"});let a=[{path:n,action:Pi(n,i)},{path:s,action:Ol(s)}];_l(n,qr,Hr);for(let c of a)c.action==="unchanged"&&c.path!==n||l.info(` ${c.action.padEnd(9)} ${zr.relative(r,c.path)}`);return l.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:a}};import me from"node:fs";import Mi from"node:os";import Yr from"node:path";import ji from"node:process";import Lt from"node:fs/promises";import Nl from"node:path";import Dl from"node:process";var Si=` // "envManagement": { // required in layer 1; provider-tagged
20
+ // "provider": "doppler",
21
+ // "config": { "name": "my-doppler-project" }
22
+ // },
23
+ //
24
+ // "ide": {
25
+ // "provider": "cursor",
26
+ // "config": { "workspaceConfigPath": "/path/to/your.code-workspace" }
27
+ // },
28
+ // // Or, for Zed (no workspace file \u2014 one window with all worktrees via "zed <root> <wt...>"):
29
+ // "ide": { "provider": "zed", "config": {} },
30
+ // // Or drive BOTH editors at once with an array (at most one entry per provider):
31
+ // "ide": [
32
+ // { "provider": "cursor", "config": { "workspaceConfigPath": "/path/to/your.code-workspace" } },
33
+ // { "provider": "zed", "config": {} }
34
+ // ],
35
+ //
36
+ // "taskManager": {
37
+ // "provider": "jira",
38
+ // "config": { "baseUrl": "https://acme.atlassian.net", "projectId": 123 }
39
+ // },
40
+ //
41
+ // "worktrees": {
42
+ // "openInGithubDesktop": false,
43
+ // "openInCmux": true,
44
+ // // cmux pane layout for opened worktrees: "two-columns" (default, left | right)
45
+ // // or "three-pane" (left split top/bottom + full-height right).
46
+ // "cmux": { "layout": "two-columns" }
47
+ // },
48
+ //
49
+ // // Auto-load Doppler env when working inside this project/worktree. Omit to
50
+ // // disable. "trigger" (pick one): "shell-startup" (new shells) | "cli-invocation"
51
+ // // (before each infra-kit command, primes subsequent commands). "config" is the
52
+ // // environment to load \u2014 must have a service token (infra-kit env-token-set) or
53
+ // // auto-load quietly disables. Requires the committed infra-kit.json at the git
54
+ // // repo root, and the zsh shell integration (infra-kit init + a new shell). zsh only.
55
+ // "envAutoLoad": { "trigger": "shell-startup", "config": "dev" },
56
+ //
57
+ // // Per-app local-dev overrides, keyed by APP FOLDER name (the directory under
58
+ // // apps/). Both fields optional: "port" pins the local listen port (otherwise
59
+ // // <APP>_PORT / PORT / a built-in default), "prefixUrl" pins the URL prefix the
60
+ // // app is served under. An unknown app name is ignored at resolve time, never a
61
+ // // parse error.
62
+ // "dev": {
63
+ // "client": { "port": 4001, "prefixUrl": "/api" }
64
+ // },
65
+ //
66
+ // // Named \`infra-kit dev <preset>\` sessions. The keys under "apps" are PACKAGES \u2014
67
+ // // "<app>/api" or "<app>/ui". A bare "<app>" is a FOLDER, not a package, and is
68
+ // // REJECTED. Per target: "watchDeps" (api targets) rebuilds the shared-package
69
+ // // dependency closure and restarts on change; "proxy" maps a route path to
70
+ // // "local" | "cloud" for this session only. "cmux": true runs each launched target
71
+ // // in its own cmux pane. Omit "apps" entirely to launch every discovered target.
72
+ // "devServersPresets": {
73
+ // "backend": {
74
+ // "apps": {
75
+ // "client/api": { "watchDeps": true, "proxy": { "/api": "local", "/auth": "cloud" } },
76
+ // "client/ui": {}
77
+ // },
78
+ // "cmux": true
79
+ // }
80
+ // },
81
+ //
82
+ // // DEPRECATED \u2014 accepted but IGNORED; safe to delete. Remove it and this note in a
83
+ // // future release.
84
+ // //
85
+ // // The proxy port is no longer configurable. Every dev URL is now
86
+ // // https://<release>.<package>.localhost with NO port, and the only port that can
87
+ // // serve a port-free HTTPS URL is 443 \u2014 so a setting here could only put the port
88
+ // // back into the URL. Set up the daemon once (the install is the only step needing
89
+ // // root; trusting its local CA does not). Run \`infra-kit doctor\`: it checks both and
90
+ // // prints each fix as a command you can paste, with the paths filled in for your
91
+ // // machine. Do not type a bare \`portless\` \u2014 it lives in node_modules, not on PATH.
92
+ // // infra-kit itself never elevates.
93
+ // "devProxy": { "port": 443 },
94
+ //
95
+ // // May this project deploy to the delivery-shaped environments ("prod")? The LIST lives in code
96
+ // // (lib/workflow-envs/protected-envs); this decides only whether THIS project may reach it.
97
+ // // "disallow" \u2014 the DEFAULT when the key is absent. Filtered out of every deploy picker and
98
+ // // refused, on both \`local deploy-*\` and \`release deploy-*\`. Use
99
+ // // \`infra-kit release deliver\`, which also does the RC PR and the Jira version.
100
+ // // "allow" \u2014 reachable from the CLI and from an MCP agent alike.
101
+ // // "cli-only" \u2014 reachable from a terminal, but NOT over MCP: an agent's tool call carries no
102
+ // // human keystroke, so agents keep the refusal.
103
+ // // Allowing it does not remove the other gates: a local deploy still requires the AWS account to
104
+ // // report that environment, still refuses a dirty tree, and still refuses \`--skip-preflight
105
+ // // clean-tree\`. A \`release deploy-*\` dispatch has no such second gate and prints a warning
106
+ // // naming what it skips.
107
+ // //
108
+ // // It IS honoured from this layer \u2014 the merge treats it like any other key \u2014 but it belongs in the
109
+ // // committed project infra-kit.json, where a reviewer and \`git blame\` can see it. Setting it here
110
+ // // grants yourself production access with no trace in the repo.
111
+ // "protectedEnvs": "disallow"
112
+ //
113
+ // // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in
114
+ // // tokens.json \u2014 a SIBLING of this file, at ~/.infra-kit/projects/<repo>/tokens.json (mode 0600) \u2014
115
+ // // shaped { "envs": { "<env>": "dp.st\u2026" } }. Write it with \`infra-kit env-token-set <env>\` (which
116
+ // // also fixes its modes), or by hand: both are supported, which is why the store carries no
117
+ // // repo-identity field and no mandatory version. Pasting a token into an
118
+ // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
119
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Fo=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
120
+ //
121
+ // Merge chain (later layers override earlier ones at top-level keys):
122
+ // 1. <repo>/infra-kit.json \u2014 committed project config (required)
123
+ // 2. ~/.infra-kit/infra-kit.json \u2014 user-global (the sibling of this file)
124
+ // 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override
125
+ //
126
+ // Merge is shallow: setting a top-level key replaces that whole section from
127
+ // layer 1. Arrays do not concatenate. Top-level keys recognized:
128
+ // envManagement, ide, taskManager, worktrees, envAutoLoad, dev,
129
+ // devServersPresets, devProxy, protectedEnvs. The schema is strict \u2014 an
130
+ // unrecognized top-level key is a parse error, not a silently ignored one.
131
+ //
132
+ // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
133
+ // overrides in the sibling infra-kit.json (strict JSON: no comments, double-quoted
134
+ // keys). Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
135
+ //
136
+ // Every recognized key is documented below. NOTE: \`envManagement\` is REQUIRED in
137
+ // the committed project infra-kit.json (layer 1) and is usually NOT set in this
138
+ // user-global layer \u2014 it is shown here only to document the full, valid config shape.
139
+ {
140
+ ${Si}
141
+ }
142
+ `,Lo=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
143
+ //
144
+ // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
145
+ // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
146
+ // top-level key set here replaces that whole section wholesale; arrays do not
147
+ // concatenate. Top-level keys recognized: envManagement, ide,
148
+ // taskManager, worktrees, envAutoLoad, dev, devServersPresets, devProxy,
149
+ // protectedEnvs. The schema is strict \u2014 an unrecognized top-level key is a parse
150
+ // error, not a silently ignored one.
151
+ //
152
+ // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
153
+ // in the sibling infra-kit.json (strict JSON: no comments, double-quoted keys).
154
+ //
155
+ // Every recognized key is documented below. NOTE: \`envManagement\` is REQUIRED in
156
+ // the committed project infra-kit.json (layer 1) and is usually NOT set in this
157
+ // override layer \u2014 it is shown here only to document the full, valid config shape.
158
+ {
159
+ ${Si}
160
+ }
161
+ `,Wo=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
162
+ //
163
+ // Machine-local registry the vendor commands (sync/manifest/diff) read to know
164
+ // where your project repos live and which ones to stamp. This .example.jsonc is
165
+ // reference only \u2014 it is NOT loaded. The real file is the strict-JSON sibling
166
+ // vendor.json (no comments, double-quoted keys); run \`infra-kit vendor config --init\`
167
+ // to scaffold it.
168
+ {
169
+ // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
170
+ // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
171
+ }
172
+ `;var Ci=!1,Ml=e=>e.replace(/\.json$/,".example.jsonc"),jl=async e=>{try{return await Lt.readFile(e,"utf-8")}catch{return null}},Wt=async e=>{let r=e.userProject,t=Ml(r);await Lt.mkdir(Nl.dirname(r),{recursive:!0});let o=!await Q(r);o&&await Lt.writeFile(r,`{}
173
+ `,"utf-8");let s=Lo(e.projectName),n=await jl(t)!==s;return n&&await Lt.writeFile(t,s,"utf-8"),o&&js(),{configPath:r,examplePath:t,createdConfig:o,refreshedExample:n}},Vt=e=>`Created ${b(e.configPath)} \u2014 see ${b(e.examplePath)} for the annotated reference.`,Fl=async()=>{if(Dl.env.INFRA_KIT_NO_SEED||Ci)return;Ci=!0;let e;try{e=await j()}catch{return}if(await Q(e.main))try{let r=await Wt(e);r.createdConfig?l.info(Vt(r)):r.refreshedExample&&l.debug(`Refreshed ${b(r.examplePath)} to match the current schema.`)}catch(r){l.debug({err:r,msg:`Skipped seeding ${b(e.userProject)} (config bootstrap failed).`})}};import Y from"node:fs/promises";import ae from"node:path";import{pathToFileURL as Vl}from"node:url";import Bl from"yaml";import{z as Ii}from"zod";import Ll from"node:fs/promises";import Vo from"node:os";import Bo from"node:path";import{z as Wl}from"zod";import{z as Bt}from"zod";var $i="vendor.json",Jt=Bt.object({workspaceDir:Bt.string().min(1),targets:Bt.array(Bt.string()).min(1)}).strict();var Jo=()=>Bo.join(Vo.homedir(),Ds,$i),Iv=e=>{if(e==="~")return Vo.homedir();if(e.startsWith("~/"))return Bo.join(Vo.homedir(),e.slice(2));if(Bo.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},_v=async()=>{let e=Jo(),r;try{r=await Ll.readFile(e,"utf-8")}catch{throw new Error(`Factory config not found at ${e}. infra-kit needs a machine-local factory registry to know where your project repos live and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
174
+
175
+ {
176
+ "workspaceDir": "~/projects",
177
+ "targets": ["my-repo"]
178
+ }
179
+ `)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(s){throw new Error(`Invalid JSON in vendor.json at ${e}: ${s.message}`)}let o=Jt.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${Wl.prettifyError(o.error)}`);return o.data};var Ai=e=>e.replace(/\.json$/,".yml"),_i=async()=>{let e;try{e=await j()}catch{return}let r=[{label:"infra-kit.json",yml:Ai(e.main),json:e.main,schema:Ms},{label:"~/.infra-kit/infra-kit.json",yml:ae.join(ae.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:fo},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Ai(e.userProject),json:e.userProject,schema:fo}],t=0;for(let o of r){let[s,n]=await Promise.all([Q(o.yml),Q(o.json)]);if(s){if(n){l.info(`\u26A0 Skipped ${b(o.yml)} \u2014 ${b(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await Y.readFile(o.yml,"utf-8"),a=Bl.parse(i)??{},c=o.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${b(o.yml)} \u2014 invalid config: ${Ii.prettifyError(c.error)}`);continue}await Y.mkdir(ae.dirname(o.json),{recursive:!0}),await Y.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
180
+ `,"utf-8"),await Y.rm(o.yml,{force:!0}),l.info(`\u2713 Migrated ${b(o.yml)} \u2192 ${b(o.json)}`),t++}catch(i){l.info(`\u26A0 Skipped ${b(o.yml)} \u2014 ${i.message}`)}}}t>0&&rr()},Oi=async()=>{let e;try{e=await j()}catch{return}let r=ae.dirname(e.userGlobal),t=[{from:ae.join(r,"config.json"),to:e.userGlobal},{from:ae.join(r,"config.example.jsonc"),to:ae.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:s,to:n}of t){let[i,a]=await Promise.all([Q(s),Q(n)]);if(i){if(a){l.info(`\u26A0 Skipped ${b(s)} \u2014 ${b(n)} already exists (remove the stale file manually)`);continue}try{await Y.mkdir(ae.dirname(n),{recursive:!0}),await Y.rename(s,n),l.info(`\u2713 Renamed ${b(s)} \u2192 ${b(n)}`),o++}catch(c){l.info(`\u26A0 Skipped ${b(s)} \u2014 ${c.message}`)}}}o>0&&rr()},Ni=async()=>{let e=Jo(),r=ae.dirname(e),t=ae.join(r,"vendor.config.ts"),[o,s]=await Promise.all([Q(t),Q(e)]);if(o){if(s){l.info(`\u26A0 Skipped ${b(t)} \u2014 ${b(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let n=await Y.stat(t),c=(await import(`${Vl(t).href}?mtime=${Number(n.mtimeMs)}`)).default,p=typeof c=="function",u=p?await c():c,d=Jt.safeParse(u);if(!d.success){l.info(`\u26A0 Skipped ${b(t)} \u2014 invalid factory config: ${Ii.prettifyError(d.error)}`);return}await Y.mkdir(r,{recursive:!0}),await Y.writeFile(e,`${JSON.stringify(d.data,null,2)}
181
+ `,"utf-8"),await Y.rm(t,{force:!0}),p?l.info(`\u26A0 Migrated ${b(t)} \u2192 ${b(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 ${b(e)} directly to change them.`):l.info(`\u2713 Migrated ${b(t)} \u2192 ${b(e)}`)}catch(n){l.info(`\u26A0 Skipped ${b(t)} \u2014 ${n.message}`)}}},Jl=e=>{let r=e.ide;if(r===null||typeof r!="object")return{changed:!1,result:e};let t=!1,o=n=>{if(n===null||typeof n!="object"||!("config"in n))return n;let i=n.config;if(i===null||typeof i!="object"||!("mode"in i))return n;t=!0;let a=Object.fromEntries(Object.entries(i).filter(([c])=>c!=="mode"));return{...n,config:a}},s=Array.isArray(r)?r.map(o):o(r);return t?{changed:!0,result:{...e,ide:s}}:{changed:!1,result:e}},Di=async()=>{let e;try{e=await j()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await Q(o))try{let s=await Y.readFile(o,"utf-8");if(s.trim()==="")continue;let n=JSON.parse(s),{changed:i,result:a}=Jl(n);if(!i)continue;await Y.writeFile(o,`${JSON.stringify(a,null,2)}
182
+ `,"utf-8"),l.info(`\u2713 Normalized ide config in ${b(o)} (removed legacy "mode")`),t++}catch(s){l.info(`\u26A0 Skipped normalizing ${b(o)} \u2014 ${s.message}`)}t>0&&rr()};var Zr="# -- infra-kit:begin --",wr="# -- infra-kit:end --",Kl=[["# region infra-kit","# endregion infra-kit"]],Gl="# infra-kit shell functions",ty=async()=>{let e=Yr.join(Mi.homedir(),".zshrc"),r=me.existsSync(e)?Hl(me.readFileSync(e,"utf-8")):"",t=Ur({content:r,body:Fi(),startMarker:Zr,endMarker:wr,placement:"append-end"});me.writeFileSync(e,t),l.info(`Added infra-kit shell functions to ${e}`),await _i(),await Di(),await Oi(),await Ni(),Ul(),await Ti(),await zl();let o=ji.env.SHELL??"";o.includes("zsh")||l.warn(`Your login shell ($SHELL=${o||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear/auto-load) is zsh-only and won't activate in bash/fish.`),l.info("Run `source ~/.zshrc` or open a new terminal to activate.")},Ul=()=>{let e=Yr.join(Mi.homedir(),".infra-kit"),r=Yr.join(e,"infra-kit.json");if(me.mkdirSync(e,{recursive:!0}),me.writeFileSync(Yr.join(e,"infra-kit.example.jsonc"),Fo(),"utf-8"),me.writeFileSync(Yr.join(e,"vendor.example.jsonc"),Wo(),"utf-8"),me.existsSync(r)){l.info(`User-global config already present at ${r} (refreshed reference examples)`);return}me.writeFileSync(r,`{}
183
+ `,"utf-8"),l.info(`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`)},zl=async()=>{if(!ji.env.INFRA_KIT_NO_SEED)try{let e=await j();if(!me.existsSync(e.main))return;let r=await Wt(e);r.createdConfig&&l.info(Vt(r))}catch(e){l.debug({err:e,msg:"Skipped seeding the user-project config (init)."})}},ql=e=>e.startsWith("#")||e.startsWith("alias ")||e.startsWith("env-load")||e.startsWith("env-clear")||e.startsWith("env-status")||e.startsWith("if ")||e.startsWith(" export INFRA_KIT_SESSION")||e.startsWith("export _INFRA_KIT_")||e.startsWith(": ${_INFRA_KIT_")||e.startsWith("fi")||e.startsWith("zmodload ")||e.startsWith("autoload ")||e.startsWith("add-zsh-hook ")||e.startsWith("_infra_kit_autoload"),Hl=e=>{let r=$e(e,Zr,wr);if(r!==null)return r;for(let[a,c]of Kl){let p=$e(e,a,c);if(p!==null)return p}let t=e.indexOf(Gl);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),s=e.slice(t).split(`
184
+ `),n=0;for(;n<s.length&&ql(s[n]);)n++;let i=s.slice(n).join(`
185
+ `);return o+(i?`
186
+ ${i}`:"")},Fi=()=>{let e="pnpm exec infra-kit";return["zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null","zmodload zsh/sched 2>/dev/null",'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",": ${_INFRA_KIT_LAST_LOAD_MTIME:=0}",": ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}",": ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}",": ${_INFRA_KIT_WARM_TTL:=7200}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED _INFRA_KIT_WARM_TTL",`env-load() { local f m; f=$(${e} env-load "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source "$f"; ${e} env-status; }`,`env-clear() { local f m; f=$(${e} env-clear "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`,"_infra_kit_notify() {"," zle && print -u2 -n $'\\r\\e[K'",' print -u2 -- "$1"'," zle && zle reset-prompt","}","_infra_kit_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local dir="$cache_root/$INFRA_KIT_SESSION"',' local load_file="$dir/env-load.sh"',' local clear_file="$dir/env-clear.sh"'," local load_mtime=0 clear_mtime=0",' [[ -f "$load_file" ]] && load_mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)',' [[ -f "$clear_file" ]] && clear_mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( load_mtime > _INFRA_KIT_LAST_LOAD_MTIME && load_mtime >= _INFRA_KIT_SHELL_STARTED && load_mtime >= clear_mtime )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$load_mtime",' _infra_kit_notify "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," if (( clear_mtime > _INFRA_KIT_LAST_CLEAR_MTIME && clear_mtime >= _INFRA_KIT_SHELL_STARTED && clear_mtime > load_mtime )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$clear_mtime",' _infra_kit_notify "infra-kit: auto-cleared env"'," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi","_INFRA_KIT_AUTOLOAD_WINDOW=6","export _INFRA_KIT_AUTOLOAD_WINDOW","_infra_kit_poll_autoload() {"," _infra_kit_autoload"," if (( _INFRA_KIT_LAST_LOAD_MTIME < _INFRA_KIT_SHELL_STARTED )) && (( ${EPOCHSECONDS:-0} - _INFRA_KIT_SHELL_STARTED < _INFRA_KIT_AUTOLOAD_WINDOW )); then"," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," fi","}","_infra_kit_warm_source() {",' local canon="$1" key'," if (( $+commands[shasum] )); then",' key=$(printf %s "$canon" | shasum -a 256 | cut -c1-64)'," elif (( $+commands[sha256sum] )); then",' key=$(printf %s "$canon" | sha256sum | cut -c1-64)'," else"," return"," fi",' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local warm="$cache_root/projects/$key/env-load.sh"',' local wclear="$cache_root/projects/$key/env-clear.sh"',' [[ -f "$warm" ]] || return'," local wm=0 cm=0",' wm=$(zstat +mtime -- "$warm" 2>/dev/null || echo 0)',' [[ -f "$wclear" ]] && cm=$(zstat +mtime -- "$wclear" 2>/dev/null || echo 0)'," (( cm >= wm )) && return"," (( ${EPOCHSECONDS:-0} - wm >= _INFRA_KIT_WARM_TTL )) && return",' source "$warm"',' _infra_kit_notify "infra-kit: loaded cached vars for ${INFRA_KIT_ENV_CONFIG:-?} (refreshing\u2026)"',"}","_infra_kit_startup_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local dir="$PWD" prev=""',' while [[ -n "$dir" && "$dir" != "$prev" ]]; do',' if [[ -f "$dir/infra-kit.json" ]]; then',' [[ -n "$INFRA_KIT_ENV_CONFIG" && "$dir" == "$INFRA_KIT_ENV_PROJECT_ROOT" ]] && return',' local canon="${dir:A}"',' _infra_kit_warm_source "$canon"',` ( ${e} env-autoload --project-dir "$canon" & ) >/dev/null 2>&1`," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," return"," fi",' prev="$dir"',' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
187
+ `)},Li=()=>`${Zr}
188
+ ${Fi()}
189
+ ${wr}`;import Yl from"node:fs/promises";var Ko=async(e,r)=>{if(!r)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let t=await Yl.readFile(e,"utf-8"),o=t.trim()===""?{}:JSON.parse(t);if(typeof o!="object"||o===null||Array.isArray(o))return{hasOverrides:!1,overrideKeys:[],unreadable:!0};let s=Object.keys(o);return{hasOverrides:s.length>0,overrideKeys:s,unreadable:!1}}catch{return{hasOverrides:!1,overrideKeys:[],unreadable:!0}}},Go=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;var br=async(e,r,t,o)=>{try{return await Bi`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Xl=()=>{let e="zshrc init block",r=ce.join(Zl.homedir(),".zshrc");if(!K.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=K.readFileSync(r,"utf-8"),o=t.indexOf(Zr),s=t.indexOf(wr);if(o===-1||s===-1||s<o)return{name:e,status:"fail",message:"infra-kit shell block missing from ~/.zshrc. Run: infra-kit init"};let n=t.slice(o,s+wr.length).trim(),i=Li().trim();return n!==i?{name:e,status:"fail",message:"infra-kit shell block in ~/.zshrc is out of date. Run: infra-kit init"}:{name:e,status:"pass",message:"infra-kit shell block in ~/.zshrc is up to date"}},Ql=async()=>{let e="warm cache",r;try{r=await x()}catch{return{name:e,status:"pass",message:"warm cache: not a git project"}}let t=ue(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let o=ce.join(Fe(t),q);if(!K.existsSync(o))return{name:e,status:"pass",message:"warm cache: none yet (populated on next auto-load)"};let s=Math.floor((Date.now()-K.statSync(o).mtimeMs)/1e3),n=Math.floor(s/60),i=Math.floor(Or/60);return s>=Or?{name:e,status:"pass",message:`warm cache: present but stale (${n}m old, TTL ${i}m) \u2014 will refresh`}:{name:e,status:"pass",message:`warm cache: present, ${n}m old`}},ep=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await x(),t=ce.join(r,"pnpm-workspace.yaml");if(!K.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=K.readFileSync(t,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(o)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(r){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${r.message}`}}},rp=async()=>{try{return rr(),{config:await T(),error:null}}catch(e){return{config:null,error:e}}},tp=e=>{let r="infra-kit config valid";return e.error?{name:r,status:"fail",message:e.error.message}:{name:r,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}},op=384,Uo=448,np=e=>e.map(r=>{let t=r.source===null?"no token":`token (${r.source})`;return`${r.env}: ${t}`}).join(", "),sp=async(e,r)=>Promise.all(e.map(async t=>{try{let{source:o}=await r(t);return{env:t,source:o}}catch{return{env:t,source:null}}})),ip=async(e,r={})=>{let t="env tokens configured",o=r.readStore??ee,s=r.resolveToken??fr;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};try{await o()}catch(d){return{name:t,status:"fail",message:`Token store unreadable \u2014 ${d.message}`}}let n=await Ge(),i=e.config.envAutoLoad?.config,a=i&&!n.includes(i)?[...n,i]:n,c=await sp(a,s),p=np(c);if(i===void 0)return{name:t,status:"pass",message:`No envAutoLoad configured \u2014 no env is load-bearing. ${p}`};let u=c.find(d=>d.env===i);return!u||u.source===null?{name:t,status:"fail",message:`No Doppler service token for the auto-load env "${i}" \u2014 your shell env will not load. Fix: run \`infra-kit env-token-set ${i}\`. ${p}`}:{name:t,status:"pass",message:`auto-load env "${i}": token (${u.source}). ${p}`}},ap={valid:{status:"pass",describe:"live and correctly scoped"},revoked:{status:"fail",describe:"REJECTED by Doppler (revoked or invalid)"},"mis-scoped":{status:"fail",describe:"live but scoped to a DIFFERENT config"},unreachable:{status:"pass",describe:"could not be checked (Doppler unreachable)"}},cp=async(e,r={})=>{let t="env token valid",o=r.resolveToken??fr,s=r.probe??Br;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let n=e.config.envAutoLoad?.config;if(n===void 0)return{name:t,status:"pass",message:"Skipped \u2014 no envAutoLoad env to probe"};let i;try{i=(await o(n)).token}catch{return{name:t,status:"pass",message:`Skipped \u2014 no token for env "${n}" (see env tokens configured)`}}let a=e.config.envManagement.config.name,c=await s({childEnv:vr(i),project:a,config:n}),p=ap[c.outcome],u=c.outcome==="revoked"||c.outcome==="mis-scoped"?` Fix: run \`infra-kit env-token-set ${n}\` with a token scoped to "${n}".`:"";return{name:t,status:p.status,message:`The token for env "${n}" (project "${a}") is ${p.describe}.${u}`}},Xr=(e,r)=>{let t=r(e);return t===null?null:t.mode&511},lp=async(e,r={})=>{let t="tokens.json perms",o=r.storePath??Ct,s=r.statPath??pp,n=r.chmodPath??K.chmodSync,i;try{i=await o()}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(Xr(i,s)===null)return{name:t,status:"pass",message:`No token store yet at ${b(i)}`};let a=ce.dirname(i),c=ce.dirname(a),p=ce.dirname(c),d=[{target:p,expected:Uo,actual:Xr(p,s)},{target:c,expected:Uo,actual:Xr(c,s)},{target:a,expected:Uo,actual:Xr(a,s)},{target:i,expected:op,actual:Xr(i,s)}].filter(v=>v.actual!==null&&v.actual!==v.expected);if(d.length===0)return{name:t,status:"pass",message:`${b(i)} is 0600 (0700 dirs)`};let f=d.map(v=>`${b(v.target)} is ${Wi(v.actual)}, expected ${Wi(v.expected)}`).join("; ");if(!e)return{name:t,status:"fail",message:`${f}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let v of d)n(v.target,v.expected);return{name:t,status:"pass",message:`Tightened ${d.length} path(s): ${f}`}},Wi=e=>`0${e.toString(8).padStart(3,"0")}`,pp=e=>{try{return K.statSync(e)}catch{return null}},dp=async()=>{let e="user override path";try{let r=await j(),t=K.existsSync(r.userProject),o=await Ko(r.userProject,t),s=t?Go(o):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${b(r.userProject)} ${s} \u2014 project: ${r.projectName}`}}catch(r){return{name:e,status:"fail",message:r.message}}},up=async()=>{let e="legacy user-global config",r;try{r=await j()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=ce.join(ce.dirname(r.userGlobal),"config.json");return K.existsSync(t)?K.existsSync(r.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${b(t)} \u2014 ${b(r.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${b(t)} \u2014 run \`infra-kit init\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},mp={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"},zed:{command:["zed","--version"],label:"Zed",failMsg:"Zed is not installed. Install from: https://zed.dev/"}},fp=async e=>{let r=mp[e];try{return await Bi`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},gp=async e=>{let r="ide installed";if(!e.config)return{name:r,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let t=se(e.config).map(n=>n.provider);if(t.length===0)return{name:r,status:"pass",message:"No IDE configured (ide unset)"};let o=await Promise.all(t.map(n=>fp(n))),s=o.filter(n=>!n.ok);return s.length===0?{name:r,status:"pass",message:`Installed: ${o.map(n=>n.label).join(", ")}`}:{name:r,status:"fail",message:s.map(n=>n.failMsg).join("; ")}},hp=async()=>{let e;try{e=(await j()).main}catch{return[]}if(!K.existsSync(e))return[];let r=ce.join(ce.dirname(e),"CLAUDE.md"),t=K.existsSync(r)?K.readFileSync(r,"utf-8"):"",o=yr(t,qr,Hr);return[{name:"CLAUDE.md block",status:o?"pass":"fail",message:o?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit init"}]},Ji=e=>Rt(["service","install"],{sudo:!0,bin:e}),Ki=e=>Rt(["trust"],{bin:e}),vp=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Vi="ERR_TLS_CERT_ALTNAME_INVALID",yp=async(e,r)=>{let t=`portless serving TLS on :${Te}`;return await e(Te,!0)?{name:t,status:"pass",message:`portless is serving HTTPS on :${Te}`}:{name:t,status:"fail",message:`No portless daemon is serving HTTPS on :${Te}. Install it once (needs root): \`${Ji(r)}\`.`}},wp=async(e,r,t,o)=>{let s="portless CA chain valid",n=["localhost",...r.slice(0,1).map(p=>p.name)],a=(await Promise.all(n.map(async p=>({servername:p,result:await e(Te,p)})))).filter(p=>!p.result.ok);if(a.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${b(t)} (${n.join(", ")})`};let c=a.map(p=>p.result.ok?"":p.result.code);return c.includes(Vi)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Vi} for servername(s) ${a.map(p=>p.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:c.some(p=>vp.has(p))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${b(t)}. Its CA was regenerated \u2014 run \`${Ki(o)}\`, or reinstall: \`${Ji(o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${c.join(", ")})`}},kp=(e,r,t)=>{let o="portless CA trusted";return e?{name:o,status:"pass",message:`${b(r)} matches the recorded ca.trusted fingerprint`}:{name:o,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Ki(t)}\` (no sudo needed).`}},bp=async(e,r,t)=>{let o="portless routes";if(e.length===0)return{name:o,status:"pass",message:"No portless routes registered"};let n=(await Promise.all(e.map(async i=>({route:i,live:await r(i.port)})))).filter(i=>!i.live).map(i=>i.route.name);return n.length===0?{name:o,status:"pass",message:`${e.length} portless route(s), all live`}:{name:o,status:"fail",message:`${n.length} stale portless route(s): ${n.join(", ")}. Remove with \`${Rt(["alias","--remove","<name>"],{bin:t})}\`.`}},Rp=async(e={})=>{let r=e.resolveBin??Fs,t=e.isProxyServing??Ls,o=e.handshake??Bs,s=e.caTrusted??Vs,n=e.routes??go,i=e.isListening??_r,a=(e.caPath??Ws)(),c=r();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."}];let p={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},u=n(),d=await yp(t,c),f=d.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await wp(o,u,a,c);return[p,d,f,kp(s(),a,c),await bp(u,i,c)]},Ep=async(e={})=>{let r="portless routes",t=e.routes??go,o=e.isListening??_r,s=e.devSessionRunning??oi,n=t();if(n.length===0)return{name:r,status:"pass",message:"No portless routes registered"};let i=await Promise.all(n.map(async u=>({name:u.name,port:u.port,live:await o(u.port)}))),{prunable:a,withheld:c}=ti(i,s());if(c.length>0)return{name:r,status:"fail",message:`${c.length} route(s) look stale (${c.join(", ")}), but a dev session is running \u2014 a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. Stop dev and re-run \`infra-kit doctor --fix\`.`};if(a.length===0)return{name:r,status:"pass",message:`${n.length} portless route(s), all live`};let p=e.removeAlias??Js().removeAlias;for(let u of a)await p(u);return{name:r,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Gi=async(e={})=>{let r=await rp(),t=await Promise.all([br("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),br("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),br("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),br("aws installed",["aws","--version"],"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"),br("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"),br("cmux installed",["cmux","--version"],"cmux is installed","cmux is not installed. Install from: https://cmux.com/"),Promise.resolve(Xl()),Ql(),ep(),Promise.resolve(tp(r)),ip(r),cp(r),lp(e.fix??!1),dp(),up(),gp(r)]),o=await Rp();if(e.fix){let i=await Ep(),a=o.findIndex(c=>c.name===i.name);a>=0?o[a]=i:o.push(i)}let s=[...t,...o,...await hp()],n={checks:s.map(i=>({name:i.name,status:i.status,message:i.message})),allPassed:s.every(i=>i.status==="pass")};return{content:w(JSON.stringify(n,null,2)),structuredContent:n}},zo=k({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs",inputSchema:{},outputSchema:{checks:kr.array(kr.object({name:kr.string().describe("Name of the check"),status:kr.enum(["pass","fail"]).describe("Check result"),message:kr.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:kr.boolean().describe("Whether all checks passed")},handler:()=>Gi()});import{Chalk as xp}from"chalk";import qo from"node:process";var Pp="Tools & CLIs",Tp="Shell & integration",Sp="Project config",Cp="Doppler env tokens",$p="Dev proxy (portless)",Ap=`portless serving TLS on :${Te}`,Ho=[[Pp,["gh installed","gh authenticated","doppler installed","aws installed","typescript-language-server installed","cmux installed","ide installed"]],[Tp,["zshrc init block","warm cache","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Sp,["infra-kit config valid","user override path","legacy user-global config"]],[Cp,["env tokens configured","env token valid","tokens.json perms"]],[$p,["portless installed",Ap,"portless CA chain valid","portless CA trusted","portless routes"]]],Ui="Other",Ip=Ho.map(([e])=>e),_p=new Map(Ho.flatMap(([e,r])=>r.map(t=>[t,e]))),Oy=Ho.flatMap(([,e])=>e),Op=new Set(["portless routes","tokens.json perms"]),Np=e=>{let r=new Map;for(let o of e){let s=_p.get(o.name)??Ui,n=r.get(s);n?n.push(o):r.set(s,[o])}return[...Ip,Ui].flatMap(o=>{let s=r.get(o);return s&&s.length>0?[{label:o,checks:s}]:[]})},zi={unicode:{pass:"\u2713",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{pass:"ok",fail:"!!",separator:"-",rule:"-"}},Dp=24,Mp=(e,r)=>{let t=e.split(/\s+/).filter(n=>n.length>0),o=[],s="";for(let n of t)s.length===0?s=n:`${s} ${n}`.length<=r?s=`${s} ${n}`:(o.push(s),s=n);return s.length>0&&o.push(s),o.length>0?o:[""]},Hi=e=>{let r=e.filter(t=>t.status==="fail").length;return{passed:e.length-r,failed:r}},jp=e=>{let r=new xp({level:e?1:0});return{header:t=>r.bold.cyan(t),pass:t=>r.green(t),fail:t=>r.red(t),dim:t=>r.dim(t),bold:t=>r.bold(t)}},Fp=(e,r,t,o)=>{if(e.failed===0){let i=`${r}/${r} ok`;return{text:t.pass(i),plainWidth:i.length}}let s=`${e.passed}/${r}`,n=`${e.failed} failed`;return{text:`${t.dim(s)} ${o.separator} ${t.fail(n)}`,plainWidth:s.length+n.length+3}},Rr=" ",qi=" ",Lp=(e,r,t,o)=>{let s=Hi(e.checks),n=Fp(s,e.checks.length,r,t),i=Math.max(1,o-Rr.length-e.label.length-n.plainWidth);return`${Rr}${r.header(e.label)}${" ".repeat(i)}${n.text}`},Wp=(e,r,t,o,s)=>{let n=e.status==="fail",i=o.pass.length,a=n?o.fail:o.pass,c=e.name.padEnd(r),p=n?t.fail(a):t.pass(a),u=n?t.fail(c):c,d=qi.length+i+1+r+2,f=Math.max(Dp,s-d),[v,...m]=Mp(e.message,f),y=S=>n?S:t.dim(S);return[`${qi}${p} ${u} ${y(v??"")}`.trimEnd(),...m.map(S=>`${" ".repeat(d)}${y(S)}`)]},Vp=(e,r,t,o)=>{let s=Hi(e),n=t.rule.repeat(Math.max(12,Math.min(o-Rr.length,56))),i=e.filter(f=>f.status==="fail"&&Op.has(f.name)).length,a=r.pass(`${s.passed} passed`),c=r.fail(`${s.failed} failed`),p=s.failed===0?a:`${a} ${t.separator} ${c}`,u=r.dim(`${i} fixable \u2014 run \`infra-kit doctor --fix\``),d=i>0?` ${u}`:"";return[`${Rr}${r.dim(n)}`,`${Rr}${p}${d}`]},Bp=(e,r={})=>{let t=r.color??!1,o=r.unicode??!0,s=r.width??80,n=jp(t),i=o?zi.unicode:zi.ascii;if(e.length===0)return[n.bold("infra-kit doctor"),"",`${Rr}${n.dim("No checks ran.")}`];let a=Math.max(...e.map(p=>p.name.length)),c=Np(e).flatMap(p=>[Lp(p,n,i,s),...p.checks.flatMap(u=>Wp(u,a,n,i,s)),""]);return[n.bold("infra-kit doctor"),"",...c,...Vp(e,n,i,s)]},Jp=new Set(["","0","false","none"]),Kp=["LC_ALL","LC_CTYPE","LANG"],Gp=(e,r)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Jp.has(e.FORCE_COLOR.toLowerCase()):!!r.isTTY,Up=(e,r)=>{if(r)return!1;let t=Kp.map(o=>e[o]).find(o=>o!==void 0&&o!=="");return t===void 0?!0:/UTF-?8/i.test(t)},zp=(e={})=>{let r=e.env??qo.env,t=e.stream??qo.stderr;return{color:Gp(r,t),unicode:Up(r,e.ascii??!1),width:t.columns??80}},qp=(e,r={})=>{(r.write??(o=>{qo.stderr.write(o)}))(`${Bp(e,zp(r)).join(`
190
+ `)}
191
+ `)};import Yo from"node:fs";import Yi from"node:path";import Hp from"node:process";import{z as Er}from"zod";var Yp=async e=>{let r="";try{r=await x()}catch{return}let t=ue(r);t&&Do(t,e)},Zp=e=>[...e.map(r=>`unset ${r}`),`unset ${Pt}`,`unset ${tr}`,`unset ${or}`,`unset ${Tt}`,`unset ${nr}`,`unset ${je}`,`export ${sr}='1'`],Zi=async({purge:e=!1}={})=>{let r=ir(),t=Yi.join(r,q),o=Yo.existsSync(t);if(!o&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await Yp(e);let s=o?St(t):[],n=Zp(s),i=Yi.resolve(r,xt);Yo.mkdirSync(r,{recursive:!0,mode:448}),Le(i,`${n.join(`
192
+ `)}
193
+ `,384),Hp.stdout.write(`${i}
194
+ `),o&&Yo.rmSync(t,{force:!0});let a={filePath:i,variableCount:s.length,unsetStatements:n,purged:e};return{content:w(JSON.stringify(a,null,2)),structuredContent:a}},Zo=k({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit init` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Er.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Er.string().describe("Path to the file that must be sourced to apply"),variableCount:Er.number().describe("Number of variables cleared"),unsetStatements:Er.array(Er.string()).describe("Unset statements generated"),purged:Er.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>Zi()});import Xp from"node:process";import{z as Ae}from"zod";var Qp=(e,r,t)=>e.map(({env:o,source:s})=>({env:o,source:s,hasToken:!!(t||r[o])})),Xi=["Environment","Source","Token"],ed=e=>{let r=e.map(n=>[n.env,n.source,n.hasToken?"set":"not set"]),t=Xi.map((n,i)=>Math.max(n.length,...r.map(a=>(a[i]??"").length))),o=n=>n.map((i,a)=>i.padEnd(t[a]??0)).join(" | ").trimEnd(),s=t.map(n=>"\u2500".repeat(n)).join("\u2500\u253C\u2500");return["Environments:","",o(Xi),s,...r.map(o)]},ea=async()=>{let e=await We(),r=await Mt(),t=await ee(),o=Xp.env[re],s=Qp(r,t?.envs??{},o);if(l.info(`Doppler project: ${e}
195
+ `),s.length===0)return l.info("No environments found."),l.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),l.info(" or add a token for one manually."),Qi({project:e,envs:s});for(let n of ed(s))l.info(n);return Qi({project:e,envs:s})},Qi=({project:e,envs:r})=>{let t={project:e,configs:r.map(o=>o.env),tokens:r};return{content:w(JSON.stringify(t,null,2)),structuredContent:t}},Xo=k({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:Ae.string().describe("Detected Doppler project name"),configs:Ae.array(Ae.string()).describe("Every environment name known to this project"),tokens:Ae.array(Ae.object({env:Ae.string().describe("Environment / Doppler config name"),source:Ae.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:Ae.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:ea});import rd from"node:path";import qe from"node:process";import{z as Ie}from"zod";var ra=async()=>{l.info("Environment session status:");let e=ir(),r=qe.env[Ks],t=rd.join(e,q),o=0,s=0,n=qe.env[tr]??null,i=qe.env[or]??null,a=qe.env[nr]??null,c=qe.env[je]==="1",p=!!qe.env[sr];if(n){let d=St(t);d.length>0&&(s=d.length,o=d.filter(m=>m in qe.env).length);let f=a?.replace(/\.\d{3}Z$/,"")??null,v=c?"auto-loaded":"manually loaded";if(l.info(` ${n}: ${o} of ${s} vars loaded (${v}, project: ${i}, loadedAt: ${f}, session: ${r})
196
+ `),s>0&&o<s){let m=s-o;l.warn(` ${m} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else{let d=p?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";l.info(` Session ${r}: no env loaded${d}
197
+ `)}let u={sessionId:r,sessionLoadedCount:o,sessionTotalCount:s,sessionConfig:n,sessionProject:i,sessionLoadedAt:a,autoLoaded:c,cleared:p};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}},Qo=k({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session.",inputSchema:{},outputSchema:{sessionId:Ie.string().describe("Current terminal session ID"),sessionLoadedCount:Ie.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Ie.number().describe("Total number of cached var names"),sessionConfig:Ie.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Ie.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Ie.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:Ie.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:Ie.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:ra});import td from"node:process";import{z as _e}from"zod";var ta="****",en=e=>typeof e!="string"||e.length<8?ta:`${ta}${e.slice(-4)}`;var oa=(e,r,t)=>e.map(o=>{let s=t||r[o];return s?{env:o,source:t?`env:${re}`:"store",redactedToken:en(s),present:!0}:{env:o,source:"-",redactedToken:"-",present:!1}}),od=["ENV","SOURCE","TOKEN","PRESENT"],na=(e,r)=>{let t=[...od,...r?["CHECK"]:[]],o=e.map(n=>[n.env,n.source,n.redactedToken,n.present?"yes":"no",...r?[n.status??"-"]:[]]),s=t.map((n,i)=>Math.max(n.length,...o.map(a=>(a[i]??"").length)));return[t,...o].map(n=>n.map((i,a)=>i.padEnd(s[a])).join(" ").trimEnd())},sa=async({check:e}={})=>{let r=await Ge(),t=await ee(),o=td.env[re],s=oa(r,t?.envs??{},o);if(e){let a=await We();for(let c of s){if(!c.present)continue;let p=o||t.envs[c.env],u=await Br({childEnv:vr(p),project:a,config:c.env});c.status=u.outcome}}for(let a of na(s,!!e))l.info(a);let n=s.filter(a=>!a.present);n.length>0&&l.info(`
198
+ No token for: ${n.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:s};return{content:w(JSON.stringify(i,null,2)),structuredContent:i}},rn=k({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:_e.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:_e.array(_e.object({env:_e.string().describe("Environment / Doppler config name"),source:_e.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:_e.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:_e.boolean().describe("Whether a token is configured for this environment"),status:_e.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:sa});import{z as P}from"zod";import{$ as vd}from"zx";import{$ as Ow}from"zx";import{$ as V}from"zx";import{$ as et}from"zx";import Qr from"node:process";var tn=async(e,r)=>{if(e.ok)return;let t=await e.text();throw l.error({status:e.status,statusText:e.statusText,error:t},r),new Error(`HTTP ${e.status}: ${e.statusText}`)},on=async(e,r)=>{try{let{baseUrl:t,token:o,email:s,projectId:n}=r,i={name:e.name,projectId:e.projectId||n,description:e.description||"",released:e.released||!1,archived:e.archived||!1},a=`${t}/rest/api/3/version`,c=btoa(`${s}:${o}`),p=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await tn(p,"Failed to create Jira version"),{success:!0,version:await p.json()}}catch(t){throw l.error({error:t},"Error creating Jira version"),t}},xr=async e=>{try{let{baseUrl:r,token:t,email:o,projectId:s}=e,n=`${r}/rest/api/3/project/${s}/versions`,i=btoa(`${o}:${t}`),a=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await tn(a,"Failed to get Jira project versions"),await a.json()}catch(r){throw l.error({error:r},"Error getting Jira project versions"),r}},Kt=async(e,r)=>{try{return(await xr(r)).find(s=>s.name===e)||null}catch(t){throw l.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Gt=async(e,r)=>{try{let{baseUrl:t,token:o,email:s}=r,n={};e.released!==void 0&&(n.released=e.released),e.archived!==void 0&&(n.archived=e.archived),e.releaseDate!==void 0&&(n.releaseDate=e.releaseDate),e.description!==void 0&&(n.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,a=btoa(`${s}:${o}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(n)});return await tn(c,"Failed to update Jira version"),{success:!0,version:await c.json()}}catch(t){throw l.error({error:t},"Error updating Jira version"),t}},nn=async(e,r)=>{try{let{versionName:t}=e,o=await Kt(t,r);if(!o)throw l.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Gt({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw l.error({error:t},"Error delivering Jira release"),t}},Pr=async()=>{let e=Qr.env.JIRA_BASE_URL,r=Qr.env.JIRA_TOKEN||Qr.env.JIRA_API_TOKEN,t=Qr.env.JIRA_PROJECT_ID,o=Qr.env.JIRA_EMAIL,s=[];if(e||s.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||s.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||s.push("JIRA_PROJECT_ID (numeric project ID)"),o||s.push("JIRA_EMAIL (your Jira email address)"),s.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...s.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
199
+ `);throw new Error(i)}let n=Number.parseInt(t,10);if(Number.isNaN(n))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:n,email:o}},He=async()=>{try{return await Pr()}catch(e){return l.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var ia="dev",Ut=e=>e==="hotfix"?"main":"dev",sn=async(e="regular")=>{let r=Ut(e);et.quiet=!0,await et`git fetch origin`,await et`git switch ${r}`,await et`git pull origin ${r}`,et.quiet=!1},an=async e=>{let{id:r,jiraConfig:t,description:o,type:s="regular"}=e,n=G(r),i=await on({name:n,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),a=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await zt({id:r,jiraVersionUrl:a,type:s,description:o});return{version:D(r),type:s,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:a}},M=async()=>{let e=new Map,r=await He();if(!r)return e;try{let t=await xr(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},rt=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",s=`[${r}]`.padEnd(11);return`${e}${o}${s}`},_=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",aa=e=>e.flatMap(r=>{let t=N(r);return t?[{branch:r,id:t,label:D(t)}]:[]}),fe=e=>{try{return oe(X(e))}catch(r){throw new h(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},tt=e=>{if(e===ia)return ia;let r=N(e);return r?D(r):e},ot=e=>e.flatMap(r=>{let t=N(r);return t?[D(t)]:[]}),sd=(e,r)=>r?r.get(e)||"regular":void 0,W=e=>{let{branches:r,descriptions:t,types:o}=e;return aa(r).map(({branch:s,id:n,label:i})=>({value:s,label:i,description:t.get(G(n)),type:sd(s,o)}))};var id=e=>e.map(r=>({pr:r,id:N(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>ks(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),nt=200,ca=(e,r)=>{e.length<nt||l.warn({source:r,limit:nt},`\u26A0\uFE0F ${r} returned ${nt} PRs \u2014 the page is full, so older release PRs may be missing`)},ad=async()=>{let e=await V`gh pr list --limit ${nt} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await V`gh pr list --limit ${nt} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=JSON.parse(e.stdout),o=JSON.parse(r.stdout);ca(t,"release PR discovery (base dev)"),ca(o,"hotfix PR discovery (base main)");let s=[...t,...o],n=new Set;return s.filter(i=>n.has(i.headRefName)?!1:(n.add(i.headRefName),!0))},la=async()=>{try{let e=await ad();if(e.length===0)throw new h(void 0,{operation:"find open release PRs",remediation:"open a release PR first, or check you are in the right repo"});return id(e)}catch(e){throw e instanceof h?e:(l.error({error:e},"\u274C Error fetching release PRs"),new h(e,{operation:"fetch release PRs"}))}},qt=async()=>(await la()).map(r=>r.headRefName),O=async()=>(await la()).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt})),Ht=async e=>{let{branch:r,body:t}=e;try{V.quiet=!0,await V`gh pr edit ${r} --body ${t}`,V.quiet=!1}catch(o){throw l.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},zt=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:s}=e,n=ws(r,o),i=Ut(o),a=oe(r),c=s&&s.trim()!==""?`${t}
200
+
201
+ ${s}`:`${t}
202
+ `;try{V.quiet=!0,await V`git switch ${i}`,await V`git pull origin ${i}`,await V`git checkout -b ${a}`,await V`git push -u origin ${a}`,await V`git commit --allow-empty-message --allow-empty --message ''`,await V`git push origin ${a}`;let u=(await V`gh pr create --title ${n} --body ${c} --base ${i} --head ${a}`).stdout.trim();return await V`git switch ${i}`,V.quiet=!1,{branchName:a,prUrl:u}}catch(p){throw l.error({error:p,branchName:a},`Error creating release branch ${a}`),p}};import{$ as pa}from"zx";var cn=async e=>{let{operation:r}=e;try{await pa({quiet:!0})`git rev-parse --git-dir`}catch(t){throw new h(t,{operation:r,remediation:"run this from inside a git repository"})}try{await pa({quiet:!0})`git remote get-url origin`}catch(t){throw new h(t,{operation:r,remediation:"this repository has no `origin` remote to fetch from or push to"})}},te=async e=>{let{operation:r}=e;if(await Rs())throw new h(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});if(!await bt())throw new h(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};import pd from"node:process";var st=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};import cd from"node:process";var Yt={enabled:!1},ld=(e,r=t=>{cd.stdout.write(t)})=>(Yt.enabled&&e&&e.structuredContent!=null&&r(`${JSON.stringify(e.structuredContent,null,2)}
203
+ `),e),da=e=>{e.options.some(t=>t.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(da)};var ua=()=>{if(er()||!pd.stdin.isTTY||Yt.enabled)throw new h(void 0,{operation:"interactive branch selection",remediation:"pass the branch selection explicitly (CLI: `--version`/`--versions`/`--all`; MCP: the `version`/`versions`/`all` fields) for non-interactive, --json, or MCP runs"})},Oe=async e=>{ua();let{runBranchPicker:r}=await import("./boot-OA6HGGO6.js"),t=await r(e);if(t===null)throw new st;return t},Tr=async(e,r)=>{ua();let{runBranchMultiPicker:t}=await import("./boot-OA6HGGO6.js"),o=await t(e,r);if(o===null)throw new st;return o};import{$ as Ye}from"zx";var dd="Merge remote-tracking branch 'origin/dev' into ",ma=e=>String(e.stderr??e.message??e).trim(),ud=async e=>{try{return(await Ye({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
204
+ `).map(t=>t.trim()).filter(t=>t.length>0)}catch{return[]}},md=async(e,r)=>{let t=ma(r),o=await ud(e);return o.length>0?{status:"conflict",conflictPaths:o,reason:t}:await Cs(e)?{status:"hook-failed",reason:t}:{status:"error",reason:t}},fa=async e=>{let{cwd:r,worktreePath:t,branches:o}=e,s=[],n=await lo(r,"origin/dev");if(!n)return o.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of o){let a=Date.now(),c=await fd({cwd:r,worktreePath:t,branch:i,devSha:n});s.push({...c,durationMs:Date.now()-a})}return s},fd=async e=>{let{cwd:r,worktreePath:t,branch:o,devSha:s}=e,n=`origin/${o}`;if(!await lo(r,n))return{branch:o,status:"error",reason:`${n} does not exist on origin`};if(await po(r,"origin/dev",n))return{branch:o,status:"up-to-date"};try{await uo(t),await Ye({cwd:t,quiet:!0})`git checkout --detach ${n}`;let i=`${dd}${o}`;await Ye({cwd:t,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await Ye({cwd:t,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:o,status:a===s?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:o,...await md(t,i)}}finally{await mo(t)}},ga=e=>e.flatMap(r=>r.mergeSha?[{branch:r.branch,sha:r.mergeSha}]:[]),ha="pnpm install --frozen-lockfile",va=async e=>{let{worktreePath:r,refs:t,command:o}=e,s=[],n=new Map;for(let i of t)try{await uo(r),await Ye({cwd:r,quiet:!0})`git checkout --detach ${i.sha}`,await Ye({cwd:r,quiet:!0})`sh -c ${o}`,s.push(i)}catch(a){n.set(i.branch,ma(a))}finally{await mo(r)}return{kept:s,failed:n}},ln=async(e,r)=>{await Ye({cwd:e,quiet:!0})`git fetch origin --prune`;let t=[],o=[];for(let s of r)await po(e,"origin/dev",`origin/${s.branch}`)?o.push(s.branch):t.push(s);return{kept:t,nowUpToDate:o}};import pn from"node:process";var Zt=new Set,ya=e=>(Zt.add(e),()=>{Zt.delete(e)}),gd=async()=>{for(let e of[...Zt])try{await e()}catch(r){l.warn({error:r,msg:"cleanup failed during shutdown"})}Zt.clear()},hd=["SIGINT","SIGTERM"],_k=async(e,r={})=>{let{register:t=(i,a)=>{pn.on(i,a)},unregister:o=(i,a)=>{pn.off(i,a)},exit:s=i=>{pn.exit(i)}}=r,n=new Map;for(let i of hd){let a=()=>{gd().then(()=>{s(zs(i))})};n.set(i,a),t(i,a)}try{return await e()}finally{for(let[i,a]of n)o(i,a)}};var yd=e=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[]}),ka=e=>({content:w(JSON.stringify(e,null,2)),structuredContent:e}),wa=new Set(["up-to-date","fast-forward","merged"]),wd=(e,r)=>{let t=(Array.isArray(e)?e:e.split(",")).map(n=>n.trim()).filter(n=>n.length>0),o=new Set(r),s=new Set;for(let n of t){let i;try{i=oe(X(n))}catch(a){throw new h(a,{operation:`resolve release selector "${n}"`,remediation:`pass one of: ${r.join(", ")}`})}if(!o.has(i))throw new h(void 0,{operation:`select release branch for "${n}"`,stderrExcerpt:`${i} is not an open regular release branch`,remediation:`pass one of: ${r.join(", ")}`});s.add(i)}return r.filter(n=>s.has(n))},kd={"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"},ba=e=>{let r=kd[e.status];if(e.status==="conflict"){let t=e.conflictPaths?.length??0;return`${r}: ${t} file(s)`}return e.reason?`${r}: ${e.reason}`:r},bd=e=>{l.info(`
205
+ \u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${ba(r)}`)},Rd=(e,r)=>{let t=r.find(o=>o.branch===e);return t?`git -C ${t.path} merge origin/dev`:`git switch ${e} && git merge origin/dev`},Ed=async e=>{let{entries:r,toPlan:t,all:o,explicit:s}=e;if(s||o)return t;g.setInteractive();let n=new Map(r.flatMap(i=>{let a=N(i.branch);return a?[[G(a),ba(i)]]:[]}));return Tr(W({branches:t,descriptions:n}),{required:!0})},xd=async e=>{let{cwd:r,worktreePath:t,entries:o,selected:s,verify:n}=e,i=o.filter(m=>s.includes(m.branch)),a=m=>{for(let y of m)l.info(`\u2139\uFE0F ${y} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await ln(r,ga(i));a(c.nowUpToDate);let p=c.kept,u=new Map;if(n&&p.length>0){l.info(`
206
+ \u{1F50E} Verifying ${p.length} merge(s) with: ${n}`);let m=await va({worktreePath:t,refs:p,command:n});u=m.failed;for(let[R,S]of m.failed)l.info(`\u2717 ${R} failed verification \u2014 not pushing it. ${S.split(`
207
+ `)[0]??""}`);let y=await ln(r,m.kept);a(y.nowUpToDate),p=y.kept}if(p.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};l.info(`
208
+ \u2B06\uFE0F Pushing atomically: ${p.map(m=>m.branch).join(", ")}`);let d=await Ss(r,p);if(d.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let v=(await Promise.all(p.map(async m=>({branch:m.branch,landed:await Ts(r,m.branch)===m.sha})))).filter(m=>m.landed);return v.length>0&&l.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${v.map(m=>m.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:d.stderr?.split(`
209
+ `)[0],observedLanded:v.map(m=>m.branch)}},Ra=async e=>{let{all:r,versions:t,dryRun:o=!1,verify:s,confirmedCommand:n}=e,i=s===!0?ha:s||void 0;await cn({operation:"merge dev into release branches"});let c=(await O()).filter(E=>_(E.title)==="regular").map(E=>E.branch);if(c.length===0)return l.info("\u2139\uFE0F No open release branches found"),g.print(),ka(yd(o));let p=await Pe();try{await vd({cwd:p,quiet:!0})`git fetch origin --prune`}catch(E){throw new h(E,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let u=t===void 0?c:wd(t,c),d=await $s({cwd:p},async E=>{let be=ya(E.remove);try{return await Pd({cwd:p,worktree:E,toPlan:u,candidates:c,all:r,versions:t,dryRun:o,verify:i,confirmedCommand:n})}finally{be()}}),{entries:f,selected:v,pushed:m,pushAborted:y,abortedBy:R,declined:S,verifyFailed:$}=d,Z=await kt(p).catch(()=>[]);return Td({entries:f,selected:v,pushed:m,pushAborted:y,abortedBy:R,declined:S,verifyFailed:$,dryRun:o,worktrees:Z})},Pd=async e=>{let{cwd:r,worktree:t,toPlan:o,candidates:s,all:n,versions:i,dryRun:a,verify:c,confirmedCommand:p}=e,u=await fa({cwd:r,worktreePath:t.path,branches:o}),d={entries:u,pushed:!1,pushAborted:!1,declined:!1};if(bd(u),a)return{...d,selected:o};let f=await Ed({entries:u,toPlan:o,all:n,explicit:i!==void 0});f.length===s.length?g.addOption("--all",!0):g.addOption("--versions",f);let v=u.filter(m=>f.includes(m.branch)&&m.mergeSha).length;v>0&&l.info(`
210
+ \u2139\uFE0F This will push ${v} branch(es), re-running CI on ${v} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await B(p,`Are you sure you want to merge dev into these branches: ${f.join(", ")}?`,{throwOnDecline:!0})}catch(m){if(!Us(m))throw m;return{...d,selected:f,declined:!0}}return p||g.addOption("--yes",!0),{entries:u,selected:f,declined:!1,...await xd({cwd:r,worktreePath:t.path,entries:u,selected:f,verify:c})}},Td=e=>{let{entries:r,selected:t,pushed:o,pushAborted:s,abortedBy:n,declined:i,dryRun:a,worktrees:c,verifyFailed:p}=e,u=new Set(o?r.filter(m=>t.includes(m.branch)&&m.mergeSha&&!p?.has(m.branch)).map(m=>m.branch):[]),d=r.filter(m=>t.includes(m.branch)).map(m=>{let y=!!m.mergeSha,R=e.verifyFailed?.get(m.branch),S=s&&y?"push-aborted":m.status,$=R?"verify-failed":S;return{branch:m.branch,status:$,mergeSha:m.mergeSha,conflictPaths:m.conflictPaths,pushed:u.has(m.branch),reason:R??m.reason}}),f=d.filter(m=>!wa.has(m.status));for(let m of d){let y=r.find(R=>R.branch===m.branch);l.info({branch:m.branch,status:m.status,mergeSha:m.mergeSha,conflictCount:m.conflictPaths?.length??0,durationMs:y?.durationMs,pushed:m.pushed,msg:"merge-dev branch result"})}if(i||a)l.info(i?`
211
+ Operation cancelled \u2014 nothing was pushed.
212
+ `:`
213
+ \u{1F50D} Dry run \u2014 nothing was pushed.
214
+ `);else if(f.length>0){l.info(`
215
+ \u26A0\uFE0F ${f.length} branch(es) did not merge.
216
+ `);for(let m of f)l.info(`# ${m.branch} \u2014 ${m.status}
217
+ ${Rd(m.branch,c)}
218
+ `)}else l.info(`\u2705 All merges completed successfully!
219
+ `);g.print();let v=a||i;return ka({successfulMerges:v?0:d.filter(m=>wa.has(m.status)).length,failedMerges:v?0:f.length,failedBranches:v?[]:f.map(m=>m.branch),totalBranches:d.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:s,abortedBy:n},results:d.map(m=>v?{...m,pushed:!1}:m)})},dn=k({name:"gh-merge-dev",description:"Merge origin/dev into open regular (non-hotfix) release branches and push them in one atomic push. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:P.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:P.union([P.string(),P.array(P.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error \u2014 hotfix branches cannot be selected. Takes precedence over `all`.'),dryRun:P.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:P.union([P.boolean(),P.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push."),confirm:P.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:P.number().describe("Number of branches that reached their desired state"),failedMerges:P.number().describe("Number of branches that did not"),failedBranches:P.array(P.string()).describe("List of branches that did not merge"),totalBranches:P.number().describe("Total number of branches processed"),dryRun:P.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:P.object({attempted:P.boolean(),aborted:P.boolean(),abortedBy:P.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:P.array(P.object({branch:P.string(),status:P.string(),mergeSha:P.string().optional(),conflictPaths:P.array(P.string()).optional(),pushed:P.boolean(),reason:P.string().optional()})).describe("Per-branch terminal state")},handler:Ra});import{z as ct}from"zod";import{$ as U}from"zx";var Ea=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},it=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let o=r.exitCode;(typeof o=="number"||o===null)&&(t.exitCode=o);let s=Ea(r.stderr,500);s&&(t.stderr=s);let n=Ea(r.stdout,200);return n&&(t.stdout=n),t};import{$ as xa}from"zx";var at=async e=>{let{branches:r,worktreeDir:t,pruneFolder:o=!1}=e,s=await Promise.allSettled(r.map(async i=>{let a=`${t}/${i}`;return await cr(a),await xa`git worktree remove ${a}`,i})),n=[];for(let[i,a]of s.entries())if(a.status==="fulfilled")n.push(a.value);else{let c=r[i],p=new h(a.reason,{operation:`remove worktree for ${c}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});l.error({error:a.reason,msg:p.message})}return o&&n.length===r.length&&await xa`git worktree prune`,n};var Sr=async(e,r,t)=>{try{return await t()}catch(o){throw l.error({err:it(o)},`\u274C Failed to ${e}`),new h(o,{operation:e,remediation:r})}},Ta=async e=>{let r=await U`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},Sd=async e=>{let r=co(e),t=await U`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(n=>n.title===r)??null},Pa=async()=>{let e=await U`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},Cd=async e=>{let r=fe(e),t=await Ta(r);if(!t)throw l.error(`\u274C No PR found for branch ${r}.`),new h(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},$d=async()=>{let e=await O(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,_(i.title)]));g.setInteractive();let o=await M(),s=await Oe(W({branches:r,descriptions:o,types:t})),n=e.find(i=>i.branch===s);if(!n)throw l.error(`\u274C Release branch ${s} not found in open PRs.`),new h(void 0,{operation:`deliver release ${s}`,remediation:`confirm an open PR exists for ${s} ('gh pr list')`});return{selectedReleaseBranch:s,releasePrTitle:n.title}},Ad=async e=>{if(!(await ne("release")).includes(e))return;let o=`${await x()}${ie}`;if((await at({branches:[e],worktreeDir:o})).length===0)throw new h(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${o}/${e} (use --force if uncommitted changes)`})},Id=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",s=await Ta(r);if(!s)throw new h(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(s.state==="MERGED"){l.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new h(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await Sr(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await U`gh pr merge ${r} --squash --admin --delete-branch`})},_d=async e=>{let r=D(e),t=co(e),o=await Pa();if(o){let n=o.number;return o.title!==t&&(l.info(`Adopting open dev \u2192 main PR #${n} ("${o.title}") and retitling for ${r}`),await Sr(`retitle dev \u2192 main PR #${n} to "${t}"`,`update manually: gh pr edit ${n} --title "${t}"`,async()=>{await U`gh pr edit ${n} --title ${t}`})),n}await Sr(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await U`gh pr create --base main --head dev --title ${t} --body ""`});let s=await Pa();if(!s)throw new h(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return s.number},Od=async e=>{let r=D(e);if(await Sd(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await _d(e);await Sr(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await U`gh pr merge ${o} --squash --admin`})},Nd=async()=>{U.quiet=!1,await Sr("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await U`gh workflow run deploy-all.yml --ref main -f environment=prod`}),U.quiet=!0},Dd=async()=>{await Sr("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 U`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Md=async e=>{try{await xs(e)}catch(r){l.warn({err:it(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Ps(e)}catch(r){l.warn({err:it(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},jd=async e=>{let r=await He();if(!r){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=G(e);await nn({versionName:t},r)}catch(t){l.error({err:it(t)},"Failed to deliver Jira release (non-blocking)")}},Sa=async e=>{let{version:r,confirmedCommand:t}=e;await te({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:s}=r?await Cd(r):await $d(),n=N(o);if(!n)throw new h(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=D(n);g.addOption("--version",i),l.info(`Delivering ${n.kind==="name"?"named release":"version"} ${o}`);let a=_(s);await B(t,`Are you sure you want to deliver version ${o} to production?`),g.addOption("--yes",!0),U.quiet=!0,await Ad(o),await Id({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await Od(n),await Nd(),await Dd(),await Md(o),U.quiet=!1,await jd(n),l.info(`Successfully delivered ${o} to production!`),g.print();let c={releaseBranch:o,version:i,type:a,success:!0};return{content:w(JSON.stringify(c,null,2)),structuredContent:c}},un=k({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:ct.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:ct.string().describe("The release branch that was delivered"),version:ct.string().describe("The version that was delivered"),type:ct.enum(["regular","hotfix"]).describe("Release type"),success:ct.boolean().describe("Whether the delivery was successful")},handler:Sa});import Ld from"@inquirer/confirm";import{z as ge}from"zod";import{$ as mn}from"zx";import Fd from"@inquirer/select";var Cr=async(e,r)=>{if(e.length===0)throw new h(void 0,{operation:r,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return C(t=>Fd({message:"\u{1F9EA} Select environment",choices:e.map(o=>({name:o,value:o}))},t))};var Wd="deploy-all.yml",Vd=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;g.setInteractive();let s=await C(n=>Ld({message:`Deploy ${t} \u2192 ${o}?`,default:!1},n));return s&&g.addOption("--yes",!0),s},Ca=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:s}=e,n="";if(r)n=r==="dev"?"dev":fe(r);else{g.setInteractive();let d=await O(),f=d.map(y=>y.branch),v=new Map(d.map(y=>[y.branch,_(y.title)])),m=await M();n=await Oe([{value:"dev",label:"dev"},...W({branches:f,descriptions:m,types:v})])}let i=tt(n);g.addOption("--version",i);let a=await Je(),c=Ve(await Ke(Wd),a),p="";t?p=t:(g.setInteractive(),p=await Cr(c,"launch deploy-all workflow")),g.addOption("--env",p),Be(p,"launch deploy-all workflow",a),Jr({env:p,branch:n});let u=o??!1;if(u&&g.addOption("--skip-terraform",!0),!await Vd({confirmedCommand:s,branch:n,env:p})){l.info("Deployment cancelled");let d={releaseBranch:n,version:i,environment:p,skipTerraformDeploy:u,success:!1};return{content:w(JSON.stringify(d,null,2)),structuredContent:d}}try{mn.quiet=!0,await mn`gh workflow run deploy-all.yml --ref ${n} -f environment=${p} ${u?["-f","skip_terraform_deploy=true"]:[]}`,mn.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${p}`),g.print();let f={releaseBranch:n,version:i,environment:p,skipTerraformDeploy:u,success:!0};return{content:w(JSON.stringify(f,null,2)),structuredContent:f}}catch(d){throw l.error({error:d},"\u274C Error launching workflow"),new h(d,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},fn=k({name:"gh-release-deploy-all",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. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',requiresHumanConfirm:!0,inputSchema:{version:ge.string().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. Required for MCP calls.'),env:ge.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:ge.boolean().optional().describe("Skip the terraform deployment stage."),confirm:ge.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:ge.string().describe("The release branch that was deployed"),version:ge.string().describe("The version that was deployed"),environment:ge.string().describe("The environment deployed to"),skipTerraformDeploy:ge.boolean().describe("Whether terraform deployment was skipped"),success:ge.boolean().describe("Whether the deployment was successful")},handler:Ca});import Bd from"@inquirer/checkbox";import Jd from"@inquirer/confirm";import Kd from"node:fs/promises";import{resolve as Gd}from"node:path";import Ud from"yaml";import{z}from"zod";import{$ as gn}from"zx";var Xt="deploy-selected-services.yml",zd="skip_terraform_deploy",qd=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;g.setInteractive();let s=await C(n=>Jd({message:`Deploy ${t} \u2192 ${o}?`,default:!1},n));return s&&g.addOption("--yes",!0),s},$a=async e=>{let{version:r,env:t,services:o,skipTerraform:s,confirmedCommand:n}=e,i="";if(r)i=r==="dev"?"dev":fe(r);else{g.setInteractive();let R=await O(),S=R.map(E=>E.branch),$=new Map(R.map(E=>[E.branch,_(E.title)])),Z=await M();i=await Oe([{value:"dev",label:"dev"},...W({branches:S,descriptions:Z,types:$})])}let a=tt(i);g.addOption("--version",a);let c=await Je(),p=Ve(await Ke(Xt),c),u="";t?u=t:(g.setInteractive(),u=await Cr(p,"launch deploy-selected workflow")),g.addOption("--env",u),Be(u,"launch deploy-selected workflow",c),Jr({env:u,branch:i});let d=await Hd();if(d.length===0)throw new h(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Xt}`,stderrExcerpt:`no services found in .github/workflows/${Xt}`});let f=[];if(o&&o.length>0?f=o:(g.setInteractive(),f=await C(R=>Bd({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:d.map(S=>({name:S,value:S}))},R))),g.addOption("--services",f),f.length===0)throw new h(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${d.join(", ")}`,stderrExcerpt:"no services selected"});let v=f.filter(R=>!d.includes(R));if(v.length>0)throw new h(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${d.join(", ")}`,stderrExcerpt:`invalid services: ${v.join(", ")}`});let m=s??!1;m&&g.addOption("--skip-terraform",!0);let y=R=>{let S={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:m,success:R};return{content:w(JSON.stringify(S,null,2)),structuredContent:S}};if(!await qd({confirmedCommand:n,branch:i,env:u}))return l.info("Deployment cancelled"),y(!1);try{gn.quiet=!0;let R=f.flatMap($=>["-f",`${$}=true`]);return await gn`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${R} ${m?["-f","skip_terraform_deploy=true"]:[]}`,gn.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),g.print(),y(!0)}catch(R){throw l.error({error:R},"\u274C Error launching workflow"),new h(R,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Hd=async()=>{let e=await x(),r=Gd(e,".github/workflows",Xt),t;try{t=Ud.parse(await Kd.readFile(r,"utf-8"))}catch{return[]}let s=t?.on?.workflow_dispatch?.inputs;return typeof s!="object"||s===null?[]:Object.entries(s).filter(([n,i])=>i?.type==="boolean"&&n!==zd).map(([n])=>n)},hn=k({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,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. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:z.string().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. Required for MCP calls.'),env:z.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:z.array(z.string()).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"). Required for MCP calls.'),skipTerraform:z.boolean().optional().describe("Skip the terraform deployment stage."),confirm:z.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:z.string().describe("The release branch that was deployed"),version:z.string().describe("The version that was deployed"),environment:z.string().describe("The environment deployed to"),services:z.array(z.string()).describe("The services that were deployed"),skipTerraformDeploy:z.boolean().describe("Whether terraform deployment was skipped"),success:z.boolean().describe("Whether the deployment was successful")},handler:$a});import{z as $r}from"zod";var Aa=async()=>{let r=(await O()).flatMap(i=>{let a=N(i.branch);return a?[{version:D(a),jiraKey:G(a),type:_(i.title)}]:[]}),t=await M(),o=Math.max(...r.map(i=>i.version.length)),s=r.map(i=>{let a=rt(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
220
+ `),l.info(`
221
+ ${s.join(`
222
+ `)}
223
+ `);let n={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:w(JSON.stringify(n,null,2)),structuredContent:n}},vn=k({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:$r.array($r.object({version:$r.string().describe("Release version"),type:$r.enum(["regular","hotfix"]).describe("Release type"),description:$r.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:$r.number().describe("Number of release branches")},handler:Aa});import Yd from"node:process";var yn=e=>({...e}),wn=e=>{let{env:r,branch:t,sha:o,ambient:s=Yd.env}=e,n={VITE_DOMAIN_ENV:r,VITE_BRANCH_NAME:t,VITE_COMMIT_HASH:o},i={},a=[];for(let[c,p]of Object.entries(s)){if(c.startsWith("VITE_")){a.push(c);continue}i[c]=p}return a.sort(),{childEnv:{...i,...n,DEPLOY_ENV:r,DEPLOY_BRANCH:t,DEPLOY_SHA:o,TURBO_TELEMETRY_DISABLED:"1"},contract:n,stripped:a}},Qt=e=>{let r=Object.entries(e.contract).map(([t,o])=>` ${t.padEnd(17)}= ${o}`);return e.stripped.length>0&&r.push(` stripped from shell: ${e.stripped.join(", ")}`),r.join(`
224
+ `)};import au from"@inquirer/checkbox";import cu from"@inquirer/confirm";import lu from"@inquirer/select";import{spawn as pu}from"node:child_process";import du from"node:process";import{z as A}from"zod";import{$ as pt}from"zx";import{$ as lt}from"zx";var Zd=async e=>{let r=lt.quiet;lt.quiet=!0;try{let t=`/${e}/environment`,o=await lt`aws sts get-caller-identity --query Account --output text`,s=await lt`aws ssm get-parameter --name ${t} --query Parameter.Value --output text`;return{accountId:o.stdout.trim(),stage:s.stdout.trim()}}catch(t){throw new h(t,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{lt.quiet=r}},Ia=(e,r)=>{if(r.stage!==e)throw new h(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${r.accountId} reports "${r.stage}" \u2014 refusing to deploy to an environment you did not name`})},_a=e=>{let{env:r,isShared:t,isClean:o}=e;if(!(!t||o))throw new h(void 0,{operation:`deploy to shared environment "${r}"`,remediation:"commit or stash first, or deploy to a personal environment instead",stderrExcerpt:"the working tree has uncommitted changes and this environment is shared"})},Oa=(e,r)=>{if(r.includes(e))throw new h(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`})},kn=async e=>{let{env:r,project:t,isShared:o,isClean:s,runningEnvs:n,skip:i,protectedEnvAccess:a}=e;if(Be(r,`deploy to "${r}"`,a),Oa(r,n),i.includes("clean-tree")&&de(r))throw new h(void 0,{operation:`deploy to "${r}"`,remediation:"commit or stash your changes \u2014 this check is not waivable for a delivery target",stderrExcerpt:`refusing to skip the clean-tree check for "${r}"`});i.includes("clean-tree")||_a({env:r,isShared:o,isClean:s});let c=await Zd(t);return Ia(r,c),{identity:c,skipped:i}};import ja from"node:fs/promises";import Ma from"node:path";import Na from"node:fs/promises";import Da from"node:path";var Xd=".github/workflows",Qd=/script_name:\s*(?<service>[a-z0-9-]+)/,eu=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,ru=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,bn=async e=>{let r=Da.resolve(e,Xd),t;try{t=await Na.readdir(r)}catch{return new Map}let o=new Map;for(let s of t.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml"))){let n;try{n=await Na.readFile(Da.resolve(r,s),"utf-8")}catch{continue}tu(n,o)}return o},tu=(e,r)=>{for(let t of e.split(/\n(?= {2}[\w-]+:)/i)){let o=Qd.exec(t)?.groups?.service??eu.exec(t)?.groups?.service;if(o===void 0||t.trimStart().startsWith("#"))continue;let s=[...t.matchAll(ru)].map(n=>n.groups?.env??"");s.length!==0&&r.set(o,[...new Set([...r.get(o)??[],...s])])}},Rn=(e,r)=>e===null?r??null:r===void 0?e:e.filter(t=>r.includes(t));var ou="devops/scripts",nu=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,su=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,En=async e=>{let r=Ma.resolve(e,ou),t;try{t=await ja.readdir(r)}catch{return[]}let o=await bn(e);return(await Promise.all(t.map(n=>({entry:n,match:nu.exec(n)})).filter(n=>n.match!==null).map(async({entry:n,match:i})=>{let a=Ma.resolve(r,n),c=i?.groups?.service??"";return{name:c,scriptPath:a,allowedEnvs:Rn(await iu(a),o.get(c))}}))).sort((n,i)=>n.name.localeCompare(i.name))},iu=async e=>{let r;try{r=await ja.readFile(e,"utf-8")}catch{return null}let t=r.split(`
225
+ `).filter(s=>!s.trimStart().startsWith("#")).reduce((s,n)=>s??su.exec(n)?.groups?.envs,void 0);if(t===void 0)return null;let o=t.split(/\s+/).filter(Boolean);return o.length>0?o:null},eo=(e,r)=>e.allowedEnvs===null||e.allowedEnvs.includes(r),xn=(e,r)=>e.filter(t=>eo(t,r));var Fa="deploy-all.yml",uu=["dev","stage"],mu=e=>uu.includes(e)||de(e),La="/bin/sh",fu=async()=>{let e=pt.quiet;pt.quiet=!0;try{let r=await pt`gh run list --workflow=${Fa} --status=in_progress --json displayTitle`;return JSON.parse(r.stdout).flatMap(o=>/\[(?<env>[a-z0-9-]+)\]/.exec(o.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{pt.quiet=e}},gu=async(e,r)=>{let t=e.map(s=>({name:s.name,value:s.name})),o=await C(s=>au({message:`Deploy which services to ${r}?`,choices:t,pageSize:20},s));if(o.length===0)throw new h(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return o},hu=async e=>{let{env:r,isShared:t,count:o}=e;return t?C(s=>lu({message:`"${r}" is a SHARED environment \u2014 deploying ${o} service(s) from this machine. Continue?`,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${r}`,value:!0}]},s)):C(s=>cu({message:`Deploy ${o} service(s) to ${r} from this machine?`,default:!1},s))},vu=(e,r,t)=>new Promise((o,s)=>{let n=pu(La,[e.scriptPath],{cwd:t,env:r,stdio:"inherit"});n.on("error",s),n.on("close",i=>{o(i??1)})}),yu=async e=>{let{chosen:r,childEnv:t,cwd:o,env:s}=e,n=[],i=[];for(let a of r){l.info(`\u2192 ${a.name} \u2192 ${s}`);let c=await vu(a,t,o);if(c!==0){i.push(a.name),l.error(`\u2717 ${a.name} failed (exit ${c})`);break}n.push(a.name),l.info(`\u2713 ${a.name}`)}return{deployed:n,failed:i}},wu=e=>{let{names:r,services:t,env:o}=e,s=new Map(t.map(a=>[a.name,a])),n=r.filter(a=>!s.has(a));if(n.length>0)throw new h(void 0,{operation:"resolve the requested services",remediation:`known services: ${t.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${n.join(", ")}`});let i=r.filter(a=>{let c=s.get(a);return c!==void 0&&!eo(c,o)});if(i.length>0)throw new h(void 0,{operation:`deploy to "${o}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${o}": ${i.join(", ")} (the scripts would skip them)`});return r.map(a=>s.get(a))},Pn=e=>{let{env:r,accountId:t,names:o,built:s,deployed:n,failed:i,dryRun:a,success:c}=e,p={environment:r,accountId:t,services:o,deployed:n,failed:i,contract:yn(s.contract),strippedVars:s.stripped,dryRun:a,success:c};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}},ku=async e=>{let{selection:r,eligible:t,service:o,env:s}=e;return r==="all"?t.map(n=>n.name):o&&o.length>0?o:(g.setInteractive(),gu(t,s))},Wa=async(e,r)=>{let{env:t,service:o,yes:s,dryRun:n,printEnv:i,skipPreflight:a=[]}=e,c=await x(),p=await Es(),u=await En(c);if(u.length===0)throw new h(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${c}/devops/scripts`});let d=await Je(),f=Ve(await Ke(Fa),d),v=t??"";v||(g.setInteractive(),v=await Cr(f,"deploy locally")),g.addOption("--env",v);let m=xn(u,v);if(m.length===0)throw new h(void 0,{operation:`deploy to "${v}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${v}"`});let y=await ku({selection:r,eligible:m,service:o,env:v}),R=wu({names:y,services:u,env:v});if(r==="selected")for(let Qe of y)g.addOption("--service",Qe);let S=mu(v),$=await bs(),Z=(await pt`git rev-parse HEAD`.quiet()).stdout.trim(),E=wn({env:v,branch:$,sha:Z});i&&l.info(`Deploy contract for ${v}:
226
+ ${Qt(E)}`);let be=a.filter(Qe=>Qe==="clean-tree"||Qe==="toolchain"),Ee=(await kn({env:v,project:p,isShared:S,isClean:await bt(),runningEnvs:await fu(),skip:be,protectedEnvAccess:d})).identity.accountId;if(n)return l.info([`Would deploy to "${v}" (AWS account ${Ee}) from this machine`,Qt(E),"Commands:",...R.map(Qe=>` ${La} ${Qe.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
227
+ `)),Pn({env:v,accountId:Ee,names:y,built:E,deployed:[],failed:[],dryRun:!0,success:!0});if(!s&&!await hu({env:v,isShared:S,count:y.length}))return l.info("Deployment cancelled"),Pn({env:v,accountId:Ee,names:y,built:E,deployed:[],failed:[],dryRun:!1,success:!1});E.stripped.length>0&&l.info(`Stripped ambient VITE_* from the build env: ${E.stripped.join(", ")}`);let{deployed:Ir,failed:xe}=await yu({chosen:R,childEnv:E.childEnv,cwd:c,env:v});return xe.length>0&&(l.error(`Partial deploy to "${v}": succeeded [${Ir.join(", ")||"none"}], failed [${xe.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),du.exitCode=1),g.print(),Pn({env:v,accountId:Ee,names:y,built:E,deployed:Ir,failed:xe,dryRun:!1,success:xe.length===0})},Va=async e=>Wa(e,"all"),Ba=async e=>Wa(e,"selected"),Ja='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.',Ka={env:A.string().describe('Target environment, e.g. "dev" or a personal env like "arthur". Required for MCP.'),dryRun:A.boolean().optional().describe("Resolve target, contract and commands without deploying."),skipPreflight:A.array(A.enum(["clean-tree","toolchain"])).optional().describe("Waive a named non-critical check. The env/account and protected-env checks can never be waived, and clean-tree cannot be waived for a protected env."),confirm:A.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Ga={environment:A.string().describe("Environment deployed to"),accountId:A.string().describe("AWS account the deploy targeted"),services:A.array(A.string()).describe("Services requested"),deployed:A.array(A.string()).describe("Services that completed successfully"),failed:A.array(A.string()).describe("Services that failed"),contract:A.record(A.string(),A.string()).describe("Build contract passed to the scripts"),strippedVars:A.array(A.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:A.boolean().describe("Whether this was a dry run"),success:A.boolean().describe("Whether every requested service deployed")},Tn=k({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Ja}`,requiresHumanConfirm:!0,inputSchema:Ka,outputSchema:Ga,handler:Va}),Sn=k({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Ja}`,requiresHumanConfirm:!0,inputSchema:{...Ka,service:A.array(A.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Ga,handler:Ba});import $u from"@inquirer/confirm";import Ln from"@inquirer/input";import Ha from"@inquirer/select";import jn from"node:process";import{z as I}from"zod";import{$ as to}from"zx";var Ne=e=>e.slice(1).split(".").map(Number),Cn=e=>[...e].sort((r,t)=>{let[o,s,n]=Ne(r),[i,a,c]=Ne(t);return o!==i?(o??0)-(i??0):s!==a?(s??0)-(a??0):(n??0)-(c??0)});var za="next",bu=/^v?(\d+)\.(\d+)\.(\d+)$/,Ru=e=>e.replace(/^.*release\//,""),An=e=>{let r=Ru(e.trim()),t=bu.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},Ua=e=>`${e[0]}.${e[1]}.${e[2]}`,In=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let s of r){let n=An(s);if(!n)continue;let i=Ua(n);o.has(i)||(o.add(i),t.push(n))}return Cn(t.map(s=>Ua(s))).map(s=>Ne(`v${s}`))},Ze=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},ro=(e,r)=>{if(e.length===0)throw new Ze;let t=e[e.length-1];if(r==="hotfix"){let[n,i]=t,a=e.reduce((c,p)=>p[0]===n&&p[1]===i?Math.max(c,p[2]):c,0);return`${n}.${i}.${a+1}`}let[o,s]=t;return`${o}.${s+1}.0`},_n=e=>e.trim().toLowerCase()===za,Eu=e=>e==="regular"||e==="hotfix",qa=e=>"name"in e,xu=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":"),o=r,s="regular",n="";if(t!==-1){o=r.slice(0,t).trim();let a=r.slice(t+1),c=a.indexOf(":"),p=c===-1?a.trim():a.slice(0,c).trim();n=c===-1?"":a.slice(c+1).trim();let u=p.toLowerCase();if(!Eu(u))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);s=u}if(_n(o)||An(o)!==null){let a={version:o,type:s};return n!==""&&(a.description=n),a}let i={name:o,type:s};return n!==""&&(i.description=n),i},On=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},$n=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Pu=e=>{let r=e.name.trim();return wt(r),$n({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},Nn=(e,r)=>{let t=[...r];return e.map(o=>{if(qa(o))return Pu(o);let s=o.version.trim();if(s==="")throw new Error("Release entry has an empty version");if(_n(s)){let a=ro(t,o.type);return t.push(Ne(`v${a}`)),$n({id:X(a),type:o.type},o.description)}let n=An(s);if(!n)throw new Error(`Invalid version "${s}". Expected semver like "1.2.5" or the token "next".`);let i=`${n[0]}.${n[1]}.${n[2]}`;return t.push(n),$n({id:X(i),type:o.type},o.description)})},Dn=e=>e.some(r=>!qa(r)&&_n(r.version));var Tu=e=>e.split(`
228
+ `).map(r=>{let t=r.indexOf(" ");return t===-1?null:N(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Su=async()=>{let e=to.quiet;try{to.quiet=!0;let r=await to`git ls-remote --heads origin 'release/v*'`;return Tu(r.stdout)}finally{to.quiet=e}},Cu=async()=>{let e=await He();return e?(await xr(e)).map(t=>t.name):[]},Mn=async()=>{let[e,r]=await Promise.allSettled([Su(),Cu()]);return e.status==="rejected"&&l.warn({error:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&l.warn({error:r.reason},"Failed to fetch Jira versions; continuing without them"),In({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Au='"1.2.5" or "next"',Iu=(e,r)=>{try{return ro(e,r)}catch(t){if(t instanceof Ze)return null;throw t}},Fn=(e,r)=>{try{return Nn(e,r)}catch(t){throw t instanceof Ze?new h(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof ys?new h(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},_u=async(e,r)=>{let t=Iu(e,r),o=t?` [${t}]`:"",s=(await C(i=>Ln({message:` Version (e.g. ${Au})${o}: `},i))).trim(),n=s===""?t??"":s;return n===""&&(l.error("No version provided. Exiting..."),jn.exit(1)),n},Ou=async()=>{let e=(await C(r=>Ln({message:' Name (kebab-case, e.g. "checkout-redesign"): '},r))).trim();e===""&&(l.error("No name provided. Exiting..."),jn.exit(1));try{wt(e)}catch(r){let t=r instanceof Error?r.message:String(r);l.error(`${t} Exiting...`),jn.exit(1)}return e},Nu=async e=>{g.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),s=[],n=!0;for(;n;){let i=s.length+1,a=await C(d=>Ha({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},d)),c=await C(d=>Ha({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},d)),p;if(a==="name"){let d=await Ou();p=Fn([{name:d,type:c}],[])[0]}else{let d=await _u(await o(),c);p=Fn([{version:d,type:c}],t)[0],p.id.kind==="version"&&t.push(Ne(`v${p.id.raw}`))}let u=(await C(d=>Ln({message:" Description (optional, press Enter to skip): "},d))).trim();s.push({...p,...u!==""?{description:u}:{}}),n=await C(d=>$u({message:"Add another release?",default:!1},d))}return s},Du=e=>{let t=[e.id.kind==="version"?`v${e.id.raw}`:e.id.name,e.type];return e.description&&t.push(e.description),t.join(" \xB7 ")},Ya=e=>{for(let r of e)g.addOption("--release",On(r))},Mu=async(e,r)=>{if(e&&e.length>0){let o=Dn(e)?await r():[],s=Fn(e,o);return Ya(s),s}let t=await Nu(r);return Ya(t),t},ju=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new h(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"})},Fu=async(e,r)=>{let t=e.map(Du).join(`
229
+ - `);await B(r,`Create the following ${e.length} release(s)?
230
+ - ${t}
231
+ `),g.addOption("--yes",!0)},Lu=async e=>{let{entry:r,jiraConfig:t}=e,o=D(r.id),s=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await sn(r.type);let n=await an({id:r.id,jiraConfig:t,description:r.description,type:r.type});return l.info(`\u2705 Successfully created release: ${s} (${r.type})`),l.info(`\u{1F517} GitHub PR: ${n.prUrl}`),l.info(`\u{1F517} Jira Version: ${n.jiraVersionUrl}
232
+ `),{result:n}}catch(n){let i=new h(n,{operation:`create release ${s} (${r.type})`,remediation:"verify the version or name is unique and the base branch is clean"});return l.error(`\u274C ${i.message}
233
+ `),{failure:{version:o,error:i.message}}}},Wu=(e,r,t)=>{r===e?l.info(`\u2705 All ${e} release branch(es) were created successfully.`):r>0?(l.warn(`\u26A0\uFE0F ${r} of ${e} release branches were created successfully.`),l.warn(`\u274C ${t} release(s) failed.`)):l.error(`\u274C All ${e} release branch(es) failed to create.`)},Za=async e=>{let{releases:r,confirmedCommand:t}=e,o=await Pr(),s=null,i=await Mu(r,async()=>(s===null&&(s=await Mn()),s));if(i.length===0)throw new h(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"});ju(i),await te({operation:"create release"}),await Fu(i,!!t);let a=[],c=[];for(let u of i){let{result:d,failure:f}=await Lu({entry:u,jiraConfig:o});d&&a.push(d),f&&c.push(f)}Wu(i.length,a.length,c.length),g.print();let p={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}},Wn=k({name:"release-create",requiresHumanConfirm:!0,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. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:I.array(I.object({version:I.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:I.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:I.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:I.string().optional().describe("Optional description for the Jira version.")}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description.'),confirm:I.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:I.array(I.string()).describe("List of created release branch names"),successCount:I.number().describe("Number of releases created successfully"),failureCount:I.number().describe("Number of releases that failed"),releases:I.array(I.object({version:I.string().describe("Version number"),type:I.enum(["regular","hotfix"]).describe("Release type"),branchName:I.string().describe("Release branch name"),prUrl:I.string().describe("GitHub PR URL"),jiraVersionUrl:I.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:I.array(I.object({version:I.string().describe("Version number that failed"),error:I.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Za});import Vu from"@inquirer/input";import{z as De}from"zod";var Xa=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,Bu=(e,r)=>r.trim()!==""?`${e}
234
+
235
+ ${r}`:`${e}
236
+ `,Ju=async()=>{let e=await O(),r=e.map(n=>n.branch),t=new Map(e.map(n=>[n.branch,_(n.title)])),o=await M(),s=await Oe(W({branches:r,descriptions:o,types:t}));return{branch:s,type:t.get(s)||"regular"}},Ku=async e=>{let t=(await O()).find(o=>o.branch===e);if(!t)throw new h(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return _(t.title)},Gu=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await C(s=>Vu({message:` New description ${r} (press Enter to keep current): `},s))).trim();return o===""?e:o},Qa=async e=>{let{version:r,description:t,confirmedCommand:o}=e,s=await Pr(),n;r?(n=fe(r),await Ku(n)):(g.setInteractive(),n=(await Ju()).branch);let i=N(n);if(!i)throw new h(void 0,{operation:`edit description for ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=D(i);g.addOption("--version",a);let c=G(i),p=await Kt(c,s);if(!p)throw new h(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let u=p.description??"",d;t!==void 0?(d=t,g.addOption("--description",d)):(g.setInteractive(),d=await Gu(u));let f=y=>{let R={version:a,branch:n,jiraVersionUrl:Xa(s,p),previousDescription:u,newDescription:d,changed:y};return{content:w(JSON.stringify(R,null,2)),structuredContent:R}};if(d===u)return l.info(`No change \u2014 description for ${c} is already: "${u}"`),g.print(),f(!1);await B(o,`Update description for ${c}?
237
+ from: "${u}"
238
+ to: "${d}"
239
+ `),g.addOption("--yes",!0),await Gt({versionId:p.id,description:d},s);let v=Xa(s,p),m=Bu(v,d);return await Ht({branch:n,body:m}),l.info(`\u2705 Updated description for ${c}`),l.info(`\u{1F517} Jira Version: ${v}`),l.info(`\u{1F517} PR branch: ${n}
240
+ `),g.print(),f(!0)},Vn=k({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:De.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:De.string().describe("New description. Empty string clears the description.")},outputSchema:{version:De.string().describe("Release version"),branch:De.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:De.string().describe("Jira fix version URL"),previousDescription:De.string().describe("The description before the update"),newDescription:De.string().describe("The description after the update"),changed:De.boolean().describe("Whether the description actually changed")},handler:Qa});import{execFile as om}from"node:child_process";import nc from"node:path";import sc from"node:process";import{z as L}from"zod";import ec from"node:fs/promises";import oo from"node:path";var dt=async e=>{let{workspacePath:r,folderPaths:t}=e,o=oo.dirname(r),s;try{s=await ec.readFile(r,"utf-8")}catch(u){throw new Error(`Cursor workspace file not found at ${r}: ${u.message}`)}let n;try{n=JSON.parse(s)}catch(u){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${u.message}`)}let i=n.folders??[],a=new Set(i.map(u=>oo.resolve(o,u.path))),c=[],p=[];for(let u of t){let d=oo.resolve(u);if(a.has(d)){p.push(u);continue}let f=oo.relative(o,d);i.push({path:f}),a.add(d),c.push(u)}return n.folders=i,await ec.writeFile(r,`${JSON.stringify(n,null,2)}
241
+ `,"utf-8"),{added:c,skipped:p}};import{$ as Uu}from"zx";var ut=async e=>{await Uu`cursor ${e}`};import zu from"node:fs/promises";import so from"node:path";import rc from"node:fs/promises";import no from"node:path";var mt=async e=>{let{workspacePath:r,folderPaths:t}=e,o=no.dirname(r),s;try{s=await rc.readFile(r,"utf-8")}catch(f){throw new Error(`Cursor workspace file not found at ${r}: ${f.message}`)}let n;try{n=JSON.parse(s)}catch(f){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${f.message}`)}let i=n.folders??[],a=new Set(t.map(f=>no.resolve(f))),c=new Set,p=i.filter(f=>{let v=no.resolve(o,f.path);return a.has(v)?(c.add(v),!1):!0});n.folders=p,await rc.writeFile(r,`${JSON.stringify(n,null,2)}
242
+ `,"utf-8");let u=[],d=[];for(let f of t){let v=no.resolve(f);c.has(v)?u.push(f):d.push(f)}return{removed:u,notFound:d}};var Bn=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,s=so.dirname(r),n=so.resolve(`${t}/release`),i=await zu.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(m=>so.resolve(`${t}/${m}`))),u=[];for(let m of c){let y=so.resolve(s,m.path);(y===n||y.startsWith(`${n}/`))&&!p.has(y)&&u.push(y)}let d=[];u.length>0&&(d=(await mt({workspacePath:r,folderPaths:u})).removed);let f=o.map(m=>`${t}/${m}`),{added:v}=f.length>0?await dt({workspacePath:r,folderPaths:f}):{added:[]};return{added:v,removed:d}};import tc from"node:path";var Xe=(e,r)=>tc.isAbsolute(e)?e:tc.resolve(r,e);var Jn=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,cursorConfig:s}=e;if(!s.workspaceConfigPath)return l.warn("\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set."),{ran:!1,added:0,removed:0};let n=Xe(s.workspaceConfigPath,r);try{let{added:i,removed:a}=await Bn({workspacePath:n,worktreeDir:t,currentBranches:o});return o.length>0&&await ut(n),{ran:!0,added:i.length,removed:a.length}}catch(i){return l.warn({error:i},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${n}`),{ran:!1,added:0,removed:0}}};import{$ as qu}from"zx";var Kn=async e=>{let{folderPaths:r}=e;for(let t of r)await qu`zed --add ${t}`;return{added:r}};import{$ as Hu}from"zx";var Gn=async e=>{let{worktreePaths:r}=e;if(r.length===0)return{ran:!1,added:0,removed:0};try{return await Hu`zed ${r}`,{ran:!0,added:r.length,removed:0}}catch(t){return l.warn({error:t},"\u26A0\uFE0F Failed to open Zed workspace"),{ran:!1,added:0,removed:0}}};import{$ as Yu}from"zx";var Un=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,s=[r,...o.map(n=>`${t}/${n}`)];try{return await Yu`zed --reuse ${s}`,l.info(`\u21BB Refreshed Zed workspace to root + ${o.length} release worktree(s) (other folders in the focused window are not preserved)`),{ran:!0}}catch(n){return l.warn({error:n},"\u26A0\uFE0F Failed to refresh Zed workspace"),{ran:!1}}};var he=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var zn=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,s=await T(),n=se(s),i=o.map(c=>`${t}/${c}`),a=[];for(let c of n)switch(c.provider){case"cursor":{if(!c.config.workspaceConfigPath){l.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),a.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let p=Xe(c.config.workspaceConfigPath,r),{added:u,skipped:d}=await dt({workspacePath:p,folderPaths:i}),f=d.length>0?` (${d.length} already present)`:"";l.info(`\u2705 Added ${u.length} folder(s) to ${p}${f}`),await ut(p),a.push({ran:!0,provider:"cursor",added:u.length,skipped:d.length});break}case"zed":{let{added:p}=await Kn({folderPaths:i});l.info(`\u2705 Added ${p.length} folder(s) to Zed workspace`),a.push({ran:!0,provider:"zed",added:p.length,skipped:0});break}default:he(c)}return a};var qn=async e=>{let r=await T(),t=se(r),{projectRoot:o,worktreeDir:s,worktreePaths:n,currentBranches:i}=e,a=[];for(let c of t)switch(c.provider){case"cursor":{let p=await Jn({projectRoot:o,worktreeDir:s,currentBranches:i,cursorConfig:c.config});a.push({...p,provider:"cursor"});break}case"zed":{let p=await Gn({worktreePaths:n});a.push({...p,provider:"zed"});break}default:he(c)}return a};var Hn=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return he(e)}};var ft=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:s,allowEditorRelaunch:n}=e;if(s.length===0)return[];let i=await T(),a=se(i),c=s.map(d=>`${t}/${d}`),p=o.filter(d=>!s.includes(d)),u=[];for(let d of a)switch(d.provider){case"cursor":{u.push(await Zu({ide:d,projectRoot:r,folderPaths:c}));break}case"zed":{u.push(await Xu({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:n}));break}default:he(d)}return u},Zu=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let s=Xe(r.config.workspaceConfigPath,t);try{let{removed:n}=await mt({workspacePath:s,folderPaths:o});return n.length>0&&l.info(`\u2705 Removed ${n.length} folder(s) from ${s}`),{provider:"cursor",supported:!0,removed:n}}catch(n){return l.warn({error:n},`\u26A0\uFE0F Failed to update Cursor workspace at ${s}`),{provider:"cursor",supported:!0,removed:[]}}},Xu=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:s}=e;return s?(await Un({projectRoot:r,worktreeDir:t,remainingBranches:o}),{provider:"zed",supported:!0,removed:[]}):(l.info("\u2139\uFE0F Zed folder removal skipped (no interactive session); close removed worktree folders in Zed manually if needed."),{provider:"zed",supported:!0,removed:[]})};var io=["workspace","none"];import Yn from"node:fs/promises";import gt from"node:path";var oc=async e=>{try{return await Yn.access(e),!0}catch{return!1}},Qu=async e=>{if(e&&e.length>0)return e;try{let r=await Pe();return[gt.dirname(r)]}catch(r){throw new h(r,{operation:"discover infra-kit projects",remediation:"run inside an infra-kit repo, or pass --root <dir>"})}},em=e=>e.isDirectory()||e.isSymbolicLink(),rm=async(e,r)=>{if(!em(r))return null;let t=gt.join(e,r.name),[o,s]=await Promise.all([oc(gt.join(t,".git")),oc(gt.join(t,"infra-kit.json"))]);if(!o||!s)return null;try{let n=await Yn.realpath(t);return{name:gt.basename(t),repoRoot:n}}catch{return null}},tm=async e=>{try{return await Yn.readdir(e,{withFileTypes:!0})}catch{return[]}},Zn=async(e={})=>{let r=await Qu(e.roots),t=new Map;for(let o of r){let s=await tm(o);for(let n of s){let i=await rm(o,n);i&&!t.has(i.repoRoot)&&t.set(i.repoRoot,i)}}return[...t.values()].sort((o,s)=>o.name.localeCompare(s.name))};var nm=async(e={})=>e.all?um(e):ic(e),ic=async(e={})=>{let{releaseOnly:r=!1,force:t=!1,dryRun:o=!1}=e;await T();try{let s=await x(),n=`${s}${ie}`,i=nc.basename(await Pe(s)),a=await kt(s),c=sm(a,r),p=c.map(y=>y.path),u=c.map(y=>y.branch).filter(y=>Me(y)),d=c.map(y=>({title:_t({branch:y.branch??nc.basename(y.path)}),cwd:y.path}));if(o){let y=await lm({repo:i,releaseOnly:r,force:t,worktreePaths:p,targets:d});return pm(y,n),g.print(),{content:w(JSON.stringify(y,null,2)),structuredContent:y}}let[f,v]=await Promise.all([qn({projectRoot:s,worktreeDir:n,worktreePaths:p,currentBranches:u}),im({targets:d,force:t,repoName:i})]),m={repo:i,dryRun:!1,releaseOnly:r,worktreePaths:p,ideProviders:f.filter(y=>y.ran).map(y=>y.provider),cmuxOpened:v.opened,cmuxSkipped:v.skipped,cmuxClosed:v.closed};return dm(m,{ideRan:f.some(y=>y.ran)}),g.print(),{content:w(JSON.stringify(m,null,2)),structuredContent:m}}catch(s){throw s instanceof h?s:(l.error({error:s},"\u274C Error reopening worktree windows"),new h(s,{operation:"reopen worktrees",remediation:"run `infra-kit doctor` to check this project's setup"}))}},sm=(e,r)=>e.filter(t=>t.bare||t.prunable?!1:r?Me(t.branch):!0),im=async e=>{let{targets:r,force:t,repoName:o}=e,s=await At(o),n=t?await am({targets:r}):[],{opened:i,skipped:a}=await cm({targets:r,force:t,repoName:o,groupRef:s});return{opened:i,skipped:a,closed:n}},am=async e=>{let{targets:r}=e;if(r.length===0)return[];let t=await ar(),o=[];for(let s of r)t.has(await Nr(s.cwd))&&(await cr(s.cwd),o.push(s.title));return o},ac=async(e,r,t)=>{let o=[],s=[];for(let n of e)!t&&r.has(await Nr(n.cwd))?s.push(n.title):o.push(n);return{toOpen:o,skipped:s}},cm=async e=>{let{targets:r,force:t,repoName:o,groupRef:s=null}=e,n=t?new Set:new Set((await ar()).keys()),{toOpen:i,skipped:a}=await ac(r,n,t),c=[],p=s,u=!1;for(let d of i)try{if(p)await lr({cwd:d.cwd,title:d.title,group:p});else{let f=await lr({cwd:d.cwd,title:d.title});u||(p=await It(o,[f]),u=!0)}c.push(d.title)}catch(f){l.warn({error:f,title:d.title},`\u26A0\uFE0F Failed to reopen cmux workspace ${d.title}`)}return{opened:c,skipped:a}},lm=async e=>{let{repo:r,releaseOnly:t,force:o,worktreePaths:s,targets:n}=e,i=o?new Set:new Set((await ar()).keys()),{toOpen:a,skipped:c}=await ac(n,i,o);return{repo:r,dryRun:!0,releaseOnly:t,worktreePaths:s,ideProviders:[],cmuxOpened:a.map(p=>p.title),cmuxSkipped:c,cmuxClosed:[]}},pm=(e,r)=>{l.info(`\u{1F50E} reopen --dry-run for ${e.repo} (worktrees dir: ${r})`),l.info(`\u{1F4C2} Would open ${e.worktreePaths.length} folder(s) in the editor:`);for(let t of e.worktreePaths)l.info(` ${t}`);if(e.cmuxOpened.length>0){l.info(`\u{1FA9F} Would open ${e.cmuxOpened.length} cmux workspace(s):`);for(let t of e.cmuxOpened)l.info(` ${t}`)}if(e.cmuxSkipped.length>0){l.info(`\u21A9\uFE0F Already open (would skip) ${e.cmuxSkipped.length} cmux workspace(s):`);for(let t of e.cmuxSkipped)l.info(` ${t}`)}},dm=(e,r)=>{if(e.cmuxClosed.length>0&&l.info(`\u{1F9F9} Closed ${e.cmuxClosed.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>Hn(o)).join(", ");l.info(`\u2705 Opened editor workspace(s): ${t}`)}if(e.cmuxOpened.length>0){l.info("\u2705 Opened cmux workspaces:");for(let t of e.cmuxOpened)l.info(t)}e.cmuxSkipped.length>0&&l.info(`\u21A9\uFE0F ${e.cmuxSkipped.length} cmux workspace(s) already open \u2014 skipped`),!r.ideRan&&e.cmuxOpened.length===0&&e.cmuxClosed.length===0&&l.info("\u2139\uFE0F Nothing to reopen")},um=async e=>{let{project:r=[],root:t=[],releaseOnly:o=!1,force:s=!1,dryRun:n=!1}=e,i=await Zn({roots:t}),a=mm(i,r),c=fm({releaseOnly:o,force:s,dryRun:n}),p=[];for(let d of a)p.push(await gm(d,c));let u={all:!0,dryRun:n,projects:a,results:p};return vm(u),g.print(),{content:w(JSON.stringify(u,null,2)),structuredContent:u}},mm=(e,r)=>{if(r.length===0)return e;let t=new Set(e.map(o=>o.name));for(let o of r)t.has(o)||l.warn(`\u26A0\uFE0F --project ${o} matched no discovered project \u2014 skipping`);return e.filter(o=>r.includes(o.name))},fm=e=>{let r=[];return e.dryRun&&r.push("--dry-run"),e.releaseOnly&&r.push("--release-only"),e.force&&r.push("--force"),r},gm=async(e,r)=>{try{let t=await hm(e.repoRoot,r);return{...JSON.parse(t),repo:e.name,ok:!0}}catch(t){let o=t instanceof Error?t.message:String(t);return l.warn({error:t},`\u26A0\uFE0F reopen failed for ${e.name} \u2014 continuing`),{repo:e.name,ok:!1,error:o}}},hm=(e,r)=>{let t=sc.argv[1];return t===void 0?Promise.reject(new Error("cannot resolve the infra-kit CLI entry \u2014 process.argv[1] is undefined")):new Promise((o,s)=>{let n=[t,"reopen","--json",...r];om(sc.execPath,n,{cwd:e,maxBuffer:16*1024*1024},(i,a)=>{if(i){s(i);return}o(a)})})},vm=e=>{let r=e.results.filter(n=>n.ok).length,t=e.results.length-r;l.info(`\u{1F310} reopen --all${e.dryRun?" --dry-run":""}: ${e.projects.length} project(s)`);let o=0,s=0;for(let n of e.results)n.ok?(o+=n.cmuxOpened.length,s+=n.cmuxSkipped.length,l.info(` \u2705 ${n.repo}: ${n.worktreePaths.length} folder(s), ${n.cmuxOpened.length} cmux ${e.dryRun?"planned":"opened"}, ${n.cmuxSkipped.length} skipped`)):l.info(` \u274C ${n.repo}: ${n.error}`);l.info(`\u{1F4CA} ${r} ok, ${t} failed \u2014 ${o} cmux ${e.dryRun?"planned":"opened"}, ${s} already open`)},Xn=k({name:"reopen",description:"Reopen editor + cmux windows for every active worktree in the current project \u2014 the main checkout plus every linked worktree (release, feature, detached). Additive and idempotent by default: cmux workspaces already open are skipped, so running twice does not double the windows. Zed opens the exact folder set; Cursor reconciles its release-branch-shaped workspace. Set releaseOnly to restrict to release worktrees (the legacy reload scope). Set force to close each cmux workspace first, then reopen (disruptive). Set dryRun to return the plan without spawning anything. Non-destructive to git \u2014 only cmux/editor view state is touched.",inputSchema:{releaseOnly:L.boolean().optional().describe("Restrict to release worktrees (reproduces the legacy worktrees-reload scope)"),force:L.boolean().optional().describe("Close each cmux workspace first, then reopen (disruptive)"),dryRun:L.boolean().optional().describe("Return the plan (paths + cmux titles) without spawning anything")},outputSchema:{repo:L.string().describe("Repository name the reopen ran for"),dryRun:L.boolean().describe("Whether this was a dry run (nothing was spawned)"),releaseOnly:L.boolean().describe("Whether the set was restricted to release worktrees"),worktreePaths:L.array(L.string()).describe("Absolute folder set handed to the editor (root-first)"),ideProviders:L.array(L.string()).describe("Configured IDE providers that opened (cursor | zed); empty in dry run"),cmuxOpened:L.array(L.string()).describe("Titles of cmux workspaces opened this run"),cmuxSkipped:L.array(L.string()).describe("Titles of cmux workspaces skipped because already open (additive mode)"),cmuxClosed:L.array(L.string()).describe("Titles of cmux workspaces closed first (force mode only)")},handler:ic});import{existsSync as pc}from"node:fs";import dc from"node:path";import Sm from"node:process";import{z as we}from"zod";import{createHash as ym}from"node:crypto";import{readFileSync as wm}from"node:fs";var Qn=e=>ym("sha256").update(wm(e)).digest("hex");import{readFileSync as Pm,writeFileSync as UP}from"node:fs";import lc from"node:path";import{z as le}from"zod";var ve="vendor",km=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),bm=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),Rm=[".tsbuildinfo"],es=e=>km.has(e),rs=e=>bm.has(e)?!0:Rm.some(r=>e.endsWith(r)),cc=e=>{let r=e.split("/"),t=r.pop()??"";return r.some(s=>es(s))||rs(t)};import{readdirSync as Em}from"node:fs";import ts from"node:path";var xm=e=>e.split(ts.sep).join("/"),os=e=>{let r=[],t=o=>{for(let s of Em(o,{withFileTypes:!0})){let n=ts.join(o,s.name);if(s.isDirectory()){if(es(s.name))continue;t(n);continue}rs(s.name)||r.push(xm(ts.relative(e,n)))}};return t(e),r.sort()};var ye=".sync-manifest.json",ns=1,Tm=le.object({schemaVersion:le.number().optional(),source:le.string(),commit:le.string(),syncedAt:le.string(),fileCount:le.number(),files:le.record(le.string(),le.string())}),ss=e=>(e.schemaVersion??ns)>ns;var is=e=>{let r=lc.join(e,ye),t;try{t=Pm(r,"utf8")}catch{throw new Error(`Missing ${ye} at ${r}`)}let o=Tm.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${ye} at ${r}: ${le.prettifyError(o.error)}`);return o.data};var as=(e,r)=>{let t=Object.fromEntries(Object.entries(r.files).filter(([c])=>!cc(c))),o=os(e),s=[],n=[];for(let c of o){if(!(c in t)){n.push(c);continue}Qn(lc.join(e,c))!==t[c]&&s.push(c)}let i=new Set(o),a=Object.keys(t).filter(c=>!i.has(c));return{modified:s,added:n,removed:a}};var cs=30,ls=(e,r)=>{if(r.length!==0){l.info(`
243
+ ${e} (${r.length}):`);for(let t of r.slice(0,cs))l.info(` ${t}`);r.length>cs&&l.info(` \u2026and ${r.length-cs} more`)}},uc=async(e={})=>{let r=e.cwd??await x(),t=dc.join(r,ve),o={modified:[],added:[],removed:[],fileCount:0};if(!pc(t)){l.info(`\u2139\uFE0F No ${ve}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...o};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}}if(!pc(dc.join(t,ye))){l.error(`\u274C Missing ${ve}/${ye}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...o};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}}let s=is(t);if(ss(s)){l.error(`\u274C ${ve}/${ye} has a newer schemaVersion (${String(s.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...o};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:n,added:i,removed:a}=as(t,s),c=n.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${ve}/ has drifted from ${ve}/${ye}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),ls("Modified",n),ls("Added (not in manifest)",i),ls("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${ve}/ matches manifest (${s.fileCount} files).`);let p={status:c?"drift":"clean",ok:!c,fileCount:s.fileCount,modified:n,added:i,removed:a};return{content:w(JSON.stringify(p,null,2)),structuredContent:p}},Cm={status:we.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:we.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:we.number(),modified:we.array(we.string()),added:we.array(we.string()),removed:we.array(we.string())},ps=k({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:Cm,handler:()=>uc({cwd:Sm.cwd()})});import{z as $m}from"zod";var mc=async()=>{let e=$t.version;l.info(e);let r={version:e};return{content:w(JSON.stringify(r,null,2)),structuredContent:r}},ds=k({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:$m.string().describe("Installed infra-kit CLI version (from package.json)")},handler:mc});import fc from"@inquirer/confirm";import Am from"node:path";import{z as ke}from"zod";import{$ as ht}from"zx";var Im="feature",_m="release",hc=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:s,cmux:n}=e,i=e.ide??e.cursor;await te({operation:"create worktrees"});try{let a=await ne("release"),c=await x(),p=`${c}${ie}`;await gc(`${p}/${_m}`),await gc(`${p}/${Im}`);let u=[];if(o)u=o.split(",").map($=>oe(X($.trim())));else{let $=await O(),Z=$.map(E=>E.branch);if(Z.length===0)return l.info("\u2139\uFE0F No open release branches found"),g.print(),{content:w(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)u=Z;else{g.setInteractive();let E=new Map($.map(Re=>[Re.branch,_(Re.title)])),be=await M();u=await Tr(W({branches:Z,descriptions:be,types:E}),{required:!0})}}t?g.addOption("--all",!0):g.addOption("--versions",ot(u)),await B(r,"Are you sure you want to proceed with these worktree changes?"),r||g.addOption("--yes",!0);let d=await T(),f=i??(se(d).length>0?"workspace":"none");g.addOption("--ide",f);let v=s??d.worktrees?.openInGithubDesktop??await C($=>fc({message:"Open created worktrees in GitHub Desktop?"},$));typeof s>"u"&&d.worktrees?.openInGithubDesktop===void 0&&g.setInteractive(),v?g.addOption("--github-desktop",!0):g.addOption("--no-github-desktop",!0);let m=n??d.worktrees?.openInCmux??await C($=>fc({message:"Open created worktrees in cmux?"},$));typeof n>"u"&&d.worktrees?.openInCmux===void 0&&g.setInteractive(),m?g.addOption("--cmux",!0):g.addOption("--no-cmux",!0);let{branchesToCreate:y}=Om({selectedReleaseBranches:u,currentWorktrees:a}),R=await Nm(y,p);if(Dm(R),f==="workspace"&&await zn({projectRoot:c,worktreeDir:p,branches:R}),v)for(let $ of R)await ht`github ${p}/${$}`,await ht`sleep 5`;if(m){let $=Am.basename(await Pe(c)),Z=await ar(),E=await At($),be=!1;for(let Re of R){let Ee=`${p}/${Re}`;if(Z.has(await Nr(Ee)))continue;let Ir=_t({branch:Re});try{if(E)await lr({cwd:Ee,title:Ir,group:E});else{let xe=await lr({cwd:Ee,title:Ir});be||(E=await It($,[xe]),be=!0)}}catch(xe){l.warn({error:xe,branch:Re},`\u26A0\uFE0F Failed to open cmux workspace for ${Re}`)}}}g.print();let S={createdWorktrees:R,count:R.length};return{content:w(JSON.stringify(S,null,2)),structuredContent:S}}catch(a){throw pr(a)?a:(l.error({error:a},"\u274C Error managing worktrees"),new h(a,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},gc=async e=>{await ht`mkdir -p ${e}`},Om=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(n=>Me(n));return{branchesToCreate:r.filter(n=>!o.includes(n))}},Nm=async(e,r)=>{let t=await Promise.allSettled(e.map(async s=>{let n=`${r}/${s}`;return await ht`git worktree add ${n} ${s}`,await ht({cwd:n})`pnpm install`,s})),o=[];for(let[s,n]of t.entries())if(n.status==="fulfilled")o.push(n.value);else{let i=e[s],a=new h(n.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});l.error({error:n.reason,msg:a.message})}return o},Dm=e=>{if(e.length>0){l.info("\u2705 Created git worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No new git worktrees to create")},us=k({name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:ke.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:ke.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:ke.enum(io).optional().describe('Editor open mode for created worktrees, applied to all configured editors (Cursor and/or Zed, per the "ide" config). "workspace" (the only attach style) adds each worktree to every configured editor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when at least one "ide" is configured \u2192 "none" otherwise.'),cursor:ke.enum(io).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:ke.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).'),cmux:ke.boolean().optional().describe('Open each created worktree in a new cmux workspace, all rooted at the worktree directory. Pane layout follows "worktrees.cmux.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInCmux" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).')},outputSchema:{createdWorktrees:ke.array(ke.string()).describe("List of created git worktree branches"),count:ke.number().describe("Number of git worktrees created")},handler:hc});import{z as Ar}from"zod";var vc=async()=>{await T();let e=await ne("release");if(e.length===0)return l.info("\u2139\uFE0F No active worktrees found"),{content:w(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([O(),M()]),o=new Map(r.map(c=>[c.branch,_(c.title)])),s=e.flatMap(c=>{let p=N(c);if(!p)return[];let u=D(p),d=o.get(c)||"regular",f=t.get(G(p))||null;return[{version:u,type:d,description:f}]}),n=Math.max(...s.map(c=>c.version.length)),i=s.map(c=>{let p=rt(c.version,c.type,n);return c.description?`${p} ${c.description}`:p});l.info(`\u{1F33F} Active worktrees:
244
+
245
+ ${i.join(`
246
+ `)}`);let a={worktrees:s,count:s.length};return{content:w(JSON.stringify(a,null,2)),structuredContent:a}},ms=k({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:Ar.array(Ar.object({version:Ar.string().describe("Release version"),type:Ar.enum(["regular","hotfix"]).describe("Release type"),description:Ar.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Ar.number().describe("Number of worktrees")},handler:vc});import{z as vt}from"zod";var Mm=e=>{if(er()){if(e.all)throw new h(void 0,{operation:"remove worktrees",remediation:'name targets explicitly via "versions"; bulk all=true removal is disabled over MCP',stderrExcerpt:"all=true is not permitted for worktrees-remove over MCP"});if(!e.versions)throw new h(void 0,{operation:"remove worktrees",remediation:'pass "versions" (comma-separated release versions/names); the interactive picker needs a TTY',stderrExcerpt:'worktrees-remove over MCP requires "versions"'})}},jm=(e,r)=>{let t=e.filter(o=>!r.includes(o));if(t.length>0)throw new h(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${t.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${t.join(", ")}`})},yc=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await te({operation:"remove worktrees"}),await T(),Mm({all:t,versions:o});try{let s=await ne("release");if(s.length===0)return l.info("\u2139\uFE0F No active worktrees to remove"),g.print(),{content:w(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let n=await x(),i=`${n}${ie}`,a=[];if(t)a=s;else if(o)a=o.split(",").map(d=>oe(X(d.trim())));else{g.setInteractive();let[d,f]=await Promise.all([M(),O()]),v=new Map(f.map(m=>[m.branch,_(m.title)]));a=await Tr(W({branches:s,descriptions:d,types:v}),{required:!0})}jm(a,s);let c=a.length===s.length;c?g.addOption("--all",!0):g.addOption("--versions",ot(a)),await B(r,"Are you sure you want to proceed with these worktree changes?"),r||g.addOption("--yes",!0);let p=await at({branches:a,worktreeDir:i,pruneFolder:c});await ft({projectRoot:n,worktreeDir:i,currentWorktrees:s,removedWorktrees:p,allowEditorRelaunch:!r}),Fm(p),g.print();let u={removedWorktrees:p,count:p.length};return{content:w(JSON.stringify(u,null,2)),structuredContent:u}}catch(s){throw pr(s)||s instanceof h?s:(l.error({error:s},"\u274C Error managing worktrees"),new h(s,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Fm=e=>{if(e.length>0){l.info("\u274C Removed worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No unused worktrees to remove")},fs=k({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named version must be an active worktree, or the call errors without removing anything. What survives: the release branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune".',requiresHumanConfirm:!0,inputSchema:{versions:vt.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:vt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:vt.array(vt.string()).describe("List of removed git worktree branches"),count:vt.number().describe("Number of git worktrees removed")},handler:yc});import{z as gs}from"zod";import{$ as Lm}from"zx";var wc=async e=>{let{confirmedCommand:r}=e;await te({operation:"sync worktrees"}),await T();try{let t=await ne("release"),o=await x(),s=`${o}${ie}`,n=await qt();await B(r,"Are you sure you want to proceed with these worktree changes?"),r||g.addOption("--yes",!0);let{branchesToRemove:i}=Wm({releasePRsList:n,currentWorktrees:t}),a=await Vm({branches:i,worktreeDir:s});await ft({projectRoot:o,worktreeDir:s,currentWorktrees:t,removedWorktrees:a,allowEditorRelaunch:!1}),Bm(a),g.print();let c={removedWorktrees:a,count:a.length};return{content:w(JSON.stringify(c,null,2)),structuredContent:c}}catch(t){throw pr(t)?t:(l.error({error:t},"\u274C Error managing worktrees"),new h(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},Wm=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>Me(n)).filter(n=>!r.includes(n))}},Vm=async e=>{let{branches:r,worktreeDir:t}=e,o=[];for(let s of r)try{let n=`${t}/${s}`;await cr(n),await Lm`git worktree remove ${n}`,o.push(s)}catch(n){let i=new h(n,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});l.error({error:n,branch:s,msg:i.message})}return o},Bm=e=>{if(e.length>0){l.info("\u274C Removed worktrees:");for(let r of e)l.info(r);l.info("")}else l.info("\u2139\uFE0F No unused worktrees to remove")},hs=k({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.",inputSchema:{},outputSchema:{removedWorktrees:gs.array(gs.string()).describe("List of removed worktree branches"),count:gs.number().describe("Number of worktrees removed during sync")},handler:wc});var Jm=[{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"}],ao=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Co,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:dn,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:vn,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Wn,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:Vn,mcpExposed:!0,mutating:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:fn,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:hn,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:un,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"local-deploy-all",menuGroup:"release",mcpTool:Tn,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:"release",mcpTool:Sn,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:us,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:ms,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"reopen",menuGroup:"worktrees",mcpTool:Xn,mcpExposed:!0,mutating:!1,groupPath:["reopen"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:fs,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:hs,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Qo,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Xo,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:jo,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Zo,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:rn,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Po,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:ps,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"init",menuGroup:"setup",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["init"]},{cliName:"doctor",menuGroup:"setup",mcpTool:zo,mcpExposed:!1,mutating:!0,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:xo,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:ds,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-autoload"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]},{cliName:"self-update",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["self-update"]},{cliName:"mcp",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["mcp"]}];var Km=()=>ao.flatMap(e=>e.mcpExposed&&e.mcpTool?[e.mcpTool]:[]),Gm=e=>ao.filter(r=>r.menuGroup===e),Um=e=>ao.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import vs from"node:process";var zm="MODULE_TYPELESS_PACKAGE_JSON",qm=(e,r)=>typeof e=="object"&&e!==null?e.code:r,kc=!1,Hm=()=>{if(kc)return;kc=!0;let e=vs.emitWarning.bind(vs);vs.emitWarning=((r,...t)=>{qm(t[0],t[1])!==zm&&e(r,...t)})};export{w as a,Xs as b,Qs as c,So as d,ri as e,Wr as f,Vr as g,We as h,Vg as i,ll as j,yi as k,wi as l,vr as m,ki as n,bi as o,Wt as p,Vt as q,Fl as r,Jo as s,Iv as t,_v as u,ty as v,Ko as w,Go as x,Gi as y,qp as z,Zi as A,ea as B,ra as C,en as D,sa as E,Yt as F,ld as G,da as H,_k as I,Ra as J,Sa as K,Ca as L,$a as M,Aa as N,Va as O,Ba as P,xu as Q,Za as R,Qa as S,io as T,nm as U,uc as V,mc as W,hc as X,vc as Y,yc as Z,wc as _,Jm as $,ao as aa,Km as ba,Gm as ca,Um as da,Hm as ea};
247
+ //# sourceMappingURL=chunk-KATIE633.js.map