infra-kit 0.7.9 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/chunk-5XK34MWH.js +442 -0
  2. package/dist/chunk-5XK34MWH.js.map +7 -0
  3. package/dist/{chunk-LDF2KOGN.js → chunk-6OFUVD7F.js} +2 -2
  4. package/dist/chunk-75URROMU.js +4 -0
  5. package/dist/chunk-75URROMU.js.map +7 -0
  6. package/dist/{chunk-DFZ5WUIM.js → chunk-AEVL5XWO.js} +2 -2
  7. package/dist/{chunk-DFZ5WUIM.js.map → chunk-AEVL5XWO.js.map} +1 -1
  8. package/dist/{chunk-KXQQUBGV.js → chunk-AOWMCNYY.js} +2 -2
  9. package/dist/chunk-BVEVERTB.js +7 -0
  10. package/dist/chunk-BVEVERTB.js.map +7 -0
  11. package/dist/chunk-GCX3HDDL.js +9 -0
  12. package/dist/chunk-GCX3HDDL.js.map +7 -0
  13. package/dist/cli.js +13 -13
  14. package/dist/cli.js.map +4 -4
  15. package/dist/dev-server.js +2 -2
  16. package/dist/dev-server.js.map +1 -1
  17. package/dist/dev-wizard-run-RPZOX53B.js +2 -0
  18. package/dist/{dev-wizard-run-MCUYV6IN.js.map → dev-wizard-run-RPZOX53B.js.map} +1 -1
  19. package/dist/mcp-proxy.js +1 -1
  20. package/dist/mcp.js +2 -2
  21. package/dist/mcp.js.map +4 -4
  22. package/dist/update-check.js +1 -1
  23. package/package.json +3 -3
  24. package/readme.md +1 -0
  25. package/dist/chunk-63VNUKUS.js +0 -8
  26. package/dist/chunk-63VNUKUS.js.map +0 -7
  27. package/dist/chunk-MFNMFVI6.js +0 -443
  28. package/dist/chunk-MFNMFVI6.js.map +0 -7
  29. package/dist/chunk-NFIFWIO6.js +0 -4
  30. package/dist/chunk-NFIFWIO6.js.map +0 -7
  31. package/dist/chunk-YKCY657C.js +0 -7
  32. package/dist/chunk-YKCY657C.js.map +0 -7
  33. package/dist/dev-wizard-run-MCUYV6IN.js +0 -2
  34. /package/dist/{chunk-LDF2KOGN.js.map → chunk-6OFUVD7F.js.map} +0 -0
  35. /package/dist/{chunk-KXQQUBGV.js.map → chunk-AOWMCNYY.js.map} +0 -0
@@ -0,0 +1,442 @@
1
+ import{a as Sn,c as be,d as b,e as oo,f as ne,i as h,j as Tn,k as N,m as A,n as Cn,o as Y}from"./chunk-BVEVERTB.js";import{a as Tl,d as Cl,f as Tr,g as nr,h as An,i as In,j as $n,n as pt,o as _n,p as je}from"./chunk-AOWMCNYY.js";import{A as fl,B as gl,C as hl,D as kn,E as bn,F as ro,G as Is,H as Rn,I as vl,J as yl,K as $s,L as _s,M as wl,P as l,Q as or,R as bl,S as Ns,T as Ce,V as ee,W as x,X as Rl,Y as lt,_ as El,aa as Pl,d as _,e as z,f as ue,g as ll,h as yn,ha as xl,i as g,j as pl,k as wn,ka as Sl,l as j,m as ke,n as Se,o as dl,p as As,q as G,r as W,s as xr,t as ul,u as rr,v as me,w as R,x as Te,y as ct,z as ml}from"./chunk-GCX3HDDL.js";import{a as qc,b as Yc,c as Ss,d as Zc,e as Xc,f as Qc,g as el,h as eo,i as rl,j as tl,k as ol,l as nl,m as sl,n as Ts,o as il,p as Cs,q as vn,r as Pr,s as al,t as cl}from"./chunk-6OFUVD7F.js";import{a as B,b as F,c as tr,d as En,e as Ds,f as Pn,g as Os,h as to,i as Sr,j as xn,k as kl,l as q,m as no,n as so,o as Ms,p as js,r as Fs}from"./chunk-AEVL5XWO.js";import{b as Qt,c as gn,d as xs,e as Uc,f as hn,g as Kc,i as Hc,m as de,o as zc}from"./chunk-HHWP3YXW.js";import{a as pe,b as dn,c as Xt,d as kr,e as Bc,f as un,g as ot,h as nt,i as mn,j as st,k as br,l as it,m as fn,q as at,r as Gc,s as Rr,t as Er,u as oe}from"./chunk-75URROMU.js";import{spawn as jm}from"node:child_process";import Il from"node:fs";import dt from"node:process";import{fileURLToPath as $l}from"node:url";var Al=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Nm=new Set(["mcp"]),Mm=e=>e[2]!=null&&Nm.has(e[2]),Ls=e=>{let{argv:r,env:t,isTty:o,selfRealPath:n,cwd:s,realpath:i}=e;return Al.some(c=>{let p=t[c];return p!=null&&p!==""})?"opt-out":r.includes("--json")?"json":Mm(r)?"own-command":o?Hc(n,s,i)?"local-install":null:"not-a-tty"};var Fm=e=>{jm(dt.execPath,[e,"--parent-pid",String(dt.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},Lm=()=>$l(new URL("./update-check.js",import.meta.url)),Wm=()=>Il.realpathSync($l(new URL("./cli.js",import.meta.url))),Jm=/^[\w@./+ -]+$/i,Vm=e=>Jm.test(e),Bm=(e,r,t)=>{!e?.latestVersion||!e.updateCommand||no(e.latestVersion,r)&&e.updateCommand.every(Vm)&&t(`infra-kit ${e.latestVersion} is available (you have ${r}). Run: ${hn(e.updateCommand)}`)},Gm=(e,r={})=>{try{let t=r.argv??dt.argv,o=r.env??dt.env,n=r.isTty??!!dt.stdout.isTTY,s=r.cwd??dt.cwd(),i=r.nowMs??Date.now(),a=r.selfRealPath??Wm(),c=r.readCache??so,p=r.spawnChild??Fm,d=r.fileExists??(f=>Il.existsSync(f)),u=r.notify??(f=>{l.info(f)});if(Ls({argv:t,env:o,isTty:n,selfRealPath:a,cwd:s,realpath:de})!==null)return;let m=c();if(Bm(m,e,u),!Ms(m,i))return;let v=r.childPath??Lm();if(!d(v))return;p(v)}catch{}};import pp from"node:process";import{z as ge}from"zod";import jl from"node:fs";import mt from"node:path";import{packageConfigSchema as Zm}from"@slip-stream-kit/config/internal";import Dl from"node:fs/promises";import Bs from"node:path";import{pathToFileURL as Xm}from"node:url";import{z as Qm}from"zod";import _l from"node:path";var io=["frontend","backend","lib","e2e","mobile"],Um={ui:"frontend",api:"backend",tests:"e2e"},Km="mobile-app",Hm=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],zm=(e,r)=>{let t=_l.relative(r,e).split(_l.sep).filter(s=>s!==""&&s!=="."),[o,,n]=t;if(t.length===3&&o==="apps"&&n!==void 0){let s=Um[n];if(s)return s}return t.at(-1)===Km?"mobile":null},qm=e=>{let r=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let o of Hm)if(o.packages.some(n=>r.has(n)))return o.type;return r.has("vite")&&r.has("react")&&!!e.scripts?.dev?"frontend":null},Ws=({packageDir:e,repoRoot:r,pkgJson:t,declaredType:o})=>o??zm(e,r)??qm(t)??"lib";var sr={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Js={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"]},Vs=(e,r=sr)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import Ym from"node:fs/promises";var Ae=async e=>{try{return await Ym.access(e),!0}catch{return!1}};var Fe="infra-kit.config.ts",ao=async e=>{try{let r=await Dl.readFile(Bs.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},Ol=async e=>{let r=await Dl.stat(e),n=(await import(`${Xm(e).href}?mtime=${Number(r.mtimeMs)}`)).default;if(n===void 0)throw new Error(`${Fe} at ${e} has no default export`);return typeof n=="function"?await n():n},co=async e=>{let r=Bs.join(e,Fe);if(await Ae(r))try{let o=(await Ol(r))?.type;return io.find(n=>n===o)}catch{return}},lo=async(e,r=sr)=>{let t=Bs.join(e,Fe);if(!await Ae(t))throw new Error(`${Fe} not found at ${t}`);let o=await Ol(t),n=Zm.safeParse(o);if(!n.success)throw new Error(`Invalid ${Fe} at ${t}: ${Qm.prettifyError(n.error)}`);return Vs(n.data,r)};import Nl from"node:fs/promises";import Dn from"node:path";import ef from"yaml";var rf="pnpm-workspace.yaml",tf=async e=>(await Nl.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Dn.join(e,t.name)),of=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await tf(o));continue}let n=Dn.join(o,r);await Ae(n)&&t.push(n)}return t},nf=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await of(t,o);return t},ie=async e=>{let r=await Nl.readFile(Dn.join(e,rf),"utf-8"),o=((ef.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await nf(e,s);for(let a of i)await Ae(Dn.join(a,"package.json"))&&n.add(a)}return[...n].sort()};import po from"node:path";var uo=async e=>{let r=po.resolve(e);for(;r!==po.dirname(r);){if(await Ae(po.join(r,"package.json")))return r;r=po.dirname(r)}if(await Ae(po.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e} \u2014 cd into a package directory, or pass --root to audit a monorepo root`)};var Ie=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},ir=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);if(o===-1||n===-1||n<o)return null;let s=e.slice(0,o).replace(/\n+$/,""),i=e.slice(n+t.length).replace(/^\n+/,"");return s+(i?`
2
+ ${i}`:"")},Gs=(e,r)=>{let t=e.indexOf(r);if(t===-1)return null;let n=e.slice(t+r.length).match(/^([^\s>]+)/);return n?n[1]:null},Ml=(e,r,t)=>`${e}
3
+ ${r}
4
+ ${t}`,ut=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=Ml(t,r,o),i=Ie(e,t,o);if(n==="replace-in-place"&&i){let p=e.indexOf(t),d=e.indexOf(o)+o.length;return e.slice(0,p)+s+e.slice(d)}let c=(i?ir(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
+ ${s}
6
+ `:`${s}
7
+ `};var fe="<!-- infra-kit:begin -->",$e="<!-- infra-kit:end -->",Us="<!-- infra-kit:version ",_e="<!-- infra-kit:package:begin -->",Le="<!-- infra-kit:package:end -->",Cr="<!-- infra-kit:package:version ";var sf=e=>{let r=e.indexOf(_e)+_e.length;return e.slice(r,e.indexOf(Le))},af=e=>{let r=e.indexOf(Cr);if(r===-1)return null;let t=e.slice(r+Cr.length).match(/^\S+\s+([^\s>]+)/)?.[1];return io.find(o=>o===t)??null},Ar=e=>{if(e===null)return{state:"missing"};if(!Ie(e,_e,Le))return e.includes(_e)||e.includes(Le)?{state:"malformed"}:Ie(e,fe,$e)?{state:"foreign-block"}:{state:"no-block"};let r=sf(e);if(r.trim()==="")return{state:"malformed"};let t={state:"ok"},o=Gs(r,Cr),n=af(r);return o!==null&&(t.version=o),n!==null&&(t.type=n),t};import cf from"node:fs";var Ir=e=>{try{return cf.readFileSync(e,"utf-8")}catch{return null}};var Fl="pnpm-workspace.yaml",lf="CLAUDE.md",Hs=e=>{let r=mt.resolve(e);for(;r!==mt.dirname(r);){if(jl.existsSync(mt.join(r,Fl)))return r;r=mt.dirname(r)}return jl.existsSync(mt.join(r,Fl))?r:null},Ks=new Map,On=()=>{Ks.clear()},pf=async e=>{let r;try{r=await ie(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let t of r){let o=mt.join(t,lf),n=Ir(o);if(n!==null&&Ar(n).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:o}}return{adopted:!1,workspaceRoot:e}},ft=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let r=Ks.get(e);if(r)return r;let t=await pf(e);return Ks.set(e,t),t};import yt from"node:fs";import $r from"node:path";var Ll=`---
8
+ name: TODO
9
+ description: TODO \u2014 one sentence describing the product surface this package renders.
10
+ colors:
11
+ primary: '#2563eb'
12
+ secondary: '#64748b'
13
+ background: '#ffffff'
14
+ surface: '#f8fafc'
15
+ text: '#0f172a'
16
+ muted: '#64748b'
17
+ border: '#e2e8f0'
18
+ success: '#16a34a'
19
+ warning: '#d97706'
20
+ danger: '#dc2626'
21
+ typography:
22
+ fontFamily: TODO \u2014 the UI typeface stack.
23
+ scale: [12, 14, 16, 20, 24, 32, 40]
24
+ weights: [400, 500, 600, 700]
25
+ rounded: 8px
26
+ spacing: [4, 8, 12, 16, 24, 32, 48]
27
+ components:
28
+ - button
29
+ - input
30
+ - card
31
+ - dialog
32
+ ---
33
+
34
+ # Design \u2014 {{packageName}}
35
+
36
+ Replace every TODO below with the real design language. This file is the source of truth
37
+ for UI decisions in this package; agents are instructed to read it before styling anything.
38
+
39
+ ## Overview
40
+
41
+ TODO \u2014 what this product is, who uses it, and the feeling the interface should convey.
42
+
43
+ ## Colors
44
+
45
+ TODO \u2014 what each token in the front matter means and when to reach for it. Name the
46
+ contrast pairs that are guaranteed accessible.
47
+
48
+ ## Typography
49
+
50
+ TODO \u2014 the typeface, the scale, and which size and weight each role uses
51
+ (page title, section title, body, caption, label).
52
+
53
+ ## Layout
54
+
55
+ TODO \u2014 the grid, the page gutters, the maximum content width, and the breakpoints.
56
+
57
+ ## Elevation & Depth
58
+
59
+ TODO \u2014 the shadow levels and what sits at each one (base, raised, overlay, modal).
60
+
61
+ ## Shapes
62
+
63
+ TODO \u2014 corner radii per component size, border widths, and where a shape is square by intent.
64
+
65
+ ## Components
66
+
67
+ TODO \u2014 for each component in the front matter list: its variants, its states
68
+ (default, hover, active, focus, disabled, loading), and its sizes.
69
+
70
+ ## Do's and Don'ts
71
+
72
+ - Do TODO.
73
+ - Do TODO.
74
+ - Don't TODO.
75
+ - Don't TODO.
76
+ `;var Wl=`# {{packageName}}
77
+
78
+ Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
79
+ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
80
+
81
+ ## Read first
82
+
83
+ - {{readmeBullet}}
84
+ - \`infra-kit.config.ts\` \u2014 the audit rules this package must satisfy.
85
+
86
+ ## Checks
87
+
88
+ - \`infra-kit audit\` \u2014 validate this package against its infra-kit rules.
89
+ - \`pnpm run ts-check && pnpm run eslint-check && pnpm run test\` \u2014 this package only.
90
+ - \`pnpm run qa\` at the repo root \u2014 the full gate; run it before claiming completion.
91
+
92
+ ## Rules
93
+
94
+ - Module-scope state belongs in the handler entry file \u2014 that is the file which re-evaluates on reload.
95
+ - Env vars come from Doppler via \`ik env-load\`; never commit a secret.
96
+ - The route prefix this service answers is declared in the consuming UI's \`dev.proxy\`, so changing a path is a two-package change.
97
+ `;var Jl=`# {{packageName}}
98
+
99
+ Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
100
+ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
101
+
102
+ ## Read first
103
+
104
+ - {{readmeBullet}}
105
+ - \`infra-kit.config.ts\` \u2014 the audit rules this package must satisfy.
106
+
107
+ ## Checks
108
+
109
+ - \`infra-kit audit\` \u2014 validate this package against its infra-kit rules.
110
+ - \`pnpm run ts-check && pnpm run eslint-check && pnpm run test\` \u2014 this package only.
111
+ - \`pnpm run qa\` at the repo root \u2014 the full gate; run it before claiming completion.
112
+
113
+ ## Rules
114
+
115
+ - Specs run on Playwright.
116
+ - Every spec cleans up what it creates, in teardown.
117
+ - Selectors live in Page Objects, never inline in specs.
118
+ - Never point a run at a production environment.
119
+ `;var Vl="# {{packageName}}\n\nWorkspace package at `{{relDir}}` \u2014 type: **{{type}}**.\nThis block is generated by `infra-kit audit --fix` \u2014 edit text _outside_ the markers, never inside.\n\n## Read first\n\n- {{readmeBullet}}\n- `DESIGN.md` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.\n- `infra-kit.config.ts` \u2014 the audit rules this package must satisfy.\n\n## Checks\n\n- `infra-kit audit` \u2014 validate this package against its infra-kit rules.\n- `pnpm run ts-check && pnpm run eslint-check && pnpm run test` \u2014 this package only.\n- `pnpm run qa` at the repo root \u2014 the full gate; run it before claiming completion.\n\n## Rules\n\n- Start the app with `infra-kit dev`, never a bare `vite` \u2014 dev URLs are proxied and port-free.\n- Backend calls go through the path prefixes declared in `dev.proxy` in `infra-kit.config.ts`. Never hardcode an API base URL or a port.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var Bl=`# {{packageName}}
120
+
121
+ Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
122
+ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
123
+
124
+ ## Read first
125
+
126
+ - {{readmeBullet}}
127
+ - \`infra-kit.config.ts\` \u2014 the audit rules this package must satisfy.
128
+
129
+ ## Checks
130
+
131
+ - \`infra-kit audit\` \u2014 validate this package against its infra-kit rules.
132
+ - \`pnpm run ts-check && pnpm run eslint-check && pnpm run test\` \u2014 this package only.
133
+ - \`pnpm run qa\` at the repo root \u2014 the full gate; run it before claiming completion.
134
+
135
+ ## Rules
136
+
137
+ - The public surface is the \`exports\` map in \`package.json\`.
138
+ - Changing that map is a breaking change for every dependent package.
139
+ - Run \`pnpm run build\` before a dependent package can see a change.
140
+ - No app-specific logic belongs here.
141
+ `;var Gl=`# {{packageName}}
142
+
143
+ Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
144
+ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
145
+
146
+ ## Read first
147
+
148
+ - {{readmeBullet}}
149
+ - \`DESIGN.md\` \u2014 the visual language (colors, typography, spacing, components). It is the source of truth for UI decisions; if it is absent, ask before inventing one.
150
+ - \`infra-kit.config.ts\` \u2014 the audit rules this package must satisfy.
151
+
152
+ ## Checks
153
+
154
+ - \`infra-kit audit\` \u2014 validate this package against its infra-kit rules.
155
+ - \`pnpm run ts-check && pnpm run eslint-check && pnpm run test\` \u2014 this package only.
156
+ - \`pnpm run qa\` at the repo root \u2014 the full gate; run it before claiming completion.
157
+
158
+ ## Rules
159
+
160
+ - The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
161
+ - The web build feeds the native shell, so a device run needs a rebuild first.
162
+ - Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
163
+ `;var Ul="# infra-kit\n\nThis repository uses the **infra-kit** CLI for environment, worktree, and release workflows.\nThis block is generated by `ik audit --fix --root` \u2014 edit text _outside_ the markers, never inside.\n\n## Commands (`ik` = `pnpm exec infra-kit`)\n\n- `ik env-load -c <config>` / `ik env-clear` / `ik env-status` \u2014 load, clear, or inspect Doppler env vars for a config (e.g. `dev`). Source the returned file to apply.\n- `ik worktrees add` / `worktrees list` / `reopen` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees.\n- `ik release create` / `release remove` / `release list` / `release deploy-all` / `release deploy-selected` / `release deliver` / `release desc-edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch.\n- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.\n- `ik audit --fix` \u2014 regenerate this repo's infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, aws, gh, doppler, portless).\n\n## Conventions\n\n- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|desc-edit|merge-dev|deploy-all|deploy-selected`, `worktrees add|remove|sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host's prompt on the argv is the approval. `release deliver` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n";var gt={"root/body":Ul.trimEnd(),"package/frontend":Vl.trimEnd(),"package/backend":Wl.trimEnd(),"package/lib":Bl.trimEnd(),"package/e2e":Jl.trimEnd(),"package/mobile":Gl.trimEnd(),"design/skeleton":Ll.trimEnd()};var zs=/\{\{(\w+)\}\}/g,yf=/^- \{\{(\w+)\}\}$/,wf=e=>new Set([...e.matchAll(zs)].map(r=>r[1])),kf=(e,r)=>{let t=Object.keys(r).filter(o=>!e.has(o));if(t.length>0)throw new Error(`renderTemplate: variable(s) never used by the template: ${t.join(", ")}`)},bf=(e,r)=>{let t=[...e].filter(o=>!(o in r));if(t.length>0)throw new Error(`renderTemplate: placeholder(s) with no variable: ${t.map(o=>`{{${o}}}`).join(", ")}`)},Rf=(e,r)=>e.filter(t=>{let o=yf.exec(t);return o===null||r[o[1]]!==""}),Ef=(e,r)=>{for(let t of e)for(let o of t.matchAll(zs)){let n=r[o[1]];if(n!==void 0&&n.includes(`
164
+ `)&&o.index!==0)throw new Error(`renderTemplate: multi-line value for {{${o[1]}}} must start its line (found at column ${o.index})`)}},ht=(e,r)=>{let t=wf(e);bf(t,r),kf(t,r);let o=Rf(e.split(`
165
+ `),r);return Ef(o,r),o.join(`
166
+ `).replace(zs,(n,s)=>r[s])};var Pf="name: TODO",qs=e=>{let r=ht(gt["design/skeleton"],{packageName:e}),t=`name: ${e}`;return`${r.replace(Pf,()=>t)}
167
+ `};var xf=(e,r)=>`${Cr}${e} ${r} -->`,Sf="`README.md` \u2014 what this package is and how to run it.",Ys=e=>{let{version:r,type:t,packageName:o,relDir:n,hasReadme:s}=e,i=ht(gt[`package/${t}`],{packageName:o,relDir:n,type:t,readmeBullet:s?Sf:""});return[xf(r,t),"",i].join(`
168
+ `)};var Tf=e=>`${Us}${e} -->`,Zs=e=>{let r=ht(gt["root/body"],{});return[Tf(e),"",r].join(`
169
+ `)};import vt from"node:fs";import Cf from"node:path";var Nn=e=>{let r;try{r=vt.lstatSync(e)}catch{return}if(r.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},mo=(e,r)=>{Nn(e);let t=vt.existsSync(e)?vt.readFileSync(e,"utf-8"):null;return t===r?"unchanged":(vt.mkdirSync(Cf.dirname(e),{recursive:!0}),vt.writeFileSync(e,r,"utf-8"),t===null?"created":"updated")},Xs=(e,r,t)=>{let o=vt.readFileSync(e,"utf-8");if(!Ie(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Kl=(e,r,t)=>Ie(e,r,t)?{before:e.slice(0,e.indexOf(r)),after:e.slice(e.indexOf(t)+t.length)}:null,Qs=(e,r,t,o)=>{let n=Kl(e,t,o),s=Kl(r,t,o);if(!(n===null||s===null)&&(n.before!==s.before||n.after!==s.after))throw new Error("Post-write validation failed: content outside the managed markers changed")};var jn="<!-- infra-kit:import:begin -->",Fn="<!-- infra-kit:import:end -->",Af="AGENTS.md",Hl="CLAUDE.md",If="README.md",ei="DESIGN.md",$f=["frontend","mobile"],_f=e=>yt.existsSync(e)?yt.readFileSync(e,"utf-8"):null,ri=(e,r)=>{try{return yt.readdirSync(e).includes(r)}catch{return!1}},Mn=(e,r,t)=>{let o=r instanceof Error?r.message:String(r),n={path:e,action:"failed",message:o};return t&&(n.type=t),n},zl=({filePath:e,body:r,startMarker:t,endMarker:o,prepare:n})=>{let s=_f(e),i=s===null?"":n?.(s)??s,a=ut({content:i,body:r,startMarker:t,endMarker:o,placement:"replace-in-place"}),c=mo(e,a);return Xs(e,t,o),s!==null&&Qs(i,a,t,o),c},Df=e=>{if(!yt.existsSync(e))return"unchanged";Nn(e);let r=yt.readFileSync(e,"utf-8"),t=ir(r,fe,$e);return t===null?"unchanged":t.trim()===""?(yt.rmSync(e),"removed"):mo(e,t)},Of=(e,r)=>zl({filePath:e,body:Zs(r),startMarker:fe,endMarker:$e,prepare:t=>ir(t,jn,Fn)??t}),fo=async(e,{version:r})=>{let t=$r.join(e,Hl),o=$r.join(e,Af),n=[];try{n.push({path:t,action:Of(t,r)})}catch(s){n.push(Mn(t,s))}try{n.push({path:o,action:Df(o)})}catch(s){n.push(Mn(o,s))}return n},Nf=(e,r,t)=>{if(!$f.includes(t)||ri(e,ei))return null;let o=$r.join(e,ei);try{return{path:o,action:mo(o,qs(r)),type:t}}catch(n){return Mn(o,n,t)}},go=async(e,{repoRoot:r,version:t,design:o,declaredType:n})=>{let s=$r.join(e,Hl),i=await ao(e),a=i.name??$r.basename(e),c=Ws({packageDir:e,repoRoot:r,pkgJson:i,declaredType:n}),p=Ys({version:t,type:c,packageName:a,relDir:$r.relative(r,e).split($r.sep).join("/"),hasReadme:ri(e,If),hasDesign:ri(e,ei)}),d=[];try{d.push({path:s,action:zl({filePath:s,body:p,startMarker:_e,endMarker:Le}),type:c})}catch(u){d.push(Mn(s,u,c))}if(o){let u=Nf(e,a,c);u&&d.push(u)}return d};import Bf from"node:path";import ql from"node:path";var ti="agent-guidance",ho="CLAUDE.md",Mf="\u2014 run: infra-kit audit --fix",jf={missing:`${ho} missing`,"no-block":`${ho} has no infra-kit block (expected ${_e} \u2026 ${Le})`,malformed:`${ho} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${ho} carries the ROOT infra-kit block (${fe}); a package needs the package block`},Ff=e=>e.adopted?` (workspace adopted: ${ql.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",oi=(e,r)=>{let t=Ar(Ir(ql.join(e,ho)));if(t.state==="ok"){let s=t.version??"unknown",i=t.type??"unknown";return{name:ti,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let o=`${jf[t.state]} ${Mf}`,n=t.state==="missing"?`${o}${Ff(r)}`:o;return r.adopted?{name:ti,status:"fail",message:n}:{name:ti,status:"pass",message:`not yet adopted \u2014 ${n}`}};var ni=async(e,r=sr)=>{try{let t=await lo(e,r);return{check:{name:Fe,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:Fe,status:"fail",message:t.message},rules:null}}};import Lf from"node:fs/promises";import Wf from"node:path";var si=async(e,r)=>Promise.all(r.map(async t=>{let o=await Lf.stat(Wf.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 ii=(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 Jf from"node:fs/promises";import Vf from"node:path";var wt="turbo.json",ai=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await Jf.readFile(Vf.join(e,wt),"utf-8");t=JSON.parse(n)}catch(n){return[{name:wt,status:"fail",message:`cannot read/parse ${wt}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:wt,status:"fail",message:`no "tasks" object defined in ${wt}`}]:r.map(n=>{let s=n in o||`//#${n}`in o;return{name:`turbo:${n}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${n}" in ${wt}`}})};var Gf={adopted:!1,workspaceRoot:null},ci=async(e,r=sr,t={})=>{let o=await ao(e),n=o.name??Bf.basename(e),{check:s,rules:i}=await ni(e,r),a=[s];t.isRoot||a.push(oi(e,t.adoption??Gf)),i&&(a.push(...ii(o.scripts??{},i.requiredScripts)),a.push(...await si(e,i.requiredFiles)),a.push(...await ai(e,i.turboTasks)));let c=a.every(p=>p.status==="pass");return{packageDir:e,packageName:n,checks:a,passed:c}};var li=["plugin","marketplace","add",tr],pi=["plugin","install",F,"--scope","project"],Yl=(e,r)=>Sr({projectPath:e,home:r}).kind==="installed",di=e=>((e??"").split(`
170
+ `).find(t=>t.trim().length>0)??"").trim(),Uf=(e,r)=>{if(to(r))return null;l.debug({msg:`Running: ${En} ${li.join(" ")}`});let t=e({args:li});return t.ok?null:{step:"marketplace",error:di(t.output)}},Kf=(e,r)=>{l.debug({msg:`Running: ${En} ${Pn.join(" ")}`});let t=e({args:Pn,cwd:r});return t.ok?{status:"updated"}:{status:"update-failed",error:di(t.output)}},ui=e=>{let{projectRoot:r,home:t}=e,o=e.run??Os;if(!o({args:Ds}).ok)return{status:"claude-missing"};if(Yl(r,t))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Kf(o,r);let n=Uf(o,t);if(n!==null)return{status:"failed",...n};l.debug({msg:`Running: ${En} ${pi.join(" ")}`});let s=o({args:pi,cwd:r});return s.ok?Yl(r,t)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:di(s.output)}};import Hf from"node:fs";import zf from"node:path";var U=".mcp.json",Re="mcpServers",qf="infra-kit",Yf=["mcp"],mi=" ",_r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Zl=e=>{if(!_r(e))return!1;let{command:r,args:t}=e;return r===qf&&Array.isArray(t)&&t[0]===Yf[0]},Xl=e=>/\n([ \t]+)"/.exec(e)?.[1]??mi,fi=e=>{try{return{kind:"raw",raw:Hf.readFileSync(e,"utf-8")}}catch(r){return r.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:r}}},gi=e=>{try{return JSON.parse(e)}catch{return}},hi=e=>e instanceof Error?e.message:String(e),Dr=e=>{let r=fi(zf.join(e,U));if(r.kind==="absent")return{kind:"missing-file"};if(r.kind==="unreadable")return{kind:"unparseable"};let t=gi(r.raw);if(!_r(t)||!_r(t[Re]))return{kind:"unparseable"};let o=t[Re];if(B in o)return{kind:"stale"};let n=Object.keys(o).find(s=>Zl(o[s]));return n===void 0?{kind:"absent"}:{kind:"wrong-key",key:n}};import Ln from"node:fs";import Zf from"node:path";var We=`claude plugin install ${F} --scope project`,kt=`claude plugin update ${F} --scope project`,vi=`claude plugin marketplace add ${tr}`,ep=" ",rp=()=>({source:{source:"github",repo:tr}}),Xf=()=>({extraKnownMarketplaces:{[B]:rp()},enabledPlugins:{[F]:!0}}),tp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qf=e=>/\n([ \t]+)"/.exec(e)?.[1]??ep,Ql=(e,r,t,o)=>{let n=e[r];return n===void 0?(e[r]={[t]:o},`${r}.${t}`):!tp(n)||t in n?null:(n[t]=o,`${r}.${t}`)},eg=e=>[Ql(e,"extraKnownMarketplaces",B,rp()),Ql(e,"enabledPlugins",F,!0)].filter(t=>t!==null),rg=e=>{try{return Ln.readFileSync(e,"utf-8")}catch{return null}},tg=e=>(Ln.mkdirSync(Zf.dirname(e),{recursive:!0}),Ln.writeFileSync(e,`${JSON.stringify(Xf(),null,ep)}
171
+ `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${B}`,`enabledPlugins.${F}`]}),yi=e=>{let r=rg(e);if(r===null)return tg(e);let t;try{t=JSON.parse(r)}catch{t=void 0}if(!tp(t))return l.warn(`Could not parse ${e} \u2014 left it untouched. Add "${F}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=eg(t);if(o.length===0)return{status:"unchanged",path:e,added:[]};let n=Qf(r),s=r.endsWith(`
172
+ `)?`
173
+ `:"";return Ln.writeFileSync(e,`${JSON.stringify(t,null,n)}${s}`,"utf-8"),{status:"added",path:e,added:o}};var y=e=>[{type:"text",text:e}],w=e=>e;import og from"node:path";import ng from"node:process";var sg=["unchanged","created"],ig=["unchanged","created","updated","removed","failed"],op=async(e,r,t)=>{let o=await co(e);return go(e,{repoRoot:r,version:q.version,design:t,declaredType:o})},ag=async(e,r)=>{if(e.root)return fo(r,{version:q.version});if(e.all){let o=[];for(let n of await ie(r))o.push(...await op(n,r,e.design));return o}let t=await uo(e.cwd??ng.cwd());return op(t,r,e.design)},cg=e=>{let r=new Map;for(let o of e)r.set(o.action,(r.get(o.action)??0)+1);return`Agent guidance synced \u2014 ${ig.filter(o=>sg.includes(o)||(r.get(o)??0)>0).map(o=>`${r.get(o)??0} ${o}`).join(", ")} (infra-kit ${q.version})`},lg=(e,r)=>{for(let t of e){if(t.action==="unchanged")continue;let o=og.relative(r,t.path),n=t.type?` (${t.type})`:"",s=t.action==="failed"&&t.message?` \u2014 ${t.message}`:"";l.info(` ${t.action.padEnd(9)} ${o}${n}${s}`)}l.info(cg(e))},pg=e=>{let r={path:e.path,action:e.action};return e.type&&(r.type=e.type),r},np=async(e,r)=>{let t=await R();On();let o=await ft(r),n=await ag(e,t);lg(n,t),On();let s=await ft(r),i=!e.all&&!e.root;return{fixed:n.map(pg),adoptionFlipped:i&&!o.adopted&&s.adopted}};import ip from"node:fs";import ap from"node:path";var wi="ik-mcp",sp=(e,r)=>{let t=["--name",e];for(let o of r.env)t.push("--env",o);for(let o of r.unset)t.push("--unset",o);return t.push("--",r.command,...r.args),{type:"stdio",command:wi,args:t}};var Wn="run `infra-kit setup` (or `infra-kit audit --root --fix`)",dg=(e,r)=>Array.isArray(e)&&e.length===r.length&&e.every((t,o)=>t===r[o]),ki=e=>_r(e)&&e.command===wi,ug=(e,r)=>({...e??{},type:r.type,command:r.command,args:r.args}),mg=(e,r,t)=>{let o=[],n={...e},s=!1;for(let[i,a]of Object.entries(r)){let c=sp(i,a),p=e[i];if(p!==void 0&&!ki(p)){o.push({name:i,status:"conflict",message:`"${i}" is configured under mcp but .mcp.json already has a hand-written "${i}" server that is not ik-mcp \u2014 left it untouched. Remove that entry (or rename it) and ${Wn}, or drop mcp.${i} from infra-kit.json`});continue}if(ki(p)&&p.type===c.type&&dg(p.args,c.args)){o.push({name:i,status:"unchanged",message:""});continue}if(t){n[i]=ug(p,c),s=!0,o.push({name:i,status:"written",message:""});continue}o.push({name:i,status:"drifted",message:p===void 0?`"${i}" is configured under mcp in infra-kit.json but has no .mcp.json entry \u2014 the entry is generated from that config: ${Wn}`:`"${i}" in .mcp.json does not match its mcp.${i} config in infra-kit.json \u2014 infra-kit.json is the source and the .mcp.json entry is generated from it, so edit the config and regenerate: ${Wn}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(r,i)||!ki(a)||o.push({name:i,status:"stale",message:`"${i}" runs ik-mcp but there is no mcp.${i} in infra-kit.json \u2014 add it, or remove the entry: claude mcp remove ${i} --scope project`});return{entries:o,servers:n,changed:s}},fg=(e,r,t)=>{let o=t===null?mi:Xl(t),n=t===null||t.endsWith(`
174
+ `)?`
175
+ `:"";try{return ip.mkdirSync(ap.dirname(e),{recursive:!0}),ip.writeFileSync(e,`${JSON.stringify(r,null,o)}${n}`,"utf-8"),!0}catch(s){return l.warn(`Could not write ${e} (${hi(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Jn=({projectRoot:e,proxies:r,write:t})=>{let o=ap.join(e,U),n=fi(o);if(n.kind==="unreadable")return l.warn(`Could not read ${o} (${hi(n.error)}) \u2014 left it untouched.`),{status:"unreadable",path:o,entries:[],wrote:!1};let s=n.kind==="raw"?n.raw:null,i=s===null?{}:gi(s);if(!_r(i))return l.warn(`Could not parse ${o} \u2014 left it untouched. Fix the JSON, then ${Wn}.`),{status:"unparseable",path:o,entries:[],wrote:!1};let a=i[Re];if(a!==void 0&&!_r(a))return l.warn(`${o} has a "${Re}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:o,entries:[],wrote:!1};let c=mg(a??{},r,t);if(!c.changed)return{status:"ok",path:o,entries:c.entries,wrote:!1};let p=fg(o,{...i,[Re]:c.servers},s);return{status:p?"ok":"failed",path:o,entries:c.entries,wrote:p}};var cp=async(e,r)=>{let t;try{t=(await x()).mcp}catch{return null}if(!t||Object.keys(t).length===0)return null;let o=Jn({projectRoot:e,proxies:t,write:r});if(o.status!=="ok"&&o.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${o.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let n=o.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=n.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:n.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:n.length===0}};var gg=(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}))],lp=async e=>{let r=(await x()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=xl(r);if(t.length>0){let d=t.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let o=El(e),n=Pl(e),s={api:o.map(d=>d.name),ui:n.map(d=>d.name)},{ctx:i,loadErrors:a}=await Tl(e,r,s,o),c=gg(Sl(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 hg="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",vg=async e=>e.root?[{dir:await R(),baseline:Js,isRoot:!0}]:e.all?(await ie(await R())).map(t=>({dir:t})):[{dir:await uo(e.cwd??pp.cwd())}],yg=async e=>e.root||e.all?await R():e.cwd??pp.cwd(),wg=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),n=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${n(r,"check")}, ${n(e.length,"target")}`;return l.info(o?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${t}/${s}`),o},kg=async(e,r)=>{let{fixed:t,adoptionFlipped:o}=await np(e,r);return o&&l.info(hg),t},bg=e=>{if(Dr(e).kind!=="stale")return null;let r=`${U} still registers "${B}" \u2014 the plugin no longer serves an MCP server, so this entry only spawns a compatibility stub (\`infra-kit mcp\`). Delete the "${B}" entry by hand in a PR, keeping its siblings`;return l.info(`[INFO] mcp mcp:legacy-key: ${r}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:r}],passed:!0}},dp=async(e={})=>{let r=Hs(await yg(e)),t=e.fix?await kg(e,r):void 0,o=await vg(e),n=await ft(r),s=[];for(let c of o)s.push(await ci(c.dir,c.baseline,{adoption:n,isRoot:c.isRoot}));if(e.root){let c=await lp(o[0].dir);c&&s.push(c);let p=await cp(o[0].dir,e.fix===!0);p&&s.push(p);let d=bg(o[0].dir);d&&s.push(d)}let a={allPassed:wg(s),packages:s.map(c=>({name:c.packageName,passed:c.passed,checks:c.checks}))};return t&&(a.fixed=t),{content:y(JSON.stringify(a,null,2)),structuredContent:a}},Rg={all:ge.boolean().optional().describe("Audit every non-vendor workspace package"),root:ge.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Eg={allPassed:ge.boolean().describe("Whether every audited package passed all checks"),packages:ge.array(ge.object({name:ge.string(),passed:ge.boolean(),checks:ge.array(ge.object({name:ge.string(),status:ge.enum(["pass","fail"]),message:ge.string()}))})).describe("Per-package check results")},bi=w({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:Rg,outputSchema:Eg,handler:e=>dp({all:e.all,root:e.root})});import{z as vo}from"zod";var up=async()=>{let[e,r]=await Promise.all([x(),ee()]),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:y(JSON.stringify(o,null,2)),structuredContent:o}},Pg={config:vo.record(vo.string(),vo.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:vo.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:vo.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Ri=w({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{},outputSchema:Pg,handler:()=>up()});import Ig from"node:fs";import{z as Z}from"zod";import yo from"node:fs";import bt from"node:path";import xg from"node:process";var Sg=bt.join(".infra-kit","dev-context"),Tg=".infra-kit",mp=(e,r)=>{let t=bt.resolve(e);for(;;){let o=bt.join(t,r);if(yo.existsSync(o))return o;let n=bt.dirname(t);if(n===t)return;t=n}},Cg=e=>{let r=mp(e,Sg);if(r)return r;let t=mp(e,Tg);return t?bt.join(t,"dev-context"):void 0},Ei=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Vn=e=>typeof e=="string"?e:"",Ag=(e,r,t)=>{let o=bt.join(e,r);try{let n=yo.statSync(o),s=JSON.parse(yo.readFileSync(o,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:r.replace(/\.json$/,""),package:Vn(i.package),port:Ei(i.port),alias:Vn(i.alias),origin:Vn(i.origin),release:Vn(i.release),pid:Ei(i.pid),writtenAt:Ei(i.writtenAt),mtimeMs:Math.round(n.mtimeMs),ageMs:Math.max(0,Math.round(t-n.mtimeMs))}}catch{return null}},Pi=(e=xg.cwd())=>{let r=Date.now(),t=Cg(e);if(!t||!yo.existsSync(t))return{session:"none",fragmentDir:t,readAt:r,apps:[]};let o;try{o=yo.readdirSync(t).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:t,readAt:r,apps:[]}}let n=o.map(s=>Ag(t,s,r)).filter(s=>s!==null).sort((s,i)=>s.app.localeCompare(i.app));return{session:n.length>0?"active":"none",fragmentDir:t,readAt:r,apps:n}};var fp=async(e={})=>{let r=e.now??Date.now,t=e.isListening??eo,o=Pi(e.cwd),n=r(),s=await Promise.all(o.apps.map(async u=>{let m=Math.max(0,Math.round((n-u.mtimeMs)/1e3)),v=await t(u.port);return{app:u.app,package:u.package,port:u.port,pid:u.pid,alias:u.alias,origin:u.origin,release:u.release,writtenAt:u.writtenAt>0?new Date(u.writtenAt).toISOString():null,fragmentMtime:new Date(u.mtimeMs).toISOString(),ageSeconds:m,live:v}})),i=s.length>0,a=o.fragmentDir??null,c=a!==null&&(Ig.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: ${s.length} app(s) with a dev-context fragment in ${p}:`);for(let u of s){let m=u.live?"live":"NOT responding",v=`written ${u.ageSeconds}s ago`;l.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${v}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";l.info(`No active infra-kit dev session \u2014 searched ${p} (${u}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},$g={active:Z.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:Z.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:Z.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:Z.array(Z.object({app:Z.string().describe("App folder name (the fragment filename without .json)."),package:Z.string().describe("The app package name the vite helper reads to decide a local route."),port:Z.number().describe("The actual bound port the dev server is listening on."),pid:Z.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:Z.string().describe("Registered portless hostname for the app."),origin:Z.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:Z.string().describe("Release slug the runner recorded for this worktree."),writtenAt:Z.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:Z.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:Z.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:Z.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.")},xi=w({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:$g,handler:()=>fp()});import{spawnSync as yy}from"node:child_process";import J from"node:fs";import _d from"node:os";import H from"node:path";import dr from"node:process";import{z as re}from"zod";import{execFileSync as _g}from"node:child_process";var gp=(e,r)=>{let t=e.filter(o=>!o.live).map(o=>o.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},Dg=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],Og=e=>Dg.some(r=>r.test(e)),Ng="/bin/ps",Mg=()=>_g(Ng,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
176
+ `),hp=(e=Mg)=>{try{return e().some(Og)}catch{return!0}};import{Chalk as jg}from"chalk";import Si from"node:process";var Fg="Tools & CLIs",Lg="Shell & integration",Wg="Project config",Jg="Doppler env tokens",Vg="Dev proxy (portless)",Bg="Claude Code plugin",Gg=`portless serving TLS on :${or}`,Ti=[[Fg,["brew installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","terminal installed","ide installed"]],[Lg,["zshrc init block","zshenv session block","warm cache","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Wg,["infra-kit config valid","user override path","legacy user-global config"]],[Jg,["tokens.json present","env tokens configured","env token valid","tokens.json perms"]],[Vg,["portless installed","portless service target",Gg,"portless CA chain valid","portless CA trusted","portless routes"]],[Bg,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","MCP server key","Agent mode","Agent allowlist"]]],vp="Other",Ug=Ti.map(([e])=>e),Kg=new Map(Ti.flatMap(([e,r])=>r.map(t=>[t,e]))),PC=Ti.flatMap(([,e])=>e),Ci=new Set(["portless routes","tokens.json perms"]),Hg=e=>{let r=new Map;for(let o of e){let n=Kg.get(o.name)??vp,s=r.get(n);s?s.push(o):r.set(n,[o])}return[...Ug,vp].flatMap(o=>{let n=r.get(o);return n&&n.length>0?[{label:o,checks:n}]:[]})},yp={unicode:{pass:"\u2713",fail:"\u2717",warn:"!",separator:"\xB7",rule:"\u2500"},ascii:{pass:"ok",fail:"!!",warn:"!?",separator:"-",rule:"-"}},zg=24,qg=(e,r)=>{let t=e.split(/\s+/).filter(s=>s.length>0),o=[],n="";for(let s of t)n.length===0?n=s:`${n} ${s}`.length<=r?n=`${n} ${s}`:(o.push(n),n=s);return n.length>0&&o.push(n),o.length>0?o:[""]},kp=e=>{let r=t=>e.filter(o=>o.status===t).length;return{passed:r("pass"),failed:r("fail"),warned:r("warn")}},Yg=e=>{let r=new jg({level:e?1:0});return{header:t=>r.bold.cyan(t),pass:t=>r.green(t),fail:t=>r.red(t),warn:t=>r.yellow(t),dim:t=>r.dim(t),bold:t=>r.bold(t)}},Zg=(e,r,t,o)=>{if(e.failed===0&&e.warned===0){let c=`${r}/${r} ok`;return{text:t.pass(c),plainWidth:c.length}}let n=`${e.passed}/${r}`,s=[...e.failed===0?[]:[{plain:`${e.failed} failed`,paint:t.fail}],...e.warned===0?[]:[{plain:`${e.warned} warning${e.warned===1?"":"s"}`,paint:t.warn}]],i=[t.dim(n),...s.map(c=>c.paint(c.plain))].join(` ${o.separator} `),a=s.reduce((c,p)=>c+p.plain.length+3,n.length);return{text:i,plainWidth:a}},Rt=" ",wp=" ",Xg=(e,r,t,o)=>{let n=kp(e.checks),s=Zg(n,e.checks.length,r,t),i=Math.max(1,o-Rt.length-e.label.length-s.plainWidth);return`${Rt}${r.header(e.label)}${" ".repeat(i)}${s.text}`},Qg=(e,r,t,o,n)=>{let s=e.status!=="pass",i=o.pass.length,a=o[e.status],c=e.name.padEnd(r),p=t[e.status],d=p(a),u=s?p(c):c,m=wp.length+i+1+r+2,v=Math.max(zg,n-m),[f,...k]=qg(e.message,v),P=C=>s?C:t.dim(C);return[`${wp}${d} ${u} ${P(f??"")}`.trimEnd(),...k.map(C=>`${" ".repeat(m)}${P(C)}`)]},eh=(e,r,t,o)=>{let n=kp(e),s=t.rule.repeat(Math.max(12,Math.min(o-Rt.length,56))),i=e.filter(d=>d.status==="fail"&&Ci.has(d.name)).length,a=[r.pass(`${n.passed} passed`),...n.failed===0?[]:[r.fail(`${n.failed} failed`)],...n.warned===0?[]:[r.warn(`${n.warned} warned`)]].join(` ${t.separator} `),c=r.dim(`${i} fixable \u2014 run \`infra-kit doctor --fix\``),p=i>0?` ${c}`:"";return[`${Rt}${r.dim(s)}`,`${Rt}${a}${p}`]},rh=(e,r={})=>{let t=r.color??!1,o=r.unicode??!0,n=r.width??80,s=Yg(t),i=o?yp.unicode:yp.ascii;if(e.length===0)return[s.bold("infra-kit doctor"),"",`${Rt}${s.dim("No checks ran.")}`];let a=Math.max(...e.map(p=>p.name.length)),c=Hg(e).flatMap(p=>[Xg(p,s,i,n),...p.checks.flatMap(d=>Qg(d,a,s,i,n)),""]);return[s.bold("infra-kit doctor"),"",...c,...eh(e,s,i,n)]},th=new Set(["","0","false","none"]),oh=["LC_ALL","LC_CTYPE","LANG"],nh=(e,r)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!th.has(e.FORCE_COLOR.toLowerCase()):!!r.isTTY,sh=(e,r)=>{if(r)return!1;let t=oh.map(o=>e[o]).find(o=>o!==void 0&&o!=="");return t===void 0?!0:/UTF-?8/i.test(t)},ih=(e={})=>{let r=e.env??Si.env,t=e.stream??Si.stderr;return{color:nh(r,t),unicode:sh(r,e.ascii??!1),width:t.columns??80}},ah=(e,r={})=>{(r.write??(o=>{Si.stderr.write(o)}))(`${rh(e,ih(r)).join(`
177
+ `)}
178
+ `)};var ch=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),lh=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(r=>ch(r[1])),ph=e=>{let r=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return r===null?null:lh(r[1])},dh=e=>{let r=[],t="",o=!1,n=!1,s=!1,i=[...e];for(let[a,c]of i.entries()){if(s){s=!1;continue}if(c==='"'){o=!o,n=!0;continue}let p=i[a+1];if(c==="\\"&&(p==='"'||p==="\\")){t+=p,n=!0,s=!0;continue}if(/\s/.test(c)&&!o){n&&(r.push(t),t="",n=!1);continue}t+=c,n=!0}return n&&r.push(t),r},uh=e=>{let r=e.split(`
179
+ `).find(t=>t.startsWith("ExecStart="));return r===void 0?null:dh(r.slice(10))},bp=(e,r)=>{try{return e==="darwin"?ph(r):e==="linux"?uh(r):null}catch{return null}};import Ih from"@inquirer/select";import{Buffer as $h}from"node:buffer";import _h from"node:fs";import Dh from"node:path";import Fi from"node:process";import{z as It}from"zod";import{$ as Un}from"zx";var mh="Could not find requested project",fh="Could not find requested config",Rp="Invalid Auth token",Ep="does not have access to requested config",wo=e=>e.includes(Rp)||e.includes(Ep)?"auth":e.includes(mh)?"project":e.includes(fh)?"config":"unknown",ko=e=>e.includes(Ep)?"mis-scoped":e.includes(Rp)?"revoked":null;var Pp=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(`
180
+ `),Et=class extends Sn{authKind;constructor(r,t=null,o){super(o??Pp(r),r),this.name="DopplerAuthError",this.authKind=t}};var Ai=({kind:e,project:r,config:t,available:o})=>{let n=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 s=e==="project"?"Available projects":`Available configs in "${r}"`;n.push(`${s}: ${o.join(", ")}.`)}return n.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."),n.join(`
181
+ `)};import{$ as Bn}from"zx";var gh=5e3,hh="DOPPLER_CONFIG",Or=async()=>{let{envManagement:e}=await x();return e.config.name},bo=async({childEnv:e,project:r,config:t})=>{let o=Bn.quiet;Bn.quiet=!0;try{let s=(await Bn({env:e})`doppler secrets get ${hh} --plain --project ${r} --config ${t}`.timeout(gh)).stdout.trim();return s!==t?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(n){return{outcome:vh(n)}}finally{Bn.quiet=o}},vh=e=>{let r=yn(e)??(e instanceof Error?e.message:String(e));return wo(r)!=="auth"?"unreachable":ko(r)??"unreachable"};import xp from"node:process";var K="INFRA_KIT_ENV_TOKEN",Pt=async e=>{let r=xp.env[K];if(r)return{token:r,source:"env"};let o=(await ne())?.envs[e];if(o)return{token:o,source:"store"};throw new Sn(yh(e,await oo()),e)},FC=async e=>xp.env[K]?!0:!!(await ne())?.envs[e],yh=(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 ${K} instead \u2014 it takes precedence and needs no home config.`].join(`
182
+ `);import Np from"node:process";import{z as Dp}from"zod";import bh from"node:process";import{z as ar}from"zod";var Sp=["prod"],xt={allowed:!1,reason:"disallow"},St=e=>Sp.includes(e),wh=["dev","stage"],Tt=e=>wh.includes(e)||St(e),Je=(e,r=xt)=>r.allowed?e:e.filter(t=>!St(t)),Nr=(e,r,t=xt)=>{if(!t.allowed&&St(e)){if(t.reason==="agent-blocked"){let{source:o}=_;throw new N({status:"refused",env:e,agentMode:o},2,{operation:r,remediation:o==="mcp"?`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`:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:o==="mcp"?`"${e}" is not reachable over MCP in this project`:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`})}throw new g(void 0,{operation:r,remediation:`use \`infra-kit release deliver\` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})}};var Ve=async()=>{let e;try{e=(await x()).protectedEnvs??"disallow"}catch{return xt}return e==="disallow"?xt:e==="cli-only"&&z()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var Ro=e=>{let{env:r,branch:t}=e;St(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(`
183
+ `))};import Tp from"node:fs/promises";import Ii from"node:path";import kh from"yaml";var Cp=".github/workflows",Be=async e=>{let r=await R();return Ap(Ii.resolve(r,Cp,e))},$i=async()=>{let e=await R(),r=Ii.resolve(e,Cp),t;try{t=await Tp.readdir(r)}catch{return[]}let o=t.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),n=await Promise.all(o.map(s=>Ap(Ii.resolve(r,s))));return[...new Set(n.flat())]},Ap=async e=>{let r;try{r=kh.parse(await Tp.readFile(e,"utf-8"))}catch{return[]}let t=Ct(r,"on")??Ct(r,"true"),o=Ct(Ct(Ct(Ct(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(o)?o.filter(n=>typeof n=="string"&&n.length>0):[]},Ct=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var At=async()=>{let e=await $i(),r=await ne(),t=e.map(s=>({env:s,source:"gh-workflow"})),o=new Set(e),n=Object.keys(r?.envs??{}).filter(s=>!o.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...t,...n]},Mr=async()=>(await At()).map(r=>r.env);var Gn=(e,r,t)=>e.map(({env:o,source:n})=>({env:o,source:n,hasToken:!!(t||r[o])})),Ip=["Environment","Source","Token"],Rh=e=>{let r=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),t=Ip.map((s,i)=>Math.max(s.length,...r.map(a=>(a[i]??"").length))),o=s=>s.map((i,a)=>i.padEnd(t[a]??0)).join(" | ").trimEnd(),n=t.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",o(Ip),n,...r.map(o)]},_p=async()=>{let e=await Or(),r=await At(),t=await ne(),o=bh.env[K],n=Gn(r,t?.envs??{},o);if(l.info(`Doppler project: ${e}
184
+ `),n.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."),$p({project:e,envs:n});for(let s of Rh(n))l.info(s);return $p({project:e,envs:n})},$p=({project:e,envs:r})=>{let t={project:e,configs:r.map(o=>o.env),tokens:r};return{content:y(JSON.stringify(t,null,2)),structuredContent:t}},_i=w({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:ar.string().describe("Detected Doppler project name"),configs:ar.array(ar.string()).describe("Every environment name known to this project"),tokens:ar.array(ar.object({env:ar.string().describe("Environment / Doppler config name"),source:ar.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:ar.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:_p});var Op=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Eh=async e=>{try{return await e}catch{return[]}},Ph=async e=>{let r=await ne().catch(()=>null);return Gn(e,r?.envs??{},Np.env[K]).filter(t=>!t.hasToken).map(t=>t.env)},Di=()=>({get message(){return`Choose the environment to load into terminal session ${Np.env[kr]??`UNKNOWN \u2014 ${kr} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>Op(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await Eh(At());if(e.length===0)return l.info({msg:"Tool execution form options empty: env-load"}),null;let r=e.map(o=>o.env),t=await Ph(e);return Dp.object({config:Dp.enum(r).describe(`The environment to load. ${t.length===0?"A service token is stored for every one of them.":`NO stored token for: ${t.join(", ")} \u2014 choosing one of those fails until you run \`infra-kit env-token-set <env>\`.`} The list is what env-list knows: workflow-declared environments first, then token-only ones.`)})},toArgs:(e,r)=>{let{config:t}=e;return typeof t!="string"||t.length===0?null:{...Op(r)?r:{},config:t}}});import{z as xh}from"zod";var Sh=()=>_.source!=="mcp"&&ue(),Th=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(r){return l.debug({err:r,operation:e.operation},"argument form builder threw; refusing without choices"),null}},he=async e=>{if(!Sh()||!e.provider.isFormable(e.params))return;let r=await Th(e),t=typeof e.params=="object"&&e.params!==null?e.params:{},o=(r===null?[]:Object.keys(r.shape)).filter(i=>t[i]===void 0||t[i]===""),n=typeof e.argument=="string"?e.argument:e.argument(o),s=r===null?void 0:xh.toJSONSchema(r);throw new N({status:"argument_required",argument:n,...s===void 0?{}:{choices:s},agentMode:_.source},2,{operation:e.operation,remediation:s===void 0?`pass --${n} on the re-run \u2014 nothing could be listed to choose from`:`ask the human to pick from "choices", then pass --${n} on the re-run`,stderrExcerpt:`--${n} was not given and there is no human to ask`})};import Mp from"node:fs";import{$ as Ch}from"zx";import jr from"node:fs";import Eo from"node:path";var Oi=({autoLoaded:e,projectDir:r,canonicalProjectRoot:t})=>!e||!r||!t?!1:t===r,Ge=e=>{if(!e)return"";try{return jr.realpathSync(e)}catch{return""}},Ni=(e,r)=>{try{let t=Rr(e);jr.mkdirSync(t,{recursive:!0,mode:448}),Er(Eo.join(t,pe),r,384)}catch(t){l.debug(`warm-cache write skipped: ${t.message}`)}},Mi=(e=Date.now(),r=Xt)=>{let t=Gc(),o;try{o=jr.readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of o){if(!n.isDirectory())continue;let s=Eo.join(t,n.name);try{let{mtimeMs:i}=jr.statSync(Eo.join(s,pe));e-i>=r*1e3&&jr.rmSync(s,{recursive:!0,force:!0})}catch{}}},ji=(e,r)=>{try{let t=Rr(e);if(r){jr.rmSync(t,{recursive:!0,force:!0});return}if(!jr.existsSync(Eo.join(t,pe)))return;Er(Eo.join(t,dn),`# infra-kit warm cache cleared
185
+ `,384)}catch(t){l.debug(`warm-cache invalidate skipped: ${t.message}`)}};var jp=e=>e.split(`
186
+ `).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),Ah=async()=>{let e;try{e=(await Ch({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 jp(e)){let o=Ge(t);if(!o)continue;let n=Rr(o);try{if(!Mp.existsSync(n))continue;Mp.rmSync(n,{recursive:!0,force:!0}),r.push(n)}catch(s){l.debug(`warm-cache purge skipped for ${n}: ${s.message}`)}}return r};var Oh=e=>e?[`${br}=${Fr("1")}`]:[`unset ${br}`,`unset ${it}`],Nh="DOPPLER_CONFIG",Fp=new Set(["DOPPLER_TOKEN",K]),Lp=!1,Mh=e=>{e.length===0||Lp||(Lp=!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.`))},Jp=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:n,autoLoaded:s})=>{let i=e.filter(([a])=>!Fp.has(a));return Mh(e.filter(([a])=>Fp.has(a)).map(([a])=>a)),["set -a",...i.map(([a,c])=>`${a}=${Fr(c)}`),`${un}=${Fr(r)}`,`${ot}=${Fr(r)}`,`${nt}=${Fr(t)}`,`${mn}=${Fr(o)}`,`${st}=${Fr(n)}`,...Oh(s),"set +a"]},jh=async()=>{try{return await R()}catch{return""}},Vp=async({config:e,autoLoaded:r=!1,beforeWrite:t,projectDir:o})=>{let n=await Or(),s=await jh(),i=await Wh(n,e),a=new Date().toISOString(),p=`${Jp({pairs:i,config:e,project:n,projectRoot:s,loadedAt:a,autoLoaded:r}).join(`
187
+ `)}
188
+ `,d=at(),u=Dh.resolve(d,pe);if(t&&!t())return null;_h.mkdirSync(d,{recursive:!0,mode:448}),Er(u,p,384);let m=Ge(s);return Oi({autoLoaded:r,projectDir:o,canonicalProjectRoot:m})&&(Ni(o,p),Mi()),{filePath:u,variableCount:i.length,project:n,config:e}},Bp=Di(),Gp=async e=>{let{config:r}=e;await he({provider:Bp,params:e,operation:"env-load",argument:"config"});let t="";if(r)t=r;else{if(z())throw new N({status:"argument_required",argument:"config",agentMode:_.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await Mr();h.setInteractive(),t=await A(i=>Ih({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:Fi.stderr,whenHeadless:"refuse"})}h.addOption("--config",t);let o=await Vp({config:t,autoLoaded:!1});if(!o)throw new Error("env-load: write was unexpectedly aborted");h.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config,sessionId:Fi.env[kr]??null};return{content:y(JSON.stringify(n,null,2)),structuredContent:n}},Wp=1024*1024,Fh=3e4,Lh=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],$t=(e,r=Fi.env)=>{let t={...r};for(let o of Lh)delete t[o];return t.DOPPLER_TOKEN=e,t},Wh=async(e,r)=>{let{token:t}=await Pt(r),o=$t(t),n=Un.quiet;Un.quiet=!0;try{let s;try{s=await Un({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(Fh)}catch(a){throw Jh(a,e,r)}Vh(s.stdout);let i=Kp(s.stdout);return Up(i,r),i}finally{Un.quiet=n}},Up=(e,r)=>{let t=e.find(([o])=>o===Nh)?.[1];if(!(t===void 0||t===r))throw new Et(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.
189
+ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},Jh=(e,r,t)=>{let o=yn(e)??(e instanceof Error?e.message:String(e)),n=wo(o);return n==="auth"?new Et(t,ko(o)):n==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(Ai({kind:n,project:r,config:t,available:null}))},Vh=e=>{let r=$h.byteLength(e,"utf-8");if(r>Wp)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Wp}) \u2014 refusing to write to disk`)},Fr=e=>`'${e.replaceAll("'","'\\''")}'`,Bh=/^[A-Z_]\w*$/i,Kp=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,n]of Object.entries(r)){if(!Bh.test(o))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(o.slice(0,80))})`);if(typeof n!="string")throw new TypeError(`doppler returned a non-string value for "${o}" (got ${typeof n})`);t.push([o,n])}if(t.length===0)throw new Error("doppler returned empty output for env-load");return t},Li=w({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess.',inputSchema:{config:It.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Bp,outputSchema:{filePath:It.string().describe("Path to the file that must be sourced to apply variables"),variableCount:It.number().describe("Number of variables loaded"),project:It.string().describe("Doppler project name"),config:It.string().describe("Doppler config name"),sessionId:It.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:Gp});import Gh from"node:fs";import Uh from"node:os";import Kh from"node:path";var Hh="infra-kit.json",zh="Skipped agent-instruction files, the plugin pointer, the plugin install and .mcp.json \u2014 no usable git repo root here (not a git repo, or the root is your home directory)",qh="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Po=async()=>{let e;try{e=await R()}catch{return null}let r=e.trim();return r===""||r===Uh.homedir()?null:r},Hp=async()=>{let e=await Po();return e===null&&l.info(zh),e},Yh=async()=>{let e=await Po();return e===null?null:Gh.existsSync(Kh.join(e,Hh))?e:(l.info(qh),null)};var Zh=async e=>{try{return await ie(e)}catch(r){return l.debug({err:r,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},zp=async()=>{let e=await Yh(),r=q.version;if(e===null)return{skipped:!0,root:null,version:r,written:[]};let t=[...await fo(e,{version:r})];for(let o of await Zh(e)){let n=await co(o);t.push(...await go(o,{repoRoot:e,version:r,declaredType:n}))}return{skipped:!1,root:e,version:r,written:t}};import ae from"node:fs";import Ki from"node:os";import ye from"node:path";import Hi from"node:process";import Hn from"node:fs/promises";import Xh from"node:path";import Qh from"node:process";var qp=` // "envManagement": { // required in layer 1; provider-tagged
190
+ // "provider": "doppler",
191
+ // "config": { "name": "my-doppler-project" }
192
+ // },
193
+ //
194
+ // "ide": {
195
+ // "provider": "cursor",
196
+ // "config": { "workspaceConfigPath": "/path/to/your.code-workspace" }
197
+ // },
198
+ // // Or, for Zed (no workspace file \u2014 one window with all worktrees via "zed <root> <wt...>"):
199
+ // "ide": { "provider": "zed", "config": {} },
200
+ // // Or drive BOTH editors at once with an array (at most one entry per provider):
201
+ // "ide": [
202
+ // { "provider": "cursor", "config": { "workspaceConfigPath": "/path/to/your.code-workspace" } },
203
+ // { "provider": "zed", "config": {} }
204
+ // ],
205
+ //
206
+ // "taskManager": {
207
+ // "provider": "jira",
208
+ // "config": { "baseUrl": "https://acme.atlassian.net", "projectId": 123 }
209
+ // },
210
+ // NOTE: taskManager is validated but NOT yet used \u2014 Jira credentials and the project id are read
211
+ // from the JIRA_BASE_URL / JIRA_EMAIL / JIRA_TOKEN / JIRA_PROJECT_ID environment variables
212
+ // (Doppler), never from this file. Editing projectId here changes nothing; change it in Doppler.
213
+ //
214
+ // "worktrees": {
215
+ // "openInGithubDesktop": false,
216
+ // "openInCmux": true,
217
+ // // cmux pane layout for opened worktrees: "two-columns" (default, left | right)
218
+ // // or "three-pane" (left split top/bottom + full-height right).
219
+ // "cmux": { "layout": "two-columns" }
220
+ // },
221
+ //
222
+ // // Auto-load Doppler env when working inside this project/worktree. Omit to
223
+ // // disable. "trigger" (pick one): "shell-startup" (new shells) | "cli-invocation"
224
+ // // (before each infra-kit command, primes subsequent commands). "config" is the
225
+ // // environment to load \u2014 must have a service token (infra-kit env-token-set) or
226
+ // // auto-load quietly disables. Requires the committed infra-kit.json at the git
227
+ // // repo root, and the zsh shell integration (infra-kit init + a new shell). zsh only.
228
+ // "envAutoLoad": { "trigger": "shell-startup", "config": "dev" },
229
+ //
230
+ // // Per-app local-dev overrides, keyed by APP FOLDER name (the directory under
231
+ // // apps/). Both fields optional: "port" pins the local listen port (otherwise
232
+ // // <APP>_PORT / PORT / a built-in default), "prefixUrl" pins the URL prefix the
233
+ // // app is served under. An unknown app name is ignored at resolve time, never a
234
+ // // parse error.
235
+ // "dev": {
236
+ // "client": { "port": 4001, "prefixUrl": "/api" }
237
+ // },
238
+ //
239
+ // // Named \`infra-kit dev <preset>\` sessions. The keys under "apps" are PACKAGES \u2014
240
+ // // "<app>/api" or "<app>/ui". A bare "<app>" is a FOLDER, not a package, and is
241
+ // // REJECTED. Per target: "watchDeps" (api targets) rebuilds the shared-package
242
+ // // dependency closure and restarts on change; "proxy" maps a route path to
243
+ // // "local" | "cloud" for this session only. "cmux": true runs each launched target
244
+ // // in its own cmux pane. Omit "apps" entirely to launch every discovered target.
245
+ // "devServersPresets": {
246
+ // "backend": {
247
+ // "apps": {
248
+ // "client/api": { "watchDeps": true, "proxy": { "/api": "local", "/auth": "cloud" } },
249
+ // "client/ui": {}
250
+ // },
251
+ // "cmux": true
252
+ // }
253
+ // },
254
+ //
255
+ // // DEPRECATED \u2014 accepted but IGNORED; safe to delete. Remove it and this note in a
256
+ // // future release.
257
+ // //
258
+ // // The proxy port is no longer configurable. Every dev URL is now
259
+ // // https://<release>.<package>.localhost with NO port, and the only port that can
260
+ // // serve a port-free HTTPS URL is 443 \u2014 so a setting here could only put the port
261
+ // // back into the URL. Set up the daemon once (the install is the only step needing
262
+ // // root; trusting its local CA does not). Run \`infra-kit doctor\`: it checks both and
263
+ // // prints each fix as a command you can paste, with the paths filled in for your
264
+ // // machine. Do not type a bare \`portless\` \u2014 it lives in node_modules, not on PATH.
265
+ // // infra-kit itself never elevates.
266
+ // "devProxy": { "port": 443 },
267
+ //
268
+ // // May this project deploy to the delivery-shaped environments ("prod")? The LIST lives in code
269
+ // // (lib/workflow-envs/protected-envs); this decides only whether THIS project may reach it.
270
+ // // "disallow" \u2014 the DEFAULT when the key is absent. Filtered out of every deploy picker and
271
+ // // refused, on both \`--from local\` and \`--from ci\`. Use
272
+ // // \`infra-kit release deliver\`, which also does the RC PR and the Jira version.
273
+ // // "allow" \u2014 reachable from the CLI and from an MCP agent alike.
274
+ // // "cli-only" \u2014 reachable from a terminal, but NOT over MCP: an agent's tool call carries no
275
+ // // human keystroke, so agents keep the refusal.
276
+ // // Allowing it does not remove the other gates: a local deploy still requires the AWS account to
277
+ // // report that environment, and still refuses a dirty tree \u2014 unconditionally, with nothing to pass
278
+ // // that waives it. A \`--from ci\` dispatch has no such second gate and prints a warning naming
279
+ // // what it skips.
280
+ // //
281
+ // // It IS honoured from this layer \u2014 the merge treats it like any other key \u2014 but it belongs in the
282
+ // // committed project infra-kit.json, where a reviewer and \`git blame\` can see it. Setting it here
283
+ // // grants yourself production access with no trace in the repo.
284
+ // "protectedEnvs": "disallow"
285
+ //
286
+ // // MCP servers fronted by \`ik-mcp\`, the credential-agnostic stdio proxy: one entry per server,
287
+ // // naming the command to spawn and the env-var NAMES it reads from the \`ik env-load\` session
288
+ // // file. \`ik setup\` derives a committed \`.mcp.json\` entry from each; \`ik audit\` guards drift.
289
+ // //
290
+ // // PROJECT LAYER ONLY. This key is REFUSED here and in the per-project override \u2014 the loader
291
+ // // throws with a message saying so \u2014 because it feeds a committed file and the layer merge is
292
+ // // shallow: a per-machine copy would replace the project's servers for everyone. For a
293
+ // // machine-only override of one server (a local fork), use Claude Code's own local scope:
294
+ // // claude mcp add --scope local <name> -- ik-mcp --name <name> --env <VAR> -- <command> <args>
295
+ // // The proxy is for STATELESS servers: a credential change respawns the child.
296
+ // "mcp": {
297
+ // "grafana": {
298
+ // "command": "mcp-grafana",
299
+ // "args": ["-t", "stdio"],
300
+ // "env": ["GRAFANA_URL", "GRAFANA_SERVICE_ACCOUNT_TOKEN"],
301
+ // "unset": ["GRAFANA_API_KEY", "GRAFANA_SERVICE_ACCOUNT_TOKEN_FILE"]
302
+ // }
303
+ // }
304
+ //
305
+ // // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in
306
+ // // tokens.json \u2014 a SIBLING of this file, at ~/.infra-kit/projects/<repo>/tokens.json (mode 0600) \u2014
307
+ // // shaped { "envs": { "<env>": "dp.st\u2026" } }. Write it with \`infra-kit env-token-set <env>\` (which
308
+ // // also fixes its modes), or by hand: both are supported, which is why the store carries no
309
+ // // repo-identity field and no mandatory version. Pasting a token into an
310
+ // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
311
+ // // the token first, because a config file can be committed, backed up by your editor, or shared.`,Wi=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
312
+ //
313
+ // Merge chain (later layers override earlier ones at top-level keys):
314
+ // 1. <repo>/infra-kit.json \u2014 committed project config (required)
315
+ // 2. ~/.infra-kit/infra-kit.json \u2014 user-global (the sibling of this file)
316
+ // 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override
317
+ //
318
+ // Merge is shallow: setting a top-level key replaces that whole section from
319
+ // layer 1. Arrays do not concatenate. Top-level keys recognized:
320
+ // envManagement, ide, taskManager, worktrees, envAutoLoad, dev,
321
+ // devServersPresets, devProxy, protectedEnvs, mcp (project layer only). The schema is strict \u2014 an
322
+ // unrecognized top-level key is a parse error, not a silently ignored one.
323
+ //
324
+ // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
325
+ // overrides in the sibling infra-kit.json (strict JSON: no comments, double-quoted
326
+ // keys). Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
327
+ //
328
+ // Every recognized key is documented below. NOTE: \`envManagement\` is REQUIRED in
329
+ // the committed project infra-kit.json (layer 1) and is usually NOT set in this
330
+ // user-global layer \u2014 it is shown here only to document the full, valid config shape.
331
+ {
332
+ ${qp}
333
+ }
334
+ `,Ji=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
335
+ //
336
+ // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
337
+ // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
338
+ // top-level key set here replaces that whole section wholesale; arrays do not
339
+ // concatenate. Top-level keys recognized: envManagement, ide,
340
+ // taskManager, worktrees, envAutoLoad, dev, devServersPresets, devProxy,
341
+ // protectedEnvs, mcp (project layer only \u2014 refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
342
+ // error, not a silently ignored one.
343
+ //
344
+ // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
345
+ // in the sibling infra-kit.json (strict JSON: no comments, double-quoted keys).
346
+ //
347
+ // Every recognized key is documented below. NOTE: \`envManagement\` is REQUIRED in
348
+ // the committed project infra-kit.json (layer 1) and is usually NOT set in this
349
+ // override layer \u2014 it is shown here only to document the full, valid config shape.
350
+ {
351
+ ${qp}
352
+ }
353
+ `,Vi=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
354
+ //
355
+ // Machine-local registry the vendor commands (sync/manifest/diff) read to know
356
+ // where your project repos live and which ones to stamp. This .example.jsonc is
357
+ // reference only \u2014 it is NOT loaded. The real file is the strict-JSON sibling
358
+ // vendor.json (no comments, double-quoted keys); run \`infra-kit vendor config --init\`
359
+ // to scaffold it.
360
+ {
361
+ // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
362
+ // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
363
+ }
364
+ `;var Yp=!1,ev=e=>e.replace(/\.json$/,".example.jsonc"),rv=async e=>{try{return await Hn.readFile(e,"utf-8")}catch{return null}},zn=async e=>{let r=e.userProject,t=ev(r);await Hn.mkdir(Xh.dirname(r),{recursive:!0});let o=!await be(r);o&&await Hn.writeFile(r,`{}
365
+ `,"utf-8");let n=Ji(e.projectName),s=await rv(t)!==n;return s&&await Hn.writeFile(t,n,"utf-8"),o&&Rl(),{configPath:r,examplePath:t,createdConfig:o,refreshedExample:s}},qn=e=>`Created ${b(e.configPath)} \u2014 see ${b(e.examplePath)} for the annotated reference.`,tv=async()=>{if(Qh.env.INFRA_KIT_NO_SEED||Yp)return;Yp=!0;let e;try{e=await ee()}catch{return}if(await be(e.main))try{let r=await zn(e);r.createdConfig?l.info(qn(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 ve from"node:fs/promises";import De from"node:path";import{pathToFileURL as sv}from"node:url";import iv from"yaml";import{z as Qp}from"zod";import ov from"node:fs/promises";import Bi from"node:os";import Gi from"node:path";import{z as nv}from"zod";import{z as Yn}from"zod";var Zp="vendor.json",Zn=Yn.object({workspaceDir:Yn.string().min(1),targets:Yn.array(Yn.string()).min(1)}).strict();var Ui=()=>Gi.join(Bi.homedir(),Bc,Zp),a$=e=>{if(e==="~")return Bi.homedir();if(e.startsWith("~/"))return Gi.join(Bi.homedir(),e.slice(2));if(Gi.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},c$=async()=>{let e=Ui(),r;try{r=await ov.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:
366
+
367
+ {
368
+ "workspaceDir": "~/projects",
369
+ "targets": ["my-repo"]
370
+ }
371
+ `)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in vendor.json at ${e}: ${n.message}`)}let o=Zn.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${nv.prettifyError(o.error)}`);return o.data};var Xp=e=>e.replace(/\.json$/,".yml"),ed=async()=>{let e;try{e=await ee()}catch{return}let r=[{label:"infra-kit.json",yml:Xp(e.main),json:e.main,schema:bl},{label:"~/.infra-kit/infra-kit.json",yml:De.join(De.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Ns},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Xp(e.userProject),json:e.userProject,schema:Ns}],t=0;for(let o of r){let[n,s]=await Promise.all([be(o.yml),be(o.json)]);if(n){if(s){l.info(`\u26A0 Skipped ${b(o.yml)} \u2014 ${b(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await ve.readFile(o.yml,"utf-8"),a=iv.parse(i)??{},c=o.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${b(o.yml)} \u2014 invalid config: ${Qp.prettifyError(c.error)}`);continue}await ve.mkdir(De.dirname(o.json),{recursive:!0}),await ve.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
372
+ `,"utf-8"),await ve.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&&lt()},rd=async()=>{let e;try{e=await ee()}catch{return}let r=De.dirname(e.userGlobal),t=[{from:De.join(r,"config.json"),to:e.userGlobal},{from:De.join(r,"config.example.jsonc"),to:De.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:n,to:s}of t){let[i,a]=await Promise.all([be(n),be(s)]);if(i){if(a){l.info(`\u26A0 Skipped ${b(n)} \u2014 ${b(s)} already exists (remove the stale file manually)`);continue}try{await ve.mkdir(De.dirname(s),{recursive:!0}),await ve.rename(n,s),l.info(`\u2713 Renamed ${b(n)} \u2192 ${b(s)}`),o++}catch(c){l.info(`\u26A0 Skipped ${b(n)} \u2014 ${c.message}`)}}}o>0&&lt()},td=async()=>{let e=Ui(),r=De.dirname(e),t=De.join(r,"vendor.config.ts"),[o,n]=await Promise.all([be(t),be(e)]);if(o){if(n){l.info(`\u26A0 Skipped ${b(t)} \u2014 ${b(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await ve.stat(t),c=(await import(`${sv(t).href}?mtime=${Number(s.mtimeMs)}`)).default,p=typeof c=="function",d=p?await c():c,u=Zn.safeParse(d);if(!u.success){l.info(`\u26A0 Skipped ${b(t)} \u2014 invalid factory config: ${Qp.prettifyError(u.error)}`);return}await ve.mkdir(r,{recursive:!0}),await ve.writeFile(e,`${JSON.stringify(u.data,null,2)}
373
+ `,"utf-8"),await ve.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(s){l.info(`\u26A0 Skipped ${b(t)} \u2014 ${s.message}`)}}},av=e=>{let r=e.ide;if(r===null||typeof r!="object")return{changed:!1,result:e};let t=!1,o=s=>{if(s===null||typeof s!="object"||!("config"in s))return s;let i=s.config;if(i===null||typeof i!="object"||!("mode"in i))return s;t=!0;let a=Object.fromEntries(Object.entries(i).filter(([c])=>c!=="mode"));return{...s,config:a}},n=Array.isArray(r)?r.map(o):o(r);return t?{changed:!0,result:{...e,ide:n}}:{changed:!1,result:e}},od=async()=>{let e;try{e=await ee()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await be(o))try{let n=await ve.readFile(o,"utf-8");if(n.trim()==="")continue;let s=JSON.parse(n),{changed:i,result:a}=av(s);if(!i)continue;await ve.writeFile(o,`${JSON.stringify(a,null,2)}
374
+ `,"utf-8"),l.info(`\u2713 Normalized ide config in ${b(o)} (removed legacy "mode")`),t++}catch(n){l.info(`\u26A0 Skipped normalizing ${b(o)} \u2014 ${n.message}`)}t>0&&lt()};var Lr="# -- infra-kit:begin --",cr="# -- infra-kit:end --",cv=[["# region infra-kit","# endregion infra-kit"]],lv="# infra-kit shell functions",_t=class extends Error{constructor(t,o){super(o instanceof Error?o.message:String(o),{cause:o});this.step=t;this.reason=o;this.name="InitStepError"}step;reason},xo="Run `source ~/.zshrc` or open a new terminal to activate.",pv={step:"migrations",outcome:"skipped",message:"Config migrations checked (legacy yml layers, ide structure, user-global filename, factory config)",level:"silent"},Ue=async(e,r)=>{try{return await r()}catch(t){throw new _t(e,t)}},zi=async e=>{let r=[],t=(...s)=>{for(let i of s)r.push(i),e?.(i)};await Ue("zshrc",()=>{t(dv())}),await Ue("zshenv",()=>{t(uv())}),await Ue("migrations",async()=>{await mv(),t(pv)}),await Ue("user-config",()=>{t(gv())});let o=await Ue("guidance",async()=>{let{entries:s,root:i}=await yv();return t(...s),i}),n=await Ue("plugin-pointer",async()=>Hp());return t(...bv(n,o)),await Ue("plugin-pointer",async()=>{await Sv(n,t)}),await Ue("mcp-proxies",async()=>{t(...await Cv(n))}),await Ue("project-config",async()=>{t(...await hv())}),t(...fv()),r},Qn=e=>{if(e.level!=="silent"){if(e.level==="warn"){l.warn(e.message);return}if(e.level==="debug"){l.debug({msg:e.message});return}l.info(e.message)}},dv=()=>{let e=ye.join(Ki.homedir(),".zshrc"),r=ae.existsSync(e)?Iv(ae.readFileSync(e,"utf-8")):"",t=ut({content:r,body:sd(),startMarker:Lr,endMarker:cr,placement:"append-end"});return ae.writeFileSync(e,t),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},uv=()=>{let e=ye.join(Ki.homedir(),".zshenv"),r=ae.existsSync(e)?ae.readFileSync(e,"utf-8"):"",t=ut({content:r,body:qi(),startMarker:Lr,endMarker:cr});return ae.writeFileSync(e,t),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},mv=async()=>{await ed(),await od(),await rd(),await td()},fv=()=>{let e=Hi.env.SHELL??"",r=[];return e.includes("zsh")||r.push({step:"shell",outcome:"warned",message:`Your login shell ($SHELL=${e||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear/auto-load) is zsh-only and won't activate in bash/fish.`,level:"warn"}),r.push({step:"shell",outcome:"unchanged",message:xo,level:"info"}),r},gv=()=>{let e=ye.join(Ki.homedir(),".infra-kit"),r=ye.join(e,"infra-kit.json");return ae.mkdirSync(e,{recursive:!0}),ae.writeFileSync(ye.join(e,"infra-kit.example.jsonc"),Wi(),"utf-8"),ae.writeFileSync(ye.join(e,"vendor.example.jsonc"),Vi(),"utf-8"),ae.existsSync(r)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${r} (refreshed reference examples)`,level:"info"}:(ae.writeFileSync(r,`{}
375
+ `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`,level:"info"})},hv=async()=>{if(Hi.env.INFRA_KIT_NO_SEED)return[Xn("INFRA_KIT_NO_SEED is set")];try{let e=await ee();if(!ae.existsSync(e.main))return[Xn(`no project config at ${e.main}`)];let r=await zn(e);return r.createdConfig?[{step:"project-config",outcome:"written",message:qn(r),level:"info"}]:[Xn("the user-project config was already present")]}catch(e){return l.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[Xn(e instanceof Error?e.message:String(e))]}},Xn=e=>({step:"project-config",outcome:"skipped",message:`Skipped seeding the user-project config \u2014 ${e}`,level:"silent"}),vv=(e,r,t)=>{let o=[];for(let s of t){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;o.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${ye.relative(e,s.path)}${i}`,level:"info"})}o.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${r})`,level:"info"});let n=t.filter(s=>s.action==="failed");return n.length===0||o.push({step:"guidance",outcome:"warned",message:`${n.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),o},yv=async()=>{let{skipped:e,root:r,version:t,written:o}=await zp();return e||r===null?{root:null,entries:[{step:"guidance",outcome:"skipped",message:"Agent-instruction files skipped \u2014 not an infra-kit repo",level:"silent"}]}:{root:r,entries:vv(r,t,o)}},wv=(e,r)=>{let t=ye.relative(e,r.path);return r.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${t} (Claude Code plugin pointer)`,level:"info"}:r.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${t} \u2014 added ${r.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:r.status==="unchanged"?"unchanged":"warned",message:`${t} \u2014 ${r.status}`,level:"silent"}},kv=(e,r)=>{let t=U;if(r.kind==="stale"||r.kind==="wrong-key"){let n=r.kind==="stale"?B:r.key;return{step:"mcp-server",outcome:"unchanged",message:` ${t} still registers the infra-kit MCP server under "${n}" \u2014 the plugin no longer serves one, so this entry only spawns a compatibility stub. Delete the "${n}" entry from ${t} by hand in a PR, keeping its siblings`,level:"info"}}return r.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${Re} from ${ye.join(e,U)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: none wanted \u2014 the plugin is skills-only (${r.kind==="absent"?`${t} carries no "${B}" key`:`no ${t}`})`,level:"info"}},bv=(e,r)=>e===null||r!==null?[]:[{step:"plugin-pointer",outcome:"warned",message:`No infra-kit.json at ${e} \u2014 setting up Claude Code there anyway: writing .claude/settings.json and installing the ${F} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],Rv=()=>[vi,We].map(e=>({step:"plugin-pointer",outcome:"skipped",message:e,level:"info"})),Ev=e=>({step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${q.version} is behind ${e.latestVersion}, update it first: ${hn(e.updateCommand)}`:`CLI ${q.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"}),Pv=(e,r)=>e.status==="skipped-cli-stale"?[Ev(r)]:e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${F} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${kt}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${F} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...Rv()]:[{step:"plugin-pointer",outcome:"warned",message:`Could not install the Claude Code plugin \u2014 ${e.status==="unverified"?"the install reported success but Claude Code recorded no installation":`the ${e.step} step failed: ${e.error}`}. Run by hand: ${We}`,level:"warn"}],nd={stale:!1},xv=async()=>{let e=so(),r=e===null?await js(Hi.env):e.latestVersion;return r===null||!Fs(r,q.version)?nd:{stale:!0,latestVersion:r,updateCommand:e?.updateCommand??Kc(r)}},Sv=async(e,r)=>{if(e===null){r({step:"plugin-pointer",outcome:"skipped",message:"Claude Code plugin steps skipped \u2014 no git root safe to write into",level:"silent"});return}try{r(wv(e,yi(ye.join(e,".claude","settings.json"))));let o=Sr({projectPath:e}).kind==="installed"?await xv():nd;r(...Pv(ui({projectRoot:e,cliIsStale:()=>o.stale}),o)),r(kv(e,Dr(e)))}catch(t){let o=t instanceof Error?t.message:String(t);r({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${o}). Run by hand: ${We}`,level:"warn"})}},Tv=(e,r)=>{let t=ye.relative(e,r.path);if(r.status!=="ok"&&r.status!=="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${t} could not be read as JSON \u2014 ik-mcp entries not synced`,level:"warn"}];if(r.status==="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${t} could not be written \u2014 ik-mcp entries not synced`,level:"warn"}];let o=[];for(let n of r.entries)n.status==="written"?o.push({step:"mcp-proxies",outcome:"written",message:` updated ${t} \u2014 ik-mcp "${n.name}"`,level:"info"}):(n.status==="conflict"||n.status==="stale")&&o.push({step:"mcp-proxies",outcome:"warned",message:` ${n.message}`,level:"warn"});return o},Cv=async e=>{if(e===null)return[];if(!ae.existsSync(ye.join(e,"infra-kit.json")))return[{step:"mcp-proxies",outcome:"skipped",message:"no infra-kit.json \u2014 no ik-mcp entries to derive",level:"silent"}];let r;try{r=(await x()).mcp}catch(t){let o=t instanceof Error?t.message:String(t);return[{step:"mcp-proxies",outcome:"skipped",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o.split(`
376
+ `)[0]??o})`,level:"warn"}]}return!r||Object.keys(r).length===0?[]:Tv(e,Jn({projectRoot:e,proxies:r,write:!0}))},Av=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"),Iv=e=>{let r=ir(e,Lr,cr);if(r!==null)return r;for(let[a,c]of cv){let p=ir(e,a,c);if(p!==null)return p}let t=e.indexOf(lv);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
377
+ `),s=0;for(;s<n.length&&Av(n[s]);)s++;let i=n.slice(s).join(`
378
+ `);return o+(i?`
379
+ ${i}`:"")},sd=()=>{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(`
380
+ `)},id=()=>`${Lr}
381
+ ${sd()}
382
+ ${cr}`,qi=()=>["# Inherit this terminal's infra-kit session env into every zsh it spawns, interactive or not.","# A fresh terminal has no session yet (it is minted in .zshrc, after this file) and skips.","# Only the canonical 8-hex id .zshrc mints is honoured. Load wins a tie with clear, as the","# .zshrc precmd gate does. Prints nothing of its own.",'if [[ -n "${INFRA_KIT_SESSION:-}" ]]; then'," () {"," emulate -L zsh -o extendedglob",' [[ "${INFRA_KIT_SESSION:-}" == [0-9a-f](#c8) ]] || return',' local _ik_dir="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit/$INFRA_KIT_SESSION"',' local _ik_load="$_ik_dir/env-load.sh" _ik_clear="$_ik_dir/env-clear.sh"',' if [[ -r "$_ik_load" && ! "$_ik_clear" -nt "$_ik_load" ]]; then',' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
383
+ `),Yi=()=>`${Lr}
384
+ ${qi()}
385
+ ${cr}`;import $v from"node:fs/promises";var Zi=async(e,r)=>{if(!r)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let t=await $v.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 n=Object.keys(o);return{hasOverrides:n.length>0,overrideKeys:n,unreadable:!1}}catch{return{hasOverrides:!1,overrideKeys:[],unreadable:!0}}},Xi=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import Dv from"node:fs";import Ov from"node:os";import ad from"node:path";import Nv from"node:process";import{$ as _v}from"zx";var Wr=()=>_v({quiet:!0});var Mv=()=>[ad.join(Ov.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],jv=async e=>{try{return(await Wr()`command -v ${e}`).stdout.trim()||null}catch{return null}},So=()=>({runCommand:async e=>{let r=await Wr()`${e}`;return{stdout:`${r.stdout}
386
+ ${r.stderr}`}},resolveBinPath:async e=>{let r=await jv(e);return r!==null?r:Mv().map(t=>ad.join(t,e)).find(t=>Dv.existsSync(t))??null},realpath:de,platform:Nv.platform});var Jr=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Co=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,Ao=["darwin","linux"],ea=e=>r=>xs(r,e)?"homebrew":"unknown",ts=(e,r)=>t=>t===null?null:r(e(t),t),dd=e=>ts(ea(e.kegName),r=>r==="homebrew"?Jr(["brew","upgrade",e.brewFormula]):null),cd=e=>gn(e,"Homebrew")||gn(e,"homebrew")?"homebrew":"unknown",Fv={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Co,platforms:Ao,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:cd,updateFor:ts(cd,e=>e==="homebrew"?Jr(["brew","update"]):null)},Qi={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},ud="https://awscli.amazonaws.com/v2/install.sh",md={steps:[["/bin/bash","-c",`curl -fsSL ${ud} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},Lv="/usr/local/aws-cli",Wv=e=>Qt(Lv,e,de)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${ud} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:md,ld=e=>xs(e,Qi.kegName)?"homebrew":gn(e,"aws-cli")?"script":"unknown",Jv={id:"aws",binName:"aws",...Qi,probeArgv:["aws","--version"],versionFrom:Co,platforms:Ao,prerequisites:[],bootstrapInstall:md,identify:ld,updateFor:ts(ld,(e,r)=>e==="homebrew"?Jr(["brew","upgrade",Qi.brewFormula]):e==="script"?Wv(r):null)},es={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},Vv={id:"gh",binName:"gh",...es,probeArgv:["gh","--version"],versionFrom:Co,platforms:Ao,prerequisites:["brew"],bootstrapInstall:Jr(["brew","install",es.brewInstallSpec]),identify:ea(es.kegName),updateFor:dd(es)},rs={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},Bv={id:"doppler",binName:"doppler",...rs,probeArgv:["doppler","--version"],versionFrom:Co,platforms:Ao,prerequisites:["brew"],bootstrapInstall:Jr(["brew","install","gnupg"],["brew","install",rs.brewInstallSpec]),identify:ea(rs.kegName),updateFor:dd(rs)},To="portless",pd=e=>Uc(e,To)===null?"unknown":"npm",Gv={id:"portless",binName:To,npmPackage:To,probeArgv:["portless","--version"],versionFrom:Co,platforms:[...Ao,"win32"],prerequisites:[],bootstrapInstall:Jr(["npm","install","-g",To]),identify:pd,updateFor:ts(pd,e=>e==="npm"?Jr(["npm","install","-g",`${To}@latest`]):null)},ra={brew:Fv,aws:Jv,gh:Vv,doppler:Bv,portless:Gv},Vr=Object.keys(ra),Ee=e=>ra[e],ta=(e,r)=>e.platforms.includes(r),oa=e=>{let r=[],t=new Set,o=(n,s)=>{if(s.includes(n))throw new Error(`dependency cycle: ${[...s,n].join(" -> ")}`);if(!t.has(n)){t.add(n);for(let i of Ee(n).prerequisites)o(i,[...s,n]);r.push(n)}};for(let n of e)o(n,[]);return r};var fd=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),gd=async(e,r)=>{try{return await e(r)}catch{return null}},Uv=async(e,r)=>{try{let t=await e.resolveBinPath(r);return t==null?null:e.realpath(t)}catch{return null}},hd=async(e,r)=>{if(!ta(e,r.platform))return fd(e.id);let t=await gd(r.runCommand,e.probeArgv),o=await Uv(r,e.binName);if(t==null&&o==null)return fd(e.id);let n=t??(o==null?null:await gd(r.runCommand,[o,...e.probeArgv.slice(1)]));return{id:e.id,present:!0,onPath:t!=null,binRealPath:o,version:n==null?null:e.versionFrom(n.stdout),manager:o==null?"unknown":e.identify(o)}},Io=async(e,r)=>Promise.all(e.map(t=>hd(Ee(t),r)));import{$ as ey}from"zx";import _o from"node:process";var Kv="x-seraph-loginreason",Hv="AUTHENTICATED_FAILED",zv=(e,r=160)=>{let t=e.split(`
387
+ `,1)[0].trim();return t.length>r?`${t.slice(0,r)}\u2026`:t},yd=(e,r)=>r===Hv||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",vd=(e,r)=>e==="auth"?`Jira rejected the credentials (HTTP ${r}) \u2014 check JIRA_EMAIL and JIRA_TOKEN; Atlassian API tokens expire`:e==="forbidden"?`Jira authenticated the account but refused the operation (HTTP ${r}) \u2014 the account lacks permission on this project`:e==="not-found-or-forbidden"?`Jira returned HTTP ${r}: either JIRA_PROJECT_ID does not exist, or these credentials cannot browse it, or the Authorization header was malformed and the request went out anonymous`:`Jira returned HTTP ${r}`,Dt=class extends Error{status;kind;body;context;constructor(r){let t=yd(r.status,r.seraphLoginReason),o=zv(r.body);super(o===""?`${r.context}: ${vd(t,r.status)}`:`${r.context}: ${vd(t,r.status)}. Jira said: ${o}`),this.name="JiraApiError",this.status=r.status,this.kind=t,this.body=r.body,this.context=r.context}},$o=e=>e instanceof Dt,wd=e=>e.headers.get(Kv);var Ot=async(e,r)=>{if(e.ok)return;let t=await e.text(),o=new Dt({status:e.status,seraphLoginReason:wd(e),body:t,context:r});throw l.debug({status:e.status,kind:o.kind,body:t},r),o},lr=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,na=async(e,r)=>{let{baseUrl:t,token:o,email:n,projectId:s}=r,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1},a=`${t}/rest/api/3/version`,c=btoa(`${n}:${o}`),p=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Ot(p,"Failed to create Jira version"),{success:!0,version:await p.json()}},Nt=async e=>{let{baseUrl:r,token:t,email:o,projectId:n}=e,s=`${r}/rest/api/3/project/${n}/versions`,i=btoa(`${o}:${t}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await Ot(a,"Failed to get Jira project versions"),await a.json()},Ke=async(e,r)=>(await Nt(r)).find(n=>n.name===e)||null,Mt=async(e,r)=>{let{baseUrl:t,token:o,email:n}=r,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${t}/rest/api/3/version/${e.versionId}`,a=btoa(`${n}:${o}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});return await Ot(c,"Failed to update Jira version"),{success:!0,version:await c.json()}},sa=async(e,r)=>{let{versionName:t}=e,o=await Ke(t,r);if(!o)throw new Error(`Version "${t}" not found in Jira project`);return await Mt({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)},jt=async()=>{let e=_o.env.JIRA_BASE_URL,r=_o.env.JIRA_TOKEN||_o.env.JIRA_API_TOKEN,t=_o.env.JIRA_PROJECT_ID,o=_o.env.JIRA_EMAIL,n=[];if(e||n.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||n.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||n.push("JIRA_PROJECT_ID (numeric project ID)"),o||n.push("JIRA_EMAIL (your Jira email address)"),n.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...n.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
388
+ `);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},He=async()=>{try{return await jt()}catch(e){return l.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var os=async(e,r)=>{let{baseUrl:t,token:o,email:n}=r,s=`${t}/rest/api/3/version/${e}/relatedIssueCounts`,i=btoa(`${n}:${o}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});await Ot(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},ia=async(e,r)=>{let{baseUrl:t,token:o,email:n}=r,s={};e.moveFixIssuesTo!==void 0&&(s.moveFixIssuesTo=e.moveFixIssuesTo),e.moveAffectedIssuesTo!==void 0&&(s.moveAffectedIssuesTo=e.moveAffectedIssuesTo);let i=`${t}/rest/api/3/version/${e.versionId}/removeAndSwap`,a=btoa(`${n}:${o}`),c=await fetch(i,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await Ot(c,"Failed to remove Jira version")};var pr=e=>e.slice(1).split(".").map(Number),Ft=e=>[...e].sort((r,t)=>{let[o,n,s]=pr(r),[i,a,c]=pr(t);return o!==i?(o??0)-(i??0):n!==a?(n??0)-(a??0):(s??0)-(c??0)});var bd="next",qv=/^v?(\d+)\.(\d+)\.(\d+)$/,Yv=e=>e.replace(/^.*release\//,""),ca=e=>{let r=Yv(e.trim()),t=qv.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},kd=e=>`${e[0]}.${e[1]}.${e[2]}`,la=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=ca(n);if(!s)continue;let i=kd(s);o.has(i)||(o.add(i),t.push(s))}return Ft(t.map(n=>kd(n))).map(n=>pr(`v${n}`))},Br=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},pa=(e,r)=>{if(e.length===0)throw new Br;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,a=e.reduce((c,p)=>p[0]===s&&p[1]===i?Math.max(c,p[2]):c,0);return`${s}.${i}.${a+1}`}let[o,n]=t;return`${o}.${n+1}.0`},Lt=(e,r)=>{try{return pa(e,r)}catch(t){if(t instanceof Br)return null;throw t}},da=e=>e.trim().toLowerCase()===bd,ns=e=>da(e)||ca(e)!==null?{version:e}:{name:e},Zv=e=>e==="regular"||e==="hotfix",Rd=e=>"name"in e,Xv=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":"),o=r,n="regular",s="";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();s=c===-1?"":a.slice(c+1).trim();let d=p.toLowerCase();if(!Zv(d))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);n=d}let i={...ns(o),type:n};return s!==""&&(i.description=s),i},ua=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},aa=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Qv=e=>{let r=e.name.trim();return wn(r),aa({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},ma=(e,r)=>{let t=[...r];return e.map(o=>{if(Rd(o))return Qv(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(da(n)){let a=pa(t,o.type);return t.push(pr(`v${a}`)),aa({id:ke(a),type:o.type},o.description)}let s=ca(n);if(!s)throw new Error(`Invalid version "${n}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return t.push(s),aa({id:ke(i),type:o.type},o.description)})},fa=e=>e.some(r=>!Rd(r)&&da(r.version));var ry=e=>e.split(`
389
+ `).map(r=>{let t=r.indexOf(" ");return t===-1?null:j(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),ty=async()=>{let e=await ey({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return ry(e.stdout)},oy=async()=>{let e=await He();return e?(await Nt(e)).map(t=>t.name):[]},Do=async()=>{let[e,r]=await Promise.allSettled([ty(),oy()]);return e.status==="rejected"&&l.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&l.warn({err:r.reason},"Failed to fetch Jira versions; continuing without them"),la({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};import cy from"node:fs";import ly from"node:path";var ga=[".claude/settings.json",".claude/settings.local.json"],py=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],dy=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),uy=e=>{let r=e.trim();if(r==="Bash")return"*";let t=/^Bash\((.*)\)$/s.exec(r);if(t===null)return null;let o=t[1]??"";return o.endsWith(":*")?`${o.slice(0,-2)}*`:o},my=(e,r)=>{let t=e.indexOf("*");if(t===-1)return e===r||e.startsWith(`${r} `);let o=e.slice(0,t);return new RegExp(`^${e.split("*").map(dy).join(".*")}$`,"s").test(r)||o===r||o.startsWith(`${r} `)},fy=e=>{let r=e.groupPath.join(" ");return r===e.cliName?[r]:[r,e.cliName]},gy=()=>Wt.filter(e=>e.mutating),hy=e=>{let r=uy(e);return r===null?[]:gy().filter(t=>py.some(o=>fy(t).some(n=>my(r,`${o} ${n}`)))).map(t=>t.groupPath.join(" "))},vy=(e,r)=>{let t;try{t=cy.readFileSync(ly.join(e,r),"utf-8")}catch(i){return i.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",file:r}}let o;try{o=JSON.parse(t)}catch{return{kind:"unreadable",file:r}}let n=o?.permissions;if(n==null)return{kind:"read",patterns:[]};let s=n.allow;return s===void 0?{kind:"read",patterns:[]}:Array.isArray(s)?{kind:"read",patterns:s.filter(i=>typeof i=="string")}:{kind:"unreadable",file:r}},Ed=e=>{let r={present:[],unreadable:[],hits:[]};for(let t of ga){let o=vy(e,t);if(o.kind!=="absent"){if(r.present.push(t),o.kind==="unreadable"){r.unreadable.push(t);continue}for(let n of o.patterns){let s=hy(n);s.length>0&&r.hits.push({file:t,pattern:n,commands:s})}}}return r};var wy=["brew","gh","doppler","aws"],ky=async e=>{let r=await Io(wy,e);return new Map(r.map(t=>[t.id,{manager:t.manager,version:t.version,present:t.present,onPath:t.onPath}]))},ze=async(e,r,t,o)=>{try{return await Wr()`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Dd=(e,r,t,o)=>{let n=H.join(_d.homedir(),r),s="Run: infra-kit setup --skip-tools";if(!J.existsSync(n))return{name:e,status:"fail",message:`~/${r} not found. ${s}`};let i=J.readFileSync(n,"utf-8"),a=i.indexOf(Lr),c=i.indexOf(cr);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${t} block missing from ~/${r}. ${s}`}:i.slice(a,c+cr.length).trim()!==o.trim()?{name:e,status:"fail",message:`infra-kit ${t} block in ~/${r} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${t} block in ~/${r} is up to date`}},by=()=>Dd("zshrc init block",".zshrc","shell",id()),Ry=()=>Dd("zshenv session block",".zshenv","session-env",Yi()),Ey=async()=>{let e="warm cache",r;try{r=await R()}catch{return{name:e,status:"pass",message:"warm cache: not a git project"}}let t=Ge(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let o=H.join(Rr(t),pe);if(!J.existsSync(o))return{name:e,status:"pass",message:"warm cache: none yet (populated on next auto-load)"};let n=Math.floor((Date.now()-J.statSync(o).mtimeMs)/1e3),s=Math.floor(n/60),i=Math.floor(Xt/60);return n>=Xt?{name:e,status:"pass",message:`warm cache: present but stale (${s}m old, TTL ${i}m) \u2014 will refresh`}:{name:e,status:"pass",message:`warm cache: present, ${s}m old`}},Py=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await R(),t=H.join(r,"pnpm-workspace.yaml");if(!J.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=J.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}`}}},xy=async()=>{try{return lt(),{config:await x(),error:null}}catch(e){return{config:null,error:e}}},Sy=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)"}},Ty=384,ha=448,Cy=e=>e.map(r=>{let t=r.source===null?"no token":`token (${r.source})`;return`${r.env}: ${t}`}).join(", "),Ay=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}}})),Iy=async(e,r={})=>{let t="env tokens configured",o=r.readStore??ne,n=r.resolveToken??Pt;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let s;try{s=await o()}catch(m){return{name:t,status:"fail",message:`Token store unreadable \u2014 ${m.message}`}}let i=await Mr(),a=e.config.envAutoLoad?.config,c=a&&!i.includes(a)?[...i,a]:i,p=await Ay(c,n),d=Cy(p);if(a===void 0)return{name:t,status:"pass",message:`No envAutoLoad configured \u2014 no env is load-bearing. ${d}`};let u=p.find(m=>m.env===a);return!u||u.source===null?s===null||Object.keys(s.envs).length===0?{name:t,status:"pass",message:"Skipped \u2014 there is no token store to read (see tokens.json present)"}:{name:t,status:"fail",message:`No Doppler service token for the auto-load env "${a}" \u2014 your shell env will not load. Fix: run \`infra-kit env-token-set ${a}\`. ${d}`}:{name:t,status:"pass",message:`auto-load env "${a}": token (${u.source}). ${d}`}},$y={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)"}},_y=async(e,r={})=>{let t="env token valid",o=r.resolveToken??Pt,n=r.probe??bo;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let s=e.config.envAutoLoad?.config;if(s===void 0)return{name:t,status:"pass",message:"Skipped \u2014 no envAutoLoad env to probe"};let i;try{i=(await o(s)).token}catch{return{name:t,status:"pass",message:`Skipped \u2014 no token for env "${s}" (see env tokens configured)`}}let a=e.config.envManagement.config.name,c=await n({childEnv:$t(i),project:a,config:s}),p=$y[c.outcome],d=c.outcome==="revoked"||c.outcome==="mis-scoped"?` Fix: run \`infra-kit env-token-set ${s}\` with a token scoped to "${s}".`:"";return{name:t,status:p.status,message:`The token for env "${s}" (project "${a}") is ${p.describe}.${d}`}},Dy=()=>dr.env[K]||void 0,Oy=async(e={})=>{let r="tokens.json present",t=e.readStore??ne,o=e.storePath??oo;if((e.readEnvToken??Dy)())return{name:r,status:"pass",message:`Skipped \u2014 ${K} is set; that channel takes precedence over the store`};let s;try{s=b(await o())}catch{return{name:r,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}let i;try{i=await t()}catch{return{name:r,status:"pass",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:r,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${K} instead.`}}return{name:r,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Oo=(e,r)=>{let t=r(e);return t===null?null:t.mode&511},Ny=async(e,r={})=>{let t="tokens.json perms",o=r.storePath??oo,n=r.statPath??My,s=r.chmodPath??J.chmodSync,i;try{i=await o()}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(Oo(i,n)===null)return{name:t,status:"pass",message:`No store to protect at ${b(i)} (see tokens.json present)`};let a=H.dirname(i),c=H.dirname(a),p=H.dirname(c),u=[{target:p,expected:ha,actual:Oo(p,n)},{target:c,expected:ha,actual:Oo(c,n)},{target:a,expected:ha,actual:Oo(a,n)},{target:i,expected:Ty,actual:Oo(i,n)}].filter(v=>v.actual!==null&&v.actual!==v.expected);if(u.length===0)return{name:t,status:"pass",message:`${b(i)} is 0600 (0700 dirs)`};let m=u.map(v=>`${b(v.target)} is ${Pd(v.actual)}, expected ${Pd(v.expected)}`).join("; ");if(!e)return{name:t,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let v of u)s(v.target,v.expected);return{name:t,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},Pd=e=>`0${e.toString(8).padStart(3,"0")}`,My=e=>{try{return J.statSync(e)}catch{return null}},jy=async()=>{let e="user override path";try{let r=await ee(),t=J.existsSync(r.userProject),o=await Zi(r.userProject,t),n=t?Xi(o):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${b(r.userProject)} ${n} \u2014 project: ${r.projectName}`}}catch(r){return{name:e,status:"fail",message:r.message}}},Fy=async()=>{let e="legacy user-global config",r;try{r=await ee()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=H.join(H.dirname(r.userGlobal),"config.json");return J.existsSync(t)?J.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 setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Ly={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/"}},Wy=async e=>{let r=Ly[e];try{return await Wr()`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},Jy=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=Ce(e.config).map(s=>s.provider);if(t.length===0)return{name:r,status:"pass",message:"No IDE configured (ide unset)"};let o=await Promise.all(t.map(s=>Wy(s))),n=o.filter(s=>!s.ok);return n.length===0?{name:r,status:"pass",message:`Installed: ${o.map(s=>s.label).join(", ")}`}:{name:r,status:"fail",message:n.map(s=>s.failMsg).join("; ")}},xd=/^\d+\.\d+\.\d+$/,Vy=(e,r)=>e===r||!xd.test(e)||!xd.test(r)?!1:Ft([`v${e}`,`v${r}`])[0]===`v${e}`,By=async(e,r)=>{let t;try{t=await ie(e)}catch{return[]}let o=[];for(let n of t){let s=Ar(Ir(H.join(n,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&Vy(s.version,r)&&o.push(s.version)}return o},Gy=async(e,r)=>{let t=await By(e,r);if(t.length===0)return"";let o=Ft(t.map(n=>`v${n}`))[0].slice(1);return` \u2014 ${t.length} package guidance blocks were generated by an older infra-kit (oldest ${o}, current ${r}) \u2014 run: infra-kit audit --fix --all`},Uy=async()=>{let e;try{e=(await ee()).main}catch{return[]}if(!J.existsSync(e))return[];let r=H.dirname(e),t=H.join(r,"CLAUDE.md"),o=J.existsSync(t)?J.readFileSync(t,"utf-8"):"",n=Ie(o,fe,$e),s=n?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",i=await Gy(r,q.version);return[{name:"CLAUDE.md block",status:n?"pass":"fail",message:`${s}${i}`}]},Ky=async()=>{try{let e=(await ee()).main;return J.existsSync(e)?H.dirname(e):null}catch{return null}},Hy=e=>{let r=kl();return r===null||!no(r,e)?"":` \u2014 plugin ${r} is fetched but not applied. Run: ${kt}`},zy=e=>{let r=e.kind==="installed"?xn(e.installation):null;return{name:"plugin version",status:r===null?"fail":"pass",message:r===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${F} version ${r}${Hy(r)}`}},Sd=3,Td=(e,r)=>de(e)===de(r),qy=e=>{if(e===void 0||e.gitRoot===null)return"";let r=b(e.gitRoot);if(e.projectDir!==null){if(Td(e.projectDir,e.gitRoot))return"";let t=Qt(e.gitRoot,de(e.projectDir),de)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${b(e.projectDir)}, ${t}: the plugin and this repo's .claude/settings.json hooks load only from ${r} (measured); restart Claude Code there`}return Td(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${b(e.cwd)} rather than ${r}, it loaded neither the plugin nor this repo's hooks; launch it at ${r}`},Yy=(e,r)=>{let t="plugin installed",o=qy(r);if(e.kind==="installed"){let{scope:c,projectPath:p}=e.installation,d=p===null?"":`, ${b(p)}`;return{name:t,status:"pass",message:`Plugin ${F} installed (${c??"unknown"} scope${d})${o}`}}if(e.kind==="absent")return{name:t,status:"fail",message:`Plugin ${F} is not installed. Run: ${We}${o}`};let n=e.installations.map(c=>c.projectPath===null?"(unnamed project)":b(c.projectPath)),s=n.length-Sd,i=s>0?` and ${s} more`:"",a=`${n.slice(0,Sd).join(", ")}${i}`;return{name:t,status:"fail",message:`Plugin ${F} is installed for ${a} only, not this project. Run: ${We}${o}`}},Zy=()=>ze("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),Xy=(e,...r)=>{try{return JSON.parse(J.readFileSync(H.join(e,...r),"utf-8"))}catch{return null}},Qy=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let r=xn(e.installation),{installPath:t}=e.installation;if(t===null)return{kind:"skills-only",version:r};let o=Xy(t,U),n=o!==null&&typeof o=="object"?o[Re]:void 0;return n==null||typeof n!="object"?{kind:"skills-only",version:r}:{kind:"stale-server",version:r,keys:Object.keys(n)}},Cd=e=>`Plugin ${F} ${e===null?"(version unreadable)":e}`,ew=e=>{let r="plugin MCP server";if(e.kind==="not-installed")return{name:r,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${We}`};if(e.kind==="stale-server"){let t=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:r,status:"pass",message:`${Cd(e.version)} still carries an MCP server in its ${U}${t} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${kt}), then restart Claude Code`}}return{name:r,status:"pass",message:`${Cd(e.version)} is skills-only \u2014 no ${U}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},rw=(e,r)=>{let t=Sr(e===null?{}:{projectPath:e}),o=to();return[{name:"marketplace registered",status:o?"pass":"fail",message:o?`Marketplace ${B} is known to Claude Code`:`Marketplace ${B} is not registered. Run: claude plugin marketplace add ${tr}`},Yy(t,r),zy(t),ew(Qy(t)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${q.version}`}]},Od=e=>`${U} still registers "${e}" \u2014 delete this key: the plugin no longer serves an MCP server, and the entry only spawns \`infra-kit mcp\`, a compatibility stub kept alive for repos that have not deleted it yet. Delete the "${e}" entry from ${U} by hand in a PR, keeping its siblings (\`claude mcp remove ${e} --scope project\` also works but re-indents the file)`,tw={stale:Od(B),absent:`${U} carries no "${B}" key \u2014 nothing spawns the retired server`,"missing-file":`no ${U} at the repo root \u2014 nothing spawns the retired server`,unparseable:`Could not read ${Re} from ${U} \u2014 fix the JSON and re-run`},ow=new Set(["absent","missing-file","stale","wrong-key"]),nw=e=>{let r="MCP server key",t=Dr(e);return t.kind==="wrong-key"?{name:r,status:"pass",message:Od(t.key)}:{name:r,status:ow.has(t.kind)?"pass":"fail",message:tw[t.kind]}},sw=({env:e,stdinIsTTY:r,flag:t})=>{let o=e.INFRA_KIT_AGENT===void 0?"unset":`= "${e.INFRA_KIT_AGENT}"`;return[`CLAUDECODE ${e.CLAUDECODE===void 0?"unset":"set"}`,`INFRA_KIT_AGENT ${o}`,`stdin ${r?"is a TTY":"is not a TTY"}`,`--agent ${t?"passed":"not passed"}`].join(", ")},iw=e=>{let r="Agent mode",t=ll(e),o=sw(e);return{name:r,status:"pass",message:`${t===null?"human":"agent"} \u2014 ${t==="flag"?"the --agent flag, which beats every environment value":e.env.INFRA_KIT_AGENT==="1"?"INFRA_KIT_AGENT=1":t==="env"?"CLAUDECODE is set and stdin is not a TTY":e.env.CLAUDECODE!==void 0&&e.stdinIsTTY?"CLAUDECODE is set but stdin is a TTY, so this is a terminal Claude Code spawned for a person":e.env.INFRA_KIT_AGENT==="0"?"INFRA_KIT_AGENT=0 suppresses the CLAUDECODE heuristic":"no source fires; pass --agent or set INFRA_KIT_AGENT=1 to drive this CLI as an agent"} (${o})`}},Ad=4,aw=e=>{let r=e.slice(0,Ad).join(", "),t=e.length-Ad;return t>0?`${r} +${t} more`:r},cw=e=>{let r="Agent allowlist",{present:t,unreadable:o,hits:n}=Ed(e);if(n.length>0){let s=n.map(i=>`${i.file} allows "${i.pattern}", which reaches ${i.commands.length} mutating infra-kit command${i.commands.length===1?"":"s"} (${aw(i.commands)})`);return{name:r,status:"warn",message:`${s.join("; ")} \u2014 a prefix allow lets an agent run the --yes re-run of a mutating command unprompted; narrow it to read-only argv (e.g. Bash(infra-kit release list:*)) so the host prompts for the rest`}}return o.length>0?{name:r,status:"warn",message:`Could not read permissions.allow from ${o.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:t.length===0?{name:r,status:"pass",message:`no ${ga.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:r,status:"pass",message:`no permissions.allow pattern in ${t.join(" or ")} reaches a mutating infra-kit command`}},Nd=e=>Ss(["trust"],{bin:e}),lw=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Id="ERR_TLS_CERT_ALTNAME_INVALID",pw=async(e,r,t)=>{let o=`portless serving TLS on :${or}`;return await e(or,!0)?{name:o,status:"pass",message:`portless is serving HTTPS on :${or}`}:{name:o,status:"fail",message:`No portless daemon is serving HTTPS on :${or}. Install it once (needs root): \`${Pr(r,t)}\`.`}},dw=async(e,r,t,o,n)=>{let s="portless CA chain valid",i=["localhost",...r.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(or,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${b(t)} (${i.join(", ")})`};let p=c.map(d=>d.result.ok?"":d.result.code);return p.includes(Id)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Id} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:p.some(d=>lw.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${b(t)}. Its CA was regenerated \u2014 run \`${Nd(o)}\`, or reinstall: \`${Pr(o,n)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${p.join(", ")})`}},uw=(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: \`${Nd(t)}\` (no sudo needed).`}},mw=async(e,r,t)=>{let o="portless routes";if(e.length===0)return{name:o,status:"pass",message:"No portless routes registered"};let s=(await Promise.all(e.map(async i=>({route:i,live:await r(i.port)})))).filter(i=>!i.live).map(i=>i.route.name);return s.length===0?{name:o,status:"pass",message:`${e.length} portless route(s), all live`}:{name:o,status:"fail",message:`${s.length} stale portless route(s): ${s.join(", ")}. Remove with \`${Ss(["alias","--remove","<name>"],{bin:t})}\`.`}},Gr="portless service target",ss=e=>({name:Gr,status:"pass",message:`Warning \u2014 ${e}`}),fw=e=>e==="darwin"?Xc:e==="linux"?Qc:null,gw=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Zc}`:`sudo systemctl restart ${el}`,hw="/bin/ps",vw=e=>{try{let r=yy(hw,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(r.status!==0)return null;let t=new Date(r.stdout.trim());return Number.isNaN(t.getTime())?null:t}catch{return null}},$d=e=>{try{return J.readFileSync(e,"utf-8")}catch{return null}},yw=e=>{try{return J.statSync(e).mtime}catch{return null}},Md=(e,r)=>({platform:e.platform??dr.platform,readServiceFile:e.readServiceFile??$d,readFile:e.readFile??$d,exists:e.exists??J.existsSync,realpath:e.realpath??de,mtime:e.mtime??yw,execPath:e.execPath??dr.execPath,home:e.home??_d.homedir(),cwd:e.cwd??dr.cwd(),repoRoot:e.repoRoot??Po,stateDir:(e.stateDir??tl)(),processStartTime:e.processStartTime??vw,bin:r}),ww=(e,r)=>{let t=r.readFile(H.join(e,"package.json"));try{let o=t===null?null:re.object({version:re.string()}).safeParse(JSON.parse(t));return o?.success===!0?o.data.version:"?"}catch{return"?"}},kw=(e,r)=>{let t=Number.parseInt(r.readFile(H.join(r.stateDir,"proxy.pid"))?.trim()??"",10);if(!Number.isInteger(t)||t<=0)return!1;let o=r.processStartTime(t),n=r.mtime(H.join(e,"package.json"));return o!==null&&n!==null&&o.getTime()<n.getTime()},bw=async(e,r)=>{let t=r.realpath(r.cwd);return t===r.realpath(r.home)?!1:Qt(await r.repoRoot()??t,e,r.realpath)},Jt=e=>({state:"drifted",row:e}),Rw=async(e,r,t)=>{let o=Pr(t.bin,t);if(!t.exists(e))return Jt({name:Gr,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded). Re-run: \`${o}\``});let n=H.join(Cs(t.home),"dist","cli.js");if(r!==n)return Jt(ss(`The service points at \`${r}\`, a version-specific location. Re-run once to switch it to the stable link: \`${o}\``));if(vn(t.home,t.exists)===null)return Jt({name:Gr,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=t.realpath(Cs(t.home));if(await bw(s,t))return Jt({name:Gr,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${o}\``});if(t.realpath(e)!==t.realpath(t.execPath))return Jt(ss(`The service runs \`${e}\`; infra-kit runs \`${t.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${o}\``));let i=ww(s,t);return kw(s,t)?{state:"converged",row:ss(`The running daemon predates portless ${i} that \`dev\` will talk to. Restart it: \`${gw(t.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Gr,status:"pass",message:`service runs \`${e}\` + stable link \u2192 portless ${i}`}}},jd=async e=>{let r=fw(e.platform);if(r===null)return{state:"absent",row:{name:Gr,status:"pass",message:"Skipped \u2014 no portless OS service file on this platform"}};let t=e.readServiceFile(r);if(t===null)return{state:"absent",row:{name:Gr,status:"pass",message:`Skipped \u2014 the OS service is not installed (no ${r})`}};let[o,n]=bp(e.platform,t)??[];return o===void 0||n===void 0?Jt(ss(`could not parse ${r} \u2014 re-run \`${Pr(e.bin,e)}\` to rewrite it.`)):Rw(o,n,e)},Fd=async(e,r)=>(await jd(Md(e,r))).state,Ew=async(e={})=>{let r=e.resolveBin??Yc,t=e.isProxyServing??rl,o=e.handshake??sl,n=e.caTrusted??nl,s=e.routes??Ts,i=e.isListening??eo,a=(e.caPath??ol)(),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"},d=Md(e,c),u=s(),m=await pw(t,c,d),v=m.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await dw(o,u,a,c,d);return[p,(await jd(d)).row,m,v,uw(n(),a,c),await mw(u,i,c)]},Pw=async(e={})=>{let r="portless routes",t=e.routes??Ts,o=e.isListening??eo,n=e.devSessionRunning??hp,s=t();if(s.length===0)return{name:r,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await o(d.port)}))),{prunable:a,withheld:c}=gp(i,n());if(c.length>0)return{name:r,status:"fail",message:`${c.length} route(s) look stale (${c.join(", ")}), but a dev session is running \u2014 a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. Stop dev and re-run \`infra-kit doctor --fix\`.`};if(a.length===0)return{name:r,status:"pass",message:`${s.length} portless route(s), all live`};let p=e.removeAlias??il().removeAlias;for(let d of a)await p(d);return{name:r,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Ld=async(e={})=>{let r=await xy(),t=ky(e.probeDeps??So()),o=async(m,v)=>{let[f,k]=await Promise.all([v,t]),P=k.get(m);return P===void 0?f:{...f,detail:P}},n=await Promise.all([o("brew",ze("brew installed",Ee("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),o("gh",ze("gh installed",Ee("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),ze("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),o("doppler",ze("doppler installed",Ee("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),o("aws",ze("aws installed",Ee("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),ze("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),ze("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"),ze("terminal installed",["cmux","--version"],"Installed: cmux","cmux is not installed. Install from: https://cmux.com/"),Promise.resolve(by()),Promise.resolve(Ry()),Ey(),Py(),Promise.resolve(Sy(r)),Oy(),Iy(r),_y(r),Ny(e.fix??!1),jy(),Fy(),Jy(r)]),s=await Ew();if(e.fix){let m=await Pw(),v=s.findIndex(f=>f.name===m.name);v>=0?s[v]=m:s.push(m)}let i=await Ky(),a=await Po(),c={projectDir:dr.env.CLAUDE_PROJECT_DIR||null,cwd:dr.cwd(),gitRoot:a},p=[await Zy(),...rw(i,c),...a===null?[]:[nw(a)],iw({env:dr.env,stdinIsTTY:dr.stdin.isTTY===!0,flag:_.source==="flag"}),...a===null?[]:[cw(a)]],d=[...n,...s,...await Uy(),...p],u={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Ci.has(m.name),detail:m.detail})),allPassed:d.every(m=>m.status!=="fail"),cliVersion:q.version};return{content:y(JSON.stringify(u,null,2)),structuredContent:u}},va=w({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:re.array(re.object({name:re.string().describe("Name of the check"),status:re.enum(["pass","fail","warn"]).describe("Check result; warn is advisory and never fails the run"),message:re.string().describe("Details about the check result"),fixable:re.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:re.object({manager:re.string().describe("Which package manager owns this install, read from its resolved path"),version:re.string().nullable().describe("The version the tool reported, or null"),present:re.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:re.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:re.boolean().describe("Whether no check failed (warnings are advisory and do not count)"),cliVersion:re.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Ld()});import ya from"node:fs";import Wd from"node:path";import{z as Vt}from"zod";var xw=async e=>{let r="";try{r=await R()}catch{return}let t=Ge(r);t&&ji(t,e)},Sw=e=>[...e.map(r=>`unset ${r}`),`unset ${un}`,`unset ${ot}`,`unset ${nt}`,`unset ${mn}`,`unset ${st}`,`unset ${br}`,`export ${it}='1'`],Jd=async({purge:e=!1}={})=>{let r=at(),t=Wd.join(r,pe),o=ya.existsSync(t);if(!o&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await xw(e);let n=o?fn(t):[],s=Sw(n),i=Wd.resolve(r,dn);ya.mkdirSync(r,{recursive:!0,mode:448}),Er(i,`${s.join(`
390
+ `)}
391
+ `,384),o&&ya.rmSync(t,{force:!0});let a={filePath:i,variableCount:n.length,unsetStatements:s,purged:e};return{content:y(JSON.stringify(a,null,2)),structuredContent:a}},wa=w({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit setup` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Vt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Vt.string().describe("Path to the file that must be sourced to apply"),variableCount:Vt.number().describe("Number of variables cleared"),unsetStatements:Vt.array(Vt.string()).describe("Unset statements generated"),purged:Vt.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>Jd()});import Tw from"node:path";import Ur from"node:process";import{z as ur}from"zod";var Vd=async()=>{l.info("Environment session status:");let e=at(),r=Ur.env[kr],t=Tw.join(e,pe),o=0,n=0,s=Ur.env[ot]??null,i=Ur.env[nt]??null,a=Ur.env[st]??null,c=Ur.env[br]==="1",p=!!Ur.env[it];if(s){let u=fn(t);u.length>0&&(n=u.length,o=u.filter(f=>f in Ur.env).length);let m=a?.replace(/\.\d{3}Z$/,"")??null,v=c?"auto-loaded":"manually loaded";if(l.info(` ${s}: ${o} of ${n} vars loaded (${v}, project: ${i}, loadedAt: ${m}, session: ${r})
392
+ `),n>0&&o<n){let f=n-o;l.warn(` ${f} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else{let u=p?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";l.info(` Session ${r}: no env loaded${u}
393
+ `)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:a,autoLoaded:c,cleared:p};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},ka=w({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:ur.string().describe("Current terminal session ID"),sessionLoadedCount:ur.number().describe("Number of cached vars active in the current session"),sessionTotalCount:ur.number().describe("Total number of cached var names"),sessionConfig:ur.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:ur.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:ur.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:ur.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:ur.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:Vd});import Cw from"node:process";import{z as mr}from"zod";var Bd="****",ba=e=>typeof e!="string"||e.length<8?Bd:`${Bd}${e.slice(-4)}`;var Gd=(e,r,t)=>e.map(o=>{let n=t||r[o];return n?{env:o,source:t?`env:${K}`:"store",redactedToken:ba(n),present:!0}:{env:o,source:"-",redactedToken:"-",present:!1}}),Aw=["ENV","SOURCE","TOKEN","PRESENT"],Ud=(e,r)=>{let t=[...Aw,...r?["CHECK"]:[]],o=e.map(s=>[s.env,s.source,s.redactedToken,s.present?"yes":"no",...r?[s.status??"-"]:[]]),n=t.map((s,i)=>Math.max(s.length,...o.map(a=>(a[i]??"").length)));return[t,...o].map(s=>s.map((i,a)=>i.padEnd(n[a])).join(" ").trimEnd())},Kd=async({check:e}={})=>{let r=await Mr(),t=await ne(),o=Cw.env[K],n=Gd(r,t?.envs??{},o);if(e){let a=await Or();for(let c of n){if(!c.present)continue;let p=o||t.envs[c.env],d=await bo({childEnv:$t(p),project:a,config:c.env});c.status=d.outcome}}for(let a of Ud(n,!!e))l.info(a);let s=n.filter(a=>!a.present);s.length>0&&l.info(`
394
+ No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:n};return{content:y(JSON.stringify(i,null,2)),structuredContent:i}},Ra=w({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:mr.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:mr.array(mr.object({env:mr.string().describe("Environment / Doppler config name"),source:mr.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:mr.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:mr.boolean().describe("Whether a token is configured for this environment"),status:mr.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Kd});import{z as S}from"zod";import{$ as Uw}from"zx";import{$ as vO}from"zx";import{$ as Gt}from"zx";import{$ as Hd}from"zx";var Ea=async e=>{let{operation:r}=e;try{await Hd({quiet:!0})`git rev-parse --git-dir`}catch(t){throw new g(t,{operation:r,remediation:"run this from inside a git repository"})}try{await Hd({quiet:!0})`git remote get-url origin`}catch(t){throw new g(t,{operation:r,remediation:"this repository has no `origin` remote to fetch from or push to"})}},$w=4,Bt=async e=>{let{operation:r}=e,t=await ml();if(t.length===0)return;l.error(`working tree has uncommitted changes:
395
+ ${t.join(`
396
+ `)}`);let o=t.slice(0,$w),n=t.length-o.length,s=n>0?`${o.join(", ")} (+${n} more)`:o.join(", ");throw new g(void 0,{operation:r,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},No=async e=>{let{operation:r,base:t}=e;if(await ct()===t)return;let o=(await rr(await R())).find(n=>n.branch===t);if(o)throw new g(void 0,{operation:r,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${t}" is checked out in the worktree at ${o.path}`})},ce=async e=>{let{operation:r}=e;if(await gl())throw new g(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await Bt({operation:r})};import{$ as zd}from"zx";var qd="dev",fr=e=>e==="hotfix"?"main":"dev",Mo=(e,r)=>(r??"").trim()!==""?`${e}
397
+
398
+ ${r}`:`${e}
399
+ `,Pa=async(e="regular")=>{let r=fr(e),t=zd({quiet:!0});await t`git fetch origin`,await t`git switch ${r}`;try{await t`git pull --ff-only origin ${r}`}catch(o){let n=await zd({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${r}...${r}`,[s="?",i="?"]=n.exitCode===0?n.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new g(o,{operation:`fast-forward ${r} onto origin/${r}`,remediation:a?`your local ${r} has diverged \u2014 rebase or reset it to origin/${r}, then retry`:`check your access to origin and that ${r} tracks it, then retry`,...a?{stderrExcerpt:`local ${r} is ${i} commit(s) ahead and ${s} behind origin/${r}`}:{}})}return(await t`git rev-parse HEAD`).stdout.trim()},_w=async e=>{let{versionName:r,jiraConfig:t,description:o}=e,n=await Ke(r,t);if(!n)return(await na({name:r,projectId:t.projectId,description:o||"",released:!1,archived:!1},t)).version;if(n.released||n.archived)throw new g(void 0,{operation:`reuse Jira fix version "${r}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${r}" is already ${n.released?"released":"archived"}`});let s=o||"";return s!==""&&s!==(n.description??"")?(await Mt({versionId:n.id,description:s},t),{...n,description:s}):n},xa=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular",baseSha:s}=e,i=G(r),a=await _w({versionName:i,jiraConfig:t,description:o}),c=lr(t,a),p=await as({id:r,jiraVersionUrl:c,type:n,description:o,baseSha:s});return{version:W(r),type:n,branchName:p.branchName,prUrl:p.prUrl,jiraVersionUrl:c}},V=async()=>{let e=new Map,r=await He();if(!r)return e;try{let t=await Nt(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch(t){l.warn({err:t},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},jo=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},D=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",is=e=>e.flatMap(r=>{let t=j(r);return t?[{branch:r,id:t,label:W(t)}]:[]}),qe=e=>{try{return Se(ke(e))}catch(r){throw new g(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},Fo=e=>{if(e===qd)return qd;let r=j(e);return r?W(r):e},Kr=e=>e.flatMap(r=>{let t=j(r);return t?[W(t)]:[]}),Dw=(e,r)=>r?r.get(e)||"regular":void 0,te=e=>{let{branches:r,descriptions:t,types:o}=e;return is(r).map(({branch:n,id:s,label:i})=>({value:n,label:i,description:t.get(G(s)),type:Dw(n,o)}))};var Ow=e=>e.map(r=>({pr:r,id:j(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>ul(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),Lo=200,Yd=(e,r)=>{e.length<Lo||l.warn({source:r,limit:Lo},`\u26A0\uFE0F ${r} returned ${Lo} PRs \u2014 the page is full, so older release PRs may be missing`)},Nw=async()=>{let[e,r]=await Promise.all([Gt`gh pr list --limit ${Lo} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Gt`gh pr list --limit ${Lo} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),t=JSON.parse(e.stdout),o=JSON.parse(r.stdout);Yd(t,"release PR discovery (base dev)"),Yd(o,"hotfix PR discovery (base main)");let n=[...t,...o],s=new Set;return n.filter(i=>s.has(i.headRefName)?!1:(s.add(i.headRefName),!0))},Wo="find open release PRs",Zd=async()=>{try{let e=await Nw();if(e.length===0)throw new g(void 0,{operation:Wo,remediation:"open a release PR first, or check you are in the right repo"});return Ow(e)}catch(e){throw e instanceof g?e:(l.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},cs=async()=>(await Zd()).map(r=>r.headRefName),$=async()=>(await Zd()).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt})),ls=async e=>{let{branch:r,body:t}=e;try{await Gt({quiet:!0})`gh pr edit ${r} --body ${t}`}catch(o){throw l.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},Mw=async(e,r)=>{let t=Gt({quiet:!0,nothrow:!0}),o=await t`git ls-remote --heads origin ${e}`,n=o.exitCode!==0,s=o.stdout.trim().length>0;if(n||s){l.error({branchName:e},n?`could not reach origin to check whether ${e} was pushed \u2014 the branch is left in place; check with \`git ls-remote --heads origin ${e}\` before deleting anything`:`release branch ${e} exists on origin without a PR \u2014 left in place; delete it with \`git push origin --delete ${e}\` once you are sure`);return}await t`git switch ${r}`,(await t`git branch -D ${e}`).exitCode!==0&&l.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},as=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n,baseSha:s}=e,i=dl(r,o),a=fr(o),c=Gt({quiet:!0}),p=Se(r),d=Mo(t,n);try{await Bt({operation:`create release branch ${p}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new g(void 0,{operation:`create release branch ${p}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${u.slice(0,8)}`});await c`git checkout -b ${p}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${p}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${p}`;return{branchName:p,prUrl:m.stdout.trim()}}catch(m){throw await Mw(p,a),m}}catch(u){throw l.error({error:u,branchName:p},`Error creating release branch ${p}`),u}finally{await Gt({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as jw}from"zx";var Hr=async e=>{let r=await jw`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null};import Fw from"node:process";var Jo=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Xd=e=>{let r={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"};if(ue())throw new N({status:"argument_required",argument:e,agentMode:_.source},2,r);if(!Fw.stdin.isTTY)throw new g(void 0,r)},gr=async e=>{Xd("version");let{runBranchPicker:r}=await import("./boot-BL4EQMZV.js"),t=await r(e);if(t===null)throw new Jo;return t},Ut=async(e,r)=>{Xd("versions");let{runBranchMultiPicker:t}=await import("./boot-BL4EQMZV.js"),o=await t(e,r);if(o===null)throw new Jo;return o};import{$ as zr}from"zx";var Lw="Merge remote-tracking branch 'origin/dev' into ",Qd=e=>String(e.stderr??e.message??e).trim(),Ww=async e=>{try{return(await zr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
400
+ `).map(t=>t.trim()).filter(t=>t.length>0)}catch{return[]}},Jw=async(e,r)=>{let t=Qd(r),o=await Ww(e);return o.length>0?{status:"conflict",conflictPaths:o,reason:t}:await yl(e)?{status:"hook-failed",reason:t}:{status:"error",reason:t}},eu=async e=>{let{cwd:r,worktreePath:t,branches:o}=e,n=[],s=await ro(r,"origin/dev");if(!s)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 Vw({cwd:r,worktreePath:t,branch:i,devSha:s});n.push({...c,durationMs:Date.now()-a})}return n},Vw=async e=>{let{cwd:r,worktreePath:t,branch:o,devSha:n}=e,s=`origin/${o}`;if(!await ro(r,s))return{branch:o,status:"error",reason:`${s} does not exist on origin`};if(await Is(r,"origin/dev",s))return{branch:o,status:"up-to-date"};try{await $s(t),await zr({cwd:t,quiet:!0})`git checkout --detach ${s}`;let i=`${Lw}${o}`;await zr({cwd:t,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await zr({cwd:t,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:o,status:a===n?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:o,...await Jw(t,i)}}finally{await _s(t)}},ru=e=>e.flatMap(r=>r.mergeSha?[{branch:r.branch,sha:r.mergeSha}]:[]),tu="pnpm install --frozen-lockfile",ou=async e=>{let{worktreePath:r,refs:t,command:o}=e,n=[],s=new Map;for(let i of t)try{await $s(r),await zr({cwd:r,quiet:!0})`git checkout --detach ${i.sha}`,await zr({cwd:r,quiet:!0})`sh -c ${o}`,n.push(i)}catch(a){s.set(i.branch,Qd(a))}finally{await _s(r)}return{kept:n,failed:s}},Sa=async(e,r)=>{await zr({cwd:e,quiet:!0})`git fetch origin --prune`;let t=[],o=[];for(let n of r)await Is(e,"origin/dev",`origin/${n.branch}`)?o.push(n.branch):t.push(n);return{kept:t,nowUpToDate:o}};import Ta from"node:process";var ps=new Set,nu=e=>(ps.add(e),()=>{ps.delete(e)}),Bw=async()=>{for(let e of[...ps])try{await e()}catch(r){l.warn({error:r,msg:"cleanup failed during shutdown"})}ps.clear()},Gw=["SIGINT","SIGTERM"],mN=async(e,r={})=>{let{register:t=(i,a)=>{Ta.on(i,a)},unregister:o=(i,a)=>{Ta.off(i,a)},exit:n=i=>{Ta.exit(i)}}=r,s=new Map;for(let i of Gw){let a=()=>{Bw().then(()=>{n(Cl(i))})};s.set(i,a),t(i,a)}try{return await e()}finally{for(let[i,a]of s)o(i,a)}};var Kw=e=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[]}),iu=e=>({content:y(JSON.stringify(e,null,2)),structuredContent:e}),su=new Set(["up-to-date","fast-forward","merged"]),Hw=(e,r)=>{let t=(Array.isArray(e)?e:e.split(",")).map(s=>s.trim()).filter(s=>s.length>0),o=new Set(r),n=new Set;for(let s of t){let i;try{i=Se(ke(s))}catch(a){throw new g(a,{operation:`resolve release selector "${s}"`,remediation:`pass one of: ${r.join(", ")}`})}if(!o.has(i))throw new g(void 0,{operation:`select release branch for "${s}"`,stderrExcerpt:`${i} is not an open regular release branch`,remediation:`pass one of: ${r.join(", ")}`});n.add(i)}return r.filter(s=>n.has(s))},zw={"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"},au=e=>{let r=zw[e.status];if(e.status==="conflict"){let t=e.conflictPaths?.length??0;return`${r}: ${t} file(s)`}return e.reason?`${r}: ${e.reason}`:r},qw=e=>{l.info(`
401
+ \u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${au(r)}`)},Yw=(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`},Zw=async e=>{let{entries:r,toPlan:t,all:o,explicit:n}=e;if(n||o)return t;h.setInteractive();let s=new Map(r.flatMap(i=>{let a=j(i.branch);return a?[[G(a),au(i)]]:[]}));return Ut(te({branches:t,descriptions:s}),{required:!0})},Xw=async e=>{let{cwd:r,worktreePath:t,entries:o,selected:n,verify:s}=e,i=o.filter(f=>n.includes(f.branch)),a=f=>{for(let k of f)l.info(`\u2139\uFE0F ${k} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await Sa(r,ru(i));a(c.nowUpToDate);let p=c.kept,d=new Map;if(s&&p.length>0){l.info(`
402
+ \u{1F50E} Verifying ${p.length} merge(s) with: ${s}`);let f=await ou({worktreePath:t,refs:p,command:s});d=f.failed;for(let[P,Q]of f.failed)l.info(`\u2717 ${P} failed verification \u2014 not pushing it. ${Q.split(`
403
+ `)[0]??""}`);let k=await Sa(r,f.kept);a(k.nowUpToDate),p=k.kept}if(p.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};l.info(`
404
+ \u2B06\uFE0F Pushing atomically: ${p.map(f=>f.branch).join(", ")}`);let u=await vl(r,p);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let v=(await Promise.all(p.map(async f=>({branch:f.branch,landed:await Rn(r,f.branch)===f.sha})))).filter(f=>f.landed);return v.length>0&&l.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${v.map(f=>f.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
405
+ `)[0],observedLanded:v.map(f=>f.branch)}},cu=async e=>{let{all:r,versions:t,dryRun:o=!1,verify:n,confirmedCommand:s}=e,i=n===!0?tu:n||void 0;await Ea({operation:"merge dev into release branches"});let c=(await $()).filter(E=>D(E.title)==="regular").map(E=>E.branch);if(c.length===0)return l.info("\u2139\uFE0F No open release branches found"),h.print(),iu(Kw(o));let p=await Te();try{await Uw({cwd:p,quiet:!0})`git fetch origin --prune`}catch(E){throw new g(E,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let d=t===void 0?c:Hw(t,c),u=await wl({cwd:p},async E=>{let Me=nu(E.remove);try{return await Qw({cwd:p,worktree:E,toPlan:d,candidates:c,all:r,versions:t,dryRun:o,verify:i,confirmedCommand:s})}finally{Me()}}),{entries:m,selected:v,pushed:f,pushAborted:k,abortedBy:P,declined:Q,verifyFailed:C}=u,T=await rr(p).catch(()=>[]);return ek({entries:m,selected:v,pushed:f,pushAborted:k,abortedBy:P,declined:Q,verifyFailed:C,dryRun:o,worktrees:T})},Qw=async e=>{let{cwd:r,worktree:t,toPlan:o,candidates:n,all:s,versions:i,dryRun:a,verify:c,confirmedCommand:p}=e,d=await eu({cwd:r,worktreePath:t.path,branches:o}),u={entries:d,pushed:!1,pushAborted:!1,declined:!1};if(qw(d),a)return{...u,selected:o};let m=await Zw({entries:d,toPlan:o,all:s,explicit:i!==void 0});m.length===n.length?h.addOption("--all",!0):h.addOption("--versions",m);let v=d.filter(f=>m.includes(f.branch)&&f.mergeSha).length;v>0&&l.info(`
406
+ \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 Y(p,`Are you sure you want to merge dev into these branches: ${m.join(", ")}?`,{throwOnDecline:!0})}catch(f){if(!Tn(f))throw f;return{...u,selected:m,declined:!0}}return p||h.addOption("--yes",!0),{entries:d,selected:m,declined:!1,...await Xw({cwd:r,worktreePath:t.path,entries:d,selected:m,verify:c})}},ek=e=>{let{entries:r,selected:t,pushed:o,pushAborted:n,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:p}=e,d=new Set(o?r.filter(f=>t.includes(f.branch)&&f.mergeSha&&!p?.has(f.branch)).map(f=>f.branch):[]),u=r.filter(f=>t.includes(f.branch)).map(f=>{let k=!!f.mergeSha,P=e.verifyFailed?.get(f.branch),Q=n&&k?"push-aborted":f.status,C=P?"verify-failed":Q;return{branch:f.branch,status:C,mergeSha:f.mergeSha,conflictPaths:f.conflictPaths,pushed:d.has(f.branch),reason:P??f.reason}}),m=u.filter(f=>!su.has(f.status));for(let f of u){let k=r.find(P=>P.branch===f.branch);l.info({branch:f.branch,status:f.status,mergeSha:f.mergeSha,conflictCount:f.conflictPaths?.length??0,durationMs:k?.durationMs,pushed:f.pushed,msg:"merge-dev branch result"})}if(i||a)l.info(i?`
407
+ Operation cancelled \u2014 nothing was pushed.
408
+ `:`
409
+ \u{1F50D} Dry run \u2014 nothing was pushed.
410
+ `);else if(m.length>0){l.info(`
411
+ \u26A0\uFE0F ${m.length} branch(es) did not merge.
412
+ `);for(let f of m)l.info(`# ${f.branch} \u2014 ${f.status}
413
+ ${Yw(f.branch,c)}
414
+ `)}else l.info(`\u2705 All merges completed successfully!
415
+ `);h.print();let v=a||i;return iu({successfulMerges:v?0:u.filter(f=>su.has(f.status)).length,failedMerges:v?0:m.length,failedBranches:v?[]:m.map(f=>f.branch),totalBranches:u.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:n,abortedBy:s},results:u.map(f=>v?{...f,pushed:!1}:f)})},Ca=w({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:S.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:S.union([S.string(),S.array(S.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error \u2014 hotfix branches cannot be selected. Takes precedence over `all`.'),dryRun:S.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:S.union([S.boolean(),S.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push."),confirm:S.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:S.number().describe("Number of branches that reached their desired state"),failedMerges:S.number().describe("Number of branches that did not"),failedBranches:S.array(S.string()).describe("List of branches that did not merge"),totalBranches:S.number().describe("Total number of branches processed"),dryRun:S.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:S.object({attempted:S.boolean(),aborted:S.boolean(),abortedBy:S.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:S.array(S.object({branch:S.string(),status:S.string(),mergeSha:S.string().optional(),conflictPaths:S.array(S.string()).optional(),pushed:S.boolean(),reason:S.string().optional()})).describe("Per-branch terminal state")},handler:cu});import{z as Uo}from"zod";import{$ as we}from"zx";var lu=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},hr=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 n=lu(r.stderr,500);n&&(t.stderr=n);let s=lu(r.stdout,200);return s&&(t.stdout=s),t};var Vo=e=>{let{removed:r,failed:t}=e;if(r.length>0){l.info("\u274C Removed worktrees:");for(let o of r)l.info(o);l.info("")}if(t.length>0){l.warn("\u26A0\uFE0F Not removed:");for(let{branch:o,reason:n}of t)l.warn(`${o} \u2014 ${n}`);l.warn("")}r.length===0&&t.length===0&&l.info("\u2139\uFE0F No worktrees to remove")};var Bo=e=>{let{result:r,operation:t}=e,o={removedWorktrees:r.removed,failedWorktrees:r.failed.map(i=>i.branch),count:r.removed.length},n=y(JSON.stringify(o,null,2));if(r.failed.length===0)return{content:n,structuredContent:o};let s={operation:t,remediation:`not removed: ${o.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:r.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw z()?new N({status:"partial_failure",...o},1,s):new g(void 0,s)};import us from"node:fs/promises";import{$ as mu}from"zx";var rk=new Set([".omc",".DS_Store"]),tk=new Set(["state","sessions"]),ok=2e3,nk="check 'git worktree list' for the path; uncommitted changes block removal",sk=e=>new Promise(r=>{setTimeout(r,e)}),Aa=e=>typeof e=="object"&&e!==null?e.code:void 0,pu=e=>{let r=e.length;for(;r>1&&e[r-1]==="/";)r-=1;return e.slice(0,r)},du=async e=>{try{return pu(await us.realpath(e))}catch{return pu(e)}},ik=async e=>{let{projectRoot:r,worktreePath:t}=e;try{let o=await rr(r),n=await du(t);for(let s of o)if(await du(s.path)===n)return!0;return!1}catch{return!0}},ak=async e=>{let r;try{r=await us.readdir(e)}catch(o){return{kind:Aa(o)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!r.every(o=>rk.has(o)))return{kind:"not-sweepable",entries:r};if(!r.includes(".omc"))return{kind:"sweepable",entries:r};try{return{kind:(await us.readdir(`${e}/.omc`)).every(s=>tk.has(s))?"sweepable":"not-sweepable",entries:r}}catch(o){return{kind:Aa(o)==="ENOENT"?"sweepable":"not-sweepable",entries:r}}},uu=async e=>{try{return await us.rm(e,{recursive:!0,force:!0}),"removed"}catch(r){return Aa(r)==="ENOTEMPTY"?"busy":"failed"}},ck=async e=>{let{worktreePath:r,sleep:t}=e,o=await uu(r);return o!=="busy"?o==="removed":(await t(ok),await uu(r)==="removed")},ds=(e,r,t)=>{let o=new g(r,{operation:`remove worktree for ${e}`,remediation:t});return l.error({error:r,branch:e,msg:o.message}),{branch:e,status:"failed",reason:o.message}},lk=async e=>{let{branch:r,worktreePath:t,projectRoot:o,error:n,sleep:s}=e;if(await ik({projectRoot:o,worktreePath:t}))return ds(r,n,nk);let i=await ak(t);if(i.kind==="gone")return{branch:r,status:"removed"};let a=`git already unregistered this worktree; inspect and remove it manually: rm -r ${t}`;return i.kind==="not-sweepable"||!await ck({worktreePath:t,sleep:s})?ds(r,n,a):(l.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${t}: a post-exit hook (e.g. oh-my-claudecode SessionEnd) wrote into the worktree while git was deleting it; set OMC_STATE_DIR to keep tool state out of worktrees`),{branch:r,status:"removed"})},pk=async e=>{let{branch:r,worktreeDir:t,projectRoot:o,sleep:n}=e,s=`${t}/${r}`;try{await An(s)}catch(i){return ds(r,i,"close the cmux workspace for this worktree manually and re-run")}try{return await mu`git worktree remove ${s}`,{branch:r,status:"removed"}}catch(i){return lk({branch:r,worktreePath:s,projectRoot:o,error:i,sleep:n})}},qr=async e=>{let{branches:r,worktreeDir:t,projectRoot:o,pruneFolder:n=!1,sleep:s=sk}=e,i=await Promise.all(r.map(c=>pk({branch:c,worktreeDir:t,projectRoot:o,sleep:s}))),a={removed:[],failed:[]};for(let c of i)c.status==="removed"?a.removed.push(c.branch):a.failed.push({branch:c.branch,reason:c.reason});return n&&a.removed.length===r.length&&await mu`git worktree prune`,a};var Go=async(e,r)=>{if(!(await me("release")).includes(e))return[];let o=await R(),n=`${o}${oe}`,{removed:s,failed:i}=await qr({branches:[e],worktreeDir:n,projectRoot:o});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...r,stderrExcerpt:a?.reason})}return s};var Kt=async(e,r,t)=>{try{return await t()}catch(o){throw l.debug({err:hr(o)},`Failed to ${e}`),new g(o,{operation:e,remediation:r})}},dk=async e=>{let r=As(e),t=await we`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},fu=async()=>{let e=await we`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},uk=async e=>{let r=qe(e),t=await Hr(r);if(!t)throw l.error(`\u274C No PR found for branch ${r}.`),new g(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},mk=async()=>{let e=await $(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,D(i.title)]));h.setInteractive();let o=await V(),n=await gr(te({branches:r,descriptions:o,types:t})),s=e.find(i=>i.branch===n);if(!s)throw l.error(`\u274C Release branch ${n} not found in open PRs.`),new g(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},fk=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await Hr(r);if(!n)throw new g(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){l.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new g(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await Kt(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await we`gh pr merge ${r} --squash --admin --delete-branch`})},gk=async e=>{let r=W(e),t=As(e),o=await fu();if(o){let s=o.number;return o.title!==t&&(l.info(`Adopting open dev \u2192 main PR #${s} ("${o.title}") and retitling for ${r}`),await Kt(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await we`gh pr edit ${s} --title ${t}`})),s}await Kt(`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 we`gh pr create --base main --head dev --title ${t} --body ""`});let n=await fu();if(!n)throw new g(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return n.number},hk=async e=>{let r=W(e);if(await dk(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await gk(e);await Kt(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await we`gh pr merge ${o} --squash --admin`})},vk=async()=>{we.quiet=!1,await Kt("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await we`gh workflow run deploy-all.yml --ref main -f environment=prod`}),we.quiet=!0},yk=async()=>{await Kt("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 we`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},wk=async e=>{try{await kn(e)}catch(r){l.warn({err:hr(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await bn(e)}catch(r){l.warn({err:hr(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},kk=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 sa({versionName:t},r)}catch(t){let o=$o(t)&&t.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";l.error({err:hr(t)},`Failed to deliver Jira release (non-blocking)${o}`)}},gu=async e=>{let{version:r,confirmedCommand:t}=e;await ce({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await uk(r):await mk(),s=j(o);if(!s)throw new g(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=W(s);h.addOption("--version",i),l.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let a=D(n);if(z())throw new N({status:"refused",agentMode:_.source},2,{operation:`deliver release ${o}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await Y(t,`Are you sure you want to deliver version ${o} to production?`),h.addOption("--yes",!0),we.quiet=!0;let p=`${await R()}${oe}`;await Go(o,{operation:`remove worktree for ${o} before merge`,remediation:`run manually: git worktree remove ${p}/${o} (use --force if uncommitted changes)`}),await fk({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await hk(s),await vk(),await yk(),await wk(o),we.quiet=!1,await kk(s),l.info(`Successfully delivered ${o} to production!`),h.print();let d={releaseBranch:o,version:i,type:a,success:!0};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},Ia=w({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:Uo.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:Uo.string().describe("The release branch that was delivered"),version:Uo.string().describe("The version that was delivered"),type:Uo.enum(["regular","hotfix"]).describe("Release type"),success:Uo.boolean().describe("Whether the delivery was successful")},handler:gu});import{z as Ye}from"zod";import{$ as Fa}from"zx";import{z as zo}from"zod";import hu from"node:fs/promises";import $a from"node:path";var vu=".github/workflows",bk=/script_name:\s*(?<service>[a-z0-9-]+)/,Rk=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,Ek=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,_a=async e=>{let r=$a.resolve(e,vu),t;try{t=await hu.readdir(r)}catch{return new Map}return yu(r,t.filter(o=>o.endsWith(".yml")||o.endsWith(".yaml")))},Ko=async(e,r)=>yu($a.resolve(e,vu),[r]),yu=async(e,r)=>{let t=new Map;for(let o of r){let n;try{n=await hu.readFile($a.resolve(e,o),"utf-8")}catch{continue}Pk(n,t)}return t},Pk=(e,r)=>{for(let t of e.split(/\n(?= {2}[\w-]+:)/i)){let o=bk.exec(t)?.groups?.service??Rk.exec(t)?.groups?.service;if(o===void 0||t.trimStart().startsWith("#"))continue;let n=[...t.matchAll(Ek)].map(s=>s.groups?.env??"");n.length!==0&&r.set(o,[...new Set([...r.get(o)??[],...n])])}},Da=(e,r)=>e===null?r??null:r===void 0?e:e.filter(t=>r.includes(t));import xk from"node:fs/promises";import Sk from"node:path";import Tk from"yaml";var Ck=".github/workflows",Ak="skip_terraform_deploy",Ho=async(e,r)=>{let t=Sk.resolve(e,Ck,r),o;try{o=Tk.parse(await xk.readFile(t,"utf-8"))}catch{return[]}let s=o?.on?.workflow_dispatch?.inputs;return typeof s!="object"||s===null?[]:Object.entries(s).filter(([i,a])=>a?.type==="boolean"&&i!==Ak).map(([i])=>i)};var wu="dev",Oa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ku=(e,r)=>e[r]===void 0,bu=(e,r)=>{let t=e[r];return typeof t=="string"&&t.length>0?t:void 0},Na=async e=>{try{return await e}catch{return[]}},Ik=async()=>{let e=await $();return Kr(e.map(r=>r.branch))},$k=(e,r)=>{let t=e.filter(n=>r.get(n)!==void 0);if(t.length===0)return"none declared.";let o=t.map(n=>`${n}: ${(r.get(n)??[]).join(", ")} only.`).join(" ");return t.length<e.length?`${o} Others: any environment.`:o},Yr=e=>{let{workflowFile:r,fields:t,toolName:o}=e,n=c=>(l.info({msg:`Tool execution form options empty (${r}): ${o}`,emptyList:c}),null),s=async c=>{let p=await Na(Ik());if(p.length===0)return null;let d=bu(c,"version");return zo.enum([...new Set([...p,wu])]).optional().describe(`Which release to deploy from. "${wu}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let p=Je(await Na(Be(r)),await Ve());if(p.length===0)return null;let d=p.filter(Tt),u=p.filter(v=>!Tt(v)),m=bu(c,"env");return zo.enum(p).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${r} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await R(),p=await Na(Ho(c,r));if(p.length===0)return null;let d=await Ko(c,r);return zo.array(zo.enum(p)).optional().describe(`Services to deploy. Environment gates declared by ${r} \u2014 ${$k(p,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${o}. Anything left blank keeps what the caller sent.`,isFormable:c=>Oa(c)?t.some(p=>ku(c,p)):!1,buildRequestedSchema:async c=>{let p=Oa(c)?c:{},d={};if(t.includes("version")){let u=await s(p);if(u===null)return n("releases");d.version=u}if(t.includes("env")){let u=await i(p);if(u===null)return n("envs");d.env=u}if(t.includes("services")&&ku(p,"services")){let u=await a();if(u===null)return n("services");d.services=u}return Object.keys(d).length===0?n("fields"):zo.object(d)},toArgs:(c,p)=>{let d={...Oa(p)?p:{}};for(let u of t){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;d[u]=m}}return d}}};import _k from"@inquirer/select";var Ht=async(e,r)=>{if(e.length===0)throw new g(void 0,{operation:r,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return A(t=>_k({message:"\u{1F9EA} Select environment",choices:e.map(o=>({name:o,value:o}))},t),{whenHeadless:"refuse"})};import Dk from"@inquirer/confirm";var qo=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;let n=`Deploy ${t} \u2192 ${o} via GitHub Actions?`;ue()&&Cn(n,{branch:t,env:o}),h.setInteractive();let s=await A(i=>Dk({message:n,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import Ok from"@inquirer/select";import Nk from"node:process";var Ma=()=>!ue()&&Nk.stdin.isTTY===!0,Mk={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},ja=async()=>A(e=>Ok({message:"\u{1F680} Where should this deploy run?",choices:zt.map(r=>({name:r,value:r,description:Mk[r]}))},e),{whenHeadless:"refuse"});var zt=["ci","local"],jk={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Ru=e=>{if(!e){let t={operation:"resolve the deploy source",remediation:`pass --from with one of: ${zt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ue()?new N({status:"argument_required",argument:"from",agentMode:_.source},2,t):new g(void 0,t)}let r=zt.find(t=>t===e);if(!r)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${zt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return r},Fk=(e,r)=>{let o=jk[e==="ci"?"local":"ci"].filter(n=>{let s=r[n];return s!==void 0&&s!==!1});if(o.length!==0)throw new g(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${o.join(", ")} ${o.length===1?"is":"are"} not valid with --from ${e}`})},Lk=async e=>e||!Ma()?Ru(e):ja();var Yo=async e=>{if(e)return e==="dev"?"dev":qe(e);h.setInteractive();let r=await $(),t=r.map(s=>s.branch),o=new Map(r.map(s=>[s.branch,D(s.title)])),n=await V();return gr([{value:"dev",label:"dev"},...te({branches:t,descriptions:n,types:o})])};var Eu="deploy-all.yml",Pu=Yr({workflowFile:Eu,fields:["version","env"],toolName:"gh-release-deploy-all"}),xu=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:n}=e;await he({provider:Pu,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await Yo(r),i=Fo(s);h.addOption("--version",i);let a=await Ve(),c=Je(await Be(Eu),a),p="";t?p=t:(h.setInteractive(),p=await Ht(c,"launch deploy-all workflow")),h.addOption("--env",p),Nr(p,"launch deploy-all workflow",a),Ro({env:p,branch:s});let d=o??!1;if(d&&h.addOption("--skip-terraform",!0),!await qo({confirmedCommand:n,branch:s,env:p})){l.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:p,skipTerraformDeploy:d,success:!1};return{content:y(JSON.stringify(u,null,2)),structuredContent:u}}try{Fa.quiet=!0,await Fa`gh workflow run deploy-all.yml --ref ${s} -f environment=${p} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Fa.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${p}`),h.print();let m={releaseBranch:s,version:i,environment:p,skipTerraformDeploy:d,success:!0};return{content:y(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw l.error({error:u},"\u274C Error launching workflow"),new g(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},La=w({name:"gh-release-deploy-all",formProvider:Pu,description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Omit "version" or "env" and this server offers the human a form listing the real releases and the environments this workflow declares; a client that cannot render one gets a refusal naming the missing field, never a guess.',requiresHumanConfirm:!0,inputSchema:{version:Ye.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:Ye.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-all.yml declares.'),skipTerraform:Ye.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ye.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ye.string().describe("The release branch that was deployed"),version:Ye.string().describe("The version that was deployed"),environment:Ye.string().describe("The environment deployed to"),skipTerraformDeploy:Ye.boolean().describe("Whether terraform deployment was skipped"),success:Ye.boolean().describe("Whether the deployment was successful")},handler:xu});import Wk from"@inquirer/checkbox";import{z as le}from"zod";import{$ as Wa}from"zx";var Zr="deploy-selected-services.yml",Su=Yr({workflowFile:Zr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Tu=async e=>{let{version:r,env:t,services:o,skipTerraform:n,confirmedCommand:s}=e;await he({provider:Su,params:e,operation:"launch deploy-selected workflow",argument:T=>T[0]??"version"});let i=await Yo(r),a=Fo(i);h.addOption("--version",a);let c=await Ve(),p=Je(await Be(Zr),c),d="";t?d=t:(h.setInteractive(),d=await Ht(p,"launch deploy-selected workflow")),h.addOption("--env",d),Nr(d,"launch deploy-selected workflow",c),Ro({env:d,branch:i});let u=await R(),m=await Ho(u,Zr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Zr}`,stderrExcerpt:`no services found in .github/workflows/${Zr}`});let v=[];if(o&&o.length>0?v=o:(h.setInteractive(),v=await A(T=>Wk({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(E=>({name:E,value:E}))},T),{whenHeadless:"refuse"})),h.addOption("--services",v),v.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let f=v.filter(T=>!m.includes(T));if(f.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${f.join(", ")}`});let k=await Ko(u,Zr),P=v.filter(T=>{let E=k.get(T);return E!==void 0&&!E.includes(d)});if(P.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:P.map(T=>`${T} deploys only to: ${(k.get(T)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Zr} gates these services out of ${d}: ${P.join(", ")}`});let Q=n??!1;Q&&h.addOption("--skip-terraform",!0);let C=T=>{let E={releaseBranch:i,version:a,environment:d,services:v,skipTerraformDeploy:Q,success:T};return{content:y(JSON.stringify(E,null,2)),structuredContent:E}};if(!await qo({confirmedCommand:s,branch:i,env:d}))return l.info("Deployment cancelled"),C(!1);try{Wa.quiet=!0;let T=v.flatMap(Me=>["-f",`${Me}=true`]);return await Wa`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${T} ${Q?["-f","skip_terraform_deploy=true"]:[]}`,Wa.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${v.join(", ")}`),h.print(),C(!0)}catch(T){throw l.error({error:T},"\u274C Error launching workflow"),new g(T,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Ja=w({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Su,description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:le.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:le.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:le.array(le.string()).optional().describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:le.boolean().optional().describe("Skip the terraform deployment stage."),confirm:le.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:le.string().describe("The release branch that was deployed"),version:le.string().describe("The version that was deployed"),environment:le.string().describe("The environment deployed to"),services:le.array(le.string()).describe("The services that were deployed"),skipTerraformDeploy:le.boolean().describe("Whether terraform deployment was skipped"),success:le.boolean().describe("Whether the deployment was successful")},handler:Tu});import{z as qt}from"zod";var Cu=async()=>{let r=(await $()).flatMap(i=>{let a=j(i.branch);return a?[{version:W(a),jiraKey:G(a),type:D(i.title)}]:[]}),t=await V(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let a=jo(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
416
+ `),l.info(`
417
+ ${n.join(`
418
+ `)}
419
+ `);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:y(JSON.stringify(s,null,2)),structuredContent:s}},Va=w({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:qt.array(qt.object({version:qt.string().describe("Release version"),type:qt.enum(["regular","hotfix"]).describe("Release type"),description:qt.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:qt.number().describe("Number of release branches")},handler:Cu});import Jk from"node:process";var Ba=e=>({...e}),Ga=e=>{let{env:r,branch:t,sha:o,isClean:n,ambient:s=Jk.env}=e,i={VITE_DOMAIN_ENV:r,VITE_BRANCH_NAME:t,VITE_COMMIT_HASH:n?o:`${o}-dirty`},a={},c=[];for(let[p,d]of Object.entries(s)){if(p.startsWith("VITE_")){c.push(p);continue}a[p]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:r,DEPLOY_BRANCH:t,DEPLOY_SHA:o,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},ms=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(`
420
+ `)};import rb from"@inquirer/checkbox";import tb from"@inquirer/confirm";import ob from"@inquirer/select";import{spawn as nb}from"node:child_process";import sb from"node:process";import{z as L}from"zod";import{$ as Xo}from"zx";import{$ as Zo}from"zx";var Vk=async e=>{let r=Zo.quiet;Zo.quiet=!0;try{let t=`/${e}/environment`,o=await Zo`aws sts get-caller-identity --query Account --output text`,n=await Zo`aws ssm get-parameter --name ${t} --query Parameter.Value --output text`;return{accountId:o.stdout.trim(),stage:n.stdout.trim()}}catch(t){throw new g(t,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Zo.quiet=r}},Au=(e,r)=>{if(r.stage!==e)throw new g(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${r.accountId} reports "${r.stage}" \u2014 refusing to deploy to an environment you did not name`})},Iu=e=>{let{env:r,isShared:t,isClean:o}=e;if(!(!t||o))throw new g(void 0,{operation:`deploy to shared environment "${r}"`,remediation:"commit, or `git stash -u` (plain stash leaves untracked files), or deploy to a personal environment",stderrExcerpt:"the working tree has uncommitted or untracked changes and this environment is shared"})},$u=(e,r)=>{if(r.includes(e))throw new g(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Ua=async e=>{let{env:r,project:t,isShared:o,isClean:n,runningEnvs:s,protectedEnvAccess:i}=e;Nr(r,`deploy to "${r}"`,i),$u(r,s),Iu({env:r,isShared:o,isClean:n});let a=await Vk(t);return Au(r,a),{identity:a}};import _u from"node:fs/promises";import fs from"node:path";var Bk="devops/scripts",Gk=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,Uk=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,Kk=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,Hk=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Ka=async e=>{let r=fs.resolve(e,Bk),t;try{t=await _u.readdir(r)}catch{return[]}let o=await _a(e);return(await Promise.all(t.map(s=>({entry:s,match:Gk.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=fs.resolve(r,s),c=i?.groups?.service??"",p=qk(await zk(a));return{name:c,scriptPath:a,allowedEnvs:Da(Yk(p),o.get(c)),ssmPrefix:Xk(p)}}))).sort((s,i)=>s.name.localeCompare(i.name))},zk=async e=>{try{return await _u.readFile(e,"utf-8")}catch{return""}},qk=e=>e.split(`
421
+ `).map((r,t)=>({line:t+1,text:r})).filter(({text:r})=>!r.trimStart().startsWith("#")),Yk=e=>{let r=e.reduce((o,{text:n})=>o??Uk.exec(n)?.groups?.envs,void 0);if(r===void 0)return null;let t=r.split(/\s+/).filter(Boolean);return t.length>0?t:null},Zk=e=>{let r=e.replaceAll(/["']/g,"");return r.includes("$")&&(r.includes("/environment")||r.startsWith("$"))},Xk=e=>{for(let{line:r,text:t}of e){let o=Hk.exec(t)?.groups?.prefix;if(o!==void 0)return o;let n=Kk.exec(t)?.groups?.arg;if(n!==void 0&&Zk(n))return{unparseable:{line:r,text:t.trim()}}}return null},Qk=e=>{let r=new Map;for(let t of e)typeof t.ssmPrefix=="string"&&r.set(t.ssmPrefix,[...r.get(t.ssmPrefix)??[],fs.basename(t.scriptPath)]);return r},eb=e=>{let r=e.flatMap(t=>{if(t.ssmPrefix===null||typeof t.ssmPrefix=="string")return[];let{line:o,text:n}=t.ssmPrefix.unparseable;return[`${fs.basename(t.scriptPath)}:${o}: ${n}`]});if(r.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:r.join("; ")})},Du=e=>{eb(e);let r=Qk(e),[t,...o]=r.keys();if(t===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(o.length>0){let n=[...r.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${r.size} different prefixes across ${e.length} deploy scripts \u2014 ${n}`})}return t},gs=(e,r)=>e.allowedEnvs===null||e.allowedEnvs.includes(r),Ha=(e,r)=>e.filter(t=>gs(t,r));var qa="deploy-all.yml",Nu="/bin/sh",ib=async()=>{let e=Xo.quiet;Xo.quiet=!0;try{let r=await Xo`gh run list --workflow=${qa} --status=in_progress --json displayTitle`;return JSON.parse(r.stdout).flatMap(o=>/\[(?<env>[a-z0-9-]+)\]/.exec(o.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Xo.quiet=e}},ab=async(e,r)=>{let t=e.map(n=>({name:n.name,value:n.name})),o=await A(n=>rb({message:`Deploy which services to ${r}?`,choices:t,pageSize:20},n),{whenHeadless:{refuse:"service"}});if(o.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return o},cb=async e=>{let{env:r,isShared:t,names:o,accountId:n}=e,s=o.length,i=t?`"${r}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${r} from this machine?`;return ue()&&Cn(i,{env:r,services:o,accountId:n,shared:t}),t?A(a=>ob({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${r}`,value:!0}]},a),{whenHeadless:"refuse"}):A(a=>tb({message:i,default:!1},a),{whenHeadless:"refuse"})},lb=(e,r,t)=>new Promise((o,n)=>{let s=nb(Nu,[e.scriptPath],{cwd:t,env:r,stdio:"inherit"});s.on("error",n),s.on("close",i=>{o(i??1)})}),pb=async e=>{let{chosen:r,childEnv:t,cwd:o,env:n}=e,s=[],i=[];for(let a of r){l.info(`\u2192 ${a.name} \u2192 ${n}`);let c=await lb(a,t,o);if(c!==0){i.push(a.name),l.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),l.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},db=e=>{let{names:r,services:t,env:o}=e,n=new Map(t.map(a=>[a.name,a])),s=r.filter(a=>!n.has(a));if(s.length>0)throw new g(void 0,{operation:"resolve the requested services",remediation:`known services: ${t.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=r.filter(a=>{let c=n.get(a);return c!==void 0&&!gs(c,o)});if(i.length>0)throw new g(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=>n.get(a))},za=e=>{let{env:r,accountId:t,names:o,built:n,deployed:s,failed:i,dryRun:a,success:c}=e,p={environment:r,accountId:t,services:o,deployed:s,failed:i,contract:Ba(n.contract),strippedVars:n.stripped,dryRun:a,success:c};return{content:y(JSON.stringify(p,null,2)),structuredContent:p}},ub=async e=>{let{selection:r,eligible:t,service:o,env:n}=e;return r==="all"?t.map(s=>s.name):o&&o.length>0?o:(h.setInteractive(),ab(t,n))},Mu=async(e,r)=>{let{env:t,service:o,confirmedCommand:n,dryRun:s,printEnv:i}=e,a=await R(),c=await Ka(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let p=Du(c);await he({provider:Ya[r],params:e,operation:"deploy locally",argument:"env"});let d=await Ve(),u=Je(await Be(qa),d),m=t??"";m||(h.setInteractive(),m=await Ht(u,"deploy locally")),h.addOption("--env",m);let v=Ha(c,m);if(v.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let f=await ub({selection:r,eligible:v,service:o,env:m}),k=db({names:f,services:c,env:m});if(r==="selected")for(let wr of f)h.addOption("--service",wr);let P=Tt(m),Q=await ct(),C=(await Xo`git rev-parse HEAD`.quiet()).stdout.trim(),T=await fl(),E=Ga({env:m,branch:Q,sha:C,isClean:T});i&&l.info(`Deploy contract for ${m}:
422
+ ${ms(E)}`);let se=(await Ua({env:m,project:p,isShared:P,isClean:T,runningEnvs:await ib(),protectedEnvAccess:d})).identity.accountId;if(s)return l.info([`Would deploy to "${m}" (AWS account ${se}) from this machine`,`Preflight parameter: /${p}/environment`,ms(E),"Commands:",...k.map(wr=>` ${Nu} ${wr.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
423
+ `)),za({env:m,accountId:se,names:f,built:E,deployed:[],failed:[],dryRun:!0,success:!0});if(!n&&!await cb({env:m,isShared:P,names:f,accountId:se}))return l.info("Deployment cancelled"),za({env:m,accountId:se,names:f,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:tt,failed:yr}=await pb({chosen:k,childEnv:E.childEnv,cwd:a,env:m});return yr.length>0&&(l.error(`Partial deploy to "${m}": succeeded [${tt.join(", ")||"none"}], failed [${yr.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),sb.exitCode=1),h.print(),za({env:m,accountId:se,names:f,built:E,deployed:tt,failed:yr,dryRun:!1,success:yr.length===0})},ju=async e=>Mu(e,"all"),Fu=async e=>Mu(e,"selected"),Lu='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.',Wu={env:L.string().optional().describe('Target environment, e.g. "dev" or a personal env like "arthur". Omit it to be offered the environments this project may reach.'),dryRun:L.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:L.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Ju={environment:L.string().describe("Environment deployed to"),accountId:L.string().describe("AWS account the deploy targeted"),services:L.array(L.string()).describe("Services requested"),deployed:L.array(L.string()).describe("Services that completed successfully"),failed:L.array(L.string()).describe("Services that failed"),contract:L.record(L.string(),L.string()).describe("Build contract passed to the scripts"),strippedVars:L.array(L.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:L.boolean().describe("Whether this was a dry run"),success:L.boolean().describe("Whether every requested service deployed")},Ou=e=>Yr({workflowFile:qa,fields:["env"],toolName:e}),Ya={all:Ou("local-deploy-all"),selected:Ou("local-deploy-selected")},Za=w({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Lu}`,requiresHumanConfirm:!0,formProvider:Ya.all,inputSchema:Wu,outputSchema:Ju,handler:ju}),Xa=w({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Lu}`,requiresHumanConfirm:!0,formProvider:Ya.selected,inputSchema:{...Wu,service:L.array(L.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Ju,handler:Fu});import gb from"@inquirer/confirm";import tc from"@inquirer/input";import Gu from"@inquirer/select";import ec from"node:process";import{z as M}from"zod";import{z as hs}from"zod";var Yt=async(e,r)=>new Promise(t=>{let o=setTimeout(()=>{t(null)},r);e.then(n=>{clearTimeout(o),t(n)},()=>{clearTimeout(o),t(null)})});var Bu=2500,Vu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mb=async()=>{let e=await Do();return{regular:Lt(e,"regular"),hotfix:Lt(e,"hotfix")}},fb=(e,r)=>e===null?(l.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${r/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(l.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,Qa=(e={})=>{let r=e.hintBudgetMs??Bu;return{message:"Choose the release to cut. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:t=>Vu(t)&&(t.releases===void 0||Array.isArray(t.releases)&&t.releases.length===0),buildRequestedSchema:async()=>{let t=await Yt(mb(),r);return hs.object({type:hs.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:hs.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign". ${fb(t,r)}`),description:hs.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none.")})},toArgs:(t,o)=>{let n=typeof t.release=="string"?t.release.trim():"";if(n==="")return null;let s=t.type==="hotfix"?"hotfix":"regular",i=typeof t.description=="string"&&t.description.trim()!==""?t.description.trim():void 0,a=ns(n);return{...Vu(o)?o:{},releases:[{...a,type:s,...i===void 0?{}:{description:i}}]}}}};var hb='"1.2.5" or "next"',rc=(e,r)=>{try{return ma(e,r)}catch(t){throw t instanceof Br?new g(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof pl?new g(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},vb=async(e,r)=>{let t=Lt(e,r),o=t?` [${t}]`:"",n=(await A(i=>tc({message:` Version (e.g. ${hb})${o}: `},i),{whenHeadless:"refuse"})).trim(),s=n===""?t??"":n;return s===""&&(l.error("No version provided. Exiting..."),ec.exit(1)),s},yb=async()=>{let e=(await A(r=>tc({message:' Name (kebab-case, e.g. "checkout-redesign"): '},r),{whenHeadless:"refuse"})).trim();e===""&&(l.error("No name provided. Exiting..."),ec.exit(1));try{wn(e)}catch(r){let t=r instanceof Error?r.message:String(r);l.error(`${t} Exiting...`),ec.exit(1)}return e},wb=async e=>{h.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),n=[],s=!0;for(;s;){let i=n.length+1,a=await A(u=>Gu({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},u),{whenHeadless:"refuse"}),c=await A(u=>Gu({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},u),{whenHeadless:"refuse"}),p;if(a==="name"){let u=await yb();p=rc([{name:u,type:c}],[])[0]}else{let u=await vb(await o(),c);p=rc([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(pr(`v${p.id.raw}`))}let d=(await A(u=>tc({message:" Description (optional, press Enter to skip): "},u),{whenHeadless:"refuse"})).trim();n.push({...p,...d!==""?{description:d}:{}}),s=await A(u=>gb({message:"Add another release?",default:!1},u),{whenHeadless:"refuse"})}return n},kb=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 ")},Uu=e=>{for(let r of e)h.addOption("--release",ua(r))},bb=async(e,r)=>{if(e&&e.length>0){let o=fa(e)?await r():[],n=rc(e,o);return Uu(n),n}if(z())throw new N({status:"argument_required",argument:"release",agentMode:_.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let t=await wb(r);return Uu(t),t},Rb=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new g(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},Eb=async(e,r)=>{let t=e.map(kb).join(`
424
+ - `);await Y(r,`Create the following ${e.length} release(s)?
425
+ - ${t}
426
+ `),h.addOption("--yes",!0)},Pb=async e=>{let{entry:r,jiraConfig:t}=e,o=W(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await Bt({operation:`create release ${n}`});let s=await Pa(r.type),i=await xa({id:r.id,jiraConfig:t,description:r.description,type:r.type,baseSha:s});return l.info(`\u2705 Successfully created release: ${n} (${r.type})`),l.info(`\u{1F517} GitHub PR: ${i.prUrl}`),l.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
427
+ `),{result:i}}catch(s){let i=$o(s)?s:void 0,a=new g(s,{operation:`create release ${n} (${r.type})`,remediation:i?.kind==="auth"?"reissue the Atlassian API token and update JIRA_TOKEN":"verify the version or name is unique and the base branch is clean",stderrExcerpt:i?.message});return l.error(`\u274C ${a.message}
428
+ `),{failure:{version:o,error:a.message}}}},xb=(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.`)},Ku=Qa(),Hu=async e=>{let{releases:r,confirmedCommand:t}=e;await ce({operation:"create release"}),await he({provider:Ku,params:e,operation:"create release",argument:"release"});let o=await jt(),n=null,i=await bb(r,async()=>(n===null&&(n=await Do()),n));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});Rb(i),await No({operation:"create release",base:fr(i[0].type)}),await Eb(i,!!t);let a=[],c=[];for(let d of i){let{result:u,failure:m}=await Pb({entry:d,jiraConfig:o});u&&a.push(u),m&&c.push(m)}xb(i.length,a.length,c.length),h.print();let p={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:y(JSON.stringify(p,null,2)),structuredContent:p}},oc=w({name:"release-create",requiresHumanConfirm:!0,formProvider:Ku,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:M.array(M.object({version:M.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:M.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:M.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:M.string().optional().describe("Optional description for the Jira version.")}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description. Optional over MCP: omit it to have the human fill one release from a form.').optional(),confirm:M.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:M.array(M.string()).describe("List of created release branch names"),successCount:M.number().describe("Number of releases created successfully"),failureCount:M.number().describe("Number of releases that failed"),releases:M.array(M.object({version:M.string().describe("Version number"),type:M.enum(["regular","hotfix"]).describe("Release type"),branchName:M.string().describe("Release branch name"),prUrl:M.string().describe("GitHub PR URL"),jiraVersionUrl:M.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:M.array(M.object({version:M.string().describe("Version number that failed"),error:M.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Hu});import Sb from"@inquirer/input";import{z as vr}from"zod";var Tb=async()=>{let e=await $(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,D(s.title)])),o=await V(),n=await gr(te({branches:r,descriptions:o,types:t}));return{branch:n,type:t.get(n)||"regular"}},Cb=async e=>{let t=(await $()).find(o=>o.branch===e);if(!t)throw new g(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return D(t.title)},Ab=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await A(n=>Sb({message:` New description ${r} (press Enter to keep current): `},n),{whenHeadless:{refuse:"description"}})).trim();return o===""?e:o},zu=async e=>{let{version:r,description:t,confirmedCommand:o}=e,n=await jt(),s;r?(s=qe(r),await Cb(s)):(h.setInteractive(),s=(await Tb()).branch);let i=j(s);if(!i)throw new g(void 0,{operation:`edit description for ${s}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=W(i);h.addOption("--version",a);let c=G(i),p=await Ke(c,n);if(!p)throw new g(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let d=p.description??"",u;t!==void 0?(u=t,h.addOption("--description",u)):(h.setInteractive(),u=await Ab(d));let m=k=>{let P={version:a,branch:s,jiraVersionUrl:lr(n,p),previousDescription:d,newDescription:u,changed:k};return{content:y(JSON.stringify(P,null,2)),structuredContent:P}};if(u===d)return l.info(`No change \u2014 description for ${c} is already: "${d}"`),h.print(),m(!1);await Y(o,`Update description for ${c}?
429
+ from: "${d}"
430
+ to: "${u}"
431
+ `),h.addOption("--yes",!0),await Mt({versionId:p.id,description:u},n);let v=lr(n,p),f=Mo(v,u);return await ls({branch:s,body:f}),l.info(`\u2705 Updated description for ${c}`),l.info(`\u{1F517} Jira Version: ${v}`),l.info(`\u{1F517} PR branch: ${s}
432
+ `),h.print(),m(!0)},nc=w({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:vr.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:vr.string().describe("New description. Empty string clears the description.")},outputSchema:{version:vr.string().describe("Release version"),branch:vr.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:vr.string().describe("Jira fix version URL"),previousDescription:vr.string().describe("The description before the update"),newDescription:vr.string().describe("The description after the update"),changed:vr.boolean().describe("Whether the description actually changed")},handler:zu});import{z as I}from"zod";import{$ as fc}from"zx";import qu from"node:fs/promises";import vs from"node:path";var Qo=async e=>{let{workspacePath:r,folderPaths:t}=e,o=vs.dirname(r),n;try{n=await qu.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let s;try{s=JSON.parse(n)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>vs.resolve(o,d.path))),c=[],p=[];for(let d of t){let u=vs.resolve(d);if(a.has(u)){p.push(d);continue}let m=vs.relative(o,u);i.push({path:m}),a.add(u),c.push(d)}return s.folders=i,await qu.writeFile(r,`${JSON.stringify(s,null,2)}
433
+ `,"utf-8"),{added:c,skipped:p}};import{$ as Ib}from"zx";var en=async e=>{await Ib`cursor ${e}`};import $b from"node:fs/promises";import ws from"node:path";import Yu from"node:fs/promises";import ys from"node:path";var rn=async e=>{let{workspacePath:r,folderPaths:t}=e,o=ys.dirname(r),n;try{n=await Yu.readFile(r,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${r}: ${m.message}`)}let s;try{s=JSON.parse(n)}catch(m){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(t.map(m=>ys.resolve(m))),c=new Set,p=i.filter(m=>{let v=ys.resolve(o,m.path);return a.has(v)?(c.add(v),!1):!0});s.folders=p,await Yu.writeFile(r,`${JSON.stringify(s,null,2)}
434
+ `,"utf-8");let d=[],u=[];for(let m of t){let v=ys.resolve(m);c.has(v)?d.push(m):u.push(m)}return{removed:d,notFound:u}};var sc=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=ws.dirname(r),s=ws.resolve(`${t}/release`),i=await $b.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(f=>ws.resolve(`${t}/${f}`))),d=[];for(let f of c){let k=ws.resolve(n,f.path);(k===s||k.startsWith(`${s}/`))&&!p.has(k)&&d.push(k)}let u=[];d.length>0&&(u=(await rn({workspacePath:r,folderPaths:d})).removed);let m=o.map(f=>`${t}/${f}`),{added:v}=m.length>0?await Qo({workspacePath:r,folderPaths:m}):{added:[]};return{added:v,removed:u}};import Zu from"node:path";var Xr=(e,r)=>Zu.isAbsolute(e)?e:Zu.resolve(r,e);var ic=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,cursorConfig:n}=e;if(!n.workspaceConfigPath)return l.warn("\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set."),{ran:!1,added:0,removed:0};let s=Xr(n.workspaceConfigPath,r);try{let{added:i,removed:a}=await sc({workspacePath:s,worktreeDir:t,currentBranches:o});return o.length>0&&await en(s),{ran:!0,added:i.length,removed:a.length}}catch(i){return l.warn({error:i},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${s}`),{ran:!1,added:0,removed:0}}};import{$ as _b}from"zx";var ac=async e=>{let{folderPaths:r}=e;for(let t of r)await _b`zed --add ${t}`;return{added:r}};import{$ as Db}from"zx";var cc=async e=>{let{worktreePaths:r}=e;if(r.length===0)return{ran:!1,added:0,removed:0};try{return await Db`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 Ob}from"zx";var lc=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,n=[r,...o.map(s=>`${t}/${s}`)];try{return await Ob`zed --reuse ${n}`,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(s){return l.warn({error:s},"\u26A0\uFE0F Failed to refresh Zed workspace"),{ran:!1}}};var Pe=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var pc=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,n=await x(),s=Ce(n),i=o.map(c=>`${t}/${c}`),a=[];for(let c of s)switch(c.provider){case"cursor":{if(!c.config.workspaceConfigPath){l.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),a.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let p=Xr(c.config.workspaceConfigPath,r),{added:d,skipped:u}=await Qo({workspacePath:p,folderPaths:i}),m=u.length>0?` (${u.length} already present)`:"";l.info(`\u2705 Added ${d.length} folder(s) to ${p}${m}`),await en(p),a.push({ran:!0,provider:"cursor",added:d.length,skipped:u.length});break}case"zed":{let{added:p}=await ac({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:Pe(c)}return a};var dc=async e=>{let r=await x(),t=Ce(r),{projectRoot:o,worktreeDir:n,worktreePaths:s,currentBranches:i}=e,a=[];for(let c of t)switch(c.provider){case"cursor":{let p=await ic({projectRoot:o,worktreeDir:n,currentBranches:i,cursorConfig:c.config});a.push({...p,provider:"cursor"});break}case"zed":{let p=await cc({worktreePaths:s});a.push({...p,provider:"zed"});break}default:Pe(c)}return a};var uc=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return Pe(e)}};var Qr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:n,allowEditorRelaunch:s}=e;if(n.length===0)return[];let i=await x(),a=Ce(i),c=n.map(u=>`${t}/${u}`),p=o.filter(u=>!n.includes(u)),d=[];for(let u of a)switch(u.provider){case"cursor":{d.push(await Nb({ide:u,projectRoot:r,folderPaths:c}));break}case"zed":{d.push(await Mb({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:s}));break}default:Pe(u)}return d},Nb=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let n=Xr(r.config.workspaceConfigPath,t);try{let{removed:s}=await rn({workspacePath:n,folderPaths:o});return s.length>0&&l.info(`\u2705 Removed ${s.length} folder(s) from ${n}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return l.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${n}`),{provider:"cursor",supported:!0,removed:[]}}},Mb=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:n}=e;return n?(await lc({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 ks=["workspace","none"];import{z as Xu}from"zod";var rm=2500,bs="release-remove",Qu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),jb=e=>e.version===void 0||e.version==="",Fb=async()=>{try{return{outcome:"listed",prs:await $()}}catch(e){return e instanceof g&&e.operation===Wo?{outcome:"empty"}:{outcome:"failed"}}},em=(e,r)=>(e===null?l.info({msg:`Tool execution form enumeration timed out (gh pr list, ${r/1e3} s): ${bs}`}):e.outcome==="failed"?l.info({msg:`Tool execution form enumeration failed (gh pr list): ${bs}`}):l.info({msg:`Tool execution form options empty (open release PRs): ${bs}`}),null),Lb=(e,r)=>{let t=new Map(e.map(o=>[o.branch,D(o.title)]));return is(e.map(o=>o.branch)).map(({branch:o,id:n,label:s})=>{let i=r?.get(G(n)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${t.get(o)??"regular"}]${a}`}})},Wb=(e,r,t)=>{let o=e.map(n=>n.prose).join("; ");return r!==null?`Open release PRs right now: ${o}. `:(l.info({msg:`Tool execution form descriptions unavailable (timeout): ${bs}`}),`Open release PRs right now: ${o}. Jira descriptions could not be fetched within ${t/1e3} s. `)},mc=(e={})=>{let r=e.fetchBudgetMs??rm;return{message:"Choose the release to remove. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:t=>Qu(t)&&jb(t),buildRequestedSchema:async()=>{let[t,o]=await Promise.all([Yt(Fb(),r),Yt(V(),r)]);if(t===null||t.outcome!=="listed")return em(t,r);let n=Lb(t.prs,o);return n.length===0?em({outcome:"empty"},r):Xu.object({version:Xu.enum(n.map(s=>s.label)).describe(`The ONE release to tear down. ${Wb(n,o,r)}Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve. Removal deletes the worktree, closes the PR, deletes both branches AND removes the Jira fix version \u2014 the last is irreversible.`)})},toArgs:(t,o)=>typeof t.version!="string"?null:{...Qu(o)?o:{},version:t.version}}};var tm=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],Es={worktree:"remove the worktree","ide-folders":"strip the worktree from configured editors",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},on="remove a release",xe=e=>{throw l.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Oe=(e,r)=>_.source==="mcp"?e:r,om=(e,r)=>{throw l.warn({operation:r.operation},`\u26D4 ${r.stderrExcerpt??r.operation}`),new N({...e,agentMode:_.source},2,r)},Jb=e=>{z()&&(e.version||om({status:"argument_required",argument:"version"},{operation:on,remediation:Oe('pass "version" (a release version or name). When "version" is omitted this server offers the open release PRs as a form; you reached this refusal instead because the client cannot render forms, there are no open release PRs, the enumeration failed or timed out (the server log names which), or a gate with no "version" was confirmed',"pass --version <ref> (a release version or name) on the re-run \u2014 `infra-kit release list --json` lists the candidates"),stderrExcerpt:Oe('release-remove reached the handler without "version"',"release remove reached the handler without --version under agent mode")}),e.skipJira&&om({status:"refused"},{operation:on,remediation:Oe("omit skipJira \u2014 over MCP the fix version is checked and removed with the release; to keep it, do not remove the release from here, or ask a human to run infra-kit release remove --skip-jira from a configured shell","drop --skip-jira \u2014 under agent mode the fix version is checked and removed with the release; to keep it, ask a human to run `infra-kit release remove --skip-jira` from their own terminal"),stderrExcerpt:Oe("skipJira is not permitted over MCP: it would tear down the branch and PR and leave a live Jira fix version behind with nothing in the result pointing at it","--skip-jira is not permitted under agent mode: it would tear down the branch and PR and leave a live Jira fix version behind with nothing in the result pointing at it")}))},sm=e=>{e.pr?.state==="MERGED"&&xe({operation:`remove release ${e.label}`,remediation:`this release has shipped \u2014 removing it would delete the branch recording the merge and strip its Jira fix version from delivered work. To undo a delivery, revert the merge commit on ${e.baseBranch} and cut a new release.`,stderrExcerpt:`PR #${e.pr.number} for ${e.branch} is MERGED`})},Vb=(e,r)=>{if(r.skipJira||(e.jiraConfig||xe({operation:`remove release ${e.label}`,remediation:Oe("call `env-load` for a config that carries JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL, then re-call; or ask a human to run `infra-kit release remove --skip-jira` from a configured shell","set JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL, or pass --skip-jira to tear down the branch and PR and leave any fix version alone"),stderrExcerpt:"Jira is not configured, so a fix version for this release cannot be checked or removed"}),!e.jira))return;let{version:t,fixCount:o,affectsCount:n}=e.jira;(t.released||t.archived)&&xe({operation:`remove Jira fix version "${t.name}"`,remediation:Oe("un-release it in Jira first; or, to tear down the branch and PR and leave the fix version alone, ask a human to run infra-kit release remove --skip-jira from a configured shell","un-release it in Jira first, or remove the release without it via --skip-jira"),stderrExcerpt:`fix version "${t.name}" is already ${t.released?"released":"archived"}`}),!(o===0&&n===0)&&(e.moveIssuesTo||xe({operation:`remove Jira fix version "${t.name}"`,remediation:Oe('deleting it would clear both fields on those issues with no way to restore them \u2014 re-call with "moveIssuesTo": "<existing fix version name>" to reassign both, or clear the version from the issues in Jira first',"deleting it would clear both fields on those issues with no way to restore them \u2014 pass --move-issues-to <version> to reassign both, or clear the version from the issues in Jira first"),stderrExcerpt:`${t.name} is set as fixVersion on ${o} issue(s) and as affectsVersion on ${n} issue(s)`}))},Bb=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;let t=Oe("the gh-release-list tool (open PRs only) or worktrees-list","`infra-kit release list`");xe({operation:`remove release ${e.label}`,remediation:`nothing named "${e.label}" exists to remove \u2014 check the spelling against ${t}. (A release this command already removed keeps a CLOSED PR, so a genuine re-run is not affected.)`,stderrExcerpt:"found no worktree, no PR (any state), no local or remote branch, and no Jira fix version"})},Gb=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||xe({operation:`remove release ${e.label}`,remediation:`commit or discard those changes (\`git -C ${e.worktreePath} stash -u\`), then re-run`,stderrExcerpt:`the worktree at ${e.worktreePath} has uncommitted changes: ${e.worktreeDirty.slice(0,4).join(", ")}`})},Ub=async e=>(await fc`git -C ${e} status --porcelain`).stdout.split(`
435
+ `).map(t=>t.trimEnd()).filter(t=>t.length>0),Kb=async e=>(await nr()).has(await Tr(e)),Hb=async(e,r)=>{let t={jiraConfig:null,jira:null,moveIssuesTo:null};if(r.skipJira)return t;let o=await He();if(!o)return t;let n=await Ke(G(e),o),s=r.moveIssuesTo?await zb(r.moveIssuesTo,o):null;if(!n)return{jiraConfig:o,jira:null,moveIssuesTo:s};let i=await os(n.id,o);return{jiraConfig:o,moveIssuesTo:s,jira:{version:n,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:lr(o,n)}}},zb=async(e,r)=>{let t=await Ke(e,r);return t||xe({operation:`reassign issues to Jira fix version "${e}"`,remediation:'name an existing fix version exactly as it appears in Jira (e.g. "v1.2.6")',stderrExcerpt:`no Jira fix version named "${e}"`})},qb=async(e,r)=>{let t=j(e);t||xe({operation:`remove release ${e}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:`"${e}" is not a release branch`});let o=await R(),n=`${o}${oe}`,s=`${n}/${e}`,[i,a,c,p]=await Promise.all([me("release"),Hr(e),ro(o,`refs/heads/${e}`),Rn(o,e)]),d=i.includes(e);return{...await Hb(t,r),branch:e,id:t,label:W(t),baseBranch:fr(D(a?.title??"")),projectRoot:o,worktreeDir:n,worktreePath:s,currentWorktrees:i,worktreePresent:d,cmuxWorkspacePresent:d?await Kb(s):!1,worktreeDirty:d?await Ub(s):null,localTipSha:c,remoteTipSha:p,pr:a}},nm=e=>({branch:e.branch,label:e.label,baseBranch:e.baseBranch,worktreePath:e.worktreePath,worktreePresent:e.worktreePresent,worktreeDirty:e.worktreeDirty,cmuxWorkspacePresent:e.cmuxWorkspacePresent,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha,pr:e.pr,jiraConfigured:e.jiraConfig!==null,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name}:null,jiraFixCount:e.jira?.fixCount??null,jiraAffectsCount:e.jira?.affectsCount??null,moveIssuesTo:e.moveIssuesTo?{id:e.moveIssuesTo.id,name:e.moveIssuesTo.name}:null}),Yb=(e,r)=>{if(r)return"skipped (--skip-jira)";if(!e.jiraConfig)return"skipped (Jira not configured)";if(!e.jira)return"none found";let{version:t,fixCount:o,affectsCount:n}=e.jira,s=`fixVersion on ${o} issue(s), affectsVersion on ${n} issue(s)`,i=e.moveIssuesTo?`, reassigned to ${e.moveIssuesTo.name}`:"";return`${t.name} \u2014 ${s}${i}`},Zb=(e,r)=>{let t=e.pr?`#${e.pr.number} (${e.pr.state})`:"none",o=[`Remove release ${e.label} (${e.branch})? This will:`,` \u2022 worktree: ${e.worktreePresent?e.worktreePath:"none"}`,` \u2022 PR: ${t}`,` \u2022 local branch: ${e.localTipSha??"absent"} (switching to ${e.baseBranch} first)`,` \u2022 remote branch: ${e.remoteTipSha??"absent"}`,` \u2022 Jira version: ${Yb(e,r)}`];return e.cmuxWorkspacePresent&&o.push(` \u2022 the cmux window rooted at ${e.worktreePath} will close`),o.join(`
436
+ `)},Rs=class extends Error{constructor(t,o){super(`step ${t} failed`,{cause:o});this.step=t;this.reason=o;this.name="StepFailure"}step;reason},Xb=e=>typeof e=="string"?e:e.outcome;async function tn(e,r,t){try{let o=await t(),n=Xb(o);return r.push({step:e}),l.info({step:e,outcome:n},`\u2705 ${Es[e]} \u2014 ${n}`),o}catch(o){throw new Rs(e,o)}}var Qb=async(e,r,t)=>{try{await t(),r.push({step:e})}catch(o){r.push({step:e,detail:"attempted"}),l.warn({err:hr(o),step:e},`\u26A0\uFE0F ${Es[e]} failed (non-blocking)`)}},eR=(e,r)=>r.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:r.detail?`${r.step} (${r.detail})`:r.step,rR=e=>{let{plan:r,step:t,done:o,cause:n}=e,s=o.map(u=>eR(r,u)).join(", ")||"nothing",i=r.jira?`The Jira fix version ${r.jira.version.name} was NOT removed. `:"",a=r.localTipSha?`Restore the branch with \`git branch ${r.branch} ${r.localTipSha}\`. `:"",c=Oe(`Re-call release-remove with "version": "${r.label}" to finish; completed steps are skipped.`,`Re-run \`infra-kit release remove --version ${r.label}\` to finish; completed steps are skipped.`),p=`completed: ${s}. ${i}${a}${c}`,d=n instanceof g?n.remediation:void 0;return new g(n,{operation:`remove release ${r.label} \u2014 step ${tm.indexOf(t)+1} of ${tm.length} (${Es[t]})`,remediation:d?`${d} \u2014 ${p}`:p})},tR=async e=>{let r=await Go(e.branch,{operation:`remove the worktree for ${e.branch}`,remediation:`commit or discard the changes inside ${e.worktreePath} (\`git -C ${e.worktreePath} stash -u\`), then re-run`});return{outcome:r.includes(e.branch)?"removed":"absent",removedBranches:r}},oR=e=>{let r=e.map(s=>({provider:s.provider,outcome:nR(s),removed:s.removed})),t=r.some(s=>s.outcome==="verified"),n=r.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:t?"verified":n,providers:r}},nR=e=>e.provider==="zed"?"skipped":e.removed.length>0?"verified":"attempted",sR=async(e,r,t)=>{let o={outcome:"attempted",providers:[]};return await Qb("ide-folders",t,async()=>{let n=await Qr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,currentWorktrees:e.currentWorktrees,removedWorktrees:r,allowEditorRelaunch:!1});o=oR(n)}),l.info({outcome:o.outcome,step:"ide-folders"},`\u2705 ${Es["ide-folders"]} \u2014 ${o.outcome}`),o},iR=async e=>{let r=await Hr(e.branch);if(sm({...e,pr:r}),!r)return{outcome:"absent",number:null};if(r.state==="CLOSED")return{outcome:"already-closed",number:r.number};let t=`Closed by \`infra-kit release remove\`: release ${e.label} was torn down.`;return await fc`gh pr close ${String(r.number)} --comment ${t}`,{outcome:"closed",number:r.number}},aR=async e=>(await ct()===e.branch&&await fc`git switch ${e.baseBranch}`,await kn(e.branch),await hl(e.branch)?xe({operation:`delete local branch ${e.branch}`,remediation:`delete it by hand with \`git branch -D ${e.branch}\`, then re-run to finish the removal`,stderrExcerpt:`${e.branch} still exists after the delete`}):e.localTipSha?"deleted":"absent"),cR=async e=>(await bn(e.branch),e.remoteTipSha?"deleted":"absent"),lR=async(e,r,t)=>{let o=await os(r.version.id,t);if(o.issuesFixedCount===r.fixCount&&o.issuesAffectedCount===r.affectsCount)return;let n=Oe(`re-call release-remove with "version": "${e.label}"`,`re-run \`infra-kit release remove --version ${e.label}\``);xe({operation:`remove Jira fix version "${r.version.name}"`,remediation:`the fix version was NOT removed and every other step is complete \u2014 ${n} so the guard re-evaluates the new counts`,stderrExcerpt:`issue counts changed since preflight: fixVersion ${r.fixCount} \u2192 ${o.issuesFixedCount}, affectsVersion ${r.affectsCount} \u2192 ${o.issuesAffectedCount}`})},pR=async(e,r)=>r.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await lR(e,e.jira,e.jiraConfig),l.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await ia({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),dR=(e,r)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:r.worktree.outcome,ideFolders:r.ideFolders,pr:r.pr.outcome,prNumber:r.pr.number,localBranch:r.localBranch,localTipSha:e.localTipSha,remoteBranch:r.remoteBranch,remoteTipSha:e.remoteTipSha,jira:r.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),uR=async(e,r,t)=>{let o=await tn("worktree",t,()=>tR(e)),n=await sR(e,o.removedBranches,t),s=await tn("pr",t,()=>iR(e));l.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await tn("local-branch",t,()=>aR(e)),a=await tn("remote-branch",t,()=>cR(e)),c=await tn("jira",t,()=>pR(e,r));return{worktree:o,ideFolders:n,pr:s,localBranch:i,remoteBranch:a,jira:c}},mR=async(e,r)=>{let t=[];try{return dR(e,await uR(e,r,t))}catch(o){throw o instanceof Rs?rR({plan:e,step:o.step,done:t,cause:o.reason}):o}},fR=async e=>{if(e)return qe(e);h.setInteractive();let[r,t]=await Promise.all([V(),$()]),o=t.map(s=>s.branch);o.length===0&&xe({operation:"select a release to remove",remediation:"pass `--version <ref>` to remove a release that is already partially torn down",stderrExcerpt:"no open release PRs to pick from"});let n=new Map(t.map(s=>[s.branch,D(s.title)]));try{return await gr(te({branches:o,descriptions:r,types:n}))}catch(s){throw je(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},im=mc(),am=async e=>{let{confirmedCommand:r,version:t,moveIssuesTo:o,skipJira:n}=e;await ce({operation:on}),await x(),await he({provider:im,params:e,operation:on,argument:"version"}),Jb(e);try{let s=await qb(await fR(t),e);l.debug({plan:nm(s)},"release remove: resolved plan"),sm(s),Vb(s,e),Bb(s),await No({operation:`remove release ${s.label}`,base:s.baseBranch}),Gb(s),h.addOption("--version",s.label),o&&h.addOption("--move-issues-to",o),n&&h.addOption("--skip-jira",!0),await Y(r,Zb(s,!!n),{throwOnDecline:!0,plan:{...nm(s),skipJira:!!n}}),r||h.addOption("--yes",!0);let i=await mR(s,e);return h.print(),{content:y(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw je(s)||Tn(s)||s instanceof g?s:(l.error({err:hr(s)},"\u274C Error removing release"),new g(s,{operation:on,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},gc=w({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (and the cmux window rooted there), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:im,inputSchema:{version:I.string().optional().describe('The release version or name to remove (e.g. "1.2.5" or "checkout-redesign"). Omit it to be offered the open release PRs.'),moveIssuesTo:I.string().optional().describe(`Optional. An EXISTING Jira fix version name (exactly as in Jira, e.g. "v1.2.6") to move this release's issues to before its fix version is removed \u2014 both fixVersion and affectsVersion. Pass it only after a refusal reported the issue counts, or when the human named the target; a name Jira does not know is refused in preflight before anything is touched.`),confirm:I.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:I.string().describe("The release branch that was targeted"),version:I.string().describe('The release label (e.g. "1.2.5")'),baseBranch:I.string().describe("The branch HEAD was moved to before the local delete"),worktree:I.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:I.object({outcome:I.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; Zed is always a declared skip'),providers:I.array(I.object({provider:I.string(),outcome:I.enum(["verified","attempted","skipped"]),removed:I.array(I.string()).describe("Folder paths confirmed removed; always empty for Zed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:I.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:I.number().nullable().describe("The pull request number, or null when none exists"),localBranch:I.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:I.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:I.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:I.string().nullable().describe("The origin tip before deletion"),jira:I.enum(["removed","absent","skipped"]).describe('"removed" when the fix version was deleted; "absent" when Jira knows none for this release (the resume path); "skipped" only on the CLI with --skip-jira'),jiraVersion:I.object({id:I.string(),name:I.string(),url:I.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:am});import{execFile as wR}from"node:child_process";import lm from"node:path";import pm from"node:process";import{z as X}from"zod";import hc from"node:fs/promises";import nn from"node:path";var cm=async e=>{try{return await hc.access(e),!0}catch{return!1}},gR=async e=>{if(e&&e.length>0)return e;try{let r=await Te();return[nn.dirname(r)]}catch(r){throw new g(r,{operation:"discover infra-kit projects",remediation:"run inside an infra-kit repo, or pass --root <dir>"})}},hR=e=>e.isDirectory()||e.isSymbolicLink(),vR=async(e,r)=>{if(!hR(r))return null;let t=nn.join(e,r.name),[o,n]=await Promise.all([cm(nn.join(t,".git")),cm(nn.join(t,"infra-kit.json"))]);if(!o||!n)return null;try{let s=await hc.realpath(t);return{name:nn.basename(t),repoRoot:s}}catch{return null}},yR=async e=>{try{return await hc.readdir(e,{withFileTypes:!0})}catch{return[]}},vc=async(e={})=>{let r=await gR(e.roots),t=new Map;for(let o of r){let n=await yR(o);for(let s of n){let i=await vR(o,s);i&&!t.has(i.repoRoot)&&t.set(i.repoRoot,i)}}return[...t.values()].sort((o,n)=>o.name.localeCompare(n.name))};var kR=async(e={})=>e.all?CR(e):dm(e),dm=async(e={})=>{let{releaseOnly:r=!1,force:t=!1,dryRun:o=!1}=e;await x();try{let n=await R(),s=`${n}${oe}`,i=lm.basename(await Te(n)),a=await rr(n),c=bR(a,r),p=c.map(k=>k.path),d=c.map(k=>k.branch).filter(k=>xr(k)),u=c.map(k=>({title:_n({branch:k.branch??lm.basename(k.path)}),cwd:k.path}));if(o){let k=await xR({repo:i,releaseOnly:r,force:t,worktreePaths:p,targets:u});return SR(k,s),h.print(),{content:y(JSON.stringify(k,null,2)),structuredContent:k}}let[m,v]=await Promise.all([dc({projectRoot:n,worktreeDir:s,worktreePaths:p,currentBranches:d}),RR({targets:u,force:t,repoName:i})]),f={repo:i,dryRun:!1,releaseOnly:r,worktreePaths:p,ideProviders:m.filter(k=>k.ran).map(k=>k.provider),cmuxOpened:v.opened,cmuxSkipped:v.skipped,cmuxClosed:v.closed};return TR(f,{ideRan:m.some(k=>k.ran)}),h.print(),{content:y(JSON.stringify(f,null,2)),structuredContent:f}}catch(n){throw n instanceof g?n:(l.debug({err:n},"Error reopening worktree windows"),new g(n,{operation:"reopen worktrees",remediation:"run `infra-kit doctor` to check this project's setup"}))}},bR=(e,r)=>e.filter(t=>t.bare||t.prunable?!1:r?xr(t.branch):!0),RR=async e=>{let{targets:r,force:t,repoName:o}=e,n=await In(o),s=t?await ER({targets:r}):[],{opened:i,skipped:a}=await PR({targets:r,force:t,repoName:o,groupRef:n});return{opened:i,skipped:a,closed:s}},ER=async e=>{let{targets:r}=e;if(r.length===0)return[];let t=await nr(),o=[];for(let n of r)t.has(await Tr(n.cwd))&&(await An(n.cwd),o.push(n.title));return o},um=async(e,r,t)=>{let o=[],n=[];for(let s of e)!t&&r.has(await Tr(s.cwd))?n.push(s.title):o.push(s);return{toOpen:o,skipped:n}},PR=async e=>{let{targets:r,force:t,repoName:o,groupRef:n=null}=e,s=t?new Set:new Set((await nr()).keys()),{toOpen:i,skipped:a}=await um(r,s,t),c=[],p=n,d=!1;for(let u of i)try{if(p)await pt({cwd:u.cwd,title:u.title,group:p});else{let m=await pt({cwd:u.cwd,title:u.title});d||(p=await $n(o,[m]),d=!0)}c.push(u.title)}catch(m){l.warn({error:m,title:u.title},`\u26A0\uFE0F Failed to reopen cmux workspace ${u.title}`)}return{opened:c,skipped:a}},xR=async e=>{let{repo:r,releaseOnly:t,force:o,worktreePaths:n,targets:s}=e,i=o?new Set:new Set((await nr()).keys()),{toOpen:a,skipped:c}=await um(s,i,o);return{repo:r,dryRun:!0,releaseOnly:t,worktreePaths:n,ideProviders:[],cmuxOpened:a.map(p=>p.title),cmuxSkipped:c,cmuxClosed:[]}},SR=(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}`)}},TR=(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=>uc(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")},CR=async e=>{let{project:r=[],root:t=[],releaseOnly:o=!1,force:n=!1,dryRun:s=!1}=e,i=await vc({roots:t}),a=AR(i,r),c=IR({releaseOnly:o,force:n,dryRun:s}),p=[];for(let u of a)p.push(await $R(u,c));let d={all:!0,dryRun:s,projects:a,results:p};return DR(d),h.print(),{content:y(JSON.stringify(d,null,2)),structuredContent:d}},AR=(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))},IR=e=>{let r=[];return e.dryRun&&r.push("--dry-run"),e.releaseOnly&&r.push("--release-only"),e.force&&r.push("--force"),r},$R=async(e,r)=>{try{let t=await _R(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}}},_R=(e,r)=>{let t=pm.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,n)=>{let s=[t,"reopen","--json",...r];wR(pm.execPath,s,{cwd:e,maxBuffer:16*1024*1024},(i,a)=>{if(i){n(i);return}o(a)})})},DR=e=>{let r=e.results.filter(s=>s.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,n=0;for(let s of e.results)s.ok?(o+=s.cmuxOpened.length,n+=s.cmuxSkipped.length,l.info(` \u2705 ${s.repo}: ${s.worktreePaths.length} folder(s), ${s.cmuxOpened.length} cmux ${e.dryRun?"planned":"opened"}, ${s.cmuxSkipped.length} skipped`)):l.info(` \u274C ${s.repo}: ${s.error}`);l.info(`\u{1F4CA} ${r} ok, ${t} failed \u2014 ${o} cmux ${e.dryRun?"planned":"opened"}, ${n} already open`)},yc=w({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:X.boolean().optional().describe("Restrict to release worktrees (reproduces the legacy worktrees-reload scope)"),force:X.boolean().optional().describe("Close each cmux workspace first, then reopen (disruptive)"),dryRun:X.boolean().optional().describe("Return the plan (paths + cmux titles) without spawning anything")},outputSchema:{repo:X.string().describe("Repository name the reopen ran for"),dryRun:X.boolean().describe("Whether this was a dry run (nothing was spawned)"),releaseOnly:X.boolean().describe("Whether the set was restricted to release worktrees"),worktreePaths:X.array(X.string()).describe("Absolute folder set handed to the editor (root-first)"),ideProviders:X.array(X.string()).describe("Configured IDE providers that opened (cursor | zed); empty in dry run"),cmuxOpened:X.array(X.string()).describe("Titles of cmux workspaces opened this run"),cmuxSkipped:X.array(X.string()).describe("Titles of cmux workspaces skipped because already open (additive mode)"),cmuxClosed:X.array(X.string()).describe("Titles of cmux workspaces closed first (force mode only)")},handler:dm});import{spawnSync as jR}from"node:child_process";import{homedir as FR}from"node:os";import LR from"node:process";var OR=e=>{let r=new Set(e.steps.map(t=>t[0]));return r.has("brew")?"homebrew":r.has("npm")?"npm":null},NR=e=>{let r=[];return e.needsSudo&&r.push("needs-sudo"),e.fetchesNetworkScript&&r.push("fetches-network-script"),r},MR=(e,r)=>{let t=OR(e);if(t===null)return[];let o=[];return r.present.includes(t)||o.push("manager-absent"),r.owner!==null&&r.owner!==t&&o.push("manager-mismatch"),o},sn=(e,r)=>{let t=[...NR(e),...MR(e,r)];return t.length===0?{executable:!0}:{executable:!1,reasons:t}},an=e=>e.steps.map(qc);var WR=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],JR=e=>{let r={...zc(e)};for(let t of WR)delete r[t];return r},wc=(e,r,t={})=>{let o=t.spawnSync??jR,n=t.env??LR.env,s=(t.agentMode??z)(),i=an(e),a=sn(e,r);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:GR({recipe:e,spawn:o,env:n,commands:i,notify:t.notify??VR}):{ran:!1,commands:i,refusedBecause:a.reasons}},VR=e=>{l.info(e)},fm=64,BR=fm*1024*1024,GR=({recipe:e,spawn:r,env:t,commands:o,notify:n})=>{let s=JR(t);for(let[i,a]of e.steps.entries()){n(` ${"running".padEnd(9)} ${o[i]}`);let c=r(a[0],a.slice(1),{stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:BR,cwd:FR(),env:s}),p=YR(c);if(p!==null)return{ran:!0,ok:!1,commands:o,failedStep:o[i],detail:p}}return{ran:!0,ok:!0,commands:o}},UR=5,KR=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,mm=e=>e==null?[]:String(e).split(`
437
+ `).map(r=>r.trim()).filter(r=>r.length>0),HR=e=>{let r=mm(e.stderr),t=mm(e.stdout),o=[...r,...t].filter(s=>KR.test(s)),n=r.length>0?r:t;return(o.length>0?o:n).slice(-UR).join(" / ")},zR="ENOBUFS",qR=e=>e.error?.code===zR,YR=e=>{if(qR(e))return`terminated after exceeding the ${fm} MiB output limit \u2014 it may be part-installed`;if(e.error)return`could not start: ${e.error.message}`;if(e.signal)return`terminated by signal ${e.signal}`;if(e.status===0)return null;let r=HR(e),t=r===""?"":`: ${r}`;return`exited ${e.status??"unknown"}${t}`};var ZR=e=>{let r=[];return e.some(o=>o.id==="brew"&&o.present)&&r.push("homebrew"),r.push("npm"),r},XR=e=>{let r=Ee(e.id);return e.present?r.updateFor(e.binRealPath):r.bootstrapInstall},QR=(e,r)=>{let t=XR(e),o={...r,owner:e.present?e.manager:null};if(t===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:o};let n=sn(t,o);return{state:e,action:e.present?"update":"install",recipe:t,executable:n.executable,refusedBecause:n.executable?[]:n.reasons,commands:an(t),context:o}},Ps=async(e=Vr,r=So())=>{let t=await Io(Vr,r),o={owner:null,present:ZR(t)},n=oa(e),s=new Map(t.map(a=>[a.id,a]));return{plans:n.filter(a=>e.includes(a)).map(a=>QR(s.get(a),o)),context:o}};var kc=(e,r)=>({...cn(e),action:"skipped",commands:e.commands,detail:r}),cn=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),gm=(e,r)=>e.action==="none"?kc(e,`nothing to do: ${e.state.manager} installs are not managed from here`):r==="update"&&e.action==="install"?kc(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...cn(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},eE=(e,r)=>r.ran?r.ok?{...cn(e),action:e.action==="install"?"installed":"updated",commands:r.commands,detail:e.action==="install"?"installed":"updated"}:{...cn(e),action:"failed",commands:r.commands,detail:`${r.failedStep??"a step"} ${r.detail??"failed"}`}:{...cn(e),action:"refused",commands:r.commands,detail:`refused (${r.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},bc=async e=>{let r=e.run??wc,{plans:t}=await Ps(e.ids,e.probeDeps),o=[];for(let n of t){let s=gm(n,e.mode);if(s!==null){o.push(s);continue}o.push(eE(n,r(n.recipe,n.context)))}return o},Rc=async(e,r)=>{let{plans:t}=await Ps(e,r);return t.map(o=>gm(o,"converge")??kc(o,`would ${o.action} \u2014 nothing was run (--skip-tools)`))};import rE from"node:process";import{z as O}from"zod";var tE=()=>{let e=cl();return{link:e,target:{home:e.home,processStartTime:()=>null}}},oE=e=>{switch(e){case"created":return"linked ~/.infra-kit/portless to the running portless";case"repointed":return"re-pointed ~/.infra-kit/portless to the running portless";case"unchanged":return"already linked to the running portless";case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-unresolved":return"skipped \u2014 portless is not installed";case"failed":return"could not update the link \u2014 see the debug log";default:return Pe(e)}},nE=async e=>{let r=al(e.link);l.info(` ${r.outcome.padEnd(9)} portless link \u2014 ${oE(r.outcome)}`);let t=vn(e.link.home,e.target.exists)??e.link.resolveBin();t!==null&&await Fd(e.target,t)!=="converged"&&(l.info("Run this yourself to finish the portless service:"),l.info(` ${Pr(t,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath})}`))},vm="--skip-tools cannot be combined with --tools or --update: --skip-tools installs and updates nothing at all, so narrowing what it would act on is a contradiction. Use one or the other.",sE=e=>{let r=Array.isArray(e.update)?e.update:void 0,t=e.update===!0||r!==void 0,o=e.skipTools===!0;if(o&&(e.tools!==void 0||t))throw new Error(vm);return{ids:e.tools??r??Vr,mode:t?"update":"converge",skipTools:o}},hm=(e,r)=>e instanceof _t?e.step:r.at(-1)?.step??"zshrc",iE=async()=>{let e=[],r=t=>{e.push(t),t.message!==xo&&Qn(t)};try{return await zi(r),{entries:e,failed:!1}}catch(t){let o={step:hm(t,e),outcome:"warned",message:`The ${hm(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"};return Qn(o),e.push(o),{entries:e,failed:!0}}},aE=async(e,r,t)=>{for(let o of e)l.info(` ${o.action.padEnd(9)} ${o.id} \u2014 ${o.detail}`);for(let o of e)if(cE(o,r)){l.info(`Run these yourself to ${r?"set up":"finish"} ${o.id}:`);for(let n of o.commands)l.info(` ${n}`)}await nE(t),l.info(xo)},cE=(e,r)=>e.commands.length===0?!1:e.action==="refused"||r&&e.action==="skipped",lE=e=>({step:e.step,outcome:e.outcome,message:e.message}),ym=async(e={})=>{let r=sE(e),t=await iE(),o=r.skipTools?await Rc(r.ids,e.probeDeps):await bc({ids:r.ids,mode:r.mode,probeDeps:e.probeDeps,run:e.run});await aE(o,r.skipTools,e.portlessDeps??tE());let n={init:t.entries.map(lE),tools:o,converged:!r.skipTools,changed:o.some(s=>s.action==="installed"||s.action==="updated"),allSucceeded:o.every(s=>s.action!=="failed")};return(t.failed||!n.allSucceeded)&&(rE.exitCode=1),{content:y(JSON.stringify(n,null,2)),structuredContent:n}},pE=O.object({step:O.enum(["zshrc","zshenv","migrations","user-config","guidance","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:O.enum(["written","unchanged","skipped","warned"]).describe("What that step did: changed something, found nothing to change, did not run, or failed non-fatally"),message:O.string().describe("The same line a human running this would have read")}),dE=O.object({id:O.string().describe("Dependency id"),action:O.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:O.object({present:O.boolean(),onPath:O.boolean(),version:O.string().nullable(),manager:O.string()}).describe("The tool\u2019s state before this run"),commands:O.array(O.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:O.string().describe("Why, in one line")}),uE={init:O.array(pE).describe("One entry per init step, in the order they ran"),tools:O.array(dE).describe("One result per requested dependency"),converged:O.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:O.boolean().describe("Whether anything was installed or updated"),allSucceeded:O.boolean().describe("Whether no tool failed (a refusal is not a failure)")},mE={tools:O.array(O.enum(Vr)).optional().describe("Which tools to act on. Omit for all five."),mode:O.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:O.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},fE={"anthropic/requiresUserInteraction":!0},Ec=w({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:mE,outputSchema:uE,requiresHumanConfirm:!0,meta:fE,handler:e=>ym({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as bm}from"node:fs";import Rm from"node:path";import PE from"node:process";import{z as Qe}from"zod";import{createHash as gE}from"node:crypto";import{readFileSync as hE}from"node:fs";var Pc=e=>gE("sha256").update(hE(e)).digest("hex");import{readFileSync as RE,writeFileSync as cB}from"node:fs";import km from"node:path";import{z as Ne}from"zod";var Ze="vendor",vE=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),yE=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),wE=[".tsbuildinfo"],xc=e=>vE.has(e),Sc=e=>yE.has(e)?!0:wE.some(r=>e.endsWith(r)),wm=e=>{let r=e.split("/"),t=r.pop()??"";return r.some(n=>xc(n))||Sc(t)};import{readdirSync as kE}from"node:fs";import Tc from"node:path";var bE=e=>e.split(Tc.sep).join("/"),Cc=e=>{let r=[],t=o=>{for(let n of kE(o,{withFileTypes:!0})){let s=Tc.join(o,n.name);if(n.isDirectory()){if(xc(n.name))continue;t(s);continue}Sc(n.name)||r.push(bE(Tc.relative(e,s)))}};return t(e),r.sort()};var Xe=".sync-manifest.json",Ac=1,EE=Ne.object({schemaVersion:Ne.number().optional(),source:Ne.string(),commit:Ne.string(),syncedAt:Ne.string(),fileCount:Ne.number(),files:Ne.record(Ne.string(),Ne.string())}),Ic=e=>(e.schemaVersion??Ac)>Ac;var $c=e=>{let r=km.join(e,Xe),t;try{t=RE(r,"utf8")}catch{throw new Error(`Missing ${Xe} at ${r}`)}let o=EE.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${Xe} at ${r}: ${Ne.prettifyError(o.error)}`);return o.data};var _c=(e,r)=>{let t=Object.fromEntries(Object.entries(r.files).filter(([c])=>!wm(c))),o=Cc(e),n=[],s=[];for(let c of o){if(!(c in t)){s.push(c);continue}Pc(km.join(e,c))!==t[c]&&n.push(c)}let i=new Set(o),a=Object.keys(t).filter(c=>!i.has(c));return{modified:n,added:s,removed:a}};var Dc=30,Oc=(e,r)=>{if(r.length!==0){l.info(`
438
+ ${e} (${r.length}):`);for(let t of r.slice(0,Dc))l.info(` ${t}`);r.length>Dc&&l.info(` \u2026and ${r.length-Dc} more`)}},Em=async(e={})=>{let r=e.cwd??await R(),t=Rm.join(r,Ze),o={modified:[],added:[],removed:[],fileCount:0};if(!bm(t)){l.info(`\u2139\uFE0F No ${Ze}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...o};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}if(!bm(Rm.join(t,Xe))){l.error(`\u274C Missing ${Ze}/${Xe}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...o};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}let n=$c(t);if(Ic(n)){l.error(`\u274C ${Ze}/${Xe} has a newer schemaVersion (${String(n.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...o};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=_c(t,n),c=s.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${Ze}/ has drifted from ${Ze}/${Xe}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Oc("Modified",s),Oc("Added (not in manifest)",i),Oc("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${Ze}/ matches manifest (${n.fileCount} files).`);let p={status:c?"drift":"clean",ok:!c,fileCount:n.fileCount,modified:s,added:i,removed:a};return{content:y(JSON.stringify(p,null,2)),structuredContent:p}},xE={status:Qe.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:Qe.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:Qe.number(),modified:Qe.array(Qe.string()),added:Qe.array(Qe.string()),removed:Qe.array(Qe.string())},Nc=w({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:xE,handler:()=>Em({cwd:PE.cwd()})});import Mc from"node:process";import{z as et}from"zod";var SE="mcp__plugin_infra-kit_infra-kit__",TE="mcp__infra-kit__",Pm=e=>{let r=e.CLAUDE_PLUGIN_ROOT;return r!==void 0&&r!==""?"plugin":"legacy"},xm=e=>e==="plugin"?SE:TE;var Sm=async e=>{try{return await e()}catch{return null}},Tm=async()=>{let e=q.version;l.info(e);let r=Pm(Mc.env),t=await Sm(R),o=t===null?null:await Sm(()=>Te(t)),n={version:e,cwd:Mc.cwd(),repoRoot:t,mainRepoRoot:o,projectDir:Mc.env.CLAUDE_PROJECT_DIR||null,launch:r,toolPrefix:xm(r)};return{content:y(JSON.stringify(n,null,2)),structuredContent:n}},jc=w({name:"version",description:"Print the installed infra-kit CLI version, where this server process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR) and which route spawned it (plugin or a repo .mcp.json entry) with the tool prefix that route produces",inputSchema:{},outputSchema:{version:et.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:et.string().describe("The working directory of this server process"),repoRoot:et.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:et.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:et.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this server, or null"),launch:et.enum(["plugin","legacy"]).describe("Which route spawned this server: the Claude Code plugin, or a repo .mcp.json entry (legacy)"),toolPrefix:et.string().describe("The prefix every tool of this server carries in this session")},handler:Tm});import Cm from"@inquirer/confirm";import CE from"node:path";import{z as er}from"zod";import{$ as ln}from"zx";var AE="feature",IE="release",Im=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:n,cmux:s}=e,i=e.ide??e.cursor;await ce({operation:"create worktrees"});try{let a=await me("release"),c=await R(),p=`${c}${oe}`;await Am(`${p}/${IE}`),await Am(`${p}/${AE}`);let d=[];if(o)d=o.split(",").map(C=>Se(ke(C.trim())));else{let C=await $(),T=C.map(E=>E.branch);if(T.length===0)return l.info("\u2139\uFE0F No open release branches found"),h.print(),{content:y(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=T;else{h.setInteractive();let E=new Map(C.map(se=>[se.branch,D(se.title)])),Me=await V();d=await Ut(te({branches:T,descriptions:Me,types:E}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",Kr(d)),await Y(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let u=await x(),m=i??(Ce(u).length>0?"workspace":"none");h.addOption("--ide",m);let v=n??u.worktrees?.openInGithubDesktop??await A(C=>Cm({message:"Open created worktrees in GitHub Desktop?"},C),{whenHeadless:{value:!1}});typeof n>"u"&&u.worktrees?.openInGithubDesktop===void 0&&h.setInteractive(),v?h.addOption("--github-desktop",!0):h.addOption("--no-github-desktop",!0);let f=s??u.worktrees?.openInCmux??await A(C=>Cm({message:"Open created worktrees in cmux?"},C),{whenHeadless:{value:!1}});typeof s>"u"&&u.worktrees?.openInCmux===void 0&&h.setInteractive(),f?h.addOption("--cmux",!0):h.addOption("--no-cmux",!0);let{branchesToCreate:k}=$E({selectedReleaseBranches:d,currentWorktrees:a}),P=await _E(k,p);if(DE(P),m==="workspace"&&await pc({projectRoot:c,worktreeDir:p,branches:P}),v)for(let C of P)await ln`github ${p}/${C}`,await ln`sleep 5`;if(f){let C=CE.basename(await Te(c)),T=await nr(),E=await In(C),Me=!1;for(let se of P){let tt=`${p}/${se}`;if(T.has(await Tr(tt)))continue;let yr=_n({branch:se});try{if(E)await pt({cwd:tt,title:yr,group:E});else{let wr=await pt({cwd:tt,title:yr});Me||(E=await $n(C,[wr]),Me=!0)}}catch(wr){l.warn({error:wr,branch:se},`\u26A0\uFE0F Failed to open cmux workspace for ${se}`)}}}h.print();let Q={createdWorktrees:P,count:P.length};return{content:y(JSON.stringify(Q,null,2)),structuredContent:Q}}catch(a){throw je(a)||a instanceof N?a:(l.debug({err:a},"Error managing worktrees"),new g(a,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},Am=async e=>{await ln`mkdir -p ${e}`},$E=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>xr(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},_E=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await ln`git worktree add ${s} ${n}`,await ln({cwd:s})`pnpm install`,n})),o=[];for(let[n,s]of t.entries())if(s.status==="fulfilled")o.push(s.value);else{let i=e[n],a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});l.error({error:s.reason,msg:a.message})}return o},DE=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")},Fc=w({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:er.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:er.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:er.enum(ks).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:er.enum(ks).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:er.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:er.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:er.array(er.string()).describe("List of created git worktree branches"),count:er.number().describe("Number of git worktrees created")},handler:Im});import{z as Zt}from"zod";var $m=async()=>{await x();let e=await me("release");if(e.length===0)return l.info("\u2139\uFE0F No active worktrees found"),{content:y(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([$(),V()]),o=new Map(r.map(c=>[c.branch,D(c.title)])),n=e.flatMap(c=>{let p=j(c);if(!p)return[];let d=W(p),u=o.get(c)||"regular",m=t.get(G(p))||null;return[{version:d,type:u,description:m}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=jo(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});l.info(`\u{1F33F} Active worktrees:
439
+
440
+ ${i.join(`
441
+ `)}`);let a={worktrees:n,count:n.length};return{content:y(JSON.stringify(a,null,2)),structuredContent:a}},Lc=w({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:Zt.array(Zt.object({version:Zt.string().describe("Release version"),type:Zt.enum(["regular","hotfix"]).describe("Release type"),description:Zt.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Zt.number().describe("Number of worktrees")},handler:$m});import{z as rt}from"zod";var OE=e=>{if(!z())return;let r=_.source==="mcp";if(e.all)throw new N({status:"refused",agentMode:_.source},2,{operation:"remove worktrees",remediation:r?'name targets explicitly via "versions"; bulk all=true removal is disabled over MCP':"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:r?"all=true is not permitted for worktrees-remove over MCP":"--all is not permitted for worktrees remove under agent mode"});if(!e.versions)throw new N({status:"argument_required",argument:"versions",agentMode:_.source},2,{operation:"remove worktrees",remediation:r?'pass "versions" (comma-separated release versions/names); the interactive picker needs a TTY':"pass --versions <refs> (comma-separated release versions/names) on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:r?'worktrees-remove over MCP requires "versions"':"worktrees remove under agent mode requires --versions"})},NE=(e,r)=>{let t=e.filter(o=>!r.includes(o));if(t.length>0)throw new g(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${t.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${t.join(", ")}`})},_m=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await ce({operation:"remove worktrees"}),await x(),OE({all:t,versions:o});try{let n=await me("release");if(n.length===0){l.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}let s=await R(),i=`${s}${oe}`,a=[];if(t)a=n;else if(o)a=o.split(",").map(d=>Se(ke(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([V(),$()]),m=new Map(u.map(v=>[v.branch,D(v.title)]));a=await Ut(te({branches:n,descriptions:d,types:m}),{required:!0})}NE(a,n);let c=a.length===n.length;c?h.addOption("--all",!0):h.addOption("--versions",Kr(a)),await Y(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let p=await qr({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await Qr({projectRoot:s,worktreeDir:i,currentWorktrees:n,removedWorktrees:p.removed,allowEditorRelaunch:!r}),Vo(p),h.print(),Bo({result:p,operation:"remove worktrees"})}catch(n){throw je(n)||n instanceof g?n:(l.error({error:n},"\u274C Error managing worktrees"),new g(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Wc=w({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named version must be an active worktree, or the call errors without removing anything. What survives: the release branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.',requiresHumanConfirm:!0,inputSchema:{versions:rt.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:rt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:rt.array(rt.string()).describe("List of removed git worktree branches"),failedWorktrees:rt.array(rt.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:rt.number().describe("Number of git worktrees removed")},handler:_m});import{z as pn}from"zod";var Dm=async e=>{let{confirmedCommand:r}=e;await ce({operation:"sync worktrees"}),await x();try{let t=await me("release"),o=await R(),n=`${o}${oe}`,s=await cs();await Y(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let{branchesToRemove:i}=ME({releasePRsList:s,currentWorktrees:t}),a=await qr({branches:i,worktreeDir:n,projectRoot:o});return await Qr({projectRoot:o,worktreeDir:n,currentWorktrees:t,removedWorktrees:a.removed,allowEditorRelaunch:!1}),Vo(a),h.print(),Bo({result:a,operation:"sync worktrees"})}catch(t){throw je(t)||t instanceof g?t:(l.error({error:t},"\u274C Error managing worktrees"),new g(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},ME=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>xr(s)).filter(s=>!r.includes(s))}},Jc=w({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:pn.array(pn.string()).describe("List of removed worktree branches"),failedWorktrees:pn.array(pn.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:pn.number().describe("Number of worktrees removed during sync")},handler:Dm});var ny=[{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"}],Wt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:xi,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:Ca,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Va,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:oc,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:nc,mcpExposed:!0,mutating:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:La,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ja,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Ia,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:gc,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Za,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Xa,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Fc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Lc,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"reopen",menuGroup:"worktrees",mcpTool:yc,mcpExposed:!0,mutating:!1,groupPath:["reopen"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Wc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Jc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:ka,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:_i,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Li,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:wa,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Ra,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Ri,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:Nc,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"setup",menuGroup:"setup",mcpTool:Ec,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:va,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:bi,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:jc,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:"mcp",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["mcp"]}];var jE={"dev-status":{title:"Dev server status",openWorld:!1},"gh-release-list":{title:"Open releases",openWorld:!0},"worktrees-list":{title:"Release worktrees",openWorld:!0},"env-status":{title:"Loaded environment",openWorld:!1},"env-list":{title:"Available environments",openWorld:!1},"env-token-list":{title:"Doppler service tokens",openWorld:!0},"config-get":{title:"Merged infra-kit config",openWorld:!1},"vendor-check":{title:"Vendor checksum check",openWorld:!1},audit:{title:"Package audit",openWorld:!1},version:{title:"CLI version",openWorld:!1},doctor:{title:"Diagnose this machine",openWorld:!0},setup:{title:"Set up this machine",openWorld:!0},"gh-merge-dev":{title:"Merge dev into release branches",openWorld:!0},"release-create":{title:"Create releases",openWorld:!0},"release-remove":{title:"Remove a release",openWorld:!0},"gh-release-deploy-all":{title:"Deploy all services (CI)",openWorld:!0},"gh-release-deploy-selected":{title:"Deploy selected services (CI)",openWorld:!0},"local-deploy-all":{title:"Deploy all services from this machine",openWorld:!0},"local-deploy-selected":{title:"Deploy selected services from this machine",openWorld:!0},"worktrees-remove":{title:"Remove release worktrees",openWorld:!1},"env-clear":{title:"Clear environment variables",openWorld:!1},"release-desc-edit":{title:"Edit release description",openWorld:!0},"worktrees-add":{title:"Add release worktrees",openWorld:!0},"worktrees-sync":{title:"Prune stale worktrees",openWorld:!0},"env-load":{title:"Load environment variables",openWorld:!0},reopen:{title:"Reopen project windows",openWorld:!1}},FE=["reopen"],sy=()=>Wt.flatMap(e=>{if(!e.mcpExposed||!e.mcpTool)return[];let r=jE[e.mcpTool.name];if(!r)throw new Error(`No MCP_TOOL_PRESENTATION entry for exposed tool "${e.mcpTool.name}" \u2014 add a title and an evidence-cited openWorld value in command-catalog.ts.`);let t=!e.mutating&&!FE.includes(e.mcpTool.name);return[{...e.mcpTool,title:r.title,annotations:{readOnlyHint:t,...t?{}:{destructiveHint:!0},openWorldHint:r.openWorld}}]}),iy=e=>Wt.filter(r=>r.menuGroup===e),ay=e=>Wt.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import Vc from"node:process";var LE="MODULE_TYPELESS_PACKAGE_JSON",WE=(e,r)=>typeof e=="object"&&e!==null?e.code:r,Om=!1,JE=()=>{if(Om)return;Om=!0;let e=Vc.emitWarning.bind(Vc);Vc.emitWarning=((r,...t)=>{WE(t[0],t[1])!==LE&&e(r,...t)})};export{y as a,dp as b,up as c,Pi as d,fp as e,ah as f,wo as g,ko as h,Or as i,FC as j,_p as k,Ah as l,Vp as m,Gp as n,$t as o,Up as p,Kp as q,zn as r,qn as s,tv as t,Gm as u,Ui as v,a$ as w,c$ as x,Zi as y,Xi as z,Xv as A,Ld as B,Jd as C,Vd as D,ba as E,Kd as F,mN as G,cu as H,gu as I,zt as J,Fk as K,Lk as L,xu as M,Tu as N,Cu as O,ju as P,Fu as Q,Yt as R,Hu as S,zu as T,Pe as U,ks as V,am as W,kR as X,ym as Y,Em as Z,Tm as _,Im as $,$m as aa,_m as ba,Dm as ca,ny as da,Wt as ea,sy as fa,iy as ga,ay as ha,JE as ia};
442
+ //# sourceMappingURL=chunk-5XK34MWH.js.map