infra-kit 0.7.9 → 0.7.12
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-63VNUKUS.js → chunk-5FYZAIFC.js} +2 -2
- package/dist/{chunk-LDF2KOGN.js → chunk-6OFUVD7F.js} +2 -2
- package/dist/chunk-75URROMU.js +4 -0
- package/dist/chunk-75URROMU.js.map +7 -0
- package/dist/{chunk-YKCY657C.js → chunk-GFKYWEPW.js} +2 -2
- package/dist/{chunk-MFNMFVI6.js → chunk-R6AYBYV6.js} +89 -89
- package/dist/chunk-R6AYBYV6.js.map +7 -0
- package/dist/{chunk-KXQQUBGV.js → chunk-T2WBH6YO.js} +2 -2
- package/dist/chunk-UNAV7SP4.js +3 -0
- package/dist/chunk-UNAV7SP4.js.map +7 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/dev-server.js +2 -2
- package/dist/{dev-wizard-run-MCUYV6IN.js → dev-wizard-run-DRBMPH2O.js} +2 -2
- package/dist/mcp-proxy.js +1 -1
- package/dist/mcp.js +2 -2
- package/dist/mcp.js.map +4 -4
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/readme.md +1 -0
- package/dist/chunk-DFZ5WUIM.js +0 -3
- package/dist/chunk-DFZ5WUIM.js.map +0 -7
- package/dist/chunk-MFNMFVI6.js.map +0 -7
- package/dist/chunk-NFIFWIO6.js +0 -4
- package/dist/chunk-NFIFWIO6.js.map +0 -7
- /package/dist/{chunk-63VNUKUS.js.map → chunk-5FYZAIFC.js.map} +0 -0
- /package/dist/{chunk-LDF2KOGN.js.map → chunk-6OFUVD7F.js.map} +0 -0
- /package/dist/{chunk-YKCY657C.js.map → chunk-GFKYWEPW.js.map} +0 -0
- /package/dist/{chunk-KXQQUBGV.js.map → chunk-T2WBH6YO.js.map} +0 -0
- /package/dist/{dev-wizard-run-MCUYV6IN.js.map → dev-wizard-run-DRBMPH2O.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
${i}`:"")},
|
|
1
|
+
import{a as bn,c as ke,d as b,e as Xt,f as te,i as h,j as Rn,k as A,l as z}from"./chunk-GFKYWEPW.js";import{a as yl,d as kl,f as Pr,g as rr,h as Pn,i as En,j as xn,n as it,o as Sn,p as De}from"./chunk-T2WBH6YO.js";import{A as Yt,B as Es,C as vn,D as cl,E as ll,F as xs,G as Ss,H as pl,K as l,L as er,M as ul,N as As,O as Ee,Q as X,R as E,S as ml,T as st,V as fl,X as gl,a as mn,b as g,ca as hl,d as j,e as rl,f as fn,fa as vl,g as W,h as ye,i as Re,j as tl,k as Ps,l as Z,m as V,n as Rr,o as ol,p as Ze,q as de,r as R,s as Pe,t as nt,u as nl,v as sl,w as il,x as al,y as gn,z as hn}from"./chunk-5FYZAIFC.js";import{a as Jc,b as Vc,c as ws,d as Bc,e as Gc,f as Uc,g as Kc,h as qt,i as Hc,j as zc,k as qc,l as Yc,m as Zc,n as bs,o as Xc,p as Rs,q as un,r as br,s as Qc,t as el}from"./chunk-6OFUVD7F.js";import{a as T,b as F,c as Xe,d as yn,e as Ts,f as kn,g as Cs,h as Zt,i as Qe,j as wn,k as dl,l as H,m as Qt,n as eo,o as $s,p as Is,r as _s}from"./chunk-UNAV7SP4.js";import{b as zt,c as pn,d as ks,e as jc,f as dn,g as Fc,i as Lc,m as pe,o as Wc}from"./chunk-HHWP3YXW.js";import{a as le,b as sn,c as Kt,d as Ht,e as Nc,f as an,g as Qr,h as et,i as cn,j as rt,k as yr,l as tt,m as ln,q as ot,r as Mc,s as kr,t as wr,u as re}from"./chunk-75URROMU.js";import{spawn as vm}from"node:child_process";import bl from"node:fs";import at from"node:process";import{fileURLToPath as Rl}from"node:url";var wl=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],gm=new Set(["mcp"]),hm=e=>e[2]!=null&&gm.has(e[2]),Ds=e=>{let{argv:r,env:t,isTty:o,selfRealPath:n,cwd:s,realpath:i}=e;return wl.some(c=>{let p=t[c];return p!=null&&p!==""})?"opt-out":r.includes("--json")?"json":hm(r)?"own-command":o?Lc(n,s,i)?"local-install":null:"not-a-tty"};var ym=e=>{vm(at.execPath,[e,"--parent-pid",String(at.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},km=()=>Rl(new URL("./update-check.js",import.meta.url)),wm=()=>bl.realpathSync(Rl(new URL("./cli.js",import.meta.url))),bm=/^[\w@./+ -]+$/i,Rm=e=>bm.test(e),Pm=(e,r,t)=>{!e?.latestVersion||!e.updateCommand||Qt(e.latestVersion,r)&&e.updateCommand.every(Rm)&&t(`infra-kit ${e.latestVersion} is available (you have ${r}). Run: ${dn(e.updateCommand)}`)},Em=(e,r={})=>{try{let t=r.argv??at.argv,o=r.env??at.env,n=r.isTty??!!at.stdout.isTTY,s=r.cwd??at.cwd(),i=r.nowMs??Date.now(),a=r.selfRealPath??wm(),c=r.readCache??eo,p=r.spawnChild??ym,d=r.fileExists??(f=>bl.existsSync(f)),u=r.notify??(f=>{l.info(f)});if(Ds({argv:t,env:o,isTty:n,selfRealPath:a,cwd:s,realpath:pe})!==null)return;let m=c();if(Pm(m,e,u),!$s(m,i))return;let v=r.childPath??km();if(!d(v))return;p(v)}catch{}};import tp from"node:process";import{z as fe}from"zod";import Cl from"node:fs";import lt from"node:path";import{packageConfigSchema as Im}from"@slip-stream-kit/config/internal";import El from"node:fs/promises";import js from"node:path";import{pathToFileURL as _m}from"node:url";import{z as Dm}from"zod";import Pl from"node:path";var ro=["frontend","backend","lib","e2e","mobile"],xm={ui:"frontend",api:"backend",tests:"e2e"},Sm="mobile-app",Tm=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Cm=(e,r)=>{let t=Pl.relative(r,e).split(Pl.sep).filter(s=>s!==""&&s!=="."),[o,,n]=t;if(t.length===3&&o==="apps"&&n!==void 0){let s=xm[n];if(s)return s}return t.at(-1)===Sm?"mobile":null},Am=e=>{let r=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let o of Tm)if(o.packages.some(n=>r.has(n)))return o.type;return r.has("vite")&&r.has("react")&&!!e.scripts?.dev?"frontend":null},Os=({packageDir:e,repoRoot:r,pkgJson:t,declaredType:o})=>o??Cm(e,r)??Am(t)??"lib";var tr={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Ns={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"]},Ms=(e,r=tr)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import $m from"node:fs/promises";var xe=async e=>{try{return await $m.access(e),!0}catch{return!1}};var Oe="infra-kit.config.ts",to=async e=>{try{let r=await El.readFile(js.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},xl=async e=>{let r=await El.stat(e),n=(await import(`${_m(e).href}?mtime=${Number(r.mtimeMs)}`)).default;if(n===void 0)throw new Error(`${Oe} at ${e} has no default export`);return typeof n=="function"?await n():n},oo=async e=>{let r=js.join(e,Oe);if(await xe(r))try{let o=(await xl(r))?.type;return ro.find(n=>n===o)}catch{return}},no=async(e,r=tr)=>{let t=js.join(e,Oe);if(!await xe(t))throw new Error(`${Oe} not found at ${t}`);let o=await xl(t),n=Im.safeParse(o);if(!n.success)throw new Error(`Invalid ${Oe} at ${t}: ${Dm.prettifyError(n.error)}`);return Ms(n.data,r)};import Sl from"node:fs/promises";import Tn from"node:path";import Om from"yaml";var Nm="pnpm-workspace.yaml",Mm=async e=>(await Sl.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Tn.join(e,t.name)),jm=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await Mm(o));continue}let n=Tn.join(o,r);await xe(n)&&t.push(n)}return t},Fm=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await jm(t,o);return t},ne=async e=>{let r=await Sl.readFile(Tn.join(e,Nm),"utf-8"),o=((Om.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await Fm(e,s);for(let a of i)await xe(Tn.join(a,"package.json"))&&n.add(a)}return[...n].sort()};import so from"node:path";var io=async e=>{let r=so.resolve(e);for(;r!==so.dirname(r);){if(await xe(so.join(r,"package.json")))return r;r=so.dirname(r)}if(await xe(so.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 Se=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},or=(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}`:"")},Fs=(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},Tl=(e,r,t)=>`${e}
|
|
3
3
|
${r}
|
|
4
|
-
${t}`,ct=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=
|
|
4
|
+
${t}`,ct=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=Tl(t,r,o),i=Se(e,t,o);if(n==="replace-in-place"&&i){let p=e.indexOf(t),d=e.indexOf(o)+o.length;return e.slice(0,p)+s+e.slice(d)}let c=(i?or(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
5
5
|
${s}
|
|
6
6
|
`:`${s}
|
|
7
|
-
`};var ue="<!-- infra-kit:begin -->",Te="<!-- infra-kit:end -->",
|
|
7
|
+
`};var ue="<!-- infra-kit:begin -->",Te="<!-- infra-kit:end -->",Ls="<!-- infra-kit:version ",Ce="<!-- infra-kit:package:begin -->",Ne="<!-- infra-kit:package:end -->",Er="<!-- infra-kit:package:version ";var Lm=e=>{let r=e.indexOf(Ce)+Ce.length;return e.slice(r,e.indexOf(Ne))},Wm=e=>{let r=e.indexOf(Er);if(r===-1)return null;let t=e.slice(r+Er.length).match(/^\S+\s+([^\s>]+)/)?.[1];return ro.find(o=>o===t)??null},xr=e=>{if(e===null)return{state:"missing"};if(!Se(e,Ce,Ne))return e.includes(Ce)||e.includes(Ne)?{state:"malformed"}:Se(e,ue,Te)?{state:"foreign-block"}:{state:"no-block"};let r=Lm(e);if(r.trim()==="")return{state:"malformed"};let t={state:"ok"},o=Fs(r,Er),n=Wm(r);return o!==null&&(t.version=o),n!==null&&(t.type=n),t};import Jm from"node:fs";var Sr=e=>{try{return Jm.readFileSync(e,"utf-8")}catch{return null}};var Al="pnpm-workspace.yaml",Vm="CLAUDE.md",Js=e=>{let r=lt.resolve(e);for(;r!==lt.dirname(r);){if(Cl.existsSync(lt.join(r,Al)))return r;r=lt.dirname(r)}return Cl.existsSync(lt.join(r,Al))?r:null},Ws=new Map,Cn=()=>{Ws.clear()},Bm=async e=>{let r;try{r=await ne(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let t of r){let o=lt.join(t,Vm),n=Sr(o);if(n!==null&&xr(n).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:o}}return{adopted:!1,workspaceRoot:e}},pt=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let r=Ws.get(e);if(r)return r;let t=await Bm(e);return Ws.set(e,t),t};import ft from"node:fs";import Tr from"node:path";var $l=`---
|
|
8
8
|
name: TODO
|
|
9
9
|
description: TODO \u2014 one sentence describing the product surface this package renders.
|
|
10
10
|
colors:
|
|
@@ -73,7 +73,7 @@ TODO \u2014 for each component in the front matter list: its variants, its state
|
|
|
73
73
|
- Do TODO.
|
|
74
74
|
- Don't TODO.
|
|
75
75
|
- Don't TODO.
|
|
76
|
-
`;var
|
|
76
|
+
`;var Il=`# {{packageName}}
|
|
77
77
|
|
|
78
78
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
79
79
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -94,7 +94,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
94
94
|
- Module-scope state belongs in the handler entry file \u2014 that is the file which re-evaluates on reload.
|
|
95
95
|
- Env vars come from Doppler via \`ik env-load\`; never commit a secret.
|
|
96
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
|
|
97
|
+
`;var _l=`# {{packageName}}
|
|
98
98
|
|
|
99
99
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
100
100
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -116,7 +116,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
116
116
|
- Every spec cleans up what it creates, in teardown.
|
|
117
117
|
- Selectors live in Page Objects, never inline in specs.
|
|
118
118
|
- Never point a run at a production environment.
|
|
119
|
-
`;var
|
|
119
|
+
`;var Dl="# {{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 Ol=`# {{packageName}}
|
|
120
120
|
|
|
121
121
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
122
122
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -138,7 +138,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
138
138
|
- Changing that map is a breaking change for every dependent package.
|
|
139
139
|
- Run \`pnpm run build\` before a dependent package can see a change.
|
|
140
140
|
- No app-specific logic belongs here.
|
|
141
|
-
`;var
|
|
141
|
+
`;var Nl=`# {{packageName}}
|
|
142
142
|
|
|
143
143
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
144
144
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -160,33 +160,33 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
160
160
|
- The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
|
|
161
161
|
- The web build feeds the native shell, so a device run needs a rebuild first.
|
|
162
162
|
- Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
|
|
163
|
-
`;var
|
|
164
|
-
`)&&o.index!==0)throw new Error(`renderTemplate: multi-line value for {{${o[1]}}} must start its line (found at column ${o.index})`)}},ut=(e,r)=>{let t=
|
|
165
|
-
`),r);return
|
|
166
|
-
`).replace(
|
|
167
|
-
`};var
|
|
168
|
-
`)};var Me="mcp__plugin_infra-kit_infra-kit__",nr="mcp__infra-kit__",
|
|
169
|
-
`)};import mt from"node:fs";import
|
|
170
|
-
`).find(t=>t.trim().length>0)??"").trim(),
|
|
171
|
-
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${T}`,`enabledPlugins.${
|
|
163
|
+
`;var Ml="# 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 (which serves the infra-kit MCP server), and the external CLIs (brew, aws, gh, doppler, portless).\n\n## Conventions\n\n- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (skills, `/infra-kit:*` commands, the `{{mcpToolPrefix}}` MCP server) and this repo's `.claude/settings.json` hooks load only from there. If those tools are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n";var dt={"root/body":Ml.trimEnd(),"package/frontend":Dl.trimEnd(),"package/backend":Il.trimEnd(),"package/lib":Ol.trimEnd(),"package/e2e":_l.trimEnd(),"package/mobile":Nl.trimEnd(),"design/skeleton":$l.trimEnd()};var Vs=/\{\{(\w+)\}\}/g,Zm=/^- \{\{(\w+)\}\}$/,Xm=e=>new Set([...e.matchAll(Vs)].map(r=>r[1])),Qm=(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(", ")}`)},ef=(e,r)=>{let t=[...e].filter(o=>!(o in r));if(t.length>0)throw new Error(`renderTemplate: placeholder(s) with no variable: ${t.map(o=>`{{${o}}}`).join(", ")}`)},rf=(e,r)=>e.filter(t=>{let o=Zm.exec(t);return o===null||r[o[1]]!==""}),tf=(e,r)=>{for(let t of e)for(let o of t.matchAll(Vs)){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})`)}},ut=(e,r)=>{let t=Xm(e);ef(t,r),Qm(t,r);let o=rf(e.split(`
|
|
165
|
+
`),r);return tf(o,r),o.join(`
|
|
166
|
+
`).replace(Vs,(n,s)=>r[s])};var of="name: TODO",Bs=e=>{let r=ut(dt["design/skeleton"],{packageName:e}),t=`name: ${e}`;return`${r.replace(of,()=>t)}
|
|
167
|
+
`};var nf=(e,r)=>`${Er}${e} ${r} -->`,sf="`README.md` \u2014 what this package is and how to run it.",Gs=e=>{let{version:r,type:t,packageName:o,relDir:n,hasReadme:s}=e,i=ut(dt[`package/${t}`],{packageName:o,relDir:n,type:t,readmeBullet:s?sf:""});return[nf(r,t),"",i].join(`
|
|
168
|
+
`)};var Me="mcp__plugin_infra-kit_infra-kit__",nr="mcp__infra-kit__",jl=e=>{let r=e.CLAUDE_PLUGIN_ROOT;return r!==void 0&&r!==""?"plugin":"legacy"},Fl=e=>e==="plugin"?Me:nr;var af=e=>`${Ls}${e} -->`,Us=e=>{let r=ut(dt["root/body"],{mcpToolPrefix:`${Me}*`});return[af(e),"",r].join(`
|
|
169
|
+
`)};import mt from"node:fs";import cf from"node:path";var An=e=>{let r;try{r=mt.lstatSync(e)}catch{return}if(r.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},ao=(e,r)=>{An(e);let t=mt.existsSync(e)?mt.readFileSync(e,"utf-8"):null;return t===r?"unchanged":(mt.mkdirSync(cf.dirname(e),{recursive:!0}),mt.writeFileSync(e,r,"utf-8"),t===null?"created":"updated")},Ks=(e,r,t)=>{let o=mt.readFileSync(e,"utf-8");if(!Se(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Ll=(e,r,t)=>Se(e,r,t)?{before:e.slice(0,e.indexOf(r)),after:e.slice(e.indexOf(t)+t.length)}:null,Hs=(e,r,t,o)=>{let n=Ll(e,t,o),s=Ll(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 In="<!-- infra-kit:import:begin -->",_n="<!-- infra-kit:import:end -->",lf="AGENTS.md",Wl="CLAUDE.md",pf="README.md",zs="DESIGN.md",df=["frontend","mobile"],uf=e=>ft.existsSync(e)?ft.readFileSync(e,"utf-8"):null,qs=(e,r)=>{try{return ft.readdirSync(e).includes(r)}catch{return!1}},$n=(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},Jl=({filePath:e,body:r,startMarker:t,endMarker:o,prepare:n})=>{let s=uf(e),i=s===null?"":n?.(s)??s,a=ct({content:i,body:r,startMarker:t,endMarker:o,placement:"replace-in-place"}),c=ao(e,a);return Ks(e,t,o),s!==null&&Hs(i,a,t,o),c},mf=e=>{if(!ft.existsSync(e))return"unchanged";An(e);let r=ft.readFileSync(e,"utf-8"),t=or(r,ue,Te);return t===null?"unchanged":t.trim()===""?(ft.rmSync(e),"removed"):ao(e,t)},ff=(e,r)=>Jl({filePath:e,body:Us(r),startMarker:ue,endMarker:Te,prepare:t=>or(t,In,_n)??t}),co=async(e,{version:r})=>{let t=Tr.join(e,Wl),o=Tr.join(e,lf),n=[];try{n.push({path:t,action:ff(t,r)})}catch(s){n.push($n(t,s))}try{n.push({path:o,action:mf(o)})}catch(s){n.push($n(o,s))}return n},gf=(e,r,t)=>{if(!df.includes(t)||qs(e,zs))return null;let o=Tr.join(e,zs);try{return{path:o,action:ao(o,Bs(r)),type:t}}catch(n){return $n(o,n,t)}},lo=async(e,{repoRoot:r,version:t,design:o,declaredType:n})=>{let s=Tr.join(e,Wl),i=await to(e),a=i.name??Tr.basename(e),c=Os({packageDir:e,repoRoot:r,pkgJson:i,declaredType:n}),p=Gs({version:t,type:c,packageName:a,relDir:Tr.relative(r,e).split(Tr.sep).join("/"),hasReadme:qs(e,pf),hasDesign:qs(e,zs)}),d=[];try{d.push({path:s,action:Jl({filePath:s,body:p,startMarker:Ce,endMarker:Ne}),type:c})}catch(u){d.push($n(s,u,c))}if(o){let u=gf(e,a,c);u&&d.push(u)}return d};import Pf from"node:path";import Vl from"node:path";var Ys="agent-guidance",po="CLAUDE.md",hf="\u2014 run: infra-kit audit --fix",vf={missing:`${po} missing`,"no-block":`${po} has no infra-kit block (expected ${Ce} \u2026 ${Ne})`,malformed:`${po} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${po} carries the ROOT infra-kit block (${ue}); a package needs the package block`},yf=e=>e.adopted?` (workspace adopted: ${Vl.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Zs=(e,r)=>{let t=xr(Sr(Vl.join(e,po)));if(t.state==="ok"){let s=t.version??"unknown",i=t.type??"unknown";return{name:Ys,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let o=`${vf[t.state]} ${hf}`,n=t.state==="missing"?`${o}${yf(r)}`:o;return r.adopted?{name:Ys,status:"fail",message:n}:{name:Ys,status:"pass",message:`not yet adopted \u2014 ${n}`}};var Xs=async(e,r=tr)=>{try{let t=await no(e,r);return{check:{name:Oe,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:Oe,status:"fail",message:t.message},rules:null}}};import kf from"node:fs/promises";import wf from"node:path";var Qs=async(e,r)=>Promise.all(r.map(async t=>{let o=await kf.stat(wf.join(e,t)).catch(()=>null);return o?o.isFile()?{name:`file:${t}`,status:"pass",message:"exists"}:{name:`file:${t}`,status:"fail",message:`not a file: ${t} (found a directory)`}:{name:`file:${t}`,status:"fail",message:`missing file: ${t}`}}));var ei=(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 bf from"node:fs/promises";import Rf from"node:path";var gt="turbo.json",ri=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await bf.readFile(Rf.join(e,gt),"utf-8");t=JSON.parse(n)}catch(n){return[{name:gt,status:"fail",message:`cannot read/parse ${gt}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:gt,status:"fail",message:`no "tasks" object defined in ${gt}`}]: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 ${gt}`}})};var Ef={adopted:!1,workspaceRoot:null},ti=async(e,r=tr,t={})=>{let o=await to(e),n=o.name??Pf.basename(e),{check:s,rules:i}=await Xs(e,r),a=[s];t.isRoot||a.push(Zs(e,t.adoption??Ef)),i&&(a.push(...ei(o.scripts??{},i.requiredScripts)),a.push(...await Qs(e,i.requiredFiles)),a.push(...await ri(e,i.turboTasks)));let c=a.every(p=>p.status==="pass");return{packageDir:e,packageName:n,checks:a,passed:c}};var oi=["plugin","marketplace","add",Xe],ni=["plugin","install",F,"--scope","project"],Bl=(e,r)=>Qe({projectPath:e,home:r}).kind==="installed",si=e=>((e??"").split(`
|
|
170
|
+
`).find(t=>t.trim().length>0)??"").trim(),xf=(e,r)=>{if(Zt(r))return null;l.debug({msg:`Running: ${yn} ${oi.join(" ")}`});let t=e({args:oi});return t.ok?null:{step:"marketplace",error:si(t.output)}},Sf=(e,r)=>{l.debug({msg:`Running: ${yn} ${kn.join(" ")}`});let t=e({args:kn,cwd:r});return t.ok?{status:"updated"}:{status:"update-failed",error:si(t.output)}},ii=e=>{let{projectRoot:r,home:t}=e,o=e.run??Cs;if(!o({args:Ts}).ok)return{status:"claude-missing"};if(Bl(r,t))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Sf(o,r);let n=xf(o,t);if(n!==null)return{status:"failed",...n};l.debug({msg:`Running: ${yn} ${ni.join(" ")}`});let s=o({args:ni,cwd:r});return s.ok?Bl(r,t)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:si(s.output)}};import Tf from"node:fs";import Cf from"node:path";var L=".mcp.json",me="mcpServers",Af="infra-kit",$f=["mcp"],ai=" ",Cr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dn=e=>{if(!Cr(e))return!1;let{command:r,args:t}=e;return r===Af&&Array.isArray(t)&&t[0]===$f[0]},Gl=e=>/\n([ \t]+)"/.exec(e)?.[1]??ai,ci=e=>{try{return{kind:"raw",raw:Tf.readFileSync(e,"utf-8")}}catch(r){return r.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:r}}},li=e=>{try{return JSON.parse(e)}catch{return}},pi=e=>e instanceof Error?e.message:String(e),Ar=e=>{let r=ci(Cf.join(e,L));if(r.kind==="absent")return{kind:"missing-file"};if(r.kind==="unreadable")return{kind:"unparseable"};let t=li(r.raw);if(!Cr(t)||!Cr(t[me]))return{kind:"unparseable"};let o=t[me];if(T in o)return{kind:"stale"};let n=Object.keys(o).find(s=>Dn(o[s]));return n===void 0?{kind:"absent"}:{kind:"wrong-key",key:n}};import On from"node:fs";import If from"node:path";var Ae=`claude plugin install ${F} --scope project`,sr=`claude plugin update ${F} --scope project`,di=`claude plugin marketplace add ${Xe}`,Kl=" ",Hl=()=>({source:{source:"github",repo:Xe}}),_f=()=>({extraKnownMarketplaces:{[T]:Hl()},enabledPlugins:{[F]:!0}}),zl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Df=e=>/\n([ \t]+)"/.exec(e)?.[1]??Kl,Ul=(e,r,t,o)=>{let n=e[r];return n===void 0?(e[r]={[t]:o},`${r}.${t}`):!zl(n)||t in n?null:(n[t]=o,`${r}.${t}`)},Of=e=>[Ul(e,"extraKnownMarketplaces",T,Hl()),Ul(e,"enabledPlugins",F,!0)].filter(t=>t!==null),Nf=e=>{try{return On.readFileSync(e,"utf-8")}catch{return null}},Mf=e=>(On.mkdirSync(If.dirname(e),{recursive:!0}),On.writeFileSync(e,`${JSON.stringify(_f(),null,Kl)}
|
|
171
|
+
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${T}`,`enabledPlugins.${F}`]}),ui=e=>{let r=Nf(e);if(r===null)return Mf(e);let t;try{t=JSON.parse(r)}catch{t=void 0}if(!zl(t))return l.warn(`Could not parse ${e} \u2014 left it untouched. Add "${F}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Of(t);if(o.length===0)return{status:"unchanged",path:e,added:[]};let n=Df(r),s=r.endsWith(`
|
|
172
172
|
`)?`
|
|
173
|
-
`:"";return
|
|
173
|
+
`:"";return On.writeFileSync(e,`${JSON.stringify(t,null,n)}${s}`,"utf-8"),{status:"added",path:e,added:o}};var y=e=>[{type:"text",text:e}],w=e=>e;import jf from"node:path";import Ff from"node:process";var Lf=["unchanged","created"],Wf=["unchanged","created","updated","removed","failed"],ql=async(e,r,t)=>{let o=await oo(e);return lo(e,{repoRoot:r,version:H.version,design:t,declaredType:o})},Jf=async(e,r)=>{if(e.root)return co(r,{version:H.version});if(e.all){let o=[];for(let n of await ne(r))o.push(...await ql(n,r,e.design));return o}let t=await io(e.cwd??Ff.cwd());return ql(t,r,e.design)},Vf=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 ${Wf.filter(o=>Lf.includes(o)||(r.get(o)??0)>0).map(o=>`${r.get(o)??0} ${o}`).join(", ")} (infra-kit ${H.version})`},Bf=(e,r)=>{for(let t of e){if(t.action==="unchanged")continue;let o=jf.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(Vf(e))},Gf=e=>{let r={path:e.path,action:e.action};return e.type&&(r.type=e.type),r},Yl=async(e,r)=>{let t=await R();Cn();let o=await pt(r),n=await Jf(e,t);Bf(n,t),Cn();let s=await pt(r),i=!e.all&&!e.root;return{fixed:n.map(Gf),adoptionFlipped:i&&!o.adopted&&s.adopted}};import Xl from"node:fs";import Ql from"node:path";var mi="ik-mcp",Zl=(e,r)=>{let t=["--name",e];for(let o of r.env)t.push("--env",o);for(let o of r.unset)t.push("--unset",o);return t.push("--",r.command,...r.args),{type:"stdio",command:mi,args:t}};var Nn="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Uf=(e,r)=>Array.isArray(e)&&e.length===r.length&&e.every((t,o)=>t===r[o]),fi=e=>Cr(e)&&e.command===mi,Kf=(e,r)=>({...e??{},type:r.type,command:r.command,args:r.args}),Hf=(e,r,t)=>{let o=[],n={...e},s=!1;for(let[i,a]of Object.entries(r)){let c=Zl(i,a),p=e[i];if(p!==void 0&&!fi(p)){o.push({name:i,status:"conflict",message:`"${i}" is configured under mcp but .mcp.json already has a hand-written "${i}" server that is not ik-mcp \u2014 left it untouched. Remove that entry (or rename it) and ${Nn}, or drop mcp.${i} from infra-kit.json`});continue}if(fi(p)&&p.type===c.type&&Uf(p.args,c.args)){o.push({name:i,status:"unchanged",message:""});continue}if(t){n[i]=Kf(p,c),s=!0,o.push({name:i,status:"written",message:""});continue}o.push({name:i,status:"drifted",message:p===void 0?`"${i}" is configured under mcp in infra-kit.json but has no .mcp.json entry \u2014 the entry is generated from that config: ${Nn}`:`"${i}" in .mcp.json does not match its mcp.${i} config in infra-kit.json \u2014 infra-kit.json is the source and the .mcp.json entry is generated from it, so edit the config and regenerate: ${Nn}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(r,i)||!fi(a)||o.push({name:i,status:"stale",message:`"${i}" runs ik-mcp but there is no mcp.${i} in infra-kit.json \u2014 add it, or remove the entry: claude mcp remove ${i} --scope project`});return{entries:o,servers:n,changed:s}},zf=(e,r,t)=>{let o=t===null?ai:Gl(t),n=t===null||t.endsWith(`
|
|
174
174
|
`)?`
|
|
175
|
-
`:"";try{return Hl.mkdirSync(zl.dirname(e),{recursive:!0}),Hl.writeFileSync(e,`${JSON.stringify(r,null,o)}${n}`,"utf-8"),!0}catch(s){return l.warn(`Could not write ${e} (${ai(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},On=({projectRoot:e,proxies:r,write:t})=>{let o=zl.join(e,F),n=si(o);if(n.kind==="unreadable")return l.warn(`Could not read ${o} (${ai(n.error)}) \u2014 left it untouched.`),{status:"unreadable",path:o,entries:[],wrote:!1};let s=n.kind==="raw"?n.raw:null,i=s===null?{}:ii(s);if(!Cr(i))return l.warn(`Could not parse ${o} \u2014 left it untouched. Fix the JSON, then ${Dn}.`),{status:"unparseable",path:o,entries:[],wrote:!1};let a=i[me];if(a!==void 0&&!Cr(a))return l.warn(`${o} has a "${me}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:o,entries:[],wrote:!1};let c=Wf(a??{},r,t);if(!c.changed)return{status:"ok",path:o,entries:c.entries,wrote:!1};let p=Jf(o,{...i,[me]:c.servers},s);return{status:p?"ok":"failed",path:o,entries:c.entries,wrote:p}};var ql=async(e,r)=>{let t;try{t=(await E()).mcp}catch{return null}if(!t||Object.keys(t).length===0)return null;let o=On({projectRoot:e,proxies:t,write:r});if(o.status!=="ok"&&o.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${o.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let n=o.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=n.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:n.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:n.length===0}};var Vf=(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}))],Yl=async e=>{let r=(await E()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=dl(r);if(t.length>0){let d=t.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let o=ll(e),n=pl(e),s={api:o.map(d=>d.name),ui:n.map(d=>d.name)},{ctx:i,loadErrors:a}=await ml(e,r,s,o),c=Vf(ul(r,i),a),p=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:p,passed:c.length===0}};var Bf="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Gf=async e=>e.root?[{dir:await R(),baseline:_s,isRoot:!0}]:e.all?(await ne(await R())).map(t=>({dir:t})):[{dir:await so(e.cwd??Zl.cwd())}],Uf=async e=>e.root||e.all?await R():e.cwd??Zl.cwd(),Kf=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},Hf=async(e,r)=>{let{fixed:t,adoptionFlipped:o}=await Ul(e,r);return o&&l.info(Bf),t},zf=e=>{if(Ar(e).kind!=="stale")return null;let r=`${F} still registers "${T}", which shadows the plugin's copy of the server: sessions here use ${nr}* until the entry is deleted by hand in a PR (keep its siblings); after that they use ${Me}*`;return l.info(`[INFO] mcp mcp:legacy-key: ${r}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:r}],passed:!0}},Xl=async(e={})=>{let r=Fs(await Uf(e)),t=e.fix?await Hf(e,r):void 0,o=await Gf(e),n=await pt(r),s=[];for(let c of o)s.push(await Qs(c.dir,c.baseline,{adoption:n,isRoot:c.isRoot}));if(e.root){let c=await Yl(o[0].dir);c&&s.push(c);let p=await ql(o[0].dir,e.fix===!0);p&&s.push(p);let d=zf(o[0].dir);d&&s.push(d)}let a={allPassed:Kf(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}},qf={all:fe.boolean().optional().describe("Audit every non-vendor workspace package"),root:fe.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Yf={allPassed:fe.boolean().describe("Whether every audited package passed all checks"),packages:fe.array(fe.object({name:fe.string(),passed:fe.boolean(),checks:fe.array(fe.object({name:fe.string(),status:fe.enum(["pass","fail"]),message:fe.string()}))})).describe("Per-package check results")},ui=w({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:qf,outputSchema:Yf,handler:e=>Xl({all:e.all,root:e.root})});import{z as po}from"zod";var Ql=async()=>{let[e,r]=await Promise.all([E(),X()]),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}},Zf={config:po.record(po.string(),po.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:po.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:po.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},mi=w({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{},outputSchema:Zf,handler:()=>Ql()});import og from"node:fs";import{z as q}from"zod";import uo from"node:fs";import ht from"node:path";import Xf from"node:process";var Qf=ht.join(".infra-kit","dev-context"),eg=".infra-kit",ep=(e,r)=>{let t=ht.resolve(e);for(;;){let o=ht.join(t,r);if(uo.existsSync(o))return o;let n=ht.dirname(t);if(n===t)return;t=n}},rg=e=>{let r=ep(e,Qf);if(r)return r;let t=ep(e,eg);return t?ht.join(t,"dev-context"):void 0},fi=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Nn=e=>typeof e=="string"?e:"",tg=(e,r,t)=>{let o=ht.join(e,r);try{let n=uo.statSync(o),s=JSON.parse(uo.readFileSync(o,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:r.replace(/\.json$/,""),package:Nn(i.package),port:fi(i.port),alias:Nn(i.alias),origin:Nn(i.origin),release:Nn(i.release),pid:fi(i.pid),writtenAt:fi(i.writtenAt),mtimeMs:Math.round(n.mtimeMs),ageMs:Math.max(0,Math.round(t-n.mtimeMs))}}catch{return null}},gi=(e=Xf.cwd())=>{let r=Date.now(),t=rg(e);if(!t||!uo.existsSync(t))return{session:"none",fragmentDir:t,readAt:r,apps:[]};let o;try{o=uo.readdirSync(t).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:t,readAt:r,apps:[]}}let n=o.map(s=>tg(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 rp=async(e={})=>{let r=e.now??Date.now,t=e.isListening??zt,o=gi(e.cwd),n=r(),s=await Promise.all(o.apps.map(async u=>{let m=Math.max(0,Math.round((n-u.mtimeMs)/1e3)),v=await t(u.port);return{app:u.app,package:u.package,port:u.port,pid:u.pid,alias:u.alias,origin:u.origin,release:u.release,writtenAt:u.writtenAt>0?new Date(u.writtenAt).toISOString():null,fragmentMtime:new Date(u.mtimeMs).toISOString(),ageSeconds:m,live:v}})),i=s.length>0,a=o.fragmentDir??null,c=a!==null&&(og.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),p=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){l.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${p}:`);for(let u of s){let m=u.live?"live":"NOT responding",v=`written ${u.ageSeconds}s ago`;l.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${v}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";l.info(`No active infra-kit dev session \u2014 searched ${p} (${u}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},ng={active:q.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:q.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:q.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:q.array(q.object({app:q.string().describe("App folder name (the fragment filename without .json)."),package:q.string().describe("The app package name the vite helper reads to decide a local route."),port:q.number().describe("The actual bound port the dev server is listening on."),pid:q.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:q.string().describe("Registered portless hostname for the app."),origin:q.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:q.string().describe("Release slug the runner recorded for this worktree."),writtenAt:q.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:q.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:q.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:q.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.")},hi=w({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:ng,handler:()=>rp()});import{spawnSync as Cv}from"node:child_process";import B from"node:fs";import vd from"node:os";import U from"node:path";import Ot from"node:process";import{z as Q}from"zod";import{execFileSync as sg}from"node:child_process";var tp=(e,r)=>{let t=e.filter(o=>!o.live).map(o=>o.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},ig=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],ag=e=>ig.some(r=>r.test(e)),cg="/bin/ps",lg=()=>sg(cg,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
176
|
-
`),
|
|
175
|
+
`:"";try{return Xl.mkdirSync(Ql.dirname(e),{recursive:!0}),Xl.writeFileSync(e,`${JSON.stringify(r,null,o)}${n}`,"utf-8"),!0}catch(s){return l.warn(`Could not write ${e} (${pi(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Mn=({projectRoot:e,proxies:r,write:t})=>{let o=Ql.join(e,L),n=ci(o);if(n.kind==="unreadable")return l.warn(`Could not read ${o} (${pi(n.error)}) \u2014 left it untouched.`),{status:"unreadable",path:o,entries:[],wrote:!1};let s=n.kind==="raw"?n.raw:null,i=s===null?{}:li(s);if(!Cr(i))return l.warn(`Could not parse ${o} \u2014 left it untouched. Fix the JSON, then ${Nn}.`),{status:"unparseable",path:o,entries:[],wrote:!1};let a=i[me];if(a!==void 0&&!Cr(a))return l.warn(`${o} has a "${me}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:o,entries:[],wrote:!1};let c=Hf(a??{},r,t);if(!c.changed)return{status:"ok",path:o,entries:c.entries,wrote:!1};let p=zf(o,{...i,[me]:c.servers},s);return{status:p?"ok":"failed",path:o,entries:c.entries,wrote:p}};var ep=async(e,r)=>{let t;try{t=(await E()).mcp}catch{return null}if(!t||Object.keys(t).length===0)return null;let o=Mn({projectRoot:e,proxies:t,write:r});if(o.status!=="ok"&&o.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${o.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let n=o.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=n.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:n.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:n.length===0}};var qf=(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}))],rp=async e=>{let r=(await E()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=hl(r);if(t.length>0){let d=t.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let o=fl(e),n=gl(e),s={api:o.map(d=>d.name),ui:n.map(d=>d.name)},{ctx:i,loadErrors:a}=await yl(e,r,s,o),c=qf(vl(r,i),a),p=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:p,passed:c.length===0}};var Yf="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Zf=async e=>e.root?[{dir:await R(),baseline:Ns,isRoot:!0}]:e.all?(await ne(await R())).map(t=>({dir:t})):[{dir:await io(e.cwd??tp.cwd())}],Xf=async e=>e.root||e.all?await R():e.cwd??tp.cwd(),Qf=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},eg=async(e,r)=>{let{fixed:t,adoptionFlipped:o}=await Yl(e,r);return o&&l.info(Yf),t},rg=e=>{if(Ar(e).kind!=="stale")return null;let r=`${L} still registers "${T}", which shadows the plugin's copy of the server: sessions here use ${nr}* until the entry is deleted by hand in a PR (keep its siblings); after that they use ${Me}*`;return l.info(`[INFO] mcp mcp:legacy-key: ${r}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:r}],passed:!0}},op=async(e={})=>{let r=Js(await Xf(e)),t=e.fix?await eg(e,r):void 0,o=await Zf(e),n=await pt(r),s=[];for(let c of o)s.push(await ti(c.dir,c.baseline,{adoption:n,isRoot:c.isRoot}));if(e.root){let c=await rp(o[0].dir);c&&s.push(c);let p=await ep(o[0].dir,e.fix===!0);p&&s.push(p);let d=rg(o[0].dir);d&&s.push(d)}let a={allPassed:Qf(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}},tg={all:fe.boolean().optional().describe("Audit every non-vendor workspace package"),root:fe.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},og={allPassed:fe.boolean().describe("Whether every audited package passed all checks"),packages:fe.array(fe.object({name:fe.string(),passed:fe.boolean(),checks:fe.array(fe.object({name:fe.string(),status:fe.enum(["pass","fail"]),message:fe.string()}))})).describe("Per-package check results")},gi=w({name:"audit",description:"Audit packages against infra-kit.config.ts rules (config present and valid, required scripts, required files, and turbo tasks for the root). Defaults to the current package; all=true audits every non-vendor workspace package; root=true audits the monorepo root.",inputSchema:tg,outputSchema:og,handler:e=>op({all:e.all,root:e.root})});import{z as uo}from"zod";var np=async()=>{let[e,r]=await Promise.all([E(),X()]),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}},ng={config:uo.record(uo.string(),uo.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:uo.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:uo.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},hi=w({name:"config-get",description:"Return the fully merged infra-kit configuration (project + user-global + per-project override layers) as it is resolved at runtime. Read-only introspection \u2014 makes no changes; use `config edit` (CLI-only) to modify the per-machine override file (every key except `mcp`, which is project-layer only and refused there). Fails with the loader error when run outside a configured infra-kit repo, or when an override layer carries a refused key.",inputSchema:{},outputSchema:ng,handler:()=>np()});import pg from"node:fs";import{z as q}from"zod";import mo from"node:fs";import ht from"node:path";import sg from"node:process";var ig=ht.join(".infra-kit","dev-context"),ag=".infra-kit",sp=(e,r)=>{let t=ht.resolve(e);for(;;){let o=ht.join(t,r);if(mo.existsSync(o))return o;let n=ht.dirname(t);if(n===t)return;t=n}},cg=e=>{let r=sp(e,ig);if(r)return r;let t=sp(e,ag);return t?ht.join(t,"dev-context"):void 0},vi=e=>typeof e=="number"&&Number.isFinite(e)?e:0,jn=e=>typeof e=="string"?e:"",lg=(e,r,t)=>{let o=ht.join(e,r);try{let n=mo.statSync(o),s=JSON.parse(mo.readFileSync(o,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:r.replace(/\.json$/,""),package:jn(i.package),port:vi(i.port),alias:jn(i.alias),origin:jn(i.origin),release:jn(i.release),pid:vi(i.pid),writtenAt:vi(i.writtenAt),mtimeMs:Math.round(n.mtimeMs),ageMs:Math.max(0,Math.round(t-n.mtimeMs))}}catch{return null}},yi=(e=sg.cwd())=>{let r=Date.now(),t=cg(e);if(!t||!mo.existsSync(t))return{session:"none",fragmentDir:t,readAt:r,apps:[]};let o;try{o=mo.readdirSync(t).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:t,readAt:r,apps:[]}}let n=o.map(s=>lg(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 ip=async(e={})=>{let r=e.now??Date.now,t=e.isListening??qt,o=yi(e.cwd),n=r(),s=await Promise.all(o.apps.map(async u=>{let m=Math.max(0,Math.round((n-u.mtimeMs)/1e3)),v=await t(u.port);return{app:u.app,package:u.package,port:u.port,pid:u.pid,alias:u.alias,origin:u.origin,release:u.release,writtenAt:u.writtenAt>0?new Date(u.writtenAt).toISOString():null,fragmentMtime:new Date(u.mtimeMs).toISOString(),ageSeconds:m,live:v}})),i=s.length>0,a=o.fragmentDir??null,c=a!==null&&(pg.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),p=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){l.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${p}:`);for(let u of s){let m=u.live?"live":"NOT responding",v=`written ${u.ageSeconds}s ago`;l.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${v}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";l.info(`No active infra-kit dev session \u2014 searched ${p} (${u}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},dg={active:q.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:q.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:q.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:q.array(q.object({app:q.string().describe("App folder name (the fragment filename without .json)."),package:q.string().describe("The app package name the vite helper reads to decide a local route."),port:q.number().describe("The actual bound port the dev server is listening on."),pid:q.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:q.string().describe("Registered portless hostname for the app."),origin:q.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:q.string().describe("Release slug the runner recorded for this worktree."),writtenAt:q.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:q.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:q.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:q.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.")},ki=w({name:"dev-status",description:"Report what `infra-kit dev` currently has running by READING the on-disk dev-context fragments (never starts a server). Advisory + read-only: surfaces each app\u2019s package, bound port, portless alias, local origin, fragment freshness (mtime / ageSeconds), and a live TCP liveness probe of the port. The fragment directory is found by searching UPWARD from the working directory, so this agrees with the `infra-kit://dev-context` resource and with the vite helper\u2019s routing decision; `contextDir` / `contextDirExists` report where it looked and whether that directory is real. Returns { active: false, apps: [] } when no dev session is active.",inputSchema:{},outputSchema:dg,handler:()=>ip()});import{spawnSync as Nv}from"node:child_process";import B from"node:fs";import Rd from"node:os";import U from"node:path";import Nt from"node:process";import{z as Q}from"zod";import{execFileSync as ug}from"node:child_process";var ap=(e,r)=>{let t=e.filter(o=>!o.live).map(o=>o.name);return r?{prunable:[],withheld:t}:{prunable:t,withheld:[]}},mg=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],fg=e=>mg.some(r=>r.test(e)),gg="/bin/ps",hg=()=>ug(gg,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
176
|
+
`),cp=(e=hg)=>{try{return e().some(fg)}catch{return!0}};import{Chalk as vg}from"chalk";import wi from"node:process";var yg="Tools & CLIs",kg="Shell & integration",wg="Project config",bg="Doppler env tokens",Rg="Dev proxy (portless)",Pg="Claude Code plugin",Eg=`portless serving TLS on :${er}`,bi=[[yg,["brew installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","terminal installed","ide installed"]],[kg,["zshrc init block","zshenv session block","warm cache","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[wg,["infra-kit config valid","user override path","legacy user-global config"]],[bg,["tokens.json present","env tokens configured","env token valid","tokens.json perms"]],[Rg,["portless installed","portless service target",Eg,"portless CA chain valid","portless CA trusted","portless routes"]],[Pg,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","MCP server key"]]],lp="Other",xg=bi.map(([e])=>e),Sg=new Map(bi.flatMap(([e,r])=>r.map(t=>[t,e]))),VT=bi.flatMap(([,e])=>e),Ri=new Set(["portless routes","tokens.json perms"]),Tg=e=>{let r=new Map;for(let o of e){let n=Sg.get(o.name)??lp,s=r.get(n);s?s.push(o):r.set(n,[o])}return[...xg,lp].flatMap(o=>{let n=r.get(o);return n&&n.length>0?[{label:o,checks:n}]:[]})},pp={unicode:{pass:"\u2713",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{pass:"ok",fail:"!!",separator:"-",rule:"-"}},Cg=24,Ag=(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:[""]},up=e=>{let r=e.filter(t=>t.status==="fail").length;return{passed:e.length-r,failed:r}},$g=e=>{let r=new vg({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)}},Ig=(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}},vt=" ",dp=" ",_g=(e,r,t,o)=>{let n=up(e.checks),s=Ig(n,e.checks.length,r,t),i=Math.max(1,o-vt.length-e.label.length-s.plainWidth);return`${vt}${r.header(e.label)}${" ".repeat(i)}${s.text}`},Dg=(e,r,t,o,n)=>{let s=e.status==="fail",i=o.pass.length,a=s?o.fail:o.pass,c=e.name.padEnd(r),p=s?t.fail(a):t.pass(a),d=s?t.fail(c):c,u=dp.length+i+1+r+2,m=Math.max(Cg,n-u),[v,...f]=Ag(e.message,m),k=D=>s?D:t.dim(D);return[`${dp}${p} ${d} ${k(v??"")}`.trimEnd(),...f.map(D=>`${" ".repeat(u)}${k(D)}`)]},Og=(e,r,t,o)=>{let n=up(e),s=t.rule.repeat(Math.max(12,Math.min(o-vt.length,56))),i=e.filter(m=>m.status==="fail"&&Ri.has(m.name)).length,a=r.pass(`${n.passed} passed`),c=r.fail(`${n.failed} failed`),p=n.failed===0?a:`${a} ${t.separator} ${c}`,d=r.dim(`${i} fixable \u2014 run \`infra-kit doctor --fix\``),u=i>0?` ${d}`:"";return[`${vt}${r.dim(s)}`,`${vt}${p}${u}`]},Ng=(e,r={})=>{let t=r.color??!1,o=r.unicode??!0,n=r.width??80,s=$g(t),i=o?pp.unicode:pp.ascii;if(e.length===0)return[s.bold("infra-kit doctor"),"",`${vt}${s.dim("No checks ran.")}`];let a=Math.max(...e.map(p=>p.name.length)),c=Tg(e).flatMap(p=>[_g(p,s,i,n),...p.checks.flatMap(d=>Dg(d,a,s,i,n)),""]);return[s.bold("infra-kit doctor"),"",...c,...Og(e,s,i,n)]},Mg=new Set(["","0","false","none"]),jg=["LC_ALL","LC_CTYPE","LANG"],Fg=(e,r)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!Mg.has(e.FORCE_COLOR.toLowerCase()):!!r.isTTY,Lg=(e,r)=>{if(r)return!1;let t=jg.map(o=>e[o]).find(o=>o!==void 0&&o!=="");return t===void 0?!0:/UTF-?8/i.test(t)},Wg=(e={})=>{let r=e.env??wi.env,t=e.stream??wi.stderr;return{color:Fg(r,t),unicode:Lg(r,e.ascii??!1),width:t.columns??80}},Jg=(e,r={})=>{(r.write??(o=>{wi.stderr.write(o)}))(`${Ng(e,Wg(r)).join(`
|
|
177
177
|
`)}
|
|
178
|
-
`)};var
|
|
179
|
-
`).find(t=>t.startsWith("ExecStart="));return r===void 0?null:
|
|
180
|
-
`),yt=class extends
|
|
181
|
-
`)};import{$ as
|
|
182
|
-
`);import
|
|
183
|
-
`))};import
|
|
184
|
-
`),n.length===0)return l.info("No environments found."),l.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),l.info(" or add a token for one manually."),
|
|
185
|
-
`,384)}catch(t){l.debug(`warm-cache invalidate skipped: ${t.message}`)}};var
|
|
186
|
-
`).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),
|
|
178
|
+
`)};var Vg=e=>e.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"),Bg=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(r=>Vg(r[1])),Gg=e=>{let r=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return r===null?null:Bg(r[1])},Ug=e=>{let r=[],t="",o=!1,n=!1,s=!1,i=[...e];for(let[a,c]of i.entries()){if(s){s=!1;continue}if(c==='"'){o=!o,n=!0;continue}let p=i[a+1];if(c==="\\"&&(p==='"'||p==="\\")){t+=p,n=!0,s=!0;continue}if(/\s/.test(c)&&!o){n&&(r.push(t),t="",n=!1);continue}t+=c,n=!0}return n&&r.push(t),r},Kg=e=>{let r=e.split(`
|
|
179
|
+
`).find(t=>t.startsWith("ExecStart="));return r===void 0?null:Ug(r.slice(10))},mp=(e,r)=>{try{return e==="darwin"?Gg(r):e==="linux"?Kg(r):null}catch{return null}};import ah from"@inquirer/select";import{Buffer as ch}from"node:buffer";import lh from"node:fs";import ph from"node:path";import Dp from"node:process";import{z as ko}from"zod";import{$ as Wn}from"zx";var Hg="Could not find requested project",zg="Could not find requested config",fp="Invalid Auth token",gp="does not have access to requested config",fo=e=>e.includes(fp)||e.includes(gp)?"auth":e.includes(Hg)?"project":e.includes(zg)?"config":"unknown",go=e=>e.includes(gp)?"mis-scoped":e.includes(fp)?"revoked":null;var hp=e=>[`Doppler rejected the service token for env "${e}" \u2014 it is invalid, revoked, or scoped to a different config.`,`Fix: run \`infra-kit env-token-set ${e}\` with a token scoped to that config.`,"CI / agents: set INFRA_KIT_ENV_TOKEN to a token scoped to that config."].join(`
|
|
180
|
+
`),yt=class extends bn{authKind;constructor(r,t=null,o){super(o??hp(r),r),this.name="DopplerAuthError",this.authKind=t}};var Pi=({kind:e,project:r,config:t,available:o})=>{let n=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}".`];if(o&&o.length>0){let s=e==="project"?"Available projects":`Available configs in "${r}"`;n.push(`${s}: ${o.join(", ")}.`)}return n.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: pass an existing config, or create it in Doppler."),n.join(`
|
|
181
|
+
`)};import{$ as Fn}from"zx";var qg=5e3,Yg="DOPPLER_CONFIG",$r=async()=>{let{envManagement:e}=await E();return e.config.name},ho=async({childEnv:e,project:r,config:t})=>{let o=Fn.quiet;Fn.quiet=!0;try{let s=(await Fn({env:e})`doppler secrets get ${Yg} --plain --project ${r} --config ${t}`.timeout(qg)).stdout.trim();return s!==t?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(n){return{outcome:Zg(n)}}finally{Fn.quiet=o}},Zg=e=>{let r=mn(e)??(e instanceof Error?e.message:String(e));return fo(r)!=="auth"?"unreachable":go(r)??"unreachable"};import vp from"node:process";var G="INFRA_KIT_ENV_TOKEN",kt=async e=>{let r=vp.env[G];if(r)return{token:r,source:"env"};let o=(await te())?.envs[e];if(o)return{token:o,source:"store"};throw new bn(Xg(e,await Xt()),e)},tC=async e=>vp.env[G]?!0:!!(await te())?.envs[e],Xg=(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 ${G} instead \u2014 it takes precedence and needs no home config.`].join(`
|
|
182
|
+
`);import Tp from"node:process";import{z as xp}from"zod";import rh from"node:process";import{z as ir}from"zod";var yp=["prod"],wt={allowed:!1,reason:"disallow"},bt=e=>yp.includes(e),Qg=["dev","stage"],Rt=e=>Qg.includes(e)||bt(e),je=(e,r=wt)=>r.allowed?e:e.filter(t=>!bt(t)),Ir=(e,r,t=wt)=>{if(!t.allowed&&bt(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 Fe=async()=>{let e;try{e=(await E()).protectedEnvs??"disallow"}catch{return wt}return e==="disallow"?wt:e==="cli-only"&&j()?{allowed:!1,reason:"mcp-blocked"}:{allowed:!0,reason:"allowed"}};var vo=e=>{let{env:r,branch:t}=e;bt(r)&&l.warn([`\u26A0\uFE0F "${r}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${t}" ships ${r} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
|
|
183
|
+
`))};import kp from"node:fs/promises";import Ei from"node:path";import eh from"yaml";var wp=".github/workflows",Le=async e=>{let r=await R();return bp(Ei.resolve(r,wp,e))},xi=async()=>{let e=await R(),r=Ei.resolve(e,wp),t;try{t=await kp.readdir(r)}catch{return[]}let o=t.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),n=await Promise.all(o.map(s=>bp(Ei.resolve(r,s))));return[...new Set(n.flat())]},bp=async e=>{let r;try{r=eh.parse(await kp.readFile(e,"utf-8"))}catch{return[]}let t=Pt(r,"on")??Pt(r,"true"),o=Pt(Pt(Pt(Pt(t,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(o)?o.filter(n=>typeof n=="string"&&n.length>0):[]},Pt=(e,r)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[r]};var Et=async()=>{let e=await xi(),r=await te(),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]},_r=async()=>(await Et()).map(r=>r.env);var Ln=(e,r,t)=>e.map(({env:o,source:n})=>({env:o,source:n,hasToken:!!(t||r[o])})),Rp=["Environment","Source","Token"],th=e=>{let r=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),t=Rp.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(Rp),n,...r.map(o)]},Ep=async()=>{let e=await $r(),r=await Et(),t=await te(),o=rh.env[G],n=Ln(r,t?.envs??{},o);if(l.info(`Doppler project: ${e}
|
|
184
|
+
`),n.length===0)return l.info("No environments found."),l.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),l.info(" or add a token for one manually."),Pp({project:e,envs:n});for(let s of th(n))l.info(s);return Pp({project:e,envs:n})},Pp=({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}},Si=w({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:ir.string().describe("Detected Doppler project name"),configs:ir.array(ir.string()).describe("Every environment name known to this project"),tokens:ir.array(ir.object({env:ir.string().describe("Environment / Doppler config name"),source:ir.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:ir.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:Ep});var Sp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),oh=async e=>{try{return await e}catch{return[]}},nh=async e=>{let r=await te().catch(()=>null);return Ln(e,r?.envs??{},Tp.env[G]).filter(t=>!t.hasToken).map(t=>t.env)},Ti=()=>({get message(){return`Choose the environment to load into terminal session ${Tp.env[Ht]??`UNKNOWN \u2014 ${Ht} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>Sp(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await oh(Et());if(e.length===0)return l.info({msg:"Tool execution form options empty: env-load"}),null;let r=e.map(o=>o.env),t=await nh(e);return xp.object({config:xp.enum(r).describe(`The environment to load. ${t.length===0?"A service token is stored for every one of them.":`NO stored token for: ${t.join(", ")} \u2014 choosing one of those fails until you run \`infra-kit env-token-set <env>\`.`} The list is what env-list knows: workflow-declared environments first, then token-only ones.`)})},toArgs:(e,r)=>{let{config:t}=e;return typeof t!="string"||t.length===0?null:{...Sp(r)?r:{},config:t}}});import Cp from"node:fs";import{$ as sh}from"zx";import Dr from"node:fs";import yo from"node:path";var Ci=({autoLoaded:e,projectDir:r,canonicalProjectRoot:t})=>!e||!r||!t?!1:t===r,We=e=>{if(!e)return"";try{return Dr.realpathSync(e)}catch{return""}},Ai=(e,r)=>{try{let t=kr(e);Dr.mkdirSync(t,{recursive:!0,mode:448}),wr(yo.join(t,le),r,384)}catch(t){l.debug(`warm-cache write skipped: ${t.message}`)}},$i=(e=Date.now(),r=Kt)=>{let t=Mc(),o;try{o=Dr.readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of o){if(!n.isDirectory())continue;let s=yo.join(t,n.name);try{let{mtimeMs:i}=Dr.statSync(yo.join(s,le));e-i>=r*1e3&&Dr.rmSync(s,{recursive:!0,force:!0})}catch{}}},Ii=(e,r)=>{try{let t=kr(e);if(r){Dr.rmSync(t,{recursive:!0,force:!0});return}if(!Dr.existsSync(yo.join(t,le)))return;wr(yo.join(t,sn),`# infra-kit warm cache cleared
|
|
185
|
+
`,384)}catch(t){l.debug(`warm-cache invalidate skipped: ${t.message}`)}};var Ap=e=>e.split(`
|
|
186
|
+
`).filter(r=>r.startsWith("worktree ")).map(r=>r.slice(9).trim()).filter(Boolean),ih=async()=>{let e;try{e=(await sh({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 Ap(e)){let o=We(t);if(!o)continue;let n=kr(o);try{if(!Cp.existsSync(n))continue;Cp.rmSync(n,{recursive:!0,force:!0}),r.push(n)}catch(s){l.debug(`warm-cache purge skipped for ${n}: ${s.message}`)}}return r};var dh=e=>e?[`${yr}=${Or("1")}`]:[`unset ${yr}`,`unset ${tt}`],uh="DOPPLER_CONFIG",$p=new Set(["DOPPLER_TOKEN",G]),Ip=!1,mh=e=>{e.length===0||Ip||(Ip=!0,l.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Op=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:n,autoLoaded:s})=>{let i=e.filter(([a])=>!$p.has(a));return mh(e.filter(([a])=>$p.has(a)).map(([a])=>a)),["set -a",...i.map(([a,c])=>`${a}=${Or(c)}`),`${an}=${Or(r)}`,`${Qr}=${Or(r)}`,`${et}=${Or(t)}`,`${cn}=${Or(o)}`,`${rt}=${Or(n)}`,...dh(s),"set +a"]},fh=async()=>{try{return await R()}catch{return""}},Np=async({config:e,autoLoaded:r=!1,beforeWrite:t,projectDir:o})=>{let n=await $r(),s=await fh(),i=await vh(n,e),a=new Date().toISOString(),p=`${Op({pairs:i,config:e,project:n,projectRoot:s,loadedAt:a,autoLoaded:r}).join(`
|
|
187
187
|
`)}
|
|
188
|
-
`,d=ot(),u=
|
|
189
|
-
Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},
|
|
188
|
+
`,d=ot(),u=ph.resolve(d,le);if(t&&!t())return null;lh.mkdirSync(d,{recursive:!0,mode:448}),wr(u,p,384);let m=We(s);return Ci({autoLoaded:r,projectDir:o,canonicalProjectRoot:m})&&(Ai(o,p),$i()),{filePath:u,variableCount:i.length,project:n,config:e}},Mp=async e=>{let{config:r}=e,t="";if(r)t=r;else{if(j())throw new g(void 0,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await _r();h.setInteractive(),t=await A(i=>ah({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:Dp.stderr,whenHeadless:"refuse"})}h.addOption("--config",t);let o=await Np({config:t,autoLoaded:!1});if(!o)throw new Error("env-load: write was unexpectedly aborted");h.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config};return{content:y(JSON.stringify(n,null,2)),structuredContent:n}},_p=1024*1024,gh=3e4,hh=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],xt=(e,r=Dp.env)=>{let t={...r};for(let o of hh)delete t[o];return t.DOPPLER_TOKEN=e,t},vh=async(e,r)=>{let{token:t}=await kt(r),o=xt(t),n=Wn.quiet;Wn.quiet=!0;try{let s;try{s=await Wn({env:o})`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(gh)}catch(a){throw yh(a,e,r)}kh(s.stdout);let i=Fp(s.stdout);return jp(i,r),i}finally{Wn.quiet=n}},jp=(e,r)=>{let t=e.find(([o])=>o===uh)?.[1];if(!(t===void 0||t===r))throw new yt(r,null,`Doppler returned secrets for config "${t}" but "${r}" was requested \u2014 the service token for env "${r}" is scoped to the wrong config. Refusing to load another environment's secrets.
|
|
189
|
+
Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},yh=(e,r,t)=>{let o=mn(e)??(e instanceof Error?e.message:String(e)),n=fo(o);return n==="auth"?new yt(t,go(o)):n==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(Pi({kind:n,project:r,config:t,available:null}))},kh=e=>{let r=ch.byteLength(e,"utf-8");if(r>_p)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${_p}) \u2014 refusing to write to disk`)},Or=e=>`'${e.replaceAll("'","'\\''")}'`,wh=/^[A-Z_]\w*$/i,Fp=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(!wh.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},_i=w({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess.',inputSchema:{config:ko.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Ti(),outputSchema:{filePath:ko.string().describe("Path to the file that must be sourced to apply variables"),variableCount:ko.number().describe("Number of variables loaded"),project:ko.string().describe("Doppler project name"),config:ko.string().describe("Doppler config name")},handler:Mp});import bh from"node:fs";import Rh from"node:os";import Ph from"node:path";var Eh="infra-kit.json",xh="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)",Sh="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",wo=async()=>{let e;try{e=await R()}catch{return null}let r=e.trim();return r===""||r===Rh.homedir()?null:r},Lp=async()=>{let e=await wo();return e===null&&l.info(xh),e},Th=async()=>{let e=await wo();return e===null?null:bh.existsSync(Ph.join(e,Eh))?e:(l.info(Sh),null)};var Ch=async e=>{try{return await ne(e)}catch(r){return l.debug({err:r,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Wp=async()=>{let e=await Th(),r=H.version;if(e===null)return{skipped:!0,root:null,version:r,written:[]};let t=[...await co(e,{version:r})];for(let o of await Ch(e)){let n=await oo(o);t.push(...await lo(o,{repoRoot:e,version:r,declaredType:n}))}return{skipped:!1,root:e,version:r,written:t}};import se from"node:fs";import Li from"node:os";import he from"node:path";import Wi from"node:process";import Vn from"node:fs/promises";import Ah from"node:path";import $h from"node:process";var Jp=` // "envManagement": { // required in layer 1; provider-tagged
|
|
190
190
|
// "provider": "doppler",
|
|
191
191
|
// "config": { "name": "my-doppler-project" }
|
|
192
192
|
// },
|
|
@@ -308,7 +308,7 @@ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},dh=(
|
|
|
308
308
|
// // also fixes its modes), or by hand: both are supported, which is why the store carries no
|
|
309
309
|
// // repo-identity field and no mandatory version. Pasting a token into an
|
|
310
310
|
// // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
|
|
311
|
-
// // the token first, because a config file can be committed, backed up by your editor, or shared
|
|
311
|
+
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,Di=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
|
|
312
312
|
//
|
|
313
313
|
// Merge chain (later layers override earlier ones at top-level keys):
|
|
314
314
|
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
@@ -329,9 +329,9 @@ Fix: run \`infra-kit env-token-set ${r}\` with a token scoped to "${r}".`)},dh=(
|
|
|
329
329
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
330
330
|
// user-global layer \u2014 it is shown here only to document the full, valid config shape.
|
|
331
331
|
{
|
|
332
|
-
${
|
|
332
|
+
${Jp}
|
|
333
333
|
}
|
|
334
|
-
`,
|
|
334
|
+
`,Oi=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
335
335
|
//
|
|
336
336
|
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
|
|
337
337
|
// <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
|
|
@@ -348,9 +348,9 @@ ${Mp}
|
|
|
348
348
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
349
349
|
// override layer \u2014 it is shown here only to document the full, valid config shape.
|
|
350
350
|
{
|
|
351
|
-
${
|
|
351
|
+
${Jp}
|
|
352
352
|
}
|
|
353
|
-
`,
|
|
353
|
+
`,Ni=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
|
|
354
354
|
//
|
|
355
355
|
// Machine-local registry the vendor commands (sync/manifest/diff) read to know
|
|
356
356
|
// where your project repos live and which ones to stamp. This .example.jsonc is
|
|
@@ -361,83 +361,83 @@ ${Mp}
|
|
|
361
361
|
// "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
|
|
362
362
|
// "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
|
|
363
363
|
}
|
|
364
|
-
`;var
|
|
365
|
-
`,"utf-8");let n=
|
|
364
|
+
`;var Vp=!1,Ih=e=>e.replace(/\.json$/,".example.jsonc"),_h=async e=>{try{return await Vn.readFile(e,"utf-8")}catch{return null}},Bn=async e=>{let r=e.userProject,t=Ih(r);await Vn.mkdir(Ah.dirname(r),{recursive:!0});let o=!await ke(r);o&&await Vn.writeFile(r,`{}
|
|
365
|
+
`,"utf-8");let n=Oi(e.projectName),s=await _h(t)!==n;return s&&await Vn.writeFile(t,n,"utf-8"),o&&ml(),{configPath:r,examplePath:t,createdConfig:o,refreshedExample:s}},Gn=e=>`Created ${b(e.configPath)} \u2014 see ${b(e.examplePath)} for the annotated reference.`,Dh=async()=>{if($h.env.INFRA_KIT_NO_SEED||Vp)return;Vp=!0;let e;try{e=await X()}catch{return}if(await ke(e.main))try{let r=await Bn(e);r.createdConfig?l.info(Gn(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 ge from"node:fs/promises";import $e from"node:path";import{pathToFileURL as Mh}from"node:url";import jh from"yaml";import{z as Up}from"zod";import Oh from"node:fs/promises";import Mi from"node:os";import ji from"node:path";import{z as Nh}from"zod";import{z as Un}from"zod";var Bp="vendor.json",Kn=Un.object({workspaceDir:Un.string().min(1),targets:Un.array(Un.string()).min(1)}).strict();var Fi=()=>ji.join(Mi.homedir(),Nc,Bp),h$=e=>{if(e==="~")return Mi.homedir();if(e.startsWith("~/"))return ji.join(Mi.homedir(),e.slice(2));if(ji.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},v$=async()=>{let e=Fi(),r;try{r=await Oh.readFile(e,"utf-8")}catch{throw new Error(`Factory config not found at ${e}. infra-kit needs a machine-local factory registry to know where your project repos live and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
|
|
366
366
|
|
|
367
367
|
{
|
|
368
368
|
"workspaceDir": "~/projects",
|
|
369
369
|
"targets": ["my-repo"]
|
|
370
370
|
}
|
|
371
|
-
`)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in vendor.json at ${e}: ${n.message}`)}let o=
|
|
372
|
-
`,"utf-8"),await ge.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&&st()},
|
|
373
|
-
`,"utf-8"),await ge.rm(t,{force:!0}),p?l.info(`\u26A0 Migrated ${b(t)} \u2192 ${b(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${b(e)} directly to change them.`):l.info(`\u2713 Migrated ${b(t)} \u2192 ${b(e)}`)}catch(s){l.info(`\u26A0 Skipped ${b(t)} \u2014 ${s.message}`)}}},
|
|
374
|
-
`,"utf-8"),l.info(`\u2713 Normalized ide config in ${b(o)} (removed legacy "mode")`),t++}catch(n){l.info(`\u26A0 Skipped normalizing ${b(o)} \u2014 ${n.message}`)}t>0&&st()};var Nr="# -- infra-kit:begin --",ar="# -- infra-kit:end --",
|
|
375
|
-
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`,level:"info"})},
|
|
376
|
-
`)[0]??o})`,level:"warn"}]}return!r||Object.keys(r).length===0?[]:
|
|
377
|
-
`),s=0;for(;s<n.length&&
|
|
371
|
+
`)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in vendor.json at ${e}: ${n.message}`)}let o=Kn.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${Nh.prettifyError(o.error)}`);return o.data};var Gp=e=>e.replace(/\.json$/,".yml"),Kp=async()=>{let e;try{e=await X()}catch{return}let r=[{label:"infra-kit.json",yml:Gp(e.main),json:e.main,schema:ul},{label:"~/.infra-kit/infra-kit.json",yml:$e.join($e.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:As},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Gp(e.userProject),json:e.userProject,schema:As}],t=0;for(let o of r){let[n,s]=await Promise.all([ke(o.yml),ke(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 ge.readFile(o.yml,"utf-8"),a=jh.parse(i)??{},c=o.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${b(o.yml)} \u2014 invalid config: ${Up.prettifyError(c.error)}`);continue}await ge.mkdir($e.dirname(o.json),{recursive:!0}),await ge.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
|
|
372
|
+
`,"utf-8"),await ge.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&&st()},Hp=async()=>{let e;try{e=await X()}catch{return}let r=$e.dirname(e.userGlobal),t=[{from:$e.join(r,"config.json"),to:e.userGlobal},{from:$e.join(r,"config.example.jsonc"),to:$e.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:n,to:s}of t){let[i,a]=await Promise.all([ke(n),ke(s)]);if(i){if(a){l.info(`\u26A0 Skipped ${b(n)} \u2014 ${b(s)} already exists (remove the stale file manually)`);continue}try{await ge.mkdir($e.dirname(s),{recursive:!0}),await ge.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&&st()},zp=async()=>{let e=Fi(),r=$e.dirname(e),t=$e.join(r,"vendor.config.ts"),[o,n]=await Promise.all([ke(t),ke(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 ge.stat(t),c=(await import(`${Mh(t).href}?mtime=${Number(s.mtimeMs)}`)).default,p=typeof c=="function",d=p?await c():c,u=Kn.safeParse(d);if(!u.success){l.info(`\u26A0 Skipped ${b(t)} \u2014 invalid factory config: ${Up.prettifyError(u.error)}`);return}await ge.mkdir(r,{recursive:!0}),await ge.writeFile(e,`${JSON.stringify(u.data,null,2)}
|
|
373
|
+
`,"utf-8"),await ge.rm(t,{force:!0}),p?l.info(`\u26A0 Migrated ${b(t)} \u2192 ${b(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${b(e)} directly to change them.`):l.info(`\u2713 Migrated ${b(t)} \u2192 ${b(e)}`)}catch(s){l.info(`\u26A0 Skipped ${b(t)} \u2014 ${s.message}`)}}},Fh=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}},qp=async()=>{let e;try{e=await X()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await ke(o))try{let n=await ge.readFile(o,"utf-8");if(n.trim()==="")continue;let s=JSON.parse(n),{changed:i,result:a}=Fh(s);if(!i)continue;await ge.writeFile(o,`${JSON.stringify(a,null,2)}
|
|
374
|
+
`,"utf-8"),l.info(`\u2713 Normalized ide config in ${b(o)} (removed legacy "mode")`),t++}catch(n){l.info(`\u26A0 Skipped normalizing ${b(o)} \u2014 ${n.message}`)}t>0&&st()};var Nr="# -- infra-kit:begin --",ar="# -- infra-kit:end --",Lh=[["# region infra-kit","# endregion infra-kit"]],Wh="# infra-kit shell functions",St=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},bo="Run `source ~/.zshrc` or open a new terminal to activate.",Jh={step:"migrations",outcome:"skipped",message:"Config migrations checked (legacy yml layers, ide structure, user-global filename, factory config)",level:"silent"},Je=async(e,r)=>{try{return await r()}catch(t){throw new St(e,t)}},Ji=async e=>{let r=[],t=(...s)=>{for(let i of s)r.push(i),e?.(i)};await Je("zshrc",()=>{t(Vh())}),await Je("zshenv",()=>{t(Bh())}),await Je("migrations",async()=>{await Gh(),t(Jh)}),await Je("user-config",()=>{t(Kh())});let o=await Je("guidance",async()=>{let{entries:s,root:i}=await qh();return t(...s),i}),n=await Je("plugin-pointer",async()=>Lp());return t(...Xh(n,o)),await Je("plugin-pointer",async()=>{await ov(n,t)}),await Je("mcp-proxies",async()=>{t(...await sv(n))}),await Je("project-config",async()=>{t(...await Hh())}),t(...Uh()),r},zn=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)}},Vh=()=>{let e=he.join(Li.homedir(),".zshrc"),r=se.existsSync(e)?av(se.readFileSync(e,"utf-8")):"",t=ct({content:r,body:Zp(),startMarker:Nr,endMarker:ar,placement:"append-end"});return se.writeFileSync(e,t),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},Bh=()=>{let e=he.join(Li.homedir(),".zshenv"),r=se.existsSync(e)?se.readFileSync(e,"utf-8"):"",t=ct({content:r,body:Vi(),startMarker:Nr,endMarker:ar});return se.writeFileSync(e,t),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},Gh=async()=>{await Kp(),await qp(),await Hp(),await zp()},Uh=()=>{let e=Wi.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:bo,level:"info"}),r},Kh=()=>{let e=he.join(Li.homedir(),".infra-kit"),r=he.join(e,"infra-kit.json");return se.mkdirSync(e,{recursive:!0}),se.writeFileSync(he.join(e,"infra-kit.example.jsonc"),Di(),"utf-8"),se.writeFileSync(he.join(e,"vendor.example.jsonc"),Ni(),"utf-8"),se.existsSync(r)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${r} (refreshed reference examples)`,level:"info"}:(se.writeFileSync(r,`{}
|
|
375
|
+
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`,level:"info"})},Hh=async()=>{if(Wi.env.INFRA_KIT_NO_SEED)return[Hn("INFRA_KIT_NO_SEED is set")];try{let e=await X();if(!se.existsSync(e.main))return[Hn(`no project config at ${e.main}`)];let r=await Bn(e);return r.createdConfig?[{step:"project-config",outcome:"written",message:Gn(r),level:"info"}]:[Hn("the user-project config was already present")]}catch(e){return l.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[Hn(e instanceof Error?e.message:String(e))]}},Hn=e=>({step:"project-config",outcome:"skipped",message:`Skipped seeding the user-project config \u2014 ${e}`,level:"silent"}),zh=(e,r,t)=>{let o=[];for(let s of t){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;o.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${he.relative(e,s.path)}${i}`,level:"info"})}o.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${r})`,level:"info"});let n=t.filter(s=>s.action==="failed");return n.length===0||o.push({step:"guidance",outcome:"warned",message:`${n.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),o},qh=async()=>{let{skipped:e,root:r,version:t,written:o}=await Wp();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:zh(r,t,o)}},Yh=(e,r)=>{let t=he.relative(e,r.path);return r.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${t} (Claude Code plugin pointer)`,level:"info"}:r.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${t} \u2014 added ${r.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:r.status==="unchanged"?"unchanged":"warned",message:`${t} \u2014 ${r.status}`,level:"silent"}},Zh=(e,r)=>{let t=L;return r.kind==="stale"?{step:"mcp-server",outcome:"unchanged",message:` ${t} still registers the "${T}" MCP server, which shadows the plugin's copy (same key, project scope wins): sessions here use ${nr}* and the guidance they read names that prefix \u2014 nothing to fix on this machine. To move this repo to the plugin's ${Me}* route, delete the "${T}" entry from ${t} by hand in a PR, keeping its siblings`,level:"info"}:r.kind==="wrong-key"?{step:"mcp-server",outcome:"warned",message:`${t} registers an infra-kit server under "${r.key}" \u2014 a second server process whose tools carry that key as their prefix, which no served guidance names. Remove that entry by hand; the plugin serves the server under "${T}"`,level:"warn"}:r.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${me} from ${he.join(e,L)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: served by the Claude Code plugin (${r.kind==="absent"?`${t} carries no "${T}" key`:`no ${t}`})`,level:"info"}},Xh=(e,r)=>e===null||r!==null?[]:[{step:"plugin-pointer",outcome:"warned",message:`No infra-kit.json at ${e} \u2014 setting up Claude Code there anyway: writing .claude/settings.json and installing the ${F} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],Qh=()=>[di,Ae].map(e=>({step:"plugin-pointer",outcome:"skipped",message:e,level:"info"})),ev=e=>({step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${H.version} is behind ${e.latestVersion}, update it first: ${dn(e.updateCommand)}`:`CLI ${H.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"}),rv=(e,r)=>e.status==="skipped-cli-stale"?[ev(r)]:e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${F} up to date (project scope)`,level:"info"}]:e.status==="update-failed"?[{step:"plugin-pointer",outcome:"warned",message:`Could not update the Claude Code plugin \u2014 ${e.error}. Run by hand: ${sr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${F} (project scope)`,level:"info"}]:e.status==="claude-missing"?[{step:"plugin-pointer",outcome:"skipped",message:"No `claude` on PATH, so the Claude Code plugin was not installed. Install Claude Code, then run:",level:"info"},...Qh()]:[{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: ${Ae}`,level:"warn"}],Yp={stale:!1},tv=async()=>{let e=eo(),r=e===null?await Is(Wi.env):e.latestVersion;return r===null||!_s(r,H.version)?Yp:{stale:!0,latestVersion:r,updateCommand:e?.updateCommand??Fc(r)}},ov=async(e,r)=>{if(e===null){r({step:"plugin-pointer",outcome:"skipped",message:"Claude Code plugin steps skipped \u2014 no git root safe to write into",level:"silent"});return}try{r(Yh(e,ui(he.join(e,".claude","settings.json"))));let o=Qe({projectPath:e}).kind==="installed"?await tv():Yp;r(...rv(ii({projectRoot:e,cliIsStale:()=>o.stale}),o)),r(Zh(e,Ar(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: ${Ae}`,level:"warn"})}},nv=(e,r)=>{let t=he.relative(e,r.path);if(r.status!=="ok"&&r.status!=="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${t} could not be read as JSON \u2014 ik-mcp entries not synced`,level:"warn"}];if(r.status==="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${t} could not be written \u2014 ik-mcp entries not synced`,level:"warn"}];let o=[];for(let n of r.entries)n.status==="written"?o.push({step:"mcp-proxies",outcome:"written",message:` updated ${t} \u2014 ik-mcp "${n.name}"`,level:"info"}):(n.status==="conflict"||n.status==="stale")&&o.push({step:"mcp-proxies",outcome:"warned",message:` ${n.message}`,level:"warn"});return o},sv=async e=>{if(e===null)return[];if(!se.existsSync(he.join(e,"infra-kit.json")))return[{step:"mcp-proxies",outcome:"skipped",message:"no infra-kit.json \u2014 no ik-mcp entries to derive",level:"silent"}];let r;try{r=(await E()).mcp}catch(t){let o=t instanceof Error?t.message:String(t);return[{step:"mcp-proxies",outcome:"skipped",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o.split(`
|
|
376
|
+
`)[0]??o})`,level:"warn"}]}return!r||Object.keys(r).length===0?[]:nv(e,Mn({projectRoot:e,proxies:r,write:!0}))},iv=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"),av=e=>{let r=or(e,Nr,ar);if(r!==null)return r;for(let[a,c]of Lh){let p=or(e,a,c);if(p!==null)return p}let t=e.indexOf(Wh);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
|
|
377
|
+
`),s=0;for(;s<n.length&&iv(n[s]);)s++;let i=n.slice(s).join(`
|
|
378
378
|
`);return o+(i?`
|
|
379
|
-
${i}`:"")},
|
|
380
|
-
`)},
|
|
381
|
-
${
|
|
382
|
-
${ar}`,
|
|
383
|
-
`),
|
|
384
|
-
${
|
|
385
|
-
${ar}`;import
|
|
386
|
-
${r.stderr}`}},resolveBinPath:async e=>{let r=await
|
|
387
|
-
`,1)[0].trim();return t.length>r?`${t.slice(0,r)}\u2026`:t},
|
|
388
|
-
`);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},Be=async()=>{try{return await It()}catch(e){return l.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var
|
|
389
|
-
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:L(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Sv=async()=>{let e=await Ev({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return xv(e.stdout)},Tv=async()=>{let e=await Be();return e?(await At(e)).map(t=>t.name):[]},na=async()=>{let[e,r]=await Promise.allSettled([Sv(),Tv()]);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"),Qi({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Av=["brew","gh","doppler","aws"],$v=async e=>{let r=await xo(Av,e);return new Map(r.map(t=>[t.id,{manager:t.manager,version:t.version,present:t.present,onPath:t.onPath}]))},Ge=async(e,r,t,o)=>{try{return await Mr()`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},yd=(e,r,t,o)=>{let n=U.join(vd.homedir(),r),s="Run: infra-kit setup --skip-tools";if(!B.existsSync(n))return{name:e,status:"fail",message:`~/${r} not found. ${s}`};let i=B.readFileSync(n,"utf-8"),a=i.indexOf(Nr),c=i.indexOf(ar);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${t} block missing from ~/${r}. ${s}`}:i.slice(a,c+ar.length).trim()!==o.trim()?{name:e,status:"fail",message:`infra-kit ${t} block in ~/${r} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${t} block in ~/${r} is up to date`}},Iv=()=>yd("zshrc init block",".zshrc","shell",Hp()),_v=()=>yd("zshenv session block",".zshenv","session-env",Wi()),Dv=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=We(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let o=U.join(kr(t),le);if(!B.existsSync(o))return{name:e,status:"pass",message:"warm cache: none yet (populated on next auto-load)"};let n=Math.floor((Date.now()-B.statSync(o).mtimeMs)/1e3),s=Math.floor(n/60),i=Math.floor(Ut/60);return n>=Ut?{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`}},Ov=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await R(),t=U.join(r,"pnpm-workspace.yaml");if(!B.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=B.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}`}}},Nv=async()=>{try{return st(),{config:await E(),error:null}}catch(e){return{config:null,error:e}}},Mv=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)"}},jv=384,sa=448,Fv=e=>e.map(r=>{let t=r.source===null?"no token":`token (${r.source})`;return`${r.env}: ${t}`}).join(", "),Lv=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}}})),Wv=async(e,r={})=>{let t="env tokens configured",o=r.readStore??te,n=r.resolveToken??kt;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 _r(),a=e.config.envAutoLoad?.config,c=a&&!i.includes(a)?[...i,a]:i,p=await Lv(c,n),d=Fv(p);if(a===void 0)return{name:t,status:"pass",message:`No envAutoLoad configured \u2014 no env is load-bearing. ${d}`};let u=p.find(m=>m.env===a);return!u||u.source===null?s===null||Object.keys(s.envs).length===0?{name:t,status:"pass",message:"Skipped \u2014 there is no token store to read (see tokens.json present)"}:{name:t,status:"fail",message:`No Doppler service token for the auto-load env "${a}" \u2014 your shell env will not load. Fix: run \`infra-kit env-token-set ${a}\`. ${d}`}:{name:t,status:"pass",message:`auto-load env "${a}": token (${u.source}). ${d}`}},Jv={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)"}},Vv=async(e,r={})=>{let t="env token valid",o=r.resolveToken??kt,n=r.probe??go;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:xt(i),project:a,config:s}),p=Jv[c.outcome],d=c.outcome==="revoked"||c.outcome==="mis-scoped"?` Fix: run \`infra-kit env-token-set ${s}\` with a token scoped to "${s}".`:"";return{name:t,status:p.status,message:`The token for env "${s}" (project "${a}") is ${p.describe}.${d}`}},Bv=()=>Ot.env[G]||void 0,Gv=async(e={})=>{let r="tokens.json present",t=e.readStore??te,o=e.storePath??Zt;if((e.readEnvToken??Bv)())return{name:r,status:"pass",message:`Skipped \u2014 ${G} 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 ${G} instead.`}}return{name:r,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Co=(e,r)=>{let t=r(e);return t===null?null:t.mode&511},Uv=async(e,r={})=>{let t="tokens.json perms",o=r.storePath??Zt,n=r.statPath??Kv,s=r.chmodPath??B.chmodSync,i;try{i=await o()}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(Co(i,n)===null)return{name:t,status:"pass",message:`No store to protect at ${b(i)} (see tokens.json present)`};let a=U.dirname(i),c=U.dirname(a),p=U.dirname(c),u=[{target:p,expected:sa,actual:Co(p,n)},{target:c,expected:sa,actual:Co(c,n)},{target:a,expected:sa,actual:Co(a,n)},{target:i,expected:jv,actual:Co(i,n)}].filter(v=>v.actual!==null&&v.actual!==v.expected);if(u.length===0)return{name:t,status:"pass",message:`${b(i)} is 0600 (0700 dirs)`};let m=u.map(v=>`${b(v.target)} is ${pd(v.actual)}, expected ${pd(v.expected)}`).join("; ");if(!e)return{name:t,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let v of u)s(v.target,v.expected);return{name:t,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},pd=e=>`0${e.toString(8).padStart(3,"0")}`,Kv=e=>{try{return B.statSync(e)}catch{return null}},Hv=async()=>{let e="user override path";try{let r=await X(),t=B.existsSync(r.userProject),o=await Ji(r.userProject,t),n=t?Vi(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}}},zv=async()=>{let e="legacy user-global config",r;try{r=await X()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=U.join(U.dirname(r.userGlobal),"config.json");return B.existsSync(t)?B.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"}},qv={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/"}},Yv=async e=>{let r=qv[e];try{return await Mr()`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},Zv=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=Ee(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=>Yv(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("; ")}},dd=/^\d+\.\d+\.\d+$/,Xv=(e,r)=>e===r||!dd.test(e)||!dd.test(r)?!1:_t([`v${e}`,`v${r}`])[0]===`v${e}`,Qv=async(e,r)=>{let t;try{t=await ne(e)}catch{return[]}let o=[];for(let n of t){let s=xr(Sr(U.join(n,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&Xv(s.version,r)&&o.push(s.version)}return o},ey=async(e,r)=>{let t=await Qv(e,r);if(t.length===0)return"";let o=_t(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`},ry=async()=>{let e;try{e=(await X()).main}catch{return[]}if(!B.existsSync(e))return[];let r=U.dirname(e),t=U.join(r,"CLAUDE.md"),o=B.existsSync(t)?B.readFileSync(t,"utf-8"):"",n=Se(o,ue,Te),s=n?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",i=await ey(r,H.version);return[{name:"CLAUDE.md block",status:n?"pass":"fail",message:`${s}${i}`}]},ty=async()=>{try{let e=(await X()).main;return B.existsSync(e)?U.dirname(e):null}catch{return null}},oy=e=>{let r=il();return r===null||!Xt(r,e)?"":` \u2014 plugin ${r} is fetched but not applied. Run: ${sr}`},ny=e=>{let r=e.kind==="installed"?yn(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 ${j} version ${r}${oy(r)}`}},ud=3,md=(e,r)=>pe(e)===pe(r),sy=e=>{if(e===void 0||e.gitRoot===null)return"";let r=b(e.gitRoot);if(e.projectDir!==null){if(md(e.projectDir,e.gitRoot))return"";let t=Ht(e.gitRoot,pe(e.projectDir),pe)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${b(e.projectDir)}, ${t}: the plugin and this repo's .claude/settings.json hooks load only from ${r} (measured); restart Claude Code there`}return md(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${b(e.cwd)} rather than ${r}, it loaded neither the plugin nor this repo's hooks; launch it at ${r}`},iy=(e,r)=>{let t="plugin installed",o=sy(r);if(e.kind==="installed"){let{scope:c,projectPath:p}=e.installation,d=p===null?"":`, ${b(p)}`;return{name:t,status:"pass",message:`Plugin ${j} installed (${c??"unknown"} scope${d})${o}`}}if(e.kind==="absent")return{name:t,status:"fail",message:`Plugin ${j} is not installed. Run: ${Ae}${o}`};let n=e.installations.map(c=>c.projectPath===null?"(unnamed project)":b(c.projectPath)),s=n.length-ud,i=s>0?` and ${s} more`:"",a=`${n.slice(0,ud).join(", ")}${i}`;return{name:t,status:"fail",message:`Plugin ${j} is installed for ${a} only, not this project. Run: ${Ae}${o}`}},ay=()=>Ge("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),fd=(e,...r)=>{try{return JSON.parse(B.readFileSync(U.join(e,...r),"utf-8"))}catch{return null}},kd=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let r=yn(e.installation),{installPath:t}=e.installation;if(t===null)return{kind:"no-server",version:r};let o=fd(t,F),n=o!==null&&typeof o=="object"?o[me]:void 0;if(n==null||typeof n!="object")return{kind:"no-server",version:r};let s=fd(t,".claude-plugin","plugin.json"),i=s!==null&&typeof s=="object"?s.name:null,a=n;return i===T&&In(a[T])?{kind:"serves",version:r}:{kind:"renamed",version:r,keys:Object.keys(a)}},ia=e=>`Plugin ${j} ${e===null?"(version unreadable)":e}`,cy=e=>{let r="plugin MCP server";if(e.kind==="not-installed")return{name:r,status:"fail",message:`No infra-kit plugin installed for this project to serve the MCP server. Run: ${Ae}`};if(e.kind==="no-server")return{name:r,status:"fail",message:`${ia(e.version)} does not carry the infra-kit MCP server \u2014 update it: ${sr}`};if(e.kind==="renamed"){let t=e.keys.length===0?"no server":`a server under "${e.keys.join('", "')}"`;return{name:r,status:"fail",message:`${ia(e.version)} carries ${t} in its ${F}, not the infra-kit server as shipped \u2014 install corrupt or renamed; reinstall: claude plugin uninstall ${j} && ${Ae}`}}return{name:r,status:"pass",message:`${ia(e.version)} serves the infra-kit MCP server as ${Me}*`}},ly=(e,r)=>{let t=Qe(e===null?{}:{projectPath:e}),o=Yt();return[{name:"marketplace registered",status:o?"pass":"fail",message:o?`Marketplace ${T} is known to Claude Code`:`Marketplace ${T} is not registered. Run: claude plugin marketplace add ${Xe}`},iy(t,r),ny(t),cy(kd(t)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${H.version}`}]},py=`${F} still registers "${T}", so Claude Code uses that entry and the plugin's copy of the server is shadowed (same key, project scope wins). Until this repo's key-deletion PR merges, sessions here serve ${nr}* and every body they read already names that prefix \u2014 nothing to fix on this machine. The PR: delete the "${T}" entry from ${F} by hand, keeping its siblings (\`claude mcp remove ${T} --scope project\` also works but re-indents the file)`,dy={stale:py,absent:`served by the plugin \u2014 ${F} carries no "${T}" key`,"missing-file":`served by the plugin \u2014 no ${F} at the repo root, so no "${T}" key to shadow it`,unparseable:`Could not read ${me} from ${F} \u2014 fix the JSON and re-run`},uy={stale:`${F} registers the server as "${T}" \u2014 the live route until the plugin carries it; this session's tools are ${nr}*`,absent:`no server at all: ${F} has no "${T}" key and the served plugin does not carry it \u2014 ${sr}, then restart Claude Code`,"missing-file":`no server at all: no ${F} at the repo root and the served plugin does not carry it \u2014 ${sr}, then restart Claude Code`,unparseable:`Could not read ${me} from ${F} \u2014 fix the JSON and re-run`},my=new Set(["absent","missing-file","stale"]),fy=new Set(["stale"]),gy=(e,r)=>{let t="MCP server key",o=Ar(e),n=r.kind==="serves";if(o.kind==="wrong-key")return{name:t,status:"fail",message:`${F} registers an infra-kit server under "${o.key}" \u2014 a second server process whose tools carry that key as their prefix, which no served guidance names. Remove that entry (a repo PR, by hand); the plugin${n?"":", once updated,"} serves the server under "${T}"`};let s=n?my:fy,i=n?dy:uy;return{name:t,status:s.has(o.kind)?"pass":"fail",message:i[o.kind]}},wd=e=>vs(["trust"],{bin:e}),hy=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),gd="ERR_TLS_CERT_ALTNAME_INVALID",vy=async(e,r,t)=>{let o=`portless serving TLS on :${er}`;return await e(er,!0)?{name:o,status:"pass",message:`portless is serving HTTPS on :${er}`}:{name:o,status:"fail",message:`No portless daemon is serving HTTPS on :${er}. Install it once (needs root): \`${br(r,t)}\`.`}},yy=async(e,r,t,o,n)=>{let s="portless CA chain valid",i=["localhost",...r.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(er,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${b(t)} (${i.join(", ")})`};let p=c.map(d=>d.result.ok?"":d.result.code);return p.includes(gd)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${gd} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:p.some(d=>hy.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${b(t)}. Its CA was regenerated \u2014 run \`${wd(o)}\`, or reinstall: \`${br(o,n)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${p.join(", ")})`}},ky=(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: \`${wd(t)}\` (no sudo needed).`}},wy=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 \`${vs(["alias","--remove","<name>"],{bin:t})}\`.`}},Wr="portless service target",Xn=e=>({name:Wr,status:"pass",message:`Warning \u2014 ${e}`}),by=e=>e==="darwin"?Lc:e==="linux"?Wc:null,Ry=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Fc}`:`sudo systemctl restart ${Jc}`,Py="/bin/ps",Ey=e=>{try{let r=Cv(Py,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(r.status!==0)return null;let t=new Date(r.stdout.trim());return Number.isNaN(t.getTime())?null:t}catch{return null}},hd=e=>{try{return B.readFileSync(e,"utf-8")}catch{return null}},xy=e=>{try{return B.statSync(e).mtime}catch{return null}},bd=(e,r)=>({platform:e.platform??Ot.platform,readServiceFile:e.readServiceFile??hd,readFile:e.readFile??hd,exists:e.exists??B.existsSync,realpath:e.realpath??pe,mtime:e.mtime??xy,execPath:e.execPath??Ot.execPath,home:e.home??vd.homedir(),cwd:e.cwd??Ot.cwd(),repoRoot:e.repoRoot??ko,stateDir:(e.stateDir??Bc)(),processStartTime:e.processStartTime??Ey,bin:r}),Sy=(e,r)=>{let t=r.readFile(U.join(e,"package.json"));try{let o=t===null?null:Q.object({version:Q.string()}).safeParse(JSON.parse(t));return o?.success===!0?o.data.version:"?"}catch{return"?"}},Ty=(e,r)=>{let t=Number.parseInt(r.readFile(U.join(r.stateDir,"proxy.pid"))?.trim()??"",10);if(!Number.isInteger(t)||t<=0)return!1;let o=r.processStartTime(t),n=r.mtime(U.join(e,"package.json"));return o!==null&&n!==null&&o.getTime()<n.getTime()},Cy=async(e,r)=>{let t=r.realpath(r.cwd);return t===r.realpath(r.home)?!1:Ht(await r.repoRoot()??t,e,r.realpath)},Dt=e=>({state:"drifted",row:e}),Ay=async(e,r,t)=>{let o=br(t.bin,t);if(!t.exists(e))return Dt({name:Wr,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded). Re-run: \`${o}\``});let n=U.join(ks(t.home),"dist","cli.js");if(r!==n)return Dt(Xn(`The service points at \`${r}\`, a version-specific location. Re-run once to switch it to the stable link: \`${o}\``));if(pn(t.home,t.exists)===null)return Dt({name:Wr,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=t.realpath(ks(t.home));if(await Cy(s,t))return Dt({name:Wr,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${o}\``});if(t.realpath(e)!==t.realpath(t.execPath))return Dt(Xn(`The service runs \`${e}\`; infra-kit runs \`${t.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${o}\``));let i=Sy(s,t);return Ty(s,t)?{state:"converged",row:Xn(`The running daemon predates portless ${i} that \`dev\` will talk to. Restart it: \`${Ry(t.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Wr,status:"pass",message:`service runs \`${e}\` + stable link \u2192 portless ${i}`}}},Rd=async e=>{let r=by(e.platform);if(r===null)return{state:"absent",row:{name:Wr,status:"pass",message:"Skipped \u2014 no portless OS service file on this platform"}};let t=e.readServiceFile(r);if(t===null)return{state:"absent",row:{name:Wr,status:"pass",message:`Skipped \u2014 the OS service is not installed (no ${r})`}};let[o,n]=cp(e.platform,t)??[];return o===void 0||n===void 0?Dt(Xn(`could not parse ${r} \u2014 re-run \`${br(e.bin,e)}\` to rewrite it.`)):Ay(o,n,e)},Pd=async(e,r)=>(await Rd(bd(e,r))).state,$y=async(e={})=>{let r=e.resolveBin??jc,t=e.isProxyServing??Vc,o=e.handshake??Kc,n=e.caTrusted??Uc,s=e.routes??ys,i=e.isListening??zt,a=(e.caPath??Gc)(),c=r();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."}];let p={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},d=bd(e,c),u=s(),m=await vy(t,c,d),v=m.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await yy(o,u,a,c,d);return[p,(await Rd(d)).row,m,v,ky(n(),a,c),await wy(u,i,c)]},Iy=async(e={})=>{let r="portless routes",t=e.routes??ys,o=e.isListening??zt,n=e.devSessionRunning??op,s=t();if(s.length===0)return{name:r,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await o(d.port)}))),{prunable:a,withheld:c}=tp(i,n());if(c.length>0)return{name:r,status:"fail",message:`${c.length} route(s) look stale (${c.join(", ")}), but a dev session is running \u2014 a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. Stop dev and re-run \`infra-kit doctor --fix\`.`};if(a.length===0)return{name:r,status:"pass",message:`${s.length} portless route(s), all live`};let p=e.removeAlias??Hc().removeAlias;for(let d of a)await p(d);return{name:r,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Ed=async(e={})=>{let r=await Nv(),t=$v(e.probeDeps??bo()),o=async(v,f)=>{let[k,x]=await Promise.all([f,t]),D=x.get(v);return D===void 0?k:{...k,detail:D}},n=await Promise.all([o("brew",Ge("brew installed",we("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),o("gh",Ge("gh installed",we("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),Ge("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),o("doppler",Ge("doppler installed",we("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),o("aws",Ge("aws installed",we("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")),Ge("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),Ge("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"),Ge("terminal installed",["cmux","--version"],"Installed: cmux","cmux is not installed. Install from: https://cmux.com/"),Promise.resolve(Iv()),Promise.resolve(_v()),Dv(),Ov(),Promise.resolve(Mv(r)),Gv(),Wv(r),Vv(r),Uv(e.fix??!1),Hv(),zv(),Zv(r)]),s=await $y();if(e.fix){let v=await Iy(),f=s.findIndex(k=>k.name===v.name);f>=0?s[f]=v:s.push(v)}let i=await ty(),a=await ko(),c=kd(Qe(i===null?{}:{projectPath:i})),p={projectDir:Ot.env.CLAUDE_PROJECT_DIR||null,cwd:Ot.cwd(),gitRoot:a},d=[await ay(),...ly(i,p),...a===null?[]:[gy(a,c)]],u=[...n,...s,...await ry(),...d],m={checks:u.map(v=>({name:v.name,status:v.status,message:v.message,fixable:ki.has(v.name),detail:v.detail})),allPassed:u.every(v=>v.status==="pass"),cliVersion:H.version};return{content:y(JSON.stringify(m,null,2)),structuredContent:m}},aa=w({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:Q.array(Q.object({name:Q.string().describe("Name of the check"),status:Q.enum(["pass","fail"]).describe("Check result"),message:Q.string().describe("Details about the check result"),fixable:Q.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Q.object({manager:Q.string().describe("Which package manager owns this install, read from its resolved path"),version:Q.string().nullable().describe("The version the tool reported, or null"),present:Q.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Q.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:Q.boolean().describe("Whether all checks passed"),cliVersion:Q.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Ed()});import ca from"node:fs";import xd from"node:path";import{z as Nt}from"zod";var _y=async e=>{let r="";try{r=await R()}catch{return}let t=We(r);t&&Ci(t,e)},Dy=e=>[...e.map(r=>`unset ${r}`),`unset ${nn}`,`unset ${Qr}`,`unset ${et}`,`unset ${sn}`,`unset ${rt}`,`unset ${yr}`,`export ${tt}='1'`],Sd=async({purge:e=!1}={})=>{let r=ot(),t=xd.join(r,le),o=ca.existsSync(t);if(!o&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await _y(e);let n=o?an(t):[],s=Dy(n),i=xd.resolve(r,on);ca.mkdirSync(r,{recursive:!0,mode:448}),wr(i,`${s.join(`
|
|
379
|
+
${i}`:"")},Zp=()=>{let e="pnpm exec infra-kit";return["zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null","zmodload zsh/sched 2>/dev/null",'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",": ${_INFRA_KIT_LAST_LOAD_MTIME:=0}",": ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}",": ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}",": ${_INFRA_KIT_WARM_TTL:=7200}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED _INFRA_KIT_WARM_TTL",`env-load() { local f m; f=$(${e} env-load "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source "$f"; ${e} env-status; }`,`env-clear() { local f m; f=$(${e} env-clear "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`,"_infra_kit_notify() {"," zle && print -u2 -n $'\\r\\e[K'",' print -u2 -- "$1"'," zle && zle reset-prompt","}","_infra_kit_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local dir="$cache_root/$INFRA_KIT_SESSION"',' local load_file="$dir/env-load.sh"',' local clear_file="$dir/env-clear.sh"'," local load_mtime=0 clear_mtime=0",' [[ -f "$load_file" ]] && load_mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)',' [[ -f "$clear_file" ]] && clear_mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( load_mtime > _INFRA_KIT_LAST_LOAD_MTIME && load_mtime >= _INFRA_KIT_SHELL_STARTED && load_mtime >= clear_mtime )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$load_mtime",' _infra_kit_notify "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," if (( clear_mtime > _INFRA_KIT_LAST_CLEAR_MTIME && clear_mtime >= _INFRA_KIT_SHELL_STARTED && clear_mtime > load_mtime )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$clear_mtime",' _infra_kit_notify "infra-kit: auto-cleared env"'," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi","_INFRA_KIT_AUTOLOAD_WINDOW=6","export _INFRA_KIT_AUTOLOAD_WINDOW","_infra_kit_poll_autoload() {"," _infra_kit_autoload"," if (( _INFRA_KIT_LAST_LOAD_MTIME < _INFRA_KIT_SHELL_STARTED )) && (( ${EPOCHSECONDS:-0} - _INFRA_KIT_SHELL_STARTED < _INFRA_KIT_AUTOLOAD_WINDOW )); then"," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," fi","}","_infra_kit_warm_source() {",' local canon="$1" key'," if (( $+commands[shasum] )); then",' key=$(printf %s "$canon" | shasum -a 256 | cut -c1-64)'," elif (( $+commands[sha256sum] )); then",' key=$(printf %s "$canon" | sha256sum | cut -c1-64)'," else"," return"," fi",' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local warm="$cache_root/projects/$key/env-load.sh"',' local wclear="$cache_root/projects/$key/env-clear.sh"',' [[ -f "$warm" ]] || return'," local wm=0 cm=0",' wm=$(zstat +mtime -- "$warm" 2>/dev/null || echo 0)',' [[ -f "$wclear" ]] && cm=$(zstat +mtime -- "$wclear" 2>/dev/null || echo 0)'," (( cm >= wm )) && return"," (( ${EPOCHSECONDS:-0} - wm >= _INFRA_KIT_WARM_TTL )) && return",' source "$warm"',' _infra_kit_notify "infra-kit: loaded cached vars for ${INFRA_KIT_ENV_CONFIG:-?} (refreshing\u2026)"',"}","_infra_kit_startup_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local dir="$PWD" prev=""',' while [[ -n "$dir" && "$dir" != "$prev" ]]; do',' if [[ -f "$dir/infra-kit.json" ]]; then',' [[ -n "$INFRA_KIT_ENV_CONFIG" && "$dir" == "$INFRA_KIT_ENV_PROJECT_ROOT" ]] && return',' local canon="${dir:A}"',' _infra_kit_warm_source "$canon"',` ( ${e} env-autoload --project-dir "$canon" & ) >/dev/null 2>&1`," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," return"," fi",' prev="$dir"',' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
|
|
380
|
+
`)},Xp=()=>`${Nr}
|
|
381
|
+
${Zp()}
|
|
382
|
+
${ar}`,Vi=()=>["# Inherit this terminal's infra-kit session env into every zsh it spawns, interactive or not.","# A fresh terminal has no session yet (it is minted in .zshrc, after this file) and skips.","# Only the canonical 8-hex id .zshrc mints is honoured. Load wins a tie with clear, as the","# .zshrc precmd gate does. Prints nothing of its own.",'if [[ -n "${INFRA_KIT_SESSION:-}" ]]; then'," () {"," emulate -L zsh -o extendedglob",' [[ "${INFRA_KIT_SESSION:-}" == [0-9a-f](#c8) ]] || return',' local _ik_dir="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit/$INFRA_KIT_SESSION"',' local _ik_load="$_ik_dir/env-load.sh" _ik_clear="$_ik_dir/env-clear.sh"',' if [[ -r "$_ik_load" && ! "$_ik_clear" -nt "$_ik_load" ]]; then',' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
|
|
383
|
+
`),Bi=()=>`${Nr}
|
|
384
|
+
${Vi()}
|
|
385
|
+
${ar}`;import cv from"node:fs/promises";var Gi=async(e,r)=>{if(!r)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let t=await cv.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}}},Ui=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import pv from"node:fs";import dv from"node:os";import Qp from"node:path";import uv from"node:process";import{$ as lv}from"zx";var Mr=()=>lv({quiet:!0});var mv=()=>[Qp.join(dv.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],fv=async e=>{try{return(await Mr()`command -v ${e}`).stdout.trim()||null}catch{return null}},Ro=()=>({runCommand:async e=>{let r=await Mr()`${e}`;return{stdout:`${r.stdout}
|
|
386
|
+
${r.stderr}`}},resolveBinPath:async e=>{let r=await fv(e);return r!==null?r:mv().map(t=>Qp.join(t,e)).find(t=>pv.existsSync(t))??null},realpath:pe,platform:uv.platform});var jr=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Eo=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,xo=["darwin","linux"],Hi=e=>r=>ks(r,e)?"homebrew":"unknown",Zn=(e,r)=>t=>t===null?null:r(e(t),t),od=e=>Zn(Hi(e.kegName),r=>r==="homebrew"?jr(["brew","upgrade",e.brewFormula]):null),ed=e=>pn(e,"Homebrew")||pn(e,"homebrew")?"homebrew":"unknown",gv={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Eo,platforms:xo,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:ed,updateFor:Zn(ed,e=>e==="homebrew"?jr(["brew","update"]):null)},Ki={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},nd="https://awscli.amazonaws.com/v2/install.sh",sd={steps:[["/bin/bash","-c",`curl -fsSL ${nd} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},hv="/usr/local/aws-cli",vv=e=>zt(hv,e,pe)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${nd} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:sd,rd=e=>ks(e,Ki.kegName)?"homebrew":pn(e,"aws-cli")?"script":"unknown",yv={id:"aws",binName:"aws",...Ki,probeArgv:["aws","--version"],versionFrom:Eo,platforms:xo,prerequisites:[],bootstrapInstall:sd,identify:rd,updateFor:Zn(rd,(e,r)=>e==="homebrew"?jr(["brew","upgrade",Ki.brewFormula]):e==="script"?vv(r):null)},qn={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},kv={id:"gh",binName:"gh",...qn,probeArgv:["gh","--version"],versionFrom:Eo,platforms:xo,prerequisites:["brew"],bootstrapInstall:jr(["brew","install",qn.brewInstallSpec]),identify:Hi(qn.kegName),updateFor:od(qn)},Yn={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},wv={id:"doppler",binName:"doppler",...Yn,probeArgv:["doppler","--version"],versionFrom:Eo,platforms:xo,prerequisites:["brew"],bootstrapInstall:jr(["brew","install","gnupg"],["brew","install",Yn.brewInstallSpec]),identify:Hi(Yn.kegName),updateFor:od(Yn)},Po="portless",td=e=>jc(e,Po)===null?"unknown":"npm",bv={id:"portless",binName:Po,npmPackage:Po,probeArgv:["portless","--version"],versionFrom:Eo,platforms:[...xo,"win32"],prerequisites:[],bootstrapInstall:jr(["npm","install","-g",Po]),identify:td,updateFor:Zn(td,e=>e==="npm"?jr(["npm","install","-g",`${Po}@latest`]):null)},zi={brew:gv,aws:yv,gh:kv,doppler:wv,portless:bv},Fr=Object.keys(zi),we=e=>zi[e],qi=(e,r)=>e.platforms.includes(r),Yi=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 we(n).prerequisites)o(i,[...s,n]);r.push(n)}};for(let n of e)o(n,[]);return r};var id=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),ad=async(e,r)=>{try{return await e(r)}catch{return null}},Rv=async(e,r)=>{try{let t=await e.resolveBinPath(r);return t==null?null:e.realpath(t)}catch{return null}},cd=async(e,r)=>{if(!qi(e,r.platform))return id(e.id);let t=await ad(r.runCommand,e.probeArgv),o=await Rv(r,e.binName);if(t==null&&o==null)return id(e.id);let n=t??(o==null?null:await ad(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)}},So=async(e,r)=>Promise.all(e.map(t=>cd(we(t),r)));import{$ as Iv}from"zx";import Co from"node:process";var Pv="x-seraph-loginreason",Ev="AUTHENTICATED_FAILED",xv=(e,r=160)=>{let t=e.split(`
|
|
387
|
+
`,1)[0].trim();return t.length>r?`${t.slice(0,r)}\u2026`:t},pd=(e,r)=>r===Ev||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",ld=(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}`,Tt=class extends Error{status;kind;body;context;constructor(r){let t=pd(r.status,r.seraphLoginReason),o=xv(r.body);super(o===""?`${r.context}: ${ld(t,r.status)}`:`${r.context}: ${ld(t,r.status)}. Jira said: ${o}`),this.name="JiraApiError",this.status=r.status,this.kind=t,this.body=r.body,this.context=r.context}},To=e=>e instanceof Tt,dd=e=>e.headers.get(Pv);var Ct=async(e,r)=>{if(e.ok)return;let t=await e.text(),o=new Tt({status:e.status,seraphLoginReason:dd(e),body:t,context:r});throw l.debug({status:e.status,kind:o.kind,body:t},r),o},cr=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,Zi=async(e,r)=>{let{baseUrl:t,token:o,email:n,projectId:s}=r,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1},a=`${t}/rest/api/3/version`,c=btoa(`${n}:${o}`),p=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Ct(p,"Failed to create Jira version"),{success:!0,version:await p.json()}},At=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 Ct(a,"Failed to get Jira project versions"),await a.json()},Ve=async(e,r)=>(await At(r)).find(n=>n.name===e)||null,$t=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 Ct(c,"Failed to update Jira version"),{success:!0,version:await c.json()}},Xi=async(e,r)=>{let{versionName:t}=e,o=await Ve(t,r);if(!o)throw new Error(`Version "${t}" not found in Jira project`);return await $t({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)},It=async()=>{let e=Co.env.JIRA_BASE_URL,r=Co.env.JIRA_TOKEN||Co.env.JIRA_API_TOKEN,t=Co.env.JIRA_PROJECT_ID,o=Co.env.JIRA_EMAIL,n=[];if(e||n.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||n.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||n.push("JIRA_PROJECT_ID (numeric project ID)"),o||n.push("JIRA_EMAIL (your Jira email address)"),n.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...n.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
388
|
+
`);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},Be=async()=>{try{return await It()}catch(e){return l.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Xn=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 Ct(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Qi=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 Ct(c,"Failed to remove Jira version")};var lr=e=>e.slice(1).split(".").map(Number),_t=e=>[...e].sort((r,t)=>{let[o,n,s]=lr(r),[i,a,c]=lr(t);return o!==i?(o??0)-(i??0):n!==a?(n??0)-(a??0):(s??0)-(c??0)});var md="next",Sv=/^v?(\d+)\.(\d+)\.(\d+)$/,Tv=e=>e.replace(/^.*release\//,""),ra=e=>{let r=Tv(e.trim()),t=Sv.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},ud=e=>`${e[0]}.${e[1]}.${e[2]}`,ta=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=ra(n);if(!s)continue;let i=ud(s);o.has(i)||(o.add(i),t.push(s))}return _t(t.map(n=>ud(n))).map(n=>lr(`v${n}`))},Lr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},oa=(e,r)=>{if(e.length===0)throw new Lr;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,a=e.reduce((c,p)=>p[0]===s&&p[1]===i?Math.max(c,p[2]):c,0);return`${s}.${i}.${a+1}`}let[o,n]=t;return`${o}.${n+1}.0`},Dt=(e,r)=>{try{return oa(e,r)}catch(t){if(t instanceof Lr)return null;throw t}},na=e=>e.trim().toLowerCase()===md,Qn=e=>na(e)||ra(e)!==null?{version:e}:{name:e},Cv=e=>e==="regular"||e==="hotfix",fd=e=>"name"in e,Av=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":"),o=r,n="regular",s="";if(t!==-1){o=r.slice(0,t).trim();let a=r.slice(t+1),c=a.indexOf(":"),p=c===-1?a.trim():a.slice(0,c).trim();s=c===-1?"":a.slice(c+1).trim();let d=p.toLowerCase();if(!Cv(d))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);n=d}let i={...Qn(o),type:n};return s!==""&&(i.description=s),i},sa=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},ea=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,$v=e=>{let r=e.name.trim();return fn(r),ea({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},ia=(e,r)=>{let t=[...r];return e.map(o=>{if(fd(o))return $v(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(na(n)){let a=oa(t,o.type);return t.push(lr(`v${a}`)),ea({id:ye(a),type:o.type},o.description)}let s=ra(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),ea({id:ye(i),type:o.type},o.description)})},aa=e=>e.some(r=>!fd(r)&&na(r.version));var _v=e=>e.split(`
|
|
389
|
+
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:W(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Dv=async()=>{let e=await Iv({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return _v(e.stdout)},Ov=async()=>{let e=await Be();return e?(await At(e)).map(t=>t.name):[]},Ao=async()=>{let[e,r]=await Promise.allSettled([Dv(),Ov()]);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"),ta({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Mv=["brew","gh","doppler","aws"],jv=async e=>{let r=await So(Mv,e);return new Map(r.map(t=>[t.id,{manager:t.manager,version:t.version,present:t.present,onPath:t.onPath}]))},Ge=async(e,r,t,o)=>{try{return await Mr()`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Pd=(e,r,t,o)=>{let n=U.join(Rd.homedir(),r),s="Run: infra-kit setup --skip-tools";if(!B.existsSync(n))return{name:e,status:"fail",message:`~/${r} not found. ${s}`};let i=B.readFileSync(n,"utf-8"),a=i.indexOf(Nr),c=i.indexOf(ar);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${t} block missing from ~/${r}. ${s}`}:i.slice(a,c+ar.length).trim()!==o.trim()?{name:e,status:"fail",message:`infra-kit ${t} block in ~/${r} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${t} block in ~/${r} is up to date`}},Fv=()=>Pd("zshrc init block",".zshrc","shell",Xp()),Lv=()=>Pd("zshenv session block",".zshenv","session-env",Bi()),Wv=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=We(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let o=U.join(kr(t),le);if(!B.existsSync(o))return{name:e,status:"pass",message:"warm cache: none yet (populated on next auto-load)"};let n=Math.floor((Date.now()-B.statSync(o).mtimeMs)/1e3),s=Math.floor(n/60),i=Math.floor(Kt/60);return n>=Kt?{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`}},Jv=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await R(),t=U.join(r,"pnpm-workspace.yaml");if(!B.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=B.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}`}}},Vv=async()=>{try{return st(),{config:await E(),error:null}}catch(e){return{config:null,error:e}}},Bv=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)"}},Gv=384,ca=448,Uv=e=>e.map(r=>{let t=r.source===null?"no token":`token (${r.source})`;return`${r.env}: ${t}`}).join(", "),Kv=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}}})),Hv=async(e,r={})=>{let t="env tokens configured",o=r.readStore??te,n=r.resolveToken??kt;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 _r(),a=e.config.envAutoLoad?.config,c=a&&!i.includes(a)?[...i,a]:i,p=await Kv(c,n),d=Uv(p);if(a===void 0)return{name:t,status:"pass",message:`No envAutoLoad configured \u2014 no env is load-bearing. ${d}`};let u=p.find(m=>m.env===a);return!u||u.source===null?s===null||Object.keys(s.envs).length===0?{name:t,status:"pass",message:"Skipped \u2014 there is no token store to read (see tokens.json present)"}:{name:t,status:"fail",message:`No Doppler service token for the auto-load env "${a}" \u2014 your shell env will not load. Fix: run \`infra-kit env-token-set ${a}\`. ${d}`}:{name:t,status:"pass",message:`auto-load env "${a}": token (${u.source}). ${d}`}},zv={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)"}},qv=async(e,r={})=>{let t="env token valid",o=r.resolveToken??kt,n=r.probe??ho;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:xt(i),project:a,config:s}),p=zv[c.outcome],d=c.outcome==="revoked"||c.outcome==="mis-scoped"?` Fix: run \`infra-kit env-token-set ${s}\` with a token scoped to "${s}".`:"";return{name:t,status:p.status,message:`The token for env "${s}" (project "${a}") is ${p.describe}.${d}`}},Yv=()=>Nt.env[G]||void 0,Zv=async(e={})=>{let r="tokens.json present",t=e.readStore??te,o=e.storePath??Xt;if((e.readEnvToken??Yv)())return{name:r,status:"pass",message:`Skipped \u2014 ${G} 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 ${G} instead.`}}return{name:r,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},$o=(e,r)=>{let t=r(e);return t===null?null:t.mode&511},Xv=async(e,r={})=>{let t="tokens.json perms",o=r.storePath??Xt,n=r.statPath??Qv,s=r.chmodPath??B.chmodSync,i;try{i=await o()}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if($o(i,n)===null)return{name:t,status:"pass",message:`No store to protect at ${b(i)} (see tokens.json present)`};let a=U.dirname(i),c=U.dirname(a),p=U.dirname(c),u=[{target:p,expected:ca,actual:$o(p,n)},{target:c,expected:ca,actual:$o(c,n)},{target:a,expected:ca,actual:$o(a,n)},{target:i,expected:Gv,actual:$o(i,n)}].filter(v=>v.actual!==null&&v.actual!==v.expected);if(u.length===0)return{name:t,status:"pass",message:`${b(i)} is 0600 (0700 dirs)`};let m=u.map(v=>`${b(v.target)} is ${gd(v.actual)}, expected ${gd(v.expected)}`).join("; ");if(!e)return{name:t,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let v of u)s(v.target,v.expected);return{name:t,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},gd=e=>`0${e.toString(8).padStart(3,"0")}`,Qv=e=>{try{return B.statSync(e)}catch{return null}},ey=async()=>{let e="user override path";try{let r=await X(),t=B.existsSync(r.userProject),o=await Gi(r.userProject,t),n=t?Ui(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}}},ry=async()=>{let e="legacy user-global config",r;try{r=await X()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=U.join(U.dirname(r.userGlobal),"config.json");return B.existsSync(t)?B.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"}},ty={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/"}},oy=async e=>{let r=ty[e];try{return await Mr()`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},ny=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=Ee(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=>oy(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("; ")}},hd=/^\d+\.\d+\.\d+$/,sy=(e,r)=>e===r||!hd.test(e)||!hd.test(r)?!1:_t([`v${e}`,`v${r}`])[0]===`v${e}`,iy=async(e,r)=>{let t;try{t=await ne(e)}catch{return[]}let o=[];for(let n of t){let s=xr(Sr(U.join(n,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&sy(s.version,r)&&o.push(s.version)}return o},ay=async(e,r)=>{let t=await iy(e,r);if(t.length===0)return"";let o=_t(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`},cy=async()=>{let e;try{e=(await X()).main}catch{return[]}if(!B.existsSync(e))return[];let r=U.dirname(e),t=U.join(r,"CLAUDE.md"),o=B.existsSync(t)?B.readFileSync(t,"utf-8"):"",n=Se(o,ue,Te),s=n?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",i=await ay(r,H.version);return[{name:"CLAUDE.md block",status:n?"pass":"fail",message:`${s}${i}`}]},ly=async()=>{try{let e=(await X()).main;return B.existsSync(e)?U.dirname(e):null}catch{return null}},py=e=>{let r=dl();return r===null||!Qt(r,e)?"":` \u2014 plugin ${r} is fetched but not applied. Run: ${sr}`},dy=e=>{let r=e.kind==="installed"?wn(e.installation):null;return{name:"plugin version",status:r===null?"fail":"pass",message:r===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${F} version ${r}${py(r)}`}},vd=3,yd=(e,r)=>pe(e)===pe(r),uy=e=>{if(e===void 0||e.gitRoot===null)return"";let r=b(e.gitRoot);if(e.projectDir!==null){if(yd(e.projectDir,e.gitRoot))return"";let t=zt(e.gitRoot,pe(e.projectDir),pe)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${b(e.projectDir)}, ${t}: the plugin and this repo's .claude/settings.json hooks load only from ${r} (measured); restart Claude Code there`}return yd(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${b(e.cwd)} rather than ${r}, it loaded neither the plugin nor this repo's hooks; launch it at ${r}`},my=(e,r)=>{let t="plugin installed",o=uy(r);if(e.kind==="installed"){let{scope:c,projectPath:p}=e.installation,d=p===null?"":`, ${b(p)}`;return{name:t,status:"pass",message:`Plugin ${F} installed (${c??"unknown"} scope${d})${o}`}}if(e.kind==="absent")return{name:t,status:"fail",message:`Plugin ${F} is not installed. Run: ${Ae}${o}`};let n=e.installations.map(c=>c.projectPath===null?"(unnamed project)":b(c.projectPath)),s=n.length-vd,i=s>0?` and ${s} more`:"",a=`${n.slice(0,vd).join(", ")}${i}`;return{name:t,status:"fail",message:`Plugin ${F} is installed for ${a} only, not this project. Run: ${Ae}${o}`}},fy=()=>Ge("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),kd=(e,...r)=>{try{return JSON.parse(B.readFileSync(U.join(e,...r),"utf-8"))}catch{return null}},Ed=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let r=wn(e.installation),{installPath:t}=e.installation;if(t===null)return{kind:"no-server",version:r};let o=kd(t,L),n=o!==null&&typeof o=="object"?o[me]:void 0;if(n==null||typeof n!="object")return{kind:"no-server",version:r};let s=kd(t,".claude-plugin","plugin.json"),i=s!==null&&typeof s=="object"?s.name:null,a=n;return i===T&&Dn(a[T])?{kind:"serves",version:r}:{kind:"renamed",version:r,keys:Object.keys(a)}},la=e=>`Plugin ${F} ${e===null?"(version unreadable)":e}`,gy=e=>{let r="plugin MCP server";if(e.kind==="not-installed")return{name:r,status:"fail",message:`No infra-kit plugin installed for this project to serve the MCP server. Run: ${Ae}`};if(e.kind==="no-server")return{name:r,status:"fail",message:`${la(e.version)} does not carry the infra-kit MCP server \u2014 update it: ${sr}`};if(e.kind==="renamed"){let t=e.keys.length===0?"no server":`a server under "${e.keys.join('", "')}"`;return{name:r,status:"fail",message:`${la(e.version)} carries ${t} in its ${L}, not the infra-kit server as shipped \u2014 install corrupt or renamed; reinstall: claude plugin uninstall ${F} && ${Ae}`}}return{name:r,status:"pass",message:`${la(e.version)} serves the infra-kit MCP server as ${Me}*`}},hy=(e,r)=>{let t=Qe(e===null?{}:{projectPath:e}),o=Zt();return[{name:"marketplace registered",status:o?"pass":"fail",message:o?`Marketplace ${T} is known to Claude Code`:`Marketplace ${T} is not registered. Run: claude plugin marketplace add ${Xe}`},my(t,r),dy(t),gy(Ed(t)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${H.version}`}]},vy=`${L} still registers "${T}", so Claude Code uses that entry and the plugin's copy of the server is shadowed (same key, project scope wins). Until this repo's key-deletion PR merges, sessions here serve ${nr}* and every body they read already names that prefix \u2014 nothing to fix on this machine. The PR: delete the "${T}" entry from ${L} by hand, keeping its siblings (\`claude mcp remove ${T} --scope project\` also works but re-indents the file)`,yy={stale:vy,absent:`served by the plugin \u2014 ${L} carries no "${T}" key`,"missing-file":`served by the plugin \u2014 no ${L} at the repo root, so no "${T}" key to shadow it`,unparseable:`Could not read ${me} from ${L} \u2014 fix the JSON and re-run`},ky={stale:`${L} registers the server as "${T}" \u2014 the live route until the plugin carries it; this session's tools are ${nr}*`,absent:`no server at all: ${L} has no "${T}" key and the served plugin does not carry it \u2014 ${sr}, then restart Claude Code`,"missing-file":`no server at all: no ${L} at the repo root and the served plugin does not carry it \u2014 ${sr}, then restart Claude Code`,unparseable:`Could not read ${me} from ${L} \u2014 fix the JSON and re-run`},wy=new Set(["absent","missing-file","stale"]),by=new Set(["stale"]),Ry=(e,r)=>{let t="MCP server key",o=Ar(e),n=r.kind==="serves";if(o.kind==="wrong-key")return{name:t,status:"fail",message:`${L} registers an infra-kit server under "${o.key}" \u2014 a second server process whose tools carry that key as their prefix, which no served guidance names. Remove that entry (a repo PR, by hand); the plugin${n?"":", once updated,"} serves the server under "${T}"`};let s=n?wy:by,i=n?yy:ky;return{name:t,status:s.has(o.kind)?"pass":"fail",message:i[o.kind]}},xd=e=>ws(["trust"],{bin:e}),Py=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),wd="ERR_TLS_CERT_ALTNAME_INVALID",Ey=async(e,r,t)=>{let o=`portless serving TLS on :${er}`;return await e(er,!0)?{name:o,status:"pass",message:`portless is serving HTTPS on :${er}`}:{name:o,status:"fail",message:`No portless daemon is serving HTTPS on :${er}. Install it once (needs root): \`${br(r,t)}\`.`}},xy=async(e,r,t,o,n)=>{let s="portless CA chain valid",i=["localhost",...r.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(er,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${b(t)} (${i.join(", ")})`};let p=c.map(d=>d.result.ok?"":d.result.code);return p.includes(wd)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${wd} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:p.some(d=>Py.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${b(t)}. Its CA was regenerated \u2014 run \`${xd(o)}\`, or reinstall: \`${br(o,n)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${p.join(", ")})`}},Sy=(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: \`${xd(t)}\` (no sudo needed).`}},Ty=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 \`${ws(["alias","--remove","<name>"],{bin:t})}\`.`}},Wr="portless service target",es=e=>({name:Wr,status:"pass",message:`Warning \u2014 ${e}`}),Cy=e=>e==="darwin"?Gc:e==="linux"?Uc:null,Ay=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Bc}`:`sudo systemctl restart ${Kc}`,$y="/bin/ps",Iy=e=>{try{let r=Nv($y,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(r.status!==0)return null;let t=new Date(r.stdout.trim());return Number.isNaN(t.getTime())?null:t}catch{return null}},bd=e=>{try{return B.readFileSync(e,"utf-8")}catch{return null}},_y=e=>{try{return B.statSync(e).mtime}catch{return null}},Sd=(e,r)=>({platform:e.platform??Nt.platform,readServiceFile:e.readServiceFile??bd,readFile:e.readFile??bd,exists:e.exists??B.existsSync,realpath:e.realpath??pe,mtime:e.mtime??_y,execPath:e.execPath??Nt.execPath,home:e.home??Rd.homedir(),cwd:e.cwd??Nt.cwd(),repoRoot:e.repoRoot??wo,stateDir:(e.stateDir??zc)(),processStartTime:e.processStartTime??Iy,bin:r}),Dy=(e,r)=>{let t=r.readFile(U.join(e,"package.json"));try{let o=t===null?null:Q.object({version:Q.string()}).safeParse(JSON.parse(t));return o?.success===!0?o.data.version:"?"}catch{return"?"}},Oy=(e,r)=>{let t=Number.parseInt(r.readFile(U.join(r.stateDir,"proxy.pid"))?.trim()??"",10);if(!Number.isInteger(t)||t<=0)return!1;let o=r.processStartTime(t),n=r.mtime(U.join(e,"package.json"));return o!==null&&n!==null&&o.getTime()<n.getTime()},Ny=async(e,r)=>{let t=r.realpath(r.cwd);return t===r.realpath(r.home)?!1:zt(await r.repoRoot()??t,e,r.realpath)},Ot=e=>({state:"drifted",row:e}),My=async(e,r,t)=>{let o=br(t.bin,t);if(!t.exists(e))return Ot({name:Wr,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded). Re-run: \`${o}\``});let n=U.join(Rs(t.home),"dist","cli.js");if(r!==n)return Ot(es(`The service points at \`${r}\`, a version-specific location. Re-run once to switch it to the stable link: \`${o}\``));if(un(t.home,t.exists)===null)return Ot({name:Wr,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=t.realpath(Rs(t.home));if(await Ny(s,t))return Ot({name:Wr,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${o}\``});if(t.realpath(e)!==t.realpath(t.execPath))return Ot(es(`The service runs \`${e}\`; infra-kit runs \`${t.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${o}\``));let i=Dy(s,t);return Oy(s,t)?{state:"converged",row:es(`The running daemon predates portless ${i} that \`dev\` will talk to. Restart it: \`${Ay(t.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Wr,status:"pass",message:`service runs \`${e}\` + stable link \u2192 portless ${i}`}}},Td=async e=>{let r=Cy(e.platform);if(r===null)return{state:"absent",row:{name:Wr,status:"pass",message:"Skipped \u2014 no portless OS service file on this platform"}};let t=e.readServiceFile(r);if(t===null)return{state:"absent",row:{name:Wr,status:"pass",message:`Skipped \u2014 the OS service is not installed (no ${r})`}};let[o,n]=mp(e.platform,t)??[];return o===void 0||n===void 0?Ot(es(`could not parse ${r} \u2014 re-run \`${br(e.bin,e)}\` to rewrite it.`)):My(o,n,e)},Cd=async(e,r)=>(await Td(Sd(e,r))).state,jy=async(e={})=>{let r=e.resolveBin??Vc,t=e.isProxyServing??Hc,o=e.handshake??Zc,n=e.caTrusted??Yc,s=e.routes??bs,i=e.isListening??qt,a=(e.caPath??qc)(),c=r();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."}];let p={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},d=Sd(e,c),u=s(),m=await Ey(t,c,d),v=m.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await xy(o,u,a,c,d);return[p,(await Td(d)).row,m,v,Sy(n(),a,c),await Ty(u,i,c)]},Fy=async(e={})=>{let r="portless routes",t=e.routes??bs,o=e.isListening??qt,n=e.devSessionRunning??cp,s=t();if(s.length===0)return{name:r,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await o(d.port)}))),{prunable:a,withheld:c}=ap(i,n());if(c.length>0)return{name:r,status:"fail",message:`${c.length} route(s) look stale (${c.join(", ")}), but a dev session is running \u2014 a UI that has not bound its port yet is indistinguishable from a dead one, so nothing was removed. Stop dev and re-run \`infra-kit doctor --fix\`.`};if(a.length===0)return{name:r,status:"pass",message:`${s.length} portless route(s), all live`};let p=e.removeAlias??Xc().removeAlias;for(let d of a)await p(d);return{name:r,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Ad=async(e={})=>{let r=await Vv(),t=jv(e.probeDeps??Ro()),o=async(v,f)=>{let[k,x]=await Promise.all([f,t]),D=x.get(v);return D===void 0?k:{...k,detail:D}},n=await Promise.all([o("brew",Ge("brew installed",we("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),o("gh",Ge("gh installed",we("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),Ge("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),o("doppler",Ge("doppler installed",we("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),o("aws",Ge("aws installed",we("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")),Ge("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),Ge("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"),Ge("terminal installed",["cmux","--version"],"Installed: cmux","cmux is not installed. Install from: https://cmux.com/"),Promise.resolve(Fv()),Promise.resolve(Lv()),Wv(),Jv(),Promise.resolve(Bv(r)),Zv(),Hv(r),qv(r),Xv(e.fix??!1),ey(),ry(),ny(r)]),s=await jy();if(e.fix){let v=await Fy(),f=s.findIndex(k=>k.name===v.name);f>=0?s[f]=v:s.push(v)}let i=await ly(),a=await wo(),c=Ed(Qe(i===null?{}:{projectPath:i})),p={projectDir:Nt.env.CLAUDE_PROJECT_DIR||null,cwd:Nt.cwd(),gitRoot:a},d=[await fy(),...hy(i,p),...a===null?[]:[Ry(a,c)]],u=[...n,...s,...await cy(),...d],m={checks:u.map(v=>({name:v.name,status:v.status,message:v.message,fixable:Ri.has(v.name),detail:v.detail})),allPassed:u.every(v=>v.status==="pass"),cliVersion:H.version};return{content:y(JSON.stringify(m,null,2)),structuredContent:m}},pa=w({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:Q.array(Q.object({name:Q.string().describe("Name of the check"),status:Q.enum(["pass","fail"]).describe("Check result"),message:Q.string().describe("Details about the check result"),fixable:Q.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Q.object({manager:Q.string().describe("Which package manager owns this install, read from its resolved path"),version:Q.string().nullable().describe("The version the tool reported, or null"),present:Q.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Q.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:Q.boolean().describe("Whether all checks passed"),cliVersion:Q.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Ad()});import da from"node:fs";import $d from"node:path";import{z as Mt}from"zod";var Ly=async e=>{let r="";try{r=await R()}catch{return}let t=We(r);t&&Ii(t,e)},Wy=e=>[...e.map(r=>`unset ${r}`),`unset ${an}`,`unset ${Qr}`,`unset ${et}`,`unset ${cn}`,`unset ${rt}`,`unset ${yr}`,`export ${tt}='1'`],Id=async({purge:e=!1}={})=>{let r=ot(),t=$d.join(r,le),o=da.existsSync(t);if(!o&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await Ly(e);let n=o?ln(t):[],s=Wy(n),i=$d.resolve(r,sn);da.mkdirSync(r,{recursive:!0,mode:448}),wr(i,`${s.join(`
|
|
390
390
|
`)}
|
|
391
|
-
`,384),o&&
|
|
391
|
+
`,384),o&&da.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}},ua=w({name:"env-clear",description:'Generate a shell script that unsets every env var previously loaded by env-load for this session, plus the infra-kit session metadata vars. Does NOT mutate the calling process. When `infra-kit setup` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Mt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Mt.string().describe("Path to the file that must be sourced to apply"),variableCount:Mt.number().describe("Number of variables cleared"),unsetStatements:Mt.array(Mt.string()).describe("Unset statements generated"),purged:Mt.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>Id()});import Jy from"node:path";import Jr from"node:process";import{z as pr}from"zod";var _d=async()=>{l.info("Environment session status:");let e=ot(),r=Jr.env[Ht],t=Jy.join(e,le),o=0,n=0,s=Jr.env[Qr]??null,i=Jr.env[et]??null,a=Jr.env[rt]??null,c=Jr.env[yr]==="1",p=!!Jr.env[tt];if(s){let u=ln(t);u.length>0&&(n=u.length,o=u.filter(f=>f in Jr.env).length);let m=a?.replace(/\.\d{3}Z$/,"")??null,v=c?"auto-loaded":"manually loaded";if(l.info(` ${s}: ${o} of ${n} vars loaded (${v}, project: ${i}, loadedAt: ${m}, session: ${r})
|
|
392
392
|
`),n>0&&o<n){let f=n-o;l.warn(` ${f} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else{let u=p?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";l.info(` Session ${r}: no env loaded${u}
|
|
393
|
-
`)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:a,autoLoaded:c,cleared:p};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},
|
|
394
|
-
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:n};return{content:y(JSON.stringify(i,null,2)),structuredContent:i}},
|
|
393
|
+
`)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:a,autoLoaded:c,cleared:p};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},ma=w({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:pr.string().describe("Current terminal session ID"),sessionLoadedCount:pr.number().describe("Number of cached vars active in the current session"),sessionTotalCount:pr.number().describe("Total number of cached var names"),sessionConfig:pr.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:pr.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:pr.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:pr.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:pr.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:_d});import Vy from"node:process";import{z as dr}from"zod";var Dd="****",fa=e=>typeof e!="string"||e.length<8?Dd:`${Dd}${e.slice(-4)}`;var Od=(e,r,t)=>e.map(o=>{let n=t||r[o];return n?{env:o,source:t?`env:${G}`:"store",redactedToken:fa(n),present:!0}:{env:o,source:"-",redactedToken:"-",present:!1}}),By=["ENV","SOURCE","TOKEN","PRESENT"],Nd=(e,r)=>{let t=[...By,...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())},Md=async({check:e}={})=>{let r=await _r(),t=await te(),o=Vy.env[G],n=Od(r,t?.envs??{},o);if(e){let a=await $r();for(let c of n){if(!c.present)continue;let p=o||t.envs[c.env],d=await ho({childEnv:xt(p),project:a,config:c.env});c.status=d.outcome}}for(let a of Nd(n,!!e))l.info(a);let s=n.filter(a=>!a.present);s.length>0&&l.info(`
|
|
394
|
+
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:n};return{content:y(JSON.stringify(i,null,2)),structuredContent:i}},ga=w({name:"env-token-list",description:'List the Doppler service tokens configured for this repo: one row per environment declared in infra-kit.json, with its source (the local token store, or the INFRA_KIT_ENV_TOKEN env var) and a REDACTED token (last 4 chars at most \u2014 the raw value is never returned). With check=true, also asks Doppler whether each token is valid and correctly scoped (valid | revoked | mis-scoped | unreachable; "unreachable" means the probe could not tell, NOT that the token is bad). Read-only.',inputSchema:{check:dr.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:dr.array(dr.object({env:dr.string().describe("Environment / Doppler config name"),source:dr.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:dr.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:dr.boolean().describe("Whether a token is configured for this environment"),status:dr.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Md});import{z as S}from"zod";import{$ as ak}from"zx";import{$ as wD}from"zx";import{$ as Ft}from"zx";import{$ as jd}from"zx";var ha=async e=>{let{operation:r}=e;try{await jd({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 jd({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"})}},Uy=4,jt=async e=>{let{operation:r}=e,t=await nl();if(t.length===0)return;l.error(`working tree has uncommitted changes:
|
|
395
395
|
${t.join(`
|
|
396
|
-
`)}`);let o=t.slice(0,
|
|
396
|
+
`)}`);let o=t.slice(0,Uy),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}`})},Io=async e=>{let{operation:r,base:t}=e;if(await nt()===t)return;let o=(await Ze(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}`})},ie=async e=>{let{operation:r}=e;if(await il())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 jt({operation:r})};import{$ as Fd}from"zx";var Ld="dev",ur=e=>e==="hotfix"?"main":"dev",_o=(e,r)=>(r??"").trim()!==""?`${e}
|
|
397
397
|
|
|
398
398
|
${r}`:`${e}
|
|
399
|
-
`,
|
|
400
|
-
`),e),
|
|
401
|
-
`).map(t=>t.trim()).filter(t=>t.length>0)}catch{return[]}},
|
|
402
|
-
\u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${
|
|
403
|
-
\u{1F50E} Verifying ${p.length} merge(s) with: ${s}`);let f=await
|
|
404
|
-
`)[0]??""}`);let k=await
|
|
405
|
-
\u2B06\uFE0F Pushing atomically: ${p.map(f=>f.branch).join(", ")}`);let u=await
|
|
406
|
-
`)[0],observedLanded:v.map(f=>f.branch)}},
|
|
407
|
-
\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 z(p,`Are you sure you want to merge dev into these branches: ${m.join(", ")}?`,{throwOnDecline:!0})}catch(f){if(!
|
|
399
|
+
`,va=async(e="regular")=>{let r=ur(e),t=Fd({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 Fd({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()},Ky=async e=>{let{versionName:r,jiraConfig:t,description:o}=e,n=await Ve(r,t);if(!n)return(await Zi({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 $t({versionId:n.id,description:s},t),{...n,description:s}):n},ya=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular",baseSha:s}=e,i=Z(r),a=await Ky({versionName:i,jiraConfig:t,description:o}),c=cr(t,a),p=await rs({id:r,jiraVersionUrl:c,type:n,description:o,baseSha:s});return{version:V(r),type:n,branchName:p.branchName,prUrl:p.prUrl,jiraVersionUrl:c}},K=async()=>{let e=new Map,r=await Be();if(!r)return e;try{let t=await At(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},Do=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},N=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Wd=e=>e.flatMap(r=>{let t=W(r);return t?[{branch:r,id:t,label:V(t)}]:[]}),Ue=e=>{try{return Re(ye(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")'})}},Oo=e=>{if(e===Ld)return Ld;let r=W(e);return r?V(r):e},Vr=e=>e.flatMap(r=>{let t=W(r);return t?[V(t)]:[]}),Hy=(e,r)=>r?r.get(e)||"regular":void 0,ee=e=>{let{branches:r,descriptions:t,types:o}=e;return Wd(r).map(({branch:n,id:s,label:i})=>({value:n,label:i,description:t.get(Z(s)),type:Hy(n,o)}))};var zy=e=>e.map(r=>({pr:r,id:W(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>ol(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),No=200,Jd=(e,r)=>{e.length<No||l.warn({source:r,limit:No},`\u26A0\uFE0F ${r} returned ${No} PRs \u2014 the page is full, so older release PRs may be missing`)},qy=async()=>{let e=await Ft`gh pr list --limit ${No} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await Ft`gh pr list --limit ${No} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=JSON.parse(e.stdout),o=JSON.parse(r.stdout);Jd(t,"release PR discovery (base dev)"),Jd(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))},Vd=async()=>{try{let e=await qy();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 zy(e)}catch(e){throw e instanceof g?e:(l.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},ts=async()=>(await Vd()).map(r=>r.headRefName),_=async()=>(await Vd()).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt})),os=async e=>{let{branch:r,body:t}=e;try{await Ft({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}},Yy=async(e,r)=>{let t=Ft({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`)},rs=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n,baseSha:s}=e,i=tl(r,o),a=ur(o),c=Ft({quiet:!0}),p=Re(r),d=_o(t,n);try{await jt({operation:`create release branch ${p}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new g(void 0,{operation:`create release branch ${p}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${u.slice(0,8)}`});await c`git checkout -b ${p}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${p}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${p}`;return{branchName:p,prUrl:m.stdout.trim()}}catch(m){throw await Yy(p,a),m}}catch(u){throw l.error({error:u,branchName:p},`Error creating release branch ${p}`),u}finally{await Ft({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Zy}from"zx";var Br=async e=>{let r=await Zy`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null};import ek from"node:process";var Mo=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};import Xy from"node:process";var Lt={enabled:!1},Qy=(e,r=t=>{Xy.stdout.write(t)})=>(Lt.enabled&&e&&e.structuredContent!=null&&r(`${JSON.stringify(e.structuredContent,null,2)}
|
|
400
|
+
`),e),Bd=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(Bd)};var Gd=()=>{if(j()||!ek.stdin.isTTY||Lt.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"})},mr=async e=>{Gd();let{runBranchPicker:r}=await import("./boot-BL4EQMZV.js"),t=await r(e);if(t===null)throw new Mo;return t},Wt=async(e,r)=>{Gd();let{runBranchMultiPicker:t}=await import("./boot-BL4EQMZV.js"),o=await t(e,r);if(o===null)throw new Mo;return o};import{$ as Gr}from"zx";var rk="Merge remote-tracking branch 'origin/dev' into ",Ud=e=>String(e.stderr??e.message??e).trim(),tk=async e=>{try{return(await Gr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
|
|
401
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}catch{return[]}},ok=async(e,r)=>{let t=Ud(r),o=await tk(e);return o.length>0?{status:"conflict",conflictPaths:o,reason:t}:await ll(e)?{status:"hook-failed",reason:t}:{status:"error",reason:t}},Kd=async e=>{let{cwd:r,worktreePath:t,branches:o}=e,n=[],s=await Yt(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 nk({cwd:r,worktreePath:t,branch:i,devSha:s});n.push({...c,durationMs:Date.now()-a})}return n},nk=async e=>{let{cwd:r,worktreePath:t,branch:o,devSha:n}=e,s=`origin/${o}`;if(!await Yt(r,s))return{branch:o,status:"error",reason:`${s} does not exist on origin`};if(await Es(r,"origin/dev",s))return{branch:o,status:"up-to-date"};try{await xs(t),await Gr({cwd:t,quiet:!0})`git checkout --detach ${s}`;let i=`${rk}${o}`;await Gr({cwd:t,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await Gr({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 ok(t,i)}}finally{await Ss(t)}},Hd=e=>e.flatMap(r=>r.mergeSha?[{branch:r.branch,sha:r.mergeSha}]:[]),zd="pnpm install --frozen-lockfile",qd=async e=>{let{worktreePath:r,refs:t,command:o}=e,n=[],s=new Map;for(let i of t)try{await xs(r),await Gr({cwd:r,quiet:!0})`git checkout --detach ${i.sha}`,await Gr({cwd:r,quiet:!0})`sh -c ${o}`,n.push(i)}catch(a){s.set(i.branch,Ud(a))}finally{await Ss(r)}return{kept:n,failed:s}},ka=async(e,r)=>{await Gr({cwd:e,quiet:!0})`git fetch origin --prune`;let t=[],o=[];for(let n of r)await Es(e,"origin/dev",`origin/${n.branch}`)?o.push(n.branch):t.push(n);return{kept:t,nowUpToDate:o}};import wa from"node:process";var ns=new Set,Yd=e=>(ns.add(e),()=>{ns.delete(e)}),sk=async()=>{for(let e of[...ns])try{await e()}catch(r){l.warn({error:r,msg:"cleanup failed during shutdown"})}ns.clear()},ik=["SIGINT","SIGTERM"],wO=async(e,r={})=>{let{register:t=(i,a)=>{wa.on(i,a)},unregister:o=(i,a)=>{wa.off(i,a)},exit:n=i=>{wa.exit(i)}}=r,s=new Map;for(let i of ik){let a=()=>{sk().then(()=>{n(kl(i))})};s.set(i,a),t(i,a)}try{return await e()}finally{for(let[i,a]of s)o(i,a)}};var ck=e=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[]}),Xd=e=>({content:y(JSON.stringify(e,null,2)),structuredContent:e}),Zd=new Set(["up-to-date","fast-forward","merged"]),lk=(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=Re(ye(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))},pk={"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"},Qd=e=>{let r=pk[e.status];if(e.status==="conflict"){let t=e.conflictPaths?.length??0;return`${r}: ${t} file(s)`}return e.reason?`${r}: ${e.reason}`:r},dk=e=>{l.info(`
|
|
402
|
+
\u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${Qd(r)}`)},uk=(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`},mk=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=W(i.branch);return a?[[Z(a),Qd(i)]]:[]}));return Wt(ee({branches:t,descriptions:s}),{required:!0})},fk=async e=>{let{cwd:r,worktreePath:t,entries:o,selected:n,verify:s}=e,i=o.filter(f=>n.includes(f.branch)),a=f=>{for(let k of f)l.info(`\u2139\uFE0F ${k} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await ka(r,Hd(i));a(c.nowUpToDate);let p=c.kept,d=new Map;if(s&&p.length>0){l.info(`
|
|
403
|
+
\u{1F50E} Verifying ${p.length} merge(s) with: ${s}`);let f=await qd({worktreePath:t,refs:p,command:s});d=f.failed;for(let[x,D]of f.failed)l.info(`\u2717 ${x} failed verification \u2014 not pushing it. ${D.split(`
|
|
404
|
+
`)[0]??""}`);let k=await ka(r,f.kept);a(k.nowUpToDate),p=k.kept}if(p.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};l.info(`
|
|
405
|
+
\u2B06\uFE0F Pushing atomically: ${p.map(f=>f.branch).join(", ")}`);let u=await cl(r,p);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let v=(await Promise.all(p.map(async f=>({branch:f.branch,landed:await vn(r,f.branch)===f.sha})))).filter(f=>f.landed);return v.length>0&&l.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${v.map(f=>f.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
|
|
406
|
+
`)[0],observedLanded:v.map(f=>f.branch)}},eu=async e=>{let{all:r,versions:t,dryRun:o=!1,verify:n,confirmedCommand:s}=e,i=n===!0?zd:n||void 0;await ha({operation:"merge dev into release branches"});let c=(await _()).filter(P=>N(P.title)==="regular").map(P=>P.branch);if(c.length===0)return l.info("\u2139\uFE0F No open release branches found"),h.print(),Xd(ck(o));let p=await Pe();try{await ak({cwd:p,quiet:!0})`git fetch origin --prune`}catch(P){throw new g(P,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let d=t===void 0?c:lk(t,c),u=await pl({cwd:p},async P=>{let _e=Yd(P.remove);try{return await gk({cwd:p,worktree:P,toPlan:d,candidates:c,all:r,versions:t,dryRun:o,verify:i,confirmedCommand:s})}finally{_e()}}),{entries:m,selected:v,pushed:f,pushAborted:k,abortedBy:x,declined:D,verifyFailed:O}=u,C=await Ze(p).catch(()=>[]);return hk({entries:m,selected:v,pushed:f,pushAborted:k,abortedBy:x,declined:D,verifyFailed:O,dryRun:o,worktrees:C})},gk=async e=>{let{cwd:r,worktree:t,toPlan:o,candidates:n,all:s,versions:i,dryRun:a,verify:c,confirmedCommand:p}=e,d=await Kd({cwd:r,worktreePath:t.path,branches:o}),u={entries:d,pushed:!1,pushAborted:!1,declined:!1};if(dk(d),a)return{...u,selected:o};let m=await mk({entries:d,toPlan:o,all:s,explicit:i!==void 0});m.length===n.length?h.addOption("--all",!0):h.addOption("--versions",m);let v=d.filter(f=>m.includes(f.branch)&&f.mergeSha).length;v>0&&l.info(`
|
|
407
|
+
\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 z(p,`Are you sure you want to merge dev into these branches: ${m.join(", ")}?`,{throwOnDecline:!0})}catch(f){if(!Rn(f))throw f;return{...u,selected:m,declined:!0}}return p||h.addOption("--yes",!0),{entries:d,selected:m,declined:!1,...await fk({cwd:r,worktreePath:t.path,entries:d,selected:m,verify:c})}},hk=e=>{let{entries:r,selected:t,pushed:o,pushAborted:n,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:p}=e,d=new Set(o?r.filter(f=>t.includes(f.branch)&&f.mergeSha&&!p?.has(f.branch)).map(f=>f.branch):[]),u=r.filter(f=>t.includes(f.branch)).map(f=>{let k=!!f.mergeSha,x=e.verifyFailed?.get(f.branch),D=n&&k?"push-aborted":f.status,O=x?"verify-failed":D;return{branch:f.branch,status:O,mergeSha:f.mergeSha,conflictPaths:f.conflictPaths,pushed:d.has(f.branch),reason:x??f.reason}}),m=u.filter(f=>!Zd.has(f.status));for(let f of u){let k=r.find(x=>x.branch===f.branch);l.info({branch:f.branch,status:f.status,mergeSha:f.mergeSha,conflictCount:f.conflictPaths?.length??0,durationMs:k?.durationMs,pushed:f.pushed,msg:"merge-dev branch result"})}if(i||a)l.info(i?`
|
|
408
408
|
Operation cancelled \u2014 nothing was pushed.
|
|
409
409
|
`:`
|
|
410
410
|
\u{1F50D} Dry run \u2014 nothing was pushed.
|
|
411
411
|
`);else if(m.length>0){l.info(`
|
|
412
412
|
\u26A0\uFE0F ${m.length} branch(es) did not merge.
|
|
413
413
|
`);for(let f of m)l.info(`# ${f.branch} \u2014 ${f.status}
|
|
414
|
-
${
|
|
414
|
+
${uk(f.branch,c)}
|
|
415
415
|
`)}else l.info(`\u2705 All merges completed successfully!
|
|
416
|
-
`);h.print();let v=a||i;return Hd({successfulMerges:v?0:u.filter(f=>Kd.has(f.status)).length,failedMerges:v?0:m.length,failedBranches:v?[]:m.map(f=>f.branch),totalBranches:u.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:n,abortedBy:s},results:u.map(f=>v?{...f,pushed:!1}:f)})},ya=w({name:"gh-merge-dev",description:"Merge origin/dev into open regular (non-hotfix) release branches and push them in one atomic push. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:S.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:S.union([S.string(),S.array(S.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error \u2014 hotfix branches cannot be selected. Takes precedence over `all`.'),dryRun:S.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:S.union([S.boolean(),S.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push."),confirm:S.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:S.number().describe("Number of branches that reached their desired state"),failedMerges:S.number().describe("Number of branches that did not"),failedBranches:S.array(S.string()).describe("List of branches that did not merge"),totalBranches:S.number().describe("Total number of branches processed"),dryRun:S.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:S.object({attempted:S.boolean(),aborted:S.boolean(),abortedBy:S.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:S.array(S.object({branch:S.string(),status:S.string(),mergeSha:S.string().optional(),conflictPaths:S.array(S.string()).optional(),pushed:S.boolean(),reason:S.string().optional()})).describe("Per-branch terminal state")},handler:qd});import{z as Fo}from"zod";import{$ as ve}from"zx";var Yd=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},fr=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=Yd(r.stderr,500);n&&(t.stderr=n);let s=Yd(r.stdout,200);return s&&(t.stdout=s),t};var No=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 Mo=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 ns from"node:fs/promises";import{$ as eu}from"zx";var pk=new Set([".omc",".DS_Store"]),dk=new Set(["state","sessions"]),uk=2e3,mk="check 'git worktree list' for the path; uncommitted changes block removal",fk=e=>new Promise(r=>{setTimeout(r,e)}),ka=e=>typeof e=="object"&&e!==null?e.code:void 0,Zd=e=>{let r=e.length;for(;r>1&&e[r-1]==="/";)r-=1;return e.slice(0,r)},Xd=async e=>{try{return Zd(await ns.realpath(e))}catch{return Zd(e)}},gk=async e=>{let{projectRoot:r,worktreePath:t}=e;try{let o=await Ze(r),n=await Xd(t);for(let s of o)if(await Xd(s.path)===n)return!0;return!1}catch{return!0}},hk=async e=>{let r;try{r=await ns.readdir(e)}catch(o){return{kind:ka(o)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!r.every(o=>pk.has(o)))return{kind:"not-sweepable",entries:r};if(!r.includes(".omc"))return{kind:"sweepable",entries:r};try{return{kind:(await ns.readdir(`${e}/.omc`)).every(s=>dk.has(s))?"sweepable":"not-sweepable",entries:r}}catch(o){return{kind:ka(o)==="ENOENT"?"sweepable":"not-sweepable",entries:r}}},Qd=async e=>{try{return await ns.rm(e,{recursive:!0,force:!0}),"removed"}catch(r){return ka(r)==="ENOTEMPTY"?"busy":"failed"}},vk=async e=>{let{worktreePath:r,sleep:t}=e,o=await Qd(r);return o!=="busy"?o==="removed":(await t(uk),await Qd(r)==="removed")},os=(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}},yk=async e=>{let{branch:r,worktreePath:t,projectRoot:o,error:n,sleep:s}=e;if(await gk({projectRoot:o,worktreePath:t}))return os(r,n,mk);let i=await hk(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 vk({worktreePath:t,sleep:s})?os(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"})},kk=async e=>{let{branch:r,worktreeDir:t,projectRoot:o,sleep:n}=e,s=`${t}/${r}`;try{await bn(s)}catch(i){return os(r,i,"close the cmux workspace for this worktree manually and re-run")}try{return await eu`git worktree remove ${s}`,{branch:r,status:"removed"}}catch(i){return yk({branch:r,worktreePath:s,projectRoot:o,error:i,sleep:n})}},Ur=async e=>{let{branches:r,worktreeDir:t,projectRoot:o,pruneFolder:n=!1,sleep:s=fk}=e,i=await Promise.all(r.map(c=>kk({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 eu`git worktree prune`,a};var jo=async(e,r)=>{if(!(await de("release")).includes(e))return[];let o=await R(),n=`${o}${re}`,{removed:s,failed:i}=await Ur({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 Wt=async(e,r,t)=>{try{return await t()}catch(o){throw l.debug({err:fr(o)},`Failed to ${e}`),new g(o,{operation:e,remediation:r})}},wk=async e=>{let r=ws(e),t=await ve`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},ru=async()=>{let e=await ve`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},bk=async e=>{let r=Ue(e),t=await Br(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}},Rk=async()=>{let e=await _(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,N(i.title)]));h.setInteractive();let o=await K(),n=await mr(ee({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}},Pk=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await Br(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 Wt(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await ve`gh pr merge ${r} --squash --admin --delete-branch`})},Ek=async e=>{let r=V(e),t=ws(e),o=await ru();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 Wt(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await ve`gh pr edit ${s} --title ${t}`})),s}await Wt(`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 ve`gh pr create --base main --head dev --title ${t} --body ""`});let n=await ru();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},xk=async e=>{let r=V(e);if(await wk(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Ek(e);await Wt(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await ve`gh pr merge ${o} --squash --admin`})},Sk=async()=>{ve.quiet=!1,await Wt("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await ve`gh workflow run deploy-all.yml --ref main -f environment=prod`}),ve.quiet=!0},Tk=async()=>{await Wt("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 ve`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Ck=async e=>{try{await mn(e)}catch(r){l.warn({err:fr(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await fn(e)}catch(r){l.warn({err:fr(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},Ak=async e=>{let r=await Be();if(!r){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=Z(e);await qi({versionName:t},r)}catch(t){let o=So(t)&&t.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";l.error({err:fr(t)},`Failed to deliver Jira release (non-blocking)${o}`)}},tu=async e=>{let{version:r,confirmedCommand:t}=e;await ie({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await bk(r):await Rk(),s=L(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=V(s);h.addOption("--version",i),l.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let a=N(n);await z(t,`Are you sure you want to deliver version ${o} to production?`),h.addOption("--yes",!0),ve.quiet=!0;let p=`${await R()}${re}`;await jo(o,{operation:`remove worktree for ${o} before merge`,remediation:`run manually: git worktree remove ${p}/${o} (use --force if uncommitted changes)`}),await Pk({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await xk(s),await Sk(),await Tk(),await Ck(o),ve.quiet=!1,await Ak(s),l.info(`Successfully delivered ${o} to production!`),h.print();let d={releaseBranch:o,version:i,type:a,success:!0};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},wa=w({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:Fo.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:Fo.string().describe("The release branch that was delivered"),version:Fo.string().describe("The version that was delivered"),type:Fo.enum(["regular","hotfix"]).describe("Release type"),success:Fo.boolean().describe("Whether the delivery was successful")},handler:tu});import{z as Ke}from"zod";import{$ as Ca}from"zx";import{z as Jo}from"zod";import ou from"node:fs/promises";import ba from"node:path";var nu=".github/workflows",$k=/script_name:\s*(?<service>[a-z0-9-]+)/,Ik=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,_k=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Ra=async e=>{let r=ba.resolve(e,nu),t;try{t=await ou.readdir(r)}catch{return new Map}return su(r,t.filter(o=>o.endsWith(".yml")||o.endsWith(".yaml")))},Lo=async(e,r)=>su(ba.resolve(e,nu),[r]),su=async(e,r)=>{let t=new Map;for(let o of r){let n;try{n=await ou.readFile(ba.resolve(e,o),"utf-8")}catch{continue}Dk(n,t)}return t},Dk=(e,r)=>{for(let t of e.split(/\n(?= {2}[\w-]+:)/i)){let o=$k.exec(t)?.groups?.service??Ik.exec(t)?.groups?.service;if(o===void 0||t.trimStart().startsWith("#"))continue;let n=[...t.matchAll(_k)].map(s=>s.groups?.env??"");n.length!==0&&r.set(o,[...new Set([...r.get(o)??[],...n])])}},Pa=(e,r)=>e===null?r??null:r===void 0?e:e.filter(t=>r.includes(t));import Ok from"node:fs/promises";import Nk from"node:path";import Mk from"yaml";var jk=".github/workflows",Fk="skip_terraform_deploy",Wo=async(e,r)=>{let t=Nk.resolve(e,jk,r),o;try{o=Mk.parse(await Ok.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!==Fk).map(([i])=>i)};var iu="dev",Ea=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),au=(e,r)=>e[r]===void 0,cu=(e,r)=>{let t=e[r];return typeof t=="string"&&t.length>0?t:void 0},xa=async e=>{try{return await e}catch{return[]}},Lk=async()=>{let e=await _();return Vr(e.map(r=>r.branch))},Wk=(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},Kr=e=>{let{workflowFile:r,fields:t,toolName:o}=e,n=c=>(l.info({msg:`Tool execution form options empty (${r}): ${o}`,emptyList:c}),null),s=async c=>{let p=await xa(Lk());if(p.length===0)return null;let d=cu(c,"version");return Jo.enum([...new Set([...p,iu])]).optional().describe(`Which release to deploy from. "${iu}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let p=je(await xa(Le(r)),await Fe());if(p.length===0)return null;let d=p.filter(Rt),u=p.filter(v=>!Rt(v)),m=cu(c,"env");return Jo.enum(p).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${r} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await R(),p=await xa(Wo(c,r));if(p.length===0)return null;let d=await Lo(c,r);return Jo.array(Jo.enum(p)).optional().describe(`Services to deploy. Environment gates declared by ${r} \u2014 ${Wk(p,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${o}. Anything left blank keeps what the caller sent.`,isFormable:c=>Ea(c)?t.some(p=>au(c,p)):!1,buildRequestedSchema:async c=>{let p=Ea(c)?c:{},d={};if(t.includes("version")){let u=await s(p);if(u===null)return n("releases");d.version=u}if(t.includes("env")){let u=await i(p);if(u===null)return n("envs");d.env=u}if(t.includes("services")&&au(p,"services")){let u=await a();if(u===null)return n("services");d.services=u}return Object.keys(d).length===0?n("fields"):Jo.object(d)},toArgs:(c,p)=>{let d={...Ea(p)?p:{}};for(let u of t){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;d[u]=m}}return d}}};import Jk from"@inquirer/select";var Jt=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=>Jk({message:"\u{1F9EA} Select environment",choices:e.map(o=>({name:o,value:o}))},t),{whenHeadless:"refuse"})};import Vk from"@inquirer/confirm";var Vo=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;h.setInteractive();let n=await A(s=>Vk({message:`Deploy ${t} \u2192 ${o} via GitHub Actions?`,default:!1},s),{whenHeadless:"refuse"});return n&&h.addOption("--yes",!0),n};import Bk from"@inquirer/select";import Gk from"node:process";var Sa=()=>!J()&&Gk.stdin.isTTY===!0&&!Ft.enabled,Uk={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Ta=async()=>A(e=>Bk({message:"\u{1F680} Where should this deploy run?",choices:Vt.map(r=>({name:r,value:r,description:Uk[r]}))},e),{whenHeadless:"refuse"});var Vt=["ci","local"],Kk={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},lu=e=>{if(!e)throw new g(void 0,{operation:"resolve the deploy source",remediation:`pass --from with one of: ${Vt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"});let r=Vt.find(t=>t===e);if(!r)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Vt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return r},Hk=(e,r)=>{let o=Kk[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}`})},zk=async e=>e||!Sa()?lu(e):Ta();var Bo=async e=>{if(e)return e==="dev"?"dev":Ue(e);h.setInteractive();let r=await _(),t=r.map(s=>s.branch),o=new Map(r.map(s=>[s.branch,N(s.title)])),n=await K();return mr([{value:"dev",label:"dev"},...ee({branches:t,descriptions:n,types:o})])};var pu="deploy-all.yml",du=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:n}=e,s=await Bo(r),i=_o(s);h.addOption("--version",i);let a=await Fe(),c=je(await Le(pu),a),p="";t?p=t:(h.setInteractive(),p=await Jt(c,"launch deploy-all workflow")),h.addOption("--env",p),Ir(p,"launch deploy-all workflow",a),ho({env:p,branch:s});let d=o??!1;if(d&&h.addOption("--skip-terraform",!0),!await Vo({confirmedCommand:n,branch:s,env:p})){l.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:p,skipTerraformDeploy:d,success:!1};return{content:y(JSON.stringify(u,null,2)),structuredContent:u}}try{Ca.quiet=!0,await Ca`gh workflow run deploy-all.yml --ref ${s} -f environment=${p} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Ca.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${p}`),h.print();let m={releaseBranch:s,version:i,environment:p,skipTerraformDeploy:d,success:!0};return{content:y(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw l.error({error:u},"\u274C Error launching workflow"),new g(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Aa=w({name:"gh-release-deploy-all",formProvider:Kr({workflowFile:pu,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:Ke.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:Ke.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:Ke.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ke.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ke.string().describe("The release branch that was deployed"),version:Ke.string().describe("The version that was deployed"),environment:Ke.string().describe("The environment deployed to"),skipTerraformDeploy:Ke.boolean().describe("Whether terraform deployment was skipped"),success:Ke.boolean().describe("Whether the deployment was successful")},handler:du});import qk from"@inquirer/checkbox";import{z as ae}from"zod";import{$ as $a}from"zx";var Hr="deploy-selected-services.yml",uu=async e=>{let{version:r,env:t,services:o,skipTerraform:n,confirmedCommand:s}=e,i=await Bo(r),a=_o(i);h.addOption("--version",a);let c=await Fe(),p=je(await Le(Hr),c),d="";t?d=t:(h.setInteractive(),d=await Jt(p,"launch deploy-selected workflow")),h.addOption("--env",d),Ir(d,"launch deploy-selected workflow",c),ho({env:d,branch:i});let u=await R(),m=await Wo(u,Hr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Hr}`,stderrExcerpt:`no services found in .github/workflows/${Hr}`});let v=[];if(o&&o.length>0?v=o:(h.setInteractive(),v=await A(C=>qk({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},C),{whenHeadless:"refuse"})),h.addOption("--services",v),v.length===0)throw new 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 k=await Lo(u,Hr),x=v.filter(C=>{let P=k.get(C);return P!==void 0&&!P.includes(d)});if(x.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:x.map(C=>`${C} deploys only to: ${(k.get(C)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Hr} gates these services out of ${d}: ${x.join(", ")}`});let D=n??!1;D&&h.addOption("--skip-terraform",!0);let O=C=>{let P={releaseBranch:i,version:a,environment:d,services:v,skipTerraformDeploy:D,success:C};return{content:y(JSON.stringify(P,null,2)),structuredContent:P}};if(!await Vo({confirmedCommand:s,branch:i,env:d}))return l.info("Deployment cancelled"),O(!1);try{$a.quiet=!0;let C=v.flatMap(_e=>["-f",`${_e}=true`]);return await $a`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${C} ${D?["-f","skip_terraform_deploy=true"]:[]}`,$a.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${v.join(", ")}`),h.print(),O(!0)}catch(C){throw l.error({error:C},"\u274C Error launching workflow"),new g(C,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Ia=w({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Kr({workflowFile:Hr,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:ae.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:ae.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:ae.array(ae.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:ae.boolean().optional().describe("Skip the terraform deployment stage."),confirm:ae.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:ae.string().describe("The release branch that was deployed"),version:ae.string().describe("The version that was deployed"),environment:ae.string().describe("The environment deployed to"),services:ae.array(ae.string()).describe("The services that were deployed"),skipTerraformDeploy:ae.boolean().describe("Whether terraform deployment was skipped"),success:ae.boolean().describe("Whether the deployment was successful")},handler:uu});import{z as Bt}from"zod";var mu=async()=>{let r=(await _()).flatMap(i=>{let a=L(i.branch);return a?[{version:V(a),jiraKey:Z(a),type:N(i.title)}]:[]}),t=await K(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let a=Io(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
|
|
416
|
+
`);h.print();let v=a||i;return Xd({successfulMerges:v?0:u.filter(f=>Zd.has(f.status)).length,failedMerges:v?0:m.length,failedBranches:v?[]:m.map(f=>f.branch),totalBranches:u.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:n,abortedBy:s},results:u.map(f=>v?{...f,pushed:!1}:f)})},ba=w({name:"gh-merge-dev",description:"Merge origin/dev into open regular (non-hotfix) release branches and push them in one atomic push. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.",requiresHumanConfirm:!0,inputSchema:{all:S.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:S.union([S.string(),S.array(S.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error \u2014 hotfix branches cannot be selected. Takes precedence over `all`.'),dryRun:S.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:S.union([S.boolean(),S.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push."),confirm:S.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:S.number().describe("Number of branches that reached their desired state"),failedMerges:S.number().describe("Number of branches that did not"),failedBranches:S.array(S.string()).describe("List of branches that did not merge"),totalBranches:S.number().describe("Total number of branches processed"),dryRun:S.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:S.object({attempted:S.boolean(),aborted:S.boolean(),abortedBy:S.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:S.array(S.object({branch:S.string(),status:S.string(),mergeSha:S.string().optional(),conflictPaths:S.array(S.string()).optional(),pushed:S.boolean(),reason:S.string().optional()})).describe("Per-branch terminal state")},handler:eu});import{z as Wo}from"zod";import{$ as ve}from"zx";var ru=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},fr=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=ru(r.stderr,500);n&&(t.stderr=n);let s=ru(r.stdout,200);return s&&(t.stdout=s),t};var jo=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 Fo=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 is from"node:fs/promises";import{$ as su}from"zx";var vk=new Set([".omc",".DS_Store"]),yk=new Set(["state","sessions"]),kk=2e3,wk="check 'git worktree list' for the path; uncommitted changes block removal",bk=e=>new Promise(r=>{setTimeout(r,e)}),Ra=e=>typeof e=="object"&&e!==null?e.code:void 0,tu=e=>{let r=e.length;for(;r>1&&e[r-1]==="/";)r-=1;return e.slice(0,r)},ou=async e=>{try{return tu(await is.realpath(e))}catch{return tu(e)}},Rk=async e=>{let{projectRoot:r,worktreePath:t}=e;try{let o=await Ze(r),n=await ou(t);for(let s of o)if(await ou(s.path)===n)return!0;return!1}catch{return!0}},Pk=async e=>{let r;try{r=await is.readdir(e)}catch(o){return{kind:Ra(o)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!r.every(o=>vk.has(o)))return{kind:"not-sweepable",entries:r};if(!r.includes(".omc"))return{kind:"sweepable",entries:r};try{return{kind:(await is.readdir(`${e}/.omc`)).every(s=>yk.has(s))?"sweepable":"not-sweepable",entries:r}}catch(o){return{kind:Ra(o)==="ENOENT"?"sweepable":"not-sweepable",entries:r}}},nu=async e=>{try{return await is.rm(e,{recursive:!0,force:!0}),"removed"}catch(r){return Ra(r)==="ENOTEMPTY"?"busy":"failed"}},Ek=async e=>{let{worktreePath:r,sleep:t}=e,o=await nu(r);return o!=="busy"?o==="removed":(await t(kk),await nu(r)==="removed")},ss=(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}},xk=async e=>{let{branch:r,worktreePath:t,projectRoot:o,error:n,sleep:s}=e;if(await Rk({projectRoot:o,worktreePath:t}))return ss(r,n,wk);let i=await Pk(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 Ek({worktreePath:t,sleep:s})?ss(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"})},Sk=async e=>{let{branch:r,worktreeDir:t,projectRoot:o,sleep:n}=e,s=`${t}/${r}`;try{await Pn(s)}catch(i){return ss(r,i,"close the cmux workspace for this worktree manually and re-run")}try{return await su`git worktree remove ${s}`,{branch:r,status:"removed"}}catch(i){return xk({branch:r,worktreePath:s,projectRoot:o,error:i,sleep:n})}},Ur=async e=>{let{branches:r,worktreeDir:t,projectRoot:o,pruneFolder:n=!1,sleep:s=bk}=e,i=await Promise.all(r.map(c=>Sk({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 su`git worktree prune`,a};var Lo=async(e,r)=>{if(!(await de("release")).includes(e))return[];let o=await R(),n=`${o}${re}`,{removed:s,failed:i}=await Ur({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 Jt=async(e,r,t)=>{try{return await t()}catch(o){throw l.debug({err:fr(o)},`Failed to ${e}`),new g(o,{operation:e,remediation:r})}},Tk=async e=>{let r=Ps(e),t=await ve`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},iu=async()=>{let e=await ve`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},Ck=async e=>{let r=Ue(e),t=await Br(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}},Ak=async()=>{let e=await _(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,N(i.title)]));h.setInteractive();let o=await K(),n=await mr(ee({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}},$k=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await Br(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 Jt(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await ve`gh pr merge ${r} --squash --admin --delete-branch`})},Ik=async e=>{let r=V(e),t=Ps(e),o=await iu();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 Jt(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await ve`gh pr edit ${s} --title ${t}`})),s}await Jt(`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 ve`gh pr create --base main --head dev --title ${t} --body ""`});let n=await iu();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},_k=async e=>{let r=V(e);if(await Tk(e)){l.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Ik(e);await Jt(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await ve`gh pr merge ${o} --squash --admin`})},Dk=async()=>{ve.quiet=!1,await Jt("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await ve`gh workflow run deploy-all.yml --ref main -f environment=prod`}),ve.quiet=!0},Ok=async()=>{await Jt("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 ve`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Nk=async e=>{try{await gn(e)}catch(r){l.warn({err:fr(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await hn(e)}catch(r){l.warn({err:fr(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},Mk=async e=>{let r=await Be();if(!r){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=Z(e);await Xi({versionName:t},r)}catch(t){let o=To(t)&&t.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";l.error({err:fr(t)},`Failed to deliver Jira release (non-blocking)${o}`)}},au=async e=>{let{version:r,confirmedCommand:t}=e;await ie({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await Ck(r):await Ak(),s=W(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=V(s);h.addOption("--version",i),l.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let a=N(n);await z(t,`Are you sure you want to deliver version ${o} to production?`),h.addOption("--yes",!0),ve.quiet=!0;let p=`${await R()}${re}`;await Lo(o,{operation:`remove worktree for ${o} before merge`,remediation:`run manually: git worktree remove ${p}/${o} (use --force if uncommitted changes)`}),await $k({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await _k(s),await Dk(),await Ok(),await Nk(o),ve.quiet=!1,await Mk(s),l.info(`Successfully delivered ${o} to production!`),h.print();let d={releaseBranch:o,version:i,type:a,success:!0};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}},Pa=w({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:Wo.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:Wo.string().describe("The release branch that was delivered"),version:Wo.string().describe("The version that was delivered"),type:Wo.enum(["regular","hotfix"]).describe("Release type"),success:Wo.boolean().describe("Whether the delivery was successful")},handler:au});import{z as Ke}from"zod";import{$ as Ia}from"zx";import{z as Bo}from"zod";import cu from"node:fs/promises";import Ea from"node:path";var lu=".github/workflows",jk=/script_name:\s*(?<service>[a-z0-9-]+)/,Fk=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,Lk=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,xa=async e=>{let r=Ea.resolve(e,lu),t;try{t=await cu.readdir(r)}catch{return new Map}return pu(r,t.filter(o=>o.endsWith(".yml")||o.endsWith(".yaml")))},Jo=async(e,r)=>pu(Ea.resolve(e,lu),[r]),pu=async(e,r)=>{let t=new Map;for(let o of r){let n;try{n=await cu.readFile(Ea.resolve(e,o),"utf-8")}catch{continue}Wk(n,t)}return t},Wk=(e,r)=>{for(let t of e.split(/\n(?= {2}[\w-]+:)/i)){let o=jk.exec(t)?.groups?.service??Fk.exec(t)?.groups?.service;if(o===void 0||t.trimStart().startsWith("#"))continue;let n=[...t.matchAll(Lk)].map(s=>s.groups?.env??"");n.length!==0&&r.set(o,[...new Set([...r.get(o)??[],...n])])}},Sa=(e,r)=>e===null?r??null:r===void 0?e:e.filter(t=>r.includes(t));import Jk from"node:fs/promises";import Vk from"node:path";import Bk from"yaml";var Gk=".github/workflows",Uk="skip_terraform_deploy",Vo=async(e,r)=>{let t=Vk.resolve(e,Gk,r),o;try{o=Bk.parse(await Jk.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!==Uk).map(([i])=>i)};var du="dev",Ta=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),uu=(e,r)=>e[r]===void 0,mu=(e,r)=>{let t=e[r];return typeof t=="string"&&t.length>0?t:void 0},Ca=async e=>{try{return await e}catch{return[]}},Kk=async()=>{let e=await _();return Vr(e.map(r=>r.branch))},Hk=(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},Kr=e=>{let{workflowFile:r,fields:t,toolName:o}=e,n=c=>(l.info({msg:`Tool execution form options empty (${r}): ${o}`,emptyList:c}),null),s=async c=>{let p=await Ca(Kk());if(p.length===0)return null;let d=mu(c,"version");return Bo.enum([...new Set([...p,du])]).optional().describe(`Which release to deploy from. "${du}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let p=je(await Ca(Le(r)),await Fe());if(p.length===0)return null;let d=p.filter(Rt),u=p.filter(v=>!Rt(v)),m=mu(c,"env");return Bo.enum(p).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${r} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await R(),p=await Ca(Vo(c,r));if(p.length===0)return null;let d=await Jo(c,r);return Bo.array(Bo.enum(p)).optional().describe(`Services to deploy. Environment gates declared by ${r} \u2014 ${Hk(p,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${o}. Anything left blank keeps what the caller sent.`,isFormable:c=>Ta(c)?t.some(p=>uu(c,p)):!1,buildRequestedSchema:async c=>{let p=Ta(c)?c:{},d={};if(t.includes("version")){let u=await s(p);if(u===null)return n("releases");d.version=u}if(t.includes("env")){let u=await i(p);if(u===null)return n("envs");d.env=u}if(t.includes("services")&&uu(p,"services")){let u=await a();if(u===null)return n("services");d.services=u}return Object.keys(d).length===0?n("fields"):Bo.object(d)},toArgs:(c,p)=>{let d={...Ta(p)?p:{}};for(let u of t){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;d[u]=m}}return d}}};import zk from"@inquirer/select";var Vt=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=>zk({message:"\u{1F9EA} Select environment",choices:e.map(o=>({name:o,value:o}))},t),{whenHeadless:"refuse"})};import qk from"@inquirer/confirm";var Go=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;h.setInteractive();let n=await A(s=>qk({message:`Deploy ${t} \u2192 ${o} via GitHub Actions?`,default:!1},s),{whenHeadless:"refuse"});return n&&h.addOption("--yes",!0),n};import Yk from"@inquirer/select";import Zk from"node:process";var Aa=()=>!j()&&Zk.stdin.isTTY===!0&&!Lt.enabled,Xk={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},$a=async()=>A(e=>Yk({message:"\u{1F680} Where should this deploy run?",choices:Bt.map(r=>({name:r,value:r,description:Xk[r]}))},e),{whenHeadless:"refuse"});var Bt=["ci","local"],Qk={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},fu=e=>{if(!e)throw new g(void 0,{operation:"resolve the deploy source",remediation:`pass --from with one of: ${Bt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"});let r=Bt.find(t=>t===e);if(!r)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Bt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return r},ew=(e,r)=>{let o=Qk[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}`})},rw=async e=>e||!Aa()?fu(e):$a();var Uo=async e=>{if(e)return e==="dev"?"dev":Ue(e);h.setInteractive();let r=await _(),t=r.map(s=>s.branch),o=new Map(r.map(s=>[s.branch,N(s.title)])),n=await K();return mr([{value:"dev",label:"dev"},...ee({branches:t,descriptions:n,types:o})])};var gu="deploy-all.yml",hu=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:n}=e,s=await Uo(r),i=Oo(s);h.addOption("--version",i);let a=await Fe(),c=je(await Le(gu),a),p="";t?p=t:(h.setInteractive(),p=await Vt(c,"launch deploy-all workflow")),h.addOption("--env",p),Ir(p,"launch deploy-all workflow",a),vo({env:p,branch:s});let d=o??!1;if(d&&h.addOption("--skip-terraform",!0),!await Go({confirmedCommand:n,branch:s,env:p})){l.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:p,skipTerraformDeploy:d,success:!1};return{content:y(JSON.stringify(u,null,2)),structuredContent:u}}try{Ia.quiet=!0,await Ia`gh workflow run deploy-all.yml --ref ${s} -f environment=${p} ${d?["-f","skip_terraform_deploy=true"]:[]}`,Ia.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${p}`),h.print();let m={releaseBranch:s,version:i,environment:p,skipTerraformDeploy:d,success:!0};return{content:y(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw l.error({error:u},"\u274C Error launching workflow"),new g(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},_a=w({name:"gh-release-deploy-all",formProvider:Kr({workflowFile:gu,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:Ke.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:Ke.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:Ke.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ke.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ke.string().describe("The release branch that was deployed"),version:Ke.string().describe("The version that was deployed"),environment:Ke.string().describe("The environment deployed to"),skipTerraformDeploy:Ke.boolean().describe("Whether terraform deployment was skipped"),success:Ke.boolean().describe("Whether the deployment was successful")},handler:hu});import tw from"@inquirer/checkbox";import{z as ae}from"zod";import{$ as Da}from"zx";var Hr="deploy-selected-services.yml",vu=async e=>{let{version:r,env:t,services:o,skipTerraform:n,confirmedCommand:s}=e,i=await Uo(r),a=Oo(i);h.addOption("--version",a);let c=await Fe(),p=je(await Le(Hr),c),d="";t?d=t:(h.setInteractive(),d=await Vt(p,"launch deploy-selected workflow")),h.addOption("--env",d),Ir(d,"launch deploy-selected workflow",c),vo({env:d,branch:i});let u=await R(),m=await Vo(u,Hr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Hr}`,stderrExcerpt:`no services found in .github/workflows/${Hr}`});let v=[];if(o&&o.length>0?v=o:(h.setInteractive(),v=await A(C=>tw({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},C),{whenHeadless:"refuse"})),h.addOption("--services",v),v.length===0)throw new 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 k=await Jo(u,Hr),x=v.filter(C=>{let P=k.get(C);return P!==void 0&&!P.includes(d)});if(x.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:x.map(C=>`${C} deploys only to: ${(k.get(C)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Hr} gates these services out of ${d}: ${x.join(", ")}`});let D=n??!1;D&&h.addOption("--skip-terraform",!0);let O=C=>{let P={releaseBranch:i,version:a,environment:d,services:v,skipTerraformDeploy:D,success:C};return{content:y(JSON.stringify(P,null,2)),structuredContent:P}};if(!await Go({confirmedCommand:s,branch:i,env:d}))return l.info("Deployment cancelled"),O(!1);try{Da.quiet=!0;let C=v.flatMap(_e=>["-f",`${_e}=true`]);return await Da`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${C} ${D?["-f","skip_terraform_deploy=true"]:[]}`,Da.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${v.join(", ")}`),h.print(),O(!0)}catch(C){throw l.error({error:C},"\u274C Error launching workflow"),new g(C,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Oa=w({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Kr({workflowFile:Hr,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:ae.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:ae.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:ae.array(ae.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:ae.boolean().optional().describe("Skip the terraform deployment stage."),confirm:ae.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:ae.string().describe("The release branch that was deployed"),version:ae.string().describe("The version that was deployed"),environment:ae.string().describe("The environment deployed to"),services:ae.array(ae.string()).describe("The services that were deployed"),skipTerraformDeploy:ae.boolean().describe("Whether terraform deployment was skipped"),success:ae.boolean().describe("Whether the deployment was successful")},handler:vu});import{z as Gt}from"zod";var yu=async()=>{let r=(await _()).flatMap(i=>{let a=W(i.branch);return a?[{version:V(a),jiraKey:Z(a),type:N(i.title)}]:[]}),t=await K(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let a=Do(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${a} ${c}`:a});l.info(`All release branches:
|
|
417
417
|
`),l.info(`
|
|
418
418
|
${n.join(`
|
|
419
419
|
`)}
|
|
420
|
-
`);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}},
|
|
421
|
-
`)};import
|
|
422
|
-
`).map((r,t)=>({line:t+1,text:r})).filter(({text:r})=>!r.trimStart().startsWith("#")),
|
|
423
|
-
${
|
|
424
|
-
`)),
|
|
420
|
+
`);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}},Na=w({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:Gt.array(Gt.object({version:Gt.string().describe("Release version"),type:Gt.enum(["regular","hotfix"]).describe("Release type"),description:Gt.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:Gt.number().describe("Number of release branches")},handler:yu});import ow from"node:process";var Ma=e=>({...e}),ja=e=>{let{env:r,branch:t,sha:o,isClean:n,ambient:s=ow.env}=e,i={VITE_DOMAIN_ENV:r,VITE_BRANCH_NAME:t,VITE_COMMIT_HASH:n?o:`${o}-dirty`},a={},c=[];for(let[p,d]of Object.entries(s)){if(p.startsWith("VITE_")){c.push(p);continue}a[p]=d}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:r,DEPLOY_BRANCH:t,DEPLOY_SHA:o,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},as=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(`
|
|
421
|
+
`)};import vw from"@inquirer/checkbox";import yw from"@inquirer/confirm";import kw from"@inquirer/select";import{spawn as ww}from"node:child_process";import bw from"node:process";import{z as J}from"zod";import{$ as Ho}from"zx";import{$ as Ko}from"zx";var nw=async e=>{let r=Ko.quiet;Ko.quiet=!0;try{let t=`/${e}/environment`,o=await Ko`aws sts get-caller-identity --query Account --output text`,n=await Ko`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{Ko.quiet=r}},ku=(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`})},wu=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"})},bu=(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`})},Fa=async e=>{let{env:r,project:t,isShared:o,isClean:n,runningEnvs:s,protectedEnvAccess:i}=e;Ir(r,`deploy to "${r}"`,i),bu(r,s),wu({env:r,isShared:o,isClean:n});let a=await nw(t);return ku(r,a),{identity:a}};import Ru from"node:fs/promises";import cs from"node:path";var sw="devops/scripts",iw=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,aw=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,cw=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,lw=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,La=async e=>{let r=cs.resolve(e,sw),t;try{t=await Ru.readdir(r)}catch{return[]}let o=await xa(e);return(await Promise.all(t.map(s=>({entry:s,match:iw.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=cs.resolve(r,s),c=i?.groups?.service??"",p=dw(await pw(a));return{name:c,scriptPath:a,allowedEnvs:Sa(uw(p),o.get(c)),ssmPrefix:fw(p)}}))).sort((s,i)=>s.name.localeCompare(i.name))},pw=async e=>{try{return await Ru.readFile(e,"utf-8")}catch{return""}},dw=e=>e.split(`
|
|
422
|
+
`).map((r,t)=>({line:t+1,text:r})).filter(({text:r})=>!r.trimStart().startsWith("#")),uw=e=>{let r=e.reduce((o,{text:n})=>o??aw.exec(n)?.groups?.envs,void 0);if(r===void 0)return null;let t=r.split(/\s+/).filter(Boolean);return t.length>0?t:null},mw=e=>{let r=e.replaceAll(/["']/g,"");return r.includes("$")&&(r.includes("/environment")||r.startsWith("$"))},fw=e=>{for(let{line:r,text:t}of e){let o=lw.exec(t)?.groups?.prefix;if(o!==void 0)return o;let n=cw.exec(t)?.groups?.arg;if(n!==void 0&&mw(n))return{unparseable:{line:r,text:t.trim()}}}return null},gw=e=>{let r=new Map;for(let t of e)typeof t.ssmPrefix=="string"&&r.set(t.ssmPrefix,[...r.get(t.ssmPrefix)??[],cs.basename(t.scriptPath)]);return r},hw=e=>{let r=e.flatMap(t=>{if(t.ssmPrefix===null||typeof t.ssmPrefix=="string")return[];let{line:o,text:n}=t.ssmPrefix.unparseable;return[`${cs.basename(t.scriptPath)}:${o}: ${n}`]});if(r.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:r.join("; ")})},Pu=e=>{hw(e);let r=gw(e),[t,...o]=r.keys();if(t===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(o.length>0){let n=[...r.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${r.size} different prefixes across ${e.length} deploy scripts \u2014 ${n}`})}return t},ls=(e,r)=>e.allowedEnvs===null||e.allowedEnvs.includes(r),Wa=(e,r)=>e.filter(t=>ls(t,r));var Va="deploy-all.yml",Eu="/bin/sh",Rw=async()=>{let e=Ho.quiet;Ho.quiet=!0;try{let r=await Ho`gh run list --workflow=${Va} --status=in_progress --json displayTitle`;return JSON.parse(r.stdout).flatMap(o=>/\[(?<env>[a-z0-9-]+)\]/.exec(o.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Ho.quiet=e}},Pw=async(e,r)=>{let t=e.map(n=>({name:n.name,value:n.name})),o=await A(n=>vw({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},Ew=async e=>{let{env:r,isShared:t,count:o}=e;return t?A(n=>kw({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=>yw({message:`Deploy ${o} service(s) to ${r} from this machine?`,default:!1},n),{whenHeadless:"refuse"})},xw=(e,r,t)=>new Promise((o,n)=>{let s=ww(Eu,[e.scriptPath],{cwd:t,env:r,stdio:"inherit"});s.on("error",n),s.on("close",i=>{o(i??1)})}),Sw=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 xw(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}},Tw=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&&!ls(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))},Ja=e=>{let{env:r,accountId:t,names:o,built:n,deployed:s,failed:i,dryRun:a,success:c}=e,p={environment:r,accountId:t,services:o,deployed:s,failed:i,contract:Ma(n.contract),strippedVars:n.stripped,dryRun:a,success:c};return{content:y(JSON.stringify(p,null,2)),structuredContent:p}},Cw=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(),Pw(t,n))},xu=async(e,r)=>{let{env:t,service:o,confirmedCommand:n,dryRun:s,printEnv:i}=e,a=await R(),c=await La(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let p=Pu(c),d=await Fe(),u=je(await Le(Va),d),m=t??"";m||(h.setInteractive(),m=await Vt(u,"deploy locally")),h.addOption("--env",m);let v=Wa(c,m);if(v.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let f=await Cw({selection:r,eligible:v,service:o,env:m}),k=Tw({names:f,services:c,env:m});if(r==="selected")for(let vr of f)h.addOption("--service",vr);let x=Rt(m),D=await nt(),O=(await Ho`git rev-parse HEAD`.quiet()).stdout.trim(),C=await sl(),P=ja({env:m,branch:D,sha:O,isClean:C});i&&l.info(`Deploy contract for ${m}:
|
|
423
|
+
${as(P)}`);let ce=(await Fa({env:m,project:p,isShared:x,isClean:C,runningEnvs:await Rw(),protectedEnvAccess:d})).identity.accountId;if(s)return l.info([`Would deploy to "${m}" (AWS account ${ce}) from this machine`,`Preflight parameter: /${p}/environment`,as(P),"Commands:",...k.map(vr=>` ${Eu} ${vr.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
|
|
424
|
+
`)),Ja({env:m,accountId:ce,names:f,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!n&&!await Ew({env:m,isShared:x,count:f.length}))return l.info("Deployment cancelled"),Ja({env:m,accountId:ce,names:f,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&l.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:Xr,failed:hr}=await Sw({chosen:k,childEnv:P.childEnv,cwd:a,env:m});return hr.length>0&&(l.error(`Partial deploy to "${m}": succeeded [${Xr.join(", ")||"none"}], failed [${hr.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),bw.exitCode=1),h.print(),Ja({env:m,accountId:ce,names:f,built:P,deployed:Xr,failed:hr,dryRun:!1,success:hr.length===0})},Su=async e=>xu(e,"all"),Tu=async e=>xu(e,"selected"),Cu='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.',Au={env:J.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:J.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:J.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},$u={environment:J.string().describe("Environment deployed to"),accountId:J.string().describe("AWS account the deploy targeted"),services:J.array(J.string()).describe("Services requested"),deployed:J.array(J.string()).describe("Services that completed successfully"),failed:J.array(J.string()).describe("Services that failed"),contract:J.record(J.string(),J.string()).describe("Build contract passed to the scripts"),strippedVars:J.array(J.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:J.boolean().describe("Whether this was a dry run"),success:J.boolean().describe("Whether every requested service deployed")},Iu=e=>Kr({workflowFile:Va,fields:["env"],toolName:e}),Ba=w({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Cu}`,requiresHumanConfirm:!0,formProvider:Iu("local-deploy-all"),inputSchema:Au,outputSchema:$u,handler:Su}),Ga=w({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Cu}`,requiresHumanConfirm:!0,formProvider:Iu("local-deploy-selected"),inputSchema:{...Au,service:J.array(J.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:$u,handler:Tu});import Iw from"@inquirer/confirm";import qa from"@inquirer/input";import Ou from"@inquirer/select";import Ha from"node:process";import{z as M}from"zod";import{z as ps}from"zod";var Ua=async(e,r)=>new Promise(t=>{let o=setTimeout(()=>{t(null)},r);e.then(n=>{clearTimeout(o),t(n)},()=>{clearTimeout(o),t(null)})});var Du=2500,_u=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Aw=async()=>{let e=await Ao();return{regular:Dt(e,"regular"),hotfix:Dt(e,"hotfix")}},$w=(e,r)=>e===null?(l.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${r/1e3} s \u2014 "next" still works and is resolved at execution.`):e.regular===null&&e.hotfix===null?(l.info({msg:"Tool execution form hint unavailable (no prior versions): release-create"}),'No prior version is known from origin release/v* branches or Jira, so "next" will be REFUSED \u2014 pass an explicit semver.'):`"next" resolves to ${e.regular} for a regular release or ${e.hotfix} for a hotfix (computed now from origin release/v* branches and Jira fix versions; recomputed at execution).`,Ka=(e={})=>{let r=e.hintBudgetMs??Du;return{message:"Choose the release to cut. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:t=>_u(t)&&(t.releases===void 0||Array.isArray(t.releases)&&t.releases.length===0),buildRequestedSchema:async()=>{let t=await Ua(Aw(),r);return ps.object({type:ps.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:ps.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign". ${$w(t,r)}`),description:ps.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none.")})},toArgs:(t,o)=>{let n=typeof t.release=="string"?t.release.trim():"";if(n==="")return null;let s=t.type==="hotfix"?"hotfix":"regular",i=typeof t.description=="string"&&t.description.trim()!==""?t.description.trim():void 0,a=Qn(n);return{..._u(o)?o:{},releases:[{...a,type:s,...i===void 0?{}:{description:i}}]}}}};var _w='"1.2.5" or "next"',za=(e,r)=>{try{return ia(e,r)}catch(t){throw t instanceof Lr?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 rl?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}},Dw=async(e,r)=>{let t=Dt(e,r),o=t?` [${t}]`:"",n=(await A(i=>qa({message:` Version (e.g. ${_w})${o}: `},i),{whenHeadless:"refuse"})).trim(),s=n===""?t??"":n;return s===""&&(l.error("No version provided. Exiting..."),Ha.exit(1)),s},Ow=async()=>{let e=(await A(r=>qa({message:' Name (kebab-case, e.g. "checkout-redesign"): '},r),{whenHeadless:"refuse"})).trim();e===""&&(l.error("No name provided. Exiting..."),Ha.exit(1));try{fn(e)}catch(r){let t=r instanceof Error?r.message:String(r);l.error(`${t} Exiting...`),Ha.exit(1)}return e},Nw=async e=>{h.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),n=[],s=!0;for(;s;){let i=n.length+1,a=await A(u=>Ou({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},u),{whenHeadless:"refuse"}),c=await A(u=>Ou({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},u),{whenHeadless:"refuse"}),p;if(a==="name"){let u=await Ow();p=za([{name:u,type:c}],[])[0]}else{let u=await Dw(await o(),c);p=za([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(lr(`v${p.id.raw}`))}let d=(await A(u=>qa({message:" Description (optional, press Enter to skip): "},u),{whenHeadless:"refuse"})).trim();n.push({...p,...d!==""?{description:d}:{}}),s=await A(u=>Iw({message:"Add another release?",default:!1},u),{whenHeadless:"refuse"})}return n},Mw=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 ")},Nu=e=>{for(let r of e)h.addOption("--release",sa(r))},jw=async(e,r)=>{if(e&&e.length>0){let o=aa(e)?await r():[],n=za(e,o);return Nu(n),n}if(j())throw new g(void 0,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let t=await Nw(r);return Nu(t),t},Fw=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"})},Lw=async(e,r)=>{let t=e.map(Mw).join(`
|
|
425
425
|
- `);await z(r,`Create the following ${e.length} release(s)?
|
|
426
426
|
- ${t}
|
|
427
|
-
`),h.addOption("--yes",!0)},
|
|
428
|
-
`),{result:i}}catch(s){let i=
|
|
429
|
-
`),{failure:{version:o,error:a.message}}}},
|
|
427
|
+
`),h.addOption("--yes",!0)},Ww=async e=>{let{entry:r,jiraConfig:t}=e,o=V(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await jt({operation:`create release ${n}`});let s=await va(r.type),i=await ya({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}
|
|
428
|
+
`),{result:i}}catch(s){let i=To(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}
|
|
429
|
+
`),{failure:{version:o,error:a.message}}}},Jw=(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.`)},Mu=async e=>{let{releases:r,confirmedCommand:t}=e;await ie({operation:"create release"});let o=await It(),n=null,i=await jw(r,async()=>(n===null&&(n=await Ao()),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"});Fw(i),await Io({operation:"create release",base:ur(i[0].type)}),await Lw(i,!!t);let a=[],c=[];for(let d of i){let{result:u,failure:m}=await Ww({entry:d,jiraConfig:o});u&&a.push(u),m&&c.push(m)}Jw(i.length,a.length,c.length),h.print();let p={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:y(JSON.stringify(p,null,2)),structuredContent:p}},Ya=w({name:"release-create",requiresHumanConfirm:!0,formProvider:Ka(),description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:M.array(M.object({version:M.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:M.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:M.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:M.string().optional().describe("Optional description for the Jira version.")}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description. Optional over MCP: omit it to have the human fill one release from a form.').optional(),confirm:M.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:M.array(M.string()).describe("List of created release branch names"),successCount:M.number().describe("Number of releases created successfully"),failureCount:M.number().describe("Number of releases that failed"),releases:M.array(M.object({version:M.string().describe("Version number"),type:M.enum(["regular","hotfix"]).describe("Release type"),branchName:M.string().describe("Release branch name"),prUrl:M.string().describe("GitHub PR URL"),jiraVersionUrl:M.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:M.array(M.object({version:M.string().describe("Version number that failed"),error:M.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Mu});import Vw from"@inquirer/input";import{z as gr}from"zod";var Bw=async()=>{let e=await _(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,N(s.title)])),o=await K(),n=await mr(ee({branches:r,descriptions:o,types:t}));return{branch:n,type:t.get(n)||"regular"}},Gw=async e=>{let t=(await _()).find(o=>o.branch===e);if(!t)throw new g(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return N(t.title)},Uw=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await A(n=>Vw({message:` New description ${r} (press Enter to keep current): `},n),{whenHeadless:"unreachable"})).trim();return o===""?e:o},ju=async e=>{let{version:r,description:t,confirmedCommand:o}=e,n=await It(),s;r?(s=Ue(r),await Gw(s)):(h.setInteractive(),s=(await Bw()).branch);let i=W(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=V(i);h.addOption("--version",a);let c=Z(i),p=await Ve(c,n);if(!p)throw new g(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let d=p.description??"",u;t!==void 0?(u=t,h.addOption("--description",u)):(h.setInteractive(),u=await Uw(d));let m=k=>{let x={version:a,branch:s,jiraVersionUrl:cr(n,p),previousDescription:d,newDescription:u,changed:k};return{content:y(JSON.stringify(x,null,2)),structuredContent:x}};if(u===d)return l.info(`No change \u2014 description for ${c} is already: "${d}"`),h.print(),m(!1);await z(o,`Update description for ${c}?
|
|
430
430
|
from: "${d}"
|
|
431
431
|
to: "${u}"
|
|
432
|
-
`),h.addOption("--yes",!0),await $t({versionId:p.id,description:u},n);let v=cr(n,p),f
|
|
433
|
-
`),h.print(),m(!0)},
|
|
434
|
-
`,"utf-8"),{added:c,skipped:p}};import{$ as
|
|
435
|
-
`,"utf-8");let d=[],u=[];for(let m of t){let v=
|
|
436
|
-
`).map(t=>t.trimEnd()).filter(t=>t.length>0),
|
|
437
|
-
`)},us=class extends Error{constructor(t,o){super(`step ${t} failed`,{cause:o});this.step=t;this.reason=o;this.name="StepFailure"}step;reason},ob=e=>typeof e=="string"?e:e.outcome;async function qo(e,r,t){try{let o=await t(),n=ob(o);return r.push({step:e}),l.info({step:e,outcome:n},`\u2705 ${ms[e]} \u2014 ${n}`),o}catch(o){throw new us(e,o)}}var nb=async(e,r,t)=>{try{await t(),r.push({step:e})}catch(o){r.push({step:e,detail:"attempted"}),l.warn({err:fr(o),step:e},`\u26A0\uFE0F ${ms[e]} failed (non-blocking)`)}},sb=(e,r)=>r.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:r.detail?`${r.step} (${r.detail})`:r.step,ib=e=>{let{plan:r,step:t,done:o,cause:n}=e,s=o.map(d=>sb(r,d)).join(", ")||"nothing",i=r.jira?`The Jira fix version ${r.jira.version.name} was NOT removed. `:"",a=r.localTipSha?`Restore the branch with \`git branch ${r.branch} ${r.localTipSha}\`. `:"",c=`completed: ${s}. ${i}${a}Re-run \`infra-kit release remove --version ${r.label}\` to finish; completed steps are skipped.`,p=n instanceof g?n.remediation:void 0;return new g(n,{operation:`remove release ${r.label} \u2014 step ${Ou.indexOf(t)+1} of ${Ou.length} (${ms[t]})`,remediation:p?`${p} \u2014 ${c}`:c})},ab=async e=>{let r=await jo(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}},cb=e=>{let r=e.map(s=>({provider:s.provider,outcome:lb(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}},lb=e=>e.provider==="zed"?"skipped":e.removed.length>0?"verified":"attempted",pb=async(e,r,t)=>{let o={outcome:"attempted",providers:[]};return await nb("ide-folders",t,async()=>{let n=await qr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,currentWorktrees:e.currentWorktrees,removedWorktrees:r,allowEditorRelaunch:!1});o=cb(n)}),l.info({outcome:o.outcome,step:"ide-folders"},`\u2705 ${ms["ide-folders"]} \u2014 ${o.outcome}`),o},db=async e=>{let r=await Br(e.branch);if(Nu({...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 rc`gh pr close ${String(r.number)} --comment ${t}`,{outcome:"closed",number:r.number}},ub=async e=>(await nt()===e.branch&&await rc`git switch ${e.baseBranch}`,await mn(e.branch),await tl(e.branch)?oe({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"),mb=async e=>(await fn(e.branch),e.remoteTipSha?"deleted":"absent"),fb=async(e,r,t)=>{let o=await Yn(r.version.id,t);o.issuesFixedCount===r.fixCount&&o.issuesAffectedCount===r.affectsCount||oe({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}`})},gb=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 fb(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 Yi({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),hb=(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}),vb=async(e,r,t)=>{let o=await qo("worktree",t,()=>ab(e)),n=await pb(e,o.removedBranches,t),s=await qo("pr",t,()=>db(e));l.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await qo("local-branch",t,()=>ub(e)),a=await qo("remote-branch",t,()=>mb(e)),c=await qo("jira",t,()=>gb(e,r));return{worktree:o,ideFolders:n,pr:s,localBranch:i,remoteBranch:a,jira:c}},yb=async(e,r)=>{let t=[];try{return hb(e,await vb(e,r,t))}catch(o){throw o instanceof us?ib({plan:e,step:o.step,done:t,cause:o.reason}):o}},kb=async e=>{if(e)return Ue(e);h.setInteractive();let[r,t]=await Promise.all([K(),_()]),o=t.map(s=>s.branch);o.length===0&&oe({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,N(s.title)]));try{return await mr(ee({branches:o,descriptions:r,types:n}))}catch(s){throw De(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"})}},Mu=async e=>{let{confirmedCommand:r,version:t,moveIssuesTo:o,skipJira:n}=e;await ie({operation:Yo}),await E(),Uw(e);try{let s=await Qw(await kb(t),e);l.debug({plan:eb(s)},"release remove: resolved plan"),Nu(s),Kw(s,e),Hw(s),await Ao({operation:`remove release ${s.label}`,base:s.baseBranch}),zw(s),h.addOption("--version",s.label),o&&h.addOption("--move-issues-to",o),n&&h.addOption("--skip-jira",!0),await z(r,tb(s,!!n),{throwOnDecline:!0}),r||h.addOption("--yes",!0);let i=await yb(s,e);return h.print(),{content:y(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw De(s)||wn(s)||s instanceof g?s:(l.error({err:fr(s)},"\u274C Error removing release"),new g(s,{operation:Yo,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},tc=w({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (and the cmux window rooted there), strips the worktree from the Cursor workspace, closes its pull request with a comment, 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:$.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:$.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:$.string().describe("The release branch that was targeted"),version:$.string().describe('The release label (e.g. "1.2.5")'),baseBranch:$.string().describe("The branch HEAD was moved to before the local delete"),worktree:$.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:$.object({outcome:$.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; Zed is always a declared skip'),providers:$.array($.object({provider:$.string(),outcome:$.enum(["verified","attempted","skipped"]),removed:$.array($.string()).describe("Folder paths confirmed removed; always empty for Zed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:$.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:$.number().nullable().describe("The pull request number, or null when none exists"),localBranch:$.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:$.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:$.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:$.string().nullable().describe("The origin tip before deletion"),jira:$.enum(["removed","absent","skipped","manual"]).describe('Always "manual" over MCP: the fix version is left for a human. "absent" means none was found.'),jiraVersion:$.object({id:$.string(),name:$.string(),url:$.string()}).nullable().describe('The fix version this release owns \u2014 the link a human needs when jira is "manual"')},handler:Mu});import{execFile as Eb}from"node:child_process";import Fu from"node:path";import Lu from"node:process";import{z as Y}from"zod";import oc from"node:fs/promises";import Zo from"node:path";var ju=async e=>{try{return await oc.access(e),!0}catch{return!1}},wb=async e=>{if(e&&e.length>0)return e;try{let r=await Pe();return[Zo.dirname(r)]}catch(r){throw new g(r,{operation:"discover infra-kit projects",remediation:"run inside an infra-kit repo, or pass --root <dir>"})}},bb=e=>e.isDirectory()||e.isSymbolicLink(),Rb=async(e,r)=>{if(!bb(r))return null;let t=Zo.join(e,r.name),[o,n]=await Promise.all([ju(Zo.join(t,".git")),ju(Zo.join(t,"infra-kit.json"))]);if(!o||!n)return null;try{let s=await oc.realpath(t);return{name:Zo.basename(t),repoRoot:s}}catch{return null}},Pb=async e=>{try{return await oc.readdir(e,{withFileTypes:!0})}catch{return[]}},nc=async(e={})=>{let r=await wb(e.roots),t=new Map;for(let o of r){let n=await Pb(o);for(let s of n){let i=await Rb(o,s);i&&!t.has(i.repoRoot)&&t.set(i.repoRoot,i)}}return[...t.values()].sort((o,n)=>o.name.localeCompare(n.name))};var xb=async(e={})=>e.all?Db(e):Wu(e),Wu=async(e={})=>{let{releaseOnly:r=!1,force:t=!1,dryRun:o=!1}=e;await E();try{let n=await R(),s=`${n}${re}`,i=Fu.basename(await Pe(n)),a=await Ze(n),c=Sb(a,r),p=c.map(k=>k.path),d=c.map(k=>k.branch).filter(k=>Rr(k)),u=c.map(k=>({title:En({branch:k.branch??Fu.basename(k.path)}),cwd:k.path}));if(o){let k=await $b({repo:i,releaseOnly:r,force:t,worktreePaths:p,targets:u});return Ib(k,s),h.print(),{content:y(JSON.stringify(k,null,2)),structuredContent:k}}let[m,v]=await Promise.all([Qa({projectRoot:n,worktreeDir:s,worktreePaths:p,currentBranches:d}),Tb({targets:u,force:t,repoName:i})]),f={repo:i,dryRun:!1,releaseOnly:r,worktreePaths:p,ideProviders:m.filter(k=>k.ran).map(k=>k.provider),cmuxOpened:v.opened,cmuxSkipped:v.skipped,cmuxClosed:v.closed};return _b(f,{ideRan:m.some(k=>k.ran)}),h.print(),{content:y(JSON.stringify(f,null,2)),structuredContent:f}}catch(n){throw n instanceof g?n:(l.debug({err:n},"Error reopening worktree windows"),new g(n,{operation:"reopen worktrees",remediation:"run `infra-kit doctor` to check this project's setup"}))}},Sb=(e,r)=>e.filter(t=>t.bare||t.prunable?!1:r?Rr(t.branch):!0),Tb=async e=>{let{targets:r,force:t,repoName:o}=e,n=await Rn(o),s=t?await Cb({targets:r}):[],{opened:i,skipped:a}=await Ab({targets:r,force:t,repoName:o,groupRef:n});return{opened:i,skipped:a,closed:s}},Cb=async e=>{let{targets:r}=e;if(r.length===0)return[];let t=await rr(),o=[];for(let n of r)t.has(await Pr(n.cwd))&&(await bn(n.cwd),o.push(n.title));return o},Ju=async(e,r,t)=>{let o=[],n=[];for(let s of e)!t&&r.has(await Pr(s.cwd))?n.push(s.title):o.push(s);return{toOpen:o,skipped:n}},Ab=async e=>{let{targets:r,force:t,repoName:o,groupRef:n=null}=e,s=t?new Set:new Set((await rr()).keys()),{toOpen:i,skipped:a}=await Ju(r,s,t),c=[],p=n,d=!1;for(let u of i)try{if(p)await it({cwd:u.cwd,title:u.title,group:p});else{let m=await it({cwd:u.cwd,title:u.title});d||(p=await Pn(o,[m]),d=!0)}c.push(u.title)}catch(m){l.warn({error:m,title:u.title},`\u26A0\uFE0F Failed to reopen cmux workspace ${u.title}`)}return{opened:c,skipped:a}},$b=async e=>{let{repo:r,releaseOnly:t,force:o,worktreePaths:n,targets:s}=e,i=o?new Set:new Set((await rr()).keys()),{toOpen:a,skipped:c}=await Ju(s,i,o);return{repo:r,dryRun:!0,releaseOnly:t,worktreePaths:n,ideProviders:[],cmuxOpened:a.map(p=>p.title),cmuxSkipped:c,cmuxClosed:[]}},Ib=(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}`)}},_b=(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=>ec(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")},Db=async e=>{let{project:r=[],root:t=[],releaseOnly:o=!1,force:n=!1,dryRun:s=!1}=e,i=await nc({roots:t}),a=Ob(i,r),c=Nb({releaseOnly:o,force:n,dryRun:s}),p=[];for(let u of a)p.push(await Mb(u,c));let d={all:!0,dryRun:s,projects:a,results:p};return Fb(d),h.print(),{content:y(JSON.stringify(d,null,2)),structuredContent:d}},Ob=(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))},Nb=e=>{let r=[];return e.dryRun&&r.push("--dry-run"),e.releaseOnly&&r.push("--release-only"),e.force&&r.push("--force"),r},Mb=async(e,r)=>{try{let t=await jb(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}}},jb=(e,r)=>{let t=Lu.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];Eb(Lu.execPath,s,{cwd:e,maxBuffer:16*1024*1024},(i,a)=>{if(i){n(i);return}o(a)})})},Fb=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`)},sc=w({name:"reopen",description:"Reopen editor + cmux windows for every active worktree in the current project \u2014 the main checkout plus every linked worktree (release, feature, detached). Additive and idempotent by default: cmux workspaces already open are skipped, so running twice does not double the windows. Zed opens the exact folder set; Cursor reconciles its release-branch-shaped workspace. Set releaseOnly to restrict to release worktrees (the legacy reload scope). Set force to close each cmux workspace first, then reopen (disruptive). Set dryRun to return the plan without spawning anything. Non-destructive to git \u2014 only cmux/editor view state is touched.",inputSchema:{releaseOnly:Y.boolean().optional().describe("Restrict to release worktrees (reproduces the legacy worktrees-reload scope)"),force:Y.boolean().optional().describe("Close each cmux workspace first, then reopen (disruptive)"),dryRun:Y.boolean().optional().describe("Return the plan (paths + cmux titles) without spawning anything")},outputSchema:{repo:Y.string().describe("Repository name the reopen ran for"),dryRun:Y.boolean().describe("Whether this was a dry run (nothing was spawned)"),releaseOnly:Y.boolean().describe("Whether the set was restricted to release worktrees"),worktreePaths:Y.array(Y.string()).describe("Absolute folder set handed to the editor (root-first)"),ideProviders:Y.array(Y.string()).describe("Configured IDE providers that opened (cursor | zed); empty in dry run"),cmuxOpened:Y.array(Y.string()).describe("Titles of cmux workspaces opened this run"),cmuxSkipped:Y.array(Y.string()).describe("Titles of cmux workspaces skipped because already open (additive mode)"),cmuxClosed:Y.array(Y.string()).describe("Titles of cmux workspaces closed first (force mode only)")},handler:Wu});import{spawnSync as Vb}from"node:child_process";import{homedir as Bb}from"node:os";import Gb from"node:process";var Lb=e=>{let r=new Set(e.steps.map(t=>t[0]));return r.has("brew")?"homebrew":r.has("npm")?"npm":null},Wb=e=>{let r=[];return e.needsSudo&&r.push("needs-sudo"),e.fetchesNetworkScript&&r.push("fetches-network-script"),r},Jb=(e,r)=>{let t=Lb(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},Xo=(e,r)=>{let t=[...Wb(e),...Jb(e,r)];return t.length===0?{executable:!0}:{executable:!1,reasons:t}},Qo=e=>e.steps.map(Mc);var Ub=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],Kb=e=>{let r={...Nc(e)};for(let t of Ub)delete r[t];return r},ic=(e,r,t={})=>{let o=t.spawnSync??Vb,n=t.env??Gb.env,s=(t.mcpMode??J)(),i=Qo(e),a=Xo(e,r);return a.executable?s?{ran:!1,commands:i,refusedBecause:["mcp-mode"]}:qb({recipe:e,spawn:o,env:n,commands:i,notify:t.notify??Hb}):{ran:!1,commands:i,refusedBecause:a.reasons}},Hb=e=>{l.info(e)},Bu=64,zb=Bu*1024*1024,qb=({recipe:e,spawn:r,env:t,commands:o,notify:n})=>{let s=Kb(t);for(let[i,a]of e.steps.entries()){n(` ${"running".padEnd(9)} ${o[i]}`);let c=r(a[0],a.slice(1),{stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:zb,cwd:Bb(),env:s}),p=rR(c);if(p!==null)return{ran:!0,ok:!1,commands:o,failedStep:o[i],detail:p}}return{ran:!0,ok:!0,commands:o}},Yb=5,Zb=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Vu=e=>e==null?[]:String(e).split(`
|
|
438
|
-
`).map(r=>r.trim()).filter(r=>r.length>0),
|
|
439
|
-
${e} (${r.length}):`);for(let t of r.slice(0,
|
|
432
|
+
`),h.addOption("--yes",!0),await $t({versionId:p.id,description:u},n);let v=cr(n,p),f=_o(v,u);return await os({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}
|
|
433
|
+
`),h.print(),m(!0)},Za=w({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching GitHub release PR body. Accepts a release version or a release name: targets the Jira fix version named `v<version>` (versioned) or `<name>` (named) and the open PR on branch `release/v<version>` or `release/<name>`. The PR body is rewritten canonically to `<jiraVersionUrl>\\n\\n<description>` \u2014 any prior manual edits to the body are overwritten. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:gr.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:gr.string().describe("New description. Empty string clears the description.")},outputSchema:{version:gr.string().describe("Release version"),branch:gr.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:gr.string().describe("Jira fix version URL"),previousDescription:gr.string().describe("The description before the update"),newDescription:gr.string().describe("The description after the update"),changed:gr.boolean().describe("Whether the description actually changed")},handler:ju});import{z as $}from"zod";import{$ as ic}from"zx";import Fu from"node:fs/promises";import ds from"node:path";var zo=async e=>{let{workspacePath:r,folderPaths:t}=e,o=ds.dirname(r),n;try{n=await Fu.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let s;try{s=JSON.parse(n)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>ds.resolve(o,d.path))),c=[],p=[];for(let d of t){let u=ds.resolve(d);if(a.has(u)){p.push(d);continue}let m=ds.relative(o,u);i.push({path:m}),a.add(u),c.push(d)}return s.folders=i,await Fu.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
434
|
+
`,"utf-8"),{added:c,skipped:p}};import{$ as Kw}from"zx";var qo=async e=>{await Kw`cursor ${e}`};import Hw from"node:fs/promises";import ms from"node:path";import Lu from"node:fs/promises";import us from"node:path";var Yo=async e=>{let{workspacePath:r,folderPaths:t}=e,o=us.dirname(r),n;try{n=await Lu.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=>us.resolve(m))),c=new Set,p=i.filter(m=>{let v=us.resolve(o,m.path);return a.has(v)?(c.add(v),!1):!0});s.folders=p,await Lu.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
435
|
+
`,"utf-8");let d=[],u=[];for(let m of t){let v=us.resolve(m);c.has(v)?d.push(m):u.push(m)}return{removed:d,notFound:u}};var Xa=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=ms.dirname(r),s=ms.resolve(`${t}/release`),i=await Hw.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(f=>ms.resolve(`${t}/${f}`))),d=[];for(let f of c){let k=ms.resolve(n,f.path);(k===s||k.startsWith(`${s}/`))&&!p.has(k)&&d.push(k)}let u=[];d.length>0&&(u=(await Yo({workspacePath:r,folderPaths:d})).removed);let m=o.map(f=>`${t}/${f}`),{added:v}=m.length>0?await zo({workspacePath:r,folderPaths:m}):{added:[]};return{added:v,removed:u}};import Wu from"node:path";var zr=(e,r)=>Wu.isAbsolute(e)?e:Wu.resolve(r,e);var Qa=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=zr(n.workspaceConfigPath,r);try{let{added:i,removed:a}=await Xa({workspacePath:s,worktreeDir:t,currentBranches:o});return o.length>0&&await qo(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 zw}from"zx";var ec=async e=>{let{folderPaths:r}=e;for(let t of r)await zw`zed --add ${t}`;return{added:r}};import{$ as qw}from"zx";var rc=async e=>{let{worktreePaths:r}=e;if(r.length===0)return{ran:!1,added:0,removed:0};try{return await qw`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 Yw}from"zx";var tc=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,n=[r,...o.map(s=>`${t}/${s}`)];try{return await Yw`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 be=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var oc=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,n=await E(),s=Ee(n),i=o.map(c=>`${t}/${c}`),a=[];for(let c of s)switch(c.provider){case"cursor":{if(!c.config.workspaceConfigPath){l.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),a.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let p=zr(c.config.workspaceConfigPath,r),{added:d,skipped:u}=await zo({workspacePath:p,folderPaths:i}),m=u.length>0?` (${u.length} already present)`:"";l.info(`\u2705 Added ${d.length} folder(s) to ${p}${m}`),await qo(p),a.push({ran:!0,provider:"cursor",added:d.length,skipped:u.length});break}case"zed":{let{added:p}=await ec({folderPaths:i});l.info(`\u2705 Added ${p.length} folder(s) to Zed workspace`),a.push({ran:!0,provider:"zed",added:p.length,skipped:0});break}default:be(c)}return a};var nc=async e=>{let r=await E(),t=Ee(r),{projectRoot:o,worktreeDir:n,worktreePaths:s,currentBranches:i}=e,a=[];for(let c of t)switch(c.provider){case"cursor":{let p=await Qa({projectRoot:o,worktreeDir:n,currentBranches:i,cursorConfig:c.config});a.push({...p,provider:"cursor"});break}case"zed":{let p=await rc({worktreePaths:s});a.push({...p,provider:"zed"});break}default:be(c)}return a};var sc=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return be(e)}};var qr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:n,allowEditorRelaunch:s}=e;if(n.length===0)return[];let i=await E(),a=Ee(i),c=n.map(u=>`${t}/${u}`),p=o.filter(u=>!n.includes(u)),d=[];for(let u of a)switch(u.provider){case"cursor":{d.push(await Zw({ide:u,projectRoot:r,folderPaths:c}));break}case"zed":{d.push(await Xw({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:s}));break}default:be(u)}return d},Zw=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let n=zr(r.config.workspaceConfigPath,t);try{let{removed:s}=await Yo({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:[]}}},Xw=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:n}=e;return n?(await tc({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 fs=["workspace","none"];var Ju=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],hs={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"},Xo="remove a release",oe=e=>{throw l.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Qw=e=>{j()&&(e.version||oe({operation:Xo,remediation:'pass "version" (a release version or name); the interactive picker needs a TTY',stderrExcerpt:'release-remove over MCP requires "version"'}),e.moveIssuesTo&&oe({operation:Xo,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&&oe({operation:Xo,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"}))},Vu=e=>{e.pr?.state==="MERGED"&&oe({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`})},eb=(e,r)=>{if(r.skipJira||(e.jiraConfig||oe({operation:`remove release ${e.label}`,remediation:j()?"call `env-load` for a config that carries JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL, then re-call; or ask a human to run `infra-kit release remove --skip-jira` from a configured shell":"set JIRA_BASE_URL / JIRA_TOKEN / JIRA_PROJECT_ID / JIRA_EMAIL, or pass --skip-jira to tear down the branch and PR and leave any fix version alone",stderrExcerpt:"Jira is not configured, so a fix version for this release cannot be checked or removed"}),!e.jira))return;let{version:t,fixCount:o,affectsCount:n}=e.jira;(t.released||t.archived)&&oe({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||oe({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)`}))},rb=e=>{e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira||oe({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"})},tb=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||oe({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(", ")}`})},ob=async e=>(await ic`git -C ${e} status --porcelain`).stdout.split(`
|
|
436
|
+
`).map(t=>t.trimEnd()).filter(t=>t.length>0),nb=async e=>(await rr()).has(await Pr(e)),sb=async(e,r)=>{let t={jiraConfig:null,jira:null,moveIssuesTo:null};if(r.skipJira)return t;let o=await Be();if(!o)return t;let n=await Ve(Z(e),o),s=r.moveIssuesTo?await ib(r.moveIssuesTo,o):null;if(!n)return{jiraConfig:o,jira:null,moveIssuesTo:s};let i=await Xn(n.id,o);return{jiraConfig:o,moveIssuesTo:s,jira:{version:n,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:cr(o,n)}}},ib=async(e,r)=>{let t=await Ve(e,r);return t||oe({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}"`})},ab=async(e,r)=>{let t=W(e);t||oe({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}${re}`,s=`${n}/${e}`,[i,a,c,p]=await Promise.all([de("release"),Br(e),Yt(o,`refs/heads/${e}`),vn(o,e)]),d=i.includes(e);return{...await sb(t,r),branch:e,id:t,label:V(t),baseBranch:ur(N(a?.title??"")),projectRoot:o,worktreeDir:n,worktreePath:s,currentWorktrees:i,worktreePresent:d,cmuxWorkspacePresent:d?await nb(s):!1,worktreeDirty:d?await ob(s):null,localTipSha:c,remoteTipSha:p,pr:a}},cb=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}),lb=(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}`},pb=(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: ${lb(e,r)}`];return e.cmuxWorkspacePresent&&o.push(` \u2022 the cmux window rooted at ${e.worktreePath} will close`),o.join(`
|
|
437
|
+
`)},gs=class extends Error{constructor(t,o){super(`step ${t} failed`,{cause:o});this.step=t;this.reason=o;this.name="StepFailure"}step;reason},db=e=>typeof e=="string"?e:e.outcome;async function Zo(e,r,t){try{let o=await t(),n=db(o);return r.push({step:e}),l.info({step:e,outcome:n},`\u2705 ${hs[e]} \u2014 ${n}`),o}catch(o){throw new gs(e,o)}}var ub=async(e,r,t)=>{try{await t(),r.push({step:e})}catch(o){r.push({step:e,detail:"attempted"}),l.warn({err:fr(o),step:e},`\u26A0\uFE0F ${hs[e]} failed (non-blocking)`)}},mb=(e,r)=>r.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:r.detail?`${r.step} (${r.detail})`:r.step,fb=e=>{let{plan:r,step:t,done:o,cause:n}=e,s=o.map(d=>mb(r,d)).join(", ")||"nothing",i=r.jira?`The Jira fix version ${r.jira.version.name} was NOT removed. `:"",a=r.localTipSha?`Restore the branch with \`git branch ${r.branch} ${r.localTipSha}\`. `:"",c=`completed: ${s}. ${i}${a}Re-run \`infra-kit release remove --version ${r.label}\` to finish; completed steps are skipped.`,p=n instanceof g?n.remediation:void 0;return new g(n,{operation:`remove release ${r.label} \u2014 step ${Ju.indexOf(t)+1} of ${Ju.length} (${hs[t]})`,remediation:p?`${p} \u2014 ${c}`:c})},gb=async e=>{let r=await Lo(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}},hb=e=>{let r=e.map(s=>({provider:s.provider,outcome:vb(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}},vb=e=>e.provider==="zed"?"skipped":e.removed.length>0?"verified":"attempted",yb=async(e,r,t)=>{let o={outcome:"attempted",providers:[]};return await ub("ide-folders",t,async()=>{let n=await qr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,currentWorktrees:e.currentWorktrees,removedWorktrees:r,allowEditorRelaunch:!1});o=hb(n)}),l.info({outcome:o.outcome,step:"ide-folders"},`\u2705 ${hs["ide-folders"]} \u2014 ${o.outcome}`),o},kb=async e=>{let r=await Br(e.branch);if(Vu({...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 ic`gh pr close ${String(r.number)} --comment ${t}`,{outcome:"closed",number:r.number}},wb=async e=>(await nt()===e.branch&&await ic`git switch ${e.baseBranch}`,await gn(e.branch),await al(e.branch)?oe({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"),bb=async e=>(await hn(e.branch),e.remoteTipSha?"deleted":"absent"),Rb=async(e,r,t)=>{let o=await Xn(r.version.id,t);o.issuesFixedCount===r.fixCount&&o.issuesAffectedCount===r.affectsCount||oe({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}`})},Pb=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 Rb(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 Qi({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),Eb=(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}),xb=async(e,r,t)=>{let o=await Zo("worktree",t,()=>gb(e)),n=await yb(e,o.removedBranches,t),s=await Zo("pr",t,()=>kb(e));l.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Zo("local-branch",t,()=>wb(e)),a=await Zo("remote-branch",t,()=>bb(e)),c=await Zo("jira",t,()=>Pb(e,r));return{worktree:o,ideFolders:n,pr:s,localBranch:i,remoteBranch:a,jira:c}},Sb=async(e,r)=>{let t=[];try{return Eb(e,await xb(e,r,t))}catch(o){throw o instanceof gs?fb({plan:e,step:o.step,done:t,cause:o.reason}):o}},Tb=async e=>{if(e)return Ue(e);h.setInteractive();let[r,t]=await Promise.all([K(),_()]),o=t.map(s=>s.branch);o.length===0&&oe({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,N(s.title)]));try{return await mr(ee({branches:o,descriptions:r,types:n}))}catch(s){throw De(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"})}},Bu=async e=>{let{confirmedCommand:r,version:t,moveIssuesTo:o,skipJira:n}=e;await ie({operation:Xo}),await E(),Qw(e);try{let s=await ab(await Tb(t),e);l.debug({plan:cb(s)},"release remove: resolved plan"),Vu(s),eb(s,e),rb(s),await Io({operation:`remove release ${s.label}`,base:s.baseBranch}),tb(s),h.addOption("--version",s.label),o&&h.addOption("--move-issues-to",o),n&&h.addOption("--skip-jira",!0),await z(r,pb(s,!!n),{throwOnDecline:!0}),r||h.addOption("--yes",!0);let i=await Sb(s,e);return h.print(),{content:y(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw De(s)||Rn(s)||s instanceof g?s:(l.error({err:fr(s)},"\u274C Error removing release"),new g(s,{operation:Xo,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},ac=w({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (and the cmux window rooted there), strips the worktree from the Cursor workspace, closes its pull request with a comment, 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 have no field over MCP; the server strips them 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 when nothing named that version exists. A fix version that still carries issues is reported, not refused: that guard protects a delete which never runs here. 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:$.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:$.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:$.string().describe("The release branch that was targeted"),version:$.string().describe('The release label (e.g. "1.2.5")'),baseBranch:$.string().describe("The branch HEAD was moved to before the local delete"),worktree:$.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:$.object({outcome:$.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; Zed is always a declared skip'),providers:$.array($.object({provider:$.string(),outcome:$.enum(["verified","attempted","skipped"]),removed:$.array($.string()).describe("Folder paths confirmed removed; always empty for Zed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:$.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:$.number().nullable().describe("The pull request number, or null when none exists"),localBranch:$.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:$.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:$.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:$.string().nullable().describe("The origin tip before deletion"),jira:$.enum(["removed","absent","skipped","manual"]).describe('"manual" when a fix version exists over MCP (it is left for a human); "absent" when Jira knows none.'),jiraVersion:$.object({id:$.string(),name:$.string(),url:$.string()}).nullable().describe('The fix version this release owns \u2014 the link a human needs when jira is "manual"')},handler:Bu});import{execFile as _b}from"node:child_process";import Uu from"node:path";import Ku from"node:process";import{z as Y}from"zod";import cc from"node:fs/promises";import Qo from"node:path";var Gu=async e=>{try{return await cc.access(e),!0}catch{return!1}},Cb=async e=>{if(e&&e.length>0)return e;try{let r=await Pe();return[Qo.dirname(r)]}catch(r){throw new g(r,{operation:"discover infra-kit projects",remediation:"run inside an infra-kit repo, or pass --root <dir>"})}},Ab=e=>e.isDirectory()||e.isSymbolicLink(),$b=async(e,r)=>{if(!Ab(r))return null;let t=Qo.join(e,r.name),[o,n]=await Promise.all([Gu(Qo.join(t,".git")),Gu(Qo.join(t,"infra-kit.json"))]);if(!o||!n)return null;try{let s=await cc.realpath(t);return{name:Qo.basename(t),repoRoot:s}}catch{return null}},Ib=async e=>{try{return await cc.readdir(e,{withFileTypes:!0})}catch{return[]}},lc=async(e={})=>{let r=await Cb(e.roots),t=new Map;for(let o of r){let n=await Ib(o);for(let s of n){let i=await $b(o,s);i&&!t.has(i.repoRoot)&&t.set(i.repoRoot,i)}}return[...t.values()].sort((o,n)=>o.name.localeCompare(n.name))};var Db=async(e={})=>e.all?Jb(e):Hu(e),Hu=async(e={})=>{let{releaseOnly:r=!1,force:t=!1,dryRun:o=!1}=e;await E();try{let n=await R(),s=`${n}${re}`,i=Uu.basename(await Pe(n)),a=await Ze(n),c=Ob(a,r),p=c.map(k=>k.path),d=c.map(k=>k.branch).filter(k=>Rr(k)),u=c.map(k=>({title:Sn({branch:k.branch??Uu.basename(k.path)}),cwd:k.path}));if(o){let k=await Fb({repo:i,releaseOnly:r,force:t,worktreePaths:p,targets:u});return Lb(k,s),h.print(),{content:y(JSON.stringify(k,null,2)),structuredContent:k}}let[m,v]=await Promise.all([nc({projectRoot:n,worktreeDir:s,worktreePaths:p,currentBranches:d}),Nb({targets:u,force:t,repoName:i})]),f={repo:i,dryRun:!1,releaseOnly:r,worktreePaths:p,ideProviders:m.filter(k=>k.ran).map(k=>k.provider),cmuxOpened:v.opened,cmuxSkipped:v.skipped,cmuxClosed:v.closed};return Wb(f,{ideRan:m.some(k=>k.ran)}),h.print(),{content:y(JSON.stringify(f,null,2)),structuredContent:f}}catch(n){throw n instanceof g?n:(l.debug({err:n},"Error reopening worktree windows"),new g(n,{operation:"reopen worktrees",remediation:"run `infra-kit doctor` to check this project's setup"}))}},Ob=(e,r)=>e.filter(t=>t.bare||t.prunable?!1:r?Rr(t.branch):!0),Nb=async e=>{let{targets:r,force:t,repoName:o}=e,n=await En(o),s=t?await Mb({targets:r}):[],{opened:i,skipped:a}=await jb({targets:r,force:t,repoName:o,groupRef:n});return{opened:i,skipped:a,closed:s}},Mb=async e=>{let{targets:r}=e;if(r.length===0)return[];let t=await rr(),o=[];for(let n of r)t.has(await Pr(n.cwd))&&(await Pn(n.cwd),o.push(n.title));return o},zu=async(e,r,t)=>{let o=[],n=[];for(let s of e)!t&&r.has(await Pr(s.cwd))?n.push(s.title):o.push(s);return{toOpen:o,skipped:n}},jb=async e=>{let{targets:r,force:t,repoName:o,groupRef:n=null}=e,s=t?new Set:new Set((await rr()).keys()),{toOpen:i,skipped:a}=await zu(r,s,t),c=[],p=n,d=!1;for(let u of i)try{if(p)await it({cwd:u.cwd,title:u.title,group:p});else{let m=await it({cwd:u.cwd,title:u.title});d||(p=await xn(o,[m]),d=!0)}c.push(u.title)}catch(m){l.warn({error:m,title:u.title},`\u26A0\uFE0F Failed to reopen cmux workspace ${u.title}`)}return{opened:c,skipped:a}},Fb=async e=>{let{repo:r,releaseOnly:t,force:o,worktreePaths:n,targets:s}=e,i=o?new Set:new Set((await rr()).keys()),{toOpen:a,skipped:c}=await zu(s,i,o);return{repo:r,dryRun:!0,releaseOnly:t,worktreePaths:n,ideProviders:[],cmuxOpened:a.map(p=>p.title),cmuxSkipped:c,cmuxClosed:[]}},Lb=(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}`)}},Wb=(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=>sc(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")},Jb=async e=>{let{project:r=[],root:t=[],releaseOnly:o=!1,force:n=!1,dryRun:s=!1}=e,i=await lc({roots:t}),a=Vb(i,r),c=Bb({releaseOnly:o,force:n,dryRun:s}),p=[];for(let u of a)p.push(await Gb(u,c));let d={all:!0,dryRun:s,projects:a,results:p};return Kb(d),h.print(),{content:y(JSON.stringify(d,null,2)),structuredContent:d}},Vb=(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))},Bb=e=>{let r=[];return e.dryRun&&r.push("--dry-run"),e.releaseOnly&&r.push("--release-only"),e.force&&r.push("--force"),r},Gb=async(e,r)=>{try{let t=await Ub(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}}},Ub=(e,r)=>{let t=Ku.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];_b(Ku.execPath,s,{cwd:e,maxBuffer:16*1024*1024},(i,a)=>{if(i){n(i);return}o(a)})})},Kb=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`)},pc=w({name:"reopen",description:"Reopen editor + cmux windows for every active worktree in the current project \u2014 the main checkout plus every linked worktree (release, feature, detached). Additive and idempotent by default: cmux workspaces already open are skipped, so running twice does not double the windows. Zed opens the exact folder set; Cursor reconciles its release-branch-shaped workspace. Set releaseOnly to restrict to release worktrees (the legacy reload scope). Set force to close each cmux workspace first, then reopen (disruptive). Set dryRun to return the plan without spawning anything. Non-destructive to git \u2014 only cmux/editor view state is touched.",inputSchema:{releaseOnly:Y.boolean().optional().describe("Restrict to release worktrees (reproduces the legacy worktrees-reload scope)"),force:Y.boolean().optional().describe("Close each cmux workspace first, then reopen (disruptive)"),dryRun:Y.boolean().optional().describe("Return the plan (paths + cmux titles) without spawning anything")},outputSchema:{repo:Y.string().describe("Repository name the reopen ran for"),dryRun:Y.boolean().describe("Whether this was a dry run (nothing was spawned)"),releaseOnly:Y.boolean().describe("Whether the set was restricted to release worktrees"),worktreePaths:Y.array(Y.string()).describe("Absolute folder set handed to the editor (root-first)"),ideProviders:Y.array(Y.string()).describe("Configured IDE providers that opened (cursor | zed); empty in dry run"),cmuxOpened:Y.array(Y.string()).describe("Titles of cmux workspaces opened this run"),cmuxSkipped:Y.array(Y.string()).describe("Titles of cmux workspaces skipped because already open (additive mode)"),cmuxClosed:Y.array(Y.string()).describe("Titles of cmux workspaces closed first (force mode only)")},handler:Hu});import{spawnSync as Yb}from"node:child_process";import{homedir as Zb}from"node:os";import Xb from"node:process";var Hb=e=>{let r=new Set(e.steps.map(t=>t[0]));return r.has("brew")?"homebrew":r.has("npm")?"npm":null},zb=e=>{let r=[];return e.needsSudo&&r.push("needs-sudo"),e.fetchesNetworkScript&&r.push("fetches-network-script"),r},qb=(e,r)=>{let t=Hb(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},en=(e,r)=>{let t=[...zb(e),...qb(e,r)];return t.length===0?{executable:!0}:{executable:!1,reasons:t}},rn=e=>e.steps.map(Jc);var Qb=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],eR=e=>{let r={...Wc(e)};for(let t of Qb)delete r[t];return r},dc=(e,r,t={})=>{let o=t.spawnSync??Yb,n=t.env??Xb.env,s=(t.mcpMode??j)(),i=rn(e),a=en(e,r);return a.executable?s?{ran:!1,commands:i,refusedBecause:["mcp-mode"]}:oR({recipe:e,spawn:o,env:n,commands:i,notify:t.notify??rR}):{ran:!1,commands:i,refusedBecause:a.reasons}},rR=e=>{l.info(e)},Yu=64,tR=Yu*1024*1024,oR=({recipe:e,spawn:r,env:t,commands:o,notify:n})=>{let s=eR(t);for(let[i,a]of e.steps.entries()){n(` ${"running".padEnd(9)} ${o[i]}`);let c=r(a[0],a.slice(1),{stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:tR,cwd:Zb(),env:s}),p=lR(c);if(p!==null)return{ran:!0,ok:!1,commands:o,failedStep:o[i],detail:p}}return{ran:!0,ok:!0,commands:o}},nR=5,sR=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,qu=e=>e==null?[]:String(e).split(`
|
|
438
|
+
`).map(r=>r.trim()).filter(r=>r.length>0),iR=e=>{let r=qu(e.stderr),t=qu(e.stdout),o=[...r,...t].filter(s=>sR.test(s)),n=r.length>0?r:t;return(o.length>0?o:n).slice(-nR).join(" / ")},aR="ENOBUFS",cR=e=>e.error?.code===aR,lR=e=>{if(cR(e))return`terminated after exceeding the ${Yu} MiB output limit \u2014 it may be part-installed`;if(e.error)return`could not start: ${e.error.message}`;if(e.signal)return`terminated by signal ${e.signal}`;if(e.status===0)return null;let r=iR(e),t=r===""?"":`: ${r}`;return`exited ${e.status??"unknown"}${t}`};var pR=e=>{let r=[];return e.some(o=>o.id==="brew"&&o.present)&&r.push("homebrew"),r.push("npm"),r},dR=e=>{let r=we(e.id);return e.present?r.updateFor(e.binRealPath):r.bootstrapInstall},uR=(e,r)=>{let t=dR(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=en(t,o);return{state:e,action:e.present?"update":"install",recipe:t,executable:n.executable,refusedBecause:n.executable?[]:n.reasons,commands:rn(t),context:o}},vs=async(e=Fr,r=Ro())=>{let t=await So(Fr,r),o={owner:null,present:pR(t)},n=Yi(e),s=new Map(t.map(a=>[a.id,a]));return{plans:n.filter(a=>e.includes(a)).map(a=>uR(s.get(a),o)),context:o}};var uc=(e,r)=>({...tn(e),action:"skipped",commands:e.commands,detail:r}),tn=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Zu=(e,r)=>e.action==="none"?uc(e,`nothing to do: ${e.state.manager} installs are not managed from here`):r==="update"&&e.action==="install"?uc(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...tn(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},mR=(e,r)=>r.ran?r.ok?{...tn(e),action:e.action==="install"?"installed":"updated",commands:r.commands,detail:e.action==="install"?"installed":"updated"}:{...tn(e),action:"failed",commands:r.commands,detail:`${r.failedStep??"a step"} ${r.detail??"failed"}`}:{...tn(e),action:"refused",commands:r.commands,detail:`refused (${r.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},mc=async e=>{let r=e.run??dc,{plans:t}=await vs(e.ids,e.probeDeps),o=[];for(let n of t){let s=Zu(n,e.mode);if(s!==null){o.push(s);continue}o.push(mR(n,r(n.recipe,n.context)))}return o},fc=async(e,r)=>{let{plans:t}=await vs(e,r);return t.map(o=>Zu(o,"converge")??uc(o,`would ${o.action} \u2014 nothing was run (--skip-tools)`))};import fR from"node:process";import{z as I}from"zod";var gR=()=>{let e=el();return{link:e,target:{home:e.home,processStartTime:()=>null}}},hR=e=>{switch(e){case"created":return"linked ~/.infra-kit/portless to the running portless";case"repointed":return"re-pointed ~/.infra-kit/portless to the running portless";case"unchanged":return"already linked to the running portless";case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-unresolved":return"skipped \u2014 portless is not installed";case"failed":return"could not update the link \u2014 see the debug log";default:return be(e)}},vR=async e=>{let r=Qc(e.link);l.info(` ${r.outcome.padEnd(9)} portless link \u2014 ${hR(r.outcome)}`);let t=un(e.link.home,e.target.exists)??e.link.resolveBin();t!==null&&await Cd(e.target,t)!=="converged"&&(l.info("Run this yourself to finish the portless service:"),l.info(` ${br(t,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath})}`))},Qu="--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.",yR=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(Qu);return{ids:e.tools??r??Fr,mode:t?"update":"converge",skipTools:o}},Xu=(e,r)=>e instanceof St?e.step:r.at(-1)?.step??"zshrc",kR=async()=>{let e=[],r=t=>{e.push(t),t.message!==bo&&zn(t)};try{return await Ji(r),{entries:e,failed:!1}}catch(t){let o={step:Xu(t,e),outcome:"warned",message:`The ${Xu(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"};return zn(o),e.push(o),{entries:e,failed:!0}}},wR=async(e,r,t)=>{for(let o of e)l.info(` ${o.action.padEnd(9)} ${o.id} \u2014 ${o.detail}`);for(let o of e)if(bR(o,r)){l.info(`Run these yourself to ${r?"set up":"finish"} ${o.id}:`);for(let n of o.commands)l.info(` ${n}`)}await vR(t),l.info(bo)},bR=(e,r)=>e.commands.length===0?!1:e.action==="refused"||r&&e.action==="skipped",RR=e=>({step:e.step,outcome:e.outcome,message:e.message}),em=async(e={})=>{let r=yR(e),t=await kR(),o=r.skipTools?await fc(r.ids,e.probeDeps):await mc({ids:r.ids,mode:r.mode,probeDeps:e.probeDeps,run:e.run});await wR(o,r.skipTools,e.portlessDeps??gR());let n={init:t.entries.map(RR),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)&&(fR.exitCode=1),{content:y(JSON.stringify(n,null,2)),structuredContent:n}},PR=I.object({step:I.enum(["zshrc","zshenv","migrations","user-config","guidance","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:I.enum(["written","unchanged","skipped","warned"]).describe("What that step did: changed something, found nothing to change, did not run, or failed non-fatally"),message:I.string().describe("The same line a human running this would have read")}),ER=I.object({id:I.string().describe("Dependency id"),action:I.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:I.object({present:I.boolean(),onPath:I.boolean(),version:I.string().nullable(),manager:I.string()}).describe("The tool\u2019s state before this run"),commands:I.array(I.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:I.string().describe("Why, in one line")}),xR={init:I.array(PR).describe("One entry per init step, in the order they ran"),tools:I.array(ER).describe("One result per requested dependency"),converged:I.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:I.boolean().describe("Whether anything was installed or updated"),allSucceeded:I.boolean().describe("Whether no tool failed (a refusal is not a failure)")},SR={tools:I.array(I.enum(Fr)).optional().describe("Which tools to act on. Omit for all five."),mode:I.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:I.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},TR={"anthropic/requiresUserInteraction":!0},gc=w({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the plugin (which serves the infra-kit MCP server; a leftover .mcp.json entry is reported, never written), then bring brew, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:SR,outputSchema:xR,requiresHumanConfirm:!0,meta:TR,handler:e=>em({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as om}from"node:fs";import nm from"node:path";import jR from"node:process";import{z as qe}from"zod";import{createHash as CR}from"node:crypto";import{readFileSync as AR}from"node:fs";var hc=e=>CR("sha256").update(AR(e)).digest("hex");import{readFileSync as NR,writeFileSync as UJ}from"node:fs";import tm from"node:path";import{z as Ie}from"zod";var He="vendor",$R=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),IR=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),_R=[".tsbuildinfo"],vc=e=>$R.has(e),yc=e=>IR.has(e)?!0:_R.some(r=>e.endsWith(r)),rm=e=>{let r=e.split("/"),t=r.pop()??"";return r.some(n=>vc(n))||yc(t)};import{readdirSync as DR}from"node:fs";import kc from"node:path";var OR=e=>e.split(kc.sep).join("/"),wc=e=>{let r=[],t=o=>{for(let n of DR(o,{withFileTypes:!0})){let s=kc.join(o,n.name);if(n.isDirectory()){if(vc(n.name))continue;t(s);continue}yc(n.name)||r.push(OR(kc.relative(e,s)))}};return t(e),r.sort()};var ze=".sync-manifest.json",bc=1,MR=Ie.object({schemaVersion:Ie.number().optional(),source:Ie.string(),commit:Ie.string(),syncedAt:Ie.string(),fileCount:Ie.number(),files:Ie.record(Ie.string(),Ie.string())}),Rc=e=>(e.schemaVersion??bc)>bc;var Pc=e=>{let r=tm.join(e,ze),t;try{t=NR(r,"utf8")}catch{throw new Error(`Missing ${ze} at ${r}`)}let o=MR.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${ze} at ${r}: ${Ie.prettifyError(o.error)}`);return o.data};var Ec=(e,r)=>{let t=Object.fromEntries(Object.entries(r.files).filter(([c])=>!rm(c))),o=wc(e),n=[],s=[];for(let c of o){if(!(c in t)){s.push(c);continue}hc(tm.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 xc=30,Sc=(e,r)=>{if(r.length!==0){l.info(`
|
|
439
|
+
${e} (${r.length}):`);for(let t of r.slice(0,xc))l.info(` ${t}`);r.length>xc&&l.info(` \u2026and ${r.length-xc} more`)}},sm=async(e={})=>{let r=e.cwd??await R(),t=nm.join(r,He),o={modified:[],added:[],removed:[],fileCount:0};if(!om(t)){l.info(`\u2139\uFE0F No ${He}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...o};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}if(!om(nm.join(t,ze))){l.error(`\u274C Missing ${He}/${ze}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...o};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}let n=Pc(t);if(Rc(n)){l.error(`\u274C ${He}/${ze} has a newer schemaVersion (${String(n.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...o};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=Ec(t,n),c=s.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${He}/ has drifted from ${He}/${ze}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Sc("Modified",s),Sc("Added (not in manifest)",i),Sc("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${He}/ matches manifest (${n.fileCount} files).`);let p={status:c?"drift":"clean",ok:!c,fileCount:n.fileCount,modified:s,added:i,removed:a};return{content:y(JSON.stringify(p,null,2)),structuredContent:p}},FR={status:qe.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:qe.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:qe.number(),modified:qe.array(qe.string()),added:qe.array(qe.string()),removed:qe.array(qe.string())},Tc=w({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:FR,handler:()=>sm({cwd:jR.cwd()})});import Cc from"node:process";import{z as Yr}from"zod";var im=async e=>{try{return await e()}catch{return null}},am=async()=>{let e=H.version;l.info(e);let r=jl(Cc.env),t=await im(R),o=t===null?null:await im(()=>Pe(t)),n={version:e,cwd:Cc.cwd(),repoRoot:t,mainRepoRoot:o,projectDir:Cc.env.CLAUDE_PROJECT_DIR||null,launch:r,toolPrefix:Fl(r)};return{content:y(JSON.stringify(n,null,2)),structuredContent:n}},Ac=w({name:"version",description:"Print the installed infra-kit CLI version, where this server process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR) and which route spawned it (plugin or a repo .mcp.json entry) with the tool prefix that route produces",inputSchema:{},outputSchema:{version:Yr.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Yr.string().describe("The working directory of this server process"),repoRoot:Yr.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Yr.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Yr.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this server, or null"),launch:Yr.enum(["plugin","legacy"]).describe("Which route spawned this server: the Claude Code plugin, or a repo .mcp.json entry (legacy)"),toolPrefix:Yr.string().describe("The prefix every tool of this server carries in this session")},handler:am});import cm from"@inquirer/confirm";import LR from"node:path";import{z as Ye}from"zod";import{$ as on}from"zx";var WR="feature",JR="release",pm=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:n,cmux:s}=e,i=e.ide??e.cursor;await ie({operation:"create worktrees"});try{let a=await de("release"),c=await R(),p=`${c}${re}`;await lm(`${p}/${JR}`),await lm(`${p}/${WR}`);let d=[];if(o)d=o.split(",").map(O=>Re(ye(O.trim())));else{let O=await _(),C=O.map(P=>P.branch);if(C.length===0)return l.info("\u2139\uFE0F No open release branches found"),h.print(),{content:y(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=C;else{h.setInteractive();let P=new Map(O.map(ce=>[ce.branch,N(ce.title)])),_e=await K();d=await Wt(ee({branches:C,descriptions:_e,types:P}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",Vr(d)),await z(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let u=await E(),m=i??(Ee(u).length>0?"workspace":"none");h.addOption("--ide",m);let v=n??u.worktrees?.openInGithubDesktop??await A(O=>cm({message:"Open created worktrees in GitHub Desktop?"},O),{whenHeadless:{value:!1}});typeof n>"u"&&u.worktrees?.openInGithubDesktop===void 0&&h.setInteractive(),v?h.addOption("--github-desktop",!0):h.addOption("--no-github-desktop",!0);let f=s??u.worktrees?.openInCmux??await A(O=>cm({message:"Open created worktrees in cmux?"},O),{whenHeadless:{value:!1}});typeof s>"u"&&u.worktrees?.openInCmux===void 0&&h.setInteractive(),f?h.addOption("--cmux",!0):h.addOption("--no-cmux",!0);let{branchesToCreate:k}=VR({selectedReleaseBranches:d,currentWorktrees:a}),x=await BR(k,p);if(GR(x),m==="workspace"&&await oc({projectRoot:c,worktreeDir:p,branches:x}),v)for(let O of x)await on`github ${p}/${O}`,await on`sleep 5`;if(f){let O=LR.basename(await Pe(c)),C=await rr(),P=await En(O),_e=!1;for(let ce of x){let Xr=`${p}/${ce}`;if(C.has(await Pr(Xr)))continue;let hr=Sn({branch:ce});try{if(P)await it({cwd:Xr,title:hr,group:P});else{let vr=await it({cwd:Xr,title:hr});_e||(P=await xn(O,[vr]),_e=!0)}}catch(vr){l.warn({error:vr,branch:ce},`\u26A0\uFE0F Failed to open cmux workspace for ${ce}`)}}}h.print();let D={createdWorktrees:x,count:x.length};return{content:y(JSON.stringify(D,null,2)),structuredContent:D}}catch(a){throw De(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'"}))}},lm=async e=>{await on`mkdir -p ${e}`},VR=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>Rr(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},BR=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await on`git worktree add ${s} ${n}`,await on({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},GR=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")},$c=w({name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:Ye.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:Ye.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:Ye.enum(fs).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:Ye.enum(fs).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:Ye.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:Ye.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:Ye.array(Ye.string()).describe("List of created git worktree branches"),count:Ye.number().describe("Number of git worktrees created")},handler:pm});import{z as Ut}from"zod";var dm=async()=>{await E();let e=await de("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([_(),K()]),o=new Map(r.map(c=>[c.branch,N(c.title)])),n=e.flatMap(c=>{let p=W(c);if(!p)return[];let d=V(p),u=o.get(c)||"regular",m=t.get(Z(p))||null;return[{version:d,type:u,description:m}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=Do(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});l.info(`\u{1F33F} Active worktrees:
|
|
440
440
|
|
|
441
441
|
${i.join(`
|
|
442
|
-
`)}`);let a={worktrees:n,count:n.length};return{content:y(JSON.stringify(a,null,2)),structuredContent:a}},Sc=w({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:Gt.array(Gt.object({version:Gt.string().describe("Release version"),type:Gt.enum(["regular","hotfix"]).describe("Release type"),description:Gt.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Gt.number().describe("Number of worktrees")},handler:nm});import{z as Zr}from"zod";var jR=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"'})}},FR=(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(", ")}`})},sm=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await ie({operation:"remove worktrees"}),await E(),jR({all:t,versions:o});try{let n=await de("release");if(n.length===0){l.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}let s=await R(),i=`${s}${re}`,a=[];if(t)a=n;else if(o)a=o.split(",").map(d=>Re(ye(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([K(),_()]),m=new Map(u.map(v=>[v.branch,N(v.title)]));a=await Lt(ee({branches:n,descriptions:d,types:m}),{required:!0})}FR(a,n);let c=a.length===n.length;c?h.addOption("--all",!0):h.addOption("--versions",Vr(a)),await z(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let p=await Ur({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await qr({projectRoot:s,worktreeDir:i,currentWorktrees:n,removedWorktrees:p.removed,allowEditorRelaunch:!r}),No(p),h.print(),Mo({result:p,operation:"remove worktrees"})}catch(n){throw De(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"}))}},Tc=w({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named version must be an active worktree, or the call errors without removing anything. What survives: the release branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.',requiresHumanConfirm:!0,inputSchema:{versions:Zr.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:Zr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Zr.array(Zr.string()).describe("List of removed git worktree branches"),failedWorktrees:Zr.array(Zr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Zr.number().describe("Number of git worktrees removed")},handler:sm});import{z as tn}from"zod";var im=async e=>{let{confirmedCommand:r}=e;await ie({operation:"sync worktrees"}),await E();try{let t=await de("release"),o=await R(),n=`${o}${re}`,s=await es();await z(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let{branchesToRemove:i}=LR({releasePRsList:s,currentWorktrees:t}),a=await Ur({branches:i,worktreeDir:n,projectRoot:o});return await qr({projectRoot:o,worktreeDir:n,currentWorktrees:t,removedWorktrees:a.removed,allowEditorRelaunch:!1}),No(a),h.print(),Mo({result:a,operation:"sync worktrees"})}catch(t){throw De(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"}))}},LR=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>Rr(s)).filter(s=>!r.includes(s))}},Cc=w({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:tn.array(tn.string()).describe("List of removed worktree branches"),failedWorktrees:tn.array(tn.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:tn.number().describe("Number of worktrees removed during sync")},handler:im});var WR=[{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"}],gs=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:hi,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:ya,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:_a,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Ua,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:Ka,mcpExposed:!0,mutating:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Aa,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ia,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:wa,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:tc,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Wa,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Ja,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:xc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Sc,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"reopen",menuGroup:"worktrees",mcpTool:sc,mcpExposed:!0,mutating:!1,groupPath:["reopen"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Tc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Cc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:pa,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Pi,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Ai,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:la,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:ua,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:mi,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:Rc,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"setup",menuGroup:"setup",mcpTool:pc,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:aa,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:ui,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Ec,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-autoload"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]},{cliName:"mcp",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["mcp"]}];var JR={"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}},VR=["reopen"],BR=()=>gs.flatMap(e=>{if(!e.mcpExposed||!e.mcpTool)return[];let r=JR[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&&!VR.includes(e.mcpTool.name);return[{...e.mcpTool,title:r.title,annotations:{readOnlyHint:t,...t?{}:{destructiveHint:!0},openWorldHint:r.openWorld}}]}),GR=e=>gs.filter(r=>r.menuGroup===e),UR=e=>gs.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import Ac from"node:process";var KR="MODULE_TYPELESS_PACKAGE_JSON",HR=(e,r)=>typeof e=="object"&&e!==null?e.code:r,am=!1,zR=()=>{if(am)return;am=!0;let e=Ac.emitWarning.bind(Ac);Ac.emitWarning=((r,...t)=>{HR(t[0],t[1])!==KR&&e(r,...t)})};export{y as a,Xl as b,Ql as c,gi as d,rp as e,Og as f,mo as g,fo as h,$r as i,zT as j,kp as k,Qg as l,$p as m,Ip as n,xt as o,_p as p,Dp as q,Jn as r,Vn as s,Sh as t,vm as u,Ni as v,c$ as w,l$ as x,Ji as y,Vi as z,Rv as A,Ed as B,Sd as C,Td as D,da as E,Id as F,Ft as G,Ky as H,Fd as I,uO as J,qd as K,tu as L,Vt as M,Hk as N,zk as O,du as P,uu as Q,mu as R,bu as S,Ru as T,Au as U,$u as V,be as W,ds as X,Mu as Y,xb as Z,Hu as _,Xu as $,em as aa,om as ba,nm as ca,sm as da,im as ea,WR as fa,gs as ga,BR as ha,GR as ia,UR as ja,zR as ka};
|
|
443
|
-
//# sourceMappingURL=chunk-
|
|
442
|
+
`)}`);let a={worktrees:n,count:n.length};return{content:y(JSON.stringify(a,null,2)),structuredContent:a}},Ic=w({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:Ut.array(Ut.object({version:Ut.string().describe("Release version"),type:Ut.enum(["regular","hotfix"]).describe("Release type"),description:Ut.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Ut.number().describe("Number of worktrees")},handler:dm});import{z as Zr}from"zod";var UR=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"'})}},KR=(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(", ")}`})},um=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;await ie({operation:"remove worktrees"}),await E(),UR({all:t,versions:o});try{let n=await de("release");if(n.length===0){l.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:y(JSON.stringify(d,null,2)),structuredContent:d}}let s=await R(),i=`${s}${re}`,a=[];if(t)a=n;else if(o)a=o.split(",").map(d=>Re(ye(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([K(),_()]),m=new Map(u.map(v=>[v.branch,N(v.title)]));a=await Wt(ee({branches:n,descriptions:d,types:m}),{required:!0})}KR(a,n);let c=a.length===n.length;c?h.addOption("--all",!0):h.addOption("--versions",Vr(a)),await z(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let p=await Ur({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await qr({projectRoot:s,worktreeDir:i,currentWorktrees:n,removedWorktrees:p.removed,allowEditorRelaunch:!r}),jo(p),h.print(),Fo({result:p,operation:"remove worktrees"})}catch(n){throw De(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"}))}},_c=w({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches. Over MCP you MUST pass "versions" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named version must be an active worktree, or the call errors without removing anything. What survives: the release branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.',requiresHumanConfirm:!0,inputSchema:{versions:Zr.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:Zr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Zr.array(Zr.string()).describe("List of removed git worktree branches"),failedWorktrees:Zr.array(Zr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Zr.number().describe("Number of git worktrees removed")},handler:um});import{z as nn}from"zod";var mm=async e=>{let{confirmedCommand:r}=e;await ie({operation:"sync worktrees"}),await E();try{let t=await de("release"),o=await R(),n=`${o}${re}`,s=await ts();await z(r,"Are you sure you want to proceed with these worktree changes?"),r||h.addOption("--yes",!0);let{branchesToRemove:i}=HR({releasePRsList:s,currentWorktrees:t}),a=await Ur({branches:i,worktreeDir:n,projectRoot:o});return await qr({projectRoot:o,worktreeDir:n,currentWorktrees:t,removedWorktrees:a.removed,allowEditorRelaunch:!1}),jo(a),h.print(),Fo({result:a,operation:"sync worktrees"})}catch(t){throw De(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"}))}},HR=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>Rr(s)).filter(s=>!r.includes(s))}},Dc=w({name:"worktrees-sync",description:"Remove worktrees whose release PR is no longer open (stale cleanup). Only removes \u2014 never creates; use worktrees-add to create worktrees for new releases. The CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically.",inputSchema:{},outputSchema:{removedWorktrees:nn.array(nn.string()).describe("List of removed worktree branches"),failedWorktrees:nn.array(nn.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:nn.number().describe("Number of worktrees removed during sync")},handler:mm});var zR=[{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"}],ys=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:ki,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:ba,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Na,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Ya,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:Za,mcpExposed:!0,mutating:!0,groupPath:["release","desc-edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:_a,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Oa,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Pa,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:ac,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Ba,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Ga,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:$c,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Ic,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"reopen",menuGroup:"worktrees",mcpTool:pc,mcpExposed:!0,mutating:!1,groupPath:["reopen"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:_c,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Dc,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:ma,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Si,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:_i,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:ua,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:ga,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:hi,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:Tc,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"setup",menuGroup:"setup",mcpTool:gc,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:pa,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:gi,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Ac,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"vendor",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["vendor"]},{cliName:"config",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["config"]},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-autoload"]},{cliName:"env-token-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-set"]},{cliName:"env-token-remove",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["env-token-remove"]},{cliName:"mcp",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!1,groupPath:["mcp"]}];var qR={"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}},YR=["reopen"],ZR=()=>ys.flatMap(e=>{if(!e.mcpExposed||!e.mcpTool)return[];let r=qR[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&&!YR.includes(e.mcpTool.name);return[{...e.mcpTool,title:r.title,annotations:{readOnlyHint:t,...t?{}:{destructiveHint:!0},openWorldHint:r.openWorld}}]}),XR=e=>ys.filter(r=>r.menuGroup===e),QR=e=>ys.some(r=>r.longRunning===!0&&r.groupPath.join(" ")===e);import Oc from"node:process";var eP="MODULE_TYPELESS_PACKAGE_JSON",rP=(e,r)=>typeof e=="object"&&e!==null?e.code:r,fm=!1,tP=()=>{if(fm)return;fm=!0;let e=Oc.emitWarning.bind(Oc);Oc.emitWarning=((r,...t)=>{rP(t[0],t[1])!==eP&&e(r,...t)})};export{y as a,op as b,np as c,yi as d,ip as e,Jg as f,fo as g,go as h,$r as i,tC as j,Ep as k,ih as l,Np as m,Mp as n,xt as o,jp as p,Fp as q,Bn as r,Gn as s,Dh as t,Em as u,Fi as v,h$ as w,v$ as x,Gi as y,Ui as z,Av as A,Ad as B,Id as C,_d as D,fa as E,Md as F,Lt as G,Qy as H,Bd as I,wO as J,eu as K,au as L,Bt as M,ew as N,rw as O,hu as P,vu as Q,yu as R,Su as S,Tu as T,Ua as U,Mu as V,ju as W,be as X,fs as Y,Bu as Z,Db as _,em as $,sm as aa,am as ba,pm as ca,dm as da,um as ea,mm as fa,zR as ga,ys as ha,ZR as ia,XR as ja,QR as ka,tP as la};
|
|
443
|
+
//# sourceMappingURL=chunk-R6AYBYV6.js.map
|