infra-kit 0.11.0 → 0.11.10
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-2H6VQIGT.js → chunk-ATGBWGER.js} +2 -2
- package/dist/{chunk-R2SZWOPC.js → chunk-GBPW4ERM.js} +2 -2
- package/dist/{chunk-F656FWV5.js → chunk-J6BHN362.js} +2 -2
- package/dist/{chunk-AG7XWZNT.js → chunk-KPRFMZCX.js} +2 -2
- package/dist/chunk-LAHHNH3T.js +2 -0
- package/dist/chunk-LAHHNH3T.js.map +7 -0
- package/dist/{chunk-OWX4O3IS.js → chunk-SREJWU57.js} +2 -2
- package/dist/chunk-ZZ7HCY2S.js +4 -0
- package/dist/{chunk-RZF36IGQ.js.map → chunk-ZZ7HCY2S.js.map} +2 -2
- package/dist/cli.js +96 -118
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +2 -2
- package/dist/{dev-wizard-run-J5WSWCZT.js → dev-wizard-run-NQM3VPQA.js} +2 -2
- package/dist/mcp-proxy.js +1 -1
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- package/readme.md +32 -30
- package/dist/chunk-6UJQB36N.js +0 -2
- package/dist/chunk-6UJQB36N.js.map +0 -7
- package/dist/chunk-RZF36IGQ.js +0 -4
- /package/dist/{chunk-2H6VQIGT.js.map → chunk-ATGBWGER.js.map} +0 -0
- /package/dist/{chunk-R2SZWOPC.js.map → chunk-GBPW4ERM.js.map} +0 -0
- /package/dist/{chunk-F656FWV5.js.map → chunk-J6BHN362.js.map} +0 -0
- /package/dist/{chunk-AG7XWZNT.js.map → chunk-KPRFMZCX.js.map} +0 -0
- /package/dist/{chunk-OWX4O3IS.js.map → chunk-SREJWU57.js.map} +0 -0
- /package/dist/{dev-wizard-run-J5WSWCZT.js.map → dev-wizard-run-NQM3VPQA.js.map} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as
|
|
3
|
-
${i}`:"")},
|
|
2
|
+
import{a as tp,b as jo,d as dr,e as Fo,f as op,g as sp,h as ip,i as ap,j as cp,k as lp,l as dp,m as pp,p as hp,r as ce}from"./chunk-SREJWU57.js";import{a as gd,b as hd,c as hi,d as vd,e as yd,f as wd,g as kd,h as nn,i as bd,j as Rd,k as Ed,l as Pd,m as Sd,n as vi,o as xd,p as Td,q as Cd,r as Ad,s as yi,t as So,u as lt,v as $d,w as xo,x as Id}from"./chunk-KPRFMZCX.js";import{a as X,b as V,c as dt,d as Oo,e as Ei,f as No,g as Pi,h as an,i as Tt,j as _o,k as Bd,l as cn,m as ln,n as Ti,o as Ci,q as Ai}from"./chunk-GBPW4ERM.js";import{b as rn,c as Eo,d as gi,e as dd,f as Po,g as pd,i as ud,k as md,m as se,o as fd}from"./chunk-AWFGP6GY.js";import{a as gp}from"./chunk-TVG47UHG.js";import{a as Mo,b as Ge,c as re,d as rp,e as np,f as T,g,h as Lo,i as up,j as x,k as Vo,l as Z}from"./chunk-ATGBWGER.js";import{$ as Yd,A as jd,B as Fd,C as Ld,D as $o,E as Io,F as sn,G as ki,H as Do,I as Vd,J as Jd,K as bi,L as Ri,M as Wd,N as l,O as Si,P as U,Q as w,R as Gd,S as Ud,T as pt,U as qd,V as xi,W as ut,X as Hd,Y as zd,Z as K,_ as $,a as on,aa as mt,b as P,c as Dd,ca as Xd,d as A,e as Y,ea as Zd,f as ie,g as To,h as ir,i as f,j as Od,k as Co,l as L,la as Qd,m as Se,n as De,o as Nd,oa as ep,p as wi,q as H,r as W,s as Ao,t as _d,u as ar,v as he,w as R,x as cr,y as lr,z as Md}from"./chunk-J6BHN362.js";import{a as Kd}from"./chunk-MFAFQVTW.js";import{a as G}from"./chunk-LAHHNH3T.js";import{a as at,b as yo,c as Ie,d as id,e as wo,f as nr,g as or,h as ko,i as sr,j as bo,k as ad,l as cd,m as ld,n as ct,o as Ro,p as ge}from"./chunk-ZZ7HCY2S.js";import{a as mp,b as fp}from"./chunk-QWVLAZ6N.js";import vT,{Separator as Gg}from"@inquirer/select";import{existsSync as yT,realpathSync as wT}from"node:fs";import{homedir as kT}from"node:os";import fe from"node:process";import{fileURLToPath as Kg}from"node:url";import Zp from"node:process";import{z as we}from"zod";import Ep from"node:fs";import ur from"node:path";import{packageConfigSchema as rh}from"@slip-stream-kit/config/internal";import wp from"node:fs/promises";import Oi from"node:path";import{pathToFileURL as nh}from"node:url";import{z as oh}from"zod";import vp from"node:path";var dn=["frontend","backend","lib","e2e","mobile"],Yg={ui:"frontend",api:"backend",tests:"e2e"},Xg="mobile-app",Zg=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Qg=(e,t)=>{let r=vp.relative(t,e).split(vp.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=Yg[o];if(s)return s}return r.at(-1)===Xg?"mobile":null},eh=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of Zg)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},pn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??Qg(e,t)??eh(r)??"lib";var ft={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},yp=2e3,$i={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${yp}} pnpm exec playwright test --ui --headed --workers=1`,"e2e-test-chrome":"pnpm exec playwright test --project=chromium","e2e-test-debug":"pnpm exec playwright test --debug","e2e-test-codegen":"pnpm exec playwright codegen","playwright-install":"pnpm exec playwright install --with-deps"},Ii={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"]},Di=(e,t=ft)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import th from"node:fs/promises";var Oe=async e=>{try{return await th.access(e),!0}catch{return!1}};var Ue="infra-kit.config.ts",un=async e=>{try{let t=await wp.readFile(Oi.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},kp=async e=>{let t=await wp.stat(e),o=(await import(`${nh(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${Ue} at ${e} has no default export`);return typeof o=="function"?await o():o},Ct=async e=>{let t=Oi.join(e,Ue);if(await Oe(t))try{let n=(await kp(t))?.type;return dn.find(o=>o===n)}catch{return}},mn=async(e,t=ft)=>{let r=Oi.join(e,Ue);if(!await Oe(r))throw new Error(`${Ue} not found at ${r}`);let n=await kp(r),o=rh.safeParse(n);if(!o.success)throw new Error(`Invalid ${Ue} at ${r}: ${oh.prettifyError(o.error)}`);return Di(o.data,t)};import bp from"node:fs/promises";import Jo from"node:path";import sh from"yaml";var ih="pnpm-workspace.yaml",ah=async e=>(await bp.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Jo.join(e,r.name)),ch=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await ah(n));continue}let o=Jo.join(n,t);await Oe(o)&&r.push(o)}return r},lh=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await ch(r,n);return r},le=async e=>{let t=await bp.readFile(Jo.join(e,ih),"utf-8"),n=((sh.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await lh(e,s);for(let a of i)await Oe(Jo.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import fn from"node:path";var gn=async e=>{let t=fn.resolve(e);for(;t!==fn.dirname(t);){if(await Oe(fn.join(t,"package.json")))return t;t=fn.dirname(t)}if(await Oe(fn.join(t,"package.json")))return t;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 Ne=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},gt=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);if(n===-1||o===-1||o<n)return null;let s=e.slice(0,n).replace(/\n+$/,""),i=e.slice(o+r.length).replace(/^\n+/,"");return s+(i?`
|
|
3
|
+
${i}`:"")},Ni=(e,t)=>{let r=e.indexOf(t);if(r===-1)return null;let o=e.slice(r+t.length).match(/^([^\s>]+)/);return o?o[1]:null},Rp=(e,t,r)=>`${e}
|
|
4
4
|
${t}
|
|
5
|
-
${r}`,
|
|
5
|
+
${r}`,pr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Rp(r,t,n),i=Ne(e,r,n);if(o==="replace-in-place"&&i){let d=e.indexOf(r),p=e.indexOf(n)+n.length;return e.slice(0,d)+s+e.slice(p)}let c=(i?gt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
6
6
|
${s}
|
|
7
7
|
`:`${s}
|
|
8
|
-
`};var
|
|
8
|
+
`};var ve="<!-- infra-kit:begin -->",_e="<!-- infra-kit:end -->",_i="<!-- infra-kit:version ",Me="<!-- infra-kit:package:begin -->",Ke="<!-- infra-kit:package:end -->",At="<!-- infra-kit:package:version ";var dh=e=>{let t=e.indexOf(Me)+Me.length;return e.slice(t,e.indexOf(Ke))},ph=e=>{let t=e.indexOf(At);if(t===-1)return null;let r=e.slice(t+At.length).match(/^\S+\s+([^\s>]+)/)?.[1];return dn.find(n=>n===r)??null},$t=e=>{if(e===null)return{state:"missing"};if(!Ne(e,Me,Ke))return e.includes(Me)||e.includes(Ke)?{state:"malformed"}:Ne(e,ve,_e)?{state:"foreign-block"}:{state:"no-block"};let t=dh(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Ni(t,At),o=ph(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import uh from"node:fs";var It=e=>{try{return uh.readFileSync(e,"utf-8")}catch{return null}};var Pp="pnpm-workspace.yaml",mh="CLAUDE.md",ji=e=>{let t=ur.resolve(e);for(;t!==ur.dirname(t);){if(Ep.existsSync(ur.join(t,Pp)))return t;t=ur.dirname(t)}return Ep.existsSync(ur.join(t,Pp))?t:null},Mi=new Map,Wo=()=>{Mi.clear()},fh=async e=>{let t;try{t=await le(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=ur.join(r,mh),o=It(n);if(o!==null&&$t(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},mr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Mi.get(e);if(t)return t;let r=await fh(e);return Mi.set(e,r),r};import Dt from"node:fs";import ht from"node:path";var Sp=`---
|
|
9
9
|
name: TODO
|
|
10
10
|
description: TODO \u2014 one sentence describing the product surface this package renders.
|
|
11
11
|
colors:
|
|
@@ -74,7 +74,7 @@ TODO \u2014 for each component in the front matter list: its variants, its state
|
|
|
74
74
|
- Do TODO.
|
|
75
75
|
- Don't TODO.
|
|
76
76
|
- Don't TODO.
|
|
77
|
-
`;var
|
|
77
|
+
`;var xp=`# {{packageName}}
|
|
78
78
|
|
|
79
79
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
80
80
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -95,29 +95,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
95
95
|
- Module-scope state belongs in the handler entry file \u2014 that is the file which re-evaluates on reload.
|
|
96
96
|
- Env vars come from Doppler via \`ik env-load\`; never commit a secret.
|
|
97
97
|
- The route prefix this service answers is declared in the consuming UI's \`dev.proxy\`, so changing a path is a two-package change.
|
|
98
|
-
`;var
|
|
99
|
-
|
|
100
|
-
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
101
|
-
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
102
|
-
|
|
103
|
-
## Read first
|
|
104
|
-
|
|
105
|
-
- {{readmeBullet}}
|
|
106
|
-
- \`infra-kit.config.ts\` \u2014 the audit rules this package must satisfy.
|
|
107
|
-
|
|
108
|
-
## Checks
|
|
109
|
-
|
|
110
|
-
- \`infra-kit audit\` \u2014 validate this package against its infra-kit rules.
|
|
111
|
-
- \`pnpm run ts-check && pnpm run eslint-check && pnpm run test\` \u2014 this package only.
|
|
112
|
-
- \`pnpm run qa\` at the repo root \u2014 the full gate; run it before claiming completion.
|
|
113
|
-
|
|
114
|
-
## Rules
|
|
115
|
-
|
|
116
|
-
- Specs run on Playwright.
|
|
117
|
-
- Every spec cleans up what it creates, in teardown.
|
|
118
|
-
- Selectors live in Page Objects, never inline in specs.
|
|
119
|
-
- Never point a run at a production environment.
|
|
120
|
-
`;var fp="# {{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 gp=`# {{packageName}}
|
|
98
|
+
`;var Tp="# {{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- `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- Specs run on Playwright. The `e2e-test*` scripts and the `E2E_SLOW_MO` / trace settings in `playwright.config.ts` are shared across repos and checked by `infra-kit audit` \u2014 never rename or fork them locally.\n- {{e2eDocBullet}}\n- `e2e-test-ui-demo` (visible browser, one worker) is for showing a flow to a person. It sets `E2E_SLOW_MO=2000` \u2014 2 s before every action \u2014 unless the variable is already set; debug with `e2e-test-ui` instead, and everywhere else `E2E_SLOW_MO` stays unset, which the config reads as 0.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- Never point a run at a production environment.\n";var Cp="# {{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 Ap=`# {{packageName}}
|
|
121
99
|
|
|
122
100
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
123
101
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -139,7 +117,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
139
117
|
- Changing that map is a breaking change for every dependent package.
|
|
140
118
|
- Run \`pnpm run build\` before a dependent package can see a change.
|
|
141
119
|
- No app-specific logic belongs here.
|
|
142
|
-
`;var
|
|
120
|
+
`;var $p=`# {{packageName}}
|
|
143
121
|
|
|
144
122
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
145
123
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -161,23 +139,23 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
161
139
|
- The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
|
|
162
140
|
- The web build feeds the native shell, so a device run needs a rebuild first.
|
|
163
141
|
- Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
|
|
164
|
-
`;var
|
|
165
|
-
`)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},
|
|
166
|
-
`),t);return
|
|
167
|
-
`).replace(
|
|
168
|
-
`};var
|
|
169
|
-
`)};var
|
|
170
|
-
`)};import
|
|
171
|
-
`).find(r=>r.trim().length>0)??"").trim()
|
|
172
|
-
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${
|
|
142
|
+
`;var Ip="# 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` / `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 edit` \u2014 release-branch and deploy flow.\n- `ik release merge-dev` \u2014 merge the dev branch into every release branch.\n- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.\n- `ik audit --fix` \u2014 regenerate this repo's infra-kit guidance blocks (`--all` for every package, `--root` for this file).\n- `ik doctor` \u2014 check gh / doppler / aws install + auth and repo setup.\n- `ik setup` \u2014 set up infra-kit on this machine: shell integration, the Claude Code skills plugin, and the external CLIs (brew, git, aws, gh, doppler, portless).\n\n## Conventions\n\n- Tickets are prefixed by area: `[FE]` frontend, `[BE]` backend, `[DO]` DevOps/infra, `[APP]` mobile app, `[IDEA]` proposal, `[ROOT]` cross-cutting. Pick the single dominant area.\n- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets.\n- Every workspace package has its own CLAUDE.md with package-scoped rules \u2014 read it before editing that package.\n- Launch Claude Code at the repository root: the infra-kit plugin (the `/infra-kit:*` skills) and this repo's `.claude/settings.json` hooks load only from there. If the `/infra-kit:*` skills are absent, this is a subdirectory session \u2014 restart Claude Code at the root.\n\n## Agents\n\n- Agents drive the same CLI over Bash: `infra-kit <command> --agent --json`. There is no MCP server; the `/infra-kit:*` skills are the entry points and they run the CLI on `PATH`.\n- A confirm-gated command (`release create|remove|edit|merge-dev|deploy-all|deploy-selected`, `worktrees add|remove|sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host's prompt on the argv is the approval. `release deliver` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n";var fr={"root/body":Ip.trimEnd(),"package/frontend":Cp.trimEnd(),"package/backend":xp.trimEnd(),"package/lib":Ap.trimEnd(),"package/e2e":Tp.trimEnd(),"package/mobile":$p.trimEnd(),"design/skeleton":Sp.trimEnd()};var Fi=/\{\{(\w+)\}\}/g,Rh=/^- \{\{(\w+)\}\}$/,Eh=e=>new Set([...e.matchAll(Fi)].map(t=>t[1])),Ph=(e,t)=>{let r=Object.keys(t).filter(n=>!e.has(n));if(r.length>0)throw new Error(`renderTemplate: variable(s) never used by the template: ${r.join(", ")}`)},Sh=(e,t)=>{let r=[...e].filter(n=>!(n in t));if(r.length>0)throw new Error(`renderTemplate: placeholder(s) with no variable: ${r.map(n=>`{{${n}}}`).join(", ")}`)},xh=(e,t)=>e.filter(r=>{let n=Rh.exec(r);return n===null||t[n[1]]!==""}),Th=(e,t)=>{for(let r of e)for(let n of r.matchAll(Fi)){let o=t[n[1]];if(o!==void 0&&o.includes(`
|
|
143
|
+
`)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},gr=(e,t)=>{let r=Eh(e);Sh(r,t),Ph(r,t);let n=xh(e.split(`
|
|
144
|
+
`),t);return Th(n,t),n.join(`
|
|
145
|
+
`).replace(Fi,(o,s)=>t[s])};var Ch="name: TODO",Li=e=>{let t=gr(fr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(Ch,()=>r)}
|
|
146
|
+
`};var Ah=(e,t)=>`${At}${e} ${t} -->`,$h="`README.md` \u2014 what this package is and how to run it.",Vi="docs/e2e-playwright.md",Ih=`\`${Vi}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Ji=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=gr(fr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?$h:"",...r==="e2e"?{e2eDocBullet:i?Ih:""}:{}});return[Ah(t,r),"",a].join(`
|
|
147
|
+
`)};var Dh=e=>`${_i}${e} -->`,Wi=e=>{let t=gr(fr["root/body"],{});return[Dh(e),"",t].join(`
|
|
148
|
+
`)};import hr from"node:fs";import Oh from"node:path";var Bo=e=>{let t;try{t=hr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},hn=(e,t)=>{Bo(e);let r=hr.existsSync(e)?hr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(hr.mkdirSync(Oh.dirname(e),{recursive:!0}),hr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Bi=(e,t,r)=>{let n=hr.readFileSync(e,"utf-8");if(!Ne(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Dp=(e,t,r)=>Ne(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Gi=(e,t,r,n)=>{let o=Dp(e,r,n),s=Dp(t,r,n);if(!(o===null||s===null)&&(o.before!==s.before||o.after!==s.after))throw new Error("Post-write validation failed: content outside the managed markers changed")};var Uo="<!-- infra-kit:import:begin -->",Ko="<!-- infra-kit:import:end -->",Nh="AGENTS.md",Op="CLAUDE.md",_h="README.md",Ui="DESIGN.md",Mh=["frontend","mobile"],jh=e=>Dt.existsSync(e)?Dt.readFileSync(e,"utf-8"):null,Ki=(e,t)=>{try{return Dt.readdirSync(e).includes(t)}catch{return!1}},Go=(e,t,r)=>{let n=t instanceof Error?t.message:String(t),o={path:e,action:"failed",message:n};return r&&(o.type=r),o},Np=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=jh(e),i=s===null?"":o?.(s)??s,a=pr({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=hn(e,a);return Bi(e,r,n),s!==null&&Gi(i,a,r,n),c},Fh=e=>{if(!Dt.existsSync(e))return"unchanged";Bo(e);let t=Dt.readFileSync(e,"utf-8"),r=gt(t,ve,_e);return r===null?"unchanged":r.trim()===""?(Dt.rmSync(e),"removed"):hn(e,r)},Lh=(e,t)=>Np({filePath:e,body:Wi(t),startMarker:ve,endMarker:_e,prepare:r=>gt(r,Uo,Ko)??r}),vn=async(e,{version:t})=>{let r=ht.join(e,Op),n=ht.join(e,Nh),o=[];try{o.push({path:r,action:Lh(r,t)})}catch(s){o.push(Go(r,s))}try{o.push({path:n,action:Fh(n)})}catch(s){o.push(Go(n,s))}return o},Vh=(e,t,r)=>{if(!Mh.includes(r)||Ki(e,Ui))return null;let n=ht.join(e,Ui);try{return{path:n,action:hn(n,Li(t)),type:r}}catch(o){return Go(n,o,r)}},yn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=ht.join(e,Op),i=await un(e),a=i.name??ht.basename(e),c=pn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),d=Ji({version:r,type:c,packageName:a,relDir:ht.relative(t,e).split(ht.sep).join("/"),hasReadme:Ki(e,_h),hasDesign:Ki(e,Ui),hasE2eDoc:Dt.existsSync(ht.join(t,Vi))}),p=[];try{p.push({path:s,action:Np({filePath:s,body:d,startMarker:Me,endMarker:Ke}),type:c})}catch(u){p.push(Go(s,u,c))}if(n){let u=Vh(e,a,c);u&&p.push(u)}return p};import Xh from"node:path";import _p from"node:path";var qi="agent-guidance",wn="CLAUDE.md",Jh="\u2014 run: infra-kit audit --fix",Wh={missing:`${wn} missing`,"no-block":`${wn} has no infra-kit block (expected ${Me} \u2026 ${Ke})`,malformed:`${wn} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${wn} carries the ROOT infra-kit block (${ve}); a package needs the package block`},Bh=e=>e.adopted?` (workspace adopted: ${_p.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Hi=(e,t)=>{let r=$t(It(_p.join(e,wn)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:qi,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${Wh[r.state]} ${Jh}`,o=r.state==="missing"?`${n}${Bh(t)}`:n;return t.adopted?{name:qi,status:"fail",message:o}:{name:qi,status:"pass",message:`not yet adopted \u2014 ${o}`}};var zi=async(e,t=ft)=>{try{let r=await mn(e,t);return{check:{name:Ue,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:Ue,status:"fail",message:r.message},rules:null}}};import Gh from"node:fs/promises";import Uh from"node:path";var qo="playwright.config.ts",Kh=[{name:"slow-mo",pattern:/process\.env\.E2E_SLOW_MO/u,expected:"const SLOW_MO = Number(process.env.E2E_SLOW_MO ?? 0)"},{name:"launch-options",pattern:/launchOptions:\s*\{[^}]*\bslowMo\b/u,expected:"use.launchOptions: { slowMo: SLOW_MO }"},{name:"timeout-headroom",pattern:/\btimeout:[^\n]*\bSLOW_MO\b/u,expected:"timeout: <base> + SLOW_MO * 100"},{name:"trace",pattern:/trace:\s*process\.env\.CI\s*\?\s*'on-first-retry'\s*:\s*'retain-on-failure'/u,expected:"use.trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure'"}],Mp=e=>Object.entries($i).map(([t,r])=>{let n=`e2e-script:${t}`,o=e[t];return typeof o!="string"||o.trim().length===0?{name:n,status:"fail",message:`missing "${t}" in package.json scripts \u2014 expected: ${r}`}:o.trim()!==r?{name:n,status:"fail",message:`"${t}" drifts from the shared e2e scripts \u2014 expected: ${r}`}:{name:n,status:"pass",message:"matches the shared e2e scripts"}}),jp=async e=>{let t=Uh.join(e,qo),r=await Gh.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${qo}`,status:"fail",message:`missing ${qo}`}]:Kh.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${qo} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},Yi=async(e,t)=>[...Mp(t),...await jp(e)];import qh from"node:fs/promises";import Hh from"node:path";var Xi=async(e,t)=>Promise.all(t.map(async r=>{let n=await qh.stat(Hh.join(e,r)).catch(()=>null);return n?n.isFile()?{name:`file:${r}`,status:"pass",message:"exists"}:{name:`file:${r}`,status:"fail",message:`not a file: ${r} (found a directory)`}:{name:`file:${r}`,status:"fail",message:`missing file: ${r}`}}));var Zi=(e,t)=>t.map(r=>{let n=e[r];return typeof n!="string"?{name:`script:${r}`,status:"fail",message:`missing "${r}" in package.json scripts`}:n.trim().length===0?{name:`script:${r}`,status:"fail",message:`"${r}" is empty in package.json scripts`}:{name:`script:${r}`,status:"pass",message:"defined"}});import zh from"node:fs/promises";import Yh from"node:path";var vr="turbo.json",Qi=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await zh.readFile(Yh.join(e,vr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:vr,status:"fail",message:`cannot read/parse ${vr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:vr,status:"fail",message:`no "tasks" object defined in ${vr}`}]:t.map(o=>{let s=o in n||`//#${o}`in n;return{name:`turbo:${o}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${o}" in ${vr}`}})};var Zh={adopted:!1,workspaceRoot:null},Qh=async(e,t,r)=>pn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Ct(e)}),ea=async(e,t=ft,r={})=>{let n=await un(e),o=n.name??Xh.basename(e),{check:s,rules:i}=await zi(e,t),a=[s];r.isRoot||a.push(Hi(e,r.adoption??Zh)),i&&(a.push(...Zi(n.scripts??{},i.requiredScripts)),a.push(...await Xi(e,i.requiredFiles)),a.push(...await Qi(e,i.turboTasks))),!r.isRoot&&await Qh(e,n,r.repoRoot)==="e2e"&&a.push(...await Yi(e,n.scripts??{}));let c=a.every(d=>d.status==="pass");return{packageDir:e,packageName:o,checks:a,passed:c}};var ta=["plugin","marketplace","add",dt],ra=["plugin","install",V,"--scope","project"],Fp=(e,t)=>Tt({projectPath:e,home:t}).kind==="installed",na=e=>((e??"").split(`
|
|
149
|
+
`).find(r=>r.trim().length>0)??"").trim(),ev=(e,t)=>{if(an(t))return null;l.debug({msg:`Running: ${Oo} ${ta.join(" ")}`});let r=e({args:ta});return r.ok?null:{step:"marketplace",error:na(r.output)}},tv=(e,t)=>{l.debug({msg:`Running: ${Oo} ${No.join(" ")}`});let r=e({args:No,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:na(r.output)}},oa=e=>{let{projectRoot:t,home:r}=e,n=e.run??Pi;if(!n({args:Ei}).ok)return{status:"claude-missing"};if(Fp(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:tv(n,t);let o=ev(n,r);if(o!==null)return{status:"failed",...o};l.debug({msg:`Running: ${Oo} ${ra.join(" ")}`});let s=n({args:ra,cwd:t});return s.ok?Fp(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:na(s.output)}};import rv from"node:fs";import nv from"node:path";var ye=".mcp.json",je="mcpServers",ov="infra-kit",sv=["mcp"],iv="/infra-kit/dist/mcp.js",sa=" ",Ot=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Lp=e=>{if(!Ot(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===ov&&r[0]===sv[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(iv)):!1},Vp=e=>/\n([ \t]+)"/.exec(e)?.[1]??sa,ia=e=>{try{return{kind:"raw",raw:rv.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},aa=e=>{try{return JSON.parse(e)}catch{return}},ca=e=>e instanceof Error?e.message:String(e),kn=e=>{let t=ia(nv.join(e,ye));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=aa(t.raw);if(!Ot(r)||!Ot(r[je]))return{kind:"unparseable"};let n=r[je];if(X in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Lp(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ho from"node:fs";import av from"node:path";var qe=`claude plugin install ${V} --scope project`,yr=`claude plugin update ${V} --scope project`,la=`claude plugin marketplace add ${dt}`,Wp=" ",Bp=()=>({source:{source:"github",repo:dt}}),cv=()=>({extraKnownMarketplaces:{[X]:Bp()},enabledPlugins:{[V]:!0}}),Gp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lv=e=>/\n([ \t]+)"/.exec(e)?.[1]??Wp,Jp=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Gp(o)||r in o?null:(o[r]=n,`${t}.${r}`)},dv=e=>[Jp(e,"extraKnownMarketplaces",X,Bp()),Jp(e,"enabledPlugins",V,!0)].filter(r=>r!==null),pv=e=>{try{return Ho.readFileSync(e,"utf-8")}catch{return null}},uv=e=>(Ho.mkdirSync(av.dirname(e),{recursive:!0}),Ho.writeFileSync(e,`${JSON.stringify(cv(),null,Wp)}
|
|
150
|
+
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${X}`,`enabledPlugins.${V}`]}),da=e=>{let t=pv(e);if(t===null)return uv(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!Gp(r))return l.warn(`Could not parse ${e} \u2014 left it untouched. Add "${V}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=dv(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=lv(t),s=t.endsWith(`
|
|
173
151
|
`)?`
|
|
174
|
-
`:"";return
|
|
152
|
+
`:"";return Ho.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};var k=e=>[{type:"text",text:e}],b=e=>e;import mv from"node:path";import fv from"node:process";var gv=["unchanged","created"],hv=["unchanged","created","updated","removed","failed"],Up=async(e,t,r)=>{let n=await Ct(e);return yn(e,{repoRoot:t,version:G.version,design:r,declaredType:n})},vv=async(e,t)=>{if(e.root)return vn(t,{version:G.version});if(e.all){let n=[];for(let o of await le(t))n.push(...await Up(o,t,e.design));return n}let r=await gn(e.cwd??fv.cwd());return Up(r,t,e.design)},yv=e=>{let t=new Map;for(let n of e)t.set(n.action,(t.get(n.action)??0)+1);return`Agent guidance synced \u2014 ${hv.filter(n=>gv.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${G.version})`},wv=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=mv.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";l.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}l.info(yv(e))},kv=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Kp=async(e,t)=>{let r=await R();Wo();let n=await mr(t),o=await vv(e,r);wv(o,r),Wo();let s=await mr(t),i=!e.all&&!e.root;return{fixed:o.map(kv),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Hp from"node:fs";import zp from"node:path";var pa="ik-mcp",qp=(e,t)=>{let r=["--name",e];for(let n of t.env)r.push("--env",n);for(let n of t.unset)r.push("--unset",n);return r.push("--",t.command,...t.args),{type:"stdio",command:pa,args:r}};var zo="run `infra-kit setup` (or `infra-kit audit --root --fix`)",bv=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),ua=e=>Ot(e)&&e.command===pa,Rv=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),Ev=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=qp(i,a),d=e[i];if(d!==void 0&&!ua(d)){n.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 ${zo}, or drop mcp.${i} from infra-kit.json`});continue}if(ua(d)&&d.type===c.type&&bv(d.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=Rv(d,c),s=!0,n.push({name:i,status:"written",message:""});continue}n.push({name:i,status:"drifted",message:d===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: ${zo}`:`"${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: ${zo}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!ua(a)||n.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:n,servers:o,changed:s}},Pv=(e,t,r)=>{let n=r===null?sa:Vp(r),o=r===null||r.endsWith(`
|
|
175
153
|
`)?`
|
|
176
|
-
`:"";try{return Dp.mkdirSync(Op.dirname(e),{recursive:!0}),Dp.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return l.warn(`Could not write ${e} (${Qi(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Ko=({projectRoot:e,proxies:t,write:r})=>{let n=Op.join(e,z),o=Xi(n);if(o.kind==="unreadable")return l.warn(`Could not read ${n} (${Qi(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Zi(s);if(!Ct(i))return l.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Uo}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Se];if(a!==void 0&&!Ct(a))return l.warn(`${n} has a "${Se}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Qh(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let d=ev(n,{...i,[Se]:c.servers},s);return{status:d?"ok":"failed",path:n,entries:c.entries,wrote:d}};var Np=async(e,t)=>{let r;try{r=(await $()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Ko({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:o.length===0}};var tv=(e,t)=>[...t.map(r=>({name:`devServersPresets:config:${r.app}`,status:"fail",message:`could not load apps/${r.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${r.message}`})),...e.map(r=>({name:`devServersPresets:${r.preset}`,status:"fail",message:r.message}))],_p=async e=>{let t=(await $()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Jd(t);if(r.length>0){let p=r.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:p,passed:!1}}let n=Fd(e),o=Ld(e),s={api:n.map(p=>p.name),ui:o.map(p=>p.name)},{ctx:i,loadErrors:a}=await Bd(e,t,s,n),c=tv(Vd(t,i),a),d=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:d,passed:c.length===0}};var rv="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",nv=async e=>e.root?[{dir:await R(),baseline:Ei,isRoot:!0}]:e.all?(await de(await R())).map(r=>({dir:r})):[{dir:await mn(e.cwd??Mp.cwd())}],ov=async e=>e.root||e.all?await R():e.cwd??Mp.cwd(),sv=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,l.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return l.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},iv=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await $p(e,t);return n&&l.info(rv),r},av=e=>{if(At(e).kind!=="stale")return null;let t=`${z} still registers "${G}" \u2014 delete this key: the plugin no longer serves an MCP server and the entry spawns a retired subcommand that exits immediately (Claude Code lists it as failed). Delete the "${G}" entry by hand in a PR, keeping its siblings`;return l.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},qo=async(e={})=>{let t=$i(await ov(e)),r=e.fix?await iv(e,t):void 0,n=await nv(e),o=await ur(t),s=[];for(let c of n)s.push(await Ui(c.dir,c.baseline,{adoption:o,isRoot:c.isRoot}));if(e.root){let c=await _p(n[0].dir);c&&s.push(c);let d=await Np(n[0].dir,e.fix===!0);d&&s.push(d);let p=av(n[0].dir);p&&s.push(p)}let a={allPassed:sv(s),packages:s.map(c=>({name:c.packageName,passed:c.passed,checks:c.checks}))};return r&&(a.fixed=r),{content:k(JSON.stringify(a,null,2)),structuredContent:a}},cv={all:we.boolean().optional().describe("Audit every non-vendor workspace package"),root:we.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},lv={allPassed:we.boolean().describe("Whether every audited package passed all checks"),packages:we.array(we.object({name:we.string(),passed:we.boolean(),checks:we.array(we.object({name:we.string(),status:we.enum(["pass","fail"]),message:we.string()}))})).describe("Per-package check results")},oa=b({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:cv,outputSchema:lv,handler:e=>qo({all:e.all,root:e.root})});import{z as yn}from"zod";var Ho=async()=>{let[e,t]=await Promise.all([$(),q()]),r=Object.keys(e).sort();l.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),l.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},dv={config:yn.record(yn.string(),yn.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, dev, devServersPresets, and protectedEnvs."),configPath:yn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:yn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},sa=b({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:dv,handler:()=>Ho()});import hv from"node:fs";import{z as ee}from"zod";import wn from"node:fs";import wr from"node:path";import pv from"node:process";var uv=wr.join(".infra-kit","dev-context"),mv=".infra-kit",jp=(e,t)=>{let r=wr.resolve(e);for(;;){let n=wr.join(r,t);if(wn.existsSync(n))return n;let o=wr.dirname(r);if(o===r)return;r=o}},fv=e=>{let t=jp(e,uv);if(t)return t;let r=jp(e,mv);return r?wr.join(r,"dev-context"):void 0},ia=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Yo=e=>typeof e=="string"?e:"",gv=(e,t,r)=>{let n=wr.join(e,t);try{let o=wn.statSync(n),s=JSON.parse(wn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Yo(i.package),port:ia(i.port),alias:Yo(i.alias),origin:Yo(i.origin),release:Yo(i.release),pid:ia(i.pid),writtenAt:ia(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},aa=(e=pv.cwd())=>{let t=Date.now(),r=fv(e);if(!r||!wn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=wn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>gv(r,s,t)).filter(s=>s!==null).sort((s,i)=>s.app.localeCompare(i.app));return{session:o.length>0?"active":"none",fragmentDir:r,readAt:t,apps:o}};var zo=async(e={})=>{let t=e.now??Date.now,r=e.isListening??tn,n=aa(e.cwd),o=t(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),h=await r(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:h}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(hv.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),d=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){l.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${d}:`);for(let u of s){let m=u.live?"live":"NOT responding",h=`written ${u.ageSeconds}s ago`;l.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${h}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";l.info(`No active infra-kit dev session \u2014 searched ${d} (${u}).`)}let p={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},vv={active:ee.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:ee.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:ee.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:ee.array(ee.object({app:ee.string().describe("App folder name (the fragment filename without .json)."),package:ee.string().describe("The app package name the vite helper reads to decide a local route."),port:ee.number().describe("The actual bound port the dev server is listening on."),pid:ee.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ee.string().describe("Registered portless hostname for the app."),origin:ee.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ee.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ee.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:ee.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ee.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ee.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.")},ca=b({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:vv,handler:()=>zo()});import{spawnSync as Ku}from"node:child_process";import H from"node:fs";import qu from"node:os";import re from"node:path";import Le from"node:process";import{z as oe}from"zod";import{execFileSync as yv}from"node:child_process";var Fp=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},wv=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],kv=e=>wv.some(t=>t.test(e)),bv="/bin/ps",Rv=()=>yv(bv,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
177
|
-
`),
|
|
154
|
+
`:"";try{return Hp.mkdirSync(zp.dirname(e),{recursive:!0}),Hp.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return l.warn(`Could not write ${e} (${ca(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Yo=({projectRoot:e,proxies:t,write:r})=>{let n=zp.join(e,ye),o=ia(n);if(o.kind==="unreadable")return l.warn(`Could not read ${n} (${ca(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:aa(s);if(!Ot(i))return l.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${zo}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[je];if(a!==void 0&&!Ot(a))return l.warn(`${n} has a "${je}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=Ev(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let d=Pv(n,{...i,[je]:c.servers},s);return{status:d?"ok":"failed",path:n,entries:c.entries,wrote:d}};var Yp=async(e,t)=>{let r;try{r=(await $()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Yo({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(i=>i.status!=="unchanged"&&i.status!=="written"),s=o.length===0?[{name:"mcp:.mcp.json",status:"pass",message:"every mcp.<name> has a matching ik-mcp entry in .mcp.json"}]:o.map(i=>({name:`mcp:${i.name}`,status:"fail",message:i.message}));return{packageDir:e,packageName:"mcp",checks:s,passed:o.length===0}};var Sv=(e,t)=>[...t.map(r=>({name:`devServersPresets:config:${r.app}`,status:"fail",message:`could not load apps/${r.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${r.message}`})),...e.map(r=>({name:`devServersPresets:${r.preset}`,status:"fail",message:r.message}))],Xp=async e=>{let t=(await $()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Qd(t);if(r.length>0){let p=r.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:p,passed:!1}}let n=Xd(e),o=Zd(e),s={api:n.map(p=>p.name),ui:o.map(p=>p.name)},{ctx:i,loadErrors:a}=await tp(e,t,s,n),c=Sv(ep(t,i),a),d=c.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:c;return{packageDir:e,packageName:"devServersPresets",checks:d,passed:c.length===0}};var xv="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Tv=async e=>e.root?[{dir:await R(),baseline:Ii,isRoot:!0}]:e.all?(await le(await R())).map(r=>({dir:r})):[{dir:await gn(e.cwd??Zp.cwd())}],Cv=async e=>e.root||e.all?await R():e.cwd??Zp.cwd(),Av=async()=>{try{return await R()}catch{return}},$v=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,l.info(`[FAIL] ${i.packageName} ${a.name}: ${a.message}`));let n=e.every(i=>i.passed),o=(i,a)=>`${i} ${a}${i===1?"":"s"}`,s=`${o(t,"check")}, ${o(e.length,"target")}`;return l.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},Iv=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Kp(e,t);return n&&l.info(xv),r},Dv=e=>{if(kn(e).kind!=="stale")return null;let t=`${ye} still registers "${X}" \u2014 delete this key: the plugin no longer serves an MCP server and the entry spawns a retired subcommand that exits immediately (Claude Code lists it as failed). Delete the "${X}" entry by hand in a PR, keeping its siblings`;return l.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},Xo=async(e={})=>{let t=ji(await Cv(e)),r=e.fix?await Iv(e,t):void 0,n=await Tv(e),o=await mr(t),s=await Av(),i=[];for(let d of n)i.push(await ea(d.dir,d.baseline,{adoption:o,isRoot:d.isRoot,repoRoot:s}));if(e.root){let d=await Xp(n[0].dir);d&&i.push(d);let p=await Yp(n[0].dir,e.fix===!0);p&&i.push(p);let u=Dv(n[0].dir);u&&i.push(u)}let c={allPassed:$v(i),packages:i.map(d=>({name:d.packageName,passed:d.passed,checks:d.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Ov={all:we.boolean().optional().describe("Audit every non-vendor workspace package"),root:we.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Nv={allPassed:we.boolean().describe("Whether every audited package passed all checks"),packages:we.array(we.object({name:we.string(),passed:we.boolean(),checks:we.array(we.object({name:we.string(),status:we.enum(["pass","fail"]),message:we.string()}))})).describe("Per-package check results")},ma=b({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:Ov,outputSchema:Nv,handler:e=>Xo({all:e.all,root:e.root})});import{z as bn}from"zod";var Zo=async()=>{let[e,t]=await Promise.all([$(),K()]),r=Object.keys(e).sort();l.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),l.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},_v={config:bn.record(bn.string(),bn.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, dev, devServersPresets, and protectedEnvs."),configPath:bn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:bn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},fa=b({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:_v,handler:()=>Zo()});import Jv from"node:fs";import{z as Q}from"zod";import Rn from"node:fs";import wr from"node:path";import Mv from"node:process";var jv=wr.join(".infra-kit","dev-context"),Fv=".infra-kit",Qp=(e,t)=>{let r=wr.resolve(e);for(;;){let n=wr.join(r,t);if(Rn.existsSync(n))return n;let o=wr.dirname(r);if(o===r)return;r=o}},Lv=e=>{let t=Qp(e,jv);if(t)return t;let r=Qp(e,Fv);return r?wr.join(r,"dev-context"):void 0},ga=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Qo=e=>typeof e=="string"?e:"",Vv=(e,t,r)=>{let n=wr.join(e,t);try{let o=Rn.statSync(n),s=JSON.parse(Rn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Qo(i.package),port:ga(i.port),alias:Qo(i.alias),origin:Qo(i.origin),release:Qo(i.release),pid:ga(i.pid),writtenAt:ga(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},ha=(e=Mv.cwd())=>{let t=Date.now(),r=Lv(e);if(!r||!Rn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Rn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>Vv(r,s,t)).filter(s=>s!==null).sort((s,i)=>s.app.localeCompare(i.app));return{session:o.length>0?"active":"none",fragmentDir:r,readAt:t,apps:o}};var es=async(e={})=>{let t=e.now??Date.now,r=e.isListening??nn,n=ha(e.cwd),o=t(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),h=await r(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:h}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(Jv.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),d=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){l.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${d}:`);for(let u of s){let m=u.live?"live":"NOT responding",h=`written ${u.ageSeconds}s ago`;l.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${h}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";l.info(`No active infra-kit dev session \u2014 searched ${d} (${u}).`)}let p={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},Wv={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.")},va=b({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:Wv,handler:()=>es()});import{spawnSync as am}from"node:child_process";import q from"node:fs";import cm from"node:os";import te from"node:path";import Ve from"node:process";import{z as ne}from"zod";import{execFileSync as Bv}from"node:child_process";var eu=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},Gv=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],Uv=e=>Gv.some(t=>t.test(e)),Kv="/bin/ps",qv=()=>Bv(Kv,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
155
|
+
`),tu=(e=qv)=>{try{return e().some(Uv)}catch{return!0}};import{Chalk as Hv}from"chalk";import ya from"node:process";var zv="Tools & CLIs",Yv="Shell & integration",Xv="Project config",Zv="Doppler env tokens",Qv="Dev proxy (portless)",ey="Claude Code plugin",ty=`portless serving TLS on :${pt}`,wa=[[zv,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Yv,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[Xv,["infra-kit config valid","user override path","legacy user-global config"]],[Zv,["tokens.json present","env tokens configured","tokens.json perms"]],[Qv,["portless installed","portless node","portless service target",ty,"portless CA chain valid","portless CA trusted","portless routes"]],[ey,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","Agent mode","Agent allowlist"]]],ru="Other",ry=wa.map(([e])=>e),ny=new Map(wa.flatMap(([e,t])=>t.map(r=>[r,e]))),II=wa.flatMap(([,e])=>e),ka=new Set(["portless routes","tokens.json perms"]),oy=e=>{let t=new Map;for(let n of e){let o=ny.get(n.name)??ru,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...ry,ru].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})},nu={unicode:{pass:"\u2713",fail:"\u2717",warn:"!",separator:"\xB7",rule:"\u2500"},ascii:{pass:"ok",fail:"!!",warn:"!?",separator:"-",rule:"-"}},sy=24,iy=(e,t)=>{let r=e.split(/\s+/).filter(s=>s.length>0),n=[],o="";for(let s of r)o.length===0?o=s:`${o} ${s}`.length<=t?o=`${o} ${s}`:(n.push(o),o=s);return o.length>0&&n.push(o),n.length>0?n:[""]},su=e=>{let t=r=>e.filter(n=>n.status===r).length;return{passed:t("pass"),failed:t("fail"),warned:t("warn")}},ay=e=>{let t=new Hv({level:e?1:0});return{header:r=>t.bold.cyan(r),pass:r=>t.green(r),fail:r=>t.red(r),warn:r=>t.yellow(r),dim:r=>t.dim(r),bold:r=>t.bold(r)}},cy=(e,t,r,n)=>{if(e.failed===0&&e.warned===0){let c=`${t}/${t} ok`;return{text:r.pass(c),plainWidth:c.length}}let o=`${e.passed}/${t}`,s=[...e.failed===0?[]:[{plain:`${e.failed} failed`,paint:r.fail}],...e.warned===0?[]:[{plain:`${e.warned} warning${e.warned===1?"":"s"}`,paint:r.warn}]],i=[r.dim(o),...s.map(c=>c.paint(c.plain))].join(` ${n.separator} `),a=s.reduce((c,d)=>c+d.plain.length+3,o.length);return{text:i,plainWidth:a}},kr=" ",ou=" ",ly=(e,t,r,n)=>{let o=su(e.checks),s=cy(o,e.checks.length,t,r),i=Math.max(1,n-kr.length-e.label.length-s.plainWidth);return`${kr}${t.header(e.label)}${" ".repeat(i)}${s.text}`},dy=(e,t,r,n,o)=>{let s=e.status!=="pass",i=n.pass.length,a=n[e.status],c=e.name.padEnd(t),d=r[e.status],p=d(a),u=s?d(c):c,m=ou.length+i+1+t+2,h=Math.max(sy,o-m),[y,...v]=iy(e.message,h),I=F=>s?F:r.dim(F);return[`${ou}${p} ${u} ${I(y??"")}`.trimEnd(),...v.map(F=>`${" ".repeat(m)}${I(F)}`)]},py=(e,t,r,n)=>{let o=su(e),s=r.rule.repeat(Math.max(12,Math.min(n-kr.length,56))),i=e.filter(p=>p.status==="fail"&&ka.has(p.name)).length,a=[t.pass(`${o.passed} passed`),...o.failed===0?[]:[t.fail(`${o.failed} failed`)],...o.warned===0?[]:[t.warn(`${o.warned} warned`)]].join(` ${r.separator} `),c=t.dim(`${i} fixable \u2014 run \`infra-kit doctor --fix\``),d=i>0?` ${c}`:"";return[`${kr}${t.dim(s)}`,`${kr}${a}${d}`]},uy=(e,t={})=>{let r=t.color??!1,n=t.unicode??!0,o=t.width??80,s=ay(r),i=n?nu.unicode:nu.ascii;if(e.length===0)return[s.bold("infra-kit doctor"),"",`${kr}${s.dim("No checks ran.")}`];let a=Math.max(...e.map(d=>d.name.length)),c=oy(e).flatMap(d=>[ly(d,s,i,o),...d.checks.flatMap(p=>dy(p,a,s,i,o)),""]);return[s.bold("infra-kit doctor"),"",...c,...py(e,s,i,o)]},my=new Set(["","0","false","none"]),fy=["LC_ALL","LC_CTYPE","LANG"],gy=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!my.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,hy=(e,t)=>{if(t)return!1;let r=fy.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},vy=(e={})=>{let t=e.env??ya.env,r=e.stream??ya.stderr;return{color:gy(t,r),unicode:hy(t,e.ascii??!1),width:r.columns??80}},ba=(e,t={})=>{(t.write??(n=>{ya.stderr.write(n)}))(`${uy(e,vy(t)).join(`
|
|
178
156
|
`)}
|
|
179
|
-
`)};var
|
|
180
|
-
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:
|
|
157
|
+
`)};var yy=e=>e.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"),wy=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>yy(t[1])),ky=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:wy(t[1])},by=e=>{let t=[],r="",n=!1,o=!1,s=!1,i=[...e];for(let[a,c]of i.entries()){if(s){s=!1;continue}if(c==='"'){n=!n,o=!0;continue}let d=i[a+1];if(c==="\\"&&(d==='"'||d==="\\")){r+=d,o=!0,s=!0;continue}if(/\s/.test(c)&&!n){o&&(t.push(r),r="",o=!1);continue}r+=c,o=!0}return o&&t.push(r),t},Ry=e=>{let t=e.split(`
|
|
158
|
+
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:by(t.slice(10))},iu=(e,t)=>{try{return e==="darwin"?ky(t):e==="linux"?Ry(t):null}catch{return null}};import Ey from"node:fs";import Py from"node:os";import Sy from"node:path";var xy="infra-kit.json",Ty="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)",Cy="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",En=async()=>{let e;try{e=await R()}catch{return null}let t=e.trim();return t===""||t===Py.homedir()?null:t},au=async()=>{let e=await En();return e===null&&l.info(Ty),e},Ay=async()=>{let e=await En();return e===null?null:Ey.existsSync(Sy.join(e,xy))?e:(l.info(Cy),null)};var $y=async e=>{try{return await le(e)}catch(t){return l.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},cu=async()=>{let e=await Ay(),t=G.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await vn(e,{version:t})];for(let n of await $y(e)){let o=await Ct(n);r.push(...await yn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import ae from"node:fs";import $a from"node:os";import de from"node:path";import Ia from"node:process";import rs from"node:fs/promises";import Iy from"node:path";import Dy from"node:process";var lu=` // "envManagement": { // required in layer 1; provider-tagged
|
|
181
159
|
// "provider": "doppler",
|
|
182
160
|
// "config": { "name": "my-doppler-project" }
|
|
183
161
|
// },
|
|
@@ -272,7 +250,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
272
250
|
// // also fixes its modes), or by hand: both are supported, which is why the store carries no
|
|
273
251
|
// // repo-identity field and no mandatory version. Pasting a token into an
|
|
274
252
|
// // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
|
|
275
|
-
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,
|
|
253
|
+
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,Ra=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
|
|
276
254
|
//
|
|
277
255
|
// Merge chain (later layers override earlier ones at top-level keys):
|
|
278
256
|
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
@@ -293,9 +271,9 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
293
271
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
294
272
|
// user-global layer \u2014 it is shown here only to document the full, valid config shape.
|
|
295
273
|
{
|
|
296
|
-
${
|
|
274
|
+
${lu}
|
|
297
275
|
}
|
|
298
|
-
`,
|
|
276
|
+
`,Ea=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
299
277
|
//
|
|
300
278
|
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
|
|
301
279
|
// <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
|
|
@@ -312,9 +290,9 @@ ${qp}
|
|
|
312
290
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
313
291
|
// override layer \u2014 it is shown here only to document the full, valid config shape.
|
|
314
292
|
{
|
|
315
|
-
${
|
|
293
|
+
${lu}
|
|
316
294
|
}
|
|
317
|
-
`,
|
|
295
|
+
`,Pa=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
|
|
318
296
|
//
|
|
319
297
|
// Machine-local registry the vendor commands (sync/manifest/diff) read to know
|
|
320
298
|
// where your project repos live and which ones to stamp. This .example.jsonc is
|
|
@@ -325,103 +303,103 @@ ${qp}
|
|
|
325
303
|
// "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
|
|
326
304
|
// "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
|
|
327
305
|
}
|
|
328
|
-
`;var
|
|
329
|
-
`,"utf-8");let o=
|
|
306
|
+
`;var du=!1,Oy=e=>e.replace(/\.json$/,".example.jsonc"),Ny=async e=>{try{return await rs.readFile(e,"utf-8")}catch{return null}},br=async e=>{let t=e.userProject,r=Oy(t);await rs.mkdir(Iy.dirname(t),{recursive:!0});let n=!await U(t);n&&await rs.writeFile(t,`{}
|
|
307
|
+
`,"utf-8");let o=Ea(e.projectName),s=await Ny(r)!==o;return s&&await rs.writeFile(r,o,"utf-8"),n&&Yd(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Rr=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,Sa=async()=>{if(Dy.env.INFRA_KIT_NO_SEED||du)return;du=!0;let e;try{e=await K()}catch{return}if(await U(e.main))try{let t=await br(e);t.createdConfig?l.info(Rr(t)):t.refreshedExample&&l.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){l.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as _y}from"node:child_process";import uu from"node:fs";import Er from"node:process";import{fileURLToPath as mu}from"node:url";var pu=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],xa=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return pu.some(c=>{let d=r[c];return d!=null&&d!==""})?"opt-out":t.includes("--json")?"json":n?ud(o,s,i)?"local-install":null:"not-a-tty"};var My=e=>{_y(Er.execPath,[e,"--parent-pid",String(Er.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},jy=()=>mu(new URL("./update-check.js",import.meta.url)),Fy=()=>uu.realpathSync(mu(new URL("./cli.js",import.meta.url))),Ly=/^[\w@./+ -]+$/i,Vy=e=>Ly.test(e),Jy=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||cn(e.latestVersion,t)&&e.updateCommand.every(Vy)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Po(e.updateCommand)}`)},Ta=(e,t={})=>{try{let r=t.argv??Er.argv,n=t.env??Er.env,o=t.isTty??!!Er.stdout.isTTY,s=t.cwd??Er.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??Fy(),c=t.readCache??ln,d=t.spawnChild??My,p=t.fileExists??(y=>uu.existsSync(y)),u=t.notify??(y=>{l.info(y)});if(xa({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:se})!==null)return;let m=c();if(Jy(m,e,u),!Ti(m,i))return;let h=t.childPath??jy();if(!p(h))return;d(h)}catch{}};import Le from"node:fs/promises";import Fe from"node:path";import{pathToFileURL as Gy}from"node:url";import Uy from"yaml";import{z as yu}from"zod";import Wy from"node:fs/promises";import Ca from"node:os";import Aa from"node:path";import{z as By}from"zod";import{z as ns}from"zod";var fu="vendor.json",os=ns.object({workspaceDir:ns.string().min(1),targets:ns.array(ns.string()).min(1)}).strict();var Pr=()=>Aa.join(Ca.homedir(),id,fu),gu=e=>{if(e==="~")return Ca.homedir();if(e.startsWith("~/"))return Aa.join(Ca.homedir(),e.slice(2));if(Aa.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},hu=async()=>{let e=Pr(),t;try{t=await Wy.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:
|
|
330
308
|
|
|
331
309
|
{
|
|
332
310
|
"workspaceDir": "~/projects",
|
|
333
311
|
"targets": ["my-repo"]
|
|
334
312
|
}
|
|
335
|
-
`)}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in vendor.json at ${e}: ${o.message}`)}let n=
|
|
336
|
-
`,"utf-8"),await
|
|
337
|
-
`,"utf-8"),await
|
|
338
|
-
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},
|
|
339
|
-
`)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:
|
|
340
|
-
`),s=0;for(;s<o.length&&
|
|
313
|
+
`)}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in vendor.json at ${e}: ${o.message}`)}let n=os.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${By.prettifyError(n.error)}`);return n.data};var vu=e=>e.replace(/\.json$/,".yml"),wu=async()=>{let e;try{e=await K()}catch{return}let t=[{label:"infra-kit.json",yml:vu(e.main),json:e.main,schema:qd},{label:"~/.infra-kit/infra-kit.json",yml:Fe.join(Fe.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:xi},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:vu(e.userProject),json:e.userProject,schema:xi}],r=0;for(let n of t){let[o,s]=await Promise.all([U(n.yml),U(n.json)]);if(o){if(s){l.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${w(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await Le.readFile(n.yml,"utf-8"),a=Uy.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){l.info(`\u26A0 Skipped ${w(n.yml)} \u2014 invalid config: ${yu.prettifyError(c.error)}`);continue}await Le.mkdir(Fe.dirname(n.json),{recursive:!0}),await Le.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
|
|
314
|
+
`,"utf-8"),await Le.rm(n.yml,{force:!0}),l.info(`\u2713 Migrated ${w(n.yml)} \u2192 ${w(n.json)}`),r++}catch(i){l.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${i.message}`)}}}r>0&&mt()},ku=async()=>{let e;try{e=await K()}catch{return}let t=Fe.dirname(e.userGlobal),r=[{from:Fe.join(t,"config.json"),to:e.userGlobal},{from:Fe.join(t,"config.example.jsonc"),to:Fe.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([U(o),U(s)]);if(i){if(a){l.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await Le.mkdir(Fe.dirname(s),{recursive:!0}),await Le.rename(o,s),l.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){l.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&mt()},bu=async()=>{let e=Pr(),t=Fe.dirname(e),r=Fe.join(t,"vendor.config.ts"),[n,o]=await Promise.all([U(r),U(e)]);if(n){if(o){l.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await Le.stat(r),c=(await import(`${Gy(r).href}?mtime=${Number(s.mtimeMs)}`)).default,d=typeof c=="function",p=d?await c():c,u=os.safeParse(p);if(!u.success){l.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${yu.prettifyError(u.error)}`);return}await Le.mkdir(t,{recursive:!0}),await Le.writeFile(e,`${JSON.stringify(u.data,null,2)}
|
|
315
|
+
`,"utf-8"),await Le.rm(r,{force:!0}),d?l.info(`\u26A0 Migrated ${w(r)} \u2192 ${w(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 ${w(e)} directly to change them.`):l.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){l.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},Ru=async()=>{let e=await Ky(),t=0;for(let r of e)if(await U(r))try{let n=await Ud(r);if(!n.changed)continue;l.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof Gd?"changed while migrating":n.message;l.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&mt()},Ky=async()=>{try{let e=await K();return[e.main,e.userGlobal,e.userProject]}catch{return[zd()]}};var Nt="# -- infra-kit:begin --",vt="# -- infra-kit:end --",qy=[["# region infra-kit","# endregion infra-kit"]],Hy="# infra-kit shell functions",Sr=class extends Error{constructor(r,n){super(n instanceof Error?n.message:String(n),{cause:n});this.step=r;this.reason=n;this.name="InitStepError"}step;reason},Pn="Run `source ~/.zshrc` or open a new terminal to activate.",zy={step:"migrations",outcome:"skipped",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},He=async(e,t)=>{try{return await t()}catch(r){throw new Sr(e,r)}},Da=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await He("zshrc",()=>{r(Yy())}),await He("zshenv",()=>{r(Xy())}),await He("migrations",async()=>{await Qy(),Zy(),r(zy)}),await He("user-config",()=>{r(tw())});let n=await He("guidance",async()=>{let{entries:s,root:i}=await ow();return r(...s),i}),o=await He("plugin-pointer",async()=>au());return r(...aw(o,n)),await He("plugin-pointer",async()=>{await uw(o,r)}),await He("mcp-proxies",async()=>{r(...await fw(o))}),await He("project-config",async()=>{r(...await rw())}),r(...ew()),t},is=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)}},Yy=()=>{let e=de.join($a.homedir(),".zshrc"),t=ae.existsSync(e)?hw(ae.readFileSync(e,"utf-8")):"",r=pr({content:t,body:Pu(),startMarker:Nt,endMarker:vt,placement:"append-end"});return ae.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},Xy=()=>{let e=de.join($a.homedir(),".zshenv"),t=ae.existsSync(e)?ae.readFileSync(e,"utf-8"):"",r=pr({content:t,body:Oa(),startMarker:Nt,endMarker:vt});return ae.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},Zy=()=>{ae.rmSync(de.join(ld(),"projects"),{recursive:!0,force:!0})},Qy=async()=>{await wu(),await ku(),await Ru(),await bu()},ew=()=>{let e=Ia.env.SHELL??"",t=[];return e.includes("zsh")||t.push({step:"shell",outcome:"warned",message:`Your login shell ($SHELL=${e||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear) is zsh-only and won't activate in bash/fish.`,level:"warn"}),t.push({step:"shell",outcome:"unchanged",message:Pn,level:"info"}),t},tw=()=>{let e=de.join($a.homedir(),".infra-kit"),t=de.join(e,"infra-kit.json");return ae.mkdirSync(e,{recursive:!0}),ae.writeFileSync(de.join(e,"infra-kit.example.jsonc"),Ra(),"utf-8"),ae.writeFileSync(de.join(e,"vendor.example.jsonc"),Pa(),"utf-8"),ae.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ae.writeFileSync(t,`{}
|
|
316
|
+
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},rw=async()=>{if(Ia.env.INFRA_KIT_NO_SEED)return[ss("INFRA_KIT_NO_SEED is set")];try{let e=await K();if(!ae.existsSync(e.main))return[ss(`no project config at ${e.main}`)];let t=await br(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:Rr(t),level:"info"}]:[ss("the user-project config was already present")]}catch(e){return l.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[ss(e instanceof Error?e.message:String(e))]}},ss=e=>({step:"project-config",outcome:"skipped",message:`Skipped seeding the user-project config \u2014 ${e}`,level:"silent"}),nw=(e,t,r)=>{let n=[];for(let s of r){if(s.action==="unchanged")continue;let i=s.type===void 0?"":` (${s.type})`;n.push({step:"guidance",outcome:s.action==="failed"?"warned":"written",message:` ${s.action.padEnd(9)} ${de.relative(e,s.path)}${i}`,level:"info"})}n.push({step:"guidance",outcome:"written",message:`Agent-instruction files synced (infra-kit ${t})`,level:"info"});let o=r.filter(s=>s.action==="failed");return o.length===0||n.push({step:"guidance",outcome:"warned",message:`${o.length} package guidance files could not be written \u2014 run: infra-kit audit --fix --all`,level:"warn"}),n},ow=async()=>{let{skipped:e,root:t,version:r,written:n}=await cu();return e||t===null?{root:null,entries:[{step:"guidance",outcome:"skipped",message:"Agent-instruction files skipped \u2014 not an infra-kit repo",level:"silent"}]}:{root:t,entries:nw(t,r,n)}},sw=(e,t)=>{let r=de.relative(e,t.path);return t.status==="created"?{step:"plugin-pointer",outcome:"written",message:` created ${r} (Claude Code plugin pointer)`,level:"info"}:t.status==="added"?{step:"plugin-pointer",outcome:"written",message:` updated ${r} \u2014 added ${t.added.join(", ")}`,level:"info"}:{step:"plugin-pointer",outcome:t.status==="unchanged"?"unchanged":"warned",message:`${r} \u2014 ${t.status}`,level:"silent"}},iw=(e,t)=>{let r=ye;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?X:t.key;return{step:"mcp-server",outcome:"unchanged",message:` ${r} still registers the infra-kit MCP server under "${o}" \u2014 the plugin no longer serves one, so this entry only spawns a failed server row. Delete the "${o}" entry from ${r} by hand in a PR, keeping its siblings`,level:"info"}}return t.kind==="unparseable"?{step:"mcp-server",outcome:"warned",message:`Could not read ${je} from ${de.join(e,ye)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: none wanted \u2014 the plugin is skills-only (${t.kind==="absent"?`${r} carries no "${X}" key`:`no ${r}`})`,level:"info"}},aw=(e,t)=>e===null||t!==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 ${V} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],cw=()=>[la,qe].map(e=>({step:"plugin-pointer",outcome:"skipped",message:e,level:"info"})),lw=e=>({step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${G.version} is behind ${e.latestVersion}, update it first: ${Po(e.updateCommand)}`:`CLI ${G.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"}),dw=(e,t)=>e.status==="skipped-cli-stale"?[lw(t)]:e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${V} 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: ${yr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${V} (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"},...cw()]:[{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: ${qe}`,level:"warn"}],Eu={stale:!1},pw=async()=>{let e=ln(),t=e===null?await Ci(Ia.env):e.latestVersion;return t===null||!Ai(t,G.version)?Eu:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??pd(t)}},uw=async(e,t)=>{if(e===null){t({step:"plugin-pointer",outcome:"skipped",message:"Claude Code plugin steps skipped \u2014 no git root safe to write into",level:"silent"});return}try{t(sw(e,da(de.join(e,".claude","settings.json"))));let n=Tt({projectPath:e}).kind==="installed"?await pw():Eu;t(...dw(oa({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(iw(e,kn(e)))}catch(r){let n=r instanceof Error?r.message:String(r);t({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${qe}`,level:"warn"})}},mw=(e,t)=>{let r=de.relative(e,t.path);if(t.status!=="ok"&&t.status!=="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${r} could not be read as JSON \u2014 ik-mcp entries not synced`,level:"warn"}];if(t.status==="failed")return[{step:"mcp-proxies",outcome:"warned",message:` ${r} could not be written \u2014 ik-mcp entries not synced`,level:"warn"}];let n=[];for(let o of t.entries)o.status==="written"?n.push({step:"mcp-proxies",outcome:"written",message:` updated ${r} \u2014 ik-mcp "${o.name}"`,level:"info"}):(o.status==="conflict"||o.status==="stale")&&n.push({step:"mcp-proxies",outcome:"warned",message:` ${o.message}`,level:"warn"});return n},fw=async e=>{if(e===null)return[];if(!ae.existsSync(de.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 t;try{t=(await $()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"skipped",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
|
|
317
|
+
`)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:mw(e,Yo({projectRoot:e,proxies:t,write:!0}))},gw=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("fi"),hw=e=>{let t=gt(e,Nt,vt);if(t!==null)return t;for(let[a,c]of qy){let d=gt(e,a,c);if(d!==null)return d}let r=e.indexOf(Hy);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
|
|
318
|
+
`),s=0;for(;s<o.length&&gw(o[s]);)s++;let i=o.slice(s).join(`
|
|
341
319
|
`);return n+(i?`
|
|
342
|
-
${i}`:"")},
|
|
343
|
-
`)},
|
|
344
|
-
${
|
|
345
|
-
${
|
|
346
|
-
`),
|
|
347
|
-
${
|
|
348
|
-
${
|
|
349
|
-
`),xr=class extends
|
|
350
|
-
`)};import{$ as
|
|
351
|
-
`);import
|
|
352
|
-
${t.stderr}`}},resolveBinPath:async e=>{let t=await
|
|
353
|
-
`))};import
|
|
354
|
-
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},
|
|
355
|
-
`);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},
|
|
356
|
-
`).map(t=>{let r=t.indexOf(" ");return r===-1?null:L(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),xw=async()=>{let e=await Ew({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return Sw(e.stdout)},Tw=async()=>{let e=await Ze();return e?(await Nr(e)).map(r=>r.name):[]},_n=async()=>{let[e,t]=await Promise.allSettled([xw(),Tw()]);return e.status==="rejected"&&l.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&l.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Va({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import Cw from"node:fs";import Aw from"node:path";var Ha=[".claude/settings.json",".claude/settings.local.json"],$w=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],Iw=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Dw=e=>{let t=e.trim();if(t==="Bash")return"*";let r=/^Bash\((.*)\)$/s.exec(t);if(r===null)return null;let n=r[1]??"";return n.endsWith(":*")?`${n.slice(0,-2)}*`:n},Ow=(e,t)=>{let r=e.indexOf("*");if(r===-1)return e===t||e.startsWith(`${t} `);let n=e.slice(0,r);return new RegExp(`^${e.split("*").map(Iw).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},Nw=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},_w=()=>Vt.filter(e=>e.mutating),Mw=e=>{let t=Dw(e);return t===null?[]:_w().filter(r=>$w.some(n=>Nw(r).some(o=>Ow(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},jw=(e,t)=>{let r;try{r=Cw.readFileSync(Aw.join(e,t),"utf-8")}catch(i){return i.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",file:t}}let n;try{n=JSON.parse(r)}catch{return{kind:"unreadable",file:t}}let o=n?.permissions;if(o==null)return{kind:"read",patterns:[]};let s=o.allow;return s===void 0?{kind:"read",patterns:[]}:Array.isArray(s)?{kind:"read",patterns:s.filter(i=>typeof i=="string")}:{kind:"unreadable",file:t}},Mu=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Ha){let n=jw(e,r);if(n.kind!=="absent"){if(t.present.push(r),n.kind==="unreadable"){t.unreadable.push(r);continue}for(let o of n.patterns){let s=Mw(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var Fw=["brew","gh","doppler","aws"],Lw=async e=>{let t=await An(Fw,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},ft=async(e,t,r,n)=>{try{return await Ot()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},Jw=async()=>{let e="orca installed",t=await lr();return t==="absent"?{name:e,status:"fail",message:"orca is not on PATH. Install with: brew install --cask stablyai/orca/orca, then register the CLI in Orca \u2192 Settings \u2192 Experimental \u2192 CLI"}:t==="unreachable"?{name:e,status:"warn",message:"orca is installed but the app is not running \u2014 start it with: orca open"}:{name:e,status:"pass",message:"Installed: orca (app running, runtime reachable)"}},Hu=(e,t,r,n)=>{let o=re.join(qu.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!H.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=H.readFileSync(o,"utf-8"),a=i.indexOf($t),c=i.indexOf(ut);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+ut.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},Vw=()=>Hu("zshrc init block",".zshrc","shell",lu()),Bw=()=>Hu("zshenv session block",".zshenv","session-env",Sa()),Ww=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await R(),r=re.join(t,"pnpm-workspace.yaml");if(!H.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=H.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},Gw=async()=>{try{return lt(),{config:await $(),error:null}}catch(e){return{config:null,error:e}}},Uw=e=>{let t="infra-kit config valid";return e.error?{name:t,status:"fail",message:e.error.message}:{name:t,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}},Kw=384,Ya=448,qw=e=>e.length===0?"no envs declared":e.map(t=>{let r=t.source===null?"no token":`token (${t.source})`;return`${t.env}: ${r}`}).join(", "),Hw=async(e,t)=>Promise.all(e.map(async r=>{try{let{source:n}=await t(r);return{env:r,source:n}}catch{return{env:r,source:null}}})),Yw=async(e,t={})=>{let r="env tokens configured",n=t.readStore??ne,o=t.resolveToken??Rn;if(!e.config)return{name:r,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await Hw(await jt(),o);return{name:r,status:"pass",message:qw(s)}},zw=()=>Le.env[te]||void 0,Xw=async(e={})=>{let t="tokens.json present",r=e.readStore??ne,n=e.storePath??We;if((e.readEnvToken??zw)())return{name:t,status:"pass",message:`Skipped \u2014 ${te} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,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:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${te} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Mn=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},Zw=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??We,o=t.statPath??Qw,s=t.chmodPath??H.chmodSync,i;try{i=await n()}catch{return{name:r,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(Mn(i,o)===null)return{name:r,status:"pass",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=re.dirname(i),c=re.dirname(a),d=re.dirname(c),u=[{target:d,expected:Ya,actual:Mn(d,o)},{target:c,expected:Ya,actual:Mn(c,o)},{target:a,expected:Ya,actual:Mn(a,o)},{target:i,expected:Kw,actual:Mn(i,o)}].filter(h=>h.actual!==null&&h.actual!==h.expected);if(u.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=u.map(h=>`${w(h.target)} is ${ju(h.actual)}, expected ${ju(h.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let h of u)s(h.target,h.expected);return{name:r,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},ju=e=>`0${e.toString(8).padStart(3,"0")}`,Qw=e=>{try{return H.statSync(e)}catch{return null}},ek=async()=>{let e="user override path";try{let t=await q(),r=H.existsSync(t.userProject),n=await Pn(t.userProject,r),o=r?En(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},tk=async()=>{let e="legacy user-global config",t;try{t=await q()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let r=re.join(re.dirname(t.userGlobal),"config.json");return H.existsSync(r)?H.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \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"}},rk={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},nk=async e=>{let t=rk[e];try{return await Ot()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},ok=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let r=ct(e.config).map(s=>s.provider);if(r.length===0)return{name:t,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(r.map(s=>nk(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:t,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:t,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},Fu=/^\d+\.\d+\.\d+$/,sk=(e,t)=>e===t||!Fu.test(e)||!Fu.test(t)?!1:Fr([`v${e}`,`v${t}`])[0]===`v${e}`,ik=async(e,t)=>{let r;try{r=await de(e)}catch{return[]}let n=[];for(let o of r){let s=St(xt(re.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&sk(s.version,t)&&n.push(s.version)}return n},ak=async(e,t)=>{let r=await ik(e,t);if(r.length===0)return"";let n=Fr(r.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${r.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${t}) \u2014 run: infra-kit audit --fix --all`},ck=async()=>{let e;try{e=(await q()).main}catch{return[]}if(!H.existsSync(e))return[];let t=re.dirname(e),r=re.join(t,"CLAUDE.md"),n=H.existsSync(r)?H.readFileSync(r,"utf-8"):"",o=Ne(n,ye,_e),s=o?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",i=await ak(t,U.version);return[{name:"CLAUDE.md block",status:o?"pass":"fail",message:`${s}${i}`}]},lk=async()=>{try{let e=(await q()).main;return H.existsSync(e)?re.dirname(e):null}catch{return null}},dk=e=>{let t=Id();return t===null||!sn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${yr}`},pk=e=>{let t=e.kind==="installed"?Do(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${J} version ${t}${dk(t)}`}},Lu=3,Ju=(e,t)=>ie(e)===ie(t),uk=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(Ju(e.projectDir,e.gitRoot))return"";let r=en(e.gitRoot,ie(e.projectDir),ie)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return Ju(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},mk=(e,t)=>{let r="plugin installed",n=uk(t);if(e.kind==="installed"){let{scope:c,projectPath:d}=e.installation,p=d===null?"":`, ${w(d)}`;return{name:r,status:"pass",message:`Plugin ${J} installed (${c??"unknown"} scope${p})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${J} is not installed. Run: ${Ke}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-Lu,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Lu).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${J} is installed for ${a} only, not this project. Run: ${Ke}${n}`}},fk=()=>ft("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),gk=(e,...t)=>{try{return JSON.parse(H.readFileSync(re.join(e,...t),"utf-8"))}catch{return null}},hk=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=Do(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=gk(r,z),o=n!==null&&typeof n=="object"?n[Se]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Vu=e=>`Plugin ${J} ${e===null?"(version unreadable)":e}`,vk=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${Ke}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Vu(e.version)} still carries an MCP server in its ${z}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${yr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Vu(e.version)} is skills-only \u2014 no ${z}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},yk=(e,t)=>{let r=Pt(e===null?{}:{projectPath:e}),n=on();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${G} is known to Claude Code`:`Marketplace ${G} is not registered. Run: claude plugin marketplace add ${it}`},mk(r,t),pk(r),vk(hk(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},Yu=e=>`${z} still registers "${e}" \u2014 delete this key: the plugin no longer serves an MCP server and the entry spawns a retired subcommand that exits immediately (Claude Code lists it as failed). Delete the "${e}" entry from ${z} by hand in a PR, keeping its siblings (\`claude mcp remove ${e} --scope project\` also works but re-indents the file)`,wk={stale:Yu(G),absent:`${z} carries no "${G}" key \u2014 nothing spawns the retired server`,"missing-file":`no ${z} at the repo root \u2014 nothing spawns the retired server`,unparseable:`Could not read ${Se} from ${z} \u2014 fix the JSON and re-run`},kk=new Set(["absent","missing-file","stale","wrong-key"]),bk=e=>{let t="MCP server key",r=At(e);return r.kind==="wrong-key"?{name:t,status:"pass",message:Yu(r.key)}:{name:t,status:kk.has(r.kind)?"pass":"fail",message:wk[r.kind]}},Rk=({env:e,stdinIsTTY:t,flag:r})=>{let n=e.INFRA_KIT_AGENT===void 0?"unset":`= "${e.INFRA_KIT_AGENT}"`;return[`CLAUDECODE ${e.CLAUDECODE===void 0?"unset":"set"}`,`INFRA_KIT_AGENT ${n}`,`stdin ${t?"is a TTY":"is not a TTY"}`,`--agent ${r?"passed":"not passed"}`].join(", ")},Pk=e=>{let t="Agent mode",r=Eo(e),n=Rk(e);return{name:t,status:"pass",message:`${r===null?"human":"agent"} \u2014 ${r==="flag"?"the --agent flag, which beats every environment value":e.env.INFRA_KIT_AGENT==="1"?"INFRA_KIT_AGENT=1":r==="env"?"CLAUDECODE is set and stdin is not a TTY":e.env.CLAUDECODE!==void 0&&e.stdinIsTTY?"CLAUDECODE is set but stdin is a TTY, so this is a terminal Claude Code spawned for a person":e.env.INFRA_KIT_AGENT==="0"?"INFRA_KIT_AGENT=0 suppresses the CLAUDECODE heuristic":"no source fires; pass --agent or set INFRA_KIT_AGENT=1 to drive this CLI as an agent"} (${n})`}},Bu=4,Ek=e=>{let t=e.slice(0,Bu).join(", "),r=e.length-Bu;return r>0?`${t} +${r} more`:t},Sk=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Mu(e);if(o.length>0){let s=o.map(i=>`${i.file} allows "${i.pattern}", which reaches ${i.commands.length} mutating infra-kit command${i.commands.length===1?"":"s"} (${Ek(i.commands)})`);return{name:t,status:"warn",message:`${s.join("; ")} \u2014 a prefix allow lets an agent run the --yes re-run of a mutating command unprompted; narrow it to read-only argv (e.g. Bash(infra-kit release list:*)) so the host prompts for the rest`}}return n.length>0?{name:t,status:"warn",message:`Could not read permissions.allow from ${n.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:r.length===0?{name:t,status:"pass",message:`no ${Ha.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:t,status:"pass",message:`no permissions.allow pattern in ${r.join(" or ")} reaches a mutating infra-kit command`}},zu=e=>li(["trust"],{bin:e}),xk=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),Wu="ERR_TLS_CERT_ALTNAME_INVALID",Tk=async(e,t,r)=>{let n=`portless serving TLS on :${at}`;return await e(at,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${at}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${at}. Install it once (needs root): \`${st(t,r)}\`.`}},Ck=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(p=>p.name)],c=(await Promise.all(i.map(async p=>({servername:p,result:await e(at,p)})))).filter(p=>!p.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let d=c.map(p=>p.result.ok?"":p.result.code);return d.includes(Wu)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${Wu} for servername(s) ${c.map(p=>p.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:d.some(p=>xk.has(p))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${zu(n)}\`, or reinstall: \`${st(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${d.join(", ")})`}},Ak=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${zu(r)}\` (no sudo needed).`}},$k=async(e,t,r)=>{let n="portless routes";if(e.length===0)return{name:n,status:"pass",message:"No portless routes registered"};let s=(await Promise.all(e.map(async i=>({route:i,live:await t(i.port)})))).filter(i=>!i.live).map(i=>i.route.name);return s.length===0?{name:n,status:"pass",message:`${e.length} portless route(s), all live`}:{name:n,status:"fail",message:`${s.length} stale portless route(s): ${s.join(", ")}. Remove with \`${li(["alias","--remove","<name>"],{bin:r})}\`.`}},Wt="portless service target",Fn=e=>({name:Wt,status:"pass",message:`Warning \u2014 ${e}`}),Xu=e=>e==="darwin"?id:e==="linux"?ad:null,Ik=e=>e==="darwin"?`sudo launchctl kickstart -k system/${sd}`:`sudo systemctl restart ${cd}`,Dk="/bin/ps",Ok=e=>{try{let t=Ku(Dk,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(t.status!==0)return null;let r=new Date(t.stdout.trim());return Number.isNaN(r.getTime())?null:r}catch{return null}},Gu=e=>{try{return H.readFileSync(e,"utf-8")}catch{return null}},Nk=e=>{try{return H.statSync(e).mtime}catch{return null}},_k=2e3,Mk=e=>{try{let t=Ku(e,["-p","process.version"],{encoding:"utf-8",timeout:_k}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},jk=(e,t)=>({platform:e.platform??Le.platform,readServiceFile:e.readServiceFile??Gu,readFile:e.readFile??Gu,exists:e.exists??H.existsSync,realpath:e.realpath??ie,mtime:e.mtime??Nk,execPath:e.execPath??Le.execPath,home:e.home??qu.homedir(),cwd:e.cwd??Le.cwd(),repoRoot:e.repoRoot??kn,stateDir:(e.stateDir??dd)(),processStartTime:e.processStartTime??Ok,version:e.version??Le.version,arch:e.arch??Le.arch,nodeVersionOf:e.nodeVersionOf??Mk,isGlobal:e.isGlobal??Po().node.isGlobal,nodeFs:e.nodeFs??H,stableNode:null,stableNodeSidecar:null,bin:t}),ds="portless node",Bt="~/.infra-kit/node",jn=e=>({row:{name:ds,status:"fail",message:e},stableNode:null,sidecar:null}),Uu=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},Fk=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,Lk=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,Jk=e=>{let t=gd(e.home),r=Uu(e.nodeFs.lstatSync,t);if(r===void 0)return jn(`${Bt} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return jn(`${Bt} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=hd(e.home,e.nodeFs);if(n===null)return jn(`${Bt} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=Uu(e.nodeFs.statSync,e.execPath),s=n.version===e.version&&n.arch===e.arch&&n.platform===e.platform,i=o!==void 0&&r.ino===o.ino&&r.dev===o.dev,a=n.method==="copy"&&o!==void 0&&n.sourceSize===o.size;if(!s||!(i||a))return jn(`${Bt} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!Lk(c,e))return jn(`${Bt} does not run as Node ${e.version} (${Fk(c)}). Re-run through the current Node: \`${st(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:ds,status:"pass",message:`${Bt} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},Vk=e=>{if(Xu(e.platform)===null)return{row:{name:ds,status:"pass",message:"Skipped \u2014 no portless OS service on this platform"},stableNode:null,sidecar:null};let t=Jk(e);return e.isGlobal()?t:{...t,row:{name:ds,status:"pass",message:`Skipped \u2014 not a global install; the global infra-kit keeps ${Bt} current`}}},Zu=(e,t)=>{let r=jk(e,t),n=Vk(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},Bk=(e,t)=>{let r=t.readFile(re.join(e,"package.json"));try{let n=r===null?null:oe.object({version:oe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},Wk=e=>{let t=Number.parseInt(e.readFile(re.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},Gk=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},Uk=(e,t,r)=>{let n=Wk(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(Gk(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(re.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},Kk=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:en(await t.repoRoot()??r,e,t.realpath)},Gt=e=>({state:"drifted",row:e}),qk=async(e,t,r)=>{let n=st(r.bin,r);if(!r.exists(e))return Gt({name:Wt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=re.join(pi(r.home),"dist","cli.js");if(t!==o)return Gt(Fn(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Ro(r.home,r.exists)===null)return Gt({name:Wt,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=r.realpath(pi(r.home));if(await Kk(s,r))return Gt({name:Wt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=Hk(e,n,r);if(i!==null)return i;let a=Bk(s,r),c=Uk(s,a,r);return c!==null?{state:"converged",row:Fn(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${Ik(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Wt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},Hk=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Gt(Fn(`The service runs \`${e}\`, a path its package manager will remove. Re-run once to switch it to the stable node: \`${t}\``)):r.realpath(e)===r.realpath(r.execPath)?null:Gt(Fn(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Qu=async e=>{let t=Xu(e.platform);if(t===null)return{state:"absent",row:{name:Wt,status:"pass",message:"Skipped \u2014 no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Wt,status:"pass",message:`Skipped \u2014 the OS service is not installed (no ${t})`}};let[n,o]=Gp(e.platform,r)??[];return n===void 0||o===void 0?Gt(Fn(`could not parse ${t} \u2014 re-run \`${st(e.bin,e)}\` to rewrite it.`)):qk(n,o,e)},em=async(e,t)=>{let{seams:r}=Zu(e,t);return{state:(await Qu(r)).state,stableNode:r.stableNode}},Yk=async(e={})=>{let t=e.resolveBin??od,r=e.isProxyServing??ld,n=e.handshake??md,o=e.caTrusted??ud,s=e.routes??di,i=e.isListening??tn,a=(e.caPath??pd)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."}];let d={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:p,node:u}=Zu(e,c),m=s(),h=await Tk(r,c,p),y=h.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await Ck(n,m,a,c,p);return[d,u,(await Qu(p)).row,h,y,Ak(o(),a,c),await $k(m,i,c)]},zk=async(e={})=>{let t="portless routes",r=e.routes??di,n=e.isListening??tn,o=e.devSessionRunning??Lp,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async p=>({name:p.name,port:p.port,live:await n(p.port)}))),{prunable:a,withheld:c}=Fp(i,o());if(c.length>0)return{name:t,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:t,status:"pass",message:`${s.length} portless route(s), all live`};let d=e.removeAlias??fd().removeAlias;for(let p of a)await d(p);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ps=async(e={})=>{let t=await Gw(),r=Lw(e.probeDeps??Sn()),n=async(m,h)=>{let[y,v]=await Promise.all([h,r]),I=v.get(m);return I===void 0?y:{...y,detail:I}},o=await Promise.all([n("brew",ft("brew installed",Te("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("gh",ft("gh installed",Te("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),ft("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",ft("doppler installed",Te("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",ft("aws installed",Te("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")),ft("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),ft("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"),Jw(),Promise.resolve(Vw()),Promise.resolve(Bw()),Ww(),Promise.resolve(Uw(t)),Xw(),Yw(t),Zw(e.fix??!1),ek(),tk(),ok(t)]),s=await Yk(e.portlessDeps);if(e.fix){let m=await zk(),h=s.findIndex(y=>y.name===m.name);h>=0?s[h]=m:s.push(m)}let i=await lk(),a=await kn(),c={projectDir:Le.env.CLAUDE_PROJECT_DIR||null,cwd:Le.cwd(),gitRoot:a},d=[await fk(),...yk(i,c),...a===null?[]:[bk(a)],Pk({env:Le.env,stdinIsTTY:Le.stdin.isTTY===!0,flag:A.source==="flag"}),...a===null?[]:[Sk(a)]],p=[...o,...s,...await ck(),...d],u={checks:p.map(m=>({name:m.name,status:m.status,message:m.message,fixable:pa.has(m.name),detail:m.detail})),allPassed:p.every(m=>m.status!=="fail"),cliVersion:U.version};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},za=b({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:oe.array(oe.object({name:oe.string().describe("Name of the check"),status:oe.enum(["pass","fail","warn"]).describe("Check result; warn is advisory and never fails the run"),message:oe.string().describe("Details about the check result"),fixable:oe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:oe.object({manager:oe.string().describe("Which package manager owns this install, read from its resolved path"),version:oe.string().nullable().describe("The version the tool reported, or null"),present:oe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:oe.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:oe.boolean().describe("Whether no check failed (warnings are advisory and do not count)"),cliVersion:oe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ps()});import Xa from"node:fs";import tm from"node:path";import{z as Ln}from"zod";var Xk=e=>[...e.map(t=>`unset ${t}`),`unset ${ho}`,`unset ${tr}`,`unset ${rr}`,`unset ${vo}`,`unset ${nr}`],us=async()=>{let e=or(),t=tm.join(e,er);if(!Xa.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=yo(t),n=Xk(r),o=tm.resolve(e,Yl);Xa.mkdirSync(e,{recursive:!0,mode:448}),wo(o,`${n.join(`
|
|
320
|
+
${i}`:"")},Pu=()=>{let e="pnpm exec infra-kit";return['if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",`env-load() { local f; f=$(${e} env-load "$@") || return; source "$f"; ${e} env-status; }`,`env-clear() { local f; f=$(${e} env-clear "$@") || return; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`].join(`
|
|
321
|
+
`)},Su=()=>`${Nt}
|
|
322
|
+
${Pu()}
|
|
323
|
+
${vt}`,Oa=()=>["# 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.","# 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(`
|
|
324
|
+
`),Na=()=>`${Nt}
|
|
325
|
+
${Oa()}
|
|
326
|
+
${vt}`;var vw="Could not find requested project",yw="Could not find requested config",xu="Invalid Auth token",Tu="does not have access to requested config",_t=e=>e.includes(xu)||e.includes(Tu)?"auth":e.includes(vw)?"project":e.includes(yw)?"config":"unknown",Mt=e=>e.includes(Tu)?"mis-scoped":e.includes(xu)?"revoked":null;var Cu=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(`
|
|
327
|
+
`),xr=class extends Mo{authKind;constructor(t,r=null,n){super(n??Cu(t),t),this.name="DopplerAuthError",this.authKind=r}};var _a=({kind:e,project:t,config:r,available:n})=>{let o=e==="project"?[`Doppler project "${t}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${r}" not found in project "${t}".`];if(n&&n.length>0){let s=e==="project"?"Available projects":`Available configs in "${t}"`;o.push(`${s}: ${n.join(", ")}.`)}return o.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."),o.join(`
|
|
328
|
+
`)};import{$ as as}from"zx";var ww=5e3,kw="DOPPLER_CONFIG",xe=async()=>{let{envManagement:e}=await $();return e.config.name},Ma=async({childEnv:e,project:t,config:r})=>{let n=as.quiet;as.quiet=!0;try{let s=(await as({env:e})`doppler secrets get ${kw} --plain --project ${t} --config ${r}`.timeout(ww)).stdout.trim();return s!==r?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(o){return{outcome:bw(o)}}finally{as.quiet=n}},bw=e=>{let t=ir(e)??(e instanceof Error?e.message:String(e));return _t(t)!=="auth"?"unreachable":Mt(t)??"unreachable"};import Rw from"node:process";var ee="INFRA_KIT_ENV_TOKEN",Sn=async e=>{let t=Rw.env[ee];if(t)return{token:t,source:"env"};let n=(await re())?.envs[e];if(n)return{token:n,source:"store"};throw new Mo(Ew(e,await Ge()),e)},Ew=(e,t)=>[`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 ${w(t)} (mode 0600, never in the repo).`,`CI / agents: set ${ee} instead \u2014 it takes precedence and needs no home config.`].join(`
|
|
329
|
+
`);import Pw from"node:fs/promises";var xn=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await Pw.readFile(e,"utf-8"),n=r.trim()===""?{}:JSON.parse(r);if(typeof n!="object"||n===null||Array.isArray(n))return{hasOverrides:!1,overrideKeys:[],unreadable:!0};let o=Object.keys(n);return{hasOverrides:o.length>0,overrideKeys:o,unreadable:!1}}catch{return{hasOverrides:!1,overrideKeys:[],unreadable:!0}}},Tn=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import xw from"node:fs";import Tw from"node:os";import Au from"node:path";import Cw from"node:process";import{$ as Sw}from"zx";var jt=()=>Sw({quiet:!0});var Aw=()=>[Au.join(Tw.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],$w=async e=>{try{return(await jt()`command -v ${e}`).stdout.trim()||null}catch{return null}},Cn=()=>({runCommand:async e=>{let t=await jt()`${e}`;return{stdout:`${t.stdout}
|
|
330
|
+
${t.stderr}`}},resolveBinPath:async e=>{let t=await $w(e);return t!==null?t:Aw().map(r=>Au.join(r,e)).find(r=>xw.existsSync(r))??null},realpath:se,platform:Cw.platform});var yt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),Tr=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,Cr=["darwin","linux"],ps=e=>t=>gi(t,e)?"homebrew":"unknown",us=(e,t)=>r=>r===null?null:t(e(r),r),Fa=e=>us(ps(e.kegName),t=>t==="homebrew"?yt(["brew","upgrade",e.brewFormula]):null),$u=e=>Eo(e,"Homebrew")||Eo(e,"homebrew")?"homebrew":"unknown",Iw={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:Tr,platforms:Cr,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:$u,updateFor:us($u,e=>e==="homebrew"?yt(["brew","update"]):null)},ja={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Ou="https://awscli.amazonaws.com/v2/install.sh",Nu={steps:[["/bin/bash","-c",`curl -fsSL ${Ou} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},Dw="/usr/local/aws-cli",Ow=e=>rn(Dw,e,se)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Ou} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Nu,Iu=e=>gi(e,ja.kegName)?"homebrew":Eo(e,"aws-cli")?"script":"unknown",Nw={id:"aws",binName:"aws",...ja,probeArgv:["aws","--version"],versionFrom:Tr,platforms:Cr,prerequisites:[],bootstrapInstall:Nu,identify:Iu,updateFor:us(Iu,(e,t)=>e==="homebrew"?yt(["brew","upgrade",ja.brewFormula]):e==="script"?Ow(t):null)},cs={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},_w={id:"git",binName:"git",...cs,probeArgv:["git","--version"],versionFrom:Tr,platforms:Cr,prerequisites:["brew"],bootstrapInstall:yt(["brew","install",cs.brewInstallSpec]),identify:ps(cs.kegName),updateFor:Fa(cs)},ls={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},Mw={id:"gh",binName:"gh",...ls,probeArgv:["gh","--version"],versionFrom:Tr,platforms:Cr,prerequisites:["brew"],bootstrapInstall:yt(["brew","install",ls.brewInstallSpec]),identify:ps(ls.kegName),updateFor:Fa(ls)},ds={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},jw={id:"doppler",binName:"doppler",...ds,probeArgv:["doppler","--version"],versionFrom:Tr,platforms:Cr,prerequisites:["brew"],bootstrapInstall:yt(["brew","install","gnupg"],["brew","install",ds.brewInstallSpec]),identify:ps(ds.kegName),updateFor:Fa(ds)},An="portless",Du=e=>dd(e,An)===null?"unknown":"npm",Fw={id:"portless",binName:An,npmPackage:An,probeArgv:["portless","--version"],versionFrom:Tr,platforms:[...Cr,"win32"],prerequisites:[],bootstrapInstall:yt(["npm","install","-g",An]),identify:Du,updateFor:us(Du,e=>e==="npm"?yt(["npm","install","-g",`${An}@latest`]):null)},La={brew:Iw,git:_w,aws:Nw,gh:Mw,doppler:jw,portless:Fw},Ft=Object.keys(La),ke=e=>La[e],Va=(e,t)=>e.platforms.includes(t),Ja=e=>{let t=[],r=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!r.has(o)){r.add(o);for(let i of ke(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var _u=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Mu=async(e,t)=>{try{return await e(t)}catch{return null}},Lw=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},ju=async(e,t)=>{if(!Va(e,t.platform))return _u(e.id);let r=await Mu(t.runCommand,e.probeArgv),n=await Lw(t,e.binName);if(r==null&&n==null)return _u(e.id);let o=r??(n==null?null:await Mu(t.runCommand,[n,...e.probeArgv.slice(1)]));return{id:e.id,present:!0,onPath:r!=null,binRealPath:n,version:o==null?null:e.versionFrom(o.stdout),manager:n==null?"unknown":e.identify(n)}},$n=async(e,t)=>Promise.all(e.map(r=>ju(ke(r),t)));var Fu=["prod"],Ar={allowed:!1,reason:"disallow"},$r=e=>Fu.includes(e),Vw=["dev","stage"],Ir=e=>Vw.includes(e)||$r(e),ze=(e,t=Ar)=>t.allowed?e:e.filter(r=>!$r(r)),Lt=(e,t,r=Ar)=>{if(!r.allowed&&$r(e))throw r.reason==="agent-blocked"?new T({status:"refused",env:e,agentMode:A.source},2,{operation:t,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new f(void 0,{operation:t,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 Ye=async()=>{let e;try{e=(await $()).protectedEnvs??"disallow"}catch{return Ar}return e==="disallow"?Ar:e==="cli-only"&&Y()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var In=e=>{let{env:t,branch:r}=e;$r(t)&&l.warn([`\u26A0\uFE0F "${t}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${r}" ships ${t} 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(`
|
|
331
|
+
`))};import Lu from"node:fs/promises";import Wa from"node:path";import Jw from"yaml";var Vu=".github/workflows",Xe=async e=>{let t=await R();return Ju(Wa.resolve(t,Vu,e))},Ba=async()=>{let e=await R(),t=Wa.resolve(e,Vu),r;try{r=await Lu.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>Ju(Wa.resolve(t,s))));return[...new Set(o.flat())]},Ju=async e=>{let t;try{t=Jw.parse(await Lu.readFile(e,"utf-8"))}catch{return[]}let r=Dr(t,"on")??Dr(t,"true"),n=Dr(Dr(Dr(Dr(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},Dr=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var Or=async()=>{let e=await Ba(),t=await re(),r=e.map(s=>({env:s,source:"gh-workflow"})),n=new Set(e),o=Object.keys(t?.envs??{}).filter(s=>!n.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...r,...o]},Vt=async()=>(await Or()).map(t=>t.env);import{$ as Yw}from"zx";import On from"node:process";var Ww="x-seraph-loginreason",Bw="AUTHENTICATED_FAILED",Gw=(e,t=160)=>{let r=e.split(`
|
|
332
|
+
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Bu=(e,t)=>t===Bw||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Wu=(e,t)=>e==="auth"?`Jira rejected the credentials (HTTP ${t}) \u2014 check JIRA_EMAIL and JIRA_TOKEN; Atlassian API tokens expire`:e==="forbidden"?`Jira authenticated the account but refused the operation (HTTP ${t}) \u2014 the account lacks permission on this project`:e==="not-found-or-forbidden"?`Jira returned HTTP ${t}: 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 ${t}`,Nr=class extends Error{status;kind;body;context;constructor(t){let r=Bu(t.status,t.seraphLoginReason),n=Gw(t.body);super(n===""?`${t.context}: ${Wu(r,t.status)}`:`${t.context}: ${Wu(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Dn=e=>e instanceof Nr,Gu=e=>e.headers.get(Ww);var _r=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Nr({status:e.status,seraphLoginReason:Gu(e),body:r,context:t});throw l.debug({status:e.status,kind:n.kind,body:r},t),n},Jt=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Ga=async(e,t)=>{let{baseUrl:r,token:n,email:o,projectId:s}=t,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1,...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}},a=`${r}/rest/api/3/version`,c=btoa(`${o}:${n}`),d=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await _r(d,"Failed to create Jira version"),{success:!0,version:await d.json()}},Mr=async e=>{let{baseUrl:t,token:r,email:n,projectId:o}=e,s=`${t}/rest/api/3/project/${o}/versions`,i=btoa(`${n}:${r}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await _r(a,"Failed to get Jira project versions"),await a.json()},Ze=async(e,t)=>(await Mr(t)).find(o=>o.name===e)||null,jr=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,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=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await _r(c,"Failed to update Jira version");let d=await c.json();if(e.releaseDate===null&&(d.releaseDate||null)!==null)throw new Error(`Jira accepted the update (the write happened) but still reports releaseDate=${d.releaseDate}; the clear payload in updateJiraVersion needs revisiting`);return{success:!0,version:d}},Ua=async(e,t)=>{let{versionName:r}=e,n=await Ze(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await jr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Fr=async()=>{let e=On.env.JIRA_BASE_URL,t=On.env.JIRA_TOKEN||On.env.JIRA_API_TOKEN,r=On.env.JIRA_PROJECT_ID,n=On.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
333
|
+
`);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},Qe=async()=>{try{return await Fr()}catch(e){return l.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var ms=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s=`${r}/rest/api/3/version/${e}/relatedIssueCounts`,i=btoa(`${o}:${n}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});await _r(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Ka=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.moveFixIssuesTo!==void 0&&(s.moveFixIssuesTo=e.moveFixIssuesTo),e.moveAffectedIssuesTo!==void 0&&(s.moveAffectedIssuesTo=e.moveAffectedIssuesTo);let i=`${r}/rest/api/3/version/${e.versionId}/removeAndSwap`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await _r(c,"Failed to remove Jira version")};import{z as Uu}from"zod";var Ku=/^\d{4}-\d{2}-\d{2}$/,Nn=e=>{if(!Ku.test(e))return!1;let[t,r,n]=e.split("-").map(Number),o=new Date(Date.UTC(t,r-1,n));return o.getUTCFullYear()===t&&o.getUTCMonth()===r-1&&o.getUTCDate()===n},qu=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,Lr=class extends Error{constructor(t){super(qu(t)),this.name="InvalidReleaseDateError"}},Wt=e=>{let t=e.trim();if(!Nn(t))throw new Lr(t);return t},_n=e=>{let t=e.trim();return t===""||Nn(t)?!0:qu(t)},qa=Uu.string().refine(Nn,{message:"Expected a calendar date in yyyy-mm-dd form."}),Ha=Uu.string().refine(e=>e===""||Nn(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var wt=e=>e.slice(1).split(".").map(Number),Vr=e=>[...e].sort((t,r)=>{let[n,o,s]=wt(t),[i,a,c]=wt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var zu="next",Uw=/^v?(\d+)\.(\d+)\.(\d+)$/,Kw=e=>e.replace(/^.*release\//,""),za=e=>{let t=Kw(e.trim()),r=Uw.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Hu=e=>`${e[0]}.${e[1]}.${e[2]}`,Ya=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=za(o);if(!s)continue;let i=Hu(s);n.has(i)||(n.add(i),r.push(s))}return Vr(r.map(o=>Hu(o))).map(o=>wt(`v${o}`))},Bt=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Xa=(e,t)=>{if(e.length===0)throw new Bt;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,d)=>d[0]===s&&d[1]===i?Math.max(c,d[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},Jr=(e,t)=>{try{return Xa(e,t)}catch(r){if(r instanceof Bt)return null;throw r}},Za=e=>e.trim().toLowerCase()===zu,gs=e=>Za(e)||za(e)!==null?{version:e}:{name:e},qw=e=>e==="regular"||e==="hotfix",Yu=e=>"name"in e,Hw=e=>{let t=e.indexOf("@");if(t===-1)return{token:e.trim()};let r=e.slice(0,t).trim(),n=e.slice(t+1);if(n.includes("@"))throw new Error(`Release spec "${e}" has more than one "@". Expected "<token>@yyyy-mm-dd".`);if(n.trim()==="")throw new Error(`Release spec "${e}" has an empty release date after "@". Expected "<token>@yyyy-mm-dd".`);return{token:r,releaseDate:Wt(n)}},Qa=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=Hw(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),d=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let p=d.toLowerCase();if(!qw(p))throw new Error(`Invalid release type "${d}". Expected "regular" or "hotfix".`);s=p}return fs({...gs(n),type:s},{description:i,releaseDate:o})},ec=e=>{let t=e.releaseDate===void 0?e.id.raw:`${e.id.raw}@${e.releaseDate}`;return e.description!==void 0&&e.description!==""?`${t}:${e.type}:${e.description}`:e.type==="hotfix"?`${t}:hotfix`:t},fs=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},zw=e=>{let t=e.name.trim();return Co(t),fs({id:{kind:"name",name:t,raw:t},type:e.type},e)},tc=(e,t)=>{let r=[...t];return e.map(n=>{if(Yu(n))return zw(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Za(o)){let a=Xa(r,n.type);return r.push(wt(`v${a}`)),fs({id:Se(a),type:n.type},n)}let s=za(o);if(!s)throw new Error(`Invalid version "${o}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return r.push(s),fs({id:Se(i),type:n.type},n)})},rc=e=>e.some(t=>!Yu(t)&&Za(t.version));var Xw=e=>e.split(`
|
|
334
|
+
`).map(t=>{let r=t.indexOf(" ");return r===-1?null:L(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),Zw=async()=>{let e=await Yw({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return Xw(e.stdout)},Qw=async()=>{let e=await Qe();return e?(await Mr(e)).map(r=>r.name):[]},Mn=async()=>{let[e,t]=await Promise.allSettled([Zw(),Qw()]);return e.status==="rejected"&&l.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&l.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Ya({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import ek from"node:fs";import tk from"node:path";var nc=[".claude/settings.json",".claude/settings.local.json"],rk=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],nk=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ok=e=>{let t=e.trim();if(t==="Bash")return"*";let r=/^Bash\((.*)\)$/s.exec(t);if(r===null)return null;let n=r[1]??"";return n.endsWith(":*")?`${n.slice(0,-2)}*`:n},sk=(e,t)=>{let r=e.indexOf("*");if(r===-1)return e===t||e.startsWith(`${t} `);let n=e.slice(0,r);return new RegExp(`^${e.split("*").map(nk).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},ik=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},ak=()=>Gt.filter(e=>e.mutating),ck=e=>{let t=ok(e);return t===null?[]:ak().filter(r=>rk.some(n=>ik(r).some(o=>sk(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},lk=(e,t)=>{let r;try{r=ek.readFileSync(tk.join(e,t),"utf-8")}catch(i){return i.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",file:t}}let n;try{n=JSON.parse(r)}catch{return{kind:"unreadable",file:t}}let o=n?.permissions;if(o==null)return{kind:"read",patterns:[]};let s=o.allow;return s===void 0?{kind:"read",patterns:[]}:Array.isArray(s)?{kind:"read",patterns:s.filter(i=>typeof i=="string")}:{kind:"unreadable",file:t}},Xu=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of nc){let n=lk(e,r);if(n.kind!=="absent"){if(t.present.push(r),n.kind==="unreadable"){t.unreadable.push(r);continue}for(let o of n.patterns){let s=ck(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var dk=["brew","git","gh","doppler","aws"],pk=async e=>{let t=await $n(dk,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},et=async(e,t,r,n)=>{try{return await jt()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},uk=async()=>{let e="orca installed",t=await dr();return t==="absent"?{name:e,status:"fail",message:"orca is not on PATH. Install with: brew install --cask stablyai/orca/orca, then register the CLI in Orca \u2192 Settings \u2192 Experimental \u2192 CLI"}:t==="unreachable"?{name:e,status:"warn",message:"orca is installed but the app is not running \u2014 start it with: orca open"}:{name:e,status:"pass",message:"Installed: orca (app running, runtime reachable)"}},lm=(e,t,r,n)=>{let o=te.join(cm.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!q.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=q.readFileSync(o,"utf-8"),a=i.indexOf(Nt),c=i.indexOf(vt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+vt.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},mk=()=>lm("zshrc init block",".zshrc","shell",Su()),fk=()=>lm("zshenv session block",".zshenv","session-env",Na()),gk=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await R(),r=te.join(t,"pnpm-workspace.yaml");if(!q.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=q.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},hk=async()=>{try{return mt(),{config:await $(),error:null}}catch(e){return{config:null,error:e}}},vk=e=>{let t="infra-kit config valid";return e.error?{name:t,status:"fail",message:e.error.message}:{name:t,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}},yk=384,oc=448,wk=e=>e.length===0?"no envs declared":e.map(t=>{let r=t.source===null?"no token":`token (${t.source})`;return`${t.env}: ${r}`}).join(", "),kk=async(e,t)=>Promise.all(e.map(async r=>{try{let{source:n}=await t(r);return{env:r,source:n}}catch{return{env:r,source:null}}})),bk=async(e,t={})=>{let r="env tokens configured",n=t.readStore??re,o=t.resolveToken??Sn;if(!e.config)return{name:r,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};try{await n()}catch(i){return{name:r,status:"fail",message:`Token store unreadable \u2014 ${i.message}`}}let s=await kk(await Vt(),o);return{name:r,status:"pass",message:wk(s)}},Rk=()=>Ve.env[ee]||void 0,Ek=async(e={})=>{let t="tokens.json present",r=e.readStore??re,n=e.storePath??Ge;if((e.readEnvToken??Rk)())return{name:t,status:"pass",message:`Skipped \u2014 ${ee} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,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:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${ee} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},jn=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},Pk=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Ge,o=t.statPath??Sk,s=t.chmodPath??q.chmodSync,i;try{i=await n()}catch{return{name:r,status:"pass",message:"Skipped \u2014 the token store path could not be resolved"}}if(jn(i,o)===null)return{name:r,status:"pass",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=te.dirname(i),c=te.dirname(a),d=te.dirname(c),u=[{target:d,expected:oc,actual:jn(d,o)},{target:c,expected:oc,actual:jn(c,o)},{target:a,expected:oc,actual:jn(a,o)},{target:i,expected:yk,actual:jn(i,o)}].filter(h=>h.actual!==null&&h.actual!==h.expected);if(u.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=u.map(h=>`${w(h.target)} is ${Zu(h.actual)}, expected ${Zu(h.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let h of u)s(h.target,h.expected);return{name:r,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},Zu=e=>`0${e.toString(8).padStart(3,"0")}`,Sk=e=>{try{return q.statSync(e)}catch{return null}},xk=async()=>{let e="user override path";try{let t=await K(),r=q.existsSync(t.userProject),n=await xn(t.userProject,r),o=r?Tn(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},Tk=async()=>{let e="legacy user-global config",t;try{t=await K()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let r=te.join(te.dirname(t.userGlobal),"config.json");return q.existsSync(r)?q.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \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"}},Ck={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},Ak=async e=>{let t=Ck[e];try{return await jt()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},$k=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"};let r=ut(e.config).map(s=>s.provider);if(r.length===0)return{name:t,status:"pass",message:"No IDE configured (ide unset)"};let n=await Promise.all(r.map(s=>Ak(s))),o=n.filter(s=>!s.ok);return o.length===0?{name:t,status:"pass",message:`Installed: ${n.map(s=>s.label).join(", ")}`}:{name:t,status:"fail",message:o.map(s=>s.failMsg).join("; ")}},Qu=/^\d+\.\d+\.\d+$/,Ik=(e,t)=>e===t||!Qu.test(e)||!Qu.test(t)?!1:Vr([`v${e}`,`v${t}`])[0]===`v${e}`,Dk=async(e,t)=>{let r;try{r=await le(e)}catch{return[]}let n=[];for(let o of r){let s=$t(It(te.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&Ik(s.version,t)&&n.push(s.version)}return n},Ok=async(e,t)=>{let r=await Dk(e,t);if(r.length===0)return"";let n=Vr(r.map(o=>`v${o}`))[0].slice(1);return` \u2014 ${r.length} package guidance blocks were generated by an older infra-kit (oldest ${n}, current ${t}) \u2014 run: infra-kit audit --fix --all`},Nk=async()=>{let e;try{e=(await K()).main}catch{return[]}if(!q.existsSync(e))return[];let t=te.dirname(e),r=te.join(t,"CLAUDE.md"),n=q.existsSync(r)?q.readFileSync(r,"utf-8"):"",o=Ne(n,ve,_e),s=o?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",i=await Ok(t,G.version);return[{name:"CLAUDE.md block",status:o?"pass":"fail",message:`${s}${i}`}]},_k=async()=>{try{let e=(await K()).main;return q.existsSync(e)?te.dirname(e):null}catch{return null}},Mk=e=>{let t=Bd();return t===null||!cn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${yr}`},jk=e=>{let t=e.kind==="installed"?_o(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${V} version ${t}${Mk(t)}`}},em=3,tm=(e,t)=>se(e)===se(t),Fk=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(tm(e.projectDir,e.gitRoot))return"";let r=rn(e.gitRoot,se(e.projectDir),se)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return tm(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},Lk=(e,t)=>{let r="plugin installed",n=Fk(t);if(e.kind==="installed"){let{scope:c,projectPath:d}=e.installation,p=d===null?"":`, ${w(d)}`;return{name:r,status:"pass",message:`Plugin ${V} installed (${c??"unknown"} scope${p})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${V} is not installed. Run: ${qe}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-em,i=s>0?` and ${s} more`:"",a=`${o.slice(0,em).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${V} is installed for ${a} only, not this project. Run: ${qe}${n}`}},Vk=()=>et("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),Jk=(e,...t)=>{try{return JSON.parse(q.readFileSync(te.join(e,...t),"utf-8"))}catch{return null}},Wk=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=_o(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=Jk(r,ye),o=n!==null&&typeof n=="object"?n[je]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},rm=e=>`Plugin ${V} ${e===null?"(version unreadable)":e}`,Bk=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${qe}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${rm(e.version)} still carries an MCP server in its ${ye}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${yr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${rm(e.version)} is skills-only \u2014 no ${ye}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},Gk=(e,t)=>{let r=Tt(e===null?{}:{projectPath:e}),n=an();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${X} is known to Claude Code`:`Marketplace ${X} is not registered. Run: claude plugin marketplace add ${dt}`},Lk(r,t),jk(r),Bk(Wk(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${G.version}`}]},Uk=({env:e,stdinIsTTY:t,flag:r})=>{let n=e.INFRA_KIT_AGENT===void 0?"unset":`= "${e.INFRA_KIT_AGENT}"`;return[`CLAUDECODE ${e.CLAUDECODE===void 0?"unset":"set"}`,`INFRA_KIT_AGENT ${n}`,`stdin ${t?"is a TTY":"is not a TTY"}`,`--agent ${r?"passed":"not passed"}`].join(", ")},Kk=e=>{let t="Agent mode",r=To(e),n=Uk(e);return{name:t,status:"pass",message:`${r===null?"human":"agent"} \u2014 ${r==="flag"?"the --agent flag, which beats every environment value":e.env.INFRA_KIT_AGENT==="1"?"INFRA_KIT_AGENT=1":r==="env"?"CLAUDECODE is set and stdin is not a TTY":e.env.CLAUDECODE!==void 0&&e.stdinIsTTY?"CLAUDECODE is set but stdin is a TTY, so this is a terminal Claude Code spawned for a person":e.env.INFRA_KIT_AGENT==="0"?"INFRA_KIT_AGENT=0 suppresses the CLAUDECODE heuristic":"no source fires; pass --agent or set INFRA_KIT_AGENT=1 to drive this CLI as an agent"} (${n})`}},nm=4,qk=e=>{let t=e.slice(0,nm).join(", "),r=e.length-nm;return r>0?`${t} +${r} more`:t},Hk=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Xu(e);if(o.length>0){let s=o.map(i=>`${i.file} allows "${i.pattern}", which reaches ${i.commands.length} mutating infra-kit command${i.commands.length===1?"":"s"} (${qk(i.commands)})`);return{name:t,status:"warn",message:`${s.join("; ")} \u2014 a prefix allow lets an agent run the --yes re-run of a mutating command unprompted; narrow it to read-only argv (e.g. Bash(infra-kit release list:*)) so the host prompts for the rest`}}return n.length>0?{name:t,status:"warn",message:`Could not read permissions.allow from ${n.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:r.length===0?{name:t,status:"pass",message:`no ${nc.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:t,status:"pass",message:`no permissions.allow pattern in ${r.join(" or ")} reaches a mutating infra-kit command`}},dm=e=>hi(["trust"],{bin:e}),zk=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),om="ERR_TLS_CERT_ALTNAME_INVALID",Yk=async(e,t,r)=>{let n=`portless serving TLS on :${pt}`;return await e(pt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${pt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${pt}. Install it once (needs root): \`${lt(t,r)}\`.`}},Xk=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(p=>p.name)],c=(await Promise.all(i.map(async p=>({servername:p,result:await e(pt,p)})))).filter(p=>!p.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let d=c.map(p=>p.result.ok?"":p.result.code);return d.includes(om)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${om} for servername(s) ${c.map(p=>p.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:d.some(p=>zk.has(p))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${dm(n)}\`, or reinstall: \`${lt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${d.join(", ")})`}},Zk=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${dm(r)}\` (no sudo needed).`}},Qk=async(e,t,r)=>{let n="portless routes";if(e.length===0)return{name:n,status:"pass",message:"No portless routes registered"};let s=(await Promise.all(e.map(async i=>({route:i,live:await t(i.port)})))).filter(i=>!i.live).map(i=>i.route.name);return s.length===0?{name:n,status:"pass",message:`${e.length} portless route(s), all live`}:{name:n,status:"fail",message:`${s.length} stale portless route(s): ${s.join(", ")}. Remove with \`${hi(["alias","--remove","<name>"],{bin:r})}\`.`}},Kt="portless service target",Ln=e=>({name:Kt,status:"pass",message:`Warning \u2014 ${e}`}),pm=e=>e==="darwin"?yd:e==="linux"?wd:null,eb=e=>e==="darwin"?`sudo launchctl kickstart -k system/${vd}`:`sudo systemctl restart ${kd}`,tb="/bin/ps",rb=e=>{try{let t=am(tb,["-o","lstart=","-p",String(e)],{encoding:"utf-8"});if(t.status!==0)return null;let r=new Date(t.stdout.trim());return Number.isNaN(r.getTime())?null:r}catch{return null}},sm=e=>{try{return q.readFileSync(e,"utf-8")}catch{return null}},nb=e=>{try{return q.statSync(e).mtime}catch{return null}},ob=2e3,sb=e=>{try{let t=am(e,["-p","process.version"],{encoding:"utf-8",timeout:ob}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},ib=(e,t)=>({platform:e.platform??Ve.platform,readServiceFile:e.readServiceFile??sm,readFile:e.readFile??sm,exists:e.exists??q.existsSync,realpath:e.realpath??se,mtime:e.mtime??nb,execPath:e.execPath??Ve.execPath,home:e.home??cm.homedir(),cwd:e.cwd??Ve.cwd(),repoRoot:e.repoRoot??En,stateDir:(e.stateDir??Rd)(),processStartTime:e.processStartTime??rb,version:e.version??Ve.version,arch:e.arch??Ve.arch,nodeVersionOf:e.nodeVersionOf??sb,isGlobal:e.isGlobal??xo().node.isGlobal,nodeFs:e.nodeFs??q,stableNode:null,stableNodeSidecar:null,bin:t}),hs="portless node",Ut="~/.infra-kit/node",Fn=e=>({row:{name:hs,status:"fail",message:e},stableNode:null,sidecar:null}),im=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},ab=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,cb=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,lb=e=>{let t=Td(e.home),r=im(e.nodeFs.lstatSync,t);if(r===void 0)return Fn(`${Ut} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Fn(`${Ut} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Cd(e.home,e.nodeFs);if(n===null)return Fn(`${Ut} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=im(e.nodeFs.statSync,e.execPath),s=n.version===e.version&&n.arch===e.arch&&n.platform===e.platform,i=o!==void 0&&r.ino===o.ino&&r.dev===o.dev,a=n.method==="copy"&&o!==void 0&&n.sourceSize===o.size;if(!s||!(i||a))return Fn(`${Ut} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!cb(c,e))return Fn(`${Ut} does not run as Node ${e.version} (${ab(c)}). Re-run through the current Node: \`${lt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:hs,status:"pass",message:`${Ut} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},db=e=>{if(pm(e.platform)===null)return{row:{name:hs,status:"pass",message:"Skipped \u2014 no portless OS service on this platform"},stableNode:null,sidecar:null};let t=lb(e);return e.isGlobal()?t:{...t,row:{name:hs,status:"pass",message:`Skipped \u2014 not a global install; the global infra-kit keeps ${Ut} current`}}},um=(e,t)=>{let r=ib(e,t),n=db(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},pb=(e,t)=>{let r=t.readFile(te.join(e,"package.json"));try{let n=r===null?null:ne.object({version:ne.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},ub=e=>{let t=Number.parseInt(e.readFile(te.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},mb=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},fb=(e,t,r)=>{let n=ub(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(mb(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(te.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},gb=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:rn(await t.repoRoot()??r,e,t.realpath)},qt=e=>({state:"drifted",row:e}),hb=async(e,t,r)=>{let n=lt(r.bin,r);if(!r.exists(e))return qt({name:Kt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=te.join(yi(r.home),"dist","cli.js");if(t!==o)return qt(Ln(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(So(r.home,r.exists)===null)return qt({name:Kt,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=r.realpath(yi(r.home));if(await gb(s,r))return qt({name:Kt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=vb(e,n,r);if(i!==null)return i;let a=pb(s,r),c=fb(s,a,r);return c!==null?{state:"converged",row:Ln(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${eb(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Kt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},vb=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:qt(Ln(`The service runs \`${e}\`, a path its package manager will remove. Re-run once to switch it to the stable node: \`${t}\``)):r.realpath(e)===r.realpath(r.execPath)?null:qt(Ln(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),mm=async e=>{let t=pm(e.platform);if(t===null)return{state:"absent",row:{name:Kt,status:"pass",message:"Skipped \u2014 no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Kt,status:"pass",message:`Skipped \u2014 the OS service is not installed (no ${t})`}};let[n,o]=iu(e.platform,r)??[];return n===void 0||o===void 0?qt(Ln(`could not parse ${t} \u2014 re-run \`${lt(e.bin,e)}\` to rewrite it.`)):hb(n,o,e)},fm=async(e,t)=>{let{seams:r}=um(e,t);return{state:(await mm(r)).state,stableNode:r.stableNode}},yb=async(e={})=>{let t=e.resolveBin??hd,r=e.isProxyServing??bd,n=e.handshake??Sd,o=e.caTrusted??Pd,s=e.routes??vi,i=e.isListening??nn,a=(e.caPath??Ed)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."}];let d={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:p,node:u}=um(e,c),m=s(),h=await Yk(r,c,p),y=h.status==="fail"?{name:"portless CA chain valid",status:"pass",message:"Skipped \u2014 no daemon to handshake with"}:await Xk(n,m,a,c,p);return[d,u,(await mm(p)).row,h,y,Zk(o(),a,c),await Qk(m,i,c)]},wb=async(e={})=>{let t="portless routes",r=e.routes??vi,n=e.isListening??nn,o=e.devSessionRunning??tu,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async p=>({name:p.name,port:p.port,live:await n(p.port)}))),{prunable:a,withheld:c}=eu(i,o());if(c.length>0)return{name:t,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:t,status:"pass",message:`${s.length} portless route(s), all live`};let d=e.removeAlias??xd().removeAlias;for(let p of a)await d(p);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},vs=async(e={})=>{let t=await hk(),r=pk(e.probeDeps??Cn()),n=async(m,h)=>{let[y,v]=await Promise.all([h,r]),I=v.get(m);return I===void 0?y:{...y,detail:I}},o=await Promise.all([n("brew",et("brew installed",ke("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",et("git installed",ke("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",et("gh installed",ke("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),et("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",et("doppler installed",ke("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",et("aws installed",ke("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")),et("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),et("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"),uk(),Promise.resolve(mk()),Promise.resolve(fk()),gk(),Promise.resolve(vk(t)),Ek(),bk(t),Pk(e.fix??!1),xk(),Tk(),$k(t)]),s=await yb(e.portlessDeps);if(e.fix){let m=await wb(),h=s.findIndex(y=>y.name===m.name);h>=0?s[h]=m:s.push(m)}let i=await _k(),a=await En(),c={projectDir:Ve.env.CLAUDE_PROJECT_DIR||null,cwd:Ve.cwd(),gitRoot:a},d=[await Vk(),...Gk(i,c),Kk({env:Ve.env,stdinIsTTY:Ve.stdin.isTTY===!0,flag:A.source==="flag"}),...a===null?[]:[Hk(a)]],p=[...o,...s,...await Nk(),...d],u={checks:p.map(m=>({name:m.name,status:m.status,message:m.message,fixable:ka.has(m.name),detail:m.detail})),allPassed:p.every(m=>m.status!=="fail"),cliVersion:G.version};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},sc=b({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:ne.array(ne.object({name:ne.string().describe("Name of the check"),status:ne.enum(["pass","fail","warn"]).describe("Check result; warn is advisory and never fails the run"),message:ne.string().describe("Details about the check result"),fixable:ne.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ne.object({manager:ne.string().describe("Which package manager owns this install, read from its resolved path"),version:ne.string().nullable().describe("The version the tool reported, or null"),present:ne.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ne.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:ne.boolean().describe("Whether no check failed (warnings are advisory and do not count)"),cliVersion:ne.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>vs()});import ic from"node:fs";import gm from"node:path";import{z as Vn}from"zod";var kb=e=>[...e.map(t=>`unset ${t}`),`unset ${wo}`,`unset ${nr}`,`unset ${or}`,`unset ${ko}`,`unset ${sr}`],ys=async()=>{let e=ct(),t=gm.join(e,at);if(!ic.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=bo(t),n=kb(r),o=gm.resolve(e,yo);ic.mkdirSync(e,{recursive:!0,mode:448}),Ro(o,`${n.join(`
|
|
357
335
|
`)}
|
|
358
|
-
`,384),
|
|
359
|
-
`),o.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."),
|
|
336
|
+
`,384),ic.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},ac=b({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 \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to go away. The infra-kit shell wrapper auto-sources; direct callers must handle sourcing themselves or surface filePath to the user. Errors if no env is currently loaded.',requiresHumanConfirm:!0,inputSchema:{confirm:Vn.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Vn.string().describe("Path to the file that must be sourced to apply"),variableCount:Vn.number().describe("Number of variables cleared"),unsetStatements:Vn.array(Vn.string()).describe("Unset statements generated")},handler:()=>ys()});import bb from"node:process";import{z as kt}from"zod";var ws=(e,t,r)=>e.map(({env:n,source:o})=>({env:n,source:o,hasToken:!!(r||t[n])})),hm=["Environment","Source","Token"],Rb=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=hm.map((s,i)=>Math.max(s.length,...t.map(a=>(a[i]??"").length))),n=s=>s.map((i,a)=>i.padEnd(r[a]??0)).join(" | ").trimEnd(),o=r.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",n(hm),o,...t.map(n)]},ks=async()=>{let e=await xe(),t=await Or(),r=await re(),n=bb.env[ee],o=ws(t,r?.envs??{},n);if(l.info(`Doppler project: ${e}
|
|
337
|
+
`),o.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."),vm({project:e,envs:o});for(let s of Rb(o))l.info(s);return vm({project:e,envs:o})},vm=({project:e,envs:t})=>{let r={project:e,configs:t.map(n=>n.env),tokens:t};return{content:k(JSON.stringify(r,null,2)),structuredContent:r}},cc=b({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:kt.string().describe("Detected Doppler project name"),configs:kt.array(kt.string()).describe("Every environment name known to this project"),tokens:kt.array(kt.object({env:kt.string().describe("Environment / Doppler config name"),source:kt.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:kt.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:ks});import Tb from"@inquirer/select";import{Buffer as Cb}from"node:buffer";import Ab from"node:fs";import $b from"node:path";import dc from"node:process";import{z as Wr}from"zod";import{$ as bs}from"zx";import km from"node:process";import{z as ym}from"zod";var wm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Eb=async e=>{try{return await e}catch{return[]}},Pb=async e=>{let t=await re().catch(()=>null);return ws(e,t?.envs??{},km.env[ee]).filter(r=>!r.hasToken).map(r=>r.env)},lc=()=>({get message(){return`Choose the environment to load into terminal session ${km.env[Ie]??`UNKNOWN \u2014 ${Ie} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>wm(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await Eb(Or());if(e.length===0)return l.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await Pb(e);return ym.object({config:ym.enum(t).describe(`The environment to load. ${r.length===0?"A service token is stored for every one of them.":`NO stored token for: ${r.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,t)=>{let{config:r}=e;return typeof r!="string"||r.length===0?null:{...wm(t)?t:{},config:r}}});import{z as Sb}from"zod";var xb=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return l.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},be=async e=>{if(!ie()||!e.provider.isFormable(e.params))return;let t=await xb(e),r=typeof e.params=="object"&&e.params!==null?e.params:{},n=(t===null?[]:Object.keys(t.shape)).filter(i=>r[i]===void 0||r[i]===""),o=typeof e.argument=="string"?e.argument:e.argument(n),s=t===null?void 0:Sb.toJSONSchema(t);throw new T({status:"argument_required",argument:o,...s===void 0?{}:{choices:s},agentMode:A.source},2,{operation:e.operation,remediation:s===void 0?`pass --${o} on the re-run \u2014 nothing could be listed to choose from`:`ask the human to pick from "choices", then pass --${o} on the re-run`,stderrExcerpt:`--${o} was not given and there is no human to ask`})};var Ib="DOPPLER_CONFIG",bm=new Set(["DOPPLER_TOKEN",ee]),Rm=!1,Db=e=>{e.length===0||Rm||(Rm=!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.`))},Pm=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!bm.has(i));return Db(e.filter(([i])=>bm.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${Br(a)}`),`${wo}=${Br(t)}`,`${nr}=${Br(t)}`,`${or}=${Br(r)}`,`${ko}=${Br(n)}`,`${sr}=${Br(o)}`,"set +a"]},Ob=async()=>{try{return await R()}catch{return""}},Sm=async({config:e})=>{let t=await xe(),r=await Ob(),n=await Mb(t,e),o=new Date().toISOString(),i=`${Pm({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
|
|
360
338
|
`)}
|
|
361
|
-
`,a=
|
|
362
|
-
Fix: run \`infra-kit env-token-set ${t}\` with a token scoped to "${t}".`)},
|
|
339
|
+
`,a=ct(),c=$b.resolve(a,at);return Ab.mkdirSync(a,{recursive:!0,mode:448}),Ro(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},xm=lc(),Rs=async e=>{let{config:t}=e;await be({provider:xm,params:e,operation:"env-load",argument:"config"});let r="";if(t)r=t;else{if(Y())throw new T({status:"argument_required",argument:"config",agentMode:A.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let s=await Vt();g.setInteractive(),r=await x(i=>Tb({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:dc.stderr,whenHeadless:"refuse"})}g.addOption("--config",r);let n=await Sm({config:r});g.print();let o={filePath:n.filePath,variableCount:n.variableCount,project:n.project,config:n.config,sessionId:dc.env[Ie]??null};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},Em=1024*1024,Nb=3e4,_b=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],Gr=(e,t=dc.env)=>{let r={...t};for(let n of _b)delete r[n];return r.DOPPLER_TOKEN=e,r},Mb=async(e,t)=>{let{token:r}=await Sn(t),n=Gr(r),o=bs.quiet;bs.quiet=!0;try{let s;try{s=await bs({env:n})`doppler secrets download --no-file --format json --project ${e} --config ${t}`.timeout(Nb)}catch(a){throw jb(a,e,t)}Fb(s.stdout);let i=Ps(s.stdout);return Es(i,t),i}finally{bs.quiet=o}},Es=(e,t)=>{let r=e.find(([n])=>n===Ib)?.[1];if(!(r===void 0||r===t))throw new xr(t,null,`Doppler returned secrets for config "${r}" but "${t}" was requested \u2014 the service token for env "${t}" is scoped to the wrong config. Refusing to load another environment's secrets.
|
|
340
|
+
Fix: run \`infra-kit env-token-set ${t}\` with a token scoped to "${t}".`)},jb=(e,t,r)=>{let n=ir(e)??(e instanceof Error?e.message:String(e)),o=_t(n);return o==="auth"?new xr(r,Mt(n)):o==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(_a({kind:o,project:t,config:r,available:null}))},Fb=e=>{let t=Cb.byteLength(e,"utf-8");if(t>Em)throw new Error(`doppler returned unexpectedly large output (${t} bytes > ${Em}) \u2014 refusing to write to disk`)},Br=e=>`'${e.replaceAll("'","'\\''")}'`,Lb=/^[A-Z_]\w*$/i,Ps=e=>{let t;try{t=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let r=[];for(let[n,o]of Object.entries(t)){if(!Lb.test(n))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(n.slice(0,80))})`);if(typeof o!="string")throw new TypeError(`doppler returned a non-string value for "${n}" (got ${typeof o})`);r.push([n,o])}if(r.length===0)throw new Error("doppler returned empty output for env-load");return r},pc=b({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:Wr.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:xm,outputSchema:{filePath:Wr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Wr.number().describe("Number of variables loaded"),project:Wr.string().describe("Doppler project name"),config:Wr.string().describe("Doppler config name"),sessionId:Wr.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:Rs});import Vb from"node:path";import Jn from"node:process";import{z as Ur}from"zod";var Ss=async()=>{l.info("Environment session status:");let e=ct(),t=Jn.env[Ie],r=Vb.join(e,at),n=0,o=0,s=Jn.env[nr]??null,i=Jn.env[or]??null,a=Jn.env[sr]??null;if(s){let d=bo(r);d.length>0&&(o=d.length,n=d.filter(u=>u in Jn.env).length);let p=a?.replace(/\.\d{3}Z$/,"")??null;if(l.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${p}, session: ${t})
|
|
363
341
|
`),o>0&&n<o){let u=o-n;l.warn(` ${u} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else l.info(` Session ${t}: no env loaded
|
|
364
|
-
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},
|
|
365
|
-
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},
|
|
342
|
+
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},uc=b({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, and how many variables are cached. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session. Over MCP this reflects the session file as of this call \u2014 the server re-reads it before every tool.",inputSchema:{},outputSchema:{sessionId:Ur.string().describe("Current terminal session ID"),sessionLoadedCount:Ur.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Ur.number().describe("Total number of cached var names"),sessionConfig:Ur.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Ur.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Ur.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Ss});import Jb from"node:process";import{z as bt}from"zod";var Tm="****",Kr=e=>typeof e!="string"||e.length<8?Tm:`${Tm}${e.slice(-4)}`;var Cm=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${ee}`:"store",redactedToken:Kr(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),Wb=["ENV","SOURCE","TOKEN","PRESENT"],Am=(e,t)=>{let r=[...Wb,...t?["CHECK"]:[]],n=e.map(s=>[s.env,s.source,s.redactedToken,s.present?"yes":"no",...t?[s.status??"-"]:[]]),o=r.map((s,i)=>Math.max(s.length,...n.map(a=>(a[i]??"").length)));return[r,...n].map(s=>s.map((i,a)=>i.padEnd(o[a])).join(" ").trimEnd())},xs=async({check:e}={})=>{let t=await Vt(),r=await re(),n=Jb.env[ee],o=Cm(t,r?.envs??{},n);if(e){let a=await xe();for(let c of o){if(!c.present)continue;let d=n||r.envs[c.env],p=await Ma({childEnv:Gr(d),project:a,config:c.env});c.status=p.outcome}}for(let a of Am(o,!!e))l.info(a);let s=o.filter(a=>!a.present);s.length>0&&l.info(`
|
|
343
|
+
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},mc=b({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:bt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:bt.array(bt.object({env:bt.string().describe("Environment / Doppler config name"),source:bt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:bt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:bt.boolean().describe("Whether a token is configured for this environment"),status:bt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:xs});import{z as S}from"zod";import{$ as oR}from"zx";import{$ as Bj}from"zx";import{$ as Hr}from"zx";import{$ as $m}from"zx";var fc=async e=>{let{operation:t}=e;try{await $m({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new f(r,{operation:t,remediation:"run this from inside a git repository"})}try{await $m({quiet:!0})`git remote get-url origin`}catch(r){throw new f(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},Gb=4,qr=async e=>{let{operation:t}=e,r=await Md();if(r.length===0)return;l.error(`working tree has uncommitted changes:
|
|
366
344
|
${r.join(`
|
|
367
|
-
`)}`);let n=r.slice(0,
|
|
345
|
+
`)}`);let n=r.slice(0,Gb),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new f(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},Wn=async e=>{let{operation:t,base:r}=e;if(await lr()===r)return;let n=(await ar(await R())).find(o=>o.branch===r);if(n)throw new f(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},pe=async e=>{let{operation:t}=e;if(await Fd())throw new f(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await qr({operation:t})};import{$ as Im}from"zx";var Dm="dev",Om={regular:"dev",hotfix:"main"},Je=e=>Om[e],Bn=e=>{let t=Object.entries(Om).find(([,r])=>r===e);return t?t[0]:null},Gn=(e,t)=>(t??"").trim()!==""?`${e}
|
|
368
346
|
|
|
369
347
|
${t}`:`${e}
|
|
370
|
-
`,
|
|
371
|
-
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},
|
|
372
|
-
\u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${
|
|
373
|
-
\u{1F50E} Verifying ${d.length} merge(s) with: ${s}`);let y=await
|
|
374
|
-
`)[0]??""}`);let v=await
|
|
375
|
-
\u2B06\uFE0F Pushing atomically: ${d.map(y=>y.branch).join(", ")}`);let u=await
|
|
376
|
-
`)[0],observedLanded:h.map(y=>y.branch)}},
|
|
377
|
-
\u2139\uFE0F This will push ${y} branch(es), re-running CI on ${y} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await
|
|
348
|
+
`,gc=async(e="regular")=>{let t=Je(e),r=Im({quiet:!0});await r`git fetch origin`,await r`git switch ${t}`;try{await r`git pull --ff-only origin ${t}`}catch(n){let o=await Im({quiet:!0,nothrow:!0})`git rev-list --left-right --count origin/${t}...${t}`,[s="?",i="?"]=o.exitCode===0?o.stdout.trim().split(/\s+/):[],a=i!=="0"||s!=="0";throw new f(n,{operation:`fast-forward ${t} onto origin/${t}`,remediation:a?`your local ${t} has diverged \u2014 rebase or reset it to origin/${t}, then retry`:`check your access to origin and that ${t} tracks it, then retry`,...a?{stderrExcerpt:`local ${t} is ${i} commit(s) ahead and ${s} behind origin/${t}`}:{}})}return(await r`git rev-parse HEAD`).stdout.trim()},Ub=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await Ze(t,r);if(!s)return(await Ga({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new f(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await jr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},hc=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=H(t),c=await Ub({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),d=Jt(r,c),p=await As({id:t,jiraVersionUrl:d,type:s,description:n,baseSha:i});return{version:W(t),type:s,branchName:p.branchName,prUrl:p.prUrl,jiraVersionUrl:d,releaseDate:c.releaseDate||null}},Ts=async()=>{let e=new Map,t=await Qe();if(!t)return e;try{let r=await Mr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){l.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},z=async()=>{let e=await Ts();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Un=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},vc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Cs=e=>e.flatMap(t=>{let r=L(t);return r?[{branch:t,id:r,label:W(r)}]:[]}),tt=e=>{try{return De(Se(e))}catch(t){throw new f(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},Kn=e=>{if(e===Dm)return Dm;let t=L(e);return t?W(t):e},Ht=e=>e.flatMap(t=>{let r=L(t);return r?[W(r)]:[]}),Kb=(e,t)=>t?t.get(e)||"regular":void 0,oe=e=>{let{branches:t,descriptions:r,types:n}=e;return Cs(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(H(s)),type:Kb(o,n)}))};var qb=e=>e.map(t=>({pr:t,id:L(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>_d(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),qn=200,Nm=(e,t)=>{e.length<qn||l.warn({source:t,limit:qn},`\u26A0\uFE0F ${t} returned ${qn} PRs \u2014 the page is full, so older release PRs may be missing`)},Hb=async()=>{let[e,t]=await Promise.all([Hr`gh pr list --limit ${qn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Hr`gh pr list --limit ${qn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Nm(r,"release PR discovery (base dev)"),Nm(n,"hotfix PR discovery (base main)");let o=new Set(r.map(c=>c.headRefName)),s=new Set(n.filter(c=>o.has(c.headRefName)).map(c=>c.headRefName)),i=[...n,...r],a=new Set;return i.filter(c=>a.has(c.headRefName)?!1:(a.add(c.headRefName),!0)).map(c=>({...c,dualBase:s.has(c.headRefName)}))},Hn="find open release PRs",_m=async()=>{try{let e=await Hb();if(e.length===0)throw new f(void 0,{operation:Hn,remediation:"open a release PR first, or check you are in the right repo"});return qb(e)}catch(e){throw e instanceof f?e:(l.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},$s=async()=>(await _m()).map(t=>t.headRefName),zb=e=>{let t=Bn(e.baseRefName);if(t===null)throw new f(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=vc(e.title)!==t;return(r||e.dualBase)&&l.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},O=async()=>(await _m()).map(zb),Is=async e=>{let{branch:t,body:r}=e;try{await Hr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw l.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},Yb=async(e,t)=>{let r=Hr({quiet:!0,nothrow:!0}),n=await r`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){l.error({branchName:e},o?`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 r`git switch ${t}`,(await r`git branch -D ${e}`).exitCode!==0&&l.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},As=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Nd(t,n),a=Je(n),c=Hr({quiet:!0}),d=De(t),p=Gn(r,o);try{await qr({operation:`create release branch ${d}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new f(void 0,{operation:`create release branch ${d}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${u.slice(0,8)}`});await c`git checkout -b ${d}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${d}`;let m=await c`gh pr create --title ${i} --body ${p} --base ${a} --head ${d}`;return{branchName:d,prUrl:m.stdout.trim()}}catch(m){throw await Yb(d,a),m}}catch(u){throw l.error({error:u,branchName:d},`Error creating release branch ${d}`),u}finally{await Hr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as yc}from"zx";var zr=async e=>{let t=await yc`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},wc=async e=>{let t=await yc`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},kc=async e=>{try{let t=await yc`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new f(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import Xb from"node:process";var zn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Mm=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(ie())throw new T({status:"argument_required",argument:e,agentMode:A.source},2,t);if(!Xb.stdin.isTTY)throw new f(void 0,t)},Rt=async e=>{Mm("version");let{runBranchPicker:t}=await import("./boot-XLDVLQEG.js"),r=await t(e);if(r===null)throw new zn;return r},Yr=async(e,t)=>{Mm("versions");let{runBranchMultiPicker:r}=await import("./boot-XLDVLQEG.js"),n=await r(e,t);if(n===null)throw new zn;return n};import{$ as zt}from"zx";var Zb="Merge remote-tracking branch 'origin/dev' into ",jm=e=>String(e.stderr??e.message??e).trim(),Qb=async e=>{try{return(await zt({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
|
|
349
|
+
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},eR=async(e,t)=>{let r=jm(t),n=await Qb(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await Jd(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Fm=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await sn(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await tR({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},tR=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await sn(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await ki(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await bi(r),await zt({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Zb}${n}`;await zt({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await zt({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:a===o?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:n,...await eR(r,i)}}finally{await Ri(r)}},Lm=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Vm="pnpm install --frozen-lockfile",Jm=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await bi(t),await zt({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await zt({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,jm(a))}finally{await Ri(t)}return{kept:o,failed:s}},bc=async(e,t)=>{await zt({cwd:e,quiet:!0})`git fetch origin --prune`;let r=[],n=[];for(let o of t)await ki(e,"origin/dev",`origin/${o.branch}`)?n.push(o.branch):r.push(o);return{kept:r,nowUpToDate:n}};import Rc from"node:process";var Ds=new Set,Wm=e=>(Ds.add(e),()=>{Ds.delete(e)}),rR=async()=>{for(let e of[...Ds])try{await e()}catch(t){l.warn({error:t,msg:"cleanup failed during shutdown"})}Ds.clear()},nR=["SIGINT","SIGTERM"],Bm=async(e,t={})=>{let{register:r=(i,a)=>{Rc.on(i,a)},unregister:n=(i,a)=>{Rc.off(i,a)},exit:o=i=>{Rc.exit(i)}}=t,s=new Map;for(let i of nR){let a=()=>{rR().then(()=>{o(hp(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var sR=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),iR=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,aR=e=>{let t=new Map;for(let r of e)t.set(r.reason,(t.get(r.reason)??0)+1);return[...t].map(([r,n])=>`${r} \xD7${n}`).join(", ")},Um=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),Gm=new Set(["up-to-date","fast-forward","merged"]),cR=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=De(Se(a))}catch(d){throw new f(d,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let d=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:d?`${c} is skipped: ${d}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},lR={"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"},Km=e=>{let t=lR[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},dR=(e,t)=>{l.info(`
|
|
350
|
+
\u{1F4CB} Merge plan:`);for(let r of e)l.info(` ${r.branch} \u2014 ${Km(r)}`);for(let r of t)l.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},pR=(e,t)=>{let r=t.find(n=>n.branch===e);return r?`git -C ${r.path} merge origin/dev`:`git switch ${e} && git merge origin/dev`},uR=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;g.setInteractive();let s=new Map(t.flatMap(i=>{let a=L(i.branch);return a?[[H(a),Km(i)]]:[]}));return Yr(oe({branches:r,descriptions:s}),{required:!0})},mR=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let v of y)l.info(`\u2139\uFE0F ${v} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await bc(t,Lm(i));a(c.nowUpToDate);let d=c.kept,p=new Map;if(s&&d.length>0){l.info(`
|
|
351
|
+
\u{1F50E} Verifying ${d.length} merge(s) with: ${s}`);let y=await Jm({worktreePath:r,refs:d,command:s});p=y.failed;for(let[I,j]of y.failed)l.info(`\u2717 ${I} failed verification \u2014 not pushing it. ${j.split(`
|
|
352
|
+
`)[0]??""}`);let v=await bc(t,y.kept);a(v.nowUpToDate),d=v.kept}if(d.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:p};l.info(`
|
|
353
|
+
\u2B06\uFE0F Pushing atomically: ${d.map(y=>y.branch).join(", ")}`);let u=await Vd(t,d);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:p};let h=(await Promise.all(d.map(async y=>({branch:y.branch,landed:await Do(t,y.branch)===y.sha})))).filter(y=>y.landed);return h.length>0&&l.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${h.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
|
|
354
|
+
`)[0],observedLanded:h.map(y=>y.branch)}},Os=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,confirmedCommand:s}=e,i=o===!0?Vm:o||void 0;await fc({operation:"merge dev into release branches"});let a=[],c=[];for(let E of await O()){let B=iR(E);B?c.push({branch:E.branch,reason:B}):a.push(E.branch)}if(a.length===0)return l.info(c.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${c.length} skipped (${aR(c)})`),g.print(),Um(sR(n,c));let d=await cr();try{await oR({cwd:d,quiet:!0})`git fetch origin --prune`}catch(E){throw new f(E,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?a:cR(r,a,c),u=await Wd({cwd:d},async E=>{let B=Wm(E.remove);try{return await fR({cwd:d,worktree:E,toPlan:p,candidates:a,skipped:c,all:t,versions:r,dryRun:n,verify:i,confirmedCommand:s})}finally{B()}}),{entries:m,selected:h,pushed:y,pushAborted:v,abortedBy:I,declined:j,verifyFailed:F}=u,C=await ar(d).catch(()=>[]);return gR({entries:m,selected:h,pushed:y,pushAborted:v,abortedBy:I,declined:j,verifyFailed:F,dryRun:n,worktrees:C,skipped:c})},fR=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:d,confirmedCommand:p}=e,u=await Fm({cwd:t,worktreePath:r.path,branches:n}),m={entries:u,pushed:!1,pushAborted:!1,declined:!1};if(dR(u,s),c)return{...m,selected:n};let h=await uR({entries:u,toPlan:n,all:i,explicit:a!==void 0});h.length===o.length?g.addOption("--all",!0):g.addOption("--versions",h);let y=u.filter(v=>h.includes(v.branch)&&v.mergeSha).length;y>0&&l.info(`
|
|
355
|
+
\u2139\uFE0F This will push ${y} branch(es), re-running CI on ${y} 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: ${h.join(", ")}?`,{throwOnDecline:!0})}catch(v){if(!Lo(v))throw v;return{...m,selected:h,declined:!0}}return p||g.addOption("--yes",!0),{entries:u,selected:h,declined:!1,...await mR({cwd:t,worktreePath:r.path,entries:u,selected:h,verify:d})}},gR=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:d,skipped:p}=e,u=new Set(n?t.filter(v=>r.includes(v.branch)&&v.mergeSha&&!d?.has(v.branch)).map(v=>v.branch):[]),m=t.filter(v=>r.includes(v.branch)).map(v=>{let I=!!v.mergeSha,j=e.verifyFailed?.get(v.branch),F=o&&I?"push-aborted":v.status,C=j?"verify-failed":F;return{branch:v.branch,status:C,mergeSha:v.mergeSha,conflictPaths:v.conflictPaths,pushed:u.has(v.branch),reason:j??v.reason}}),h=m.filter(v=>!Gm.has(v.status));for(let v of m){let I=t.find(j=>j.branch===v.branch);l.info({branch:v.branch,status:v.status,mergeSha:v.mergeSha,conflictCount:v.conflictPaths?.length??0,durationMs:I?.durationMs,pushed:v.pushed,msg:"merge-dev branch result"})}if(i||a)l.info(i?`
|
|
378
356
|
Operation cancelled \u2014 nothing was pushed.
|
|
379
357
|
`:`
|
|
380
358
|
\u{1F50D} Dry run \u2014 nothing was pushed.
|
|
381
359
|
`);else if(h.length>0){l.info(`
|
|
382
360
|
\u26A0\uFE0F ${h.length} branch(es) did not merge.
|
|
383
361
|
`);for(let v of h)l.info(`# ${v.branch} \u2014 ${v.status}
|
|
384
|
-
${
|
|
362
|
+
${pR(v.branch,c)}
|
|
385
363
|
`)}else l.info(`\u2705 All merges completed successfully!
|
|
386
|
-
`);g.print();let y=a||i;return Im({successfulMerges:y?0:m.filter(v=>$m.has(v.status)).length,failedMerges:y?0:h.length,failedBranches:y?[]:h.map(v=>v.branch),totalBranches:m.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:m.map(v=>y?{...v,pushed:!1}:v),skipped:p})},fc=b({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. 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; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. 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"),skipped:S.array(S.object({branch:S.string(),reason:S.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:Ts});import{z as Zn}from"zod";import{$ as be}from"zx";var Om=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},yt=e=>{if(e===null||typeof e!="object")return{message:String(e)};let t=e,r={};e instanceof Error?(r.name=e.name,r.message=e.message):typeof t.message=="string"&&(r.message=t.message);let n=t.exitCode;(typeof n=="number"||n===null)&&(r.exitCode=n);let o=Om(t.stderr,500);o&&(r.stderr=o);let s=Om(t.stdout,200);return s&&(r.stdout=s),r};var Yn=e=>{let{removed:t,failed:r}=e;if(t.length>0){l.info("\u274C Removed worktrees:");for(let n of t)l.info(n);l.info("")}if(r.length>0){l.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)l.warn(`${n} \u2014 ${o}`);l.warn("")}t.length===0&&r.length===0&&l.info("\u2139\uFE0F No worktrees to remove")};var zn=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=k(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw Z()?new T({status:"partial_failure",...n},1,s):new f(void 0,s)};import As from"node:fs/promises";import{$ as jm}from"zx";var qb=new Set([".omc",".DS_Store"]),Hb=new Set(["state","sessions"]),Yb=2e3,zb="check 'git worktree list' for the path; uncommitted changes block removal",Xb=e=>new Promise(t=>{setTimeout(t,e)}),gc=e=>typeof e=="object"&&e!==null?e.code:void 0,Nm=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},_m=async e=>{try{return Nm(await As.realpath(e))}catch{return Nm(e)}},Zb=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await ir(t),o=await _m(r);for(let s of n)if(await _m(s.path)===o)return!0;return!1}catch{return!0}},Qb=async e=>{let t;try{t=await As.readdir(e)}catch(n){return{kind:gc(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>qb.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await As.readdir(`${e}/.omc`)).every(s=>Hb.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:gc(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Mm=async e=>{try{return await As.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return gc(t)==="ENOTEMPTY"?"busy":"failed"}},eR=async e=>{let{worktreePath:t,sleep:r}=e,n=await Mm(t);return n!=="busy"?n==="removed":(await r(Yb),await Mm(t)==="removed")},Cs=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return l.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},tR=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await Zb({projectRoot:n,worktreePath:r}))return Cs(t,o,zb);let i=await Qb(r);if(i.kind==="gone")return{branch:t,status:"removed"};let a=`git already unregistered this worktree; inspect and remove it manually: rm -r ${r}`;return i.kind==="not-sweepable"||!await eR({worktreePath:r,sleep:s})?Cs(t,o,a):(l.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${r}: 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:t,status:"removed"})},rR=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await Kd(i,o);if(!a.closed&&"error"in a)return Cs(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await jm`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return tR({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},qt=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=Xb}=e,i=t.length>0?await lr():"unreachable",a=await Promise.all(t.map(d=>rR({branch:d,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let d of a)d.status==="removed"?c.removed.push(d.branch):c.failed.push({branch:d.branch,reason:d.reason});return o&&c.removed.length===t.length&&await jm`git worktree prune`,c};var Xn=async(e,t)=>{if(!(await ve("release")).includes(e))return[];let n=await R(),o=`${n}${he}`,{removed:s,failed:i}=await qt({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Yr=async(e,t,r)=>{try{return await r()}catch(n){throw l.debug({err:yt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},nR=async e=>{let t=ui(e),r=await be`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},Fm=async()=>{let e=await be`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},oR=async e=>{let t=Qe(e),r=await dc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await qr(t);if(!n)throw l.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=Bn(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},sR=async()=>{let e=await O(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));g.setInteractive();let n=await X(),o=await vt(se({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw l.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},iR=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Je(r),s=await pc(n);if(s.state==="MERGED"){l.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await Yr(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await be`gh pr merge ${n} --squash --admin --delete-branch`})},aR=async e=>{let t=B(e),r=ui(e),n=await Fm();if(n){let s=n.number;return n.title!==r&&(l.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Yr(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await be`gh pr edit ${s} --title ${r}`})),s}await Yr(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await be`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Fm();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},cR=async e=>{let t=B(e);if(await nR(e)){l.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await aR(e);await Yr(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await be`gh pr merge ${n} --squash --admin`})},lR=async()=>{be.quiet=!1,await Yr("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await be`gh workflow run deploy-all.yml --ref main -f environment=prod`}),be.quiet=!0},dR=async()=>{await Yr("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 be`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},pR=async e=>{try{await To(e)}catch(t){l.warn({err:yt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Co(e)}catch(t){l.warn({err:yt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},uR=async e=>{let t=await Ze();if(!t){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=Y(e);await Ma({versionName:r},t)}catch(r){let n=In(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";l.error({err:yt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},$s=async e=>{let{version:t,confirmedCommand:r}=e;await ue({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await oR(t):await sR(),i=L(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=B(i);if(g.addOption("--version",a),l.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),Z())throw new T({status:"refused",agentMode:A.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await Q(r,`Are you sure you want to deliver version ${n} to production?`),g.addOption("--yes",!0),be.quiet=!0;let d=`${await R()}${he}`;await Xn(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${d}/${n} (use --force if uncommitted changes)`}),await iR({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await cR(i),await lR(),await dR(),await pR(n),be.quiet=!1,await uR(i),l.info(`Successfully delivered ${n} to production!`),g.print();let p={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},hc=b({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).',requiresHumanConfirm:!0,inputSchema:{version:Zn.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:Zn.string().describe("The release branch that was delivered"),version:Zn.string().describe("The version that was delivered"),type:Zn.enum(["regular","hotfix"]).describe("Release type"),success:Zn.boolean().describe("Whether the delivery was successful")},handler:$s});import{z as et}from"zod";import{$ as xc}from"zx";import{z as to}from"zod";import Lm from"node:fs/promises";import vc from"node:path";var Jm=".github/workflows",mR=/script_name:\s*(?<service>[a-z0-9-]+)/,fR=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,gR=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,yc=async e=>{let t=vc.resolve(e,Jm),r;try{r=await Lm.readdir(t)}catch{return new Map}return Vm(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Qn=async(e,t)=>Vm(vc.resolve(e,Jm),[t]),Vm=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await Lm.readFile(vc.resolve(e,n),"utf-8")}catch{continue}hR(o,r)}return r},hR=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=mR.exec(r)?.groups?.service??fR.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(gR)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},wc=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import vR from"node:fs/promises";import yR from"node:path";import wR from"yaml";var kR=".github/workflows",bR="skip_terraform_deploy",eo=async(e,t)=>{let r=yR.resolve(e,kR,t),n;try{n=wR.parse(await vR.readFile(r,"utf-8"))}catch{return[]}let s=n?.on?.workflow_dispatch?.inputs;return typeof s!="object"||s===null?[]:Object.entries(s).filter(([i,a])=>a?.type==="boolean"&&i!==bR).map(([i])=>i)};var Bm="dev",kc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Wm=(e,t)=>e[t]===void 0,Gm=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},bc=async e=>{try{return await e}catch{return[]}},RR=async()=>{let e=await O();return Ut(e.map(t=>t.branch))},PR=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},Ht=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(l.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let d=await bc(RR());if(d.length===0)return null;let p=Gm(c,"version");return to.enum([...new Set([...d,Bm])]).optional().describe(`Which release to deploy from. "${Bm}" deploys from the dev branch instead of a release branch. ${p===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 "${p}".`}`)},i=async c=>{let d=He(await bc(ze(t)),await Ye());if(d.length===0)return null;let p=d.filter(Ar),u=d.filter(h=>!Ar(h)),m=Gm(c,"env");return to.enum(d).optional().describe(`Target environment. Shared with the whole team: ${p.length>0?p.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await R(),d=await bc(eo(c,t));if(d.length===0)return null;let p=await Qn(c,t);return to.array(to.enum(d)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${PR(d,p)} 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 ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>kc(c)?r.some(d=>Wm(c,d)):!1,buildRequestedSchema:async c=>{let d=kc(c)?c:{},p={};if(r.includes("version")){let u=await s(d);if(u===null)return o("releases");p.version=u}if(r.includes("env")){let u=await i(d);if(u===null)return o("envs");p.env=u}if(r.includes("services")&&Wm(d,"services")){let u=await a();if(u===null)return o("services");p.services=u}return Object.keys(p).length===0?o("fields"):to.object(p)},toArgs:(c,d)=>{let p={...kc(d)?d:{}};for(let u of r){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;p[u]=m}}return p}}};import ER from"@inquirer/select";var zr=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return x(r=>ER({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import SR from"@inquirer/confirm";var ro=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ae()&&jo(o,{branch:r,env:n}),g.setInteractive();let s=await x(i=>SR({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&g.addOption("--yes",!0),s};import xR from"@inquirer/select";import TR from"node:process";var Rc=()=>!ae()&&TR.stdin.isTTY===!0,CR={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Pc=async()=>x(e=>xR({message:"\u{1F680} Where should this deploy run?",choices:wt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:CR[t]}))},e),{whenHeadless:"refuse"});var wt=["ci","local"],AR={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Um=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${wt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ae()?new T({status:"argument_required",argument:"from",agentMode:A.source},2,r):new f(void 0,r)}let t=wt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${wt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Ec=(e,t)=>{let n=AR[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Sc=async e=>e||!Rc()?Um(e):Pc();var no=async e=>{if(e)return e==="dev"?"dev":Qe(e);g.setInteractive();let t=await O(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await X();return vt([{value:"dev",label:"dev"},...se({branches:r,descriptions:o,types:n})])};var Km="deploy-all.yml",qm=Ht({workflowFile:Km,fields:["version","env"],toolName:"gh-release-deploy-all"}),Is=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await ke({provider:qm,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await no(t),i=Un(s);g.addOption("--version",i);let a=await Ye(),c=He(await ze(Km),a),d="";r?d=r:(g.setInteractive(),d=await zr(c,"launch deploy-all workflow")),g.addOption("--env",d),Mt(d,"launch deploy-all workflow",a),$n({env:d,branch:s});let p=n??!1;if(p&&g.addOption("--skip-terraform",!0),!await ro({confirmedCommand:o,branch:s,env:d})){l.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:d,skipTerraformDeploy:p,success:!1};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}try{xc.quiet=!0,await xc`gh workflow run deploy-all.yml --ref ${s} -f environment=${d} ${p?["-f","skip_terraform_deploy=true"]:[]}`,xc.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${d}`),g.print();let m={releaseBranch:s,version:i,environment:d,skipTerraformDeploy:p,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw l.error({error:u},"\u274C Error launching workflow"),new f(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Tc=b({name:"gh-release-deploy-all",formProvider:qm,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:et.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:et.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:et.boolean().optional().describe("Skip the terraform deployment stage."),confirm:et.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:et.string().describe("The release branch that was deployed"),version:et.string().describe("The version that was deployed"),environment:et.string().describe("The environment deployed to"),skipTerraformDeploy:et.boolean().describe("Whether terraform deployment was skipped"),success:et.boolean().describe("Whether the deployment was successful")},handler:Is});import $R from"@inquirer/checkbox";import{z as me}from"zod";import{$ as Cc}from"zx";var Yt="deploy-selected-services.yml",Hm=Ht({workflowFile:Yt,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Ds=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await ke({provider:Hm,params:e,operation:"launch deploy-selected workflow",argument:C=>C[0]??"version"});let i=await no(t),a=Un(i);g.addOption("--version",a);let c=await Ye(),d=He(await ze(Yt),c),p="";r?p=r:(g.setInteractive(),p=await zr(d,"launch deploy-selected workflow")),g.addOption("--env",p),Mt(p,"launch deploy-selected workflow",c),$n({env:p,branch:i});let u=await R(),m=await eo(u,Yt);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Yt}`,stderrExcerpt:`no services found in .github/workflows/${Yt}`});let h=[];if(n&&n.length>0?h=n:(g.setInteractive(),h=await x(C=>$R({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},C),{whenHeadless:"refuse"})),g.addOption("--services",h),h.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=h.filter(C=>!m.includes(C));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let v=await Qn(u,Yt),I=h.filter(C=>{let P=v.get(C);return P!==void 0&&!P.includes(p)});if(I.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:I.map(C=>`${C} deploys only to: ${(v.get(C)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Yt} gates these services out of ${p}: ${I.join(", ")}`});let j=o??!1;j&&g.addOption("--skip-terraform",!0);let F=C=>{let P={releaseBranch:i,version:a,environment:p,services:h,skipTerraformDeploy:j,success:C};return{content:k(JSON.stringify(P,null,2)),structuredContent:P}};if(!await ro({confirmedCommand:s,branch:i,env:p}))return l.info("Deployment cancelled"),F(!1);try{Cc.quiet=!0;let C=h.flatMap(W=>["-f",`${W}=true`]);return await Cc`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${C} ${j?["-f","skip_terraform_deploy=true"]:[]}`,Cc.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${h.join(", ")}`),g.print(),F(!0)}catch(C){throw l.error({error:C},"\u274C Error launching workflow"),new f(C,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Ac=b({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Hm,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:me.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:me.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:me.array(me.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:me.boolean().optional().describe("Skip the terraform deployment stage."),confirm:me.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:me.string().describe("The release branch that was deployed"),version:me.string().describe("The version that was deployed"),environment:me.string().describe("The environment deployed to"),services:me.array(me.string()).describe("The services that were deployed"),skipTerraformDeploy:me.boolean().describe("Whether terraform deployment was skipped"),success:me.boolean().describe("Whether the deployment was successful")},handler:Ds});import{z as kt}from"zod";var Os=async()=>{let t=(await O()).flatMap(i=>{let a=L(i.branch);return a?[{version:B(a),jiraKey:Y(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await bs(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Gn(i.version,i.type,n),c=r.get(i.jiraKey),d=c?.description?` ${c.description}`:"",p=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",u=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${d}${p}${u}`});l.info(`All release branches:
|
|
364
|
+
`);g.print();let y=a||i;return Um({successfulMerges:y?0:m.filter(v=>Gm.has(v.status)).length,failedMerges:y?0:h.length,failedBranches:y?[]:h.map(v=>v.branch),totalBranches:m.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:m.map(v=>y?{...v,pushed:!1}:v),skipped:p})},Ec=b({name:"gh-merge-dev",description:"Merge origin/dev into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. 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; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. 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"),skipped:S.array(S.object({branch:S.string(),reason:S.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:Os});import{z as Qn}from"zod";import{$ as Re}from"zx";var qm=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Et=e=>{if(e===null||typeof e!="object")return{message:String(e)};let t=e,r={};e instanceof Error?(r.name=e.name,r.message=e.message):typeof t.message=="string"&&(r.message=t.message);let n=t.exitCode;(typeof n=="number"||n===null)&&(r.exitCode=n);let o=qm(t.stderr,500);o&&(r.stderr=o);let s=qm(t.stdout,200);return s&&(r.stdout=s),r};var Yn=e=>{let{removed:t,failed:r}=e;if(t.length>0){l.info("\u274C Removed worktrees:");for(let n of t)l.info(n);l.info("")}if(r.length>0){l.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)l.warn(`${n} \u2014 ${o}`);l.warn("")}t.length===0&&r.length===0&&l.info("\u2139\uFE0F No worktrees to remove")};var Xn=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=k(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw Y()?new T({status:"partial_failure",...n},1,s):new f(void 0,s)};import _s from"node:fs/promises";import{$ as Xm}from"zx";var hR=new Set([".omc",".DS_Store"]),vR=new Set(["state","sessions"]),yR=2e3,wR="check 'git worktree list' for the path; uncommitted changes block removal",kR=e=>new Promise(t=>{setTimeout(t,e)}),Pc=e=>typeof e=="object"&&e!==null?e.code:void 0,Hm=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},zm=async e=>{try{return Hm(await _s.realpath(e))}catch{return Hm(e)}},bR=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await ar(t),o=await zm(r);for(let s of n)if(await zm(s.path)===o)return!0;return!1}catch{return!0}},RR=async e=>{let t;try{t=await _s.readdir(e)}catch(n){return{kind:Pc(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>hR.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await _s.readdir(`${e}/.omc`)).every(s=>vR.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Pc(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Ym=async e=>{try{return await _s.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Pc(t)==="ENOTEMPTY"?"busy":"failed"}},ER=async e=>{let{worktreePath:t,sleep:r}=e,n=await Ym(t);return n!=="busy"?n==="removed":(await r(yR),await Ym(t)==="removed")},Ns=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return l.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},PR=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await bR({projectRoot:n,worktreePath:r}))return Ns(t,o,wR);let i=await RR(r);if(i.kind==="gone")return{branch:t,status:"removed"};let a=`git already unregistered this worktree; inspect and remove it manually: rm -r ${r}`;return i.kind==="not-sweepable"||!await ER({worktreePath:r,sleep:s})?Ns(t,o,a):(l.warn(`\u26A0\uFE0F swept leftover ${i.entries.join(", ")} from ${r}: 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:t,status:"removed"})},SR=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await sp(i,o);if(!a.closed&&"error"in a)return Ns(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await Xm`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return PR({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},Yt=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=kR}=e,i=t.length>0?await dr():"unreachable",a=await Promise.all(t.map(d=>SR({branch:d,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let d of a)d.status==="removed"?c.removed.push(d.branch):c.failed.push({branch:d.branch,reason:d.reason});return o&&c.removed.length===t.length&&await Xm`git worktree prune`,c};var Zn=async(e,t)=>{if(!(await he("release")).includes(e))return[];let n=await R(),o=`${n}${ge}`,{removed:s,failed:i}=await Yt({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new f(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Xr=async(e,t,r)=>{try{return await r()}catch(n){throw l.debug({err:Et(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},xR=async e=>{let t=wi(e),r=await Re`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},Zm=async()=>{let e=await Re`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},TR=async e=>{let t=tt(e),r=await wc(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new f(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await zr(t);if(!n)throw l.error(`\u274C No PR found for branch ${t}.`),new f(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=Bn(n.baseRefName);if(!o)throw new f(void 0,{operation:`deliver release ${t}`,remediation:`PR #${n.number} targets '${n.baseRefName}', which is neither dev nor main; retarget it ('gh pr edit ${n.number} --base <dev|main>')`});return{selectedReleaseBranch:t,releaseType:o,prNumber:n.number}},CR=async()=>{let e=await O(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));g.setInteractive();let n=await z(),o=await Rt(oe({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw l.error(`\u274C Release branch ${o} not found in open PRs.`),new f(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new f(void 0,{operation:`deliver release ${o}`,remediation:"the branch has open PRs to both dev and main; close the one that should not be delivered"});return{selectedReleaseBranch:o,releaseType:s.type,prNumber:s.number}},AR=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Je(r),s=await kc(n);if(s.state==="MERGED"){l.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${t} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(s.baseRefName!==o||s.headRefName!==t)throw new f(void 0,{operation:`merge release PR #${n} ${t} into ${o}`,remediation:`PR #${n} now reads ${s.headRefName} \u2192 ${s.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await Xr(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Re`gh pr merge ${n} --squash --admin --delete-branch`})},$R=async e=>{let t=W(e),r=wi(e),n=await Zm();if(n){let s=n.number;return n.title!==r&&(l.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Xr(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await Re`gh pr edit ${s} --title ${r}`})),s}await Xr(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await Re`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Zm();if(!o)throw new f(void 0,{operation:`look up RC PR for ${t}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},IR=async e=>{let t=W(e);if(await xR(e)){l.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await $R(e);await Xr(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Re`gh pr merge ${n} --squash --admin`})},DR=async()=>{Re.quiet=!1,await Xr("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await Re`gh workflow run deploy-all.yml --ref main -f environment=prod`}),Re.quiet=!0},OR=async()=>{await Xr("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 Re`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},NR=async e=>{try{await $o(e)}catch(t){l.warn({err:Et(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Io(e)}catch(t){l.warn({err:Et(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},_R=async e=>{let t=await Qe();if(!t){l.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=H(e);await Ua({versionName:r},t)}catch(r){let n=Dn(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";l.error({err:Et(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ms=async e=>{let{version:t,confirmedCommand:r}=e;await pe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await TR(t):await CR(),i=L(n);if(!i)throw new f(void 0,{operation:`deliver release ${n}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let a=W(i);if(g.addOption("--version",a),l.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),Y())throw new T({status:"refused",agentMode:A.source},2,{operation:`deliver release ${n}`,remediation:"ask a human to run `infra-kit release deliver` from their own shell \u2014 delivery is never confirmed by an agent",stderrExcerpt:"release deliver is CLI-only: refused in agent mode regardless of --yes"});await Z(r,`Are you sure you want to deliver version ${n} to production?`),g.addOption("--yes",!0),Re.quiet=!0;let d=`${await R()}${ge}`;await Zn(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${d}/${n} (use --force if uncommitted changes)`}),await AR({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await IR(i),await DR(),await OR(),await NR(n),Re.quiet=!1,await _R(i),l.info(`Successfully delivered ${n} to production!`),g.print();let p={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},Sc=b({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).',requiresHumanConfirm:!0,inputSchema:{version:Qn.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:Qn.string().describe("The release branch that was delivered"),version:Qn.string().describe("The version that was delivered"),type:Qn.enum(["regular","hotfix"]).describe("Release type"),success:Qn.boolean().describe("Whether the delivery was successful")},handler:Ms});import{z as rt}from"zod";import{$ as _c}from"zx";import{z as ro}from"zod";import Qm from"node:fs/promises";import xc from"node:path";var ef=".github/workflows",MR=/script_name:\s*(?<service>[a-z0-9-]+)/,jR=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,FR=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Tc=async e=>{let t=xc.resolve(e,ef),r;try{r=await Qm.readdir(t)}catch{return new Map}return tf(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},eo=async(e,t)=>tf(xc.resolve(e,ef),[t]),tf=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await Qm.readFile(xc.resolve(e,n),"utf-8")}catch{continue}LR(o,r)}return r},LR=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=MR.exec(r)?.groups?.service??jR.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(FR)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},Cc=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import VR from"node:fs/promises";import JR from"node:path";import WR from"yaml";var BR=".github/workflows",GR="skip_terraform_deploy",to=async(e,t)=>{let r=JR.resolve(e,BR,t),n;try{n=WR.parse(await VR.readFile(r,"utf-8"))}catch{return[]}let s=n?.on?.workflow_dispatch?.inputs;return typeof s!="object"||s===null?[]:Object.entries(s).filter(([i,a])=>a?.type==="boolean"&&i!==GR).map(([i])=>i)};var rf="dev",Ac=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nf=(e,t)=>e[t]===void 0,of=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},$c=async e=>{try{return await e}catch{return[]}},UR=async()=>{let e=await O();return Ht(e.map(t=>t.branch))},KR=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},Xt=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(l.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let d=await $c(UR());if(d.length===0)return null;let p=of(c,"version");return ro.enum([...new Set([...d,rf])]).optional().describe(`Which release to deploy from. "${rf}" deploys from the dev branch instead of a release branch. ${p===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 "${p}".`}`)},i=async c=>{let d=ze(await $c(Xe(t)),await Ye());if(d.length===0)return null;let p=d.filter(Ir),u=d.filter(h=>!Ir(h)),m=of(c,"env");return ro.enum(d).optional().describe(`Target environment. Shared with the whole team: ${p.length>0?p.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await R(),d=await $c(to(c,t));if(d.length===0)return null;let p=await eo(c,t);return ro.array(ro.enum(d)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${KR(d,p)} 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 ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Ac(c)?r.some(d=>nf(c,d)):!1,buildRequestedSchema:async c=>{let d=Ac(c)?c:{},p={};if(r.includes("version")){let u=await s(d);if(u===null)return o("releases");p.version=u}if(r.includes("env")){let u=await i(d);if(u===null)return o("envs");p.env=u}if(r.includes("services")&&nf(d,"services")){let u=await a();if(u===null)return o("services");p.services=u}return Object.keys(p).length===0?o("fields"):ro.object(p)},toArgs:(c,d)=>{let p={...Ac(d)?d:{}};for(let u of r){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;p[u]=m}}return p}}};import qR from"@inquirer/select";var Zr=async(e,t)=>{if(e.length===0)throw new f(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return x(r=>qR({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import HR from"@inquirer/confirm";var no=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ie()&&Vo(o,{branch:r,env:n}),g.setInteractive();let s=await x(i=>HR({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&g.addOption("--yes",!0),s};import zR from"@inquirer/select";import YR from"node:process";var Ic=()=>!ie()&&YR.stdin.isTTY===!0,XR={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Dc=async()=>x(e=>zR({message:"\u{1F680} Where should this deploy run?",choices:Pt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:XR[t]}))},e),{whenHeadless:"refuse"});var Pt=["ci","local"],ZR={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},sf=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Pt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ie()?new T({status:"argument_required",argument:"from",agentMode:A.source},2,r):new f(void 0,r)}let t=Pt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Pt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Oc=(e,t)=>{let n=ZR[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new f(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Nc=async e=>e||!Ic()?sf(e):Dc();var oo=async e=>{if(e)return e==="dev"?"dev":tt(e);g.setInteractive();let t=await O(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await z();return Rt([{value:"dev",label:"dev"},...oe({branches:r,descriptions:o,types:n})])};var af="deploy-all.yml",cf=Xt({workflowFile:af,fields:["version","env"],toolName:"gh-release-deploy-all"}),js=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await be({provider:cf,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await oo(t),i=Kn(s);g.addOption("--version",i);let a=await Ye(),c=ze(await Xe(af),a),d="";r?d=r:(g.setInteractive(),d=await Zr(c,"launch deploy-all workflow")),g.addOption("--env",d),Lt(d,"launch deploy-all workflow",a),In({env:d,branch:s});let p=n??!1;if(p&&g.addOption("--skip-terraform",!0),!await no({confirmedCommand:o,branch:s,env:d})){l.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:d,skipTerraformDeploy:p,success:!1};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}try{_c.quiet=!0,await _c`gh workflow run deploy-all.yml --ref ${s} -f environment=${d} ${p?["-f","skip_terraform_deploy=true"]:[]}`,_c.quiet=!1,l.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${d}`),g.print();let m={releaseBranch:s,version:i,environment:d,skipTerraformDeploy:p,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw l.error({error:u},"\u274C Error launching workflow"),new f(u,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Mc=b({name:"gh-release-deploy-all",formProvider:cf,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:rt.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:rt.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:rt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:rt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:rt.string().describe("The release branch that was deployed"),version:rt.string().describe("The version that was deployed"),environment:rt.string().describe("The environment deployed to"),skipTerraformDeploy:rt.boolean().describe("Whether terraform deployment was skipped"),success:rt.boolean().describe("Whether the deployment was successful")},handler:js});import QR from"@inquirer/checkbox";import{z as ue}from"zod";import{$ as jc}from"zx";var Zt="deploy-selected-services.yml",lf=Xt({workflowFile:Zt,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Fs=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await be({provider:lf,params:e,operation:"launch deploy-selected workflow",argument:C=>C[0]??"version"});let i=await oo(t),a=Kn(i);g.addOption("--version",a);let c=await Ye(),d=ze(await Xe(Zt),c),p="";r?p=r:(g.setInteractive(),p=await Zr(d,"launch deploy-selected workflow")),g.addOption("--env",p),Lt(p,"launch deploy-selected workflow",c),In({env:p,branch:i});let u=await R(),m=await to(u,Zt);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Zt}`,stderrExcerpt:`no services found in .github/workflows/${Zt}`});let h=[];if(n&&n.length>0?h=n:(g.setInteractive(),h=await x(C=>QR({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(E=>({name:E,value:E}))},C),{whenHeadless:"refuse"})),g.addOption("--services",h),h.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=h.filter(C=>!m.includes(C));if(y.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let v=await eo(u,Zt),I=h.filter(C=>{let E=v.get(C);return E!==void 0&&!E.includes(p)});if(I.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:I.map(C=>`${C} deploys only to: ${(v.get(C)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Zt} gates these services out of ${p}: ${I.join(", ")}`});let j=o??!1;j&&g.addOption("--skip-terraform",!0);let F=C=>{let E={releaseBranch:i,version:a,environment:p,services:h,skipTerraformDeploy:j,success:C};return{content:k(JSON.stringify(E,null,2)),structuredContent:E}};if(!await no({confirmedCommand:s,branch:i,env:p}))return l.info("Deployment cancelled"),F(!1);try{jc.quiet=!0;let C=h.flatMap(B=>["-f",`${B}=true`]);return await jc`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${C} ${j?["-f","skip_terraform_deploy=true"]:[]}`,jc.quiet=!1,l.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${h.join(", ")}`),g.print(),F(!0)}catch(C){throw l.error({error:C},"\u274C Error launching workflow"),new f(C,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Fc=b({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:lf,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:ue.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:ue.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:ue.array(ue.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:ue.boolean().optional().describe("Skip the terraform deployment stage."),confirm:ue.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:ue.string().describe("The release branch that was deployed"),version:ue.string().describe("The version that was deployed"),environment:ue.string().describe("The environment deployed to"),services:ue.array(ue.string()).describe("The services that were deployed"),skipTerraformDeploy:ue.boolean().describe("Whether terraform deployment was skipped"),success:ue.boolean().describe("Whether the deployment was successful")},handler:Fs});import{z as St}from"zod";var Ls=async()=>{let t=(await O()).flatMap(i=>{let a=L(i.branch);return a?[{version:W(a),jiraKey:H(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Ts(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Un(i.version,i.type,n),c=r.get(i.jiraKey),d=c?.description?` ${c.description}`:"",p=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",u=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${d}${p}${u}`});l.info(`All release branches:
|
|
387
365
|
`),l.info(`
|
|
388
366
|
${o.join(`
|
|
389
367
|
`)}
|
|
390
|
-
`);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}}
|
|
391
|
-
`)};import
|
|
392
|
-
`).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),
|
|
393
|
-
${
|
|
394
|
-
`)),
|
|
395
|
-
- `);await
|
|
368
|
+
`);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Lc=b({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and the associated Jira fix version\u2019s description and planned release date. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:St.array(St.object({version:St.string().describe("Release version"),type:St.enum(["regular","hotfix"]).describe("Release type"),description:St.string().nullable().describe("Jira version description"),releaseDate:St.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:St.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:St.number().describe("Number of release branches")},handler:Ls});import eE from"node:process";var Vc=e=>({...e}),Jc=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=eE.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[d,p]of Object.entries(s)){if(d.startsWith("VITE_")){c.push(d);continue}a[d]=p}return c.sort(),{childEnv:{...a,...i,DEPLOY_ENV:t,DEPLOY_BRANCH:r,DEPLOY_SHA:n,DEPLOY_SHA_LABEL:i.VITE_COMMIT_HASH,TURBO_TELEMETRY_DISABLED:"1"},contract:i,stripped:c}},Vs=e=>{let t=Object.entries(e.contract).map(([r,n])=>` ${r.padEnd(17)}= ${n}`);return e.stripped.length>0&&t.push(` stripped from shell: ${e.stripped.join(", ")}`),t.join(`
|
|
369
|
+
`)};import fE from"@inquirer/checkbox";import gE from"@inquirer/confirm";import hE from"@inquirer/select";import{spawn as vE}from"node:child_process";import yE from"node:process";import{z as J}from"zod";import{$ as io}from"zx";import{$ as so}from"zx";var tE=async e=>{let t=so.quiet;so.quiet=!0;try{let r=`/${e}/environment`,n=await so`aws sts get-caller-identity --query Account --output text`,o=await so`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new f(r,{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{so.quiet=t}},df=(e,t)=>{if(t.stage!==e)throw new f(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},pf=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new f(void 0,{operation:`deploy to shared environment "${t}"`,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"})},uf=(e,t)=>{if(t.includes(e))throw new f(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},Wc=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Lt(t,`deploy to "${t}"`,i),uf(t,s),pf({env:t,isShared:n,isClean:o});let a=await tE(r);return df(t,a),{identity:a}};import mf from"node:fs/promises";import Js from"node:path";var rE="devops/scripts",nE=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,oE=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,sE=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,iE=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,Bc=async e=>{let t=Js.resolve(e,rE),r;try{r=await mf.readdir(t)}catch{return[]}let n=await Tc(e);return(await Promise.all(r.map(s=>({entry:s,match:nE.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Js.resolve(t,s),c=i?.groups?.service??"",d=cE(await aE(a));return{name:c,scriptPath:a,allowedEnvs:Cc(lE(d),n.get(c)),ssmPrefix:pE(d)}}))).sort((s,i)=>s.name.localeCompare(i.name))},aE=async e=>{try{return await mf.readFile(e,"utf-8")}catch{return""}},cE=e=>e.split(`
|
|
370
|
+
`).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),lE=e=>{let t=e.reduce((n,{text:o})=>n??oE.exec(o)?.groups?.envs,void 0);if(t===void 0)return null;let r=t.split(/\s+/).filter(Boolean);return r.length>0?r:null},dE=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},pE=e=>{for(let{line:t,text:r}of e){let n=iE.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=sE.exec(r)?.groups?.arg;if(o!==void 0&&dE(o))return{unparseable:{line:t,text:r.trim()}}}return null},uE=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Js.basename(r.scriptPath)]);return t},mE=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Js.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},ff=e=>{mE(e);let t=uE(e),[r,...n]=t.keys();if(r===void 0)throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new f(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},Ws=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Gc=(e,t)=>e.filter(r=>Ws(r,t));var Kc="deploy-all.yml",hf="/bin/sh",wE=async()=>{let e=io.quiet;io.quiet=!0;try{let t=await io`gh run list --workflow=${Kc} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{io.quiet=e}},kE=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await x(o=>fE({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new f(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},bE=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return ie()&&Vo(i,{env:t,services:n,accountId:o,shared:r}),r?x(a=>hE({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):x(a=>gE({message:i,default:!1},a),{whenHeadless:"refuse"})},RE=(e,t,r)=>new Promise((n,o)=>{let s=vE(hf,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),EE=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){l.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await RE(a,r,n);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}},PE=e=>{let{names:t,services:r,env:n}=e,o=new Map(r.map(a=>[a.name,a])),s=t.filter(a=>!o.has(a));if(s.length>0)throw new f(void 0,{operation:"resolve the requested services",remediation:`known services: ${r.map(a=>a.name).join(", ")}`,stderrExcerpt:`no deploy script for: ${s.join(", ")}`});let i=t.filter(a=>{let c=o.get(a);return c!==void 0&&!Ws(c,n)});if(i.length>0)throw new f(void 0,{operation:`deploy to "${n}"`,remediation:"drop those services, or deploy them to an environment they allow",stderrExcerpt:`not enabled for "${n}": ${i.join(", ")} (the scripts would skip them)`});return t.map(a=>o.get(a))},Uc=e=>{let{env:t,accountId:r,names:n,built:o,deployed:s,failed:i,dryRun:a,success:c}=e,d={environment:t,accountId:r,services:n,deployed:s,failed:i,contract:Vc(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},SE=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(g.setInteractive(),kE(r,o))},vf=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await R(),c=await Bc(a);if(c.length===0)throw new f(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let d=ff(c);await be({provider:qc[t],params:e,operation:"deploy locally",argument:"env"});let p=await Ye(),u=ze(await Xe(Kc),p),m=r??"";m||(g.setInteractive(),m=await Zr(u,"deploy locally")),g.addOption("--env",m);let h=Gc(c,m);if(h.length===0)throw new f(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let y=await SE({selection:t,eligible:h,service:n,env:m}),v=PE({names:y,services:c,env:m});if(t==="selected")for(let $e of y)g.addOption("--service",$e);let I=Ir(m),j=await lr(),F=(await io`git rev-parse HEAD`.quiet()).stdout.trim(),C=await jd(),E=Jc({env:m,branch:j,sha:F,isClean:C});i&&l.info(`Deploy contract for ${m}:
|
|
371
|
+
${Vs(E)}`);let Pe=(await Wc({env:m,project:d,isShared:I,isClean:C,runningEnvs:await wE(),protectedEnvAccess:p})).identity.accountId;if(s)return l.info([`Would deploy to "${m}" (AWS account ${Pe}) from this machine`,`Preflight parameter: /${d}/environment`,Vs(E),"Commands:",...v.map($e=>` ${hf} ${$e.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
|
|
372
|
+
`)),Uc({env:m,accountId:Pe,names:y,built:E,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await bE({env:m,isShared:I,names:y,accountId:Pe}))return l.info("Deployment cancelled"),Uc({env:m,accountId:Pe,names:y,built:E,deployed:[],failed:[],dryRun:!1,success:!1});E.stripped.length>0&&l.info(`Stripped ambient VITE_* from the build env: ${E.stripped.join(", ")}`);let{deployed:Be,failed:it}=await EE({chosen:v,childEnv:E.childEnv,cwd:a,env:m});return it.length>0&&(l.error(`Partial deploy to "${m}": succeeded [${Be.join(", ")||"none"}], failed [${it.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),yE.exitCode=1),g.print(),Uc({env:m,accountId:Pe,names:y,built:E,deployed:Be,failed:it,dryRun:!1,success:it.length===0})},yf=async e=>vf(e,"all"),wf=async e=>vf(e,"selected"),kf='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.',bf={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.")},Rf={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")},gf=e=>Xt({workflowFile:Kc,fields:["env"],toolName:e}),qc={all:gf("local-deploy-all"),selected:gf("local-deploy-selected")},Hc=b({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${kf}`,requiresHumanConfirm:!0,formProvider:qc.all,inputSchema:bf,outputSchema:Rf,handler:yf}),zc=b({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${kf}`,requiresHumanConfirm:!0,formProvider:qc.selected,inputSchema:{...bf,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:Rf,handler:wf});import CE from"@inquirer/confirm";import Bs from"@inquirer/input";import xf from"@inquirer/select";import Xc from"node:process";import{z as _}from"zod";import{z as ao}from"zod";var Qr=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Sf=2500,Ef=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pf=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,xE=async()=>{let e=await Mn();return{regular:Jr(e,"regular"),hotfix:Jr(e,"hotfix")}},TE=(e,t)=>e===null?(l.info({msg:"Tool execution form hint unavailable (timeout): release-create"}),`The "next" hint could not be computed within ${t/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).`,Yc=(e={})=>{let t=e.hintBudgetMs??Sf;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:r=>Ef(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Qr(xE(),t);return ao.object({type:ao.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:ao.string().describe(`A semver such as "1.64.0", the literal "next", or a kebab-case name such as "checkout-redesign" \u2014 no "@" here, the date has its own field. ${TE(r,t)}`),description:ao.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:ao.string().optional().describe("Optional. Planned production date, yyyy-mm-dd. Becomes the Jira fix version's release date; delivery overwrites it with the actual date. On the re-run it is passed as <token>@yyyy-mm-dd inside -r.")})},toArgs:(r,n)=>{let o=typeof r.release=="string"?r.release.trim():"";if(o==="")return null;let s=r.type==="hotfix"?"hotfix":"regular",i=Pf(r.description),a=Pf(r.releaseDate),c=gs(o);return{...Ef(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var AE='"1.2.5" or "next"',Zc=(e,t)=>{try{return tc(e,t)}catch(r){throw r instanceof Bt?new f(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof Od?new f(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},$E=async(e,t)=>{let r=Jr(e,t),n=r?` [${r}]`:"",o=(await x(i=>Bs({message:` Version (e.g. ${AE})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(l.error("No version provided. Exiting..."),Xc.exit(1)),s},IE=async()=>{let e=(await x(t=>Bs({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(l.error("No name provided. Exiting..."),Xc.exit(1));try{Co(e)}catch(t){let r=t instanceof Error?t.message:String(t);l.error(`${r} Exiting...`),Xc.exit(1)}return e},DE=async()=>(await x(e=>Bs({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:_n},e),{whenHeadless:"refuse"})).trim(),OE=async e=>{g.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await x(m=>xf({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},m),{whenHeadless:"refuse"}),c=await x(m=>xf({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),d;if(a==="name"){let m=await IE();d=Zc([{name:m,type:c}],[])[0]}else{let m=await $E(await n(),c);d=Zc([{version:m,type:c}],r)[0],d.id.kind==="version"&&r.push(wt(`v${d.id.raw}`))}let p=(await x(m=>Bs({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),u=await DE();o.push({...d,...p!==""?{description:p}:{},...u!==""?{releaseDate:u}:{}}),s=await x(m=>CE({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},NE=e=>{let r=[e.id.kind==="version"?`v${e.id.raw}`:e.id.name,e.type];return e.description&&r.push(e.description),e.releaseDate&&r.push(`ships ${e.releaseDate}`),r.join(" \xB7 ")},Tf=e=>{for(let t of e)g.addOption("--release",ec(t))},_E=async(e,t)=>{if(e&&e.length>0){let n=rc(e)?await t():[],o=Zc(e,n);return Tf(o),o}if(Y())throw new T({status:"argument_required",argument:"release",agentMode:A.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await OE(t);return Tf(r),r},ME=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},jE=async(e,t)=>{let r=e.map(NE).join(`
|
|
373
|
+
- `);await Z(t,`Create the following ${e.length} release(s)?
|
|
396
374
|
- ${r}
|
|
397
|
-
`),g.addOption("--yes",!0)},
|
|
398
|
-
`),{result:i}}catch(s){let i=
|
|
399
|
-
`),{failure:{version:n,error:a.message}}}},
|
|
400
|
-
${
|
|
375
|
+
`),g.addOption("--yes",!0)},FE=async e=>{let{entry:t,jiraConfig:r}=e,n=W(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await qr({operation:`create release ${o}`});let s=await gc(t.type),i=await hc({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return l.info(`\u2705 Successfully created release: ${o} (${t.type})`),l.info(`\u{1F517} GitHub PR: ${i.prUrl}`),l.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
|
|
376
|
+
`),{result:i}}catch(s){let i=Dn(s)?s:void 0,a=new f(s,{operation:`create release ${o} (${t.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}
|
|
377
|
+
`),{failure:{version:n,error:a.message}}}},LE=(e,t,r)=>{t===e?l.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(l.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),l.warn(`\u274C ${r} release(s) failed.`)):l.error(`\u274C All ${e} release branch(es) failed to create.`)},Cf=Yc(),Gs=async e=>{let{releases:t,confirmedCommand:r}=e;await pe({operation:"create release"}),await be({provider:Cf,params:e,operation:"create release",argument:"release"});let n=await Fr(),o=null,i=await _E(t,async()=>(o===null&&(o=await Mn()),o));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});ME(i),await Wn({operation:"create release",base:Je(i[0].type)}),await jE(i,!!r);let a=[],c=[];for(let p of i){let{result:u,failure:m}=await FE({entry:p,jiraConfig:n});u&&a.push(u),m&&c.push(m)}LE(i.length,a.length,c.length),g.print();let d={createdBranches:a.map(p=>p.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Qc=b({name:"release-create",requiresHumanConfirm:!0,formProvider:Cf,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:_.array(_.object({version:_.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:_.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:_.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:_.string().optional().describe("Optional description for the Jira version."),releaseDate:qa.optional().describe('Optional planned production date, yyyy-mm-dd. Written to the Jira fix version as its release date; "release deliver" overwrites it with the actual date. Rides in the CLI spec as "<token>@yyyy-mm-dd".')}).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=>{let t={...e.description?{description:e.description}:{},...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}};return e.name!==void 0?{name:e.name,type:e.type,...t}:{version:e.version,type:e.type,...t}})).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:_.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:_.array(_.string()).describe("List of created release branch names"),successCount:_.number().describe("Number of releases created successfully"),failureCount:_.number().describe("Number of releases that failed"),releases:_.array(_.object({version:_.string().describe("Version number"),type:_.enum(["regular","hotfix"]).describe("Release type"),branchName:_.string().describe("Release branch name"),prUrl:_.string().describe("GitHub PR URL"),jiraVersionUrl:_.string().describe("Jira version URL"),releaseDate:_.string().nullable().describe("The release date the Jira fix version now carries (yyyy-mm-dd), or null when it has none")})).describe("Detailed information for each created release with URLs"),failedReleases:_.array(_.object({version:_.string().describe("Version number that failed"),error:_.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Gs});import Af from"@inquirer/input";import{z as Ee}from"zod";var $f=["description","releaseDate"],VE=async()=>{let e=await O(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await z(),o=await Rt(oe({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},JE=async e=>{let r=(await O()).find(n=>n.branch===e);if(!r)throw new f(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},WE=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await x(o=>Af({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},BE=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await x(o=>Af({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:_n},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Wt(n)},GE=e=>{if(e!==void 0)return e===""?null:e},UE=async e=>(g.setInteractive(),{description:await WE(e.description),releaseDate:await BE(e.releaseDate)}),el=e=>e??"(none)",KE=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${el(t.releaseDate)} \u2192 ${el(r.releaseDate)}`,Us=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=GE(n),i=await Fr(),a;t?(a=tt(t),await JE(a)):(g.setInteractive(),a=(await VE()).branch);let c=L(a);if(!c)throw new f(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let d=W(c);g.addOption("--version",d);let p=H(c),u=await Ze(p,i);if(!u)throw new f(void 0,{operation:`edit release ${p}`,remediation:`create the Jira fix version "${p}" first or pick a different release`});let m={description:u.description??"",releaseDate:u.releaseDate||null},h=r!==void 0||s!==void 0;if(!h&&ie())throw new T({status:"argument_required",argument:"description",agentMode:A.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=h?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await UE(m),v=$f.filter(B=>y[B]!==m[B]),I=v.includes("description"),j=v.includes("releaseDate"),F=Jt(i,u),C=B=>{let Pe={version:d,branch:a,jiraVersionUrl:F,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:v,changed:B};return{content:k(JSON.stringify(Pe,null,2)),structuredContent:Pe}};if(v.length===0)return l.info(`No change \u2014 ${p} already has description "${m.description}" and release date ${el(m.releaseDate)}`),g.print(),C(!1);I&&g.addOption("--description",y.description),j&&g.addOption("--release-date",y.releaseDate??"");let E=v.map(B=>KE(B,m,y));return await Z(o,`Update ${p}?
|
|
378
|
+
${E.join(`
|
|
401
379
|
`)}
|
|
402
|
-
`),g.addOption("--yes",!0),await
|
|
403
|
-
`),g.print(),C(!0)},
|
|
404
|
-
`,"utf-8"),{added:c,skipped:d}};import{$ as
|
|
405
|
-
`,"utf-8");let p=[],u=[];for(let m of r){let h=
|
|
406
|
-
`).map(r=>r.trimEnd()).filter(r=>r.length>0),
|
|
407
|
-
`)},Ws=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},WP=e=>typeof e=="string"?e:e.outcome;async function co(e,t,r){try{let n=await r(),o=WP(n);return t.push({step:e}),l.info({step:e,outcome:o},`\u2705 ${Gs[e]} \u2014 ${o}`),n}catch(n){throw new Ws(e,n)}}var GP=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),l.warn({err:yt(n),step:e},`\u26A0\uFE0F ${Gs[e]} failed (non-blocking)`)}},UP=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,KP=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(u=>UP(t,u)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,d=`completed: ${s}. ${i}${a}${c}`,p=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Ef.indexOf(r)+1} of ${Ef.length} (${Gs[r]})`,remediation:p?`${p} \u2014 ${d}`:d})},qP=async e=>{let t=await Xn(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:t.includes(e.branch)?"removed":"absent",removedBranches:t}},HP=e=>{let t=e.map(s=>({provider:s.provider,outcome:YP(s),removed:s.removed})),r=t.some(s=>s.outcome==="verified"),o=t.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:r?"verified":o,providers:t}},YP=e=>e.removed.length>0?"verified":"attempted",zP=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await GP("ide-folders",r,async()=>{let o=await zt({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=HP(o)}),l.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${Gs["ide-folders"]} \u2014 ${n.outcome}`),n},XP=async e=>{let t=await qr(e.branch);if(Tf({...e,pr:t}),!t)return{outcome:"absent",number:null};if(t.state==="CLOSED")return{outcome:"already-closed",number:t.number};let r=`Closed by \`infra-kit release remove\`: release ${e.label} was torn down.`;return await Zc`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},ZP=async e=>(await cr()===e.branch&&await Zc`git switch ${e.baseBranch}`,await To(e.branch),await Td(e.branch)?Ce({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"),QP=async e=>(await Co(e.branch),e.remoteTipSha?"deleted":"absent"),eE=async(e,t,r)=>{let n=await as(t.version.id,r);if(n.issuesFixedCount===t.fixCount&&n.issuesAffectedCount===t.affectsCount)return;let o=`re-run \`infra-kit release remove --version ${e.label}\``;Ce({operation:`remove Jira fix version "${t.version.name}"`,remediation:`the fix version was NOT removed and every other step is complete \u2014 ${o} so the guard re-evaluates the new counts`,stderrExcerpt:`issue counts changed since preflight: fixVersion ${t.fixCount} \u2192 ${n.issuesFixedCount}, affectsVersion ${t.affectsCount} \u2192 ${n.issuesAffectedCount}`})},tE=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await eE(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 ja({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),rE=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree.outcome,ideFolders:t.ideFolders,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),nE=async(e,t,r)=>{let n=await co("worktree",r,()=>qP(e)),o=await zP(e,n.removedBranches,r),s=await co("pr",r,()=>XP(e));l.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await co("local-branch",r,()=>ZP(e)),a=await co("remote-branch",r,()=>QP(e)),c=await co("jira",r,()=>tE(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},oE=async(e,t)=>{let r=[];try{return rE(e,await nE(e,t,r))}catch(n){throw n instanceof Ws?KP({plan:e,step:n.step,done:r,cause:n.reason}):n}},sE=async e=>{if(e)return Qe(e);g.setInteractive();let[t,r]=await Promise.all([X(),O()]),n=r.map(s=>s.branch);n.length===0&&Ce({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 o=new Map(r.map(s=>[s.branch,s.type]));try{return await vt(se({branches:n,descriptions:t,types:o}))}catch(s){throw le(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},Cf=Xc(),Us=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await ue({operation:Zt}),await $(),await ke({provider:Cf,params:e,operation:Zt,argument:"version"}),IP(e);try{let s=await JP(await sE(r),e);l.debug({plan:xf(s)},"release remove: resolved plan"),Tf(s),DP(s,e),OP(s),await Vn({operation:`remove release ${s.label}`,base:s.baseBranch}),NP(s),g.addOption("--version",s.label),n&&g.addOption("--move-issues-to",n),o&&g.addOption("--skip-jira",!0),await Q(t,BP(s,!!o),{throwOnDecline:!0,plan:{...xf(s),skipJira:!!o}}),t||g.addOption("--yes",!0);let i=await oE(s,e);return g.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw le(s)||Mo(s)||s instanceof f?s:(l.error({err:yt(s)},"\u274C Error removing release"),new f(s,{operation:Zt,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Qc=b({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:Cf,inputSchema:{version:D.string().optional().describe('The release version or name to remove (e.g. "1.2.5" or "checkout-redesign"). Omit it to be offered the open release PRs.'),moveIssuesTo:D.string().optional().describe(`Optional. An EXISTING Jira fix version name (exactly as in Jira, e.g. "v1.2.6") to move this release's issues to before its fix version is removed \u2014 both fixVersion and affectsVersion. Pass it only after a refusal reported the issue counts, or when the human named the target; a name Jira does not know is refused in preflight before anything is touched.`),confirm:D.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:D.string().describe("The release branch that was targeted"),version:D.string().describe('The release label (e.g. "1.2.5")'),baseBranch:D.string().describe("The branch HEAD was moved to before the local delete"),worktree:D.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:D.object({outcome:D.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:D.array(D.object({provider:D.string(),outcome:D.enum(["verified","attempted","skipped"]),removed:D.array(D.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:D.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:D.number().nullable().describe("The pull request number, or null when none exists"),localBranch:D.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:D.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:D.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:D.string().nullable().describe("The origin tip before deletion"),jira:D.enum(["removed","absent","skipped"]).describe('"removed" when the fix version was deleted; "absent" when Jira knows none for this release (the resume path); "skipped" only on the CLI with --skip-jira'),jiraVersion:D.object({id:D.string(),name:D.string(),url:D.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Us});import{spawnSync as lE}from"node:child_process";import{homedir as dE}from"node:os";import pE from"node:process";var iE=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},aE=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},cE=(e,t)=>{let r=iE(e);if(r===null)return[];let n=[];return t.present.includes(r)||n.push("manager-absent"),t.owner!==null&&t.owner!==r&&n.push("manager-mismatch"),n},lo=(e,t)=>{let r=[...aE(e),...cE(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},po=e=>e.steps.map(nd);var uE=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],mE=e=>{let t={...rd(e)};for(let r of uE)delete t[r];return t},el=(e,t,r={})=>{let n=r.spawnSync??lE,o=r.env??pE.env,s=(r.agentMode??Z)(),i=po(e),a=lo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:hE({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??fE}):{ran:!1,commands:i,refusedBecause:a.reasons}},fE=e=>{l.info(e)},$f=64,gE=$f*1024*1024,hE=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=mE(r);for(let[i,a]of e.steps.entries()){o(` ${"running".padEnd(9)} ${n[i]}`);let c=t(a[0],a.slice(1),{stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:gE,cwd:dE(),env:s}),d=RE(c);if(d!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:d}}return{ran:!0,ok:!0,commands:n}},vE=5,yE=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Af=e=>e==null?[]:String(e).split(`
|
|
408
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),wE=e=>{let t=Af(e.stderr),r=Af(e.stdout),n=[...t,...r].filter(s=>yE.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-vE).join(" / ")},kE="ENOBUFS",bE=e=>e.error?.code===kE,RE=e=>{if(bE(e))return`terminated after exceeding the ${$f} 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 t=wE(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var PE=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},EE=e=>{let t=Te(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},SE=(e,t)=>{let r=EE(e),n={...t,owner:e.present?e.manager:null};if(r===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=lo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:po(r),context:n}},Ks=async(e=_t,t=Sn())=>{let r=await An(_t,t),n={owner:null,present:PE(r)},o=Da(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>SE(s.get(a),n)),context:n}};var tl=(e,t)=>({...uo(e),action:"skipped",commands:e.commands,detail:t}),uo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),If=(e,t)=>e.action==="none"?tl(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?tl(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...uo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},xE=(e,t)=>t.ran?t.ok?{...uo(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...uo(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...uo(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},rl=async e=>{let t=e.run??el,{plans:r}=await Ks(e.ids,e.probeDeps),n=[];for(let o of r){let s=If(o,e.mode);if(s!==null){n.push(s);continue}n.push(xE(o,t(o.recipe,o.context)))}return n},nl=async(e,t)=>{let{plans:r}=await Ks(e,t);return r.map(n=>If(n,"converge")??tl(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import TE from"node:process";import{z as N}from"zod";var CE=()=>{let{link:e,node:t}=Po();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},AE=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 yi(e)}},$E=e=>{let t=e.method==="copy"?"copied":"linked";switch(e.outcome){case"created":return`${t} Node ${e.version} to ~/.infra-kit/node`;case"refreshed":return`re-${t} Node ${e.version} to ~/.infra-kit/node`;case"unchanged":return`~/.infra-kit/node is already Node ${e.version}`;case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-platform":return"skipped \u2014 no portless OS service on this platform";case"failed":return"could not write ~/.infra-kit/node \u2014 see the debug log";default:return yi(e.outcome)}},IE=async e=>{let t=yd(e.link);l.info(` ${t.outcome.padEnd(9)} portless link \u2014 ${AE(t.outcome)}`);let r=vd(e.node);l.info(` ${r.outcome.padEnd(9)} portless node \u2014 ${$E(r)}`);let n=Ro(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return;let{state:o,stableNode:s}=await em(e.target,n);o!=="converged"&&(l.info("Run this yourself to finish the portless service:"),l.info(` ${st(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s})}`))},Of="--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.",DE=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||r))throw new Error(Of);return{ids:e.tools??t??_t,mode:r?"update":"converge",skipTools:n}},Df=(e,t)=>e instanceof Sr?e.step:t.at(-1)?.step??"zshrc",OE=async()=>{let e=[],t=r=>{e.push(r),r.message!==bn&&rs(r)};try{return await Pa(t),{entries:e,failed:!1}}catch(r){let n={step:Df(r,e),outcome:"warned",message:`The ${Df(r,e)} step failed: ${r instanceof Error?r.message:String(r)}`,level:"warn"};return rs(n),e.push(n),{entries:e,failed:!0}}},NE=async(e,t,r)=>{for(let n of e)l.info(` ${n.action.padEnd(9)} ${n.id} \u2014 ${n.detail}`);for(let n of e)if(_E(n,t)){l.info(`Run these yourself to ${t?"set up":"finish"} ${n.id}:`);for(let o of n.commands)l.info(` ${o}`)}await IE(r),l.info(bn)},_E=(e,t)=>e.commands.length===0?!1:e.action==="refused"||t&&e.action==="skipped",ME=e=>({step:e.step,outcome:e.outcome,message:e.message}),qs=async(e={})=>{let t=DE(e),r=await OE(),n=t.skipTools?await nl(t.ids,e.probeDeps):await rl({ids:t.ids,mode:t.mode,probeDeps:e.probeDeps,run:e.run});await NE(n,t.skipTools,e.portlessDeps??CE());let o={init:r.entries.map(ME),tools:n,converged:!t.skipTools,changed:n.some(s=>s.action==="installed"||s.action==="updated"),allSucceeded:n.every(s=>s.action!=="failed")};return(r.failed||!o.allSucceeded)&&(TE.exitCode=1),{content:k(JSON.stringify(o,null,2)),structuredContent:o}},jE=N.object({step:N.enum(["zshrc","zshenv","migrations","user-config","guidance","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:N.enum(["written","unchanged","skipped","warned"]).describe("What that step did: changed something, found nothing to change, did not run, or failed non-fatally"),message:N.string().describe("The same line a human running this would have read")}),FE=N.object({id:N.string().describe("Dependency id"),action:N.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:N.object({present:N.boolean(),onPath:N.boolean(),version:N.string().nullable(),manager:N.string()}).describe("The tool\u2019s state before this run"),commands:N.array(N.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:N.string().describe("Why, in one line")}),LE={init:N.array(jE).describe("One entry per init step, in the order they ran"),tools:N.array(FE).describe("One result per requested dependency"),converged:N.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:N.boolean().describe("Whether anything was installed or updated"),allSucceeded:N.boolean().describe("Whether no tool failed (a refusal is not a failure)")},JE={tools:N.array(N.enum(_t)).optional().describe("Which tools to act on. Omit for all five."),mode:N.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:N.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},ol=b({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, aws, gh, doppler and portless to a working state \u2014 installing what is missing and updating what is present. Pass mode:"update" to update only and never install, or skipTools:true to do the local setup and then REPORT what each tool needs without installing anything. Recipes that need sudo or pipe a script fetched over the network \u2014 the Homebrew bootstrap and the first AWS CLI install \u2014 are never run; they are reported with the exact commands for you to run yourself. Use `doctor` first to see the state of this machine without changing it.',inputSchema:JE,outputSchema:LE,requiresHumanConfirm:!0,handler:e=>qs({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Mf}from"node:fs";import jf from"node:path";import zE from"node:process";import{z as nt}from"zod";import{createHash as VE}from"node:crypto";import{readFileSync as BE}from"node:fs";var sl=e=>VE("sha256").update(BE(e)).digest("hex");import{readFileSync as HE,writeFileSync as W0}from"node:fs";import _f from"node:path";import{z as Ve}from"zod";var tt="vendor",WE=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),GE=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),UE=[".tsbuildinfo"],il=e=>WE.has(e),al=e=>GE.has(e)?!0:UE.some(t=>e.endsWith(t)),Nf=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>il(o))||al(r)};import{readdirSync as KE}from"node:fs";import cl from"node:path";var qE=e=>e.split(cl.sep).join("/"),ll=e=>{let t=[],r=n=>{for(let o of KE(n,{withFileTypes:!0})){let s=cl.join(n,o.name);if(o.isDirectory()){if(il(o.name))continue;r(s);continue}al(o.name)||t.push(qE(cl.relative(e,s)))}};return r(e),t.sort()};var rt=".sync-manifest.json",dl=1,YE=Ve.object({schemaVersion:Ve.number().optional(),source:Ve.string(),commit:Ve.string(),syncedAt:Ve.string(),fileCount:Ve.number(),files:Ve.record(Ve.string(),Ve.string())}),pl=e=>(e.schemaVersion??dl)>dl;var ul=e=>{let t=_f.join(e,rt),r;try{r=HE(t,"utf8")}catch{throw new Error(`Missing ${rt} at ${t}`)}let n=YE.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${rt} at ${t}: ${Ve.prettifyError(n.error)}`);return n.data};var ml=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Nf(c))),n=ll(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}sl(_f.join(e,c))!==r[c]&&o.push(c)}let i=new Set(n),a=Object.keys(r).filter(c=>!i.has(c));return{modified:o,added:s,removed:a}};var fl=30,gl=(e,t)=>{if(t.length!==0){l.info(`
|
|
409
|
-
${e} (${t.length}):`);for(let r of t.slice(0,
|
|
410
|
-
`)},
|
|
380
|
+
`),g.addOption("--yes",!0),await jr({versionId:u.id,...I?{description:y.description}:{},...j?{releaseDate:y.releaseDate}:{}},i),I&&await Is({branch:a,body:Gn(F,y.description)}),l.info(`\u2705 Updated ${v.join(" and ")} for ${p}`),l.info(`\u{1F517} Jira Version: ${F}`),l.info(`\u{1F517} PR branch: ${a}
|
|
381
|
+
`),g.print(),C(!0)},tl=b({name:"release-edit",description:"Edit a release's description and/or planned release date in Jira; a changed description is mirrored into the 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. `version` and at least one of `description`/`releaseDate` are required for MCP calls (the picker and prompts are unreachable without a TTY). Empty string clears a field. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:Ee.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ee.string().optional().describe("New description. Empty string clears the description."),releaseDate:Ha.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ee.string().describe("Release version"),branch:Ee.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ee.string().describe("Jira fix version URL"),previousDescription:Ee.string().describe("The description before the update"),newDescription:Ee.string().describe("The description after the update"),previousReleaseDate:Ee.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ee.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ee.array(Ee.enum($f)).describe("The fields whose value actually changed"),changed:Ee.boolean().describe("Whether anything actually changed")},handler:Us});import{z as D}from"zod";import{$ as al}from"zx";import If from"node:fs/promises";import Ks from"node:path";var rl=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Ks.dirname(t),o;try{o=await If.readFile(t,"utf-8")}catch(p){throw new Error(`Cursor workspace file not found at ${t}: ${p.message}`)}let s;try{s=JSON.parse(o)}catch(p){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${p.message}`)}let i=s.folders??[],a=new Set(i.map(p=>Ks.resolve(n,p.path))),c=[],d=[];for(let p of r){let u=Ks.resolve(p);if(a.has(u)){d.push(p);continue}let m=Ks.relative(n,u);i.push({path:m}),a.add(u),c.push(p)}return s.folders=i,await If.writeFile(t,`${JSON.stringify(s,null,2)}
|
|
382
|
+
`,"utf-8"),{added:c,skipped:d}};import{$ as qE}from"zx";var nl=async e=>{await qE`cursor ${e}`};import Df from"node:fs/promises";import qs from"node:path";var ol=async e=>{let{workspacePath:t,folderPaths:r}=e,n=qs.dirname(t),o;try{o=await Df.readFile(t,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${t}: ${m.message}`)}let s;try{s=JSON.parse(o)}catch(m){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],a=new Set(r.map(m=>qs.resolve(m))),c=new Set,d=i.filter(m=>{let h=qs.resolve(n,m.path);return a.has(h)?(c.add(h),!1):!0});s.folders=d,await Df.writeFile(t,`${JSON.stringify(s,null,2)}
|
|
383
|
+
`,"utf-8");let p=[],u=[];for(let m of r){let h=qs.resolve(m);c.has(h)?p.push(m):u.push(m)}return{removed:p,notFound:u}};import Of from"node:path";var co=(e,t)=>Of.isAbsolute(e)?e:Of.resolve(t,e);var sl=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await $(),s=ut(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await HE({ide:c,projectRoot:t,folderPaths:i}));return a},HE=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return l.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),{ran:!1,provider:"cursor",added:0,skipped:0};let o=co(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await rl({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return l.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await nl(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var Qt=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await $(),s=ut(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await zE({ide:c,projectRoot:t,folderPaths:i}));return a},zE=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=co(t.config.workspaceConfigPath,r);try{let{removed:s}=await ol({workspacePath:o,folderPaths:n});return s.length>0&&l.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return l.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var er=["workspace","none"];import{z as Nf}from"zod";var jf=2500,Hs="release-remove",_f=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),YE=e=>e.version===void 0||e.version==="",XE=async()=>{try{return{outcome:"listed",prs:await O()}}catch(e){return e instanceof f&&e.operation===Hn?{outcome:"empty"}:{outcome:"failed"}}},Mf=(e,t)=>(e===null?l.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Hs}`}):e.outcome==="failed"?l.info({msg:`Tool execution form enumeration failed (gh pr list): ${Hs}`}):l.info({msg:`Tool execution form options empty (open release PRs): ${Hs}`}),null),ZE=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Cs(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(H(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},QE=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(l.info({msg:`Tool execution form descriptions unavailable (timeout): ${Hs}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},il=(e={})=>{let t=e.fetchBudgetMs??jf;return{message:"Choose the release to remove. Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve.",isFormable:r=>_f(r)&&YE(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Qr(XE(),t),Qr(z(),t)]);if(r===null||r.outcome!=="listed")return Mf(r,t);let o=ZE(r.prs,n);return o.length===0?Mf({outcome:"empty"},t):Nf.object({version:Nf.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${QE(o,n,t)}Nothing runs yet: the confirm gate follows, and the agent will show you the resolved arguments to approve. Removal deletes the worktree, closes the PR, deletes both branches AND removes the Jira fix version \u2014 the last is irreversible.`)})},toArgs:(r,n)=>typeof r.version!="string"?null:{..._f(n)?n:{},version:r.version}}};var Ff=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],Ys={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"},tr="remove a release",Te=e=>{throw l.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},Lf=(e,t)=>{throw l.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new T({...e,agentMode:A.source},2,t)},eP=e=>{Y()&&(e.version||Lf({status:"argument_required",argument:"version"},{operation:tr,remediation:"pass --version <ref> (a release version or name) on the re-run \u2014 `infra-kit release list --json` lists the candidates",stderrExcerpt:"release remove reached the handler without --version under agent mode"}),e.skipJira&&Lf({status:"refused"},{operation:tr,remediation:"drop --skip-jira \u2014 under agent mode the fix version is checked and removed with the release; to keep it, ask a human to run `infra-kit release remove --skip-jira` from their own terminal",stderrExcerpt:"--skip-jira is not permitted under agent mode: it would tear down the branch and PR and leave a live Jira fix version behind with nothing in the result pointing at it"}))},Jf=e=>{e.pr?.state==="MERGED"&&Te({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`})},tP=(e,t)=>{if(t.skipJira||(e.jiraConfig||Te({operation:`remove release ${e.label}`,remediation:"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:r,fixCount:n,affectsCount:o}=e.jira;(r.released||r.archived)&&Te({operation:`remove Jira fix version "${r.name}"`,remediation:"un-release it in Jira first, or remove the release without it via --skip-jira",stderrExcerpt:`fix version "${r.name}" is already ${r.released?"released":"archived"}`}),!(n===0&&o===0)&&(e.moveIssuesTo||Te({operation:`remove Jira fix version "${r.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:`${r.name} is set as fixVersion on ${n} issue(s) and as affectsVersion on ${o} issue(s)`}))},rP=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Te({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"})},nP=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Te({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(", ")}`})},oP=async e=>(await al`git -C ${e} status --porcelain`).stdout.split(`
|
|
384
|
+
`).map(r=>r.trimEnd()).filter(r=>r.length>0),sP=async e=>{try{let{terminals:t}=await op(e);return t.filter(r=>r.connected).length}catch(t){return l.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},iP=async e=>{let t=await Fo([e]);if(t!==null)throw l.warn({operation:tr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new T({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:tr,remediation:`re-run from a terminal that is not an Orca pane of ${t} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${t}, which the removal would close`})},aP=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await Qe();if(!n)return r;let o=await Ze(H(e),n),s=t.moveIssuesTo?await cP(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await ms(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:Jt(n,o)}}},cP=async(e,t)=>{let r=await Ze(e,t);return r||Te({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}"`})},lP=async(e,t)=>{let r=L(e);r||Te({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 n=await R(),o=`${n}${ge}`,s=`${o}/${e}`,[i,a,c,d]=await Promise.all([he("release"),zr(e),sn(n,`refs/heads/${e}`),Do(n,e)]),p=i.includes(e);return p&&await iP(s),{...await aP(r,t),branch:e,id:r,label:W(r),baseBranch:a?.baseRefName??Je("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:p,orcaTerminalCount:p?await sP(s):0,worktreeDirty:p?await oP(s):null,localTipSha:c,remoteTipSha:d,pr:a}},Vf=e=>({branch:e.branch,label:e.label,baseBranch:e.baseBranch,worktreePath:e.worktreePath,worktreePresent:e.worktreePresent,worktreeDirty:e.worktreeDirty,orcaTerminalCount:e.orcaTerminalCount,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}),dP=(e,t)=>{if(t)return"skipped (--skip-jira)";if(!e.jiraConfig)return"skipped (Jira not configured)";if(!e.jira)return"none found";let{version:r,fixCount:n,affectsCount:o}=e.jira,s=`fixVersion on ${n} issue(s), affectsVersion on ${o} issue(s)`,i=e.moveIssuesTo?`, reassigned to ${e.moveIssuesTo.name}`:"";return`${r.name} \u2014 ${s}${i}`},pP=(e,t)=>{let r=e.pr?`#${e.pr.number} (${e.pr.state})`:"none",n=[`Remove release ${e.label} (${e.branch})? This will:`,` \u2022 worktree: ${e.worktreePresent?e.worktreePath:"none"}`,` \u2022 PR: ${r}`,` \u2022 local branch: ${e.localTipSha??"absent"} (switching to ${e.baseBranch} first)`,` \u2022 remote branch: ${e.remoteTipSha??"absent"}`,` \u2022 Jira version: ${dP(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
|
|
385
|
+
`)},zs=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},uP=e=>typeof e=="string"?e:e.outcome;async function lo(e,t,r){try{let n=await r(),o=uP(n);return t.push({step:e}),l.info({step:e,outcome:o},`\u2705 ${Ys[e]} \u2014 ${o}`),n}catch(n){throw new zs(e,n)}}var mP=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),l.warn({err:Et(n),step:e},`\u26A0\uFE0F ${Ys[e]} failed (non-blocking)`)}},fP=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,gP=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(u=>fP(t,u)).join(", ")||"nothing",i=t.jira?`The Jira fix version ${t.jira.version.name} was NOT removed. `:"",a=t.localTipSha?`Restore the branch with \`git branch ${t.branch} ${t.localTipSha}\`. `:"",c=`Re-run \`infra-kit release remove --version ${t.label}\` to finish; completed steps are skipped.`,d=`completed: ${s}. ${i}${a}${c}`,p=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Ff.indexOf(r)+1} of ${Ff.length} (${Ys[r]})`,remediation:p?`${p} \u2014 ${d}`:d})},hP=async e=>{let t=await Zn(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:t.includes(e.branch)?"removed":"absent",removedBranches:t}},vP=e=>{let t=e.map(s=>({provider:s.provider,outcome:yP(s),removed:s.removed})),r=t.some(s=>s.outcome==="verified"),o=t.some(s=>s.outcome==="attempted")?"attempted":"skipped";return{outcome:r?"verified":o,providers:t}},yP=e=>e.removed.length>0?"verified":"attempted",wP=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await mP("ide-folders",r,async()=>{let o=await Qt({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=vP(o)}),l.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${Ys["ide-folders"]} \u2014 ${n.outcome}`),n},kP=async e=>{let t=await zr(e.branch);if(Jf({...e,pr:t}),!t)return{outcome:"absent",number:null};if(t.state==="CLOSED")return{outcome:"already-closed",number:t.number};let r=`Closed by \`infra-kit release remove\`: release ${e.label} was torn down.`;return await al`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},bP=async e=>(await lr()===e.branch&&await al`git switch ${e.baseBranch}`,await $o(e.branch),await Ld(e.branch)?Te({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"),RP=async e=>(await Io(e.branch),e.remoteTipSha?"deleted":"absent"),EP=async(e,t,r)=>{let n=await ms(t.version.id,r);if(n.issuesFixedCount===t.fixCount&&n.issuesAffectedCount===t.affectsCount)return;let o=`re-run \`infra-kit release remove --version ${e.label}\``;Te({operation:`remove Jira fix version "${t.version.name}"`,remediation:`the fix version was NOT removed and every other step is complete \u2014 ${o} so the guard re-evaluates the new counts`,stderrExcerpt:`issue counts changed since preflight: fixVersion ${t.fixCount} \u2192 ${n.issuesFixedCount}, affectsVersion ${t.affectsCount} \u2192 ${n.issuesAffectedCount}`})},PP=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await EP(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 Ka({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),SP=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree.outcome,ideFolders:t.ideFolders,pr:t.pr.outcome,prNumber:t.pr.number,localBranch:t.localBranch,localTipSha:e.localTipSha,remoteBranch:t.remoteBranch,remoteTipSha:e.remoteTipSha,jira:t.jira,jiraVersion:e.jira?{id:e.jira.version.id,name:e.jira.version.name,url:e.jira.url}:null}),xP=async(e,t,r)=>{let n=await lo("worktree",r,()=>hP(e)),o=await wP(e,n.removedBranches,r),s=await lo("pr",r,()=>kP(e));l.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await lo("local-branch",r,()=>bP(e)),a=await lo("remote-branch",r,()=>RP(e)),c=await lo("jira",r,()=>PP(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},TP=async(e,t)=>{let r=[];try{return SP(e,await xP(e,t,r))}catch(n){throw n instanceof zs?gP({plan:e,step:n.step,done:r,cause:n.reason}):n}},CP=async e=>{if(e)return tt(e);g.setInteractive();let[t,r]=await Promise.all([z(),O()]),n=r.map(s=>s.branch);n.length===0&&Te({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 o=new Map(r.map(s=>[s.branch,s.type]));try{return await Rt(oe({branches:n,descriptions:t,types:o}))}catch(s){throw ce(s)?s:new f(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},Wf=il(),Xs=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await pe({operation:tr}),await $(),await be({provider:Wf,params:e,operation:tr,argument:"version"}),eP(e);try{let s=await lP(await CP(r),e);l.debug({plan:Vf(s)},"release remove: resolved plan"),Jf(s),tP(s,e),rP(s),await Wn({operation:`remove release ${s.label}`,base:s.baseBranch}),nP(s),g.addOption("--version",s.label),n&&g.addOption("--move-issues-to",n),o&&g.addOption("--skip-jira",!0),await Z(t,pP(s,!!o),{throwOnDecline:!0,plan:{...Vf(s),skipJira:!!o}}),t||g.addOption("--yes",!0);let i=await TP(s,e);return g.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw ce(s)||Lo(s)||s instanceof f?s:(l.error({err:Et(s)},"\u274C Error removing release"),new f(s,{operation:tr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},cl=b({name:"release-remove",description:'Tear down ONE release created by release-create: removes its git worktree (closing every Orca terminal open in it first \u2014 a call made from an Orca terminal inside that worktree is refused as orca_caller_inside_target before anything is touched), strips the worktree from the Cursor workspace, closes its pull request with a comment, deletes the release branch locally and on origin, and REMOVES ITS JIRA FIX VERSION \u2014 the one irreversible step (new id, new URL, lost issue links), which is why every call is gated behind human confirmation. Omit "version" and this server offers the human a form listing the open release PRs; the accepted choice feeds the confirm gate. A client that cannot render a form gets a gate with no version \u2014 confirming it is refused, never guessed. Pass "version" when the human already named the release. One release per call \u2014 repeat the call for another; there is no "versions" field. Refuses before any mutation when the PR is MERGED (the release has shipped), when the fix version is released/archived, when the fix version still carries issues (pass "moveIssuesTo" to reassign them), or when nothing named that version exists. skipJira is CLI-only and has no field here: it would leave a live fix version behind with nothing in the result pointing at it. Resumable: every step is a verified no-op when its artefact is already gone, so a re-run finishes a partial teardown. What is lost with the worktree directory: gitignored contents including a hydrated .env of Doppler secrets (re-fetch with env-load) and node_modules/dist.',requiresHumanConfirm:!0,formProvider:Wf,inputSchema:{version:D.string().optional().describe('The release version or name to remove (e.g. "1.2.5" or "checkout-redesign"). Omit it to be offered the open release PRs.'),moveIssuesTo:D.string().optional().describe(`Optional. An EXISTING Jira fix version name (exactly as in Jira, e.g. "v1.2.6") to move this release's issues to before its fix version is removed \u2014 both fixVersion and affectsVersion. Pass it only after a refusal reported the issue counts, or when the human named the target; a name Jira does not know is refused in preflight before anything is touched.`),confirm:D.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:D.string().describe("The release branch that was targeted"),version:D.string().describe('The release label (e.g. "1.2.5")'),baseBranch:D.string().describe("The branch HEAD was moved to before the local delete"),worktree:D.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:D.object({outcome:D.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:D.array(D.object({provider:D.string(),outcome:D.enum(["verified","attempted","skipped"]),removed:D.array(D.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:D.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:D.number().nullable().describe("The pull request number, or null when none exists"),localBranch:D.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:D.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:D.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:D.string().nullable().describe("The origin tip before deletion"),jira:D.enum(["removed","absent","skipped"]).describe('"removed" when the fix version was deleted; "absent" when Jira knows none for this release (the resume path); "skipped" only on the CLI with --skip-jira'),jiraVersion:D.object({id:D.string(),name:D.string(),url:D.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Xs});import{spawnSync as DP}from"node:child_process";import{homedir as OP}from"node:os";import NP from"node:process";var AP=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},$P=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},IP=(e,t)=>{let r=AP(e);if(r===null)return[];let n=[];return t.present.includes(r)||n.push("manager-absent"),t.owner!==null&&t.owner!==r&&n.push("manager-mismatch"),n},po=(e,t)=>{let r=[...$P(e),...IP(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},uo=e=>e.steps.map(gd);var _P=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],MP=e=>{let t={...fd(e)};for(let r of _P)delete t[r];return t},ll=(e,t,r={})=>{let n=r.spawnSync??DP,o=r.env??NP.env,s=(r.agentMode??Y)(),i=uo(e),a=po(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:LP({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??jP}):{ran:!1,commands:i,refusedBecause:a.reasons}},jP=e=>{l.info(e)},Gf=64,FP=Gf*1024*1024,LP=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=MP(r);for(let[i,a]of e.steps.entries()){o(` ${"running".padEnd(9)} ${n[i]}`);let c=t(a[0],a.slice(1),{stdio:["ignore","pipe","pipe"],encoding:"utf8",maxBuffer:FP,cwd:OP(),env:s}),d=UP(c);if(d!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:d}}return{ran:!0,ok:!0,commands:n}},VP=5,JP=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Bf=e=>e==null?[]:String(e).split(`
|
|
386
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),WP=e=>{let t=Bf(e.stderr),r=Bf(e.stdout),n=[...t,...r].filter(s=>JP.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-VP).join(" / ")},BP="ENOBUFS",GP=e=>e.error?.code===BP,UP=e=>{if(GP(e))return`terminated after exceeding the ${Gf} 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 t=WP(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var KP=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},qP=e=>{let t=ke(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},HP=(e,t)=>{let r=qP(e),n={...t,owner:e.present?e.manager:null};if(r===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=po(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:uo(r),context:n}},Zs=async(e=Ft,t=Cn())=>{let r=await $n(Ft,t),n={owner:null,present:KP(r)},o=Ja(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>HP(s.get(a),n)),context:n}};var dl=(e,t)=>({...mo(e),action:"skipped",commands:e.commands,detail:t}),mo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Uf=(e,t)=>e.action==="none"?dl(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?dl(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...mo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},zP=(e,t)=>t.ran?t.ok?{...mo(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...mo(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...mo(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},pl=async e=>{let t=e.run??ll,{plans:r}=await Zs(e.ids,e.probeDeps),n=[];for(let o of r){let s=Uf(o,e.mode);if(s!==null){n.push(s);continue}n.push(zP(o,t(o.recipe,o.context)))}return n},ul=async(e,t)=>{let{plans:r}=await Zs(e,t);return r.map(n=>Uf(n,"converge")??dl(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import YP from"node:process";import{z as N}from"zod";var XP=()=>{let{link:e,node:t}=xo();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},ZP=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 Si(e)}},QP=e=>{let t=e.method==="copy"?"copied":"linked";switch(e.outcome){case"created":return`${t} Node ${e.version} to ~/.infra-kit/node`;case"refreshed":return`re-${t} Node ${e.version} to ~/.infra-kit/node`;case"unchanged":return`~/.infra-kit/node is already Node ${e.version}`;case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-platform":return"skipped \u2014 no portless OS service on this platform";case"failed":return"could not write ~/.infra-kit/node \u2014 see the debug log";default:return Si(e.outcome)}},eS=async e=>{let t=$d(e.link);l.info(` ${t.outcome.padEnd(9)} portless link \u2014 ${ZP(t.outcome)}`);let r=Ad(e.node);l.info(` ${r.outcome.padEnd(9)} portless node \u2014 ${QP(r)}`);let n=So(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return;let{state:o,stableNode:s}=await fm(e.target,n);o!=="converged"&&(l.info("Run this yourself to finish the portless service:"),l.info(` ${lt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s})}`))},qf="--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.",tS=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.skipTools===!0;if(n&&(e.tools!==void 0||r))throw new Error(qf);return{ids:e.tools??t??Ft,mode:r?"update":"converge",skipTools:n}},Kf=(e,t)=>e instanceof Sr?e.step:t.at(-1)?.step??"zshrc",rS=async()=>{let e=[],t=r=>{e.push(r),r.message!==Pn&&is(r)};try{return await Da(t),{entries:e,failed:!1}}catch(r){let n={step:Kf(r,e),outcome:"warned",message:`The ${Kf(r,e)} step failed: ${r instanceof Error?r.message:String(r)}`,level:"warn"};return is(n),e.push(n),{entries:e,failed:!0}}},nS=async(e,t,r)=>{for(let n of e)l.info(` ${n.action.padEnd(9)} ${n.id} \u2014 ${n.detail}`);for(let n of e)if(oS(n,t)){l.info(`Run these yourself to ${t?"set up":"finish"} ${n.id}:`);for(let o of n.commands)l.info(` ${o}`)}await eS(r),l.info(Pn)},oS=(e,t)=>e.commands.length===0?!1:e.action==="refused"||t&&e.action==="skipped",sS=e=>({step:e.step,outcome:e.outcome,message:e.message}),Qs=async(e={})=>{let t=tS(e),r=await rS(),n=t.skipTools?await ul(t.ids,e.probeDeps):await pl({ids:t.ids,mode:t.mode,probeDeps:e.probeDeps,run:e.run});await nS(n,t.skipTools,e.portlessDeps??XP());let o={init:r.entries.map(sS),tools:n,converged:!t.skipTools,changed:n.some(s=>s.action==="installed"||s.action==="updated"),allSucceeded:n.every(s=>s.action!=="failed")};return(r.failed||!o.allSucceeded)&&(YP.exitCode=1),{content:k(JSON.stringify(o,null,2)),structuredContent:o}},iS=N.object({step:N.enum(["zshrc","zshenv","migrations","user-config","guidance","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:N.enum(["written","unchanged","skipped","warned"]).describe("What that step did: changed something, found nothing to change, did not run, or failed non-fatally"),message:N.string().describe("The same line a human running this would have read")}),aS=N.object({id:N.string().describe("Dependency id"),action:N.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:N.object({present:N.boolean(),onPath:N.boolean(),version:N.string().nullable(),manager:N.string()}).describe("The tool\u2019s state before this run"),commands:N.array(N.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:N.string().describe("Why, in one line")}),cS={init:N.array(iS).describe("One entry per init step, in the order they ran"),tools:N.array(aS).describe("One result per requested dependency"),converged:N.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:N.boolean().describe("Whether anything was installed or updated"),allSucceeded:N.boolean().describe("Whether no tool failed (a refusal is not a failure)")},lS={tools:N.array(N.enum(Ft)).optional().describe("Which tools to act on. Omit for all six."),mode:N.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:N.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},ml=b({name:"setup",description:'Set this machine up in one call: inject the shell integration into .zshrc and the session-env block into .zshenv, run the config migrations, seed the user-global config, refresh the agent-instruction files, register the Claude Code plugin pointer and install or update the skills plugin (the `/infra-kit:*` skills drive the infra-kit CLI on PATH; a leftover .mcp.json entry is reported, never written), then bring brew, git, 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:lS,outputSchema:cS,requiresHumanConfirm:!0,handler:e=>Qs({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Yf}from"node:fs";import Xf from"node:path";import wS from"node:process";import{z as st}from"zod";import{createHash as dS}from"node:crypto";import{readFileSync as pS}from"node:fs";var fl=e=>dS("sha256").update(pS(e)).digest("hex");import{readFileSync as vS,writeFileSync as CG}from"node:fs";import zf from"node:path";import{z as We}from"zod";var nt="vendor",uS=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),mS=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),fS=[".tsbuildinfo"],gl=e=>uS.has(e),hl=e=>mS.has(e)?!0:fS.some(t=>e.endsWith(t)),Hf=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>gl(o))||hl(r)};import{readdirSync as gS}from"node:fs";import vl from"node:path";var hS=e=>e.split(vl.sep).join("/"),yl=e=>{let t=[],r=n=>{for(let o of gS(n,{withFileTypes:!0})){let s=vl.join(n,o.name);if(o.isDirectory()){if(gl(o.name))continue;r(s);continue}hl(o.name)||t.push(hS(vl.relative(e,s)))}};return r(e),t.sort()};var ot=".sync-manifest.json",wl=1,yS=We.object({schemaVersion:We.number().optional(),source:We.string(),commit:We.string(),syncedAt:We.string(),fileCount:We.number(),files:We.record(We.string(),We.string())}),kl=e=>(e.schemaVersion??wl)>wl;var bl=e=>{let t=zf.join(e,ot),r;try{r=vS(t,"utf8")}catch{throw new Error(`Missing ${ot} at ${t}`)}let n=yS.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${ot} at ${t}: ${We.prettifyError(n.error)}`);return n.data};var Rl=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Hf(c))),n=yl(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}fl(zf.join(e,c))!==r[c]&&o.push(c)}let i=new Set(n),a=Object.keys(r).filter(c=>!i.has(c));return{modified:o,added:s,removed:a}};var El=30,Pl=(e,t)=>{if(t.length!==0){l.info(`
|
|
387
|
+
${e} (${t.length}):`);for(let r of t.slice(0,El))l.info(` ${r}`);t.length>El&&l.info(` \u2026and ${t.length-El} more`)}},ei=async(e={})=>{let t=e.cwd??await R(),r=Xf.join(t,nt),n={modified:[],added:[],removed:[],fileCount:0};if(!Yf(r)){l.info(`\u2139\uFE0F No ${nt}/ folder found \u2014 nothing to check.`);let p={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}if(!Yf(Xf.join(r,ot))){l.error(`\u274C Missing ${nt}/${ot}. Re-run the vendor sync to generate it.`);let p={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}let o=bl(r);if(kl(o)){l.error(`\u274C ${nt}/${ot} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let p={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}let{modified:s,added:i,removed:a}=Rl(r,o),c=s.length>0||i.length>0||a.length>0;c?(l.error(`\u274C ${nt}/ has drifted from ${nt}/${ot}.`),l.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Pl("Modified",s),Pl("Added (not in manifest)",i),Pl("Removed (in manifest, now missing)",a)):l.info(`\u2705 ${nt}/ matches manifest (${o.fileCount} files).`);let d={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},kS={status:st.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:st.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:st.number(),modified:st.array(st.string()),added:st.array(st.string()),removed:st.array(st.string())},Sl=b({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:kS,handler:()=>ei({cwd:wS.cwd()})});import Zf from"node:process";import{z as fo}from"zod";var Qf=async e=>{try{return await e()}catch{return null}},ti=async()=>{let e=G.version;l.info(e);let t=await Qf(R),r=t===null?null:await Qf(()=>cr(t)),n={version:e,cwd:Zf.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Zf.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},xl=b({name:"version",description:"Print the installed infra-kit CLI version and where this process runs (cwd, repo root, main repo root, CLAUDE_PROJECT_DIR)",inputSchema:{},outputSchema:{version:fo.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:fo.string().describe("The working directory of this process"),repoRoot:fo.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:fo.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:fo.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:ti});import tg from"@inquirer/confirm";import bS from"node:path";import{z as M}from"zod";import{$ as go}from"zx";var RS="feature",ES="release",ri="create worktrees",PS=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Tl=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),ni=async e=>{let{confirmedCommand:t,all:r,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await pe({operation:ri});try{let a=await he("release"),c=await R(),d=`${c}${ge}`;await eg(`${d}/${ES}`),await eg(`${d}/${RS}`);let p=[];if(n)p=n.split(",").map(Be=>De(Se(Be.trim())));else{let Be=await O(),it=Be.map($e=>$e.branch);if(it.length===0){l.info("\u2139\uFE0F No open release branches found"),g.print();let $e={createdWorktrees:[],count:0,...Tl()};return{content:k(JSON.stringify($e,null,2)),structuredContent:$e}}if(r)p=it;else{g.setInteractive();let $e=new Map(Be.map(sd=>[sd.branch,sd.type])),zg=await z();p=await Yr(oe({branches:it,descriptions:zg,types:$e}),{required:!0})}}r?g.addOption("--all",!0):g.addOption("--versions",Ht(p));let u=await $(),m=i??(ut(u).length>0?"workspace":"none");g.addOption("--ide",m);let h=await SS(o,u),y=await xS(s,u),v=await cr(c),I=bS.basename(v),j=y?await TS({explicit:s!==void 0,mainRepoRoot:v}):null;await Z(t,CS(j,I)),t||g.addOption("--yes",!0);let F=j?await AS(j,v):null,{branchesToCreate:C}=OS({selectedReleaseBranches:p,currentWorktrees:a}),E=await NS(C,d);if(_S(E),m==="workspace"&&await sl({projectRoot:c,worktreeDir:d,branches:E}),h)for(let Be of E)await go`github ${d}/${Be}`,await go`sleep 5`;let B=F?await IS({registration:F,createdWorktrees:E,worktreeDir:d,mainRepoRoot:v,repoName:I,config:u}):Tl();DS(B),g.print();let Pe={createdWorktrees:E,count:E.length,...B};return{content:k(JSON.stringify(Pe,null,2)),structuredContent:Pe}}catch(a){throw ce(a)||a instanceof T?a:(l.debug({err:a},"Error managing worktrees"),new f(a,{operation:ri,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},SS=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await x(o=>tg({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&g.setInteractive(),g.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},xS=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await x(o=>tg({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&g.setInteractive(),g.addOption(n?"--orca":"--no-orca",!0),n},rg=e=>e==="absent"?{reason:"orca_absent",text:"the orca CLI is not installed (Orca \u2192 Settings \u2192 Experimental \u2192 CLI)"}:{reason:"orca_unreachable",text:"Orca is not running"},TS=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await dr();if(n!=="ready"){let{reason:s,text:i}=rg(n);if(t)throw l.warn({operation:ri},`\u26D4 --orca was passed but ${i}`),new T({status:"refused",reason:s,agentMode:A.source},2,{operation:ri,remediation:n==="absent"?"install Orca (brew install --cask stablyai/orca/orca) and register its CLI from Settings \u2192 Experimental \u2192 CLI, or re-run with --no-orca":"open Orca (`orca open`) and re-run, or re-run with --no-orca",stderrExcerpt:`--orca was passed but ${i}; no worktree was created`});return l.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await ip(r);return{probe:n,registered:o.registered,visibility:o.visibility}},CS=(e,t)=>{let r=["Are you sure you want to proceed with these worktree changes?"];return e?.probe==="ready"&&!e.registered&&r.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),r.join(`
|
|
388
|
+
`)},AS=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:rg(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await ap(t);return{kind:"ready",visibility:r}}catch(r){return l.warn({error:r},"\u26A0\uFE0F orca repo add failed \u2014 worktrees will be created but not opened in Orca"),{kind:"skip",reason:"orca_error",code:r instanceof jo?r.code:void 0}}},$S=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,IS=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Tl();if(t.kind==="skip"){for(let u of r)a.orcaSkipped.push({branch:u,reason:t.reason,code:t.code});return a}let c=Hd(i),d=r.length===1&&t.visibility!=="hide",p=lp();for(let u of r){let m=`${n}/${u}`;try{let{layout:h}=await dp({cwd:m,title:pp({branch:u}),focus:d,layout:"full",panes:c,poll:p});await cp(o,m)?a.orcaOpened.push({branch:u,layout:h}):a.orcaHidden.push({branch:u,path:m,fix:$S(s)})}catch(h){l.warn({error:h,branch:u},`\u26A0\uFE0F Failed to open Orca terminals for ${u}`),h instanceof jo&&h.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:u,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:u,reason:"orca_error",code:h instanceof jo?h.code:void 0})}}return a},DS=e=>{for(let t of e.orcaOpened)l.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)l.info(`\u{1F648} ${t.branch} opened in Orca but its row is hidden (${t.path}) \u2014 ${t.fix}`);for(let t of e.orcaSkipped){let r=t.code?` (${t.code})`:"";l.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},eg=async e=>{await go`mkdir -p ${e}`},OS=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Ao(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},NS=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o}`;return await go`git worktree add ${s} ${o}`,await go({cwd:s})`pnpm install`,o})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o],a=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});l.error({error:s.reason,msg:a.message})}return n},_S=e=>{if(e.length>0){l.info("\u2705 Created git worktrees:");for(let t of e)l.info(t);l.info("")}else l.info("\u2139\uFE0F No new git worktrees to create")},Cl=b({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 / Orca" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls. With "orca" true each created worktree gets an Orca terminal tab laid out per "worktrees.orca.layout"; the result reports orcaOpened, orcaSkipped (with a reason) and orcaHidden (a worktree Orca's sidebar hides, with the UI steps to reveal it). An unregistered repo is registered in Orca first (orca repo add).`,inputSchema:{all:M.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:M.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:M.enum(er).optional().describe('Editor open mode for created worktrees, applied to the configured editor (Cursor, per the "ide" config). "workspace" (the only attach style) adds each worktree to the Cursor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when an "ide" is configured \u2192 "none" otherwise.'),cursor:M.enum(er).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:M.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).'),orca:M.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{createdWorktrees:M.array(M.string()).describe("List of created git worktree branches"),count:M.number().describe("Number of git worktrees created"),orcaOpened:M.array(M.object({branch:M.string(),layout:M.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:M.array(M.object({branch:M.string(),reason:M.enum(PS),code:M.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:M.array(M.object({branch:M.string(),path:M.string(),fix:M.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:ni});import{z as en}from"zod";var oi=async()=>{await $();let e=await he("release");if(e.length===0)return l.info("\u2139\uFE0F No active worktrees found"),{content:k(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[t,r]=await Promise.all([O(),z()]),n=new Map(t.map(c=>[c.branch,c.type])),o=e.flatMap(c=>{let d=L(c);if(!d)return[];let p=W(d),u=n.get(c)||"regular",m=r.get(H(d))||null;return[{version:p,type:u,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let d=Un(c.version,c.type,s);return c.description?`${d} ${c.description}`:d});l.info(`\u{1F33F} Active worktrees:
|
|
411
389
|
|
|
412
390
|
${i.join(`
|
|
413
|
-
`)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},kl=b({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:Zr.array(Zr.object({version:Zr.string().describe("Release version"),type:Zr.enum(["regular","hotfix"]).describe("Release type"),description:Zr.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Zr.number().describe("Number of worktrees")},handler:Zs});import{z as Qt}from"zod";var mS=e=>{if(Z()){if(e.all)throw new T({status:"refused",agentMode:A.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions)throw new T({status:"argument_required",argument:"versions",agentMode:A.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions"})}},fS=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},gS=async(e,t)=>{let r=await _o(t.map(n=>`${e}/${n}`));if(r!==null)throw new T({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},Qs=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await ue({operation:"remove worktrees"}),await $(),mS({all:r,versions:n});try{let o=await ve("release");if(o.length===0){l.info("\u2139\uFE0F No active worktrees to remove"),g.print();let p={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}let s=await R(),i=`${s}${he}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(p=>De(Ee(p.trim())));else{g.setInteractive();let[p,u]=await Promise.all([X(),O()]),m=new Map(u.map(h=>[h.branch,h.type]));a=await Hr(se({branches:o,descriptions:p,types:m}),{required:!0})}fS(a,o);let c=a.length===o.length;c?g.addOption("--all",!0):g.addOption("--versions",Ut(a)),await gS(i,a),await Q(t,"Are you sure you want to proceed with these worktree changes?"),t||g.addOption("--yes",!0);let d=await qt({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await zt({projectRoot:s,worktreeDir:i,removedWorktrees:d.removed}),Yn(d),g.print(),zn({result:d,operation:"remove worktrees"})}catch(o){throw le(o)||o instanceof f?o:(l.error({error:o},"\u274C Error managing worktrees"),new f(o,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},bl=b({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. Every Orca terminal open in a removed worktree is closed first; a call made from an Orca terminal INSIDE one of the targets is refused (orca_caller_inside_target) before anything is removed \u2014 re-run it from a terminal that is not an Orca pane of that worktree.',requiresHumanConfirm:!0,inputSchema:{versions:Qt.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:Qt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Qt.array(Qt.string()).describe("List of removed git worktree branches"),failedWorktrees:Qt.array(Qt.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Qt.number().describe("Number of git worktrees removed")},handler:Qs});import{z as go}from"zod";var ei=async e=>{let{confirmedCommand:t}=e;await ue({operation:"sync worktrees"}),await $();try{let r=await ve("release"),n=await R(),o=`${n}${he}`,s=await Es();await Q(t,"Are you sure you want to proceed with these worktree changes?"),t||g.addOption("--yes",!0);let{branchesToRemove:i}=hS({releasePRsList:s,currentWorktrees:r}),a=await qt({branches:i,worktreeDir:o,projectRoot:n});return await zt({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),Yn(a),g.print(),zn({result:a,operation:"sync worktrees"})}catch(r){throw le(r)||r instanceof f?r:(l.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},hS=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>xo(s)).filter(s=>!t.includes(s))}},Rl=b({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:go.array(go.string()).describe("List of removed worktree branches"),failedWorktrees:go.array(go.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:go.number().describe("Number of worktrees removed during sync")},handler:ei});var Pl=[{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"}],Vt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:ca,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:fc,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:$c,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Gc,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Kc,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Tc,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ac,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:hc,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Qc,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Lc,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Jc,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:wl,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:kl,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:bl,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Rl,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:nc,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Qa,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:rc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Za,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:oc,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:sa,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:hl,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:ol,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:za,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:oa,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:vl,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-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"]}];var El=e=>Vt.filter(t=>t.menuGroup===e),Sl=e=>Vt.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var vS=(e,t)=>{let r=e,n;for(let o of t){if(n=r.find(s=>s.name()===o),!n)return;r=n.commands}return n},Wf=e=>Pl.flatMap(({key:t,label:r})=>El(t).flatMap(n=>{let o=vS(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import xl from"node:process";var yS="MODULE_TYPELESS_PACKAGE_JSON",wS=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Gf=!1,Tl=()=>{if(Gf)return;Gf=!0;let e=xl.emitWarning.bind(xl);xl.emitWarning=((t,...r)=>{wS(r[0],r[1])!==yS&&e(t,...r)})};import{Command as MS,InvalidArgumentError as jS}from"commander";import{resolve as FS}from"node:path";import Ae from"node:process";import{cd as LS}from"zx";import Uf from"node:process";import{$ as kS}from"zx";var Cl=async()=>{let e=await q(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await K(i.path)}))),r=t.at(-1)?.exists===!0,n=await Pn(e.userProject,r),o=r?En(n):"";l.info(`Project name: ${e.projectName}
|
|
391
|
+
`)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},Al=b({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:en.array(en.object({version:en.string().describe("Release version"),type:en.enum(["regular","hotfix"]).describe("Release type"),description:en.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:en.number().describe("Number of worktrees")},handler:oi});import{z as rr}from"zod";var MS=e=>{if(Y()){if(e.all)throw new T({status:"refused",agentMode:A.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions)throw new T({status:"argument_required",argument:"versions",agentMode:A.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions"})}},jS=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new f(void 0,{operation:"remove worktrees",remediation:`no active worktree for: ${r.join(", ")}. Run 'infra-kit worktrees list' to see current worktrees`,stderrExcerpt:`unmatched worktree target(s): ${r.join(", ")}`})},FS=async(e,t)=>{let r=await Fo(t.map(n=>`${e}/${n}`));if(r!==null)throw new T({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},si=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await pe({operation:"remove worktrees"}),await $(),MS({all:r,versions:n});try{let o=await he("release");if(o.length===0){l.info("\u2139\uFE0F No active worktrees to remove"),g.print();let p={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}let s=await R(),i=`${s}${ge}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(p=>De(Se(p.trim())));else{g.setInteractive();let[p,u]=await Promise.all([z(),O()]),m=new Map(u.map(h=>[h.branch,h.type]));a=await Yr(oe({branches:o,descriptions:p,types:m}),{required:!0})}jS(a,o);let c=a.length===o.length;c?g.addOption("--all",!0):g.addOption("--versions",Ht(a)),await FS(i,a),await Z(t,"Are you sure you want to proceed with these worktree changes?"),t||g.addOption("--yes",!0);let d=await Yt({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await Qt({projectRoot:s,worktreeDir:i,removedWorktrees:d.removed}),Yn(d),g.print(),Xn({result:d,operation:"remove worktrees"})}catch(o){throw ce(o)||o instanceof f?o:(l.error({error:o},"\u274C Error managing worktrees"),new f(o,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},$l=b({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. Every Orca terminal open in a removed worktree is closed first; a call made from an Orca terminal INSIDE one of the targets is refused (orca_caller_inside_target) before anything is removed \u2014 re-run it from a terminal that is not an Orca pane of that worktree.',requiresHumanConfirm:!0,inputSchema:{versions:rr.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:rr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:rr.array(rr.string()).describe("List of removed git worktree branches"),failedWorktrees:rr.array(rr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:rr.number().describe("Number of git worktrees removed")},handler:si});import{z as ho}from"zod";var ii=async e=>{let{confirmedCommand:t}=e;await pe({operation:"sync worktrees"}),await $();try{let r=await he("release"),n=await R(),o=`${n}${ge}`,s=await $s();await Z(t,"Are you sure you want to proceed with these worktree changes?"),t||g.addOption("--yes",!0);let{branchesToRemove:i}=LS({releasePRsList:s,currentWorktrees:r}),a=await Yt({branches:i,worktreeDir:o,projectRoot:n});return await Qt({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),Yn(a),g.print(),Xn({result:a,operation:"sync worktrees"})}catch(r){throw ce(r)||r instanceof f?r:(l.error({error:r},"\u274C Error managing worktrees"),new f(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},LS=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Ao(s)).filter(s=>!t.includes(s))}},Il=b({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:ho.array(ho.string()).describe("List of removed worktree branches"),failedWorktrees:ho.array(ho.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ho.number().describe("Number of worktrees removed during sync")},handler:ii});var Dl=[{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"}],Gt=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:va,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:Ec,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Lc,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Qc,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:tl,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Mc,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Fc,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Sc,mcpExposed:!1,mutating:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:cl,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Hc,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:zc,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Cl,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Al,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:$l,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Il,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:uc,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:cc,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:pc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:ac,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:mc,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:fa,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:Sl,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:ml,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:sc,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:ma,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:xl,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-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"]}];var Ol=e=>Gt.filter(t=>t.menuGroup===e),Nl=e=>Gt.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var VS=(e,t)=>{let r=e,n;for(let o of t){if(n=r.find(s=>s.name()===o),!n)return;r=n.commands}return n},ng=e=>Dl.flatMap(({key:t,label:r})=>Ol(t).flatMap(n=>{let o=VS(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import _l from"node:process";var JS="MODULE_TYPELESS_PACKAGE_JSON",WS=(e,t)=>typeof e=="object"&&e!==null?e.code:t,og=!1,Ml=()=>{if(og)return;og=!0;let e=_l.emitWarning.bind(_l);_l.emitWarning=((t,...r)=>{WS(r[0],r[1])!==JS&&e(t,...r)})};import{Command as sx,InvalidArgumentError as ix}from"commander";import{resolve as ax}from"node:path";import Ce from"node:process";import{cd as cx}from"zx";import sg from"node:process";import{$ as BS}from"zx";var jl=async()=>{let e=await K(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await U(i.path)}))),r=t.at(-1)?.exists===!0,n=await xn(e.userProject,r),o=r?Tn(n):"";l.info(`Project name: ${e.projectName}
|
|
414
392
|
`),l.info(`Config merge chain (later overrides earlier):
|
|
415
|
-
`);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";l.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},
|
|
416
|
-
`))},
|
|
417
|
-
`),
|
|
418
|
-
`;var
|
|
419
|
-
`),E(e)),BS=e=>e.description("List all release branches").action(async()=>{E(await Os())}),WS=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[@yyyy-mm-dd][:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"); "@yyyy-mm-dd" is the planned release date, written to the Jira fix version. Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "1.64.0@2026-10-28", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',JS,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Ga),o=n.length>0?n:void 0;E(await Fs({releases:o,confirmedCommand:t.yes}))}),GS=e=>{if(e==="")return e;try{return Lt(e)}catch(t){throw t instanceof jr?new jS(t.message):t}},US=e=>e.description("Edit a release's description and/or release date in Jira (description also in the matching GitHub PR body)").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("--release-date <yyyy-mm-dd>",'New planned release date (use "" to clear)',GS).option("-y, --yes","Skip confirmation prompt").action(async t=>{E(await Ls({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),ig=e=>e.option("-f, --from <where>",`Where the deploy runs: ${wt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),KS=e=>ig(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{E(await Nl({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),qS=e=>ig(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{E(await _l({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),HS=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{E(await $s({version:t.version,confirmedCommand:t.yes}))}),YS=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{E(await Us({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),zS=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{E(await ei({confirmedCommand:t.yes}))}),XS=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{let r=og(t.ide,"--ide")??og(t.cursor,"--cursor");E(await Xs({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),ZS=e=>e.description("List all git worktrees with detailed information").action(async()=>{E(await Zs())}),QS=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{E(await Qs({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),ex=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{E(await Fl({init:t.init}))}),tx=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Hs();E(t),t.structuredContent.ok||(Ae.exitCode=1)}),rx=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{E(await Cl())}),nx=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{E(await Al())}),ox=new Set(["version"]),ai=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Bl=()=>{let e=new MS().option("-C <dir>","Run as if infra-kit was started in <dir> instead of the current working directory"),t=e.command("release").description("Release management commands");VS(t.command("merge-dev")),BS(t.command("list")),WS(t.command("create")),US(t.command("edit")),KS(t.command("deploy-all")),qS(t.command("deploy-selected")),HS(t.command("deliver")),YS(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");XS(r.command("add")),ZS(r.command("list")),QS(r.command("remove")),zS(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");rx(n.command("path")),nx(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{E(await Ho())});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{E(await ni({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{E(await ni({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){l.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Ae.exitCode=1;return}let c=await qo({all:a.all,root:a.root,fix:a.fix,design:a.design});E(c);let{allPassed:d,fixed:p}=c.structuredContent,u=(p??[]).some(m=>m.action==="failed");(!d||u)&&(Ae.exitCode=1)});let i=e.command("vendor").description("Verify the mirrored vendor/ tree");return tx(i.command("check")),ex(i.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async a=>{let c=await ps({fix:!!a.fix});rn.enabled||ua(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(p=>p.name==="plugin installed"&&p.status==="fail")&&(Ae.exitCode=1),E(c)}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:d}=await import("./dev-server.js"),p=!!(Ae.stdout.isTTY&&Ae.stdin.isTTY);await d({...c,preset:a},p,rn.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{E(await zo())}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").action(async a=>{E(await qs({tools:a.tools,update:a.update,skipTools:a.skipTools}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{E(await Ys())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{E(await ws())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{E(await fs())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async a=>{sg(await hs({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{sg(await us())}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{E(await Dl({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{E(await ks({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{E(await $l({env:a}))}),e.commands.forEach(kd),Jl(e),Vl(e),e.hook("preAction",async(a,c)=>{let{C:d}=e.opts();d!==void 0&&LS(FS(Ae.cwd(),d)),g.start(ai(c)),rn.enabled=!!c.optsWithGlobals().json,rn.enabled&&(l.level="warn"),A.source=Eo({env:Ae.env,stdinIsTTY:Ae.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),ox.has(ai(c))||await ha()}),e.hook("postAction",(a,c)=>{let d=ai(c);if(Sl(d))return;let u=g.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",h=`infra-kit ${d}${m}`;tg({equivalent:oi(h,!0)})}),e};import sx from"node:process";var ix={exit:sx.exit,emit:E,logger:l},ag=(e,t=ix)=>le(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof T?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var Wl=(e,t=" ")=>{let r=e.reduce((n,[o])=>Math.max(n,o.length),0);return e.map(([n,o])=>`${n.padEnd(r)}${t}${o}`)};import{chalkStderr as Tx}from"chalk";import{spawn as Cx}from"node:child_process";import fe from"node:process";import{Chalk as ax}from"chalk";var Qr=new ax({level:1}),$e={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to your shell after you exit this session."},cx={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},cg={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},lg={unicode:"\u2500",ascii:"-"},lx=3,Gl=e=>e,dx={ok:e=>Qr.green(e),findings:e=>Qr.yellow(e),failed:e=>Qr.red(e),cancelled:e=>Qr.gray(e)},Kl=e=>e?{dim:t=>Qr.dim(t),bold:t=>Qr.bold(t)}:{dim:Gl,bold:Gl},px=(e,t)=>e?dx[t]:Gl,Ul=e=>[...e].length,ux=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Ul(e)<=r?e:[...e].slice(0,r).join("")},dg=e=>{let t=Kl(e.color===!0).dim,r=cx[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(ux(n,e.width))},pg=(e,t={})=>{let r=Kl(t.color===!0);return`${r.dim($e.reproPrefix.trim())} ${r.bold(e)}`},mx=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,fx=(e,t)=>e==="findings"?t!=null?`${t} ${$e.findingsSuffix}`:$e.findingsPlain:{ok:$e.ok,failed:$e.failed,cancelled:$e.cancelled}[e],gx=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<lx?"":` ${n(r.repeat(o))}`},ug=e=>{let t=e.color===!0,r=Kl(t),n=px(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?$e.reproPrefix:$e.nonReproPrefix,i=o?cg[e.outcome].ascii:cg[e.outcome].unicode,a=fx(e.outcome,e.findingsCount),c=[mx(e.durationMs)],d=e.summary?.[0]?.split(`
|
|
420
|
-
`)[0];d!=null&&d.length>0&&c.push(d);let p=`${i} ${a}`,u=`${
|
|
421
|
-
`)};var
|
|
422
|
-
`,
|
|
393
|
+
`);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";l.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Fl=async()=>{let e=await K(),t=sg.env.EDITOR||sg.env.VISUAL||"vi",r=await br(e);r.createdConfig&&l.info(Rr(r)),l.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await BS({stdio:"inherit"})`${t} ${e.userProject}`,mt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var ig="https://dashboard.doppler.com/workplace/projects",GS=(e,t)=>["Removing it locally does NOT revoke it \u2014 the token still works anywhere else it is stored.",`Revoke it in Doppler (project "${e}", config "${t}"): ${ig}/${e}`],Ll=async({env:e})=>{let r=!!(await re())?.envs[e];await np(e);let n=await xe(),o=await Ge();r?l.info(`Removed the "${e}" service token from ${w(o)}.`):l.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of GS(n,e))l.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${ig}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import US from"@inquirer/password";import ci from"node:process";import{$ as ai}from"zx";var KS=async({stdin:e,fromEnv:t})=>{if(e)return{token:await qS(),source:"stdin"};if(t){let n=ci.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return g.setInteractive(),{token:(await x(n=>US({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:ci.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},qS=async()=>{let e=[];ci.stdin.setEncoding("utf8");for await(let t of ci.stdin)e.push(t);return e.join("").trim()},Vl="DOPPLER_CONFIG",HS=3e4,zS=async(e,t,r)=>{let n=ai.quiet;ai.quiet=!0;let o;try{o=(await ai({env:Gr(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(HS)).stdout}catch(s){throw YS(s,r)}finally{ai.quiet=n}return Ps(o)},YS=(e,t)=>{let r=ir(e)??(e instanceof Error?e.message:String(e));if(_t(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Mt(r)==="mis-scoped"?"it is scoped to a DIFFERENT config (pasting another environment's token here is the mistake this check exists to catch).":"it is invalid or has been revoked.";return new Error([`Doppler refused this token for config "${t}" \u2014 ${n}`,"Nothing was written. Issue a service token scoped to that config and try again."].join(`
|
|
394
|
+
`))},XS=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Vl}.`,"Refusing to store a credential whose scope is unknown (a token for the wrong environment would load","the wrong secrets into every shell).","Re-run with --force if you are certain the token is scoped to this config."].join(`
|
|
395
|
+
`),Jl=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await xe(),{token:s,source:i}=await KS({stdin:t,fromEnv:r});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await zS(s,o,e);Es(a,e);let c=a.some(([u])=>u===Vl);if(!c&&!n)throw new Error(XS(e));await rp(e,s);let d=await Ge();l.info(`Stored the "${e}" service token (${Kr(s)}) in ${w(d)} (mode 0600).`),c||l.warn(`Scope was NOT verified (no ${Vl} in the payload) \u2014 written because --force was given.`);let p={env:e,source:i,redactedToken:Kr(s),storePath:d,scopeVerified:c};return g.print(),{content:k(JSON.stringify(p,null,2)),structuredContent:p}};var Wl=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:d,printEnv:p}=e,u=await Nc(n);if(r&&g.addOption("--from",u),Oc(u,{"--version":o,"--skip-terraform":a,"--dry-run":d,"--print-env":p}),u==="local")throw new f(void 0,{operation:"deploy --from local",remediation:"use --from ci to dispatch the release workflow",stderrExcerpt:"local deploys are disabled for now \u2014 deploys run in CI only"});return t==="all"?js({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Fs({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Bl=async e=>Wl(e,"all"),Gl=async e=>Wl(e,"selected"),li=async(e,t)=>{let r=`release deploy-${t} --from local`;return l.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),Wl({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as cg}from"@slip-stream-kit/config/internal";import Ul from"node:fs/promises";import Kl from"node:path";import ag from"node:process";import{pathToFileURL as ZS}from"node:url";var lg="~/projects",ql=async(e={})=>{if(e.init){await ex(e.cwd);return}await QS()},QS=async()=>{let e=Pr(),t=await U(e);if(l.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){l.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),ag.exitCode=1;return}let{workspaceDir:r,targets:n}=await hu(),o=gu(r),s=await U(o);l.info(`workspaceDir: ${r} (resolved: ${o}) ${s?"[\u2713 exists]":"[ ] not found"}`),l.info("Targets:");let i=s;for(let a of n){let c=Kl.join(o,a),d=await U(c);d||(i=!1);let p=d?"[\u2713]":"[ ]",u=d?"":" (not found \u2014 clone or remove)";l.info(` ${p} ${a} ${w(c)}${u}`)}i||(ag.exitCode=1)},ex=async e=>{let t=Pr();if(await U(t)){l.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await R(),n=await tx(r);await Ul.mkdir(Kl.dirname(t),{recursive:!0}),await Ul.writeFile(t,rx(n),"utf-8"),l.info(`\u2713 Created ${w(t)}`),n.length>0&&l.info(` Seeded ${n.length} target(s) from the source ${cg}.`),l.info(` Edit \`workspaceDir\` (placeholder: ${lg}) to point at where your repos live.`),n.length===0&&l.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},tx=async e=>{try{let t=Kl.join(e,cg),r=await Ul.stat(t),s=(await import(`${ZS(t).href}?mtime=${Number(r.mtimeMs)}`)).default,i=typeof s=="function"?await s():s;if(i&&typeof i=="object"&&"targets"in i){let a=i.targets;if(Array.isArray(a)&&a.every(c=>typeof c=="string"))return a}}catch{}return[]},rx=e=>`${JSON.stringify({workspaceDir:lg,targets:e},null,2)}
|
|
396
|
+
`;var di=(e,t=!0)=>({line:e,reproducible:t});import pi from"node:fs";import nx from"node:os";import ox from"node:path";import mg from"node:process";var ui="INFRA_KIT_SESSION_REPORT",Hl=null,dg=!1,pg=[],fg=(e=mg.env)=>{dg||(Hl=e[ui]??null,dg=!0,delete e[ui])};var gg=(e,t)=>{if(!Hl)return;let r=e.summary??(pg.length>0?[...pg]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{pi.writeFileSync(s,i)});try{o(Hl,JSON.stringify(n))}catch{}},ug=0,hg=e=>{let t=e?.tmpdir?.()??nx.tmpdir(),r=e?.pid??mg.pid;return ug+=1,ox.join(t,`infra-kit-session-${r}-${ug}.json`)},vg=(e,t)=>{if(!(t?.exists??(i=>pi.existsSync(i)))(e))return null;let n=t?.read??(i=>pi.readFileSync(i,"utf-8")),o=t?.unlink??(i=>pi.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var zl=e=>{e.options.some(r=>r.long==="--agent")||e.option("--agent","Run as an agent: never prompt; refuse with a structured payload (under --json) naming what to pass instead"),e.commands.forEach(zl)};var Yl=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Yl)};var lx=(e,t)=>[...t,e],yg=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&er.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${er.join(", ")}.`)}},dx=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-y, --yes","Skip confirmation prompt").option("--dry-run","Compute and print the merge plan without pushing anything").option("--verify [command]","Check each merge before pushing it. Bare runs `pnpm install --frozen-lockfile`; pass a command to run that instead. A branch that fails is dropped from the push, never rolled back").action(async t=>{let r=await Bm(()=>Os({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,confirmedCommand:t.yes}));P(r),r.structuredContent.failedMerges>0&&(Ce.exitCode=1)}),wg=e=>(Ce.stdout.write(`${e.structuredContent.filePath}
|
|
397
|
+
`),P(e)),px=e=>e.description("List all release branches").action(async()=>{P(await Ls())}),ux=e=>e.description("Create one or more release branches (each entry can mix regular/hotfix and its own description)").option("-r, --release <spec>",'Release spec "<version|next|name>[@yyyy-mm-dd][:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"); "@yyyy-mm-dd" is the planned release date, written to the Jira fix version. Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "1.64.0@2026-10-28", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',lx,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Qa),o=n.length>0?n:void 0;P(await Gs({releases:o,confirmedCommand:t.yes}))}),mx=e=>{if(e==="")return e;try{return Wt(e)}catch(t){throw t instanceof Lr?new ix(t.message):t}},fx=e=>e.description("Edit a release's description and/or release date in Jira (description also in the matching GitHub PR body)").option("-v, --version <version>","Release version (e.g. 1.2.5) or release name (e.g. checkout-redesign)").option("-d, --description <description>",'New description (use "" to clear)').option("--release-date <yyyy-mm-dd>",'New planned release date (use "" to clear)',mx).option("-y, --yes","Skip confirmation prompt").action(async t=>{P(await Us({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),kg=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Pt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),gx=e=>kg(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{P(await Bl({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),hx=e=>kg(e).description("Deploy selected services to any environment, in CI or from this machine").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").action(async t=>{P(await Gl({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),vx=e=>e.description("Release a new version to production").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deliver").option("-y, --yes","Skip confirmation prompt").action(async t=>{P(await Ms({version:t.version,confirmedCommand:t.yes}))}),yx=e=>e.description("Tear down a release: worktree, PR, branches, and the Jira fix version").option("-v, --version <version>","Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to remove").option("--move-issues-to <version>","Reassign issues carrying the fix version to this version before removing it").option("--skip-jira","Remove everything except the Jira fix version").option("-y, --yes","Skip confirmation prompt").action(async t=>{P(await Xs({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),wx=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{P(await ii({confirmedCommand:t.yes}))}),kx=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("--orca","Open created worktrees in Orca (pane layout from worktrees.orca.layout)").option("--no-orca","Skip the Orca prompt").action(async t=>{let r=yg(t.ide,"--ide")??yg(t.cursor,"--cursor");P(await ni({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),bx=e=>e.description("List all git worktrees with detailed information").action(async()=>{P(await oi())}),Rx=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async t=>{P(await si({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),Ex=e=>e.description("Show the machine-local factory config (~/.infra-kit/vendor.json) or scaffold it with --init").option("--init","Scaffold ~/.infra-kit/vendor.json (skips if it already exists)").action(async t=>{P(await ql({init:t.init}))}),Px=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await ei();P(t),t.structuredContent.ok||(Ce.exitCode=1)}),Sx=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{P(await jl())}),xx=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{P(await Fl())}),Tx=new Set(["version"]),mi=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Xl=()=>{let e=new sx().option("-C <dir>","Run as if infra-kit was started in <dir> instead of the current working directory"),t=e.command("release").description("Release management commands");dx(t.command("merge-dev")),px(t.command("list")),ux(t.command("create")),fx(t.command("edit")),gx(t.command("deploy-all")),hx(t.command("deploy-selected")),vx(t.command("deliver")),yx(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");kx(r.command("add")),bx(r.command("list")),Rx(r.command("remove")),wx(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");Sx(n.command("path")),xx(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{P(await Zo())});let o=e.command("local").description("Deprecated \u2014 use `release deploy-all|deploy-selected --from local`"),s=a=>a.option("-e, --env <name>","Target environment (prompts when omitted)").option("-y, --yes","Skip the confirmation prompt").option("--dry-run","Resolve target, contract and commands without deploying").option("--print-env","Print the resolved build contract");s(o.command("deploy-all")).description("Deprecated \u2014 use `release deploy-all --from local`").action(async a=>{P(await li({env:a.env,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"all"))}),s(o.command("deploy-selected")).description("Deprecated \u2014 use `release deploy-selected --from local`").option("-s, --service <name...>","Service name(s), as in deploy-<name>.sh (prompts when omitted)").action(async a=>{P(await li({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){l.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Ce.exitCode=1;return}let c=await Xo({all:a.all,root:a.root,fix:a.fix,design:a.design});P(c);let{allPassed:d,fixed:p}=c.structuredContent,u=(p??[]).some(m=>m.action==="failed");(!d||u)&&(Ce.exitCode=1)});let i=e.command("vendor").description("Verify the mirrored vendor/ tree");return Px(i.command("check")),Ex(i.command("config")),e.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").option("--fix","Remove portless routes left behind by a dev-server that was killed (kill -9, OOM, force-quit). Refuses while a dev session is running, when a booting UI is indistinguishable from a dead route.").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (check messages are unchanged)").action(async a=>{let c=await vs({fix:!!a.fix});on.enabled||ba(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(p=>p.name==="plugin installed"&&p.status==="fail")&&(Ce.exitCode=1),P(c)}),e.command("dev").description("Run local dev servers for a named devServersPresets preset (or all apps); api + ui").argument("[preset]","Named preset from devServersPresets (omit to run every app)").option("-w, --watch","Rebuild and restart on file save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:d}=await import("./dev-server.js"),p=!!(Ce.stdout.isTTY&&Ce.stdin.isTTY);await d({...c,preset:a},p,on.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{P(await es())}),e.command("setup").description("Set this machine up: shell integration, agent files, the Claude Code skills plugin, then the external tools").option("--tools <ids...>","Limit to these tools (brew, git, aws, gh, doppler, portless)").option("--update [ids...]","Update what is already installed; never install a missing tool").option("--skip-tools","Do the local setup only, then REPORT what each tool needs \u2014 installs nothing").action(async a=>{P(await Qs({tools:a.tools,update:a.update,skipTools:a.skipTools}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{P(await ti())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{P(await Ss())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{P(await ks())}),e.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async a=>{wg(await Rs({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{wg(await ys())}),e.command("env-token-set").description("Store the Doppler service token for an env (masked prompt; validated against Doppler before writing)").argument("<env>","Environment / Doppler config the token is scoped to (e.g. dev)").option("--stdin","Read the token from stdin instead of prompting (e.g. from a password manager)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{P(await Jl({env:a,stdin:c.stdin,fromEnv:c.fromEnv,force:c.force}))}),e.command("env-token-list").description("Show which envs have a Doppler service token (redacted), and where it came from").option("--check","Also ask Doppler whether each token is valid and correctly scoped").action(async a=>{P(await xs({check:!!a.check}))}),e.command("env-token-remove").description("Delete an env\u2019s Doppler service token from the local store (does NOT revoke it in Doppler)").argument("<env>","Environment / Doppler config whose token to remove").action(async a=>{P(await Ll({env:a}))}),e.commands.forEach(Dd),zl(e),Yl(e),e.hook("preAction",async(a,c)=>{let{C:d}=e.opts();d!==void 0&&cx(ax(Ce.cwd(),d)),g.start(mi(c)),on.enabled=!!c.optsWithGlobals().json,on.enabled&&(l.level="warn"),A.source=To({env:Ce.env,stdinIsTTY:Ce.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),Tx.has(mi(c))||await Sa()}),e.hook("postAction",(a,c)=>{let d=mi(c);if(Nl(d))return;let u=g.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",h=`infra-kit ${d}${m}`;gg({equivalent:di(h,!0)})}),e};import Cx from"node:process";var Ax={exit:Cx.exit,emit:P,logger:l},bg=(e,t=Ax)=>ce(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof T?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var Zl=(e,t=" ")=>{let r=e.reduce((n,[o])=>Math.max(n,o.length),0);return e.map(([n,o])=>`${n.padEnd(r)}${t}${o}`)};import $x from"node:fs";import Rg from"node:path";import vo from"node:process";var Sg=new Set([...Kd,Ie,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),xg=null,fi=new Set,Ql=null,Eg=!1;var Pg=e=>{try{return $x.statSync(e)}catch{return null}},Ix=()=>{if(Eg)return null;try{return ct()}catch{return Eg=!0,l.debug(`session-env: ${Ie} unset \u2014 no overlay`),null}},Dx=e=>{let t=Rg.join(e,at),r=Rg.join(e,yo),n=Pg(t),o=Pg(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},Ox=e=>e.kind==="load"?{kind:"load",vars:ad(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:cd(e.file),signature:e.signature}:e;var Nx=()=>{let e=Ix();if(e===null)return{kind:"no-session"};let t=Dx(e);return t.signature===Ql?null:Ox(t)},_x=()=>{for(let e of fi){let t=xg[e];t===void 0?delete vo.env[e]:vo.env[e]=t}fi.clear()},Mx=(e,t,r)=>{if(Sg.has(t)){e.skipped.push(t);return}vo.env[t]=r,fi.add(t),e.set.push(t)},jx=(e,t)=>{if(Sg.has(t)){e.skipped.push(t);return}delete vo.env[t],fi.add(t),e.unset.push(t)},Fx=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))Mx(t,r,n);if(e.kind==="clear")for(let r of e.unset)jx(t,r);return t},Lx=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,ed=(e=Nx())=>{if(xg??={...vo.env},e===null||e.kind==="no-session"||e.signature===Ql)return{set:[],unset:[],changed:!1};_x();let{set:t,unset:r,skipped:n}=Fx(e);return Ql=e.signature,n.length>0&&l.warn(`session-env: skipped protected names [${n.join(", ")}]`),l.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${Lx(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as iT}from"chalk";import{spawn as aT}from"node:child_process";import me from"node:process";import{Chalk as Vx}from"chalk";var tn=new Vx({level:1}),Ae={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},Jx={suspend:{unicode:"any key commands \xB7 Esc / Ctrl-C quit \xB7 Ctrl-Z suspend",ascii:"any key commands - Esc / Ctrl-C quit - Ctrl-Z suspend"},plain:{unicode:"any key commands \xB7 Esc / Ctrl-C quit",ascii:"any key commands - Esc / Ctrl-C quit"}},Tg={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Cg={unicode:"\u2500",ascii:"-"},Wx=3,td=e=>e,Bx={ok:e=>tn.green(e),findings:e=>tn.yellow(e),failed:e=>tn.red(e),cancelled:e=>tn.gray(e)},nd=e=>e?{dim:t=>tn.dim(t),bold:t=>tn.bold(t)}:{dim:td,bold:td},Gx=(e,t)=>e?Bx[t]:td,rd=e=>[...e].length,Ux=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return rd(e)<=r?e:[...e].slice(0,r).join("")},Ag=e=>{let t=nd(e.color===!0).dim,r=Jx[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(Ux(n,e.width))},$g=(e,t={})=>{let r=nd(t.color===!0);return`${r.dim(Ae.reproPrefix.trim())} ${r.bold(e)}`},Kx=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,qx=(e,t)=>e==="findings"?t!=null?`${t} ${Ae.findingsSuffix}`:Ae.findingsPlain:{ok:Ae.ok,failed:Ae.failed,cancelled:Ae.cancelled}[e],Hx=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<Wx?"":` ${n(r.repeat(o))}`},Ig=e=>{let t=e.color===!0,r=nd(t),n=Gx(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ae.reproPrefix:Ae.nonReproPrefix,i=o?Tg[e.outcome].ascii:Tg[e.outcome].unicode,a=qx(e.outcome,e.findingsCount),c=[Kx(e.durationMs)],d=e.summary?.[0]?.split(`
|
|
398
|
+
`)[0];d!=null&&d.length>0&&c.push(d);let p=`${i} ${a}`,u=`${Ae.sep}${c.join(Ae.sep)}`,m=rd(p)+rd(u),h=Hx(m,e.width,o?Cg.ascii:Cg.unicode,r.dim),y=[`${n(p)}${r.dim(u)}${h}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Ae.envNotice)),y.join(`
|
|
399
|
+
`)};var zx=new Set([130,143]),Dg=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&zx.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import Yx from"node:process";var Xx={3:"quit",4:"quit",26:"suspend",27:"quit"},Zx=e=>{if(e.length!==1)return"continue";let t=typeof e=="string"?e.charCodeAt(0):e[0];return t===void 0||Number.isNaN(t)?"continue":Xx[t]??"continue"},Qx=150,eT="\r\x1B[2K",tT=`\r
|
|
400
|
+
`,Og=(e,t)=>{Ng(e),e.stdin.on("data",t),e.listener=t},Ng=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},_g=(e,t)=>{mp(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Og(e,t)},Mg=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(eT)),Ng(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),fp()},rT=e=>{e.settled||(e.settled=!0,Mg(e))},jg=(e,t)=>{let r=Ag({canSuspend:e.deps.suspend!==void 0,ascii:e.deps.ascii,color:e.deps.color,width:e.deps.columns()});e.deps.write(t+r),e.hintOnScreen=!0},nT=async e=>{await new Promise(t=>{setTimeout(t,e)})},oT=(e,t,r)=>{Mg(e),t(),_g(e,r),jg(e,tT)},sT=async e=>new Promise(t=>{let r=n=>{let o=Zx(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){oT(e,s,r);return}t("palette")};Og(e,r),jg(e,"")}),Fg=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??Yx.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return _g(n,()=>{}),e.armed(),await nT(t.drainMs??Qx),await sT(n)}finally{rT(n)}};import Lg from"node:process";var xt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Vg=(e,t)=>{let r=t?.write??(s=>{Lg.stderr.write(s)}),n=t?.stdin??Lg.stdin,o=[xt.saveCursor,xt.scrollRegion,xt.restoreCursor,xt.column,xt.sgr,xt.cursor,xt.wrap];e.entersAltScreen===!0&&o.push(xt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var Jg=e=>`infra-kit ${e.groupPath.join(" ")}`,cT=()=>{lT();let e=me.stderr.columns;return e!=null&&e>0?e:void 0},lT=()=>{let e=me.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},dT=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),pT=async(e,t,r)=>{let n=hg(),o={...t.env,[ui]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let u=t.spawn(me.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await dT(u)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=vg(n),c=Dg(i.code,i.signal,a!=null,e.longRunning),d=Jg(e),p=a?.equivalent??di(d,!0);return Ig({equivalent:p,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(p.reproducible&&p.line===d)})},uT=1e3,mT=(e,t)=>e!=null&&t-e<=uT,od=e=>{e.resetTerminal(),e.exit(0)},fT=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&od(t)},s=()=>{let c=e();if(c==="palette"){od(t);return}if(!mT(r,t.now())){if(c==="pause"){od(t);return}n=!0}},i=()=>{t.exit(129)},a=()=>{e()==="child"&&t.raise("SIGSTOP")};return t.register("SIGINT",o),t.register("SIGTERM",s),t.register("SIGHUP",i),t.register("SIGTSTP",a),{dispose:()=>{t.unregister("SIGINT",o),t.unregister("SIGTERM",s),t.unregister("SIGHUP",i),t.unregister("SIGTSTP",a)},childStarted:()=>{r=null},quitRequested:()=>n}},Wg=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),gT=me.platform==="win32"?void 0:()=>{gp()},hT=(e,t)=>r=>Fg(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:gT}),Bg=async(e,t)=>{let r={spawn:t.spawn??aT,now:t.now??(()=>Date.now()),env:t.env??me.env,cliPath:t.cliPath,ascii:t.ascii??!(me.stdout.isTTY&&me.env.TERM!=="dumb"),color:t.color??iT.level>0,columns:t.columns??cT,resetTerminal:t.resetTerminal??(p=>{Vg(p)})},n=t.write??(p=>me.stderr.write(p)),o="palette",s=t.signals??{register:(p,u)=>{me.on(p,u)},unregister:(p,u)=>{me.off(p,u)},exit:p=>{me.exit(p)},raise:p=>{me.kill(me.pid,p)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:fT(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},d=t.afterRun??hT(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let p=await t.renderPalette(e);if(p==null)return;let u=t.resolveCommand(p);if(!u)continue;let m=$g(Jg(u),{color:r.color});n(`
|
|
423
401
|
${m}
|
|
424
|
-
`),a.childStarted();let h=await
|
|
402
|
+
`),a.childStarted();let h=await pT(u,r,()=>{o="child"});if(n(`
|
|
425
403
|
${h}
|
|
426
|
-
`),await d(c)==="quit")return}}finally{a.dispose()}};
|
|
404
|
+
`),await d(c)==="quit")return}}finally{a.dispose()}};Ml();fg();var qg=Xl(),Ug=async(e=fe.argv)=>{ed(),up(e);try{await qg.parseAsync(e)}catch(t){bg(t)}},bT=()=>{try{if(fe.env.INFRA_KIT_NO_LOCATION_WARN||fe.argv.includes("--json"))return;md({selfRealPath:wT(Kg(import.meta.url)),cwd:fe.cwd(),env:fe.env,realpath:se,home:kT(),exists:yT})&&l.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};bT();Id((e,t)=>{l.debug(e,t)});Ta(G.version);var Hg=()=>ng(qg.commands),RT=async()=>{let e=Hg(),t=null;try{if(fe.stdout.isTTY&&fe.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-XLDVLQEG.js");t=await r(e)}else{let r=Zl(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new Gg(" "),new Gg(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await x(o=>vT({message:"Select a command to run",choices:n},o),{output:fe.stderr})}}catch(r){if(!ce(r))throw r}return t},ET=async()=>{let{runCommandPalette:e}=await import("./boot-XLDVLQEG.js"),t=Kg(import.meta.url),r=new Map(Gt.map(n=>[n.groupPath.join(" "),n]));await Bg(Hg(),{renderPalette:e,resolveCommand:n=>{let o=r.get(n);return o?{groupPath:o.groupPath,entersAltScreen:o.entersAltScreen,sessionEnvNotice:o.sessionEnvNotice,longRunning:o.longRunning}:void 0},cliPath:t})};if(fe.argv.length<=2){let e={stdoutIsTTY:!!fe.stdout.isTTY,stdinIsTTY:!!fe.stdin.isTTY,stderrIsTTY:!!fe.stderr.isTTY};if(Wg(fe.env,e))await ET();else{let t=await RT();t&&await Ug(["node","infra-kit",...t.split(" ")])}}else await Ug();
|
|
427
405
|
//# sourceMappingURL=cli.js.map
|