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