infra-kit 0.7.0 → 0.7.8

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.
@@ -1,444 +0,0 @@
1
- import{a as cn,c as fe,d as b,e as Lt,f as ce,i as h,j as ln,k as A,l as G}from"./chunk-YKCY657C.js";import{a as qc,d as Yc,f as vr,g as qe,h as pn,i as dn,j as un,n as Xr,o as mn,p as Ae}from"./chunk-KXQQUBGV.js";import{A as Ft,B as ms,C as an,D as Wc,E as Jc,F as fs,G as gs,H as Vc,K as l,L as ze,M as Bc,N as hs,O as we,Q as q,R as E,S as Gc,T as Zr,V as Kc,X as Uc,a as tn,b as f,ca as Hc,d as V,e as Oc,f as on,fa as zc,g as j,h as me,i as ke,j as _c,k as us,l as z,m as L,n as hr,o as Nc,p as Ue,q as ie,r as R,s as He,t as Yr,u as jc,v as Mc,w as Fc,x as Lc,y as nn,z as sn}from"./chunk-63VNUKUS.js";import{a as kc,b as wc,c as ls,d as bc,e as Rc,f as Pc,g as Ec,h as Mt,i as xc,j as Sc,k as Tc,l as Cc,m as Ac,n as ps,o as Ic,p as ds,q as rn,r as gr,s as $c,t as Dc}from"./chunk-UI2MUEVR.js";import{a as ae}from"./chunk-MFLYORUJ.js";import{b as Qo,c as en,d as cs,e as vc,l as qr,n as yc}from"./chunk-GYPVEWUV.js";import{a as se,b as qo,c as jt,d as fc,e as gc,f as Yo,g as Gr,h as Kr,i as Zo,j as Ur,k as ur,l as Hr,m as Xo,p as zr,q as hc,r as mr,s as fr,t as Q}from"./chunk-NFIFWIO6.js";import $l from"node:process";import{z as pe}from"zod";import tl from"node:fs";import Qr from"node:path";import{packageConfigSchema as Ku}from"@slip-stream-kit/config/internal";import Xc from"node:fs/promises";import ws from"node:path";import{pathToFileURL as Uu}from"node:url";import{z as Hu}from"zod";import Zc from"node:path";var Wt=["frontend","backend","lib","e2e","mobile"],Lu={ui:"frontend",api:"backend",tests:"e2e"},Wu="mobile-app",Ju=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Vu=(e,r)=>{let t=Zc.relative(r,e).split(Zc.sep).filter(s=>s!==""&&s!=="."),[o,,n]=t;if(t.length===3&&o==="apps"&&n!==void 0){let s=Lu[n];if(s)return s}return t.at(-1)===Wu?"mobile":null},Bu=e=>{let r=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let o of Ju)if(o.packages.some(n=>r.has(n)))return o.type;return r.has("vite")&&r.has("react")&&!!e.scripts?.dev?"frontend":null},vs=({packageDir:e,repoRoot:r,pkgJson:t,declaredType:o})=>o??Vu(e,r)??Bu(t)??"lib";var Ye={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},ys={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"]},ks=(e,r=Ye)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import Gu from"node:fs/promises";var be=async e=>{try{return await Gu.access(e),!0}catch{return!1}};var Ie="infra-kit.config.ts",Jt=async e=>{try{let r=await Xc.readFile(ws.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},Qc=async e=>{let r=await Xc.stat(e),n=(await import(`${Uu(e).href}?mtime=${Number(r.mtimeMs)}`)).default;if(n===void 0)throw new Error(`${Ie} at ${e} has no default export`);return typeof n=="function"?await n():n},Vt=async e=>{let r=ws.join(e,Ie);if(await be(r))try{let o=(await Qc(r))?.type;return Wt.find(n=>n===o)}catch{return}},Bt=async(e,r=Ye)=>{let t=ws.join(e,Ie);if(!await be(t))throw new Error(`${Ie} not found at ${t}`);let o=await Qc(t),n=Ku.safeParse(o);if(!n.success)throw new Error(`Invalid ${Ie} at ${t}: ${Hu.prettifyError(n.error)}`);return ks(n.data,r)};import el from"node:fs/promises";import fn from"node:path";import zu from"yaml";var qu="pnpm-workspace.yaml",Yu=async e=>(await el.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>fn.join(e,t.name)),Zu=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await Yu(o));continue}let n=fn.join(o,r);await be(n)&&t.push(n)}return t},Xu=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await Zu(t,o);return t},re=async e=>{let r=await el.readFile(fn.join(e,qu),"utf-8"),o=((zu.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await Xu(e,s);for(let a of i)await be(fn.join(a,"package.json"))&&n.add(a)}return[...n].sort()};import Gt from"node:path";var Kt=async e=>{let r=Gt.resolve(e);for(;r!==Gt.dirname(r);){if(await be(Gt.join(r,"package.json")))return r;r=Gt.dirname(r)}if(await be(Gt.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 Re=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},Ze=(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}`:"")},bs=(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},rl=(e,r,t)=>`${e}
3
- ${r}
4
- ${t}`,Ut=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=rl(t,r,o),i=Re(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?Ze(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
5
- ${s}
6
- `:`${s}
7
- `};var le="<!-- infra-kit:begin -->",Pe="<!-- infra-kit:end -->",Rs="<!-- infra-kit:version ",Ee="<!-- infra-kit:package:begin -->",$e="<!-- infra-kit:package:end -->",yr="<!-- infra-kit:package:version ";var Qu=e=>{let r=e.indexOf(Ee)+Ee.length;return e.slice(r,e.indexOf($e))},em=e=>{let r=e.indexOf(yr);if(r===-1)return null;let t=e.slice(r+yr.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Wt.find(o=>o===t)??null},kr=e=>{if(e===null)return{state:"missing"};if(!Re(e,Ee,$e))return e.includes(Ee)||e.includes($e)?{state:"malformed"}:Re(e,le,Pe)?{state:"foreign-block"}:{state:"no-block"};let r=Qu(e);if(r.trim()==="")return{state:"malformed"};let t={state:"ok"},o=bs(r,yr),n=em(r);return o!==null&&(t.version=o),n!==null&&(t.type=n),t};import rm from"node:fs";var wr=e=>{try{return rm.readFileSync(e,"utf-8")}catch{return null}};var ol="pnpm-workspace.yaml",tm="CLAUDE.md",Es=e=>{let r=Qr.resolve(e);for(;r!==Qr.dirname(r);){if(tl.existsSync(Qr.join(r,ol)))return r;r=Qr.dirname(r)}return tl.existsSync(Qr.join(r,ol))?r:null},Ps=new Map,gn=()=>{Ps.clear()},om=async e=>{let r;try{r=await re(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let t of r){let o=Qr.join(t,tm),n=wr(o);if(n!==null&&kr(n).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:o}}return{adopted:!1,workspaceRoot:e}},et=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let r=Ps.get(e);if(r)return r;let t=await om(e);return Ps.set(e,t),t};import nt from"node:fs";import br from"node:path";var nl=`---
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 sl=`# {{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 il=`# {{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 al="# {{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 cl=`# {{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 ll=`# {{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 pl="# 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 plugin, the `.mcp.json` key, 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\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 rt={"root/body":pl.trimEnd(),"package/frontend":al.trimEnd(),"package/backend":sl.trimEnd(),"package/lib":cl.trimEnd(),"package/e2e":il.trimEnd(),"package/mobile":ll.trimEnd(),"design/skeleton":nl.trimEnd()};var xs=/\{\{(\w+)\}\}/g,dm=/^- \{\{(\w+)\}\}$/,um=e=>new Set([...e.matchAll(xs)].map(r=>r[1])),mm=(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(", ")}`)},fm=(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(", ")}`)},gm=(e,r)=>e.filter(t=>{let o=dm.exec(t);return o===null||r[o[1]]!==""}),hm=(e,r)=>{for(let t of e)for(let o of t.matchAll(xs)){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})`)}},tt=(e,r)=>{let t=um(e);fm(t,r),mm(t,r);let o=gm(e.split(`
165
- `),r);return hm(o,r),o.join(`
166
- `).replace(xs,(n,s)=>r[s])};var vm="name: TODO",Ss=e=>{let r=tt(rt["design/skeleton"],{packageName:e}),t=`name: ${e}`;return`${r.replace(vm,()=>t)}
167
- `};var ym=(e,r)=>`${yr}${e} ${r} -->`,km="`README.md` \u2014 what this package is and how to run it.",Ts=e=>{let{version:r,type:t,packageName:o,relDir:n,hasReadme:s}=e,i=tt(rt[`package/${t}`],{packageName:o,relDir:n,type:t,readmeBullet:s?km:""});return[ym(r,t),"",i].join(`
168
- `)};var wm=e=>`${Rs}${e} -->`,Cs=e=>{let r=tt(rt["root/body"],{});return[wm(e),"",r].join(`
169
- `)};import ot from"node:fs";import bm from"node:path";var hn=e=>{let r;try{r=ot.lstatSync(e)}catch{return}if(r.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Ht=(e,r)=>{hn(e);let t=ot.existsSync(e)?ot.readFileSync(e,"utf-8"):null;return t===r?"unchanged":(ot.mkdirSync(bm.dirname(e),{recursive:!0}),ot.writeFileSync(e,r,"utf-8"),t===null?"created":"updated")},As=(e,r,t)=>{let o=ot.readFileSync(e,"utf-8");if(!Re(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},dl=(e,r,t)=>Re(e,r,t)?{before:e.slice(0,e.indexOf(r)),after:e.slice(e.indexOf(t)+t.length)}:null,Is=(e,r,t,o)=>{let n=dl(e,t,o),s=dl(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 yn="<!-- infra-kit:import:begin -->",kn="<!-- infra-kit:import:end -->",Rm="AGENTS.md",ul="CLAUDE.md",Pm="README.md",$s="DESIGN.md",Em=["frontend","mobile"],xm=e=>nt.existsSync(e)?nt.readFileSync(e,"utf-8"):null,Ds=(e,r)=>{try{return nt.readdirSync(e).includes(r)}catch{return!1}},vn=(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},ml=({filePath:e,body:r,startMarker:t,endMarker:o,prepare:n})=>{let s=xm(e),i=s===null?"":n?.(s)??s,a=Ut({content:i,body:r,startMarker:t,endMarker:o,placement:"replace-in-place"}),c=Ht(e,a);return As(e,t,o),s!==null&&Is(i,a,t,o),c},Sm=e=>{if(!nt.existsSync(e))return"unchanged";hn(e);let r=nt.readFileSync(e,"utf-8"),t=Ze(r,le,Pe);return t===null?"unchanged":t.trim()===""?(nt.rmSync(e),"removed"):Ht(e,t)},Tm=(e,r)=>ml({filePath:e,body:Cs(r),startMarker:le,endMarker:Pe,prepare:t=>Ze(t,yn,kn)??t}),zt=async(e,{version:r})=>{let t=br.join(e,ul),o=br.join(e,Rm),n=[];try{n.push({path:t,action:Tm(t,r)})}catch(s){n.push(vn(t,s))}try{n.push({path:o,action:Sm(o)})}catch(s){n.push(vn(o,s))}return n},Cm=(e,r,t)=>{if(!Em.includes(t)||Ds(e,$s))return null;let o=br.join(e,$s);try{return{path:o,action:Ht(o,Ss(r)),type:t}}catch(n){return vn(o,n,t)}},qt=async(e,{repoRoot:r,version:t,design:o,declaredType:n})=>{let s=br.join(e,ul),i=await Jt(e),a=i.name??br.basename(e),c=vs({packageDir:e,repoRoot:r,pkgJson:i,declaredType:n}),p=Ts({version:t,type:c,packageName:a,relDir:br.relative(r,e).split(br.sep).join("/"),hasReadme:Ds(e,Pm),hasDesign:Ds(e,$s)}),d=[];try{d.push({path:s,action:ml({filePath:s,body:p,startMarker:Ee,endMarker:$e}),type:c})}catch(u){d.push(vn(s,u,c))}if(o){let u=Cm(e,a,c);u&&d.push(u)}return d};import jm from"node:path";import fl from"node:path";var Os="agent-guidance",Yt="CLAUDE.md",Am="\u2014 run: infra-kit audit --fix",Im={missing:`${Yt} missing`,"no-block":`${Yt} has no infra-kit block (expected ${Ee} \u2026 ${$e})`,malformed:`${Yt} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Yt} carries the ROOT infra-kit block (${le}); a package needs the package block`},$m=e=>e.adopted?` (workspace adopted: ${fl.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",_s=(e,r)=>{let t=kr(wr(fl.join(e,Yt)));if(t.state==="ok"){let s=t.version??"unknown",i=t.type??"unknown";return{name:Os,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let o=`${Im[t.state]} ${Am}`,n=t.state==="missing"?`${o}${$m(r)}`:o;return r.adopted?{name:Os,status:"fail",message:n}:{name:Os,status:"pass",message:`not yet adopted \u2014 ${n}`}};var Ns=async(e,r=Ye)=>{try{let t=await Bt(e,r);return{check:{name:Ie,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:Ie,status:"fail",message:t.message},rules:null}}};import Dm from"node:fs/promises";import Om from"node:path";var js=async(e,r)=>Promise.all(r.map(async t=>{let o=await Dm.stat(Om.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 Ms=(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 _m from"node:fs/promises";import Nm from"node:path";var st="turbo.json",Fs=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await _m.readFile(Nm.join(e,st),"utf-8");t=JSON.parse(n)}catch(n){return[{name:st,status:"fail",message:`cannot read/parse ${st}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:st,status:"fail",message:`no "tasks" object defined in ${st}`}]: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 ${st}`}})};var Mm={adopted:!1,workspaceRoot:null},Ls=async(e,r=Ye,t={})=>{let o=await Jt(e),n=o.name??jm.basename(e),{check:s,rules:i}=await Ns(e,r),a=[s];t.isRoot||a.push(_s(e,t.adoption??Mm)),i&&(a.push(...Ms(o.scripts??{},i.requiredScripts)),a.push(...await js(e,i.requiredFiles)),a.push(...await Fs(e,i.turboTasks)));let c=a.every(p=>p.status==="pass");return{packageDir:e,packageName:n,checks:a,passed:c}};var y=e=>[{type:"text",text:e}],k=e=>e;import Fm from"node:path";import Lm from"node:process";var Wm=["unchanged","created"],Jm=["unchanged","created","updated","removed","failed"],gl=async(e,r,t)=>{let o=await Vt(e);return qt(e,{repoRoot:r,version:ae.version,design:t,declaredType:o})},Vm=async(e,r)=>{if(e.root)return zt(r,{version:ae.version});if(e.all){let o=[];for(let n of await re(r))o.push(...await gl(n,r,e.design));return o}let t=await Kt(e.cwd??Lm.cwd());return gl(t,r,e.design)},Bm=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 ${Jm.filter(o=>Wm.includes(o)||(r.get(o)??0)>0).map(o=>`${r.get(o)??0} ${o}`).join(", ")} (infra-kit ${ae.version})`},Gm=(e,r)=>{for(let t of e){if(t.action==="unchanged")continue;let o=Fm.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(Bm(e))},Km=e=>{let r={path:e.path,action:e.action};return e.type&&(r.type=e.type),r},hl=async(e,r)=>{let t=await R();gn();let o=await et(r),n=await Vm(e,t);Gm(n,t),gn();let s=await et(r),i=!e.all&&!e.root;return{fixed:n.map(Km),adoptionFlipped:i&&!o.adopted&&s.adopted}};import Tl from"node:fs";import Cl from"node:path";var Ws="ik-mcp",vl=(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:Ws,args:t}};import Us from"node:fs";import xl from"node:path";import Bs from"node:fs";import Xm from"node:os";import bn from"node:path";import wn from"node:fs";import Um from"node:path";var x="infra-kit",W="infra-kit@infra-kit",Rr="ArthurSaenz/infra-kit",Xe=`claude plugin install ${W} --scope project`,Js=`claude plugin marketplace add ${Rr}`,kl=" ",wl=()=>({source:{source:"github",repo:Rr}}),Hm=()=>({extraKnownMarketplaces:{[x]:wl()},enabledPlugins:{[W]:!0}}),bl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zm=e=>/\n([ \t]+)"/.exec(e)?.[1]??kl,yl=(e,r,t,o)=>{let n=e[r];return n===void 0?(e[r]={[t]:o},`${r}.${t}`):!bl(n)||t in n?null:(n[t]=o,`${r}.${t}`)},qm=e=>[yl(e,"extraKnownMarketplaces",x,wl()),yl(e,"enabledPlugins",W,!0)].filter(t=>t!==null),Ym=e=>{try{return wn.readFileSync(e,"utf-8")}catch{return null}},Zm=e=>(wn.mkdirSync(Um.dirname(e),{recursive:!0}),wn.writeFileSync(e,`${JSON.stringify(Hm(),null,kl)}
170
- `,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${x}`,`enabledPlugins.${W}`]}),Vs=e=>{let r=Ym(e);if(r===null)return Zm(e);let t;try{t=JSON.parse(r)}catch{t=void 0}if(!bl(t))return l.warn(`Could not parse ${e} \u2014 left it untouched. Add "${W}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=qm(t);if(o.length===0)return{status:"unchanged",path:e,added:[]};let n=zm(r),s=r.endsWith(`
171
- `)?`
172
- `:"";return wn.writeFileSync(e,`${JSON.stringify(t,null,n)}${s}`,"utf-8"),{status:"added",path:e,added:o}};var Qm=[".claude","plugins"],Rn=e=>{try{return JSON.parse(Bs.readFileSync(e,"utf-8"))}catch{return}},Qe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),it=(e,r)=>{let t=e[r];return typeof t=="string"?t:null},Rl=(e,r=Xm.homedir())=>bn.join(r,...Qm,e),Zt=e=>{let r=Rn(Rl("known_marketplaces.json",e));return Qe(r)&&x in r},ef=e=>Qe(e)?{scope:it(e,"scope"),projectPath:it(e,"projectPath"),installPath:it(e,"installPath"),version:it(e,"version")}:null,rf=e=>{let r=Rn(Rl("installed_plugins.json",e));if(!Qe(r)||!Qe(r.plugins))return[];let t=r.plugins[W];return Array.isArray(t)?t.flatMap(o=>{let n=ef(o);return n===null?[]:[n]}):[]},Pl=e=>{try{return Bs.realpathSync(e)}catch{return bn.resolve(e)}},tf=(e,r)=>e.scope==="user"?!0:r===null||e.projectPath===null?!1:Pl(e.projectPath)===r,Xt=(e={})=>{let r=rf(e.home);if(r.length===0)return{kind:"absent"};let t=e.projectPath===void 0?null:Pl(e.projectPath),o=r.find(n=>tf(n,t));return o===void 0?{kind:"elsewhere",installations:r}:{kind:"installed",installation:o}},Gs=e=>{if(e.installPath===null)return e.version;let r=Rn(bn.join(e.installPath,".claude-plugin","plugin.json"));return(Qe(r)?it(r,"version"):null)??e.version},of=e=>{if(!Qe(e))return!1;let r=it(e,"command")??"",t=Array.isArray(e.args)?e.args.join(" "):"";return`${r} ${t}`.includes("infra-kit")},Qt=e=>{let r=bn.join(e,".mcp.json");if(!Bs.existsSync(r))return{kind:"missing-file"};let t=Rn(r);if(!Qe(t)||!Qe(t.mcpServers))return{kind:"unparseable"};let o=t.mcpServers;if(x in o)return{kind:"ok"};let n=Object.keys(o).find(s=>of(o[s]));return n===void 0?{kind:"absent"}:{kind:"wrong-key",key:n}};var Hs=".mcp.json",ge="mcpServers",nf="infra-kit",Pn=" ",Ks=()=>({type:"stdio",command:nf,args:["mcp"]}),at=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),De=(e,r,t=null)=>({status:e,path:r,misfiledKey:t}),zs=e=>/\n([ \t]+)"/.exec(e)?.[1]??Pn,qs=e=>{try{return{kind:"raw",raw:Us.readFileSync(e,"utf-8")}}catch(r){return r.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:r}}},Ys=e=>{try{return JSON.parse(e)}catch{return}},eo=e=>e instanceof Error?e.message:String(e),Sl=(e,r)=>{try{return Us.writeFileSync(e,r,"utf-8"),!0}catch(t){return l.warn(`Could not write ${e} (${eo(t)}) \u2014 the infra-kit MCP server is not registered. Add a "${x}" entry to ${ge} by hand, then re-run: infra-kit setup --skip-tools`),!1}},El=(e,r,t)=>{let o=t.endsWith(`
173
- `)?`
174
- `:"",n=`${JSON.stringify(r,null,zs(t))}${o}`;return Sl(e,n)?De("added",e):De("failed",e)},sf=e=>{let r={[ge]:{[x]:Ks()}},t=`${JSON.stringify(r,null,Pn)}
175
- `;return Us.mkdirSync(xl.dirname(e),{recursive:!0}),Sl(e,t)?De("created",e):De("failed",e)},af=e=>{let r=Qt(e);return r.kind==="wrong-key"?r.key:null},cf=({mcpPath:e,parsed:r,projectRoot:t,raw:o})=>{let n=r[ge];if(n===void 0)return r[ge]={[x]:Ks()},El(e,r,o);if(!at(n))return l.warn(`${e} has a "${ge}" that is not an object \u2014 left it untouched. Fix it and re-run: infra-kit setup --skip-tools`),De("unparseable",e);if(x in n)return l.debug(`${e} already registers the "${x}" server`),De("unchanged",e);let s=af(t);return s!==null?(l.warn(`${e} already registers the infra-kit server under "${s}" \u2014 left it untouched. Rename that key to "${x}" by hand: tool names are mcp__<key>__<tool>, and a second "${x}" entry beside "${s}" would run two servers`),De("misfiled",e,s)):(n[x]=Ks(),El(e,r,o))},Zs=e=>{let r=xl.join(e,Hs),t=qs(r);if(t.kind==="absent")return sf(r);if(t.kind==="unreadable")return l.warn(`Could not read ${r} (${eo(t.error)}) \u2014 left it untouched. Fix its permissions and re-run \`infra-kit setup --skip-tools\`, or add a "${x}" entry to ${ge} by hand.`),De("failed",r);let{raw:o}=t,n=Ys(o);return at(n)?cf({mcpPath:r,parsed:n,projectRoot:e,raw:o}):(l.warn(`Could not parse ${r} \u2014 left it untouched. Add a "${x}" entry to ${ge} by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),De("unparseable",r))};var En="run `infra-kit setup` (or `infra-kit audit --root --fix`)",lf=(e,r)=>Array.isArray(e)&&e.length===r.length&&e.every((t,o)=>t===r[o]),Xs=e=>at(e)&&e.command===Ws,pf=(e,r)=>({...e??{},type:r.type,command:r.command,args:r.args}),df=(e,r,t)=>{let o=[],n={...e},s=!1;for(let[i,a]of Object.entries(r)){let c=vl(i,a),p=e[i];if(p!==void 0&&!Xs(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 ${En}, or drop mcp.${i} from infra-kit.json`});continue}if(Xs(p)&&p.type===c.type&&lf(p.args,c.args)){o.push({name:i,status:"unchanged",message:""});continue}if(t){n[i]=pf(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 but has no .mcp.json entry \u2014 ${En}`:`"${i}" in .mcp.json does not match its mcp.${i} config \u2014 ${En}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(r,i)||!Xs(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}},uf=(e,r,t)=>{let o=t===null?Pn:zs(t),n=t===null||t.endsWith(`
176
- `)?`
177
- `:"";try{return Tl.mkdirSync(Cl.dirname(e),{recursive:!0}),Tl.writeFileSync(e,`${JSON.stringify(r,null,o)}${n}`,"utf-8"),!0}catch(s){return l.warn(`Could not write ${e} (${eo(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},xn=({projectRoot:e,proxies:r,write:t})=>{let o=Cl.join(e,Hs),n=qs(o);if(n.kind==="unreadable")return l.warn(`Could not read ${o} (${eo(n.error)}) \u2014 left it untouched.`),{status:"unreadable",path:o,entries:[],wrote:!1};let s=n.kind==="raw"?n.raw:null,i=s===null?{}:Ys(s);if(!at(i))return l.warn(`Could not parse ${o} \u2014 left it untouched. Fix the JSON, then ${En}.`),{status:"unparseable",path:o,entries:[],wrote:!1};let a=i[ge];if(a!==void 0&&!at(a))return l.warn(`${o} has a "${ge}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:o,entries:[],wrote:!1};let c=df(a??{},r,t);if(!c.changed)return{status:"ok",path:o,entries:c.entries,wrote:!1};let p=uf(o,{...i,[ge]:c.servers},s);return{status:p?"ok":"failed",path:o,entries:c.entries,wrote:p}};var Al=async(e,r)=>{let t;try{t=(await E()).mcp}catch{return null}if(!t||Object.keys(t).length===0)return null;let o=xn({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 mf=(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}))],Il=async e=>{let r=(await E()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=Hc(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=Kc(e),n=Uc(e),s={api:o.map(d=>d.name),ui:n.map(d=>d.name)},{ctx:i,loadErrors:a}=await qc(e,r,s,o),c=mf(zc(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 ff="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",gf=async e=>e.root?[{dir:await R(),baseline:ys,isRoot:!0}]:e.all?(await re(await R())).map(t=>({dir:t})):[{dir:await Kt(e.cwd??$l.cwd())}],hf=async e=>e.root||e.all?await R():e.cwd??$l.cwd(),vf=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},yf=async(e,r)=>{let{fixed:t,adoptionFlipped:o}=await hl(e,r);return o&&l.info(ff),t},Dl=async(e={})=>{let r=Es(await hf(e)),t=e.fix?await yf(e,r):void 0,o=await gf(e),n=await et(r),s=[];for(let c of o)s.push(await Ls(c.dir,c.baseline,{adoption:n,isRoot:c.isRoot}));if(e.root){let c=await Il(o[0].dir);c&&s.push(c);let p=await Al(o[0].dir,e.fix===!0);p&&s.push(p)}let a={allPassed:vf(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}},kf={all:pe.boolean().optional().describe("Audit every non-vendor workspace package"),root:pe.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},wf={allPassed:pe.boolean().describe("Whether every audited package passed all checks"),packages:pe.array(pe.object({name:pe.string(),passed:pe.boolean(),checks:pe.array(pe.object({name:pe.string(),status:pe.enum(["pass","fail"]),message:pe.string()}))})).describe("Per-package check results")},Qs=k({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:kf,outputSchema:wf,handler:e=>Dl({all:e.all,root:e.root})});import{z as ro}from"zod";var Ol=async()=>{let[e,r]=await Promise.all([E(),q()]),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}},bf={config:ro.record(ro.string(),ro.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:ro.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:ro.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},ei=k({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{},outputSchema:bf,handler:()=>Ol()});import Tf from"node:fs";import{z as K}from"zod";import to from"node:fs";import ct from"node:path";import Rf from"node:process";var Pf=ct.join(".infra-kit","dev-context"),Ef=".infra-kit",_l=(e,r)=>{let t=ct.resolve(e);for(;;){let o=ct.join(t,r);if(to.existsSync(o))return o;let n=ct.dirname(t);if(n===t)return;t=n}},xf=e=>{let r=_l(e,Pf);if(r)return r;let t=_l(e,Ef);return t?ct.join(t,"dev-context"):void 0},ri=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Sn=e=>typeof e=="string"?e:"",Sf=(e,r,t)=>{let o=ct.join(e,r);try{let n=to.statSync(o),s=JSON.parse(to.readFileSync(o,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:r.replace(/\.json$/,""),package:Sn(i.package),port:ri(i.port),alias:Sn(i.alias),origin:Sn(i.origin),release:Sn(i.release),pid:ri(i.pid),writtenAt:ri(i.writtenAt),mtimeMs:Math.round(n.mtimeMs),ageMs:Math.max(0,Math.round(t-n.mtimeMs))}}catch{return null}},ti=(e=Rf.cwd())=>{let r=Date.now(),t=xf(e);if(!t||!to.existsSync(t))return{session:"none",fragmentDir:t,readAt:r,apps:[]};let o;try{o=to.readdirSync(t).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:t,readAt:r,apps:[]}}let n=o.map(s=>Sf(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 Nl=async(e={})=>{let r=e.now??Date.now,t=e.isListening??Mt,o=ti(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&&(Tf.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}},Cf={active:K.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:K.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:K.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:K.array(K.object({app:K.string().describe("App folder name (the fragment filename without .json)."),package:K.string().describe("The app package name the vite helper reads to decide a local route."),port:K.number().describe("The actual bound port the dev server is listening on."),pid:K.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:K.string().describe("Registered portless hostname for the app."),origin:K.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:K.string().describe("Release slug the runner recorded for this worktree."),writtenAt:K.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:K.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:K.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:K.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.")},oi=k({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:Cf,handler:()=>Nl()});import{spawnSync as zh}from"node:child_process";import J from"node:fs";import zp from"node:os";import U from"node:path";import Bn from"node:process";import{z as Z}from"zod";import{execFileSync as Af}from"node:child_process";var jl=(e,r)=>{let t=e.filter(o=>!o.live).map(o=>o.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},If=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],$f=e=>If.some(r=>r.test(e)),Df="/bin/ps",Of=()=>Af(Df,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
178
- `),Ml=(e=Of)=>{try{return e().some($f)}catch{return!0}};import{Chalk as _f}from"chalk";import ni from"node:process";var Nf="Tools & CLIs",jf="Shell & integration",Mf="Project config",Ff="Doppler env tokens",Lf="Dev proxy (portless)",Wf="Claude Code plugin",Jf=`portless serving TLS on :${ze}`,si=[[Nf,["brew installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","terminal installed","ide installed"]],[jf,["zshrc init block","warm cache","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Mf,["infra-kit config valid","user override path","legacy user-global config"]],[Ff,["tokens.json present","env tokens configured","env token valid","tokens.json perms"]],[Lf,["portless installed","portless service target",Jf,"portless CA chain valid","portless CA trusted","portless routes"]],[Wf,["claude CLI","marketplace registered","plugin installed","plugin version","CLI version","MCP server key"]]],Fl="Other",Vf=si.map(([e])=>e),Bf=new Map(si.flatMap(([e,r])=>r.map(t=>[t,e]))),nS=si.flatMap(([,e])=>e),ii=new Set(["portless routes","tokens.json perms"]),Gf=e=>{let r=new Map;for(let o of e){let n=Bf.get(o.name)??Fl,s=r.get(n);s?s.push(o):r.set(n,[o])}return[...Vf,Fl].flatMap(o=>{let n=r.get(o);return n&&n.length>0?[{label:o,checks:n}]:[]})},Ll={unicode:{pass:"\u2713",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{pass:"ok",fail:"!!",separator:"-",rule:"-"}},Kf=24,Uf=(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:[""]},Jl=e=>{let r=e.filter(t=>t.status==="fail").length;return{passed:e.length-r,failed:r}},Hf=e=>{let r=new _f({level:e?1:0});return{header:t=>r.bold.cyan(t),pass:t=>r.green(t),fail:t=>r.red(t),dim:t=>r.dim(t),bold:t=>r.bold(t)}},zf=(e,r,t,o)=>{if(e.failed===0){let i=`${r}/${r} ok`;return{text:t.pass(i),plainWidth:i.length}}let n=`${e.passed}/${r}`,s=`${e.failed} failed`;return{text:`${t.dim(n)} ${o.separator} ${t.fail(s)}`,plainWidth:n.length+s.length+3}},lt=" ",Wl=" ",qf=(e,r,t,o)=>{let n=Jl(e.checks),s=zf(n,e.checks.length,r,t),i=Math.max(1,o-lt.length-e.label.length-s.plainWidth);return`${lt}${r.header(e.label)}${" ".repeat(i)}${s.text}`},Yf=(e,r,t,o,n)=>{let s=e.status==="fail",i=o.pass.length,a=s?o.fail:o.pass,c=e.name.padEnd(r),p=s?t.fail(a):t.pass(a),d=s?t.fail(c):c,u=Wl.length+i+1+r+2,m=Math.max(Kf,n-u),[v,...g]=Uf(e.message,m),w=F=>s?F:t.dim(F);return[`${Wl}${p} ${d} ${w(v??"")}`.trimEnd(),...g.map(F=>`${" ".repeat(u)}${w(F)}`)]},Zf=(e,r,t,o)=>{let n=Jl(e),s=t.rule.repeat(Math.max(12,Math.min(o-lt.length,56))),i=e.filter(m=>m.status==="fail"&&ii.has(m.name)).length,a=r.pass(`${n.passed} passed`),c=r.fail(`${n.failed} failed`),p=n.failed===0?a:`${a} ${t.separator} ${c}`,d=r.dim(`${i} fixable \u2014 run \`infra-kit doctor --fix\``),u=i>0?` ${d}`:"";return[`${lt}${r.dim(s)}`,`${lt}${p}${u}`]},Xf=(e,r={})=>{let t=r.color??!1,o=r.unicode??!0,n=r.width??80,s=Hf(t),i=o?Ll.unicode:Ll.ascii;if(e.length===0)return[s.bold("infra-kit doctor"),"",`${lt}${s.dim("No checks ran.")}`];let a=Math.max(...e.map(p=>p.name.length)),c=Gf(e).flatMap(p=>[qf(p,s,i,n),...p.checks.flatMap(d=>Yf(d,a,s,i,n)),""]);return[s.bold("infra-kit doctor"),"",...c,...Zf(e,s,i,n)]},Qf=new Set(["","0","false","none"]),eg=["LC_ALL","LC_CTYPE","LANG"],rg=(e,r)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Qf.has(e.FORCE_COLOR.toLowerCase()):!!r.isTTY,tg=(e,r)=>{if(r)return!1;let t=eg.map(o=>e[o]).find(o=>o!==void 0&&o!=="");return t===void 0?!0:/UTF-?8/i.test(t)},og=(e={})=>{let r=e.env??ni.env,t=e.stream??ni.stderr;return{color:rg(r,t),unicode:tg(r,e.ascii??!1),width:t.columns??80}},ng=(e,r={})=>{(r.write??(o=>{ni.stderr.write(o)}))(`${Xf(e,og(r)).join(`
179
- `)}
180
- `)};var sg=e=>e.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&"),ig=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(r=>sg(r[1])),ag=e=>{let r=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return r===null?null:ig(r[1])},cg=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},lg=e=>{let r=e.split(`
181
- `).find(t=>t.startsWith("ExecStart="));return r===void 0?null:cg(r.slice(10))},Vl=(e,r)=>{try{return e==="darwin"?ag(r):e==="linux"?lg(r):null}catch{return null}};import wg from"@inquirer/select";import{Buffer as bg}from"node:buffer";import Rg from"node:fs";import Pg from"node:path";import tp from"node:process";import{z as co}from"zod";import{$ as An}from"zx";var pg="Could not find requested project",dg="Could not find requested config",Bl="Invalid Auth token",Gl="does not have access to requested config",oo=e=>e.includes(Bl)||e.includes(Gl)?"auth":e.includes(pg)?"project":e.includes(dg)?"config":"unknown",no=e=>e.includes(Gl)?"mis-scoped":e.includes(Bl)?"revoked":null;var Kl=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(`
182
- `),pt=class extends cn{authKind;constructor(r,t=null,o){super(o??Kl(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(`
183
- `)};import{$ as Tn}from"zx";var ug=5e3,mg="DOPPLER_CONFIG",Pr=async()=>{let{envManagement:e}=await E();return e.config.name},so=async({childEnv:e,project:r,config:t})=>{let o=Tn.quiet;Tn.quiet=!0;try{let s=(await Tn({env:e})`doppler secrets get ${mg} --plain --project ${r} --config ${t}`.timeout(ug)).stdout.trim();return s!==t?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(n){return{outcome:fg(n)}}finally{Tn.quiet=o}},fg=e=>{let r=tn(e)??(e instanceof Error?e.message:String(e));return oo(r)!=="auth"?"unreachable":no(r)??"unreachable"};import Ul from"node:process";var Y="INFRA_KIT_ENV_TOKEN",dt=async e=>{let r=Ul.env[Y];if(r)return{token:r,source:"env"};let o=(await ce())?.envs[e];if(o)return{token:o,source:"store"};throw new cn(gg(e,await Lt()),e)},yS=async e=>Ul.env[Y]?!0:!!(await ce())?.envs[e],gg=(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 ${Y} instead \u2014 it takes precedence and needs no home config.`].join(`
184
- `);var Hl=["prod"],ut={allowed:!1,reason:"disallow"},mt=e=>Hl.includes(e),hg=["dev","stage"],ft=e=>hg.includes(e)||mt(e),Oe=(e,r=ut)=>r.allowed?e:e.filter(t=>!mt(t)),Er=(e,r,t=ut)=>{if(!t.allowed&&mt(e))throw t.reason==="mcp-blocked"?new f(void 0,{operation:r,remediation:`run it yourself in a terminal \u2014 this project sets \`protectedEnvs: "cli-only"\`, which deliberately withholds "${e}" from agents while allowing it on the CLI`,stderrExcerpt:`"${e}" is not reachable over MCP in this project`}):new f(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 _e=async()=>{let e;try{e=(await E()).protectedEnvs??"disallow"}catch{return ut}return e==="disallow"?ut:e==="cli-only"&&V()?{allowed:!1,reason:"mcp-blocked"}:{allowed:!0,reason:"allowed"}};var io=e=>{let{env:r,branch:t}=e;mt(r)&&l.warn([`\u26A0\uFE0F "${r}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${t}" ships ${r} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
185
- `))};import zl from"node:fs/promises";import ci from"node:path";import vg from"yaml";var ql=".github/workflows",Ne=async e=>{let r=await R();return Yl(ci.resolve(r,ql,e))},li=async()=>{let e=await R(),r=ci.resolve(e,ql),t;try{t=await zl.readdir(r)}catch{return[]}let o=t.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),n=await Promise.all(o.map(s=>Yl(ci.resolve(r,s))));return[...new Set(n.flat())]},Yl=async e=>{let r;try{r=vg.parse(await zl.readFile(e,"utf-8"))}catch{return[]}let t=gt(r,"on")??gt(r,"true"),o=gt(gt(gt(gt(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(o)?o.filter(n=>typeof n=="string"&&n.length>0):[]},gt=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var Cn=async()=>{let e=await li(),r=await ce(),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]},xr=async()=>(await Cn()).map(r=>r.env);import Zl from"node:fs";import{$ as yg}from"zx";import Sr from"node:fs";import ao from"node:path";var pi=({autoLoaded:e,projectDir:r,canonicalProjectRoot:t})=>!e||!r||!t?!1:t===r,je=e=>{if(!e)return"";try{return Sr.realpathSync(e)}catch{return""}},di=(e,r)=>{try{let t=mr(e);Sr.mkdirSync(t,{recursive:!0,mode:448}),fr(ao.join(t,se),r,384)}catch(t){l.debug(`warm-cache write skipped: ${t.message}`)}},ui=(e=Date.now(),r=jt)=>{let t=hc(),o;try{o=Sr.readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of o){if(!n.isDirectory())continue;let s=ao.join(t,n.name);try{let{mtimeMs:i}=Sr.statSync(ao.join(s,se));e-i>=r*1e3&&Sr.rmSync(s,{recursive:!0,force:!0})}catch{}}},mi=(e,r)=>{try{let t=mr(e);if(r){Sr.rmSync(t,{recursive:!0,force:!0});return}if(!Sr.existsSync(ao.join(t,se)))return;fr(ao.join(t,qo),`# infra-kit warm cache cleared
186
- `,384)}catch(t){l.debug(`warm-cache invalidate skipped: ${t.message}`)}};var Xl=e=>e.split(`
187
- `).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),kg=async()=>{let e;try{e=(await yg({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 Xl(e)){let o=je(t);if(!o)continue;let n=mr(o);try{if(!Zl.existsSync(n))continue;Zl.rmSync(n,{recursive:!0,force:!0}),r.push(n)}catch(s){l.debug(`warm-cache purge skipped for ${n}: ${s.message}`)}}return r};var Eg=e=>e?[`${ur}=${Tr("1")}`]:[`unset ${ur}`,`unset ${Hr}`],xg="DOPPLER_CONFIG",Ql=new Set(["DOPPLER_TOKEN",Y]),ep=!1,Sg=e=>{e.length===0||ep||(ep=!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.`))},op=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:n,autoLoaded:s})=>{let i=e.filter(([a])=>!Ql.has(a));return Sg(e.filter(([a])=>Ql.has(a)).map(([a])=>a)),["set -a",...i.map(([a,c])=>`${a}=${Tr(c)}`),`${Yo}=${Tr(r)}`,`${Gr}=${Tr(r)}`,`${Kr}=${Tr(t)}`,`${Zo}=${Tr(o)}`,`${Ur}=${Tr(n)}`,...Eg(s),"set +a"]},Tg=async()=>{try{return await R()}catch{return""}},np=async({config:e,autoLoaded:r=!1,beforeWrite:t,projectDir:o})=>{let n=await Pr(),s=await Tg(),i=await Ig(n,e),a=new Date().toISOString(),p=`${op({pairs:i,config:e,project:n,projectRoot:s,loadedAt:a,autoLoaded:r}).join(`
188
- `)}
189
- `,d=zr(),u=Pg.resolve(d,se);if(t&&!t())return null;Rg.mkdirSync(d,{recursive:!0,mode:448}),fr(u,p,384);let m=je(s);return pi({autoLoaded:r,projectDir:o,canonicalProjectRoot:m})&&(di(o,p),ui()),{filePath:u,variableCount:i.length,project:n,config:e}},sp=async e=>{let{config:r}=e,t="";if(r)t=r;else{let s=await xr();h.setInteractive(),t=await A(i=>wg({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:tp.stderr,whenHeadless:"unreachable"})}h.addOption("--config",t);let o=await np({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};return{content:y(JSON.stringify(n,null,2)),structuredContent:n}},rp=1024*1024,Cg=3e4,Ag=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],ht=(e,r=tp.env)=>{let t={...r};for(let o of Ag)delete t[o];return t.DOPPLER_TOKEN=e,t},Ig=async(e,r)=>{let{token:t}=await dt(r),o=ht(t),n=An.quiet;An.quiet=!0;try{let s;try{s=await An({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(Cg)}catch(a){throw $g(a,e,r)}Dg(s.stdout);let i=ap(s.stdout);return ip(i,r),i}finally{An.quiet=n}},ip=(e,r)=>{let t=e.find(([o])=>o===xg)?.[1];if(!(t===void 0||t===r))throw new pt(r,null,`Doppler returned secrets for config "${t}" but "${r}" was requested \u2014 the service token for env "${r}" is scoped to the wrong config. Refusing to load another environment's secrets.
190
- Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},$g=(e,r,t)=>{let o=tn(e)??(e instanceof Error?e.message:String(e)),n=oo(o);return n==="auth"?new pt(t,no(o)):n==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(ai({kind:n,project:r,config:t,available:null}))},Dg=e=>{let r=bg.byteLength(e,"utf-8");if(r>rp)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${rp}) \u2014 refusing to write to disk`)},Tr=e=>`'${e.replaceAll("'","'\\''")}'`,Og=/^[A-Z_]\w*$/i,ap=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(!Og.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},fi=k({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. "config" is required when invoked via MCP (the CLI interactive picker is unreachable without a TTY).',inputSchema:{config:co.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:co.string().describe("Path to the file that must be sourced to apply variables"),variableCount:co.number().describe("Number of variables loaded"),project:co.string().describe("Doppler project name"),config:co.string().describe("Doppler config name")},handler:sp});import _g from"node:fs";import Ng from"node:os";import jg from"node:path";var Mg="infra-kit.json",Fg="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)",Lg="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",lo=async()=>{let e;try{e=await R()}catch{return null}let r=e.trim();return r===""||r===Ng.homedir()?null:r},cp=async()=>{let e=await lo();return e===null&&l.info(Fg),e},Wg=async()=>{let e=await lo();return e===null?null:_g.existsSync(jg.join(e,Mg))?e:(l.info(Lg),null)};var Jg=async e=>{try{return await re(e)}catch(r){return l.debug({err:r,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},lp=async()=>{let e=await Wg(),r=ae.version;if(e===null)return{skipped:!0,root:null,version:r,written:[]};let t=[...await zt(e,{version:r})];for(let o of await Jg(e)){let n=await Vt(o);t.push(...await qt(o,{repoRoot:e,version:r,declaredType:n}))}return{skipped:!1,root:e,version:r,written:t}};import Se from"node:fs";import Pp from"node:os";import he from"node:path";import Ep from"node:process";import $n from"node:fs/promises";import Vg from"node:path";import Bg from"node:process";var pp=` // "envManagement": { // required in layer 1; provider-tagged
191
- // "provider": "doppler",
192
- // "config": { "name": "my-doppler-project" }
193
- // },
194
- //
195
- // "ide": {
196
- // "provider": "cursor",
197
- // "config": { "workspaceConfigPath": "/path/to/your.code-workspace" }
198
- // },
199
- // // Or, for Zed (no workspace file \u2014 one window with all worktrees via "zed <root> <wt...>"):
200
- // "ide": { "provider": "zed", "config": {} },
201
- // // Or drive BOTH editors at once with an array (at most one entry per provider):
202
- // "ide": [
203
- // { "provider": "cursor", "config": { "workspaceConfigPath": "/path/to/your.code-workspace" } },
204
- // { "provider": "zed", "config": {} }
205
- // ],
206
- //
207
- // "taskManager": {
208
- // "provider": "jira",
209
- // "config": { "baseUrl": "https://acme.atlassian.net", "projectId": 123 }
210
- // },
211
- // NOTE: taskManager is validated but NOT yet used \u2014 Jira credentials and the project id are read
212
- // from the JIRA_BASE_URL / JIRA_EMAIL / JIRA_TOKEN / JIRA_PROJECT_ID environment variables
213
- // (Doppler), never from this file. Editing projectId here changes nothing; change it in Doppler.
214
- //
215
- // "worktrees": {
216
- // "openInGithubDesktop": false,
217
- // "openInCmux": true,
218
- // // cmux pane layout for opened worktrees: "two-columns" (default, left | right)
219
- // // or "three-pane" (left split top/bottom + full-height right).
220
- // "cmux": { "layout": "two-columns" }
221
- // },
222
- //
223
- // // Auto-load Doppler env when working inside this project/worktree. Omit to
224
- // // disable. "trigger" (pick one): "shell-startup" (new shells) | "cli-invocation"
225
- // // (before each infra-kit command, primes subsequent commands). "config" is the
226
- // // environment to load \u2014 must have a service token (infra-kit env-token-set) or
227
- // // auto-load quietly disables. Requires the committed infra-kit.json at the git
228
- // // repo root, and the zsh shell integration (infra-kit init + a new shell). zsh only.
229
- // "envAutoLoad": { "trigger": "shell-startup", "config": "dev" },
230
- //
231
- // // Per-app local-dev overrides, keyed by APP FOLDER name (the directory under
232
- // // apps/). Both fields optional: "port" pins the local listen port (otherwise
233
- // // <APP>_PORT / PORT / a built-in default), "prefixUrl" pins the URL prefix the
234
- // // app is served under. An unknown app name is ignored at resolve time, never a
235
- // // parse error.
236
- // "dev": {
237
- // "client": { "port": 4001, "prefixUrl": "/api" }
238
- // },
239
- //
240
- // // Named \`infra-kit dev <preset>\` sessions. The keys under "apps" are PACKAGES \u2014
241
- // // "<app>/api" or "<app>/ui". A bare "<app>" is a FOLDER, not a package, and is
242
- // // REJECTED. Per target: "watchDeps" (api targets) rebuilds the shared-package
243
- // // dependency closure and restarts on change; "proxy" maps a route path to
244
- // // "local" | "cloud" for this session only. "cmux": true runs each launched target
245
- // // in its own cmux pane. Omit "apps" entirely to launch every discovered target.
246
- // "devServersPresets": {
247
- // "backend": {
248
- // "apps": {
249
- // "client/api": { "watchDeps": true, "proxy": { "/api": "local", "/auth": "cloud" } },
250
- // "client/ui": {}
251
- // },
252
- // "cmux": true
253
- // }
254
- // },
255
- //
256
- // // DEPRECATED \u2014 accepted but IGNORED; safe to delete. Remove it and this note in a
257
- // // future release.
258
- // //
259
- // // The proxy port is no longer configurable. Every dev URL is now
260
- // // https://<release>.<package>.localhost with NO port, and the only port that can
261
- // // serve a port-free HTTPS URL is 443 \u2014 so a setting here could only put the port
262
- // // back into the URL. Set up the daemon once (the install is the only step needing
263
- // // root; trusting its local CA does not). Run \`infra-kit doctor\`: it checks both and
264
- // // prints each fix as a command you can paste, with the paths filled in for your
265
- // // machine. Do not type a bare \`portless\` \u2014 it lives in node_modules, not on PATH.
266
- // // infra-kit itself never elevates.
267
- // "devProxy": { "port": 443 },
268
- //
269
- // // May this project deploy to the delivery-shaped environments ("prod")? The LIST lives in code
270
- // // (lib/workflow-envs/protected-envs); this decides only whether THIS project may reach it.
271
- // // "disallow" \u2014 the DEFAULT when the key is absent. Filtered out of every deploy picker and
272
- // // refused, on both \`--from local\` and \`--from ci\`. Use
273
- // // \`infra-kit release deliver\`, which also does the RC PR and the Jira version.
274
- // // "allow" \u2014 reachable from the CLI and from an MCP agent alike.
275
- // // "cli-only" \u2014 reachable from a terminal, but NOT over MCP: an agent's tool call carries no
276
- // // human keystroke, so agents keep the refusal.
277
- // // Allowing it does not remove the other gates: a local deploy still requires the AWS account to
278
- // // report that environment, and still refuses a dirty tree \u2014 unconditionally, with nothing to pass
279
- // // that waives it. A \`--from ci\` dispatch has no such second gate and prints a warning naming
280
- // // what it skips.
281
- // //
282
- // // It IS honoured from this layer \u2014 the merge treats it like any other key \u2014 but it belongs in the
283
- // // committed project infra-kit.json, where a reviewer and \`git blame\` can see it. Setting it here
284
- // // grants yourself production access with no trace in the repo.
285
- // "protectedEnvs": "disallow"
286
- //
287
- // // MCP servers fronted by \`ik-mcp\`, the credential-agnostic stdio proxy: one entry per server,
288
- // // naming the command to spawn and the env-var NAMES it reads from the \`ik env-load\` session
289
- // // file. \`ik setup\` derives a committed \`.mcp.json\` entry from each; \`ik audit\` guards drift.
290
- // //
291
- // // PROJECT LAYER ONLY. This key is REFUSED here and in the per-project override \u2014 the loader
292
- // // throws with a message saying so \u2014 because it feeds a committed file and the layer merge is
293
- // // shallow: a per-machine copy would replace the project's servers for everyone. For a
294
- // // machine-only override of one server (a local fork), use Claude Code's own local scope:
295
- // // claude mcp add --scope local <name> -- ik-mcp --name <name> --env <VAR> -- <command> <args>
296
- // // The proxy is for STATELESS servers: a credential change respawns the child.
297
- // "mcp": {
298
- // "grafana": {
299
- // "command": "mcp-grafana",
300
- // "args": ["-t", "stdio"],
301
- // "env": ["GRAFANA_URL", "GRAFANA_SERVICE_ACCOUNT_TOKEN"],
302
- // "unset": ["GRAFANA_API_KEY", "GRAFANA_SERVICE_ACCOUNT_TOKEN_FILE"]
303
- // }
304
- // }
305
- //
306
- // // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in
307
- // // tokens.json \u2014 a SIBLING of this file, at ~/.infra-kit/projects/<repo>/tokens.json (mode 0600) \u2014
308
- // // shaped { "envs": { "<env>": "dp.st\u2026" } }. Write it with \`infra-kit env-token-set <env>\` (which
309
- // // also fixes its modes), or by hand: both are supported, which is why the store carries no
310
- // // repo-identity field and no mandatory version. Pasting a token into an
311
- // // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
312
- // // the token first, because a config file can be committed, backed up by your editor, or shared.`,gi=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
313
- //
314
- // Merge chain (later layers override earlier ones at top-level keys):
315
- // 1. <repo>/infra-kit.json \u2014 committed project config (required)
316
- // 2. ~/.infra-kit/infra-kit.json \u2014 user-global (the sibling of this file)
317
- // 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override
318
- //
319
- // Merge is shallow: setting a top-level key replaces that whole section from
320
- // layer 1. Arrays do not concatenate. Top-level keys recognized:
321
- // envManagement, ide, taskManager, worktrees, envAutoLoad, dev,
322
- // devServersPresets, devProxy, protectedEnvs, mcp (project layer only). The schema is strict \u2014 an
323
- // unrecognized top-level key is a parse error, not a silently ignored one.
324
- //
325
- // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
326
- // overrides in the sibling infra-kit.json (strict JSON: no comments, double-quoted
327
- // keys). Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
328
- //
329
- // Every recognized key is documented below. NOTE: \`envManagement\` is REQUIRED in
330
- // the committed project infra-kit.json (layer 1) and is usually NOT set in this
331
- // user-global layer \u2014 it is shown here only to document the full, valid config shape.
332
- {
333
- ${pp}
334
- }
335
- `,hi=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
336
- //
337
- // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
338
- // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
339
- // top-level key set here replaces that whole section wholesale; arrays do not
340
- // concatenate. Top-level keys recognized: envManagement, ide,
341
- // taskManager, worktrees, envAutoLoad, dev, devServersPresets, devProxy,
342
- // protectedEnvs, mcp (project layer only \u2014 refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
343
- // error, not a silently ignored one.
344
- //
345
- // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
346
- // in the sibling infra-kit.json (strict JSON: no comments, double-quoted keys).
347
- //
348
- // Every recognized key is documented below. NOTE: \`envManagement\` is REQUIRED in
349
- // the committed project infra-kit.json (layer 1) and is usually NOT set in this
350
- // override layer \u2014 it is shown here only to document the full, valid config shape.
351
- {
352
- ${pp}
353
- }
354
- `,vi=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
355
- //
356
- // Machine-local registry the vendor commands (sync/manifest/diff) read to know
357
- // where your project repos live and which ones to stamp. This .example.jsonc is
358
- // reference only \u2014 it is NOT loaded. The real file is the strict-JSON sibling
359
- // vendor.json (no comments, double-quoted keys); run \`infra-kit vendor config --init\`
360
- // to scaffold it.
361
- {
362
- // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
363
- // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
364
- }
365
- `;var dp=!1,Gg=e=>e.replace(/\.json$/,".example.jsonc"),Kg=async e=>{try{return await $n.readFile(e,"utf-8")}catch{return null}},Dn=async e=>{let r=e.userProject,t=Gg(r);await $n.mkdir(Vg.dirname(r),{recursive:!0});let o=!await fe(r);o&&await $n.writeFile(r,`{}
366
- `,"utf-8");let n=hi(e.projectName),s=await Kg(t)!==n;return s&&await $n.writeFile(t,n,"utf-8"),o&&Gc(),{configPath:r,examplePath:t,createdConfig:o,refreshedExample:s}},On=e=>`Created ${b(e.configPath)} \u2014 see ${b(e.examplePath)} for the annotated reference.`,Ug=async()=>{if(Bg.env.INFRA_KIT_NO_SEED||dp)return;dp=!0;let e;try{e=await q()}catch{return}if(await fe(e.main))try{let r=await Dn(e);r.createdConfig?l.info(On(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{spawnSync as Hg}from"node:child_process";var wi="claude",zg=12e4,yi=["plugin","marketplace","add",Rr],ki=["plugin","install",W,"--scope","project"],mp=["--version"],fp=e=>{let r=Hg(wi,[...e.args],{cwd:e.cwd,encoding:"utf-8",stdio:["ignore","pipe","pipe"],timeout:zg});if(r.error!==void 0)return{ok:!1,output:r.error.message};let t=`${r.stderr??""}
367
- ${r.stdout??""}`.trim();return{ok:r.status===0,output:t}},up=(e,r)=>Xt({projectPath:e,home:r}).kind==="installed",gp=e=>((e??"").split(`
368
- `).find(t=>t.trim().length>0)??"").trim(),qg=(e,r)=>{if(Zt(r))return null;l.debug({msg:`Running: ${wi} ${yi.join(" ")}`});let t=e({args:yi});return t.ok?null:{step:"marketplace",error:gp(t.output)}},bi=e=>{let{projectRoot:r,home:t}=e,o=e.run??fp;if(up(r,t))return{status:"already-installed"};if(!o({args:mp}).ok)return{status:"claude-missing"};let n=qg(o,t);if(n!==null)return{status:"failed",...n};l.debug({msg:`Running: ${wi} ${ki.join(" ")}`});let s=o({args:ki,cwd:r});return s.ok?up(r,t)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:gp(s.output)}};import de from"node:fs/promises";import xe from"node:path";import{pathToFileURL as Xg}from"node:url";import Qg from"yaml";import{z as yp}from"zod";import Yg from"node:fs/promises";import Ri from"node:os";import Pi from"node:path";import{z as Zg}from"zod";import{z as _n}from"zod";var hp="vendor.json",Nn=_n.object({workspaceDir:_n.string().min(1),targets:_n.array(_n.string()).min(1)}).strict();var Ei=()=>Pi.join(Ri.homedir(),gc,hp),yC=e=>{if(e==="~")return Ri.homedir();if(e.startsWith("~/"))return Pi.join(Ri.homedir(),e.slice(2));if(Pi.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},kC=async()=>{let e=Ei(),r;try{r=await Yg.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:
369
-
370
- {
371
- "workspaceDir": "~/projects",
372
- "targets": ["my-repo"]
373
- }
374
- `)}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=Nn.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${Zg.prettifyError(o.error)}`);return o.data};var vp=e=>e.replace(/\.json$/,".yml"),kp=async()=>{let e;try{e=await q()}catch{return}let r=[{label:"infra-kit.json",yml:vp(e.main),json:e.main,schema:Bc},{label:"~/.infra-kit/infra-kit.json",yml:xe.join(xe.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:hs},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:vp(e.userProject),json:e.userProject,schema:hs}],t=0;for(let o of r){let[n,s]=await Promise.all([fe(o.yml),fe(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 de.readFile(o.yml,"utf-8"),a=Qg.parse(i)??{},c=o.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${b(o.yml)} \u2014 invalid config: ${yp.prettifyError(c.error)}`);continue}await de.mkdir(xe.dirname(o.json),{recursive:!0}),await de.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
375
- `,"utf-8"),await de.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&&Zr()},wp=async()=>{let e;try{e=await q()}catch{return}let r=xe.dirname(e.userGlobal),t=[{from:xe.join(r,"config.json"),to:e.userGlobal},{from:xe.join(r,"config.example.jsonc"),to:xe.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:n,to:s}of t){let[i,a]=await Promise.all([fe(n),fe(s)]);if(i){if(a){l.info(`\u26A0 Skipped ${b(n)} \u2014 ${b(s)} already exists (remove the stale file manually)`);continue}try{await de.mkdir(xe.dirname(s),{recursive:!0}),await de.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&&Zr()},bp=async()=>{let e=Ei(),r=xe.dirname(e),t=xe.join(r,"vendor.config.ts"),[o,n]=await Promise.all([fe(t),fe(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 de.stat(t),c=(await import(`${Xg(t).href}?mtime=${Number(s.mtimeMs)}`)).default,p=typeof c=="function",d=p?await c():c,u=Nn.safeParse(d);if(!u.success){l.info(`\u26A0 Skipped ${b(t)} \u2014 invalid factory config: ${yp.prettifyError(u.error)}`);return}await de.mkdir(r,{recursive:!0}),await de.writeFile(e,`${JSON.stringify(u.data,null,2)}
376
- `,"utf-8"),await de.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}`)}}},eh=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}},Rp=async()=>{let e;try{e=await q()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await fe(o))try{let n=await de.readFile(o,"utf-8");if(n.trim()==="")continue;let s=JSON.parse(n),{changed:i,result:a}=eh(s);if(!i)continue;await de.writeFile(o,`${JSON.stringify(a,null,2)}
377
- `,"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&&Zr()};var po="# -- infra-kit:begin --",yt="# -- infra-kit:end --",rh=[["# region infra-kit","# endregion infra-kit"]],th="# infra-kit shell functions",vt=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},uo="Run `source ~/.zshrc` or open a new terminal to activate.",oh={step:"migrations",outcome:"skipped",message:"Config migrations checked (legacy yml layers, ide structure, user-global filename, factory config)",level:"silent"},er=async(e,r)=>{try{return await r()}catch(t){throw new vt(e,t)}},xi=async e=>{let r=[],t=(...s)=>{for(let i of s)r.push(i),e?.(i)};await er("zshrc",()=>{t(nh())}),await er("migrations",async()=>{await sh(),t(oh)}),await er("user-config",()=>{t(ah())});let o=await er("guidance",async()=>{let{entries:s,root:i}=await ph();return t(...s),i}),n=await er("plugin-pointer",async()=>cp());return t(...mh(n,o)),await er("plugin-pointer",()=>{hh(n,t)}),await er("mcp-proxies",async()=>{t(...await yh(n))}),await er("project-config",async()=>{t(...await ch())}),t(...ih()),r},Mn=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)}},nh=()=>{let e=he.join(Pp.homedir(),".zshrc"),r=Se.existsSync(e)?wh(Se.readFileSync(e,"utf-8")):"",t=Ut({content:r,body:xp(),startMarker:po,endMarker:yt,placement:"append-end"});return Se.writeFileSync(e,t),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},sh=async()=>{await kp(),await Rp(),await wp(),await bp()},ih=()=>{let e=Ep.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:uo,level:"info"}),r},ah=()=>{let e=he.join(Pp.homedir(),".infra-kit"),r=he.join(e,"infra-kit.json");return Se.mkdirSync(e,{recursive:!0}),Se.writeFileSync(he.join(e,"infra-kit.example.jsonc"),gi(),"utf-8"),Se.writeFileSync(he.join(e,"vendor.example.jsonc"),vi(),"utf-8"),Se.existsSync(r)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${r} (refreshed reference examples)`,level:"info"}:(Se.writeFileSync(r,`{}
378
- `,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`,level:"info"})},ch=async()=>{if(Ep.env.INFRA_KIT_NO_SEED)return[jn("INFRA_KIT_NO_SEED is set")];try{let e=await q();if(!Se.existsSync(e.main))return[jn(`no project config at ${e.main}`)];let r=await Dn(e);return r.createdConfig?[{step:"project-config",outcome:"written",message:On(r),level:"info"}]:[jn("the user-project config was already present")]}catch(e){return l.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[jn(e instanceof Error?e.message:String(e))]}},jn=e=>({step:"project-config",outcome:"skipped",message:`Skipped seeding the user-project config \u2014 ${e}`,level:"silent"}),lh=(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)} ${he.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},ph=async()=>{let{skipped:e,root:r,version:t,written:o}=await lp();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:lh(r,t,o)}},dh=(e,r)=>{let t=he.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"}},uh=(e,r)=>{let t=he.relative(e,r.path);return r.status==="created"?{step:"mcp-server",outcome:"written",message:` created ${t} (infra-kit MCP server)`,level:"info"}:r.status==="added"?{step:"mcp-server",outcome:"written",message:` updated ${t} \u2014 added the ${x} MCP server`,level:"info"}:{step:"mcp-server",outcome:r.status==="unchanged"?"unchanged":"warned",message:`${t} \u2014 ${r.status}`,level:"silent"}},mh=(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 .mcp.json, and installing the ${W} plugin for that project. If that is not the repo you meant to set up, revert those two files.`,level:"warn"}],fh=()=>[Js,Xe].map(e=>({step:"plugin-pointer",outcome:"skipped",message:e,level:"info"})),gh=e=>e.status==="already-installed"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${W} is already installed for this project.`,level:"debug"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${W} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...fh()]:[{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: ${Xe}`,level:"warn"}],hh=(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(dh(e,Vs(he.join(e,".claude","settings.json")))),r(uh(e,Zs(e))),r(...gh(bi({projectRoot: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: ${Xe}`,level:"warn"})}},vh=(e,r)=>{let t=he.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},yh=async e=>{if(e===null)return[];if(!Se.existsSync(he.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 E()).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(`
379
- `)[0]??o})`,level:"warn"}]}return!r||Object.keys(r).length===0?[]:vh(e,xn({projectRoot:e,proxies:r,write:!0}))},kh=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"),wh=e=>{let r=Ze(e,po,yt);if(r!==null)return r;for(let[a,c]of rh){let p=Ze(e,a,c);if(p!==null)return p}let t=e.indexOf(th);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
380
- `),s=0;for(;s<n.length&&kh(n[s]);)s++;let i=n.slice(s).join(`
381
- `);return o+(i?`
382
- ${i}`:"")},xp=()=>{let e="pnpm exec infra-kit";return["zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null","zmodload zsh/sched 2>/dev/null",'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",": ${_INFRA_KIT_LAST_LOAD_MTIME:=0}",": ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}",": ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}",": ${_INFRA_KIT_WARM_TTL:=7200}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED _INFRA_KIT_WARM_TTL",`env-load() { local f m; f=$(${e} env-load "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source "$f"; ${e} env-status; }`,`env-clear() { local f m; f=$(${e} env-clear "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`,"_infra_kit_notify() {"," zle && print -u2 -n $'\\r\\e[K'",' print -u2 -- "$1"'," zle && zle reset-prompt","}","_infra_kit_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local dir="$cache_root/$INFRA_KIT_SESSION"',' local load_file="$dir/env-load.sh"',' local clear_file="$dir/env-clear.sh"'," local load_mtime=0 clear_mtime=0",' [[ -f "$load_file" ]] && load_mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)',' [[ -f "$clear_file" ]] && clear_mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( load_mtime > _INFRA_KIT_LAST_LOAD_MTIME && load_mtime >= _INFRA_KIT_SHELL_STARTED && load_mtime >= clear_mtime )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$load_mtime",' _infra_kit_notify "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," if (( clear_mtime > _INFRA_KIT_LAST_CLEAR_MTIME && clear_mtime >= _INFRA_KIT_SHELL_STARTED && clear_mtime > load_mtime )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$clear_mtime",' _infra_kit_notify "infra-kit: auto-cleared env"'," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi","_INFRA_KIT_AUTOLOAD_WINDOW=6","export _INFRA_KIT_AUTOLOAD_WINDOW","_infra_kit_poll_autoload() {"," _infra_kit_autoload"," if (( _INFRA_KIT_LAST_LOAD_MTIME < _INFRA_KIT_SHELL_STARTED )) && (( ${EPOCHSECONDS:-0} - _INFRA_KIT_SHELL_STARTED < _INFRA_KIT_AUTOLOAD_WINDOW )); then"," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," fi","}","_infra_kit_warm_source() {",' local canon="$1" key'," if (( $+commands[shasum] )); then",' key=$(printf %s "$canon" | shasum -a 256 | cut -c1-64)'," elif (( $+commands[sha256sum] )); then",' key=$(printf %s "$canon" | sha256sum | cut -c1-64)'," else"," return"," fi",' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local warm="$cache_root/projects/$key/env-load.sh"',' local wclear="$cache_root/projects/$key/env-clear.sh"',' [[ -f "$warm" ]] || return'," local wm=0 cm=0",' wm=$(zstat +mtime -- "$warm" 2>/dev/null || echo 0)',' [[ -f "$wclear" ]] && cm=$(zstat +mtime -- "$wclear" 2>/dev/null || echo 0)'," (( cm >= wm )) && return"," (( ${EPOCHSECONDS:-0} - wm >= _INFRA_KIT_WARM_TTL )) && return",' source "$warm"',' _infra_kit_notify "infra-kit: loaded cached vars for ${INFRA_KIT_ENV_CONFIG:-?} (refreshing\u2026)"',"}","_infra_kit_startup_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local dir="$PWD" prev=""',' while [[ -n "$dir" && "$dir" != "$prev" ]]; do',' if [[ -f "$dir/infra-kit.json" ]]; then',' [[ -n "$INFRA_KIT_ENV_CONFIG" && "$dir" == "$INFRA_KIT_ENV_PROJECT_ROOT" ]] && return',' local canon="${dir:A}"',' _infra_kit_warm_source "$canon"',` ( ${e} env-autoload --project-dir "$canon" & ) >/dev/null 2>&1`," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," return"," fi",' prev="$dir"',' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
383
- `)},Sp=()=>`${po}
384
- ${xp()}
385
- ${yt}`;import bh from"node:fs/promises";var Si=async(e,r)=>{if(!r)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let t=await bh.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}}},Ti=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import Ph from"node:fs";import Eh from"node:os";import Tp from"node:path";import xh from"node:process";import{$ as Rh}from"zx";var Cr=()=>Rh({quiet:!0});var Sh=()=>[Tp.join(Eh.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],Th=async e=>{try{return(await Cr()`command -v ${e}`).stdout.trim()||null}catch{return null}},mo=()=>({runCommand:async e=>{let r=await Cr()`${e}`;return{stdout:`${r.stdout}
386
- ${r.stderr}`}},resolveBinPath:async e=>{let r=await Th(e);return r!==null?r:Sh().map(t=>Tp.join(t,e)).find(t=>Ph.existsSync(t))??null},realpath:qr,platform:xh.platform});var Ar=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),go=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,ho=["darwin","linux"],Ai=e=>r=>cs(r,e)?"homebrew":"unknown",Wn=(e,r)=>t=>t===null?null:r(e(t),t),$p=e=>Wn(Ai(e.kegName),r=>r==="homebrew"?Ar(["brew","upgrade",e.brewFormula]):null),Cp=e=>en(e,"Homebrew")||en(e,"homebrew")?"homebrew":"unknown",Ch={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:go,platforms:ho,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Cp,updateFor:Wn(Cp,e=>e==="homebrew"?Ar(["brew","update"]):null)},Ci={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Dp="https://awscli.amazonaws.com/v2/install.sh",Op={steps:[["/bin/bash","-c",`curl -fsSL ${Dp} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},Ah="/usr/local/aws-cli",Ih=e=>Qo(Ah,e,qr)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Dp} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Op,Ap=e=>cs(e,Ci.kegName)?"homebrew":en(e,"aws-cli")?"script":"unknown",$h={id:"aws",binName:"aws",...Ci,probeArgv:["aws","--version"],versionFrom:go,platforms:ho,prerequisites:[],bootstrapInstall:Op,identify:Ap,updateFor:Wn(Ap,(e,r)=>e==="homebrew"?Ar(["brew","upgrade",Ci.brewFormula]):e==="script"?Ih(r):null)},Fn={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},Dh={id:"gh",binName:"gh",...Fn,probeArgv:["gh","--version"],versionFrom:go,platforms:ho,prerequisites:["brew"],bootstrapInstall:Ar(["brew","install",Fn.brewInstallSpec]),identify:Ai(Fn.kegName),updateFor:$p(Fn)},Ln={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},Oh={id:"doppler",binName:"doppler",...Ln,probeArgv:["doppler","--version"],versionFrom:go,platforms:ho,prerequisites:["brew"],bootstrapInstall:Ar(["brew","install","gnupg"],["brew","install",Ln.brewInstallSpec]),identify:Ai(Ln.kegName),updateFor:$p(Ln)},fo="portless",Ip=e=>vc(e,fo)===null?"unknown":"npm",_h={id:"portless",binName:fo,npmPackage:fo,probeArgv:["portless","--version"],versionFrom:go,platforms:[...ho,"win32"],prerequisites:[],bootstrapInstall:Ar(["npm","install","-g",fo]),identify:Ip,updateFor:Wn(Ip,e=>e==="npm"?Ar(["npm","install","-g",`${fo}@latest`]):null)},Ii={brew:Ch,aws:$h,gh:Dh,doppler:Oh,portless:_h},Ir=Object.keys(Ii),ve=e=>Ii[e],$i=(e,r)=>e.platforms.includes(r),Di=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 ve(n).prerequisites)o(i,[...s,n]);r.push(n)}};for(let n of e)o(n,[]);return r};var _p=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Np=async(e,r)=>{try{return await e(r)}catch{return null}},Nh=async(e,r)=>{try{let t=await e.resolveBinPath(r);return t==null?null:e.realpath(t)}catch{return null}},jp=async(e,r)=>{if(!$i(e,r.platform))return _p(e.id);let t=await Np(r.runCommand,e.probeArgv),o=await Nh(r,e.binName);if(t==null&&o==null)return _p(e.id);let n=t??(o==null?null:await Np(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)}},vo=async(e,r)=>Promise.all(e.map(t=>jp(ve(t),r)));import{$ as Gh}from"zx";import ko from"node:process";var jh="x-seraph-loginreason",Mh="AUTHENTICATED_FAILED",Fh=(e,r=160)=>{let t=e.split(`
387
- `,1)[0].trim();return t.length>r?`${t.slice(0,r)}\u2026`:t},Fp=(e,r)=>r===Mh||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Mp=(e,r)=>e==="auth"?`Jira rejected the credentials (HTTP ${r}) \u2014 check JIRA_EMAIL and JIRA_TOKEN; Atlassian API tokens expire`:e==="forbidden"?`Jira authenticated the account but refused the operation (HTTP ${r}) \u2014 the account lacks permission on this project`:e==="not-found-or-forbidden"?`Jira returned HTTP ${r}: either JIRA_PROJECT_ID does not exist, or these credentials cannot browse it, or the Authorization header was malformed and the request went out anonymous`:`Jira returned HTTP ${r}`,kt=class extends Error{status;kind;body;context;constructor(r){let t=Fp(r.status,r.seraphLoginReason),o=Fh(r.body);super(o===""?`${r.context}: ${Mp(t,r.status)}`:`${r.context}: ${Mp(t,r.status)}. Jira said: ${o}`),this.name="JiraApiError",this.status=r.status,this.kind=t,this.body=r.body,this.context=r.context}},yo=e=>e instanceof kt,Lp=e=>e.headers.get(jh);var wt=async(e,r)=>{if(e.ok)return;let t=await e.text(),o=new kt({status:e.status,seraphLoginReason:Lp(e),body:t,context:r});throw l.debug({status:e.status,kind:o.kind,body:t},r),o},rr=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,Oi=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 wt(p,"Failed to create Jira version"),{success:!0,version:await p.json()}},bt=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 wt(a,"Failed to get Jira project versions"),await a.json()},Me=async(e,r)=>(await bt(r)).find(n=>n.name===e)||null,Rt=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 wt(c,"Failed to update Jira version"),{success:!0,version:await c.json()}},_i=async(e,r)=>{let{versionName:t}=e,o=await Me(t,r);if(!o)throw new Error(`Version "${t}" not found in Jira project`);return await Rt({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)},Pt=async()=>{let e=ko.env.JIRA_BASE_URL,r=ko.env.JIRA_TOKEN||ko.env.JIRA_API_TOKEN,t=ko.env.JIRA_PROJECT_ID,o=ko.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}},Fe=async()=>{try{return await Pt()}catch(e){return l.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Jn=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 wt(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Ni=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 wt(c,"Failed to remove Jira version")};var tr=e=>e.slice(1).split(".").map(Number),Et=e=>[...e].sort((r,t)=>{let[o,n,s]=tr(r),[i,a,c]=tr(t);return o!==i?(o??0)-(i??0):n!==a?(n??0)-(a??0):(s??0)-(c??0)});var Jp="next",Lh=/^v?(\d+)\.(\d+)\.(\d+)$/,Wh=e=>e.replace(/^.*release\//,""),Mi=e=>{let r=Wh(e.trim()),t=Lh.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},Wp=e=>`${e[0]}.${e[1]}.${e[2]}`,Fi=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=Mi(n);if(!s)continue;let i=Wp(s);o.has(i)||(o.add(i),t.push(s))}return Et(t.map(n=>Wp(n))).map(n=>tr(`v${n}`))},$r=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Vn=(e,r)=>{if(e.length===0)throw new $r;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`},Li=e=>e.trim().toLowerCase()===Jp,Jh=e=>e==="regular"||e==="hotfix",Vp=e=>"name"in e,Vh=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(!Jh(d))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);n=d}if(Li(o)||Mi(o)!==null){let a={version:o,type:n};return s!==""&&(a.description=s),a}let i={name:o,type:n};return s!==""&&(i.description=s),i},Wi=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},ji=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Bh=e=>{let r=e.name.trim();return on(r),ji({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},Ji=(e,r)=>{let t=[...r];return e.map(o=>{if(Vp(o))return Bh(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(Li(n)){let a=Vn(t,o.type);return t.push(tr(`v${a}`)),ji({id:me(a),type:o.type},o.description)}let s=Mi(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),ji({id:me(i),type:o.type},o.description)})},Vi=e=>e.some(r=>!Vp(r)&&Li(r.version));var Kh=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),Uh=async()=>{let e=await Gh({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return Kh(e.stdout)},Hh=async()=>{let e=await Fe();return e?(await bt(e)).map(t=>t.name):[]},Bi=async()=>{let[e,r]=await Promise.allSettled([Uh(),Hh()]);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"),Fi({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var qh=["brew","gh","doppler","aws"],Yh=async e=>{let r=await vo(qh,e);return new Map(r.map(t=>[t.id,{manager:t.manager,version:t.version,present:t.present,onPath:t.onPath}]))},Le=async(e,r,t,o)=>{try{return await Cr()`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Zh=()=>{let e="zshrc init block",r=U.join(zp.homedir(),".zshrc");if(!J.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit setup --skip-tools"};let t=J.readFileSync(r,"utf-8"),o=t.indexOf(po),n=t.indexOf(yt);if(o===-1||n===-1||n<o)return{name:e,status:"fail",message:"infra-kit shell block missing from ~/.zshrc. Run: infra-kit setup --skip-tools"};let s=t.slice(o,n+yt.length).trim(),i=Sp().trim();return s!==i?{name:e,status:"fail",message:"infra-kit shell block in ~/.zshrc is out of date. Run: infra-kit setup --skip-tools"}:{name:e,status:"pass",message:"infra-kit shell block in ~/.zshrc is up to date"}},Xh=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=je(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let o=U.join(mr(t),se);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(jt/60);return n>=jt?{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`}},Qh=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await R(),t=U.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}`}}},ev=async()=>{try{return Zr(),{config:await E(),error:null}}catch(e){return{config:null,error:e}}},rv=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)"}},tv=384,Gi=448,ov=e=>e.map(r=>{let t=r.source===null?"no token":`token (${r.source})`;return`${r.env}: ${t}`}).join(", "),nv=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}}})),sv=async(e,r={})=>{let t="env tokens configured",o=r.readStore??ce,n=r.resolveToken??dt;if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let s;try{s=await o()}catch(m){return{name:t,status:"fail",message:`Token store unreadable \u2014 ${m.message}`}}let i=await xr(),a=e.config.envAutoLoad?.config,c=a&&!i.includes(a)?[...i,a]:i,p=await nv(c,n),d=ov(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}`}},iv={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)"}},av=async(e,r={})=>{let t="env token valid",o=r.resolveToken??dt,n=r.probe??so;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:ht(i),project:a,config:s}),p=iv[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}`}},cv=()=>Bn.env[Y]||void 0,lv=async(e={})=>{let r="tokens.json present",t=e.readStore??ce,o=e.storePath??Lt;if((e.readEnvToken??cv)())return{name:r,status:"pass",message:`Skipped \u2014 ${Y} 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 ${Y} instead.`}}return{name:r,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},wo=(e,r)=>{let t=r(e);return t===null?null:t.mode&511},pv=async(e,r={})=>{let t="tokens.json perms",o=r.storePath??Lt,n=r.statPath??dv,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(wo(i,n)===null)return{name:t,status:"pass",message:`No store to protect at ${b(i)} (see tokens.json present)`};let a=U.dirname(i),c=U.dirname(a),p=U.dirname(c),u=[{target:p,expected:Gi,actual:wo(p,n)},{target:c,expected:Gi,actual:wo(c,n)},{target:a,expected:Gi,actual:wo(a,n)},{target:i,expected:tv,actual:wo(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 ${Bp(v.actual)}, expected ${Bp(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}`}},Bp=e=>`0${e.toString(8).padStart(3,"0")}`,dv=e=>{try{return J.statSync(e)}catch{return null}},uv=async()=>{let e="user override path";try{let r=await q(),t=J.existsSync(r.userProject),o=await Si(r.userProject,t),n=t?Ti(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}}},mv=async()=>{let e="legacy user-global config",r;try{r=await q()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=U.join(U.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"}},fv={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/"}},gv=async e=>{let r=fv[e];try{return await Cr()`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},hv=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=we(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=>gv(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("; ")}},Gp=/^\d+\.\d+\.\d+$/,vv=(e,r)=>e===r||!Gp.test(e)||!Gp.test(r)?!1:Et([`v${e}`,`v${r}`])[0]===`v${e}`,yv=async(e,r)=>{let t;try{t=await re(e)}catch{return[]}let o=[];for(let n of t){let s=kr(wr(U.join(n,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&vv(s.version,r)&&o.push(s.version)}return o},kv=async(e,r)=>{let t=await yv(e,r);if(t.length===0)return"";let o=Et(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`},wv=async()=>{let e;try{e=(await q()).main}catch{return[]}if(!J.existsSync(e))return[];let r=U.dirname(e),t=U.join(r,"CLAUDE.md"),o=J.existsSync(t)?J.readFileSync(t,"utf-8"):"",n=Re(o,le,Pe),s=n?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",i=await kv(r,ae.version);return[{name:"CLAUDE.md block",status:n?"pass":"fail",message:`${s}${i}`}]},bv=async()=>{try{let e=(await q()).main;return J.existsSync(e)?U.dirname(e):null}catch{return null}},Rv=e=>{let r=e.kind==="installed"?Gs(e.installation):null;return{name:"plugin version",status:r===null?"fail":"pass",message:r===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${W} version ${r}`}},Kp=3,Pv=e=>{let r="plugin installed";if(e.kind==="installed"){let{scope:i,projectPath:a}=e.installation,c=a===null?"":`, ${b(a)}`;return{name:r,status:"pass",message:`Plugin ${W} installed (${i??"unknown"} scope${c})`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${W} is not installed. Run: ${Xe}`};let t=e.installations.map(i=>i.projectPath===null?"(unnamed project)":b(i.projectPath)),o=t.length-Kp,n=o>0?` and ${o} more`:"",s=`${t.slice(0,Kp).join(", ")}${n}`;return{name:r,status:"fail",message:`Plugin ${W} is installed for ${s} only, not this project. Run: ${Xe}`}},Ev=()=>Le("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),xv=e=>{let r=Xt(e===null?{}:{projectPath:e}),t=Zt();return[{name:"marketplace registered",status:t?"pass":"fail",message:t?`Marketplace ${x} is known to Claude Code`:`Marketplace ${x} is not registered. Run: claude plugin marketplace add ${Rr}`},Pv(r),Rv(r),{name:"CLI version",status:"pass",message:`infra-kit CLI ${ae.version}`}]},Sv={ok:`.mcp.json registers the server as "${x}" \u2014 plugin skills resolve mcp__${x}__* tools`,"missing-file":"No .mcp.json at the repo root yet, so there is no server key to check. Run: infra-kit setup --skip-tools",unparseable:"Could not read mcpServers from .mcp.json \u2014 fix the JSON and re-run",absent:`.mcp.json has no "${x}" server. Plugin skills name mcp__${x}__* tools and will resolve nothing without it`},Tv=new Set(["ok","missing-file"]),Cv=e=>{let r="MCP server key",t=Qt(e);return t.kind==="wrong-key"?{name:r,status:"fail",message:`.mcp.json registers the infra-kit server under "${t.key}". Rename the key to "${x}": tool names are mcp__<key>__<tool>, and every plugin skill expects the mcp__${x}__ prefix`}:{name:r,status:Tv.has(t.kind)?"pass":"fail",message:Sv[t.kind]}},qp=e=>ls(["trust"],{bin:e}),Av=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Up="ERR_TLS_CERT_ALTNAME_INVALID",Iv=async(e,r,t)=>{let o=`portless serving TLS on :${ze}`;return await e(ze,!0)?{name:o,status:"pass",message:`portless is serving HTTPS on :${ze}`}:{name:o,status:"fail",message:`No portless daemon is serving HTTPS on :${ze}. Install it once (needs root): \`${gr(r,t)}\`.`}},$v=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(ze,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(Up)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Up} 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=>Av.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 \`${qp(o)}\`, or reinstall: \`${gr(o,n)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${p.join(", ")})`}},Dv=(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: \`${qp(t)}\` (no sudo needed).`}},Ov=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 \`${ls(["alias","--remove","<name>"],{bin:t})}\`.`}},Dr="portless service target",Gn=e=>({name:Dr,status:"pass",message:`Warning \u2014 ${e}`}),_v=e=>e==="darwin"?Rc:e==="linux"?Pc:null,Nv=e=>e==="darwin"?`sudo launchctl kickstart -k system/${bc}`:`sudo systemctl restart ${Ec}`,jv="/bin/ps",Mv=e=>{try{let r=zh(jv,["-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}},Hp=e=>{try{return J.readFileSync(e,"utf-8")}catch{return null}},Fv=e=>{try{return J.statSync(e).mtime}catch{return null}},Yp=(e,r)=>({platform:e.platform??Bn.platform,readServiceFile:e.readServiceFile??Hp,readFile:e.readFile??Hp,exists:e.exists??J.existsSync,realpath:e.realpath??qr,mtime:e.mtime??Fv,execPath:e.execPath??Bn.execPath,home:e.home??zp.homedir(),cwd:e.cwd??Bn.cwd(),repoRoot:e.repoRoot??lo,stateDir:(e.stateDir??Sc)(),processStartTime:e.processStartTime??Mv,bin:r}),Lv=(e,r)=>{let t=r.readFile(U.join(e,"package.json"));try{let o=t===null?null:Z.object({version:Z.string()}).safeParse(JSON.parse(t));return o?.success===!0?o.data.version:"?"}catch{return"?"}},Wv=(e,r)=>{let t=Number.parseInt(r.readFile(U.join(r.stateDir,"proxy.pid"))?.trim()??"",10);if(!Number.isInteger(t)||t<=0)return!1;let o=r.processStartTime(t),n=r.mtime(U.join(e,"package.json"));return o!==null&&n!==null&&o.getTime()<n.getTime()},Jv=async(e,r)=>{let t=r.realpath(r.cwd);return t===r.realpath(r.home)?!1:Qo(await r.repoRoot()??t,e,r.realpath)},xt=e=>({state:"drifted",row:e}),Vv=async(e,r,t)=>{let o=gr(t.bin,t);if(!t.exists(e))return xt({name:Dr,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded). Re-run: \`${o}\``});let n=U.join(ds(t.home),"dist","cli.js");if(r!==n)return xt(Gn(`The service points at \`${r}\`, a version-specific location. Re-run once to switch it to the stable link: \`${o}\``));if(rn(t.home,t.exists)===null)return xt({name:Dr,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(ds(t.home));if(await Jv(s,t))return xt({name:Dr,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 xt(Gn(`The service runs \`${e}\`; infra-kit runs \`${t.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${o}\``));let i=Lv(s,t);return Wv(s,t)?{state:"converged",row:Gn(`The running daemon predates portless ${i} that \`dev\` will talk to. Restart it: \`${Nv(t.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Dr,status:"pass",message:`service runs \`${e}\` + stable link \u2192 portless ${i}`}}},Zp=async e=>{let r=_v(e.platform);if(r===null)return{state:"absent",row:{name:Dr,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:Dr,status:"pass",message:`Skipped \u2014 the OS service is not installed (no ${r})`}};let[o,n]=Vl(e.platform,t)??[];return o===void 0||n===void 0?xt(Gn(`could not parse ${r} \u2014 re-run \`${gr(e.bin,e)}\` to rewrite it.`)):Vv(o,n,e)},Xp=async(e,r)=>(await Zp(Yp(e,r))).state,Bv=async(e={})=>{let r=e.resolveBin??wc,t=e.isProxyServing??xc,o=e.handshake??Ac,n=e.caTrusted??Cc,s=e.routes??ps,i=e.isListening??Mt,a=(e.caPath??Tc)(),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=Yp(e,c),u=s(),m=await Iv(t,c,d),v=m.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await $v(o,u,a,c,d);return[p,(await Zp(d)).row,m,v,Dv(n(),a,c),await Ov(u,i,c)]},Gv=async(e={})=>{let r="portless routes",t=e.routes??ps,o=e.isListening??Mt,n=e.devSessionRunning??Ml,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}=jl(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??Ic().removeAlias;for(let d of a)await p(d);return{name:r,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Qp=async(e={})=>{let r=await ev(),t=Yh(e.probeDeps??mo()),o=async(u,m)=>{let[v,g]=await Promise.all([m,t]),w=g.get(u);return w===void 0?v:{...v,detail:w}},n=await Promise.all([o("brew",Le("brew installed",ve("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),o("gh",Le("gh installed",ve("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),Le("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),o("doppler",Le("doppler installed",ve("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),o("aws",Le("aws installed",ve("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")),Le("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),Le("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"),Le("terminal installed",["cmux","--version"],"Installed: cmux","cmux is not installed. Install from: https://cmux.com/"),Promise.resolve(Zh()),Xh(),Qh(),Promise.resolve(rv(r)),lv(),sv(r),av(r),pv(e.fix??!1),uv(),mv(),hv(r)]),s=await Bv();if(e.fix){let u=await Gv(),m=s.findIndex(v=>v.name===u.name);m>=0?s[m]=u:s.push(u)}let i=await bv(),a=await lo(),c=[await Ev(),...xv(i),...a===null?[]:[Cv(a)]],p=[...n,...s,...await wv(),...c],d={checks:p.map(u=>({name:u.name,status:u.status,message:u.message,fixable:ii.has(u.name),detail:u.detail})),allPassed:p.every(u=>u.status==="pass"),cliVersion:ae.version};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},Ki=k({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:Z.array(Z.object({name:Z.string().describe("Name of the check"),status:Z.enum(["pass","fail"]).describe("Check result"),message:Z.string().describe("Details about the check result"),fixable:Z.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Z.object({manager:Z.string().describe("Which package manager owns this install, read from its resolved path"),version:Z.string().nullable().describe("The version the tool reported, or null"),present:Z.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Z.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:Z.boolean().describe("Whether all checks passed"),cliVersion:Z.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Qp()});import Ui from"node:fs";import ed from"node:path";import{z as St}from"zod";var Kv=async e=>{let r="";try{r=await R()}catch{return}let t=je(r);t&&mi(t,e)},Uv=e=>[...e.map(r=>`unset ${r}`),`unset ${Yo}`,`unset ${Gr}`,`unset ${Kr}`,`unset ${Zo}`,`unset ${Ur}`,`unset ${ur}`,`export ${Hr}='1'`],rd=async({purge:e=!1}={})=>{let r=zr(),t=ed.join(r,se),o=Ui.existsSync(t);if(!o&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await Kv(e);let n=o?Xo(t):[],s=Uv(n),i=ed.resolve(r,qo);Ui.mkdirSync(r,{recursive:!0,mode:448}),fr(i,`${s.join(`
390
- `)}
391
- `,384),o&&Ui.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}},Hi=k({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit setup` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:St.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:St.string().describe("Path to the file that must be sourced to apply"),variableCount:St.number().describe("Number of variables cleared"),unsetStatements:St.array(St.string()).describe("Unset statements generated"),purged:St.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>rd()});import Hv from"node:process";import{z as or}from"zod";var zv=(e,r,t)=>e.map(({env:o,source:n})=>({env:o,source:n,hasToken:!!(t||r[o])})),td=["Environment","Source","Token"],qv=e=>{let r=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),t=td.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(td),n,...r.map(o)]},nd=async()=>{let e=await Pr(),r=await Cn(),t=await ce(),o=Hv.env[Y],n=zv(r,t?.envs??{},o);if(l.info(`Doppler project: ${e}
392
- `),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."),od({project:e,envs:n});for(let s of qv(n))l.info(s);return od({project:e,envs:n})},od=({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}},zi=k({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:or.string().describe("Detected Doppler project name"),configs:or.array(or.string()).describe("Every environment name known to this project"),tokens:or.array(or.object({env:or.string().describe("Environment / Doppler config name"),source:or.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:or.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:nd});import Yv from"node:path";import Or from"node:process";import{z as nr}from"zod";var sd=async()=>{l.info("Environment session status:");let e=zr(),r=Or.env[fc],t=Yv.join(e,se),o=0,n=0,s=Or.env[Gr]??null,i=Or.env[Kr]??null,a=Or.env[Ur]??null,c=Or.env[ur]==="1",p=!!Or.env[Hr];if(s){let u=Xo(t);u.length>0&&(n=u.length,o=u.filter(g=>g in Or.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})
393
- `),n>0&&o<n){let g=n-o;l.warn(` ${g} 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}
394
- `)}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}},qi=k({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session.",inputSchema:{},outputSchema:{sessionId:nr.string().describe("Current terminal session ID"),sessionLoadedCount:nr.number().describe("Number of cached vars active in the current session"),sessionTotalCount:nr.number().describe("Total number of cached var names"),sessionConfig:nr.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:nr.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:nr.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:nr.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:nr.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:sd});import Zv from"node:process";import{z as sr}from"zod";var id="****",Yi=e=>typeof e!="string"||e.length<8?id:`${id}${e.slice(-4)}`;var ad=(e,r,t)=>e.map(o=>{let n=t||r[o];return n?{env:o,source:t?`env:${Y}`:"store",redactedToken:Yi(n),present:!0}:{env:o,source:"-",redactedToken:"-",present:!1}}),Xv=["ENV","SOURCE","TOKEN","PRESENT"],cd=(e,r)=>{let t=[...Xv,...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())},ld=async({check:e}={})=>{let r=await xr(),t=await ce(),o=Zv.env[Y],n=ad(r,t?.envs??{},o);if(e){let a=await Pr();for(let c of n){if(!c.present)continue;let p=o||t.envs[c.env],d=await so({childEnv:ht(p),project:a,config:c.env});c.status=d.outcome}}for(let a of cd(n,!!e))l.info(a);let s=n.filter(a=>!a.present);s.length>0&&l.info(`
395
- 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}},Zi=k({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:sr.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:sr.array(sr.object({env:sr.string().describe("Environment / Doppler config name"),source:sr.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:sr.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:sr.boolean().describe("Whether a token is configured for this environment"),status:sr.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ld});import{z as S}from"zod";import{$ as hy}from"zx";import{$ as k$}from"zx";import{$ as Ct}from"zx";import{$ as pd}from"zx";var Xi=async e=>{let{operation:r}=e;try{await pd({quiet:!0})`git rev-parse --git-dir`}catch(t){throw new f(t,{operation:r,remediation:"run this from inside a git repository"})}try{await pd({quiet:!0})`git remote get-url origin`}catch(t){throw new f(t,{operation:r,remediation:"this repository has no `origin` remote to fetch from or push to"})}},ey=4,Tt=async e=>{let{operation:r}=e,t=await jc();if(t.length===0)return;l.error(`working tree has uncommitted changes:
396
- ${t.join(`
397
- `)}`);let o=t.slice(0,ey),n=t.length-o.length,s=n>0?`${o.join(", ")} (+${n} more)`:o.join(", ");throw new f(void 0,{operation:r,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},bo=async e=>{let{operation:r,base:t}=e;if(await Yr()===t)return;let o=(await Ue(await R())).find(n=>n.branch===t);if(o)throw new f(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}`})},te=async e=>{let{operation:r}=e;if(await Fc())throw new f(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 Tt({operation:r})};import{$ as dd}from"zx";var ud="dev",ir=e=>e==="hotfix"?"main":"dev",Ro=(e,r)=>(r??"").trim()!==""?`${e}
398
-
399
- ${r}`:`${e}
400
- `,Qi=async(e="regular")=>{let r=ir(e),t=dd({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 dd({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 f(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()},ry=async e=>{let{versionName:r,jiraConfig:t,description:o}=e,n=await Me(r,t);if(!n)return(await Oi({name:r,projectId:t.projectId,description:o||"",released:!1,archived:!1},t)).version;if(n.released||n.archived)throw new f(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 Rt({versionId:n.id,description:s},t),{...n,description:s}):n},ea=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular",baseSha:s}=e,i=z(r),a=await ry({versionName:i,jiraConfig:t,description:o}),c=rr(t,a),p=await Kn({id:r,jiraVersionUrl:c,type:n,description:o,baseSha:s});return{version:L(r),type:n,branchName:p.branchName,prUrl:p.prUrl,jiraVersionUrl:c}},B=async()=>{let e=new Map,r=await Fe();if(!r)return e;try{let t=await bt(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},Po=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},_=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",md=e=>e.flatMap(r=>{let t=j(r);return t?[{branch:r,id:t,label:L(t)}]:[]}),We=e=>{try{return ke(me(e))}catch(r){throw new f(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},Eo=e=>{if(e===ud)return ud;let r=j(e);return r?L(r):e},_r=e=>e.flatMap(r=>{let t=j(r);return t?[L(t)]:[]}),ty=(e,r)=>r?r.get(e)||"regular":void 0,X=e=>{let{branches:r,descriptions:t,types:o}=e;return md(r).map(({branch:n,id:s,label:i})=>({value:n,label:i,description:t.get(z(s)),type:ty(n,o)}))};var oy=e=>e.map(r=>({pr:r,id:j(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>Nc(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),xo=200,fd=(e,r)=>{e.length<xo||l.warn({source:r,limit:xo},`\u26A0\uFE0F ${r} returned ${xo} PRs \u2014 the page is full, so older release PRs may be missing`)},ny=async()=>{let e=await Ct`gh pr list --limit ${xo} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await Ct`gh pr list --limit ${xo} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=JSON.parse(e.stdout),o=JSON.parse(r.stdout);fd(t,"release PR discovery (base dev)"),fd(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))},gd=async()=>{try{let e=await ny();if(e.length===0)throw new f(void 0,{operation:"find open release PRs",remediation:"open a release PR first, or check you are in the right repo"});return oy(e)}catch(e){throw e instanceof f?e:(l.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Un=async()=>(await gd()).map(r=>r.headRefName),D=async()=>(await gd()).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt})),Hn=async e=>{let{branch:r,body:t}=e;try{await Ct({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}},sy=async(e,r)=>{let t=Ct({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`)},Kn=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n,baseSha:s}=e,i=_c(r,o),a=ir(o),c=Ct({quiet:!0}),p=ke(r),d=Ro(t,n);try{await Tt({operation:`create release branch ${p}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new f(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 sy(p,a),m}}catch(u){throw l.error({error:u,branchName:p},`Error creating release branch ${p}`),u}finally{await Ct({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as iy}from"zx";var Nr=async e=>{let r=await iy`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null};import ly from"node:process";var So=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};import ay from"node:process";var At={enabled:!1},cy=(e,r=t=>{ay.stdout.write(t)})=>(At.enabled&&e&&e.structuredContent!=null&&r(`${JSON.stringify(e.structuredContent,null,2)}
401
- `),e),hd=e=>{e.options.some(t=>t.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(hd)};var vd=()=>{if(V()||!ly.stdin.isTTY||At.enabled)throw new f(void 0,{operation:"interactive branch selection",remediation:"pass the branch selection explicitly (CLI: `--version`/`--versions`/`--all`; MCP: the `version`/`versions`/`all` fields) for non-interactive, --json, or MCP runs"})},ar=async e=>{vd();let{runBranchPicker:r}=await import("./boot-BL4EQMZV.js"),t=await r(e);if(t===null)throw new So;return t},It=async(e,r)=>{vd();let{runBranchMultiPicker:t}=await import("./boot-BL4EQMZV.js"),o=await t(e,r);if(o===null)throw new So;return o};import{$ as jr}from"zx";var py="Merge remote-tracking branch 'origin/dev' into ",yd=e=>String(e.stderr??e.message??e).trim(),dy=async e=>{try{return(await jr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
402
- `).map(t=>t.trim()).filter(t=>t.length>0)}catch{return[]}},uy=async(e,r)=>{let t=yd(r),o=await dy(e);return o.length>0?{status:"conflict",conflictPaths:o,reason:t}:await Jc(e)?{status:"hook-failed",reason:t}:{status:"error",reason:t}},kd=async e=>{let{cwd:r,worktreePath:t,branches:o}=e,n=[],s=await Ft(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 my({cwd:r,worktreePath:t,branch:i,devSha:s});n.push({...c,durationMs:Date.now()-a})}return n},my=async e=>{let{cwd:r,worktreePath:t,branch:o,devSha:n}=e,s=`origin/${o}`;if(!await Ft(r,s))return{branch:o,status:"error",reason:`${s} does not exist on origin`};if(await ms(r,"origin/dev",s))return{branch:o,status:"up-to-date"};try{await fs(t),await jr({cwd:t,quiet:!0})`git checkout --detach ${s}`;let i=`${py}${o}`;await jr({cwd:t,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await jr({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 uy(t,i)}}finally{await gs(t)}},wd=e=>e.flatMap(r=>r.mergeSha?[{branch:r.branch,sha:r.mergeSha}]:[]),bd="pnpm install --frozen-lockfile",Rd=async e=>{let{worktreePath:r,refs:t,command:o}=e,n=[],s=new Map;for(let i of t)try{await fs(r),await jr({cwd:r,quiet:!0})`git checkout --detach ${i.sha}`,await jr({cwd:r,quiet:!0})`sh -c ${o}`,n.push(i)}catch(a){s.set(i.branch,yd(a))}finally{await gs(r)}return{kept:n,failed:s}},ra=async(e,r)=>{await jr({cwd:e,quiet:!0})`git fetch origin --prune`;let t=[],o=[];for(let n of r)await ms(e,"origin/dev",`origin/${n.branch}`)?o.push(n.branch):t.push(n);return{kept:t,nowUpToDate:o}};import ta from"node:process";var zn=new Set,Pd=e=>(zn.add(e),()=>{zn.delete(e)}),fy=async()=>{for(let e of[...zn])try{await e()}catch(r){l.warn({error:r,msg:"cleanup failed during shutdown"})}zn.clear()},gy=["SIGINT","SIGTERM"],kD=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 gy){let a=()=>{fy().then(()=>{n(Yc(i))})};s.set(i,a),t(i,a)}try{return await e()}finally{for(let[i,a]of s)o(i,a)}};var vy=e=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[]}),xd=e=>({content:y(JSON.stringify(e,null,2)),structuredContent:e}),Ed=new Set(["up-to-date","fast-forward","merged"]),yy=(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=ke(me(s))}catch(a){throw new f(a,{operation:`resolve release selector "${s}"`,remediation:`pass one of: ${r.join(", ")}`})}if(!o.has(i))throw new f(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))},ky={"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"},Sd=e=>{let r=ky[e.status];if(e.status==="conflict"){let t=e.conflictPaths?.length??0;return`${r}: ${t} file(s)`}return e.reason?`${r}: ${e.reason}`:r},wy=e=>{l.info(`
403
- \u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${Sd(r)}`)},by=(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`},Ry=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?[[z(a),Sd(i)]]:[]}));return It(X({branches:t,descriptions:s}),{required:!0})},Py=async e=>{let{cwd:r,worktreePath:t,entries:o,selected:n,verify:s}=e,i=o.filter(g=>n.includes(g.branch)),a=g=>{for(let w of g)l.info(`\u2139\uFE0F ${w} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await ra(r,wd(i));a(c.nowUpToDate);let p=c.kept,d=new Map;if(s&&p.length>0){l.info(`
404
- \u{1F50E} Verifying ${p.length} merge(s) with: ${s}`);let g=await Rd({worktreePath:t,refs:p,command:s});d=g.failed;for(let[T,F]of g.failed)l.info(`\u2717 ${T} failed verification \u2014 not pushing it. ${F.split(`
405
- `)[0]??""}`);let w=await ra(r,g.kept);a(w.nowUpToDate),p=w.kept}if(p.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};l.info(`
406
- \u2B06\uFE0F Pushing atomically: ${p.map(g=>g.branch).join(", ")}`);let u=await Wc(r,p);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let v=(await Promise.all(p.map(async g=>({branch:g.branch,landed:await an(r,g.branch)===g.sha})))).filter(g=>g.landed);return v.length>0&&l.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${v.map(g=>g.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
407
- `)[0],observedLanded:v.map(g=>g.branch)}},Td=async e=>{let{all:r,versions:t,dryRun:o=!1,verify:n,confirmedCommand:s}=e,i=n===!0?bd:n||void 0;await Xi({operation:"merge dev into release branches"});let c=(await D()).filter(P=>_(P.title)==="regular").map(P=>P.branch);if(c.length===0)return l.info("\u2139\uFE0F No open release branches found"),h.print(),xd(vy(o));let p=await He();try{await hy({cwd:p,quiet:!0})`git fetch origin --prune`}catch(P){throw new f(P,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let d=t===void 0?c:yy(t,c),u=await Vc({cwd:p},async P=>{let Ce=Pd(P.remove);try{return await Ey({cwd:p,worktree:P,toPlan:d,candidates:c,all:r,versions:t,dryRun:o,verify:i,confirmedCommand:s})}finally{Ce()}}),{entries:m,selected:v,pushed:g,pushAborted:w,abortedBy:T,declined:F,verifyFailed:O}=u,C=await Ue(p).catch(()=>[]);return xy({entries:m,selected:v,pushed:g,pushAborted:w,abortedBy:T,declined:F,verifyFailed:O,dryRun:o,worktrees:C})},Ey=async e=>{let{cwd:r,worktree:t,toPlan:o,candidates:n,all:s,versions:i,dryRun:a,verify:c,confirmedCommand:p}=e,d=await kd({cwd:r,worktreePath:t.path,branches:o}),u={entries:d,pushed:!1,pushAborted:!1,declined:!1};if(wy(d),a)return{...u,selected:o};let m=await Ry({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(g=>m.includes(g.branch)&&g.mergeSha).length;v>0&&l.info(`
408
- \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 G(p,`Are you sure you want to merge dev into these branches: ${m.join(", ")}?`,{throwOnDecline:!0})}catch(g){if(!ln(g))throw g;return{...u,selected:m,declined:!0}}return p||h.addOption("--yes",!0),{entries:d,selected:m,declined:!1,...await Py({cwd:r,worktreePath:t.path,entries:d,selected:m,verify:c})}},xy=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(g=>t.includes(g.branch)&&g.mergeSha&&!p?.has(g.branch)).map(g=>g.branch):[]),u=r.filter(g=>t.includes(g.branch)).map(g=>{let w=!!g.mergeSha,T=e.verifyFailed?.get(g.branch),F=n&&w?"push-aborted":g.status,O=T?"verify-failed":F;return{branch:g.branch,status:O,mergeSha:g.mergeSha,conflictPaths:g.conflictPaths,pushed:d.has(g.branch),reason:T??g.reason}}),m=u.filter(g=>!Ed.has(g.status));for(let g of u){let w=r.find(T=>T.branch===g.branch);l.info({branch:g.branch,status:g.status,mergeSha:g.mergeSha,conflictCount:g.conflictPaths?.length??0,durationMs:w?.durationMs,pushed:g.pushed,msg:"merge-dev branch result"})}if(i||a)l.info(i?`
409
- Operation cancelled \u2014 nothing was pushed.
410
- `:`
411
- \u{1F50D} Dry run \u2014 nothing was pushed.
412
- `);else if(m.length>0){l.info(`
413
- \u26A0\uFE0F ${m.length} branch(es) did not merge.
414
- `);for(let g of m)l.info(`# ${g.branch} \u2014 ${g.status}
415
- ${by(g.branch,c)}
416
- `)}else l.info(`\u2705 All merges completed successfully!
417
- `);h.print();let v=a||i;return xd({successfulMerges:v?0:u.filter(g=>Ed.has(g.status)).length,failedMerges:v?0:m.length,failedBranches:v?[]:m.map(g=>g.branch),totalBranches:u.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:n,abortedBy:s},results:u.map(g=>v?{...g,pushed:!1}:g)})},oa=k({name:"gh-merge-dev",description:"Merge origin/dev into open regular (non-hotfix) release branches and push them in one atomic push. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all: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:Td});import{z as Io}from"zod";import{$ as ue}from"zx";var Cd=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},cr=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=Cd(r.stderr,500);n&&(t.stderr=n);let s=Cd(r.stdout,200);return s&&(t.stdout=s),t};var To=e=>{let{removed:r,failed:t}=e;if(r.length>0){l.info("\u274C Removed worktrees:");for(let 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 Co=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};if(V())return{content:n,structuredContent:o,isError:!0};let s=r.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ");throw new f(void 0,{operation:t,remediation:`not removed: ${o.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:s})};import Yn from"node:fs/promises";import{$ as Dd}from"zx";var Sy=new Set([".omc",".DS_Store"]),Ty=new Set(["state","sessions"]),Cy=2e3,Ay="check 'git worktree list' for the path; uncommitted changes block removal",Iy=e=>new Promise(r=>{setTimeout(r,e)}),na=e=>typeof e=="object"&&e!==null?e.code:void 0,Ad=e=>{let r=e.length;for(;r>1&&e[r-1]==="/";)r-=1;return e.slice(0,r)},Id=async e=>{try{return Ad(await Yn.realpath(e))}catch{return Ad(e)}},$y=async e=>{let{projectRoot:r,worktreePath:t}=e;try{let o=await Ue(r),n=await Id(t);for(let s of o)if(await Id(s.path)===n)return!0;return!1}catch{return!0}},Dy=async e=>{let r;try{r=await Yn.readdir(e)}catch(o){return{kind:na(o)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!r.every(o=>Sy.has(o)))return{kind:"not-sweepable",entries:r};if(!r.includes(".omc"))return{kind:"sweepable",entries:r};try{return{kind:(await Yn.readdir(`${e}/.omc`)).every(s=>Ty.has(s))?"sweepable":"not-sweepable",entries:r}}catch(o){return{kind:na(o)==="ENOENT"?"sweepable":"not-sweepable",entries:r}}},$d=async e=>{try{return await Yn.rm(e,{recursive:!0,force:!0}),"removed"}catch(r){return na(r)==="ENOTEMPTY"?"busy":"failed"}},Oy=async e=>{let{worktreePath:r,sleep:t}=e,o=await $d(r);return o!=="busy"?o==="removed":(await t(Cy),await $d(r)==="removed")},qn=(e,r,t)=>{let o=new f(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}},_y=async e=>{let{branch:r,worktreePath:t,projectRoot:o,error:n,sleep:s}=e;if(await $y({projectRoot:o,worktreePath:t}))return qn(r,n,Ay);let i=await Dy(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 Oy({worktreePath:t,sleep:s})?qn(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"})},Ny=async e=>{let{branch:r,worktreeDir:t,projectRoot:o,sleep:n}=e,s=`${t}/${r}`;try{await pn(s)}catch(i){return qn(r,i,"close the cmux workspace for this worktree manually and re-run")}try{return await Dd`git worktree remove ${s}`,{branch:r,status:"removed"}}catch(i){return _y({branch:r,worktreePath:s,projectRoot:o,error:i,sleep:n})}},Mr=async e=>{let{branches:r,worktreeDir:t,projectRoot:o,pruneFolder:n=!1,sleep:s=Iy}=e,i=await Promise.all(r.map(c=>Ny({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 Dd`git worktree prune`,a};var Ao=async(e,r)=>{if(!(await ie("release")).includes(e))return[];let o=await R(),n=`${o}${Q}`,{removed:s,failed:i}=await Mr({branches:[e],worktreeDir:n,projectRoot:o});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...r,stderrExcerpt:a?.reason})}return s};var $t=async(e,r,t)=>{try{return await t()}catch(o){throw l.debug({err:cr(o)},`Failed to ${e}`),new f(o,{operation:e,remediation:r})}},jy=async e=>{let r=us(e),t=await ue`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},Od=async()=>{let e=await ue`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},My=async e=>{let r=We(e),t=await Nr(r);if(!t)throw l.error(`\u274C No PR found for branch ${r}.`),new f(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},Fy=async()=>{let e=await D(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,_(i.title)]));h.setInteractive();let o=await B(),n=await ar(X({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 f(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},Ly=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await Nr(r);if(!n)throw new f(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 f(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await $t(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await ue`gh pr merge ${r} --squash --admin --delete-branch`})},Wy=async e=>{let r=L(e),t=us(e),o=await Od();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 $t(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await ue`gh pr edit ${s} --title ${t}`})),s}await $t(`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 ue`gh pr create --base main --head dev --title ${t} --body ""`});let n=await Od();if(!n)throw new f(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},Jy=async e=>{let r=L(e);if(await jy(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Wy(e);await $t(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await ue`gh pr merge ${o} --squash --admin`})},Vy=async()=>{ue.quiet=!1,await $t("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await ue`gh workflow run deploy-all.yml --ref main -f environment=prod`}),ue.quiet=!0},By=async()=>{await $t("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 ue`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Gy=async e=>{try{await nn(e)}catch(r){l.warn({err:cr(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await sn(e)}catch(r){l.warn({err:cr(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},Ky=async e=>{let r=await Fe();if(!r){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=z(e);await _i({versionName:t},r)}catch(t){let o=yo(t)&&t.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";l.error({err:cr(t)},`Failed to deliver Jira release (non-blocking)${o}`)}},_d=async e=>{let{version:r,confirmedCommand:t}=e;await te({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await My(r):await Fy(),s=j(o);if(!s)throw new f(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=L(s);h.addOption("--version",i),l.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let a=_(n);await G(t,`Are you sure you want to deliver version ${o} to production?`),h.addOption("--yes",!0),ue.quiet=!0;let p=`${await R()}${Q}`;await Ao(o,{operation:`remove worktree for ${o} before merge`,remediation:`run manually: git worktree remove ${p}/${o} (use --force if uncommitted changes)`}),await Ly({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await Jy(s),await Vy(),await By(),await Gy(o),ue.quiet=!1,await Ky(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}},sa=k({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:Io.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") to deliver to production. Required for MCP calls.')},outputSchema:{releaseBranch:Io.string().describe("The release branch that was delivered"),version:Io.string().describe("The version that was delivered"),type:Io.enum(["regular","hotfix"]).describe("Release type"),success:Io.boolean().describe("Whether the delivery was successful")},handler:_d});import{z as Je}from"zod";import{$ as ma}from"zx";import{z as Oo}from"zod";import Nd from"node:fs/promises";import ia from"node:path";var jd=".github/workflows",Uy=/script_name:\s*(?<service>[a-z0-9-]+)/,Hy=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,zy=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,aa=async e=>{let r=ia.resolve(e,jd),t;try{t=await Nd.readdir(r)}catch{return new Map}return Md(r,t.filter(o=>o.endsWith(".yml")||o.endsWith(".yaml")))},$o=async(e,r)=>Md(ia.resolve(e,jd),[r]),Md=async(e,r)=>{let t=new Map;for(let o of r){let n;try{n=await Nd.readFile(ia.resolve(e,o),"utf-8")}catch{continue}qy(n,t)}return t},qy=(e,r)=>{for(let t of e.split(/\n(?= {2}[\w-]+:)/i)){let o=Uy.exec(t)?.groups?.service??Hy.exec(t)?.groups?.service;if(o===void 0||t.trimStart().startsWith("#"))continue;let n=[...t.matchAll(zy)].map(s=>s.groups?.env??"");n.length!==0&&r.set(o,[...new Set([...r.get(o)??[],...n])])}},ca=(e,r)=>e===null?r??null:r===void 0?e:e.filter(t=>r.includes(t));import Yy from"node:fs/promises";import Zy from"node:path";import Xy from"yaml";var Qy=".github/workflows",ek="skip_terraform_deploy",Do=async(e,r)=>{let t=Zy.resolve(e,Qy,r),o;try{o=Xy.parse(await Yy.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!==ek).map(([i])=>i)};var Fd="dev",la=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ld=(e,r)=>e[r]===void 0,Wd=(e,r)=>{let t=e[r];return typeof t=="string"&&t.length>0?t:void 0},pa=async e=>{try{return await e}catch{return[]}},rk=async()=>{let e=await D();return _r(e.map(r=>r.branch))},tk=(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},Fr=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 pa(rk());if(p.length===0)return null;let d=Wd(c,"version");return Oo.enum([...new Set([...p,Fd])]).optional().describe(`Which release to deploy from. "${Fd}" 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=Oe(await pa(Ne(r)),await _e());if(p.length===0)return null;let d=p.filter(ft),u=p.filter(v=>!ft(v)),m=Wd(c,"env");return Oo.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 pa(Do(c,r));if(p.length===0)return null;let d=await $o(c,r);return Oo.array(Oo.enum(p)).optional().describe(`Services to deploy. Environment gates declared by ${r} \u2014 ${tk(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=>la(c)?t.some(p=>Ld(c,p)):!1,buildRequestedSchema:async c=>{let p=la(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")&&Ld(p,"services")){let u=await a();if(u===null)return n("services");d.services=u}return Object.keys(d).length===0?n("fields"):Oo.object(d)},toArgs:(c,p)=>{let d={...la(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 ok from"@inquirer/select";var Dt=async(e,r)=>{if(e.length===0)throw new f(void 0,{operation:r,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return A(t=>ok({message:"\u{1F9EA} Select environment",choices:e.map(o=>({name:o,value:o}))},t),{whenHeadless:"refuse"})};import nk from"@inquirer/confirm";var _o=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;h.setInteractive();let n=await A(s=>nk({message:`Deploy ${t} \u2192 ${o} via GitHub Actions?`,default:!1},s),{whenHeadless:"refuse"});return n&&h.addOption("--yes",!0),n};import sk from"@inquirer/select";import ik from"node:process";var da=()=>!V()&&ik.stdin.isTTY===!0&&!At.enabled,ak={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},ua=async()=>A(e=>sk({message:"\u{1F680} Where should this deploy run?",choices:Ot.map(r=>({name:r,value:r,description:ak[r]}))},e),{whenHeadless:"refuse"});var Ot=["ci","local"],ck={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Jd=e=>{if(!e)throw new f(void 0,{operation:"resolve the deploy source",remediation:`pass --from with one of: ${Ot.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"});let r=Ot.find(t=>t===e);if(!r)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Ot.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return r},lk=(e,r)=>{let o=ck[e==="ci"?"local":"ci"].filter(n=>{let s=r[n];return s!==void 0&&s!==!1});if(o.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${o.join(", ")} ${o.length===1?"is":"are"} not valid with --from ${e}`})},pk=async e=>e||!da()?Jd(e):ua();var No=async e=>{if(e)return e==="dev"?"dev":We(e);h.setInteractive();let r=await D(),t=r.map(s=>s.branch),o=new Map(r.map(s=>[s.branch,_(s.title)])),n=await B();return ar([{value:"dev",label:"dev"},...X({branches:t,descriptions:n,types:o})])};var Vd="deploy-all.yml",Bd=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:n}=e,s=await No(r),i=Eo(s);h.addOption("--version",i);let a=await _e(),c=Oe(await Ne(Vd),a),p="";t?p=t:(h.setInteractive(),p=await Dt(c,"launch deploy-all workflow")),h.addOption("--env",p),Er(p,"launch deploy-all workflow",a),io({env:p,branch:s});let d=o??!1;if(d&&h.addOption("--skip-terraform",!0),!await _o({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{ma.quiet=!0,await ma`gh workflow run deploy-all.yml --ref ${s} -f environment=${p} ${d?["-f","skip_terraform_deploy=true"]:[]}`,ma.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 f(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},fa=k({name:"gh-release-deploy-all",formProvider:Fr({workflowFile:Vd,fields:["version","env"],toolName:"gh-release-deploy-all"}),description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. 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:Je.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:Je.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:Je.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Je.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Je.string().describe("The release branch that was deployed"),version:Je.string().describe("The version that was deployed"),environment:Je.string().describe("The environment deployed to"),skipTerraformDeploy:Je.boolean().describe("Whether terraform deployment was skipped"),success:Je.boolean().describe("Whether the deployment was successful")},handler:Bd});import dk from"@inquirer/checkbox";import{z as oe}from"zod";import{$ as ga}from"zx";var Lr="deploy-selected-services.yml",Gd=async e=>{let{version:r,env:t,services:o,skipTerraform:n,confirmedCommand:s}=e,i=await No(r),a=Eo(i);h.addOption("--version",a);let c=await _e(),p=Oe(await Ne(Lr),c),d="";t?d=t:(h.setInteractive(),d=await Dt(p,"launch deploy-selected workflow")),h.addOption("--env",d),Er(d,"launch deploy-selected workflow",c),io({env:d,branch:i});let u=await R(),m=await Do(u,Lr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Lr}`,stderrExcerpt:`no services found in .github/workflows/${Lr}`});let v=[];if(o&&o.length>0?v=o:(h.setInteractive(),v=await A(C=>dk({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},C),{whenHeadless:"refuse"})),h.addOption("--services",v),v.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let g=v.filter(C=>!m.includes(C));if(g.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${g.join(", ")}`});let w=await $o(u,Lr),T=v.filter(C=>{let P=w.get(C);return P!==void 0&&!P.includes(d)});if(T.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:T.map(C=>`${C} deploys only to: ${(w.get(C)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Lr} gates these services out of ${d}: ${T.join(", ")}`});let F=n??!1;F&&h.addOption("--skip-terraform",!0);let O=C=>{let P={releaseBranch:i,version:a,environment:d,services:v,skipTerraformDeploy:F,success:C};return{content:y(JSON.stringify(P,null,2)),structuredContent:P}};if(!await _o({confirmedCommand:s,branch:i,env:d}))return l.info("Deployment cancelled"),O(!1);try{ga.quiet=!0;let C=v.flatMap(Ce=>["-f",`${Ce}=true`]);return await ga`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${C} ${F?["-f","skip_terraform_deploy=true"]:[]}`,ga.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${v.join(", ")}`),h.print(),O(!0)}catch(C){throw l.error({error:C},"\u274C Error launching workflow"),new f(C,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},ha=k({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Fr({workflowFile:Lr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),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:oe.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:oe.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:oe.array(oe.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:oe.boolean().optional().describe("Skip the terraform deployment stage."),confirm:oe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:oe.string().describe("The release branch that was deployed"),version:oe.string().describe("The version that was deployed"),environment:oe.string().describe("The environment deployed to"),services:oe.array(oe.string()).describe("The services that were deployed"),skipTerraformDeploy:oe.boolean().describe("Whether terraform deployment was skipped"),success:oe.boolean().describe("Whether the deployment was successful")},handler:Gd});import{z as _t}from"zod";var Kd=async()=>{let r=(await D()).flatMap(i=>{let a=j(i.branch);return a?[{version:L(a),jiraKey:z(a),type:_(i.title)}]:[]}),t=await B(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let a=Po(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
418
- `),l.info(`
419
- ${n.join(`
420
- `)}
421
- `);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=k({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:_t.array(_t.object({version:_t.string().describe("Release version"),type:_t.enum(["regular","hotfix"]).describe("Release type"),description:_t.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:_t.number().describe("Number of release branches")},handler:Kd});import uk from"node:process";var ya=e=>({...e}),ka=e=>{let{env:r,branch:t,sha:o,isClean:n,ambient:s=uk.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}},Zn=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(`
422
- `)};import Sk from"@inquirer/checkbox";import Tk from"@inquirer/confirm";import Ck from"@inquirer/select";import{spawn as Ak}from"node:child_process";import Ik from"node:process";import{z as M}from"zod";import{$ as Mo}from"zx";import{$ as jo}from"zx";var mk=async e=>{let r=jo.quiet;jo.quiet=!0;try{let t=`/${e}/environment`,o=await jo`aws sts get-caller-identity --query Account --output text`,n=await jo`aws ssm get-parameter --name ${t} --query Parameter.Value --output text`;return{accountId:o.stdout.trim(),stage:n.stdout.trim()}}catch(t){throw new f(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{jo.quiet=r}},Ud=(e,r)=>{if(r.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${r.accountId} reports "${r.stage}" \u2014 refusing to deploy to an environment you did not name`})},Hd=e=>{let{env:r,isShared:t,isClean:o}=e;if(!(!t||o))throw new f(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"})},zd=(e,r)=>{if(r.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},wa=async e=>{let{env:r,project:t,isShared:o,isClean:n,runningEnvs:s,protectedEnvAccess:i}=e;Er(r,`deploy to "${r}"`,i),zd(r,s),Hd({env:r,isShared:o,isClean:n});let a=await mk(t);return Ud(r,a),{identity:a}};import qd from"node:fs/promises";import Xn from"node:path";var fk="devops/scripts",gk=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,hk=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,vk=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,yk=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,ba=async e=>{let r=Xn.resolve(e,fk),t;try{t=await qd.readdir(r)}catch{return[]}let o=await aa(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=Xn.resolve(r,s),c=i?.groups?.service??"",p=wk(await kk(a));return{name:c,scriptPath:a,allowedEnvs:ca(bk(p),o.get(c)),ssmPrefix:Pk(p)}}))).sort((s,i)=>s.name.localeCompare(i.name))},kk=async e=>{try{return await qd.readFile(e,"utf-8")}catch{return""}},wk=e=>e.split(`
423
- `).map((r,t)=>({line:t+1,text:r})).filter(({text:r})=>!r.trimStart().startsWith("#")),bk=e=>{let r=e.reduce((o,{text:n})=>o??hk.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},Rk=e=>{let r=e.replaceAll(/["']/g,"");return r.includes("$")&&(r.includes("/environment")||r.startsWith("$"))},Pk=e=>{for(let{line:r,text:t}of e){let o=yk.exec(t)?.groups?.prefix;if(o!==void 0)return o;let n=vk.exec(t)?.groups?.arg;if(n!==void 0&&Rk(n))return{unparseable:{line:r,text:t.trim()}}}return null},Ek=e=>{let r=new Map;for(let t of e)typeof t.ssmPrefix=="string"&&r.set(t.ssmPrefix,[...r.get(t.ssmPrefix)??[],Xn.basename(t.scriptPath)]);return r},xk=e=>{let r=e.flatMap(t=>{if(t.ssmPrefix===null||typeof t.ssmPrefix=="string")return[];let{line:o,text:n}=t.ssmPrefix.unparseable;return[`${Xn.basename(t.scriptPath)}:${o}: ${n}`]});if(r.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:r.join("; ")})},Yd=e=>{xk(e);let r=Ek(e),[t,...o]=r.keys();if(t===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(o.length>0){let n=[...r.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${r.size} different prefixes across ${e.length} deploy scripts \u2014 ${n}`})}return t},Qn=(e,r)=>e.allowedEnvs===null||e.allowedEnvs.includes(r),Ra=(e,r)=>e.filter(t=>Qn(t,r));var Ea="deploy-all.yml",Zd="/bin/sh",$k=async()=>{let e=Mo.quiet;Mo.quiet=!0;try{let r=await Mo`gh run list --workflow=${Ea} --status=in_progress --json displayTitle`;return JSON.parse(r.stdout).flatMap(o=>/\[(?<env>[a-z0-9-]+)\]/.exec(o.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Mo.quiet=e}},Dk=async(e,r)=>{let t=e.map(n=>({name:n.name,value:n.name})),o=await A(n=>Sk({message:`Deploy which services to ${r}?`,choices:t,pageSize:20},n),{whenHeadless:"unreachable"});if(o.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return o},Ok=async e=>{let{env:r,isShared:t,count:o}=e;return t?A(n=>Ck({message:`"${r}" is a SHARED environment \u2014 deploying ${o} service(s) from this machine. Continue?`,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${r}`,value:!0}]},n),{whenHeadless:"refuse"}):A(n=>Tk({message:`Deploy ${o} service(s) to ${r} from this machine?`,default:!1},n),{whenHeadless:"refuse"})},_k=(e,r,t)=>new Promise((o,n)=>{let s=Ak(Zd,[e.scriptPath],{cwd:t,env:r,stdio:"inherit"});s.on("error",n),s.on("close",i=>{o(i??1)})}),Nk=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 _k(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}},jk=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 f(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&&!Qn(c,o)});if(i.length>0)throw new f(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))},Pa=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:ya(n.contract),strippedVars:n.stripped,dryRun:a,success:c};return{content:y(JSON.stringify(p,null,2)),structuredContent:p}},Mk=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(),Dk(t,n))},Xd=async(e,r)=>{let{env:t,service:o,confirmedCommand:n,dryRun:s,printEnv:i}=e,a=await R(),c=await ba(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let p=Yd(c),d=await _e(),u=Oe(await Ne(Ea),d),m=t??"";m||(h.setInteractive(),m=await Dt(u,"deploy locally")),h.addOption("--env",m);let v=Ra(c,m);if(v.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let g=await Mk({selection:r,eligible:v,service:o,env:m}),w=jk({names:g,services:c,env:m});if(r==="selected")for(let dr of g)h.addOption("--service",dr);let T=ft(m),F=await Yr(),O=(await Mo`git rev-parse HEAD`.quiet()).stdout.trim(),C=await Mc(),P=ka({env:m,branch:F,sha:O,isClean:C});i&&l.info(`Deploy contract for ${m}:
424
- ${Zn(P)}`);let ne=(await wa({env:m,project:p,isShared:T,isClean:C,runningEnvs:await $k(),protectedEnvAccess:d})).identity.accountId;if(s)return l.info([`Would deploy to "${m}" (AWS account ${ne}) from this machine`,`Preflight parameter: /${p}/environment`,Zn(P),"Commands:",...w.map(dr=>` ${Zd} ${dr.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
425
- `)),Pa({env:m,accountId:ne,names:g,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!n&&!await Ok({env:m,isShared:T,count:g.length}))return l.info("Deployment cancelled"),Pa({env:m,accountId:ne,names:g,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&l.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:Br,failed:pr}=await Nk({chosen:w,childEnv:P.childEnv,cwd:a,env:m});return pr.length>0&&(l.error(`Partial deploy to "${m}": succeeded [${Br.join(", ")||"none"}], failed [${pr.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Ik.exitCode=1),h.print(),Pa({env:m,accountId:ne,names:g,built:P,deployed:Br,failed:pr,dryRun:!1,success:pr.length===0})},Qd=async e=>Xd(e,"all"),eu=async e=>Xd(e,"selected"),ru='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.',tu={env:M.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:M.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:M.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},ou={environment:M.string().describe("Environment deployed to"),accountId:M.string().describe("AWS account the deploy targeted"),services:M.array(M.string()).describe("Services requested"),deployed:M.array(M.string()).describe("Services that completed successfully"),failed:M.array(M.string()).describe("Services that failed"),contract:M.record(M.string(),M.string()).describe("Build contract passed to the scripts"),strippedVars:M.array(M.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:M.boolean().describe("Whether this was a dry run"),success:M.boolean().describe("Whether every requested service deployed")},nu=e=>Fr({workflowFile:Ea,fields:["env"],toolName:e}),xa=k({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${ru}`,requiresHumanConfirm:!0,formProvider:nu("local-deploy-all"),inputSchema:tu,outputSchema:ou,handler:Qd}),Sa=k({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${ru}`,requiresHumanConfirm:!0,formProvider:nu("local-deploy-selected"),inputSchema:{...tu,service:M.array(M.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:ou,handler:eu});import Fk from"@inquirer/confirm";import Aa from"@inquirer/input";import su from"@inquirer/select";import Ta from"node:process";import{z as N}from"zod";var Lk='"1.2.5" or "next"',Wk=(e,r)=>{try{return Vn(e,r)}catch(t){if(t instanceof $r)return null;throw t}},Ca=(e,r)=>{try{return Ji(e,r)}catch(t){throw t instanceof $r?new f(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 Oc?new f(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},Jk=async(e,r)=>{let t=Wk(e,r),o=t?` [${t}]`:"",n=(await A(i=>Aa({message:` Version (e.g. ${Lk})${o}: `},i),{whenHeadless:"unreachable"})).trim(),s=n===""?t??"":n;return s===""&&(l.error("No version provided. Exiting..."),Ta.exit(1)),s},Vk=async()=>{let e=(await A(r=>Aa({message:' Name (kebab-case, e.g. "checkout-redesign"): '},r),{whenHeadless:"unreachable"})).trim();e===""&&(l.error("No name provided. Exiting..."),Ta.exit(1));try{on(e)}catch(r){let t=r instanceof Error?r.message:String(r);l.error(`${t} Exiting...`),Ta.exit(1)}return e},Bk=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=>su({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},u),{whenHeadless:"unreachable"}),c=await A(u=>su({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},u),{whenHeadless:"unreachable"}),p;if(a==="name"){let u=await Vk();p=Ca([{name:u,type:c}],[])[0]}else{let u=await Jk(await o(),c);p=Ca([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(tr(`v${p.id.raw}`))}let d=(await A(u=>Aa({message:" Description (optional, press Enter to skip): "},u),{whenHeadless:"unreachable"})).trim();n.push({...p,...d!==""?{description:d}:{}}),s=await A(u=>Fk({message:"Add another release?",default:!1},u),{whenHeadless:"unreachable"})}return n},Gk=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 ")},iu=e=>{for(let r of e)h.addOption("--release",Wi(r))},Kk=async(e,r)=>{if(e&&e.length>0){let o=Vi(e)?await r():[],n=Ca(e,o);return iu(n),n}let t=await Bk(r);return iu(t),t},Uk=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},Hk=async(e,r)=>{let t=e.map(Gk).join(`
426
- - `);await G(r,`Create the following ${e.length} release(s)?
427
- - ${t}
428
- `),h.addOption("--yes",!0)},zk=async e=>{let{entry:r,jiraConfig:t}=e,o=L(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await Tt({operation:`create release ${n}`});let s=await Qi(r.type),i=await ea({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}
429
- `),{result:i}}catch(s){let i=yo(s)?s:void 0,a=new f(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}
430
- `),{failure:{version:o,error:a.message}}}},qk=(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.`)},au=async e=>{let{releases:r,confirmedCommand:t}=e;await te({operation:"create release"});let o=await Pt(),n=null,i=await Kk(r,async()=>(n===null&&(n=await Bi()),n));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});Uk(i),await bo({operation:"create release",base:ir(i[0].type)}),await Hk(i,!!t);let a=[],c=[];for(let d of i){let{result:u,failure:m}=await zk({entry:d,jiraConfig:o});u&&a.push(u),m&&c.push(m)}qk(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}},Ia=k({name:"release-create",requiresHumanConfirm:!0,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:N.array(N.object({version:N.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:N.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:N.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:N.string().optional().describe("Optional description for the Jira version.")}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description.'),confirm:N.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:N.array(N.string()).describe("List of created release branch names"),successCount:N.number().describe("Number of releases created successfully"),failureCount:N.number().describe("Number of releases that failed"),releases:N.array(N.object({version:N.string().describe("Version number"),type:N.enum(["regular","hotfix"]).describe("Release type"),branchName:N.string().describe("Release branch name"),prUrl:N.string().describe("GitHub PR URL"),jiraVersionUrl:N.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:N.array(N.object({version:N.string().describe("Version number that failed"),error:N.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:au});import Yk from"@inquirer/input";import{z as lr}from"zod";var Zk=async()=>{let e=await D(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,_(s.title)])),o=await B(),n=await ar(X({branches:r,descriptions:o,types:t}));return{branch:n,type:t.get(n)||"regular"}},Xk=async e=>{let t=(await D()).find(o=>o.branch===e);if(!t)throw new f(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return _(t.title)},Qk=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await A(n=>Yk({message:` New description ${r} (press Enter to keep current): `},n),{whenHeadless:"unreachable"})).trim();return o===""?e:o},cu=async e=>{let{version:r,description:t,confirmedCommand:o}=e,n=await Pt(),s;r?(s=We(r),await Xk(s)):(h.setInteractive(),s=(await Zk()).branch);let i=j(s);if(!i)throw new f(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=L(i);h.addOption("--version",a);let c=z(i),p=await Me(c,n);if(!p)throw new f(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 Qk(d));let m=w=>{let T={version:a,branch:s,jiraVersionUrl:rr(n,p),previousDescription:d,newDescription:u,changed:w};return{content:y(JSON.stringify(T,null,2)),structuredContent:T}};if(u===d)return l.info(`No change \u2014 description for ${c} is already: "${d}"`),h.print(),m(!1);await G(o,`Update description for ${c}?
431
- from: "${d}"
432
- to: "${u}"
433
- `),h.addOption("--yes",!0),await Rt({versionId:p.id,description:u},n);let v=rr(n,p),g=Ro(v,u);return await Hn({branch:s,body:g}),l.info(`\u2705 Updated description for ${c}`),l.info(`\u{1F517} Jira Version: ${v}`),l.info(`\u{1F517} PR branch: ${s}
434
- `),h.print(),m(!0)},$a=k({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:lr.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:lr.string().describe("New description. Empty string clears the description.")},outputSchema:{version:lr.string().describe("Release version"),branch:lr.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:lr.string().describe("Jira fix version URL"),previousDescription:lr.string().describe("The description before the update"),newDescription:lr.string().describe("The description after the update"),changed:lr.boolean().describe("Whether the description actually changed")},handler:cu});import{z as I}from"zod";import{$ as Wa}from"zx";import lu from"node:fs/promises";import es from"node:path";var Fo=async e=>{let{workspacePath:r,folderPaths:t}=e,o=es.dirname(r),n;try{n=await lu.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=>es.resolve(o,d.path))),c=[],p=[];for(let d of t){let u=es.resolve(d);if(a.has(u)){p.push(d);continue}let m=es.relative(o,u);i.push({path:m}),a.add(u),c.push(d)}return s.folders=i,await lu.writeFile(r,`${JSON.stringify(s,null,2)}
435
- `,"utf-8"),{added:c,skipped:p}};import{$ as ew}from"zx";var Lo=async e=>{await ew`cursor ${e}`};import rw from"node:fs/promises";import ts from"node:path";import pu from"node:fs/promises";import rs from"node:path";var Wo=async e=>{let{workspacePath:r,folderPaths:t}=e,o=rs.dirname(r),n;try{n=await pu.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=>rs.resolve(m))),c=new Set,p=i.filter(m=>{let v=rs.resolve(o,m.path);return a.has(v)?(c.add(v),!1):!0});s.folders=p,await pu.writeFile(r,`${JSON.stringify(s,null,2)}
436
- `,"utf-8");let d=[],u=[];for(let m of t){let v=rs.resolve(m);c.has(v)?d.push(m):u.push(m)}return{removed:d,notFound:u}};var Da=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=ts.dirname(r),s=ts.resolve(`${t}/release`),i=await rw.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(g=>ts.resolve(`${t}/${g}`))),d=[];for(let g of c){let w=ts.resolve(n,g.path);(w===s||w.startsWith(`${s}/`))&&!p.has(w)&&d.push(w)}let u=[];d.length>0&&(u=(await Wo({workspacePath:r,folderPaths:d})).removed);let m=o.map(g=>`${t}/${g}`),{added:v}=m.length>0?await Fo({workspacePath:r,folderPaths:m}):{added:[]};return{added:v,removed:u}};import du from"node:path";var Wr=(e,r)=>du.isAbsolute(e)?e:du.resolve(r,e);var Oa=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=Wr(n.workspaceConfigPath,r);try{let{added:i,removed:a}=await Da({workspacePath:s,worktreeDir:t,currentBranches:o});return o.length>0&&await Lo(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 tw}from"zx";var _a=async e=>{let{folderPaths:r}=e;for(let t of r)await tw`zed --add ${t}`;return{added:r}};import{$ as ow}from"zx";var Na=async e=>{let{worktreePaths:r}=e;if(r.length===0)return{ran:!1,added:0,removed:0};try{return await ow`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 nw}from"zx";var ja=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,n=[r,...o.map(s=>`${t}/${s}`)];try{return await nw`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 ye=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var Ma=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,n=await E(),s=we(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=Wr(c.config.workspaceConfigPath,r),{added:d,skipped:u}=await Fo({workspacePath:p,folderPaths:i}),m=u.length>0?` (${u.length} already present)`:"";l.info(`\u2705 Added ${d.length} folder(s) to ${p}${m}`),await Lo(p),a.push({ran:!0,provider:"cursor",added:d.length,skipped:u.length});break}case"zed":{let{added:p}=await _a({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:ye(c)}return a};var Fa=async e=>{let r=await E(),t=we(r),{projectRoot:o,worktreeDir:n,worktreePaths:s,currentBranches:i}=e,a=[];for(let c of t)switch(c.provider){case"cursor":{let p=await Oa({projectRoot:o,worktreeDir:n,currentBranches:i,cursorConfig:c.config});a.push({...p,provider:"cursor"});break}case"zed":{let p=await Na({worktreePaths:s});a.push({...p,provider:"zed"});break}default:ye(c)}return a};var La=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return ye(e)}};var Jr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:n,allowEditorRelaunch:s}=e;if(n.length===0)return[];let i=await E(),a=we(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 sw({ide:u,projectRoot:r,folderPaths:c}));break}case"zed":{d.push(await iw({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:s}));break}default:ye(u)}return d},sw=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let n=Wr(r.config.workspaceConfigPath,t);try{let{removed:s}=await Wo({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:[]}}},iw=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:n}=e;return n?(await ja({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 os=["workspace","none"];var uu=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],ss={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"},Vo="remove a release",ee=e=>{throw l.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},aw=e=>{V()&&(e.version||ee({operation:Vo,remediation:'pass "version" (a release version or name); the interactive picker needs a TTY',stderrExcerpt:'release-remove over MCP requires "version"'}),e.moveIssuesTo&&ee({operation:Vo,remediation:'remove the Jira fix version yourself \u2014 this tool returns its id, name and URL as jira: "manual"',stderrExcerpt:"moveIssuesTo is not permitted over MCP: the Jira step is never attempted here"}),e.skipJira&&ee({operation:Vo,remediation:"omit skipJira \u2014 over MCP the Jira fix version is always left in place",stderrExcerpt:"skipJira is meaningless over MCP: the Jira step is never attempted here"}))},mu=e=>{e.pr?.state==="MERGED"&&ee({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`})},cw=(e,r)=>{if(r.skipJira||(e.jiraConfig||ee({operation:`remove release ${e.label}`,remediation:V()?"set JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL in the environment the MCP server was launched with, 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)&&ee({operation:`remove Jira fix version "${t.name}"`,remediation:"un-release it in Jira first, or remove the release without it via --skip-jira",stderrExcerpt:`fix version "${t.name}" is already ${t.released?"released":"archived"}`}),!V()&&(o===0&&n===0||e.moveIssuesTo||ee({operation:`remove Jira fix version "${t.name}"`,remediation:"deleting it would clear both fields on those issues with no way to restore them \u2014 pass --move-issues-to <version> to reassign both, or clear the version from the issues in Jira first",stderrExcerpt:`${t.name} is set as fixVersion on ${o} issue(s) and as affectsVersion on ${n} issue(s)`}))},lw=e=>{e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira||ee({operation:`remove release ${e.label}`,remediation:`nothing named "${e.label}" exists to remove \u2014 check the spelling against \`infra-kit release list\`. (A release this command already removed keeps a CLOSED PR, so a genuine re-run is not affected.)`,stderrExcerpt:"found no worktree, no PR (any state), no local or remote branch, and no Jira fix version"})},pw=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||ee({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(", ")}`})},dw=async e=>(await Wa`git -C ${e} status --porcelain`).stdout.split(`
437
- `).map(t=>t.trimEnd()).filter(t=>t.length>0),uw=async e=>(await qe()).has(await vr(e)),mw=async(e,r)=>{let t={jiraConfig:null,jira:null,moveIssuesTo:null};if(r.skipJira)return t;let o=await Fe();if(!o)return t;let n=await Me(z(e),o),s=r.moveIssuesTo?await fw(r.moveIssuesTo,o):null;if(!n)return{jiraConfig:o,jira:null,moveIssuesTo:s};let i=await Jn(n.id,o);return{jiraConfig:o,moveIssuesTo:s,jira:{version:n,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:rr(o,n)}}},fw=async(e,r)=>{let t=await Me(e,r);return t||ee({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}"`})},gw=async(e,r)=>{let t=j(e);t||ee({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}${Q}`,s=`${n}/${e}`,[i,a,c,p]=await Promise.all([ie("release"),Nr(e),Ft(o,`refs/heads/${e}`),an(o,e)]),d=i.includes(e);return{...await mw(t,r),branch:e,id:t,label:L(t),baseBranch:ir(_(a?.title??"")),projectRoot:o,worktreeDir:n,worktreePath:s,currentWorktrees:i,worktreePresent:d,cmuxWorkspacePresent:d?await uw(s):!1,worktreeDirty:d?await dw(s):null,localTipSha:c,remoteTipSha:p,pr:a}},hw=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}),vw=(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}`},yw=(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: ${vw(e,r)}`];return e.cmuxWorkspacePresent&&o.push(` \u2022 the cmux window rooted at ${e.worktreePath} will close`),o.join(`
438
- `)},ns=class extends Error{constructor(t,o){super(`step ${t} failed`,{cause:o});this.step=t;this.reason=o;this.name="StepFailure"}step;reason},kw=e=>typeof e=="string"?e:e.outcome;async function Jo(e,r,t){try{let o=await t(),n=kw(o);return r.push({step:e}),l.info({step:e,outcome:n},`\u2705 ${ss[e]} \u2014 ${n}`),o}catch(o){throw new ns(e,o)}}var ww=async(e,r,t)=>{try{await t(),r.push({step:e})}catch(o){r.push({step:e,detail:"attempted"}),l.warn({err:cr(o),step:e},`\u26A0\uFE0F ${ss[e]} failed (non-blocking)`)}},bw=(e,r)=>r.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:r.detail?`${r.step} (${r.detail})`:r.step,Rw=e=>{let{plan:r,step:t,done:o,cause:n}=e,s=o.map(d=>bw(r,d)).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=`completed: ${s}. ${i}${a}Re-run \`infra-kit release remove --version ${r.label}\` to finish; completed steps are skipped.`,p=n instanceof f?n.remediation:void 0;return new f(n,{operation:`remove release ${r.label} \u2014 step ${uu.indexOf(t)+1} of ${uu.length} (${ss[t]})`,remediation:p?`${p} \u2014 ${c}`:c})},Pw=async e=>{let r=await Ao(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}},Ew=e=>{let r=e.map(s=>({provider:s.provider,outcome:xw(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}},xw=e=>e.provider==="zed"?"skipped":e.removed.length>0?"verified":"attempted",Sw=async(e,r,t)=>{let o={outcome:"attempted",providers:[]};return await ww("ide-folders",t,async()=>{let n=await Jr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,currentWorktrees:e.currentWorktrees,removedWorktrees:r,allowEditorRelaunch:!1});o=Ew(n)}),l.info({outcome:o.outcome,step:"ide-folders"},`\u2705 ${ss["ide-folders"]} \u2014 ${o.outcome}`),o},Tw=async e=>{let r=await Nr(e.branch);if(mu({...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 Wa`gh pr close ${String(r.number)} --comment ${t}`,{outcome:"closed",number:r.number}},Cw=async e=>(await Yr()===e.branch&&await Wa`git switch ${e.baseBranch}`,await nn(e.branch),await Lc(e.branch)?ee({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"),Aw=async e=>(await sn(e.branch),e.remoteTipSha?"deleted":"absent"),Iw=async(e,r,t)=>{let o=await Jn(r.version.id,t);o.issuesFixedCount===r.fixCount&&o.issuesAffectedCount===r.affectsCount||ee({operation:`remove Jira fix version "${r.version.name}"`,remediation:`the fix version was NOT removed and every other step is complete \u2014 re-run \`infra-kit release remove --version ${e.label}\` 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}`})},$w=async(e,r)=>r.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":V()?(l.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name,url:e.jira.url},"\u2139\uFE0F Jira fix version left in place for a human to remove"),"manual"):(await Iw(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 Ni({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),Dw=(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}),Ow=async(e,r,t)=>{let o=await Jo("worktree",t,()=>Pw(e)),n=await Sw(e,o.removedBranches,t),s=await Jo("pr",t,()=>Tw(e));l.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Jo("local-branch",t,()=>Cw(e)),a=await Jo("remote-branch",t,()=>Aw(e)),c=await Jo("jira",t,()=>$w(e,r));return{worktree:o,ideFolders:n,pr:s,localBranch:i,remoteBranch:a,jira:c}},_w=async(e,r)=>{let t=[];try{return Dw(e,await Ow(e,r,t))}catch(o){throw o instanceof ns?Rw({plan:e,step:o.step,done:t,cause:o.reason}):o}},Nw=async e=>{if(e)return We(e);h.setInteractive();let[r,t]=await Promise.all([B(),D()]),o=t.map(s=>s.branch);o.length===0&&ee({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,_(s.title)]));try{return await ar(X({branches:o,descriptions:r,types:n}))}catch(s){throw Ae(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},fu=async e=>{let{confirmedCommand:r,version:t,moveIssuesTo:o,skipJira:n}=e;await te({operation:Vo}),await E(),aw(e);try{let s=await gw(await Nw(t),e);l.debug({plan:hw(s)},"release remove: resolved plan"),mu(s),cw(s,e),lw(s),await bo({operation:`remove release ${s.label}`,base:s.baseBranch}),pw(s),h.addOption("--version",s.label),o&&h.addOption("--move-issues-to",o),n&&h.addOption("--skip-jira",!0),await G(r,yw(s,!!n),{throwOnDecline:!0}),r||h.addOption("--yes",!0);let i=await _w(s,e);return h.print(),{content:y(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Ae(s)||ln(s)||s instanceof f?s:(l.error({err:cr(s)},"\u274C Error removing release"),new f(s,{operation:Vo,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Ja=k({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, and deletes the release branch locally and on origin. THE JIRA FIX VERSION IS DELIBERATELY LEFT IN PLACE \u2014 removing it is irreversible (new id, new URL, lost issue links), so this tool never attempts it and instead returns jira: "manual" with the version id, name and URL for a human to finish in Jira. Requires "version"; the moveIssuesTo/skipJira flags are CLI-only and are refused here because the Jira step does not run. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived or still carries issues, or when nothing named that version exists. 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,inputSchema:{version:I.string().describe('The release version or name to remove (e.g. "1.2.5" or "checkout-redesign"). Required: the interactive picker is unavailable without a TTY.'),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","manual"]).describe('Always "manual" over MCP: the fix version is left for a human. "absent" means none was found.'),jiraVersion:I.object({id:I.string(),name:I.string(),url:I.string()}).nullable().describe('The fix version this release owns \u2014 the link a human needs when jira is "manual"')},handler:fu});import{execFile as Ww}from"node:child_process";import hu from"node:path";import vu from"node:process";import{z as H}from"zod";import Va from"node:fs/promises";import Bo from"node:path";var gu=async e=>{try{return await Va.access(e),!0}catch{return!1}},jw=async e=>{if(e&&e.length>0)return e;try{let r=await He();return[Bo.dirname(r)]}catch(r){throw new f(r,{operation:"discover infra-kit projects",remediation:"run inside an infra-kit repo, or pass --root <dir>"})}},Mw=e=>e.isDirectory()||e.isSymbolicLink(),Fw=async(e,r)=>{if(!Mw(r))return null;let t=Bo.join(e,r.name),[o,n]=await Promise.all([gu(Bo.join(t,".git")),gu(Bo.join(t,"infra-kit.json"))]);if(!o||!n)return null;try{let s=await Va.realpath(t);return{name:Bo.basename(t),repoRoot:s}}catch{return null}},Lw=async e=>{try{return await Va.readdir(e,{withFileTypes:!0})}catch{return[]}},Ba=async(e={})=>{let r=await jw(e.roots),t=new Map;for(let o of r){let n=await Lw(o);for(let s of n){let i=await Fw(o,s);i&&!t.has(i.repoRoot)&&t.set(i.repoRoot,i)}}return[...t.values()].sort((o,n)=>o.name.localeCompare(n.name))};var Jw=async(e={})=>e.all?qw(e):yu(e),yu=async(e={})=>{let{releaseOnly:r=!1,force:t=!1,dryRun:o=!1}=e;await E();try{let n=await R(),s=`${n}${Q}`,i=hu.basename(await He(n)),a=await Ue(n),c=Vw(a,r),p=c.map(w=>w.path),d=c.map(w=>w.branch).filter(w=>hr(w)),u=c.map(w=>({title:mn({branch:w.branch??hu.basename(w.path)}),cwd:w.path}));if(o){let w=await Uw({repo:i,releaseOnly:r,force:t,worktreePaths:p,targets:u});return Hw(w,s),h.print(),{content:y(JSON.stringify(w,null,2)),structuredContent:w}}let[m,v]=await Promise.all([Fa({projectRoot:n,worktreeDir:s,worktreePaths:p,currentBranches:d}),Bw({targets:u,force:t,repoName:i})]),g={repo:i,dryRun:!1,releaseOnly:r,worktreePaths:p,ideProviders:m.filter(w=>w.ran).map(w=>w.provider),cmuxOpened:v.opened,cmuxSkipped:v.skipped,cmuxClosed:v.closed};return zw(g,{ideRan:m.some(w=>w.ran)}),h.print(),{content:y(JSON.stringify(g,null,2)),structuredContent:g}}catch(n){throw n instanceof f?n:(l.debug({err:n},"Error reopening worktree windows"),new f(n,{operation:"reopen worktrees",remediation:"run `infra-kit doctor` to check this project's setup"}))}},Vw=(e,r)=>e.filter(t=>t.bare||t.prunable?!1:r?hr(t.branch):!0),Bw=async e=>{let{targets:r,force:t,repoName:o}=e,n=await dn(o),s=t?await Gw({targets:r}):[],{opened:i,skipped:a}=await Kw({targets:r,force:t,repoName:o,groupRef:n});return{opened:i,skipped:a,closed:s}},Gw=async e=>{let{targets:r}=e;if(r.length===0)return[];let t=await qe(),o=[];for(let n of r)t.has(await vr(n.cwd))&&(await pn(n.cwd),o.push(n.title));return o},ku=async(e,r,t)=>{let o=[],n=[];for(let s of e)!t&&r.has(await vr(s.cwd))?n.push(s.title):o.push(s);return{toOpen:o,skipped:n}},Kw=async e=>{let{targets:r,force:t,repoName:o,groupRef:n=null}=e,s=t?new Set:new Set((await qe()).keys()),{toOpen:i,skipped:a}=await ku(r,s,t),c=[],p=n,d=!1;for(let u of i)try{if(p)await Xr({cwd:u.cwd,title:u.title,group:p});else{let m=await Xr({cwd:u.cwd,title:u.title});d||(p=await un(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}},Uw=async e=>{let{repo:r,releaseOnly:t,force:o,worktreePaths:n,targets:s}=e,i=o?new Set:new Set((await qe()).keys()),{toOpen:a,skipped:c}=await ku(s,i,o);return{repo:r,dryRun:!0,releaseOnly:t,worktreePaths:n,ideProviders:[],cmuxOpened:a.map(p=>p.title),cmuxSkipped:c,cmuxClosed:[]}},Hw=(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}`)}},zw=(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=>La(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")},qw=async e=>{let{project:r=[],root:t=[],releaseOnly:o=!1,force:n=!1,dryRun:s=!1}=e,i=await Ba({roots:t}),a=Yw(i,r),c=Zw({releaseOnly:o,force:n,dryRun:s}),p=[];for(let u of a)p.push(await Xw(u,c));let d={all:!0,dryRun:s,projects:a,results:p};return eb(d),h.print(),{content:y(JSON.stringify(d,null,2)),structuredContent:d}},Yw=(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))},Zw=e=>{let r=[];return e.dryRun&&r.push("--dry-run"),e.releaseOnly&&r.push("--release-only"),e.force&&r.push("--force"),r},Xw=async(e,r)=>{try{let t=await Qw(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}}},Qw=(e,r)=>{let t=vu.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];Ww(vu.execPath,s,{cwd:e,maxBuffer:16*1024*1024},(i,a)=>{if(i){n(i);return}o(a)})})},eb=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`)},Ga=k({name:"reopen",description:"Reopen editor + cmux windows for every active worktree in the current project \u2014 the main checkout plus every linked worktree (release, feature, detached). Additive and idempotent by default: cmux workspaces already open are skipped, so running twice does not double the windows. Zed opens the exact folder set; Cursor reconciles its release-branch-shaped workspace. Set releaseOnly to restrict to release worktrees (the legacy reload scope). Set force to close each cmux workspace first, then reopen (disruptive). Set dryRun to return the plan without spawning anything. Non-destructive to git \u2014 only cmux/editor view state is touched.",inputSchema:{releaseOnly:H.boolean().optional().describe("Restrict to release worktrees (reproduces the legacy worktrees-reload scope)"),force:H.boolean().optional().describe("Close each cmux workspace first, then reopen (disruptive)"),dryRun:H.boolean().optional().describe("Return the plan (paths + cmux titles) without spawning anything")},outputSchema:{repo:H.string().describe("Repository name the reopen ran for"),dryRun:H.boolean().describe("Whether this was a dry run (nothing was spawned)"),releaseOnly:H.boolean().describe("Whether the set was restricted to release worktrees"),worktreePaths:H.array(H.string()).describe("Absolute folder set handed to the editor (root-first)"),ideProviders:H.array(H.string()).describe("Configured IDE providers that opened (cursor | zed); empty in dry run"),cmuxOpened:H.array(H.string()).describe("Titles of cmux workspaces opened this run"),cmuxSkipped:H.array(H.string()).describe("Titles of cmux workspaces skipped because already open (additive mode)"),cmuxClosed:H.array(H.string()).describe("Titles of cmux workspaces closed first (force mode only)")},handler:yu});import{spawnSync as nb}from"node:child_process";import{homedir as sb}from"node:os";import ib from"node:process";var rb=e=>{let r=new Set(e.steps.map(t=>t[0]));return r.has("brew")?"homebrew":r.has("npm")?"npm":null},tb=e=>{let r=[];return e.needsSudo&&r.push("needs-sudo"),e.fetchesNetworkScript&&r.push("fetches-network-script"),r},ob=(e,r)=>{let t=rb(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},Go=(e,r)=>{let t=[...tb(e),...ob(e,r)];return t.length===0?{executable:!0}:{executable:!1,reasons:t}},Ko=e=>e.steps.map(kc);var ab=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],cb=e=>{let r={...yc(e)};for(let t of ab)delete r[t];return r},Ka=(e,r,t={})=>{let o=t.spawnSync??nb,n=t.env??ib.env,s=(t.mcpMode??V)(),i=Ko(e),a=Go(e,r);return a.executable?s?{ran:!1,commands:i,refusedBecause:["mcp-mode"]}:db({recipe:e,spawn:o,env:n,commands:i,notify:t.notify??lb}):{ran:!1,commands:i,refusedBecause:a.reasons}},lb=e=>{l.info(e)},bu=64,pb=bu*1024*1024,db=({recipe:e,spawn:r,env:t,commands:o,notify:n})=>{let s=cb(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:pb,cwd:sb(),env:s}),p=vb(c);if(p!==null)return{ran:!0,ok:!1,commands:o,failedStep:o[i],detail:p}}return{ran:!0,ok:!0,commands:o}},ub=5,mb=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,wu=e=>e==null?[]:String(e).split(`
439
- `).map(r=>r.trim()).filter(r=>r.length>0),fb=e=>{let r=wu(e.stderr),t=wu(e.stdout),o=[...r,...t].filter(s=>mb.test(s)),n=r.length>0?r:t;return(o.length>0?o:n).slice(-ub).join(" / ")},gb="ENOBUFS",hb=e=>e.error?.code===gb,vb=e=>{if(hb(e))return`terminated after exceeding the ${bu} 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=fb(e),t=r===""?"":`: ${r}`;return`exited ${e.status??"unknown"}${t}`};var yb=e=>{let r=[];return e.some(o=>o.id==="brew"&&o.present)&&r.push("homebrew"),r.push("npm"),r},kb=e=>{let r=ve(e.id);return e.present?r.updateFor(e.binRealPath):r.bootstrapInstall},wb=(e,r)=>{let t=kb(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=Go(t,o);return{state:e,action:e.present?"update":"install",recipe:t,executable:n.executable,refusedBecause:n.executable?[]:n.reasons,commands:Ko(t),context:o}},is=async(e=Ir,r=mo())=>{let t=await vo(Ir,r),o={owner:null,present:yb(t)},n=Di(e),s=new Map(t.map(a=>[a.id,a]));return{plans:n.filter(a=>e.includes(a)).map(a=>wb(s.get(a),o)),context:o}};var Ua=(e,r)=>({...Uo(e),action:"skipped",commands:e.commands,detail:r}),Uo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Ru=(e,r)=>e.action==="none"?Ua(e,`nothing to do: ${e.state.manager} installs are not managed from here`):r==="update"&&e.action==="install"?Ua(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Uo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},bb=(e,r)=>r.ran?r.ok?{...Uo(e),action:e.action==="install"?"installed":"updated",commands:r.commands,detail:e.action==="install"?"installed":"updated"}:{...Uo(e),action:"failed",commands:r.commands,detail:`${r.failedStep??"a step"} ${r.detail??"failed"}`}:{...Uo(e),action:"refused",commands:r.commands,detail:`refused (${r.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Ha=async e=>{let r=e.run??Ka,{plans:t}=await is(e.ids,e.probeDeps),o=[];for(let n of t){let s=Ru(n,e.mode);if(s!==null){o.push(s);continue}o.push(bb(n,r(n.recipe,n.context)))}return o},za=async(e,r)=>{let{plans:t}=await is(e,r);return t.map(o=>Ru(o,"converge")??Ua(o,`would ${o.action} \u2014 nothing was run (--skip-tools)`))};import Rb from"node:process";import{z as $}from"zod";var Pb=()=>{let e=Dc();return{link:e,target:{home:e.home,processStartTime:()=>null}}},Eb=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 ye(e)}},xb=async e=>{let r=$c(e.link);l.info(` ${r.outcome.padEnd(9)} portless link \u2014 ${Eb(r.outcome)}`);let t=rn(e.link.home,e.target.exists)??e.link.resolveBin();t!==null&&await Xp(e.target,t)!=="converged"&&(l.info("Run this yourself to finish the portless service:"),l.info(` ${gr(t,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath})}`))},Eu="--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.",Sb=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(Eu);return{ids:e.tools??r??Ir,mode:t?"update":"converge",skipTools:o}},Pu=(e,r)=>e instanceof vt?e.step:r.at(-1)?.step??"zshrc",Tb=async()=>{let e=[],r=t=>{e.push(t),t.message!==uo&&Mn(t)};try{return await xi(r),{entries:e,failed:!1}}catch(t){let o={step:Pu(t,e),outcome:"warned",message:`The ${Pu(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"};return Mn(o),e.push(o),{entries:e,failed:!0}}},Cb=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(Ab(o,r)){l.info(`Run these yourself to ${r?"set up":"finish"} ${o.id}:`);for(let n of o.commands)l.info(` ${n}`)}await xb(t),l.info(uo)},Ab=(e,r)=>e.commands.length===0?!1:e.action==="refused"||r&&e.action==="skipped",Ib=e=>({step:e.step,outcome:e.outcome,message:e.message}),xu=async(e={})=>{let r=Sb(e),t=await Tb(),o=r.skipTools?await za(r.ids,e.probeDeps):await Ha({ids:r.ids,mode:r.mode,probeDeps:e.probeDeps,run:e.run});await Cb(o,r.skipTools,e.portlessDeps??Pb());let n={init:t.entries.map(Ib),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)&&(Rb.exitCode=1),{content:y(JSON.stringify(n,null,2)),structuredContent:n}},$b=$.object({step:$.enum(["zshrc","migrations","user-config","guidance","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:$.enum(["written","unchanged","skipped","warned"]).describe("What that step did: changed something, found nothing to change, did not run, or failed non-fatally"),message:$.string().describe("The same line a human running this would have read")}),Db=$.object({id:$.string().describe("Dependency id"),action:$.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:$.object({present:$.boolean(),onPath:$.boolean(),version:$.string().nullable(),manager:$.string()}).describe("The tool\u2019s state before this run"),commands:$.array($.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:$.string().describe("Why, in one line")}),Ob={init:$.array($b).describe("One entry per init step, in the order they ran"),tools:$.array(Db).describe("One result per requested dependency"),converged:$.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:$.boolean().describe("Whether anything was installed or updated"),allSucceeded:$.boolean().describe("Whether no tool failed (a refusal is not a failure)")},_b={tools:$.array($.enum(Ir)).optional().describe("Which tools to act on. Omit for all five."),mode:$.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:$.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},Nb={"anthropic/requiresUserInteraction":!0},qa=k({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and the infra-kit MCP server, 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:_b,outputSchema:Ob,requiresHumanConfirm:!0,meta:Nb,handler:e=>xu({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Cu}from"node:fs";import Au from"node:path";import Kb from"node:process";import{z as Ge}from"zod";import{createHash as jb}from"node:crypto";import{readFileSync as Mb}from"node:fs";var Ya=e=>jb("sha256").update(Mb(e)).digest("hex");import{readFileSync as Bb,writeFileSync as jL}from"node:fs";import Tu from"node:path";import{z as Te}from"zod";var Ve="vendor",Fb=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),Lb=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),Wb=[".tsbuildinfo"],Za=e=>Fb.has(e),Xa=e=>Lb.has(e)?!0:Wb.some(r=>e.endsWith(r)),Su=e=>{let r=e.split("/"),t=r.pop()??"";return r.some(n=>Za(n))||Xa(t)};import{readdirSync as Jb}from"node:fs";import Qa from"node:path";var Vb=e=>e.split(Qa.sep).join("/"),ec=e=>{let r=[],t=o=>{for(let n of Jb(o,{withFileTypes:!0})){let s=Qa.join(o,n.name);if(n.isDirectory()){if(Za(n.name))continue;t(s);continue}Xa(n.name)||r.push(Vb(Qa.relative(e,s)))}};return t(e),r.sort()};var Be=".sync-manifest.json",rc=1,Gb=Te.object({schemaVersion:Te.number().optional(),source:Te.string(),commit:Te.string(),syncedAt:Te.string(),fileCount:Te.number(),files:Te.record(Te.string(),Te.string())}),tc=e=>(e.schemaVersion??rc)>rc;var oc=e=>{let r=Tu.join(e,Be),t;try{t=Bb(r,"utf8")}catch{throw new Error(`Missing ${Be} at ${r}`)}let o=Gb.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${Be} at ${r}: ${Te.prettifyError(o.error)}`);return o.data};var nc=(e,r)=>{let t=Object.fromEntries(Object.entries(r.files).filter(([c])=>!Su(c))),o=ec(e),n=[],s=[];for(let c of o){if(!(c in t)){s.push(c);continue}Ya(Tu.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 sc=30,ic=(e,r)=>{if(r.length!==0){l.info(`
440
- ${e} (${r.length}):`);for(let t of r.slice(0,sc))l.info(` ${t}`);r.length>sc&&l.info(` \u2026and ${r.length-sc} more`)}},Iu=async(e={})=>{let r=e.cwd??await R(),t=Au.join(r,Ve),o={modified:[],added:[],removed:[],fileCount:0};if(!Cu(t)){l.info(`\u2139\uFE0F No ${Ve}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...o};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}if(!Cu(Au.join(t,Be))){l.error(`\u274C Missing ${Ve}/${Be}. 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=oc(t);if(tc(n)){l.error(`\u274C ${Ve}/${Be} 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}=nc(t,n),c=s.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${Ve}/ has drifted from ${Ve}/${Be}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),ic("Modified",s),ic("Added (not in manifest)",i),ic("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${Ve}/ 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}},Ub={status:Ge.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:Ge.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:Ge.number(),modified:Ge.array(Ge.string()),added:Ge.array(Ge.string()),removed:Ge.array(Ge.string())},ac=k({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:Ub,handler:()=>Iu({cwd:Kb.cwd()})});import{z as Hb}from"zod";var $u=async()=>{let e=ae.version;l.info(e);let r={version:e};return{content:y(JSON.stringify(r,null,2)),structuredContent:r}},cc=k({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:Hb.string().describe("Installed infra-kit CLI version (from package.json)")},handler:$u});import Du from"@inquirer/confirm";import zb from"node:path";import{z as Ke}from"zod";import{$ as Ho}from"zx";var qb="feature",Yb="release",_u=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:n,cmux:s}=e,i=e.ide??e.cursor;await te({operation:"create worktrees"});try{let a=await ie("release"),c=await R(),p=`${c}${Q}`;await Ou(`${p}/${Yb}`),await Ou(`${p}/${qb}`);let d=[];if(o)d=o.split(",").map(O=>ke(me(O.trim())));else{let O=await D(),C=O.map(P=>P.branch);if(C.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=C;else{h.setInteractive();let P=new Map(O.map(ne=>[ne.branch,_(ne.title)])),Ce=await B();d=await It(X({branches:C,descriptions:Ce,types:P}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",_r(d)),await G(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let u=await E(),m=i??(we(u).length>0?"workspace":"none");h.addOption("--ide",m);let v=n??u.worktrees?.openInGithubDesktop??await A(O=>Du({message:"Open created worktrees in GitHub Desktop?"},O),{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 g=s??u.worktrees?.openInCmux??await A(O=>Du({message:"Open created worktrees in cmux?"},O),{whenHeadless:{value:!1}});typeof s>"u"&&u.worktrees?.openInCmux===void 0&&h.setInteractive(),g?h.addOption("--cmux",!0):h.addOption("--no-cmux",!0);let{branchesToCreate:w}=Zb({selectedReleaseBranches:d,currentWorktrees:a}),T=await Xb(w,p);if(Qb(T),m==="workspace"&&await Ma({projectRoot:c,worktreeDir:p,branches:T}),v)for(let O of T)await Ho`github ${p}/${O}`,await Ho`sleep 5`;if(g){let O=zb.basename(await He(c)),C=await qe(),P=await dn(O),Ce=!1;for(let ne of T){let Br=`${p}/${ne}`;if(C.has(await vr(Br)))continue;let pr=mn({branch:ne});try{if(P)await Xr({cwd:Br,title:pr,group:P});else{let dr=await Xr({cwd:Br,title:pr});Ce||(P=await un(O,[dr]),Ce=!0)}}catch(dr){l.warn({error:dr,branch:ne},`\u26A0\uFE0F Failed to open cmux workspace for ${ne}`)}}}h.print();let F={createdWorktrees:T,count:T.length};return{content:y(JSON.stringify(F,null,2)),structuredContent:F}}catch(a){throw Ae(a)?a:(l.debug({err:a},"Error managing worktrees"),new f(a,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},Ou=async e=>{await Ho`mkdir -p ${e}`},Zb=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>hr(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},Xb=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Ho`git worktree add ${s} ${n}`,await Ho({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 f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});l.error({error:s.reason,msg:a.message})}return o},Qb=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")},lc=k({name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:Ke.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:Ke.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:Ke.enum(os).optional().describe('Editor open mode for created worktrees, applied to all configured editors (Cursor and/or Zed, per the "ide" config). "workspace" (the only attach style) adds each worktree to every configured editor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when at least one "ide" is configured \u2192 "none" otherwise.'),cursor:Ke.enum(os).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:Ke.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),cmux:Ke.boolean().optional().describe('Open each created worktree in a new cmux workspace, all rooted at the worktree directory. Pane layout follows "worktrees.cmux.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInCmux" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).')},outputSchema:{createdWorktrees:Ke.array(Ke.string()).describe("List of created git worktree branches"),count:Ke.number().describe("Number of git worktrees created")},handler:_u});import{z as Nt}from"zod";var Nu=async()=>{await E();let e=await ie("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([D(),B()]),o=new Map(r.map(c=>[c.branch,_(c.title)])),n=e.flatMap(c=>{let p=j(c);if(!p)return[];let d=L(p),u=o.get(c)||"regular",m=t.get(z(p))||null;return[{version:d,type:u,description:m}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=Po(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});l.info(`\u{1F33F} Active worktrees:
441
-
442
- ${i.join(`
443
- `)}`);let a={worktrees:n,count:n.length};return{content:y(JSON.stringify(a,null,2)),structuredContent:a}},pc=k({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:Nt.array(Nt.object({version:Nt.string().describe("Release version"),type:Nt.enum(["regular","hotfix"]).describe("Release type"),description:Nt.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Nt.number().describe("Number of worktrees")},handler:Nu});import{z as Vr}from"zod";var eR=e=>{if(V()){if(e.all)throw new f(void 0,{operation:"remove worktrees",remediation:'name targets explicitly via "versions"; bulk all=true removal is disabled over MCP',stderrExcerpt:"all=true is not permitted for worktrees-remove over MCP"});if(!e.versions)throw new f(void 0,{operation:"remove worktrees",remediation:'pass "versions" (comma-separated release versions/names); the interactive picker needs a TTY',stderrExcerpt:'worktrees-remove over MCP requires "versions"'})}},rR=(e,r)=>{let t=e.filter(o=>!r.includes(o));if(t.length>0)throw new f(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(", ")}`})},ju=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await te({operation:"remove worktrees"}),await E(),eR({all:t,versions:o});try{let n=await ie("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}${Q}`,a=[];if(t)a=n;else if(o)a=o.split(",").map(d=>ke(me(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([B(),D()]),m=new Map(u.map(v=>[v.branch,_(v.title)]));a=await It(X({branches:n,descriptions:d,types:m}),{required:!0})}rR(a,n);let c=a.length===n.length;c?h.addOption("--all",!0):h.addOption("--versions",_r(a)),await G(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let p=await Mr({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await Jr({projectRoot:s,worktreeDir:i,currentWorktrees:n,removedWorktrees:p.removed,allowEditorRelaunch:!r}),To(p),h.print(),Co({result:p,operation:"remove worktrees"})}catch(n){throw Ae(n)||n instanceof f?n:(l.error({error:n},"\u274C Error managing worktrees"),new f(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},dc=k({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named version must be an active worktree, or the call errors without removing anything. What survives: the release branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.',requiresHumanConfirm:!0,inputSchema:{versions:Vr.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:Vr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Vr.array(Vr.string()).describe("List of removed git worktree branches"),failedWorktrees:Vr.array(Vr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Vr.number().describe("Number of git worktrees removed")},handler:ju});import{z as zo}from"zod";var Mu=async e=>{let{confirmedCommand:r}=e;await te({operation:"sync worktrees"}),await E();try{let t=await ie("release"),o=await R(),n=`${o}${Q}`,s=await Un();await G(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let{branchesToRemove:i}=tR({releasePRsList:s,currentWorktrees:t}),a=await Mr({branches:i,worktreeDir:n,projectRoot:o});return await Jr({projectRoot:o,worktreeDir:n,currentWorktrees:t,removedWorktrees:a.removed,allowEditorRelaunch:!1}),To(a),h.print(),Co({result:a,operation:"sync worktrees"})}catch(t){throw Ae(t)||t instanceof f?t:(l.error({error:t},"\u274C Error managing worktrees"),new f(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},tR=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>hr(s)).filter(s=>!r.includes(s))}},uc=k({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:zo.array(zo.string()).describe("List of removed worktree branches"),failedWorktrees:zo.array(zo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:zo.number().describe("Number of worktrees removed during sync")},handler:Mu});var oR=[{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"}],as=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:oi,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:oa,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:Ia,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:$a,mcpExposed:!0,mutating:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:fa,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:ha,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:sa,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Ja,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:xa,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Sa,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:lc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:pc,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"reopen",menuGroup:"worktrees",mcpTool:Ga,mcpExposed:!0,mutating:!1,groupPath:["reopen"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:dc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:uc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:qi,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:zi,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:fi,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Hi,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Zi,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:ei,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:ac,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:qa,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Ki,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Qs,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:cc,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 nR={"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}},sR=["reopen"],iR=()=>as.flatMap(e=>{if(!e.mcpExposed||!e.mcpTool)return[];let r=nR[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&&!sR.includes(e.mcpTool.name);return[{...e.mcpTool,title:r.title,annotations:{readOnlyHint:t,...t?{}:{destructiveHint:!0},openWorldHint:r.openWorld}}]}),aR=e=>as.filter(r=>r.menuGroup===e),cR=e=>as.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import mc from"node:process";var lR="MODULE_TYPELESS_PACKAGE_JSON",pR=(e,r)=>typeof e=="object"&&e!==null?e.code:r,Fu=!1,dR=()=>{if(Fu)return;Fu=!0;let e=mc.emitWarning.bind(mc);mc.emitWarning=((r,...t)=>{pR(t[0],t[1])!==lR&&e(r,...t)})};export{y as a,Dl as b,Ol as c,ti as d,Nl as e,ng as f,oo as g,no as h,Pr as i,yS as j,kg as k,np as l,sp as m,ht as n,ip as o,ap as p,Dn as q,On as r,Ug as s,Ei as t,yC as u,kC as v,Si as w,Ti as x,Vh as y,Qp as z,rd as A,nd as B,sd as C,Yi as D,ld as E,At as F,cy as G,hd as H,kD as I,Td as J,_d as K,Ot as L,lk as M,pk as N,Bd as O,Gd as P,Kd as Q,Qd as R,eu as S,au as T,cu as U,os as V,fu as W,Jw as X,xu as Y,Iu as Z,$u as _,_u as $,Nu as aa,ju as ba,Mu as ca,oR as da,as as ea,iR as fa,aR as ga,cR as ha,dR as ia};
444
- //# sourceMappingURL=chunk-7YE5QKKB.js.map