infra-kit 0.11.12 → 0.11.15
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-RD556L3P.js → chunk-EARHBKGG.js} +2 -2
- package/dist/{chunk-666XR52E.js → chunk-GVWC7K7X.js} +10 -10
- package/dist/{chunk-666XR52E.js.map → chunk-GVWC7K7X.js.map} +2 -2
- package/dist/{chunk-2CCPRPPP.js → chunk-HUUQWK6R.js} +2 -2
- package/dist/{chunk-SBD7FT5C.js → chunk-SLBZUXXO.js} +2 -2
- package/dist/{chunk-SBD7FT5C.js.map → chunk-SLBZUXXO.js.map} +1 -1
- package/dist/cli.js +101 -103
- package/dist/cli.js.map +3 -3
- package/dist/dev-server.js +2 -2
- package/dist/{dev-wizard-run-32WAMLAT.js → dev-wizard-run-Z7KRY24V.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- /package/dist/{chunk-RD556L3P.js.map → chunk-EARHBKGG.js.map} +0 -0
- /package/dist/{chunk-2CCPRPPP.js.map → chunk-HUUQWK6R.js.map} +0 -0
- /package/dist/{dev-wizard-run-32WAMLAT.js.map → dev-wizard-run-Z7KRY24V.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 Tu,d as Du,f as ys,h as Ir,i as vs,j as Mu,k as ju,l as Fu,m as Lu,n as Vu,o as Bu,p as Wu,q as Ju,t as Uu,u as Gu,v as we}from"./chunk-EARHBKGG.js";import{a as Rt,b as Bp,c as ha,d as Wp,e as Jp,f as Up,g as Gp,h as An,i as Kp,j as Hp,k as qp,l as zp,m as Yp,n as On,o as Xp,p as Zp,q as Qp,r as eu,s as ya,t as os,u as Pt,v as tu,w as ss,x as ru}from"./chunk-CMF7HEVU.js";import{a as ae,b as H,c as Et,d as us,e as ba,f as ms,g as Ra,h as Dn,i as qt,j as fs,k as gu,l as Nn,m as _n,n as Sa,o as Ea,q as xa}from"./chunk-BQPSXIH2.js";import{b as $n,c as rs,d as ga,e as Mp,f as ns,g as jp,i as Fp,k as Lp,m as he,o as Vp}from"./chunk-AWFGP6GY.js";import{a as Iu}from"./chunk-TVG47UHG.js";import{a as h,b as ct,c as x,d as Cu,e as $u,f as I,g as gs,h as W,i as hs,j as lt,k as ue,l as Nu,m as _u}from"./chunk-HUUQWK6R.js";import{$ as te,A as cu,B as lu,C as du,D as ls,E as ds,F as $e,G as In,H as Or,I as ps,J as pu,K as uu,L as mu,M as wa,N as ka,O as fu,P as p,Q as qe,R as ee,S as w,T as hu,U as yu,V as xt,W as wu,X as Pa,Y as Tt,Z as ku,_ as bu,a as at,aa as D,b as $,ba as Ru,c as nu,ca as Ct,d as A,e as Q,ea as Pu,f as ie,g as is,ga as Su,h as $r,i as f,j as ou,k as as,l as K,m as ve,n as Te,na as Eu,o as su,p as va,q as ne,qa as xu,r as Y,s as cs,t as iu,u as St,v as Ce,w as S,x as Le,y as Ar,z as au}from"./chunk-GVWC7K7X.js";import{a as vu}from"./chunk-MFAFQVTW.js";import{a as q}from"./chunk-SLBZUXXO.js";import{a as kt,b as Zo,c as He,d as Ip,e as it,f as Er,g as xr,h as Qo,i as Tr,j as es,k as Dp,l as Np,m as _p,n as bt,o as ts,p as ge,q as Cr}from"./chunk-QSTGO43H.js";import{a as Au,b as Ou}from"./chunk-QWVLAZ6N.js";import rI,{Separator as wv}from"@inquirer/select";import{existsSync as nI,realpathSync as oI}from"node:fs";import{homedir as sI}from"node:os";import Ee from"node:process";import{fileURLToPath as bv}from"node:url";import Cm from"node:process";import{z as Ie}from"zod";import Qu from"node:fs";import Nr from"node:path";import{packageConfigSchema as qu}from"@slip-stream-kit/config/internal";import zu from"node:fs/promises";import ws from"node:path";import{pathToFileURL as Av}from"node:url";import{z as Yu}from"zod";import Ku from"node:path";var Mn=["frontend","backend","lib","e2e","mobile"],Sv={ui:"frontend",api:"backend",tests:"e2e"},Ev="mobile-app",xv=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],Tv=(e,t)=>{let r=Ku.relative(t,e).split(Ku.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=Sv[o];if(s)return s}return r.at(-1)===Ev?"mobile":null},Cv=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of xv)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},jn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??Tv(e,t)??Cv(r)??"lib";var $t={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Hu=2e3,Ta={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Hu}} 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"},Ca={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"]},$a=(e,t=$t)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import $v from"node:fs/promises";var Ve=async e=>{try{return await $v.access(e),!0}catch{return!1}};var Be="infra-kit.config.ts",zt=async e=>{try{let t=await zu.readFile(ws.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Aa=async e=>{let t=await zu.stat(e),o=(await import(`${Av(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${Be} at ${e} has no default export`);return typeof o=="function"?await o():o},Yt=async e=>{let t=ws.join(e,Be);if(await Ve(t))try{let n=(await Aa(t))?.type;return Mn.find(o=>o===n)}catch{return}},Fn=async(e,t=$t)=>{let r=ws.join(e,Be);if(!await Ve(r))throw new Error(`${Be} not found at ${r}`);let n=await Aa(r),o=qu.safeParse(n);if(!o.success)throw new Error(`Invalid ${Be} at ${r}: ${Yu.prettifyError(o.error)}`);return $a(o.data,t)},Oa=async e=>{let t=ws.join(e,Be);if(!await Ve(t))return;let r=qu.safeParse(await Aa(t));if(!r.success)throw new Error(`Invalid ${Be} at ${t}: ${Yu.prettifyError(r.error)}`);return r.data};import Xu from"node:fs/promises";import ks from"node:path";import Ov from"yaml";var Iv="pnpm-workspace.yaml",Dv=async e=>(await Xu.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>ks.join(e,r.name)),Nv=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await Dv(n));continue}let o=ks.join(n,t);await Ve(o)&&r.push(o)}return r},_v=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await Nv(r,n);return r},ke=async e=>{let t=await Xu.readFile(ks.join(e,Iv),"utf-8"),n=((Ov.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await _v(e,s);for(let a of i)await Ve(ks.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Ln from"node:path";var Vn=async e=>{let t=Ln.resolve(e);for(;t!==Ln.dirname(t);){if(await Ve(Ln.join(t,"package.json")))return t;t=Ln.dirname(t)}if(await Ve(Ln.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 ze=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},At=(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}`:"")},Ia=(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},Zu=(e,t,r)=>`${e}
|
|
4
4
|
${t}
|
|
5
|
-
${r}`,
|
|
5
|
+
${r}`,Dr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Zu(r,t,n),i=ze(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),d=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(d)}let c=(i?At(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
6
6
|
${s}
|
|
7
7
|
`:`${s}
|
|
8
|
-
`};var Ae="<!-- infra-kit:begin -->",Ye="<!-- infra-kit:end -->",
|
|
8
|
+
`};var Ae="<!-- infra-kit:begin -->",Ye="<!-- infra-kit:end -->",Da="<!-- infra-kit:version ",Xe="<!-- infra-kit:package:begin -->",dt="<!-- infra-kit:package:end -->",Xt="<!-- infra-kit:package:version ";var Mv=e=>{let t=e.indexOf(Xe)+Xe.length;return e.slice(t,e.indexOf(dt))},jv=e=>{let t=e.indexOf(Xt);if(t===-1)return null;let r=e.slice(t+Xt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Mn.find(n=>n===r)??null},Zt=e=>{if(e===null)return{state:"missing"};if(!ze(e,Xe,dt))return e.includes(Xe)||e.includes(dt)?{state:"malformed"}:ze(e,Ae,Ye)?{state:"foreign-block"}:{state:"no-block"};let t=Mv(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Ia(t,Xt),o=jv(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import Fv from"node:fs";var Qt=e=>{try{return Fv.readFileSync(e,"utf-8")}catch{return null}};var em="pnpm-workspace.yaml",Lv="CLAUDE.md",_a=e=>{let t=Nr.resolve(e);for(;t!==Nr.dirname(t);){if(Qu.existsSync(Nr.join(t,em)))return t;t=Nr.dirname(t)}return Qu.existsSync(Nr.join(t,em))?t:null},Na=new Map,bs=()=>{Na.clear()},Vv=async e=>{let t;try{t=await ke(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Nr.join(r,Lv),o=Qt(n);if(o!==null&&Zt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},_r=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Na.get(e);if(t)return t;let r=await Vv(e);return Na.set(e,r),r};import er from"node:fs";import Ot from"node:path";var tm=`---
|
|
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 rm=`# {{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,7 +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
|
|
98
|
+
`;var nm="# {{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- Run the suite with `infra-kit e2e`: it sets `e2e.baseUrlEnv` from `infra-kit.config.ts` to this worktree's dev server when one serves `e2e.target`, else to the deployed URL `infra-kit env-load` loaded (or `e2e.cloud` at `INFRA_KIT_ENV`). Never hand-set that variable to reach a local server.\n- Never point a run at a production environment.\n\n## Structure\n\n- Specs live in `src/tests/<domain>/`, one folder per business domain \u2014 never per page, browser, device, or environment (those are Playwright projects).\n- A domain folder's root holds only its `*.spec.ts` files. Everything else always goes in a subfolder, even a single file: `pages/` (`.page.ts`, `.component.ts`), `fixtures/` (`.fixture.ts`), `mocks/` (`.mock.ts`), `data/` (`.data.ts`), `lib/` (domain-private helpers).\n- Never nest specs in subfolders \u2014 when a domain has too many specs to scan, split it into two domains (`luggage/`, `luggage-pricing/`).\n- Anything two domains share moves up to `src/pages/`, `src/fixtures/`, `src/mocks/`, or `src/lib/`; a domain never imports from a sibling domain.\n- API and contract specs stay in their domain folder, told apart by suffix: `<flow>.api.spec.ts`, `<flow>.contract.spec.ts`. A suffix exists only when that suite runs in its own Playwright project.\n- Visual-regression specs live in `src/visual/<domain>/<flow>.visual.spec.ts`, so baseline screenshots stay out of the domain folders.\n- Auth and data preparation are `src/setup/*.setup.ts` / `*.teardown.ts`, wired as Playwright setup projects \u2014 never `globalSetup`. Saved auth state goes to the gitignored `.auth/`.\n\n## Naming\n\n- Every Playwright spec is `*.spec.ts`; `.test.ts` is never used in an e2e package.\n- Files and folders are kebab-case.\n- A spec file names a stable flow: `<feature-or-flow>.spec.ts`. No ticket ids, sequence numbers, or `common` / `main` / `smoke`.\n- Non-spec files never carry `.spec` / `.test`. A spec never imports another spec.\n- `describe` is a short domain context in Title Case (`Checkout`).\n- `test` is a lowercase behaviour phrase \u2014 action or condition plus the observable outcome (`rejects an expired coupon without changing the total`). No `should`, `test \u2026`, `works`, or case numbers.\n- `test.step` is a verb plus a business operation (`Pay with the saved card`), 3\u20136 per long flow \u2014 never one step per click or fill.\n- Screenshot baselines are named by UI state (`checkout-payment-error.png`), never `screenshot-1.png`.\n\n## Tags\n\nRun categories are tags (`{ tag: [...] }`), never file names. Only these four exist:\n\n- `@smoke` \u2014 the fast post-deploy check; every domain has at least one.\n- `@readonly` \u2014 creates and changes nothing, so it is safe against any shared environment.\n- `@mocked` \u2014 every backend call is mocked; runs without a live API.\n- `@slow` \u2014 excluded from local runs with `--grep-invert @slow`.\n\nNever tag a browser, device, or environment, and never add `@flaky`; fix the test or skip it with a linked issue.\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-test-tags` the tag list, `@wl/e2e-test-title` the missing `should`. The rest of Naming \u2014 `describe` in Title Case, no ticket ids, outcome-bearing titles, `test.step` wording \u2014 is on the author and the reviewer.\n";var om="# {{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 sm=`# {{packageName}}
|
|
99
99
|
|
|
100
100
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
101
101
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -117,7 +117,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
117
117
|
- Changing that map is a breaking change for every dependent package.
|
|
118
118
|
- Run \`pnpm run build\` before a dependent package can see a change.
|
|
119
119
|
- No app-specific logic belongs here.
|
|
120
|
-
`;var
|
|
120
|
+
`;var im=`# {{packageName}}
|
|
121
121
|
|
|
122
122
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
123
123
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -139,39 +139,39 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
139
139
|
- The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
|
|
140
140
|
- The web build feeds the native shell, so a device run needs a rebuild first.
|
|
141
141
|
- Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
|
|
142
|
-
`;var
|
|
142
|
+
`;var am="# 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 dev [preset]` / `ik dev-status` \u2014 run this worktree's dev servers (a `devServersPresets` preset, or every app), or report what is running.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite against this worktree's dev server when one serves `e2e.target`, else against the deployed app at `INFRA_KIT_ENV` (the env-loaded `e2e.baseUrlEnv`, or `e2e.cloud`); `--dry-run` prints the target and proxy split. A cloud run previews and needs `--yes`.\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; `--keep-conflicts` hands off any real conflict to a CLI-owned resolution worktree, `--continue`/`--abort` resume or drop that hand-off. The `/infra-kit:merge-dev` skill is the agent entry point for the whole flow.\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`, `release merge-dev --continue|--abort`, `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` and `vendor sync` are human-only and are 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- Unit tests are `*.test.ts(x)` in a `__tests__/` folder beside the code they test (`src/foo/__tests__/foo.test.ts`), never next to the source file; inside a frontend feature, all of them go in the feature root's `features/<name>/__tests__/`. `*.spec.ts` is only for Playwright specs in an e2e package. The `@wl/test-location` lint rule enforces it.\n";var Mr={"root/body":am.trimEnd(),"package/frontend":om.trimEnd(),"package/backend":rm.trimEnd(),"package/lib":sm.trimEnd(),"package/e2e":nm.trimEnd(),"package/mobile":im.trimEnd(),"design/skeleton":tm.trimEnd()};var Ma=/\{\{(\w+)\}\}/g,qv=/^- \{\{(\w+)\}\}$/,zv=e=>new Set([...e.matchAll(Ma)].map(t=>t[1])),Yv=(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(", ")}`)},Xv=(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(", ")}`)},Zv=(e,t)=>e.filter(r=>{let n=qv.exec(r);return n===null||t[n[1]]!==""}),Qv=(e,t)=>{for(let r of e)for(let n of r.matchAll(Ma)){let o=t[n[1]];if(o!==void 0&&o.includes(`
|
|
143
143
|
`)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},jr=(e,t)=>{let r=zv(e);Xv(r,t),Yv(r,t);let n=Zv(e.split(`
|
|
144
144
|
`),t);return Qv(n,t),n.join(`
|
|
145
145
|
`).replace(Ma,(o,s)=>t[s])};var ew="name: TODO",ja=e=>{let t=jr(Mr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(ew,()=>r)}
|
|
146
146
|
`};var tw=(e,t)=>`${Xt}${e} ${t} -->`,rw="`README.md` \u2014 what this package is and how to run it.",Fa="docs/e2e-playwright.md",nw=`\`${Fa}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,La=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i}=e,a=jr(Mr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?rw:"",...r==="e2e"?{e2eDocBullet:i?nw:""}:{}});return[tw(t,r),"",a].join(`
|
|
147
|
-
`)};var ow=e=>`${
|
|
148
|
-
`)};import Fr from"node:fs";import sw from"node:path";var
|
|
149
|
-
`).find(r=>r.trim().length>0)??"").trim(),xw=(e,t)=>{if(Dn(t))return null;p.debug({msg:`Running: ${
|
|
150
|
-
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ae}`,`enabledPlugins.${H}`]}),cc=e=>{let t=jw(e);if(t===null)return Fw(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!
|
|
147
|
+
`)};var ow=e=>`${Da}${e} -->`,Va=e=>{let t=jr(Mr["root/body"],{});return[ow(e),"",t].join(`
|
|
148
|
+
`)};import Fr from"node:fs";import sw from"node:path";var Rs=e=>{let t;try{t=Fr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Bn=(e,t)=>{Rs(e);let r=Fr.existsSync(e)?Fr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":(Fr.mkdirSync(sw.dirname(e),{recursive:!0}),Fr.writeFileSync(e,t,"utf-8"),r===null?"created":"updated")},Ba=(e,t,r)=>{let n=Fr.readFileSync(e,"utf-8");if(!ze(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},cm=(e,t,r)=>ze(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Wa=(e,t,r,n)=>{let o=cm(e,r,n),s=cm(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 Ss="<!-- infra-kit:import:begin -->",Es="<!-- infra-kit:import:end -->",iw="AGENTS.md",lm="CLAUDE.md",aw="README.md",Ja="DESIGN.md",cw=["frontend","mobile"],lw=e=>er.existsSync(e)?er.readFileSync(e,"utf-8"):null,Ua=(e,t)=>{try{return er.readdirSync(e).includes(t)}catch{return!1}},Ps=(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},dm=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o})=>{let s=lw(e),i=s===null?"":o?.(s)??s,a=Dr({content:i,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"}),c=Bn(e,a);return Ba(e,r,n),s!==null&&Wa(i,a,r,n),c},dw=e=>{if(!er.existsSync(e))return"unchanged";Rs(e);let t=er.readFileSync(e,"utf-8"),r=At(t,Ae,Ye);return r===null?"unchanged":r.trim()===""?(er.rmSync(e),"removed"):Bn(e,r)},pw=(e,t)=>dm({filePath:e,body:Va(t),startMarker:Ae,endMarker:Ye,prepare:r=>At(r,Ss,Es)??r}),Wn=async(e,{version:t})=>{let r=Ot.join(e,lm),n=Ot.join(e,iw),o=[];try{o.push({path:r,action:pw(r,t)})}catch(s){o.push(Ps(r,s))}try{o.push({path:n,action:dw(n)})}catch(s){o.push(Ps(n,s))}return o},uw=(e,t,r)=>{if(!cw.includes(r)||Ua(e,Ja))return null;let n=Ot.join(e,Ja);try{return{path:n,action:Bn(n,ja(t)),type:r}}catch(o){return Ps(n,o,r)}},Jn=async(e,{repoRoot:t,version:r,design:n,declaredType:o})=>{let s=Ot.join(e,lm),i=await zt(e),a=i.name??Ot.basename(e),c=jn({packageDir:e,repoRoot:t,pkgJson:i,declaredType:o}),l=La({version:r,type:c,packageName:a,relDir:Ot.relative(t,e).split(Ot.sep).join("/"),hasReadme:Ua(e,aw),hasDesign:Ua(e,Ja),hasE2eDoc:er.existsSync(Ot.join(t,Fa))}),d=[];try{d.push({path:s,action:dm({filePath:s,body:l,startMarker:Xe,endMarker:dt}),type:c})}catch(u){d.push(Ps(s,u,c))}if(n){let u=uw(e,a,c);u&&d.push(u)}return d};import Pw from"node:path";import pm from"node:path";var Ga="agent-guidance",Un="CLAUDE.md",mw="\u2014 run: infra-kit audit --fix",fw={missing:`${Un} missing`,"no-block":`${Un} has no infra-kit block (expected ${Xe} \u2026 ${dt})`,malformed:`${Un} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Un} carries the ROOT infra-kit block (${Ae}); a package needs the package block`},gw=e=>e.adopted?` (workspace adopted: ${pm.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Ka=(e,t)=>{let r=Zt(Qt(pm.join(e,Un)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ga,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${fw[r.state]} ${mw}`,o=r.state==="missing"?`${n}${gw(t)}`:n;return t.adopted?{name:Ga,status:"fail",message:o}:{name:Ga,status:"pass",message:`not yet adopted \u2014 ${o}`}};var Ha=async(e,t=$t)=>{try{let r=await Fn(e,t);return{check:{name:Be,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:Be,status:"fail",message:r.message},rules:null}}};import hw from"node:fs/promises";import yw from"node:path";var xs="playwright.config.ts",vw=[{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'"}],um=e=>Object.entries(Ta).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"}}),mm=async e=>{let t=yw.join(e,xs),r=await hw.readFile(t,"utf-8").catch(()=>null);return r===null?[{name:`e2e-config:${xs}`,status:"fail",message:`missing ${xs}`}]:vw.map(n=>{let o=`e2e-config:${n.name}`;return n.pattern.test(r)?{name:o,status:"pass",message:"present"}:{name:o,status:"fail",message:`${xs} lacks the shared e2e convention \u2014 expected: ${n.expected}`}})},qa=async(e,t)=>[...um(t),...await mm(e)];import ww from"node:fs/promises";import kw from"node:path";var za=async(e,t)=>Promise.all(t.map(async r=>{let n=await ww.stat(kw.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 Ya=(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 bw from"node:fs/promises";import Rw from"node:path";var Lr="turbo.json",Xa=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await bw.readFile(Rw.join(e,Lr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Lr,status:"fail",message:`cannot read/parse ${Lr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Lr,status:"fail",message:`no "tasks" object defined in ${Lr}`}]: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 ${Lr}`}})};var Sw={adopted:!1,workspaceRoot:null},Ew=async(e,t,r)=>jn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Yt(e)}),Za=async(e,t=$t,r={})=>{let n=await zt(e),o=n.name??Pw.basename(e),{check:s,rules:i}=await Ha(e,t),a=[s];r.isRoot||a.push(Ka(e,r.adoption??Sw)),i&&(a.push(...Ya(n.scripts??{},i.requiredScripts)),a.push(...await za(e,i.requiredFiles)),a.push(...await Xa(e,i.turboTasks))),!r.isRoot&&await Ew(e,n,r.repoRoot)==="e2e"&&a.push(...await qa(e,n.scripts??{}));let c=a.every(l=>l.status==="pass");return{packageDir:e,packageName:o,checks:a,passed:c}};var Qa=["plugin","marketplace","add",Et],ec=["plugin","install",H,"--scope","project"],fm=(e,t)=>qt({projectPath:e,home:t}).kind==="installed",tc=e=>((e??"").split(`
|
|
149
|
+
`).find(r=>r.trim().length>0)??"").trim(),xw=(e,t)=>{if(Dn(t))return null;p.debug({msg:`Running: ${us} ${Qa.join(" ")}`});let r=e({args:Qa});return r.ok?null:{step:"marketplace",error:tc(r.output)}},Tw=(e,t)=>{p.debug({msg:`Running: ${us} ${ms.join(" ")}`});let r=e({args:ms,cwd:t});return r.ok?{status:"updated"}:{status:"update-failed",error:tc(r.output)}},rc=e=>{let{projectRoot:t,home:r}=e,n=e.run??Ra;if(!n({args:ba}).ok)return{status:"claude-missing"};if(fm(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:Tw(n,t);let o=xw(n,r);if(o!==null)return{status:"failed",...o};p.debug({msg:`Running: ${us} ${ec.join(" ")}`});let s=n({args:ec,cwd:t});return s.ok?fm(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:tc(s.output)}};import Cw from"node:fs";import $w from"node:path";var Oe=".mcp.json",Ze="mcpServers",Aw="infra-kit",Ow=["mcp"],Iw="/infra-kit/dist/mcp.js",nc=" ",tr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gm=e=>{if(!tr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===Aw&&r[0]===Ow[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(Iw)):!1},hm=e=>/\n([ \t]+)"/.exec(e)?.[1]??nc,oc=e=>{try{return{kind:"raw",raw:Cw.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},sc=e=>{try{return JSON.parse(e)}catch{return}},ic=e=>e instanceof Error?e.message:String(e),Gn=e=>{let t=oc($w.join(e,Oe));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=sc(t.raw);if(!tr(r)||!tr(r[Ze]))return{kind:"unparseable"};let n=r[Ze];if(ae in n)return{kind:"stale"};let o=Object.keys(n).find(s=>gm(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Ts from"node:fs";import Dw from"node:path";var pt=`claude plugin install ${H} --scope project`,Vr=`claude plugin update ${H} --scope project`,ac=`claude plugin marketplace add ${Et}`,vm=" ",wm=()=>({source:{source:"github",repo:Et}}),Nw=()=>({extraKnownMarketplaces:{[ae]:wm()},enabledPlugins:{[H]:!0}}),km=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_w=e=>/\n([ \t]+)"/.exec(e)?.[1]??vm,ym=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!km(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Mw=e=>[ym(e,"extraKnownMarketplaces",ae,wm()),ym(e,"enabledPlugins",H,!0)].filter(r=>r!==null),jw=e=>{try{return Ts.readFileSync(e,"utf-8")}catch{return null}},Fw=e=>(Ts.mkdirSync(Dw.dirname(e),{recursive:!0}),Ts.writeFileSync(e,`${JSON.stringify(Nw(),null,vm)}
|
|
150
|
+
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ae}`,`enabledPlugins.${H}`]}),cc=e=>{let t=jw(e);if(t===null)return Fw(e);let r;try{r=JSON.parse(t)}catch{r=void 0}if(!km(r))return p.warn(`Could not parse ${e} \u2014 left it untouched. Add "${H}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let n=Mw(r);if(n.length===0)return{status:"unchanged",path:e,added:[]};let o=_w(t),s=t.endsWith(`
|
|
151
151
|
`)?`
|
|
152
|
-
`:"";return
|
|
152
|
+
`:"";return Ts.writeFileSync(e,`${JSON.stringify(r,null,o)}${s}`,"utf-8"),{status:"added",path:e,added:n}};var k=e=>[{type:"text",text:e}],R=e=>e;import Lw from"node:path";import Vw from"node:process";var Bw=["unchanged","created"],Ww=["unchanged","created","updated","removed","failed"],bm=async(e,t,r)=>{let n=await Yt(e);return Jn(e,{repoRoot:t,version:q.version,design:r,declaredType:n})},Jw=async(e,t)=>{if(e.root)return Wn(t,{version:q.version});if(e.all){let n=[];for(let o of await ke(t))n.push(...await bm(o,t,e.design));return n}let r=await Vn(e.cwd??Vw.cwd());return bm(r,t,e.design)},Uw=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 ${Ww.filter(n=>Bw.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${q.version})`},Gw=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=Lw.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";p.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}p.info(Uw(e))},Kw=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Rm=async(e,t)=>{let r=await S();bs();let n=await _r(t),o=await Jw(e,r);Gw(o,r),bs();let s=await _r(t),i=!e.all&&!e.root;return{fixed:o.map(Kw),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Sm from"node:fs";import Em from"node:path";var lc="ik-mcp",Pm=(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:lc,args:r}};var Cs="run `infra-kit setup` (or `infra-kit audit --root --fix`)",Hw=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),dc=e=>tr(e)&&e.command===lc,qw=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),zw=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Pm(i,a),l=e[i];if(l!==void 0&&!dc(l)){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 ${Cs}, or drop mcp.${i} from infra-kit.json`});continue}if(dc(l)&&l.type===c.type&&Hw(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=qw(l,c),s=!0,n.push({name:i,status:"written",message:""});continue}n.push({name:i,status:"drifted",message:l===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: ${Cs}`:`"${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: ${Cs}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!dc(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}},Yw=(e,t,r)=>{let n=r===null?nc:hm(r),o=r===null||r.endsWith(`
|
|
153
153
|
`)?`
|
|
154
|
-
`:"";try{return Pm.mkdirSync(Sm.dirname(e),{recursive:!0}),Pm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return p.warn(`Could not write ${e} (${ic(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Cs=({projectRoot:e,proxies:t,write:r})=>{let n=Sm.join(e,Oe),o=oc(n);if(o.kind==="unreadable")return p.warn(`Could not read ${n} (${ic(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:sc(s);if(!tr(i))return p.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ts}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Ze];if(a!==void 0&&!tr(a))return p.warn(`${n} has a "${Ze}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=zw(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Yw(n,{...i,[Ze]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Em=async(e,t)=>{let r;try{r=(await I()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Cs({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 Xw=(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}))],xm=async e=>{let t=(await I()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Su(t);if(r.length>0){let d=r.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=Ru(e),o=Pu(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await xu(e,t,s,n),c=Xw(Eu(t,i),a),l=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:l,passed:c.length===0}};var Zw="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Qw=async e=>e.root?[{dir:await S(),baseline:Ca,isRoot:!0}]:e.all?(await ke(await S())).map(r=>({dir:r})):[{dir:await Ln(e.cwd??Tm.cwd())}],ek=async e=>e.root||e.all?await S():e.cwd??Tm.cwd(),tk=async()=>{try{return await S()}catch{return}},rk=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,p.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 p.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},nk=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await bm(e,t);return n&&p.info(Zw),r},ok=e=>{if(Un(e).kind!=="stale")return null;let t=`${Oe} still registers "${ae}" \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 "${ae}" entry by hand in a PR, keeping its siblings`;return p.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},$s=async(e={})=>{let t=_a(await ek(e)),r=e.fix?await nk(e,t):void 0,n=await Qw(e),o=await _r(t),s=await tk(),i=[];for(let l of n)i.push(await Za(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await xm(n[0].dir);l&&i.push(l);let d=await Em(n[0].dir,e.fix===!0);d&&i.push(d);let u=ok(n[0].dir);u&&i.push(u)}let c={allPassed:rk(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},sk={all:De.boolean().optional().describe("Audit every non-vendor workspace package"),root:De.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},ik={allPassed:De.boolean().describe("Whether every audited package passed all checks"),packages:De.array(De.object({name:De.string(),passed:De.boolean(),checks:De.array(De.object({name:De.string(),status:De.enum(["pass","fail"]),message:De.string()}))})).describe("Per-package check results")},pc=R({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:sk,outputSchema:ik,handler:e=>$s({all:e.all,root:e.root})});import{z as Gn}from"zod";var As=async()=>{let[e,t]=await Promise.all([I(),te()]),r=Object.keys(e).sort();p.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),p.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},ak={config:Gn.record(Gn.string(),Gn.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:Gn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:Gn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},uc=R({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:ak,handler:()=>As()});import mk from"node:fs";import{z as ce}from"zod";import Kn from"node:fs";import Br from"node:path";import ck from"node:process";var lk=Br.join(".infra-kit","dev-context"),dk=".infra-kit",Cm=(e,t)=>{let r=Br.resolve(e);for(;;){let n=Br.join(r,t);if(Kn.existsSync(n))return n;let o=Br.dirname(r);if(o===r)return;r=o}},pk=e=>{let t=Cm(e,lk);if(t)return t;let r=Cm(e,dk);return r?Br.join(r,"dev-context"):void 0},mc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Os=e=>typeof e=="string"?e:"",uk=(e,t,r)=>{let n=Br.join(e,t);try{let o=Kn.statSync(n),s=JSON.parse(Kn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Os(i.package),port:mc(i.port),alias:Os(i.alias),origin:Os(i.origin),release:Os(i.release),pid:mc(i.pid),writtenAt:mc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},fc=(e=ck.cwd())=>{let t=Date.now(),r=pk(e);if(!r||!Kn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Kn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>uk(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 Ds=async(e={})=>{let t=e.now??Date.now,r=e.isListening??$n,n=fc(e.cwd),o=t(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),g=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:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(mk.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){p.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let u of s){let m=u.live?"live":"NOT responding",g=`written ${u.ageSeconds}s ago`;p.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${g}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";p.info(`No active infra-kit dev session \u2014 searched ${l} (${u}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},fk={active:ce.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:ce.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:ce.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:ce.array(ce.object({app:ce.string().describe("App folder name (the fragment filename without .json)."),package:ce.string().describe("The app package name the vite helper reads to decide a local route."),port:ce.number().describe("The actual bound port the dev server is listening on."),pid:ce.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ce.string().describe("Registered portless hostname for the app."),origin:ce.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ce.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ce.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:ce.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ce.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ce.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.")},gc=R({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:fk,handler:()=>Ds()});import{spawnSync as bg}from"node:child_process";import re from"node:fs";import Rg from"node:os";import pe from"node:path";import nt from"node:process";import{z as fe}from"zod";import{execFileSync as gk}from"node:child_process";var $m=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},hk=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],yk=e=>hk.some(t=>t.test(e)),vk="/bin/ps",wk=()=>gk(vk,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
155
|
-
`),
|
|
154
|
+
`:"";try{return Sm.mkdirSync(Em.dirname(e),{recursive:!0}),Sm.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return p.warn(`Could not write ${e} (${ic(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},$s=({projectRoot:e,proxies:t,write:r})=>{let n=Em.join(e,Oe),o=oc(n);if(o.kind==="unreadable")return p.warn(`Could not read ${n} (${ic(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:sc(s);if(!tr(i))return p.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Cs}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[Ze];if(a!==void 0&&!tr(a))return p.warn(`${n} has a "${Ze}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=zw(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=Yw(n,{...i,[Ze]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var xm=async(e,t)=>{let r;try{r=(await D()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=$s({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 Xw=(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}))],Tm=async e=>{let t=(await D()).devServersPresets;if(!t||Object.keys(t).length===0)return null;let r=Eu(t);if(r.length>0){let d=r.map(u=>({name:`devServersPresets:${u.preset}`,status:"fail",message:u.message}));return{packageDir:e,packageName:"devServersPresets",checks:d,passed:!1}}let n=Pu(e),o=Su(e),s={api:n.map(d=>d.name),ui:o.map(d=>d.name)},{ctx:i,loadErrors:a}=await Tu(e,t,s,n),c=Xw(xu(t,i),a),l=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:l,passed:c.length===0}};var Zw="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",Qw=async e=>e.root?[{dir:await S(),baseline:Ca,isRoot:!0}]:e.all?(await ke(await S())).map(r=>({dir:r})):[{dir:await Vn(e.cwd??Cm.cwd())}],ek=async e=>e.root||e.all?await S():e.cwd??Cm.cwd(),tk=async()=>{try{return await S()}catch{return}},rk=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,p.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 p.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},nk=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Rm(e,t);return n&&p.info(Zw),r},ok=e=>{if(Gn(e).kind!=="stale")return null;let t=`${Oe} still registers "${ae}" \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 "${ae}" entry by hand in a PR, keeping its siblings`;return p.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},As=async(e={})=>{let t=_a(await ek(e)),r=e.fix?await nk(e,t):void 0,n=await Qw(e),o=await _r(t),s=await tk(),i=[];for(let l of n)i.push(await Za(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await Tm(n[0].dir);l&&i.push(l);let d=await xm(n[0].dir,e.fix===!0);d&&i.push(d);let u=ok(n[0].dir);u&&i.push(u)}let c={allPassed:rk(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:k(JSON.stringify(c,null,2)),structuredContent:c}},sk={all:Ie.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ie.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},ik={allPassed:Ie.boolean().describe("Whether every audited package passed all checks"),packages:Ie.array(Ie.object({name:Ie.string(),passed:Ie.boolean(),checks:Ie.array(Ie.object({name:Ie.string(),status:Ie.enum(["pass","fail"]),message:Ie.string()}))})).describe("Per-package check results")},pc=R({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:sk,outputSchema:ik,handler:e=>As({all:e.all,root:e.root})});import{z as Kn}from"zod";var Os=async()=>{let[e,t]=await Promise.all([D(),te()]),r=Object.keys(e).sort();p.info(`Merged config for ${t.projectName} \u2014 ${r.length} section(s): ${r.join(", ")}`),p.info(` source: ${t.main}`);let n={config:e,configPath:t.main,projectName:t.projectName};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},ak={config:Kn.record(Kn.string(),Kn.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:Kn.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),projectName:Kn.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},uc=R({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:ak,handler:()=>Os()});import mk from"node:fs";import{z as ce}from"zod";import Hn from"node:fs";import Br from"node:path";import ck from"node:process";var lk=Br.join(".infra-kit","dev-context"),dk=".infra-kit",$m=(e,t)=>{let r=Br.resolve(e);for(;;){let n=Br.join(r,t);if(Hn.existsSync(n))return n;let o=Br.dirname(r);if(o===r)return;r=o}},pk=e=>{let t=$m(e,lk);if(t)return t;let r=$m(e,dk);return r?Br.join(r,"dev-context"):void 0},mc=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Is=e=>typeof e=="string"?e:"",uk=(e,t,r)=>{let n=Br.join(e,t);try{let o=Hn.statSync(n),s=JSON.parse(Hn.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Is(i.package),port:mc(i.port),alias:Is(i.alias),origin:Is(i.origin),release:Is(i.release),pid:mc(i.pid),writtenAt:mc(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},fc=(e=ck.cwd())=>{let t=Date.now(),r=pk(e);if(!r||!Hn.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Hn.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>uk(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 Ds=async(e={})=>{let t=e.now??Date.now,r=e.isListening??An,n=fc(e.cwd),o=t(),s=await Promise.all(n.apps.map(async u=>{let m=Math.max(0,Math.round((o-u.mtimeMs)/1e3)),g=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:g}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(mk.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){p.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let u of s){let m=u.live?"live":"NOT responding",g=`written ${u.ageSeconds}s ago`;p.info(` ${u.app} (${u.package}) \u2192 ${u.origin} on :${u.port} \u2014 ${m}, ${g}`)}}else{let u=c?"no readable fragment found there":"that directory does not exist";p.info(`No active infra-kit dev session \u2014 searched ${l} (${u}).`)}let d={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},fk={active:ce.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:ce.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:ce.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:ce.array(ce.object({app:ce.string().describe("App folder name (the fragment filename without .json)."),package:ce.string().describe("The app package name the vite helper reads to decide a local route."),port:ce.number().describe("The actual bound port the dev server is listening on."),pid:ce.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ce.string().describe("Registered portless hostname for the app."),origin:ce.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ce.string().describe("Release slug the runner recorded for this worktree."),writtenAt:ce.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:ce.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ce.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ce.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.")},gc=R({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:fk,handler:()=>Ds()});import{spawnSync as bg}from"node:child_process";import re from"node:fs";import Rg from"node:os";import pe from"node:path";import ot from"node:process";import{z as fe}from"zod";import{execFileSync as gk}from"node:child_process";var Am=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},hk=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],yk=e=>hk.some(t=>t.test(e)),vk="/bin/ps",wk=()=>gk(vk,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
155
|
+
`),Om=(e=wk)=>{try{return e().some(yk)}catch{return!0}};import{Chalk as kk}from"chalk";import hc from"node:process";var yc={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},bk=new Set(["warn","fail"]),Rk=24,Wr=" ",Im=" ",Pk=(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:[""]},Dm=e=>{let t={ok:0,changed:0,skipped:0,manual:0,warn:0,fail:0};for(let r of e)t[r.status]+=1;return t},Sk=e=>{let t=new kk({level:e?1:0});return{header:r=>t.bold.cyan(r),ok:r=>t.green(r),changed:r=>t.green(r),skipped:r=>t.gray(r),manual:r=>t.cyan(r),fail:r=>t.red(r),warn:r=>t.yellow(r),dim:r=>t.dim(r),bold:r=>t.bold(r)}},Nm=(e,t)=>[{status:"changed",plain:`${e.changed} changed`},{status:"skipped",plain:`${e.skipped} skipped`},{status:"manual",plain:`${e.manual} to run yourself`},{status:"fail",plain:`${e.fail} failed`},{status:"warn",plain:`${e.warn} ${t(e.warn)}`}].filter(n=>e[n.status]>0),Ek=(e,t,r,n)=>{if(e.ok===t){let c=`${t}/${t} ok`;return{text:r.ok(c),plainWidth:c.length}}let o=`${e.ok+e.changed}/${t}`,s=Nm(e,c=>`warning${c===1?"":"s"}`),i=[r.dim(o),...s.map(c=>r[c.status](c.plain))].join(` ${n.separator} `),a=s.reduce((c,l)=>c+l.plain.length+3,o.length);return{text:i,plainWidth:a}},xk=(e,t,r,n)=>{let o=Ek(Dm(e.rows),e.rows.length,t,r),s=Math.max(1,n-Wr.length-e.label.length-o.plainWidth);return`${Wr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},Tk=(e,t,r,n,o)=>{let s=bk.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,d=Im.length+i+1+t+2,u=Math.max(Rk,o-d),[m,...g]=Pk(e.message,u),y=" ".repeat(d),P=C=>s?C:r.dim(C);return[`${Im}${c(n[e.status])} ${l} ${P(m??"")}`.trimEnd(),...g.map(C=>`${y}${P(C)}`),...(e.notes??[]).map(C=>`${y}${C}`.trimEnd())]},Ck=(e,t,r,n,o)=>{let s=Dm(t),i=n.rule.repeat(Math.max(12,Math.min(o-Wr.length,56))),a=Nm(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(d=>r[d.status](d.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(d=>` ${r.dim(d)}`);return[`${Wr}${r.dim(i)}`,`${Wr}${c}${l.join("")}`]},vc=(e,t={})=>{let r=t.width??80,n=Sk(t.color??!1),o=t.unicode??!0?yc.unicode:yc.ascii,s=e.sections.filter(d=>d.rows.length>0),i=s.flatMap(d=>d.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Wr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(d=>d.name.length)),l=s.flatMap(d=>[xk(d,n,o,r),...d.rows.flatMap(u=>Tk(u,c,n,o,r)),""]);return[a,"",...l,...Ck(e,i,n,o,r)]},$k=new Set(["","0","false","none"]),Ak=["LC_ALL","LC_CTYPE","LANG"],Ok=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!$k.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,Ik=(e,t)=>{if(t)return!1;let r=Ak.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},wc=(e={})=>{let t=e.env??hc.env,r=e.stream??hc.stderr;return{color:Ok(t,r),unicode:Ik(t,e.ascii??!1),width:r.columns??80}},It=(e,t={})=>{(t.write??(n=>{hc.stderr.write(n)}))(`${vc(e,wc(t)).join(`
|
|
156
156
|
`)}
|
|
157
|
-
`)};var
|
|
158
|
-
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:qk(t.slice(10))},
|
|
157
|
+
`)};var Dk="Tools & CLIs",Nk="Shell & integration",_k="Project config",Mk="Doppler env tokens",jk="Dev proxy (portless)",Fk="Claude Code plugin",Lk=`portless serving TLS on :${xt}`,kc=[[Dk,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed","ide installed"]],[Nk,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[_k,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Mk,["tokens.json present","env tokens configured","tokens.json perms"]],[jk,["portless installed","portless node","portless service target",Lk,"portless CA chain valid","portless CA trusted","portless routes"]],[Fk,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","Agent mode","Agent allowlist"]]],_m="Other",Vk=kc.map(([e])=>e),Bk=new Map(kc.flatMap(([e,t])=>t.map(r=>[r,e]))),wM=kc.flatMap(([,e])=>e),bc=new Set(["portless routes","tokens.json perms"]),Wk=e=>{let t=new Map;for(let n of e){let o=Bk.get(n.name)??_m,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...Vk,_m].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Jk=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return qe(e)}},Uk=e=>{let t=e.filter(r=>r.status==="fail"&&bc.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Wk(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Jk(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Rc=(e,t={})=>{It(Uk(e),t)};var Gk=e=>e.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"),Kk=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>Gk(t[1])),Hk=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Kk(t[1])},qk=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 l=i[a+1];if(c==="\\"&&(l==='"'||l==="\\")){r+=l,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},zk=e=>{let t=e.split(`
|
|
158
|
+
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:qk(t.slice(10))},Mm=(e,t)=>{try{return e==="darwin"?Hk(t):e==="linux"?zk(t):null}catch{return null}};import{Buffer as rf}from"node:buffer";import Re from"node:fs/promises";import et from"node:path";import nf from"node:process";import{$ as Us}from"zx";import Yk from"node:process";var qn=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var jm=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 x({status:"argument_required",argument:e,agentMode:A.source},2,t);if(!Yk.stdin.isTTY)throw new f(void 0,t)},Dt=async e=>{jm("version");let{runBranchPicker:t}=await import("./boot-XLDVLQEG.js"),r=await t(e);if(r===null)throw new qn;return r},Nt=async(e,t)=>{jm("versions");let{runBranchMultiPicker:r}=await import("./boot-XLDVLQEG.js"),n=await r(e,t);if(n===null)throw new qn;return n};import{$ as Um}from"zx";import{$ as AM}from"zx";import{$ as Ur}from"zx";import{$ as Fm}from"zx";var Pc=async e=>{let{operation:t}=e;try{await Fm({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 Fm({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"})}},Zk=4,Jr=async e=>{let{operation:t}=e,r=await au();if(r.length===0)return;p.error(`working tree has uncommitted changes:
|
|
159
159
|
${r.join(`
|
|
160
|
-
`)}`);let n=r.slice(0,Zk),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}`})},
|
|
161
|
-
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},
|
|
162
|
-
`);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}},
|
|
160
|
+
`)}`);let n=r.slice(0,Zk),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}`})},zn=async e=>{let{operation:t,base:r}=e;if(await Ar()===r)return;let n=(await St(await S())).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}`})},be=async e=>{let{operation:t}=e;if(await lu())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 Jr({operation:t})};var Qk=e=>e.map(t=>({pr:t,id:K(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>iu(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Yn=200,Lm=(e,t)=>{e.length<Yn||p.warn({source:t,limit:Yn},`\u26A0\uFE0F ${t} returned ${Yn} PRs \u2014 the page is full, so older release PRs may be missing`)},eb=async()=>{let[e,t]=await Promise.all([Ur`gh pr list --limit ${Yn} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Ur`gh pr list --limit ${Yn} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Lm(r,"release PR discovery (base dev)"),Lm(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)}))},Xn="find open release PRs",Vm=async()=>{try{let e=await eb();if(e.length===0)throw new f(void 0,{operation:Xn,remediation:"open a release PR first, or check you are in the right repo"});return Qk(e)}catch(e){throw e instanceof f?e:(p.debug({err:e},"Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},Ns=async()=>(await Vm()).map(t=>t.headRefName),tb=e=>{let t=Zn(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=Sc(e.title)!==t;return(r||e.dualBase)&&p.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}},F=async()=>(await Vm()).map(tb),_s=async e=>{let{branch:t,body:r}=e;try{await Ur({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw p.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},rb=async(e,t)=>{let r=Ur({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){p.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&&p.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Ms=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=su(t,n),a=Qe(n),c=Ur({quiet:!0}),l=Te(t),d=Qn(r,o);try{await Jr({operation:`create release branch ${l}`});let u=(await c`git rev-parse HEAD`).stdout.trim();if(u!==s)throw new f(void 0,{operation:`create release branch ${l}`,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 ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${d} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await rb(l,a),m}}catch(u){throw p.error({error:u,branchName:l},`Error creating release branch ${l}`),u}finally{await Ur({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Ec}from"zx";var Gr=async e=>{let t=await Ec`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},xc=async e=>{let t=await Ec`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Tc=async e=>{try{let t=await Ec`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 to from"node:process";var nb="x-seraph-loginreason",ob="AUTHENTICATED_FAILED",sb=(e,t=160)=>{let r=e.split(`
|
|
161
|
+
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Wm=(e,t)=>t===ob||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Bm=(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}`,Kr=class extends Error{status;kind;body;context;constructor(t){let r=Wm(t.status,t.seraphLoginReason),n=sb(t.body);super(n===""?`${t.context}: ${Bm(r,t.status)}`:`${t.context}: ${Bm(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},eo=e=>e instanceof Kr,Jm=e=>e.headers.get(nb);var Hr=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Kr({status:e.status,seraphLoginReason:Jm(e),body:r,context:t});throw p.debug({status:e.status,kind:n.kind,body:r},t),n},rr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Cc=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}`),l=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await Hr(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},qr=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 Hr(a,"Failed to get Jira project versions"),await a.json()},ut=async(e,t)=>(await qr(t)).find(o=>o.name===e)||null,zr=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 Hr(c,"Failed to update Jira version");let l=await c.json();if(e.releaseDate===null&&(l.releaseDate||null)!==null)throw new Error(`Jira accepted the update (the write happened) but still reports releaseDate=${l.releaseDate}; the clear payload in updateJiraVersion needs revisiting`);return{success:!0,version:l}},$c=async(e,t)=>{let{versionName:r}=e,n=await ut(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await zr({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Yr=async()=>{let e=to.env.JIRA_BASE_URL,t=to.env.JIRA_TOKEN||to.env.JIRA_API_TOKEN,r=to.env.JIRA_PROJECT_ID,n=to.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(`
|
|
162
|
+
`);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}},mt=async()=>{try{return await Yr()}catch(e){return p.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var js=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 Hr(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Ac=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 Hr(c,"Failed to remove Jira version")};var Gm="dev",Km={regular:"dev",hotfix:"main"},Qe=e=>Km[e],Zn=e=>{let t=Object.entries(Km).find(([,r])=>r===e);return t?t[0]:null},Qn=(e,t)=>(t??"").trim()!==""?`${e}
|
|
163
163
|
|
|
164
164
|
${t}`:`${e}
|
|
165
|
-
`,Oc=async(e="regular")=>{let t=Qe(e),r=
|
|
166
|
-
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},pb=async(e,t)=>{let r=
|
|
167
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),
|
|
168
|
-
`)},ff=async e=>{let t=await uf(e),r=await Re.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>mf(
|
|
169
|
-
`).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),
|
|
170
|
-
`)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},
|
|
171
|
-
${l}`:l}).join(""),c=
|
|
172
|
-
\u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?p.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):p.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Pf=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await bf({cwd:t,versions:r,all:n});if(a.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),
|
|
173
|
-
\u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await
|
|
174
|
-
`)[0]}}},lf=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let u=await
|
|
165
|
+
`,Oc=async(e="regular")=>{let t=Qe(e),r=Um({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 Um({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()},ib=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await ut(t,r);if(!s)return(await Cc({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 zr({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Ic=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ne(t),c=await ib({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=rr(r,c),d=await Ms({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:Y(t),type:s,branchName:d.branchName,prUrl:d.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Fs=async()=>{let e=new Map,t=await mt();if(!t)return e;try{let r=await qr(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){p.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},oe=async()=>{let e=await Fs();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},ro=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Sc=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Ls=e=>e.flatMap(t=>{let r=K(t);return r?[{branch:t,id:r,label:Y(r)}]:[]}),ft=e=>{try{return Te(ve(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)})}},no=e=>{if(e===Gm)return Gm;let t=K(e);return t?Y(t):e},nr=e=>e.flatMap(t=>{let r=K(t);return r?[Y(r)]:[]}),ab=(e,t)=>t?t.get(e)||"regular":void 0,se=e=>{let{branches:t,descriptions:r,types:n}=e;return Ls(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ne(s)),type:ab(o,n)}))};import Hm from"node:fs/promises";import cb from"node:path";import{$ as Dc}from"zx";var L="pnpm-lock.yaml",lb=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,zm=async(e,t)=>{let r=cb.join(e,L),n=`${t}:${L}`;try{let o=await Dc({cwd:e,quiet:!0})`git show ${n}`;await Hm.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${L} to start from: ${qm(o)}`}}try{await Dc({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${L}: ${qm(o)}`}}return lb.test(await Hm.readFile(r,"utf8"))?{ok:!1,reason:`${L} still carries conflict markers after pnpm ran`}:(await Dc({cwd:e,quiet:!0})`git add -- ${L}`,{ok:!0})},qm=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as or}from"zx";var Nc="Merge remote-tracking branch 'origin/dev' into ",Ym=e=>String(e.stderr??e.message??e).trim(),db=async e=>{try{return(await or({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
|
|
166
|
+
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},pb=async(e,t)=>{let r=Ym(t),n=await db(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await mu(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Xm=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await $e(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 ub({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},ub=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await $e(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await In(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await wa(r),await or({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${Nc}${n}`;await or({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await or({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 pb(r,i)}}finally{await ka(r)}},Zm=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Qm="pnpm install --frozen-lockfile",ef=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await wa(t),await or({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await or({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,Ym(a))}finally{await ka(t)}return{kept:o,failed:s}},oo=async(e,t,r="origin/dev")=>{await or({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await In(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import _c from"node:process";var Vs=new Set,Bs=e=>(Vs.add(e),()=>{Vs.delete(e)}),mb=async()=>{for(let e of[...Vs])try{await e()}catch(t){p.warn({error:t,msg:"cleanup failed during shutdown"})}Vs.clear()},fb=["SIGINT","SIGTERM"],tf=async(e,t={})=>{let{register:r=(i,a)=>{_c.on(i,a)},unregister:n=(i,a)=>{_c.off(i,a)},exit:o=i=>{_c.exit(i)}}=t,s=new Map;for(let i of fb){let a=()=>{mb().then(()=>{o(Du(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var gb="pnpm install --frozen-lockfile --ignore-scripts",hb="pnpm install --frozen-lockfile",of=64*1024,df=4096,io=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-df)},N=async(e,t)=>(await Us({cwd:e,quiet:!0})`git ${t}`).stdout,Mc=e=>e.split(`
|
|
167
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),Gs=e=>e.split("\0").filter(t=>t.length>0),Ws=async(e,t)=>{try{return(await N(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},pf=async e=>et.resolve(e,(await N(e,["rev-parse","--git-common-dir"])).trim()),jc=e=>e.then(()=>!0,()=>!1),so=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Fc=e=>e?.length===1&&e[0]===L,uf=async e=>et.join(await pf(e),"infra-kit","merge-dev-resolutions"),Lc=async(e,t)=>et.join(await uf(e),`${pu(t)}.json`),mf=async e=>{try{return JSON.parse(await Re.readFile(e,"utf8"))}catch{return null}},Zr=async(e,t)=>{let r=await Lc(e,t.branch);await Re.mkdir(et.dirname(r),{recursive:!0}),await Re.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
168
|
+
`)},ff=async e=>{let t=await uf(e),r=await Re.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>mf(et.join(t,o))))).filter(o=>o!==null)},gf=async e=>Promise.all((await ff(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await jc(Re.stat(t.worktreePath))}))),sf=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),Vc=async(e,t,r)=>{await N(e,["worktree","remove","--force",r]).catch(()=>Re.rm(r,{recursive:!0,force:!0})),await Re.rm(await Lc(e,t),{force:!0}).catch(()=>{}),await N(e,["worktree","prune"]).catch(()=>{})},hf=async e=>Gs(await N(e,["diff","--name-only","-z","--diff-filter=U"])),Js=async e=>Gs(await N(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),yb=async(e,t)=>{let r=(await N(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await jc(Re.stat(et.join(await pf(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Mc(await N(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},yf=e=>e.split("/").includes("node_modules"),Ks=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=Gs(await N(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await vb(e),...o].filter(a=>!r.has(a)),i=(await Js(e)).filter(a=>!n.has(a)&&!yf(a));return[...new Set([...s,...i,...await wb(e)])].sort()},vb=async e=>{let t=Gs(await N(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},wb=async e=>(await N(e,["ls-files","-v"])).split(`
|
|
169
|
+
`).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),kb=async e=>{let t=`:(exclude)${L}`;try{return await N(e,["diff","--cached","--check","HEAD","--",".",t]),[]}catch(r){let{stdout:n="",stderr:o="",exitCode:s}=r;if(o.trim().length>0||n.trim().length===0||s!==1&&s!==2)throw new f(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
|
|
170
|
+
`)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},bb=async(e,t)=>{let r=[];for(let n of t)(await jc(Re.lstat(et.join(e,n)))||(await N(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await N(e,["--literal-pathspecs","add","-A","--",...r])},af=async e=>(await N(e,["write-tree"])).trim(),vf=async e=>(await N(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),Rb=e=>e?`${hb} && ${e}`:gb,Pb=async(e,t)=>{try{return await Us({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:io(r)}}},wf=async(e,t)=>{let r=(await N(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await N(e,["diff","--cached","--stat",l,"--",L])).trim(),o=t.conflictPaths.includes(L)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await N(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${L}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let d=/^diff --git a\/(.*) b\//.exec(l)?.[1];return d&&i.has(d)?`# rerere (recorded resolution)
|
|
171
|
+
${l}`:l}).join(""),c=rf.byteLength(a)>of;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?rf.from(a).subarray(0,of).toString():a,resolutionDiffTruncated:c}},kf=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await Sb(t,s,n));return o},Sb=async(e,t,r)=>{let n=await mf(await Lc(e,t));if(n)return{resolution:sf(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await $e(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=uu(e,t),i=()=>Vc(e,t,s),a=Bs(i);try{await N(e,["worktree","prune"]),await Re.mkdir(et.dirname(s),{recursive:!0}),await N(e,["worktree","add","--detach",s,o]),await Us({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${Nc+t}`.catch(()=>{});let c=await hf(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await Ws(s,"AUTO_MERGE");if(!l)return await i(),{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await N(e,["--version"])).trim()})`};let d=await yb(s,c),u=Fc(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:d,ignoredAtHandoff:await Js(s),lockfileOnly:u,cliVersion:q.version,createdAt:new Date().toISOString()};return await Zr(e,m),{resolution:sf(m,u?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:io(c)}}finally{a()}},bf=async e=>{let{cwd:t,versions:r,all:n}=e,o=await ff(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=Te(ve(c)),d=o.find(u=>u.branch===l);if(!d)throw new f(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return d});if(n||o.length===0)return o;let i=await Nt(se({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},Eb=async(e,t)=>{let r=await Re.realpath(t).catch(()=>null);if(!r)return!1;let n=await St(e);for(let o of n)if(await Re.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},Xr=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Rf=async(e,t,r)=>{let n=t.worktreePath,o={branch:t.branch,worktreePath:n,baseSha:t.baseSha,devSha:t.devSha,conflictPaths:t.conflictPaths,lockfileMerged:!1,rerereFiles:t.rererePreResolved};if(!await Eb(e,n))return Xr(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Ws(n,"HEAD"),i=await Ws(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?Ab(e,t,o,r):xb(t,o,s,i)},xb=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return Xr(t,"tree-changed",`commit ${r} carries a tree a commit hook rewrote after approval \u2014 run --abort, then hand off again`);let s=n?[]:await vf(o),i=n?null:await Ws(o,"HEAD^{tree}");if(!(s.length===2&&s[0]===e.baseSha&&s[1]===e.devSha&&i!==null&&i===e.previewedTree)||!r||!i){let l=n?`HEAD ${r??"none"} merging ${n}`:`HEAD ${r??"none"}`;return Xr(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Ks(o,e);return c.length>0?Xr(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(L),...await wf(o,e)}},cf=async(e,t)=>{let r=Mc(await N(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},Tb=async(e,t)=>{let r=t.worktreePath,n=await cf(r,L),o=t.lockfileBlob,s=await zm(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[L]};let i=await cf(r,L);if(i!==null&&i!==o&&(t.lockfileBlob=i,await Zr(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${L} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[L]}:{code:"out-of-scope-edit",detail:`${L} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[L]};let a=await Ks(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},Cb=async(e,t)=>{let r=t.worktreePath;await bb(r,t.conflictPaths.filter(i=>i!==L));let n=await Ks(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await hf(r)).filter(i=>i!==L);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await kb(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${io(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(L)?Tb(e,t):null},$b=async(e,t,r,n)=>{if(t.verified?.treeSha===r&&t.verified.command===n)return{command:n,ok:!0,reused:!0};let o=t.worktreePath,s=new Set(await Js(o)),i=await Pb(o,n);if(!i.ok)return i;let a=(await Js(o)).filter(c=>!s.has(c)&&!yf(c)&&et.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await Zr(e,t),i},Ab=async(e,t,r,n)=>{let o=t.worktreePath,s=await Cb(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(L),a=await af(o),c=await $b(e,t,a,Rb(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return Xr(l,"verify-failed",c.reason??"the verify command failed");let d=await Ks(o,t),u=Mc(await N(o,["diff","--name-only"]));return d.length>0||u.length>0||await af(o)!==a?Xr(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...d,...u])]):(c.reused||(t.verified={treeSha:a,command:c.command},await Zr(e,t)),{...l,...await wf(o,t)})},Ob=12e4,Ib=async(e,t=Ob)=>{let r=Us({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...nf.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&nf.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:io(s)};let i=(await N(e,["rev-parse","--git-path","index.lock"])).trim();return await Re.rm(et.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},Db={"verify-failed":"verify-failed","tree-changed":"tree-changed"},Nb=e=>{let t=e.blocked;return{branch:e.branch,status:Db[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},_b=async(e,t,r,n)=>{let o=r.worktreePath,s=(d,u,m={})=>({branch:t.branch,status:d,conflictPaths:t.conflictPaths,pushed:!1,reason:u,...m});if(!n)return s("tree-changed",`not approved: the preview this --yes came from had no ready tree for ${t.branch} \u2014 preview again`);if(t.treeSha!==n)return s("tree-changed",`the resolution is tree ${t.treeSha} but the approved tree is ${n} \u2014 preview again`);if(t.committed&&t.mergeSha)return{sha:t.mergeSha};let i=await Ib(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await N(o,["rev-parse","HEAD"])).trim(),c=(await N(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await Zr(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await vf(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let d={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${d.detail}`,{mergeSha:a,blocked:d})}return{sha:a}},Mb=async(e,t,r)=>{let n=(c,l,d)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...d?{blocked:d}:{}}),o;try{o=(await oo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${io(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await $e(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await In(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},jb=e=>{p.info(`
|
|
172
|
+
\u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?p.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):p.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},Pf=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await bf({cwd:t,versions:r,all:n});if(a.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),so();if(i)return lf(t,a,o,s);let c=[];for(let m of a){let g=await Rf(t,m,o);!g.blocked&&!g.committed&&g.treeSha&&(m.previewedTree=g.treeSha,await Zr(t,m)),c.push(g)}jb(c);let l={branches:c},d=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(d.length===0)throw new x({status:"refused",plan:l,agentMode:A.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let u=new Map(d.map(m=>[m.branch,m.treeSha]));try{await W(i,`Commit and push the resolved merges for: ${[...u.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Fb(u)})}catch(m){if(!ct(m))throw m;return{...so(),declined:!0}}return lf(t,a,o,u)},Sf=e=>{let t=new Map,r=(Array.isArray(e)?e:[e??""]).flatMap(n=>n.split(","));for(let n of r.map(o=>o.trim())){if(n.length===0)continue;let o=/^(.+)=([0-9a-f]{40,64})$/.exec(n);if(!o?.[1]||!o[2])throw new f(void 0,{operation:"read --tree",stderrExcerpt:`"${n}" is not <branch>=<tree sha>`,remediation:"run the rerun a --continue preview printed, unchanged"});t.set(o[1],o[2])}return t},Fb=e=>{let t=[],r=!1;for(let o of $u())r?r=!1:o==="--tree"?r=!0:o!=="--yes"&&o!=="-y"&&!o.startsWith("--tree=")&&t.push(o);let n=[...e].map(([o,s])=>`${o}=${s}`);return[...t,"--tree",n.join(","),"--yes"]},Lb=async(e,t,r,n)=>{let o=await Rf(e,t,r);if(o.blocked)return Nb(o);let s=await _b(e,o,t,n);if(!("sha"in s))return s;let i=await Mb(e,t,s.sha);return i==="keep"?s:i},Vb=async(e,t)=>{if(t.length===0)return{results:[],atomicPush:{attempted:!1,aborted:!1}};let r=t.map(s=>({branch:s.record.branch,sha:s.sha}));p.info(`
|
|
173
|
+
\u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await ps(e,r),o=[];for(let s of t){let i=n.pushed||await Or(e,s.record.branch)===s.sha;o.push({branch:s.record.branch,status:i?"merged":"push-aborted",mergeSha:s.sha,conflictPaths:s.record.conflictPaths,pushed:i,...i?{}:{reason:n.stderr?.trim().slice(-df)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
|
|
174
|
+
`)[0]}}},lf=async(e,t,r,n)=>{let o=[],s=[];for(let d of t){let u=await Lb(e,d,r,n.get(d.branch));"sha"in u?s.push({record:d,sha:u.sha}):o.push(u)}let i=await Vb(e,s),a=[...o,...i.results],c=t.filter(d=>a.some(u=>u.branch===d.branch&&(u.pushed||u.status==="up-to-date")));for(let d of c)await Vc(e,d.branch,d.worktreePath);let l=t.map(d=>d.branch);return a.sort((d,u)=>l.indexOf(d.branch)-l.indexOf(u.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},Ef=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await bf({cwd:t,versions:r,all:n});if(s.length===0)return p.info("\u2139\uFE0F No merge-dev resolutions in progress"),so();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await W(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!ct(a))throw a;return{...so(),declined:!0}}for(let a of s)await Vc(t,a.branch,a.worktreePath),p.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...so(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Bb from"node:fs";import Wb from"node:os";import Jb from"node:path";var Ub="infra-kit.json",Gb="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)",Kb="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",ao=async()=>{let e;try{e=await S()}catch{return null}let t=e.trim();return t===""||t===Wb.homedir()?null:t},xf=async()=>{let e=await ao();return e===null&&p.info(Gb),e},Hb=async()=>{let e=await ao();return e===null?null:Bb.existsSync(Jb.join(e,Ub))?e:(p.info(Kb),null)};var qb=async e=>{try{return await ke(e)}catch(t){return p.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},Tf=async()=>{let e=await Hb(),t=q.version;if(e===null)return{skipped:!0,root:null,version:t,written:[]};let r=[...await Wn(e,{version:t})];for(let n of await qb(e)){let o=await Yt(n);r.push(...await Jn(n,{repoRoot:e,version:t,declaredType:o}))}return{skipped:!1,root:e,version:t,written:r}};import le from"node:fs";import zc from"node:os";import me from"node:path";import Yc from"node:process";import qs from"node:fs/promises";import zb from"node:path";import Yb from"node:process";var Cf=` // "envManagement": { // required in layer 1; provider-tagged
|
|
175
175
|
// "provider": "doppler",
|
|
176
176
|
// "config": { "name": "my-doppler-project" }
|
|
177
177
|
// },
|
|
@@ -261,17 +261,15 @@ ${l}`:l}).join(""),c=tf.byteLength(a)>of;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
261
261
|
// }
|
|
262
262
|
//
|
|
263
263
|
// // Marks the repo as the source \`ik vendor sync\` copies from: the tracked paths to mirror into
|
|
264
|
-
// // every target in ~/.infra-kit/vendor.json
|
|
265
|
-
// //
|
|
266
|
-
// // every consumer repo.
|
|
264
|
+
// // every target in ~/.infra-kit/vendor.json and the path segments dropped on both sides of the
|
|
265
|
+
// // diff. Absent or null means "not a source", which is every consumer repo.
|
|
267
266
|
// //
|
|
268
267
|
// // PROJECT LAYER ONLY. This key is REFUSED here and in the per-project override \u2014 a machine-wide
|
|
269
268
|
// // copy would make every repo on this machine a source, and a per-project override would make this
|
|
270
269
|
// // machine disagree with every other clone. Commit it in the source repo's own infra-kit.json.
|
|
271
270
|
// "vendorSource": {
|
|
272
271
|
// "copy": [{ "path": ".claude" }, { "path": "vendor/configs" }],
|
|
273
|
-
// "exclude": ["serverless-config"]
|
|
274
|
-
// "legacyCleanup": ["configs"]
|
|
272
|
+
// "exclude": ["serverless-config"]
|
|
275
273
|
// }
|
|
276
274
|
//
|
|
277
275
|
// // Doppler SERVICE TOKENS are not a config key and never belong in this file. They live in
|
|
@@ -333,19 +331,19 @@ ${Cf}
|
|
|
333
331
|
// "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
|
|
334
332
|
// "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
|
|
335
333
|
}
|
|
336
|
-
`;var $f=!1,
|
|
337
|
-
`,"utf-8");let o=Wc(e.projectName),s=await
|
|
334
|
+
`;var $f=!1,Xb=e=>e.replace(/\.json$/,".example.jsonc"),Zb=async e=>{try{return await qs.readFile(e,"utf-8")}catch{return null}},Qr=async e=>{let t=e.userProject,r=Xb(t);await qs.mkdir(zb.dirname(t),{recursive:!0});let n=!await ee(t);n&&await qs.writeFile(t,`{}
|
|
335
|
+
`,"utf-8");let o=Wc(e.projectName),s=await Zb(r)!==o;return s&&await qs.writeFile(r,o,"utf-8"),n&&Ru(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},en=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,Uc=async()=>{if(Yb.env.INFRA_KIT_NO_SEED||$f)return;$f=!0;let e;try{e=await te()}catch{return}if(await ee(e.main))try{let t=await Qr(e);t.createdConfig?p.info(en(t)):t.refreshedExample&&p.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){p.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as Qb}from"node:child_process";import Of from"node:fs";import tn from"node:process";import{fileURLToPath as If}from"node:url";var Af=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Gc=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Af.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Fp(o,s,i)?"local-install":null:"not-a-tty"};var eR=e=>{Qb(tn.execPath,[e,"--parent-pid",String(tn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},tR=()=>If(new URL("./update-check.js",import.meta.url)),rR=()=>Of.realpathSync(If(new URL("./cli.js",import.meta.url))),nR=/^[\w@./+ -]+$/i,oR=e=>nR.test(e),sR=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Nn(e.latestVersion,t)&&e.updateCommand.every(oR)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${ns(e.updateCommand)}`)},Kc=(e,t={})=>{try{let r=t.argv??tn.argv,n=t.env??tn.env,o=t.isTty??!!tn.stdout.isTTY,s=t.cwd??tn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??rR(),c=t.readCache??_n,l=t.spawnChild??eR,d=t.fileExists??(y=>Of.existsSync(y)),u=t.notify??(y=>{p.info(y)});if(Gc({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:he})!==null)return;let m=c();if(sR(m,e,u),!Sa(m,i))return;let g=t.childPath??tR();if(!d(g))return;l(g)}catch{}};import rt from"node:fs/promises";import tt from"node:path";import{pathToFileURL as cR}from"node:url";import lR from"yaml";import{z as _f}from"zod";import iR from"node:fs/promises";import Hc from"node:os";import qc from"node:path";import{z as aR}from"zod";import{z as zs}from"zod";var Df="vendor.json",Ys=zs.object({workspaceDir:zs.string().min(1),targets:zs.array(zs.string()).min(1)}).strict();var rn=()=>qc.join(Hc.homedir(),Ip,Df),Xs=e=>{if(e==="~")return Hc.homedir();if(e.startsWith("~/"))return qc.join(Hc.homedir(),e.slice(2));if(qc.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Zs=async()=>{let e=rn(),t;try{t=await iR.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:
|
|
338
336
|
|
|
339
337
|
{
|
|
340
338
|
"workspaceDir": "~/projects",
|
|
341
339
|
"targets": ["my-repo"]
|
|
342
340
|
}
|
|
343
|
-
`)}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=
|
|
344
|
-
`,"utf-8"),await
|
|
345
|
-
`,"utf-8"),await
|
|
346
|
-
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},
|
|
347
|
-
`)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]
|
|
348
|
-
`),s=0;for(;s<o.length&&
|
|
341
|
+
`)}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=Ys.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${aR.prettifyError(n.error)}`);return n.data};var Nf=e=>e.replace(/\.json$/,".yml"),Mf=async()=>{let e;try{e=await te()}catch{return}let t=[{label:"infra-kit.json",yml:Nf(e.main),json:e.main,schema:wu},{label:"~/.infra-kit/infra-kit.json",yml:tt.join(tt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Pa},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Nf(e.userProject),json:e.userProject,schema:Pa}],r=0;for(let n of t){let[o,s]=await Promise.all([ee(n.yml),ee(n.json)]);if(o){if(s){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${w(n.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await rt.readFile(n.yml,"utf-8"),a=lR.parse(i)??{},c=n.schema.safeParse(a);if(!c.success){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 invalid config: ${_f.prettifyError(c.error)}`);continue}await rt.mkdir(tt.dirname(n.json),{recursive:!0}),await rt.writeFile(n.json,`${JSON.stringify(c.data,null,2)}
|
|
342
|
+
`,"utf-8"),await rt.rm(n.yml,{force:!0}),p.info(`\u2713 Migrated ${w(n.yml)} \u2192 ${w(n.json)}`),r++}catch(i){p.info(`\u26A0 Skipped ${w(n.yml)} \u2014 ${i.message}`)}}}r>0&&Ct()},jf=async()=>{let e;try{e=await te()}catch{return}let t=tt.dirname(e.userGlobal),r=[{from:tt.join(t,"config.json"),to:e.userGlobal},{from:tt.join(t,"config.example.jsonc"),to:tt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([ee(o),ee(s)]);if(i){if(a){p.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await rt.mkdir(tt.dirname(s),{recursive:!0}),await rt.rename(o,s),p.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){p.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Ct()},Ff=async()=>{let e=rn(),t=tt.dirname(e),r=tt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ee(r),ee(e)]);if(n){if(o){p.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await rt.stat(r),c=(await import(`${cR(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",d=l?await c():c,u=Ys.safeParse(d);if(!u.success){p.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${_f.prettifyError(u.error)}`);return}await rt.mkdir(t,{recursive:!0}),await rt.writeFile(e,`${JSON.stringify(u.data,null,2)}
|
|
343
|
+
`,"utf-8"),await rt.rm(r,{force:!0}),l?p.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.`):p.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){p.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},Lf=async()=>{let e=await dR(),t=0;for(let r of e)if(await ee(r))try{let n=await yu(r);if(!n.changed)continue;p.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof hu?"changed while migrating":n.message;p.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Ct()},dR=async()=>{try{let e=await te();return[e.main,e.userGlobal,e.userProject]}catch{return[bu()]}};var sr="# -- infra-kit:begin --",_t="# -- infra-kit:end --",pR=[["# region infra-kit","# endregion infra-kit"]],uR="# infra-kit shell functions",nn=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},on="Run `source ~/.zshrc` or open a new terminal to activate.",mR={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},nt=async(e,t)=>{try{return await t()}catch(r){throw new nn(e,r)}},Xc=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await nt("zshrc",()=>{r(fR())}),await nt("zshenv",()=>{r(gR())}),await nt("migrations",async()=>{await yR(),hR(),r(mR)}),await nt("user-config",()=>{r(wR())});let n=await nt("guidance",async()=>{let{entries:s,root:i}=await RR();return r(...s),i}),o=await nt("plugin-pointer",async()=>xf());return r(...ER(o,n)),await nt("worktrees",async()=>{r(...await AR(o))}),await nt("plugin-pointer",async()=>{await OR(o,r)}),await nt("mcp-proxies",async()=>{r(...await DR(o))}),await nt("project-config",async()=>{r(...await kR())}),r(...vR()),t};var fR=()=>{let e=me.join(zc.homedir(),".zshrc"),t=le.existsSync(e)?_R(le.readFileSync(e,"utf-8")):"",r=Dr({content:t,body:Bf(),startMarker:sr,endMarker:_t,placement:"append-end"});return le.writeFileSync(e,r),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"}},gR=()=>{let e=me.join(zc.homedir(),".zshenv"),t=le.existsSync(e)?le.readFileSync(e,"utf-8"):"",r=Dr({content:t,body:Zc(),startMarker:sr,endMarker:_t});return le.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"}},hR=()=>{le.rmSync(me.join(_p(),"projects"),{recursive:!0,force:!0})},yR=async()=>{await Mf(),await jf(),await Lf(),await Ff()},vR=()=>{let e=Yc.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:on,level:"info"}),t},wR=()=>{let e=me.join(zc.homedir(),".infra-kit"),t=me.join(e,"infra-kit.json");return le.mkdirSync(e,{recursive:!0}),le.writeFileSync(me.join(e,"infra-kit.example.jsonc"),Bc(),"utf-8"),le.writeFileSync(me.join(e,"vendor.example.jsonc"),Jc(),"utf-8"),le.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(le.writeFileSync(t,`{}
|
|
344
|
+
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},kR=async()=>{if(Yc.env.INFRA_KIT_NO_SEED)return[Qs("skipped","INFRA_KIT_NO_SEED is set")];try{let e=await te();if(!le.existsSync(e.main))return[Qs("skipped",`no project config at ${e.main}`)];let t=await Qr(e);return t.createdConfig?[{step:"project-config",outcome:"written",message:en(t),level:"info"}]:[Qs("unchanged","the user-project config was already present")]}catch(e){return p.debug({err:e,msg:"Skipped seeding the user-project config (init)."}),[Qs("warned",e instanceof Error?e.message:String(e))]}},Qs=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),bR=(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)} ${me.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},RR=async()=>{let{skipped:e,root:t,version:r,written:n}=await Tf();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:bR(t,r,n)}},PR=(e,t)=>{let r=me.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"}},SR=(e,t)=>{let r=Oe;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?ae: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 ${Ze} from ${me.join(e,Oe)} \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 "${ae}" key`:`no ${r}`})`,level:"info"}},ER=(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 ${H} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],xR=()=>[ac,pt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),TR=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${q.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${q.version} is behind the published version, update it first`}. The plugin follows on the next update check after that.`,level:"warn"};return e.stale?[r,{step:"plugin-pointer",outcome:"manual",message:ns(e.updateCommand),level:"info"}]:[r]},CR=(e,t)=>e.status==="skipped-cli-stale"?TR(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${H} 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: ${Vr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${H} (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"},...xR()]:[{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: ${pt}`,level:"warn"}],Vf={stale:!1},$R=async()=>{let e=_n(),t=e===null?await Ea(Yc.env):e.latestVersion;return t===null||!xa(t,q.version)?Vf:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??jp(t)}},AR=async e=>{if(e===null)return[];let r=`${await Le(e)}${ge}`,n=Object.values(Cr).filter(o=>!le.existsSync(me.join(r,o)));for(let o of Object.values(Cr))le.mkdirSync(me.join(r,o),{recursive:!0});return n.length===0?[{step:"worktrees",outcome:"unchanged",message:`Worktree directories already present at ${r}`,level:"info"}]:[{step:"worktrees",outcome:"written",message:`Created worktree directories at ${r} (${n.join(", ")})`,level:"info"}]},OR=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(PR(e,cc(me.join(e,".claude","settings.json"))));let n=qt({projectPath:e}).kind==="installed"?await $R():Vf;t(...CR(rc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(SR(e,Gn(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: ${pt}`,level:"warn"})}},IR=(e,t)=>{let r=me.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},DR=async e=>{if(e===null)return[];if(!le.existsSync(me.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 D()).mcp}catch(r){let n=r instanceof Error?r.message:String(r);return[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${n.split(`
|
|
345
|
+
`)[0]??n})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:IR(e,$s({projectRoot:e,proxies:t,write:!0}))},NR=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"),_R=e=>{let t=At(e,sr,_t);if(t!==null)return t;for(let[a,c]of pR){let l=At(e,a,c);if(l!==null)return l}let r=e.indexOf(uR);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
|
|
346
|
+
`),s=0;for(;s<o.length&&NR(o[s]);)s++;let i=o.slice(s).join(`
|
|
349
347
|
`);return n+(i?`
|
|
350
348
|
${i}`:"")},Bf=()=>{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(`
|
|
351
349
|
`)},Wf=()=>`${sr}
|
|
@@ -353,73 +351,73 @@ ${Bf()}
|
|
|
353
351
|
${_t}`,Zc=()=>["# 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(`
|
|
354
352
|
`),Qc=()=>`${sr}
|
|
355
353
|
${Zc()}
|
|
356
|
-
${_t}`;var
|
|
357
|
-
`),
|
|
358
|
-
`)};import{$ as
|
|
359
|
-
`);import
|
|
360
|
-
${t.stderr}`}},resolveBinPath:async e=>{let t=await
|
|
361
|
-
`))};import rg from"node:fs/promises";import al from"node:path";import
|
|
362
|
-
`).map(t=>{let r=t.indexOf(" ");return r===-1?null:K(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),pP=async()=>{let e=await lP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return dP(e.stdout)},uP=async()=>{let e=await ut();return e?(await qr(e)).map(r=>r.name):[]},yo=async()=>{let[e,t]=await Promise.allSettled([pP(),uP()]);return e.status==="rejected"&&p.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&p.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),ul({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import mP from"node:fs";import fP from"node:path";var wl=[".claude/settings.json",".claude/settings.local.json"],gP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],hP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),yP=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},vP=(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(hP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},wP=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},kP=()=>fr.filter(e=>e.mutating),bP=e=>{let t=yP(e);return t===null?[]:kP().filter(r=>gP.some(n=>wP(r).some(o=>vP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},RP=(e,t)=>{let r;try{r=mP.readFileSync(fP.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}},pg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of wl){let n=RP(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=bP(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var PP=e=>e.every(t=>t.status!=="fail"),SP=["brew","git","gh","doppler","aws"],EP=async e=>{let t=await mo(SP,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},yt=async(e,t,r,n)=>{try{return await cr()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},xP=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)"}},Pg=(e,t,r,n)=>{let o=pe.join(Rg.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!re.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=re.readFileSync(o,"utf-8"),a=i.indexOf(sr),c=i.indexOf(_t);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+_t.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`}},TP=()=>Pg("zshrc init block",".zshrc","shell",Wf()),CP=()=>Pg("zshenv session block",".zshenv","session-env",Qc()),$P=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await S(),r=pe.join(t,"pnpm-workspace.yaml");if(!re.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=re.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}`}}},AP=async()=>{try{return Ct(),{config:await I(),error:null}}catch(e){return{config:null,error:e}}},OP=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)"}},DP=384,kl=448,IP=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(", "),NP=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}}})),_P=async(e,t={})=>{let r="env tokens configured",n=t.readStore??ue,o=t.resolveToken??ao;if(!e.config)return{name:r,status:"skip",message:"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 NP(await pr(),o);return{name:r,status:"pass",message:IP(s)}},MP=()=>nt.env[de]||void 0,jP=async(e={})=>{let t="tokens.json present",r=e.readStore??ue,n=e.storePath??ct;if((e.readEnvToken??MP)())return{name:t,status:"skip",message:`${de} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",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 ${de} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},vo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},FP=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??ct,o=t.statPath??LP,s=t.chmodPath??re.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(vo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=pe.dirname(i),c=pe.dirname(a),l=pe.dirname(c),u=[{target:l,expected:kl,actual:vo(l,o)},{target:c,expected:kl,actual:vo(c,o)},{target:a,expected:kl,actual:vo(a,o)},{target:i,expected:DP,actual:vo(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(u.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=u.map(g=>`${w(g.target)} is ${ug(g.actual)}, expected ${ug(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of u)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},ug=e=>`0${e.toString(8).padStart(3,"0")}`,LP=e=>{try{return re.statSync(e)}catch{return null}},VP=async()=>{let e="user override path";try{let t=await te(),r=re.existsSync(t.userProject),n=await co(t.userProject,r),o=r?lo(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}}},BP=async()=>{let e="legacy user-global config",t;try{t=await te()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=pe.join(pe.dirname(t.userGlobal),"config.json");return re.existsSync(r)?re.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"}},WP={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},JP=async e=>{let t=WP[e];try{return await cr()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},UP=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=Tt(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=>JP(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("; ")}},mg=/^\d+\.\d+\.\d+$/,GP=(e,t)=>e===t||!mg.test(e)||!mg.test(t)?!1:mn([`v${e}`,`v${t}`])[0]===`v${e}`,KP=async(e,t)=>{let r;try{r=await ke(e)}catch{return[]}let n=[];for(let o of r){let s=Zt(Qt(pe.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&GP(s.version,t)&&n.push(s.version)}return n},HP=async(e,t)=>{let r=await KP(e,t);if(r.length===0)return"";let n=mn(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`},qP=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await te()).main}catch{return e}if(!re.existsSync(t))return e;let r=pe.dirname(t),n=pe.join(r,"CLAUDE.md"),o=re.existsSync(n)?re.readFileSync(n,"utf-8"):"",s=ze(o,Ae,Ye),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await HP(r,q.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},zP=async()=>{try{let e=(await te()).main;return re.existsSync(e)?pe.dirname(e):null}catch{return null}},YP=e=>{let t=fu();return t===null||!In(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Vr}`},XP=e=>{let t=e.kind==="installed"?ms(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 ${H} version ${t}${YP(t)}`}},fg=3,gg=(e,t)=>he(e)===he(t),ZP=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(gg(e.projectDir,e.gitRoot))return"";let r=Cn(e.gitRoot,he(e.projectDir),he)?"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 gg(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}`},QP=(e,t)=>{let r="plugin installed",n=ZP(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${H} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${H} is not installed. Run: ${dt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-fg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,fg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${H} is installed for ${a} only, not this project. Run: ${dt}${n}`}},eS=()=>yt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),tS=(e,...t)=>{try{return JSON.parse(re.readFileSync(pe.join(e,...t),"utf-8"))}catch{return null}},rS=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ms(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=tS(r,Oe),o=n!==null&&typeof n=="object"?n[Ze]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},hg=e=>`Plugin ${H} ${e===null?"(version unreadable)":e}`,nS=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: ${dt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${hg(e.version)} still carries an MCP server in its ${Oe}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Vr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${hg(e.version)} is skills-only \u2014 no ${Oe}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},oS=(e,t)=>{let r=qt(e===null?{}:{projectPath:e}),n=Dn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ae} is known to Claude Code`:`Marketplace ${ae} is not registered. Run: claude plugin marketplace add ${Et}`},QP(r,t),XP(r),nS(rS(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${q.version}`}]},sS=({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(", ")},iS=e=>{let t="Agent mode",r=ss(e),n=sS(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})`}},yg=4,aS=e=>{let t=e.slice(0,yg).join(", "),r=e.length-yg;return r>0?`${t} +${r} more`:t},cS=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=pg(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"} (${aS(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 ${wl.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`}},lS=(e,t)=>{let r=Math.floor((t-Date.parse(e))/36e5);return Number.isNaN(r)?"age unknown":r>=24?`${Math.floor(r/24)}d old`:`${Math.max(r,0)}h old`},dS=async(e,t=Date.now())=>{let r="merge-dev resolutions";if(e===null)return{name:r,status:"skip",message:"no git root"};let n;try{n=await gf(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${lS(i.createdAt,t)}, ${a})`}),s=n.map(i=>i.branch).join(",");return{name:r,status:"warn",message:`${n.length} unfinished merge-dev hand-off${n.length===1?"":"s"}: ${o.join("; ")} \u2014 finish with: infra-kit release merge-dev --continue --versions ${s}, or drop with --abort`}},Sg=e=>ha(["trust"],{bin:e}),pS=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),vg="ERR_TLS_CERT_ALTNAME_INVALID",Eg=()=>`portless serving TLS on :${xt}`,uS=async(e,t,r)=>{let n=Eg();return await e(xt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${xt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${xt}. Install it once (needs root): \`${Pt(t,r)}\`.`}},mS=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(xt,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(vg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${vg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>pS.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${Sg(n)}\`, or reinstall: \`${Pt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},fS=(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: \`${Sg(r)}\` (no sudo needed).`}},gS=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 \`${ha(["alias","--remove","<name>"],{bin:r})}\`.`}},Lt="portless service target",ko=e=>({name:Lt,status:"warn",message:e}),xg=e=>e==="darwin"?Wp:e==="linux"?Jp:null,hS=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Bp}`:`sudo systemctl restart ${Up}`,yS="/bin/ps",vS=e=>{try{let t=bg(yS,["-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}},wg=e=>{try{return re.readFileSync(e,"utf-8")}catch{return null}},wS=e=>{try{return re.statSync(e).mtime}catch{return null}},kS=2e3,bS=e=>{try{let t=bg(e,["-p","process.version"],{encoding:"utf-8",timeout:kS}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},RS=(e,t)=>({platform:e.platform??nt.platform,readServiceFile:e.readServiceFile??wg,readFile:e.readFile??wg,exists:e.exists??re.existsSync,realpath:e.realpath??he,mtime:e.mtime??wS,execPath:e.execPath??nt.execPath,home:e.home??Rg.homedir(),cwd:e.cwd??nt.cwd(),repoRoot:e.repoRoot??io,stateDir:(e.stateDir??Kp)(),processStartTime:e.processStartTime??vS,version:e.version??nt.version,arch:e.arch??nt.arch,nodeVersionOf:e.nodeVersionOf??bS,isGlobal:e.isGlobal??os().node.isGlobal,nodeFs:e.nodeFs??re,stableNode:null,stableNodeSidecar:null,bin:t}),bo="portless node",gr="~/.infra-kit/node",wo=e=>({row:{name:bo,status:"fail",message:e},stableNode:null,sidecar:null}),kg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},PS=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,SS=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,ES=e=>{let t=Xp(e.home),r=kg(e.nodeFs.lstatSync,t);if(r===void 0)return wo(`${gr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return wo(`${gr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Zp(e.home,e.nodeFs);if(n===null)return wo(`${gr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=kg(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 wo(`${gr} 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(!SS(c,e))return wo(`${gr} does not run as Node ${e.version} (${PS(c)}). Re-run through the current Node: \`${Pt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:bo,status:"pass",message:`${gr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},xS=e=>{if(xg(e.platform)===null)return{row:{name:bo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=ES(e);return e.isGlobal()?t:{...t,row:{name:bo,status:"skip",message:`not a global install; the global infra-kit keeps ${gr} current`}}},Tg=(e,t)=>{let r=RS(e,t),n=xS(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},TS=(e,t)=>{let r=t.readFile(pe.join(e,"package.json"));try{let n=r===null?null:fe.object({version:fe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},CS=e=>{let t=Number.parseInt(e.readFile(pe.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},$S=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},AS=(e,t,r)=>{let n=CS(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o($S(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(pe.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},OS=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Cn(await t.repoRoot()??r,e,t.realpath)},hr=e=>({state:"drifted",row:e}),DS=async(e,t,r)=>{let n=Pt(r.bin,r);if(!r.exists(e))return hr({name:Lt,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=pe.join(ya(r.home),"dist","cli.js");if(t!==o)return hr(ko(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(ns(r.home,r.exists)===null)return hr({name:Lt,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(ya(r.home));if(await OS(s,r))return hr({name:Lt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=IS(e,n,r);if(i!==null)return i;let a=TS(s,r),c=AS(s,a,r);return c!==null?{state:"converged",row:ko(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${hS(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Lt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},IS=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:hr(ko(`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:hr(ko(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Cg=async e=>{let t=xg(e.platform);if(t===null)return{state:"absent",row:{name:Lt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Lt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=_m(e.platform,r)??[];return n===void 0||o===void 0?hr(ko(`could not parse ${t} \u2014 re-run \`${Pt(e.bin,e)}\` to rewrite it.`)):DS(n,o,e)},$g=async(e,t)=>{let{seams:r}=Tg(e,t);return{state:(await Cg(r)).state,stableNode:r.stableNode}},NS=()=>[bo,Lt,Eg(),"portless CA chain valid","portless CA trusted","portless routes"],_S=async(e={})=>{let t=e.resolveBin??Vp,r=e.isProxyServing??Gp,n=e.handshake??zp,o=e.caTrusted??qp,s=e.routes??An,i=e.isListening??$n,a=(e.caPath??Hp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...NS().map(P=>({name:P,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:u}=Tg(e,c),m=s(),g=await uS(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await mS(n,m,a,c,d);return[l,u,(await Cg(d)).row,g,y,fS(o(),a,c),await gS(m,i,c)]},MS=async(e={})=>{let t="portless routes",r=e.routes??An,n=e.isListening??$n,o=e.devSessionRunning??Am,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=$m(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 l=e.removeAlias??Yp().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ai=async(e={})=>{let t=await AP(),r=EP(e.probeDeps??po()),n=async(m,g)=>{let[y,P]=await Promise.all([g,r]),v=P.get(m);return v===void 0?y:{...y,detail:v}},o=await Promise.all([n("brew",yt("brew installed",Ie("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",yt("git installed",Ie("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",yt("gh installed",Ie("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),yt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",yt("doppler installed",Ie("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",yt("aws installed",Ie("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")),yt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),yt("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"),xP(),Promise.resolve(TP()),Promise.resolve(CP()),$P(),Promise.resolve(OP(t)),jP(),_P(t),FP(e.fix??!1),VP(),BP(),UP(t)]),s=await _S(e.portlessDeps);if(e.fix){let m=await MS(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await zP(),a=await io(),c={projectDir:nt.env.CLAUDE_PROJECT_DIR||null,cwd:nt.cwd(),gitRoot:a},l=[await eS(),...oS(i,c),iS({env:nt.env,stdinIsTTY:nt.stdin.isTTY===!0,flag:A.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:cS(a)],d=[...o,await dS(a),...s,...await qP(),...l],u={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:bc.has(m.name),detail:m.detail})),allPassed:PP(d),cliVersion:q.version};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},bl=R({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:fe.array(fe.object({name:fe.string().describe("Name of the check"),status:fe.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:fe.string().describe("Details about the check result"),fixable:fe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:fe.object({manager:fe.string().describe("Which package manager owns this install, read from its resolved path"),version:fe.string().nullable().describe("The version the tool reported, or null"),present:fe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:fe.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:fe.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:fe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ai()});import{spawn as US}from"node:child_process";import El from"node:process";import{z as V}from"zod";import{describeProxyRoutes as jS,loadDev as FS,readLocalContext as LS,slugifyHostLabel as Ag}from"@slip-stream-kit/config/internal";import Og from"node:fs";import gn from"node:path";import Rl from"node:process";import{z as Pl}from"zod";var VS=async e=>{let t=gn.join(e,"apps"),r=Og.existsSync(t)?Og.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=gn.join(t,o,"tests"),i=await Oa(s).catch(()=>{});i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},BS=(e,t)=>{let[r,n]=gn.relative(e,t).split(gn.sep);return r==="apps"&&n?n:void 0},WS=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(BS(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target, baseUrlEnv }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new x({status:"argument_required",argument:a,choices:Pl.toJSONSchema(Pl.object({app:Pl.enum(i)})),agentMode:A.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},JS=async(e,t,r)=>Promise.all(e.map(async n=>{if(n.source==="cloud")return{...n,live:null};let o=t.get(n.packageName)??0,s=o>0&&await r({tag:`${n.packageName}`,port:o,kind:"api"})==="ok";return{...n,live:s}})),Sl=async(e,t={})=>{let r=t.cwd??Rl.cwd(),n=t.projectRoot??await S(),o=(t.env??Rl.env)[st]||null,s=t.healthProbe??Ju,i=WS(await VS(n),e,r,n),{target:a,baseUrlEnv:c,cloud:l}=i.e2e,[d,u]=a.split("/"),m=gn.join(n,"apps",d,u),g=(await zt(m)).name;if(!g)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${gn.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${m} has no package.json name`});let y=Uu(m),P=`${y}.${Ag(g)}.localhost`,v=LS(m),C=`https://${P}`,_=0;if(u==="ui")_=(t.listRoutes??An)().find(j=>j.name===P||j.name===`${y}.${Ag(g)}`)?.port??0;else{let j=v.info.get(g);_=j?.port??0,C=j?.origin??C}let O=_>0&&await s({tag:a,port:_,kind:u})==="ok",E={app:i.app,testsDir:i.testsDir,target:a,packageName:g,baseUrlEnv:c,release:y,env:o,localUrl:C};if(O){let j=u==="ui"?await FS(m):void 0,Ke=j?.proxy?jS({proxy:j.proxy,localContext:v,env:o??void 0,getRelease:()=>y}):[],xe=new Map([...v.info].map(([fa,Yo])=>[fa,Yo.port]));return{...E,mode:"local",baseUrl:C,routes:await JS(Ke,xe,s)}}let G=t.env??Rl.env,B=l?o&&l.replaceAll("<env>",o):G[c];if(!o||!B){let j=o?`${c} is not set (and \`e2e.cloud\` is not configured)`:`${st} is not set`;throw new f(void 0,{operation:`resolve where ${i.app}'s e2e tests run`,remediation:"start the dev server (`infra-kit dev`), or load an environment (`infra-kit env-load -c <env>`) to run against cloud",stderrExcerpt:`nothing serves ${a} at ${C}, and ${j}`})}return{...E,mode:"cloud",baseUrl:B,routes:[]}};var GS=e=>{let t=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl} (${e.baseUrlEnv})`,e.mode==="local"?` dev server for ${e.target} on release "${e.release}"`:` nothing serves ${e.target} at ${e.localUrl}; cloud env "${e.env}" (${st})`];for(let r of e.routes){let n="";r.live!==null&&(n=r.live?" \u2014 live":" \u2014 NOT responding"),t.push(` ${r.path.padEnd(24)} ${r.source.padEnd(5)} ${r.target??"(unresolved)"}${n}`)}return t.join(`
|
|
363
|
-
`)},
|
|
354
|
+
${_t}`;var MR="Could not find requested project",jR="Could not find requested config",Jf="Invalid Auth token",Uf="does not have access to requested config",ir=e=>e.includes(Jf)||e.includes(Uf)?"auth":e.includes(MR)?"project":e.includes(jR)?"config":"unknown",ar=e=>e.includes(Uf)?"mis-scoped":e.includes(Jf)?"revoked":null;var Gf=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(`
|
|
355
|
+
`),sn=class extends hs{authKind;constructor(t,r=null,n){super(n??Gf(t),t),this.name="DopplerAuthError",this.authKind=r}};var el=({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(`
|
|
356
|
+
`)};import{$ as ei}from"zx";var FR=5e3,LR="DOPPLER_CONFIG",We=async()=>{let{envManagement:e}=await D();return e.config.name},tl=async({childEnv:e,project:t,config:r})=>{let n=ei.quiet;ei.quiet=!0;try{let s=(await ei({env:e})`doppler secrets get ${LR} --plain --project ${t} --config ${r}`.timeout(FR)).stdout.trim();return s!==r?{outcome:"mis-scoped",scopedTo:s}:{outcome:"valid",scopedTo:s}}catch(o){return{outcome:VR(o)}}finally{ei.quiet=n}},VR=e=>{let t=$r(e)??(e instanceof Error?e.message:String(e));return ir(t)!=="auth"?"unreachable":ar(t)??"unreachable"};import BR from"node:process";var de="INFRA_KIT_ENV_TOKEN",co=async e=>{let t=BR.env[de];if(t)return{token:t,source:"env"};let n=(await ue())?.envs[e];if(n)return{token:n,source:"store"};throw new hs(WR(e,await lt()),e)},WR=(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 ${de} instead \u2014 it takes precedence and needs no home config.`].join(`
|
|
357
|
+
`);import JR from"node:fs/promises";var lo=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await JR.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}}},po=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import GR from"node:fs";import KR from"node:os";import Kf from"node:path";import HR from"node:process";import{$ as UR}from"zx";var cr=()=>UR({quiet:!0});var qR=()=>[Kf.join(KR.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],zR=async e=>{try{return(await cr()`command -v ${e}`).stdout.trim()||null}catch{return null}},uo=()=>({runCommand:async e=>{let t=await cr()`${e}`;return{stdout:`${t.stdout}
|
|
358
|
+
${t.stderr}`}},resolveBinPath:async e=>{let t=await zR(e);return t!==null?t:qR().map(r=>Kf.join(r,e)).find(r=>GR.existsSync(r))??null},realpath:he,platform:HR.platform});var Mt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),an=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,cn=["darwin","linux"],oi=e=>t=>ga(t,e)?"homebrew":"unknown",si=(e,t)=>r=>r===null?null:t(e(r),r),nl=e=>si(oi(e.kegName),t=>t==="homebrew"?Mt(["brew","upgrade",e.brewFormula]):null),Hf=e=>rs(e,"Homebrew")||rs(e,"homebrew")?"homebrew":"unknown",YR={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:an,platforms:cn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Hf,updateFor:si(Hf,e=>e==="homebrew"?Mt(["brew","update"]):null)},rl={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Yf="https://awscli.amazonaws.com/v2/install.sh",Xf={steps:[["/bin/bash","-c",`curl -fsSL ${Yf} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},XR="/usr/local/aws-cli",ZR=e=>$n(XR,e,he)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Yf} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Xf,qf=e=>ga(e,rl.kegName)?"homebrew":rs(e,"aws-cli")?"script":"unknown",QR={id:"aws",binName:"aws",...rl,probeArgv:["aws","--version"],versionFrom:an,platforms:cn,prerequisites:[],bootstrapInstall:Xf,identify:qf,updateFor:si(qf,(e,t)=>e==="homebrew"?Mt(["brew","upgrade",rl.brewFormula]):e==="script"?ZR(t):null)},ti={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},eP={id:"git",binName:"git",...ti,probeArgv:["git","--version"],versionFrom:an,platforms:cn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install",ti.brewInstallSpec]),identify:oi(ti.kegName),updateFor:nl(ti)},ri={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},tP={id:"gh",binName:"gh",...ri,probeArgv:["gh","--version"],versionFrom:an,platforms:cn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install",ri.brewInstallSpec]),identify:oi(ri.kegName),updateFor:nl(ri)},ni={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},rP={id:"doppler",binName:"doppler",...ni,probeArgv:["doppler","--version"],versionFrom:an,platforms:cn,prerequisites:["brew"],bootstrapInstall:Mt(["brew","install","gnupg"],["brew","install",ni.brewInstallSpec]),identify:oi(ni.kegName),updateFor:nl(ni)},mo="portless",zf=e=>Mp(e,mo)===null?"unknown":"npm",nP={id:"portless",binName:mo,npmPackage:mo,probeArgv:["portless","--version"],versionFrom:an,platforms:[...cn,"win32"],prerequisites:[],bootstrapInstall:Mt(["npm","install","-g",mo]),identify:zf,updateFor:si(zf,e=>e==="npm"?Mt(["npm","install","-g",`${mo}@latest`]):null)},ol={brew:YR,git:eP,aws:QR,gh:tP,doppler:rP,portless:nP},lr=Object.keys(ol),De=e=>ol[e],sl=(e,t)=>e.platforms.includes(t),il=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 De(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Zf=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Qf=async(e,t)=>{try{return await e(t)}catch{return null}},oP=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},eg=async(e,t)=>{if(!sl(e,t.platform))return Zf(e.id);let r=await Qf(t.runCommand,e.probeArgv),n=await oP(t,e.binName);if(r==null&&n==null)return Zf(e.id);let o=r??(n==null?null:await Qf(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)}},fo=async(e,t)=>Promise.all(e.map(r=>eg(De(r),t)));var tg=["prod"],ln={allowed:!1,reason:"disallow"},jt=e=>tg.includes(e),sP=["dev","stage"],dn=e=>sP.includes(e)||jt(e),gt=(e,t=ln)=>t.allowed?e:e.filter(r=>!jt(r)),dr=(e,t,r=ln)=>{if(!r.allowed&&jt(e))throw r.reason==="agent-blocked"?new x({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 Je=async()=>{let e;try{e=(await D()).protectedEnvs??"disallow"}catch{return ln}return e==="disallow"?ln:e==="cli-only"&&Q()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var go=e=>{let{env:t,branch:r}=e;jt(t)&&p.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(`
|
|
359
|
+
`))};import rg from"node:fs/promises";import al from"node:path";import iP from"yaml";var ng=".github/workflows",ht=async e=>{let t=await S();return og(al.resolve(t,ng,e))},cl=async()=>{let e=await S(),t=al.resolve(e,ng),r;try{r=await rg.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>og(al.resolve(t,s))));return[...new Set(o.flat())]},og=async e=>{let t;try{t=iP.parse(await rg.readFile(e,"utf-8"))}catch{return[]}let r=pn(t,"on")??pn(t,"true"),n=pn(pn(pn(pn(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},pn=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var un=async()=>{let e=await cl(),t=await ue(),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]},pr=async()=>(await un()).map(t=>t.env);import{$ as uP}from"zx";import{z as sg}from"zod";var ig=/^\d{4}-\d{2}-\d{2}$/,ho=e=>{if(!ig.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},ag=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,mn=class extends Error{constructor(t){super(ag(t)),this.name="InvalidReleaseDateError"}},ur=e=>{let t=e.trim();if(!ho(t))throw new mn(t);return t},yo=e=>{let t=e.trim();return t===""||ho(t)?!0:ag(t)},ll=sg.string().refine(ho,{message:"Expected a calendar date in yyyy-mm-dd form."}),dl=sg.string().refine(e=>e===""||ho(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Ft=e=>e.slice(1).split(".").map(Number),fn=e=>[...e].sort((t,r)=>{let[n,o,s]=Ft(t),[i,a,c]=Ft(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var lg="next",aP=/^v?(\d+)\.(\d+)\.(\d+)$/,cP=e=>e.replace(/^.*release\//,""),pl=e=>{let t=cP(e.trim()),r=aP.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},cg=e=>`${e[0]}.${e[1]}.${e[2]}`,ul=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=pl(o);if(!s)continue;let i=cg(s);n.has(i)||(n.add(i),r.push(s))}return fn(r.map(o=>cg(o))).map(o=>Ft(`v${o}`))},mr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},ml=(e,t)=>{if(e.length===0)throw new mr;let r=e[e.length-1];if(t==="hotfix"){let[s,i]=r,a=e.reduce((c,l)=>l[0]===s&&l[1]===i?Math.max(c,l[2]):c,0);return`${s}.${i}.${a+1}`}let[n,o]=r;return`${n}.${o+1}.0`},gn=(e,t)=>{try{return ml(e,t)}catch(r){if(r instanceof mr)return null;throw r}},fl=e=>e.trim().toLowerCase()===lg,ai=e=>fl(e)||pl(e)!==null?{version:e}:{name:e},lP=e=>e==="regular"||e==="hotfix",dg=e=>"name"in e,dP=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:ur(n)}},gl=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=dP(r===-1?t:t.slice(0,r)),s="regular",i="";if(r!==-1){let a=t.slice(r+1),c=a.indexOf(":"),l=c===-1?a.trim():a.slice(0,c).trim();i=c===-1?"":a.slice(c+1).trim();let d=l.toLowerCase();if(!lP(d))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=d}return ii({...ai(n),type:s},{description:i,releaseDate:o})},hl=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},ii=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},pP=e=>{let t=e.name.trim();return as(t),ii({id:{kind:"name",name:t,raw:t},type:e.type},e)},yl=(e,t)=>{let r=[...t];return e.map(n=>{if(dg(n))return pP(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(fl(o)){let a=ml(r,n.type);return r.push(Ft(`v${a}`)),ii({id:ve(a),type:n.type},n)}let s=pl(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),ii({id:ve(i),type:n.type},n)})},vl=e=>e.some(t=>!dg(t)&&fl(t.version));var mP=e=>e.split(`
|
|
360
|
+
`).map(t=>{let r=t.indexOf(" ");return r===-1?null:K(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),fP=async()=>{let e=await uP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return mP(e.stdout)},gP=async()=>{let e=await mt();return e?(await qr(e)).map(r=>r.name):[]},vo=async()=>{let[e,t]=await Promise.allSettled([fP(),gP()]);return e.status==="rejected"&&p.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&p.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),ul({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import hP from"node:fs";import yP from"node:path";var wl=[".claude/settings.json",".claude/settings.local.json"],vP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],wP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),kP=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},bP=(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(wP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},RP=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},PP=()=>fr.filter(e=>e.mutating),SP=e=>{let t=kP(e);return t===null?[]:PP().filter(r=>vP.some(n=>RP(r).some(o=>bP(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},EP=(e,t)=>{let r;try{r=hP.readFileSync(yP.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}},pg=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of wl){let n=EP(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=SP(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var xP=e=>e.every(t=>t.status!=="fail"),TP=["brew","git","gh","doppler","aws"],CP=async e=>{let t=await fo(TP,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},yt=async(e,t,r,n)=>{try{return await cr()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},$P=async()=>{let e="orca installed",t=await Ir();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)"}},Pg=(e,t,r,n)=>{let o=pe.join(Rg.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!re.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=re.readFileSync(o,"utf-8"),a=i.indexOf(sr),c=i.indexOf(_t);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+_t.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`}},AP=()=>Pg("zshrc init block",".zshrc","shell",Wf()),OP=()=>Pg("zshenv session block",".zshenv","session-env",Qc()),IP=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await S(),r=pe.join(t,"pnpm-workspace.yaml");if(!re.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=re.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}`}}},DP=async()=>{try{return Ct(),{config:await D(),error:null}}catch(e){return{config:null,error:e}}},NP=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)"}},_P=384,kl=448,MP=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(", "),jP=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}}})),FP=async(e,t={})=>{let r="env tokens configured",n=t.readStore??ue,o=t.resolveToken??co;if(!e.config)return{name:r,status:"skip",message:"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 jP(await pr(),o);return{name:r,status:"pass",message:MP(s)}},LP=()=>ot.env[de]||void 0,VP=async(e={})=>{let t="tokens.json present",r=e.readStore??ue,n=e.storePath??lt;if((e.readEnvToken??LP)())return{name:t,status:"skip",message:`${de} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",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 ${de} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},wo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},BP=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??lt,o=t.statPath??WP,s=t.chmodPath??re.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(wo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=pe.dirname(i),c=pe.dirname(a),l=pe.dirname(c),u=[{target:l,expected:kl,actual:wo(l,o)},{target:c,expected:kl,actual:wo(c,o)},{target:a,expected:kl,actual:wo(a,o)},{target:i,expected:_P,actual:wo(i,o)}].filter(g=>g.actual!==null&&g.actual!==g.expected);if(u.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=u.map(g=>`${w(g.target)} is ${ug(g.actual)}, expected ${ug(g.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit doctor --fix\`, or chmod them by hand.`};for(let g of u)s(g.target,g.expected);return{name:r,status:"pass",message:`Tightened ${u.length} path(s): ${m}`}},ug=e=>`0${e.toString(8).padStart(3,"0")}`,WP=e=>{try{return re.statSync(e)}catch{return null}},JP=async()=>{let e="user override path";try{let t=await te(),r=re.existsSync(t.userProject),n=await lo(t.userProject,r),o=r?po(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}}},UP=async()=>{let e="legacy user-global config",t;try{t=await te()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=pe.join(pe.dirname(t.userGlobal),"config.json");return re.existsSync(r)?re.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"}},GP={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"}},KP=async e=>{let t=GP[e];try{return await cr()`${t.command}`,{ok:!0,label:t.label,failMsg:t.failMsg}}catch{return{ok:!1,label:t.label,failMsg:t.failMsg}}},HP=async e=>{let t="ide installed";if(!e.config)return{name:t,status:"skip",message:"infra-kit config could not be read (see config check)"};let r=Tt(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=>KP(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("; ")}},mg=/^\d+\.\d+\.\d+$/,qP=(e,t)=>e===t||!mg.test(e)||!mg.test(t)?!1:fn([`v${e}`,`v${t}`])[0]===`v${e}`,zP=async(e,t)=>{let r;try{r=await ke(e)}catch{return[]}let n=[];for(let o of r){let s=Zt(Qt(pe.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&qP(s.version,t)&&n.push(s.version)}return n},YP=async(e,t)=>{let r=await zP(e,t);if(r.length===0)return"";let n=fn(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`},XP=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await te()).main}catch{return e}if(!re.existsSync(t))return e;let r=pe.dirname(t),n=pe.join(r,"CLAUDE.md"),o=re.existsSync(n)?re.readFileSync(n,"utf-8"):"",s=ze(o,Ae,Ye),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await YP(r,q.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},ZP=async()=>{try{let e=(await te()).main;return re.existsSync(e)?pe.dirname(e):null}catch{return null}},QP=e=>{let t=gu();return t===null||!Nn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Vr}`},eS=e=>{let t=e.kind==="installed"?fs(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 ${H} version ${t}${QP(t)}`}},fg=3,gg=(e,t)=>he(e)===he(t),tS=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(gg(e.projectDir,e.gitRoot))return"";let r=$n(e.gitRoot,he(e.projectDir),he)?"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 gg(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}`},rS=(e,t)=>{let r="plugin installed",n=tS(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,d=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${H} installed (${c??"unknown"} scope${d})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${H} is not installed. Run: ${pt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-fg,i=s>0?` and ${s} more`:"",a=`${o.slice(0,fg).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${H} is installed for ${a} only, not this project. Run: ${pt}${n}`}},nS=()=>yt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first"),oS=(e,...t)=>{try{return JSON.parse(re.readFileSync(pe.join(e,...t),"utf-8"))}catch{return null}},sS=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=fs(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=oS(r,Oe),o=n!==null&&typeof n=="object"?n[Ze]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},hg=e=>`Plugin ${H} ${e===null?"(version unreadable)":e}`,iS=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: ${pt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${hg(e.version)} still carries an MCP server in its ${Oe}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Vr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${hg(e.version)} is skills-only \u2014 no ${Oe}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},aS=(e,t)=>{let r=qt(e===null?{}:{projectPath:e}),n=Dn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ae} is known to Claude Code`:`Marketplace ${ae} is not registered. Run: claude plugin marketplace add ${Et}`},rS(r,t),eS(r),iS(sS(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${q.version}`}]},cS=({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(", ")},lS=e=>{let t="Agent mode",r=is(e),n=cS(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})`}},yg=4,dS=e=>{let t=e.slice(0,yg).join(", "),r=e.length-yg;return r>0?`${t} +${r} more`:t},pS=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=pg(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"} (${dS(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 ${wl.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`}},uS=(e,t)=>{let r=Math.floor((t-Date.parse(e))/36e5);return Number.isNaN(r)?"age unknown":r>=24?`${Math.floor(r/24)}d old`:`${Math.max(r,0)}h old`},mS=async(e,t=Date.now())=>{let r="merge-dev resolutions";if(e===null)return{name:r,status:"skip",message:"no git root"};let n;try{n=await gf(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${uS(i.createdAt,t)}, ${a})`}),s=n.map(i=>i.branch).join(",");return{name:r,status:"warn",message:`${n.length} unfinished merge-dev hand-off${n.length===1?"":"s"}: ${o.join("; ")} \u2014 finish with: infra-kit release merge-dev --continue --versions ${s}, or drop with --abort`}},Sg=e=>ha(["trust"],{bin:e}),fS=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),vg="ERR_TLS_CERT_ALTNAME_INVALID",Eg=()=>`portless serving TLS on :${xt}`,gS=async(e,t,r)=>{let n=Eg();return await e(xt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${xt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${xt}. Install it once (needs root): \`${Pt(t,r)}\`.`}},hS=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(d=>d.name)],c=(await Promise.all(i.map(async d=>({servername:d,result:await e(xt,d)})))).filter(d=>!d.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(d=>d.result.ok?"":d.result.code);return l.includes(vg)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${vg} for servername(s) ${c.map(d=>d.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(d=>fS.has(d))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${Sg(n)}\`, or reinstall: \`${Pt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},yS=(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: \`${Sg(r)}\` (no sudo needed).`}},vS=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 \`${ha(["alias","--remove","<name>"],{bin:r})}\`.`}},Lt="portless service target",bo=e=>({name:Lt,status:"warn",message:e}),xg=e=>e==="darwin"?Jp:e==="linux"?Up:null,wS=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Wp}`:`sudo systemctl restart ${Gp}`,kS="/bin/ps",bS=e=>{try{let t=bg(kS,["-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}},wg=e=>{try{return re.readFileSync(e,"utf-8")}catch{return null}},RS=e=>{try{return re.statSync(e).mtime}catch{return null}},PS=2e3,SS=e=>{try{let t=bg(e,["-p","process.version"],{encoding:"utf-8",timeout:PS}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},ES=(e,t)=>({platform:e.platform??ot.platform,readServiceFile:e.readServiceFile??wg,readFile:e.readFile??wg,exists:e.exists??re.existsSync,realpath:e.realpath??he,mtime:e.mtime??RS,execPath:e.execPath??ot.execPath,home:e.home??Rg.homedir(),cwd:e.cwd??ot.cwd(),repoRoot:e.repoRoot??ao,stateDir:(e.stateDir??Hp)(),processStartTime:e.processStartTime??bS,version:e.version??ot.version,arch:e.arch??ot.arch,nodeVersionOf:e.nodeVersionOf??SS,isGlobal:e.isGlobal??ss().node.isGlobal,nodeFs:e.nodeFs??re,stableNode:null,stableNodeSidecar:null,bin:t}),Ro="portless node",gr="~/.infra-kit/node",ko=e=>({row:{name:Ro,status:"fail",message:e},stableNode:null,sidecar:null}),kg=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},xS=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,TS=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,CS=e=>{let t=Zp(e.home),r=kg(e.nodeFs.lstatSync,t);if(r===void 0)return ko(`${gr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return ko(`${gr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Qp(e.home,e.nodeFs);if(n===null)return ko(`${gr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=kg(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 ko(`${gr} 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(!TS(c,e))return ko(`${gr} does not run as Node ${e.version} (${xS(c)}). Re-run through the current Node: \`${Pt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Ro,status:"pass",message:`${gr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},$S=e=>{if(xg(e.platform)===null)return{row:{name:Ro,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=CS(e);return e.isGlobal()?t:{...t,row:{name:Ro,status:"skip",message:`not a global install; the global infra-kit keeps ${gr} current`}}},Tg=(e,t)=>{let r=ES(e,t),n=$S(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},AS=(e,t)=>{let r=t.readFile(pe.join(e,"package.json"));try{let n=r===null?null:fe.object({version:fe.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},OS=e=>{let t=Number.parseInt(e.readFile(pe.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},IS=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},DS=(e,t,r)=>{let n=OS(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(IS(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(pe.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},NS=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:$n(await t.repoRoot()??r,e,t.realpath)},hr=e=>({state:"drifted",row:e}),_S=async(e,t,r)=>{let n=Pt(r.bin,r);if(!r.exists(e))return hr({name:Lt,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=pe.join(ya(r.home),"dist","cli.js");if(t!==o)return hr(bo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(os(r.home,r.exists)===null)return hr({name:Lt,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(ya(r.home));if(await NS(s,r))return hr({name:Lt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=MS(e,n,r);if(i!==null)return i;let a=AS(s,r),c=DS(s,a,r);return c!==null?{state:"converged",row:bo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${wS(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Lt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},MS=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:hr(bo(`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:hr(bo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Cg=async e=>{let t=xg(e.platform);if(t===null)return{state:"absent",row:{name:Lt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Lt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Mm(e.platform,r)??[];return n===void 0||o===void 0?hr(bo(`could not parse ${t} \u2014 re-run \`${Pt(e.bin,e)}\` to rewrite it.`)):_S(n,o,e)},$g=async(e,t)=>{let{seams:r}=Tg(e,t);return{state:(await Cg(r)).state,stableNode:r.stableNode}},jS=()=>[Ro,Lt,Eg(),"portless CA chain valid","portless CA trusted","portless routes"],FS=async(e={})=>{let t=e.resolveBin??Bp,r=e.isProxyServing??Kp,n=e.handshake??Yp,o=e.caTrusted??zp,s=e.routes??On,i=e.isListening??An,a=(e.caPath??qp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...jS().map(P=>({name:P,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:d,node:u}=Tg(e,c),m=s(),g=await gS(r,c,d),y=g.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await hS(n,m,a,c,d);return[l,u,(await Cg(d)).row,g,y,yS(o(),a,c),await vS(m,i,c)]},LS=async(e={})=>{let t="portless routes",r=e.routes??On,n=e.isListening??An,o=e.devSessionRunning??Om,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async d=>({name:d.name,port:d.port,live:await n(d.port)}))),{prunable:a,withheld:c}=Am(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 l=e.removeAlias??Xp().removeAlias;for(let d of a)await l(d);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ci=async(e={})=>{let t=await DP(),r=CP(e.probeDeps??uo()),n=async(m,g)=>{let[y,P]=await Promise.all([g,r]),v=P.get(m);return v===void 0?y:{...y,detail:v}},o=await Promise.all([n("brew",yt("brew installed",De("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",yt("git installed",De("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",yt("gh installed",De("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),yt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",yt("doppler installed",De("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",yt("aws installed",De("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")),yt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),yt("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"),$P(),Promise.resolve(AP()),Promise.resolve(OP()),IP(),Promise.resolve(NP(t)),VP(),FP(t),BP(e.fix??!1),JP(),UP(),HP(t)]),s=await FS(e.portlessDeps);if(e.fix){let m=await LS(),g=s.findIndex(y=>y.name===m.name);g>=0?s[g]=m:s.push(m)}let i=await ZP(),a=await ao(),c={projectDir:ot.env.CLAUDE_PROJECT_DIR||null,cwd:ot.cwd(),gitRoot:a},l=[await nS(),...aS(i,c),lS({env:ot.env,stdinIsTTY:ot.stdin.isTTY===!0,flag:A.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:pS(a)],d=[...o,await mS(a),...s,...await XP(),...l],u={checks:d.map(m=>({name:m.name,status:m.status,message:m.message,fixable:bc.has(m.name),detail:m.detail})),allPassed:xP(d),cliVersion:q.version};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},bl=R({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:fe.array(fe.object({name:fe.string().describe("Name of the check"),status:fe.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:fe.string().describe("Details about the check result"),fixable:fe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:fe.object({manager:fe.string().describe("Which package manager owns this install, read from its resolved path"),version:fe.string().nullable().describe("The version the tool reported, or null"),present:fe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:fe.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:fe.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:fe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ci()});import{spawn as HS}from"node:child_process";import El from"node:process";import{z as V}from"zod";import{describeProxyRoutes as VS,loadDev as BS,readLocalContext as WS,slugifyHostLabel as Ag}from"@slip-stream-kit/config/internal";import Og from"node:fs";import hn from"node:path";import Rl from"node:process";import{z as Pl}from"zod";var JS=async e=>{let t=hn.join(e,"apps"),r=Og.existsSync(t)?Og.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=hn.join(t,o,"tests"),i=await Oa(s).catch(()=>{});i?.e2e&&n.push({app:o,testsDir:s,e2e:i.e2e})}return n},US=(e,t)=>{let[r,n]=hn.relative(e,t).split(hn.sep);return r==="apps"&&n?n:void 0},GS=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(US(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new f(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target, baseUrlEnv }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new x({status:"argument_required",argument:a,choices:Pl.toJSONSchema(Pl.object({app:Pl.enum(i)})),agentMode:A.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},KS=async(e,t,r)=>Promise.all(e.map(async n=>{if(n.source==="cloud")return{...n,live:null};let o=t.get(n.packageName)??0,s=o>0&&await r({tag:`${n.packageName}`,port:o,kind:"api"})==="ok";return{...n,live:s}})),Sl=async(e,t={})=>{let r=t.cwd??Rl.cwd(),n=t.projectRoot??await S(),o=(t.env??Rl.env)[it]||null,s=t.healthProbe??Uu,i=GS(await JS(n),e,r,n),{target:a,baseUrlEnv:c,cloud:l}=i.e2e,[d,u]=a.split("/"),m=hn.join(n,"apps",d,u),g=(await zt(m)).name;if(!g)throw new f(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${hn.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${m} has no package.json name`});let y=Gu(m),P=`${y}.${Ag(g)}.localhost`,v=WS(m),C=`https://${P}`,_=0;if(u==="ui")_=(t.listRoutes??On)().find(j=>j.name===P||j.name===`${y}.${Ag(g)}`)?.port??0;else{let j=v.info.get(g);_=j?.port??0,C=j?.origin??C}let O=_>0&&await s({tag:a,port:_,kind:u})==="ok",E={app:i.app,testsDir:i.testsDir,target:a,packageName:g,baseUrlEnv:c,release:y,env:o,localUrl:C};if(O){let j=u==="ui"?await BS(m):void 0,Ke=j?.proxy?VS({proxy:j.proxy,localContext:v,env:o??void 0,getRelease:()=>y}):[],xe=new Map([...v.info].map(([fa,Xo])=>[fa,Xo.port]));return{...E,mode:"local",baseUrl:C,routes:await KS(Ke,xe,s)}}let G=t.env??Rl.env,B=l?o&&l.replaceAll("<env>",o):G[c];if(!o||!B){let j=o?`${c} is not set (and \`e2e.cloud\` is not configured)`:`${it} is not set`;throw new f(void 0,{operation:`resolve where ${i.app}'s e2e tests run`,remediation:"start the dev server (`infra-kit dev`), or load an environment (`infra-kit env-load -c <env>`) to run against cloud",stderrExcerpt:`nothing serves ${a} at ${C}, and ${j}`})}return{...E,mode:"cloud",baseUrl:B,routes:[]}};var qS=e=>{let t=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl} (${e.baseUrlEnv})`,e.mode==="local"?` dev server for ${e.target} on release "${e.release}"`:` nothing serves ${e.target} at ${e.localUrl}; cloud env "${e.env}" (${it})`];for(let r of e.routes){let n="";r.live!==null&&(n=r.live?" \u2014 live":" \u2014 NOT responding"),t.push(` ${r.path.padEnd(24)} ${r.source.padEnd(5)} ${r.target??"(unresolved)"}${n}`)}return t.join(`
|
|
361
|
+
`)},zS=e=>{let t=e.routes.filter(n=>n.source==="local"&&n.live!==!0);if(t.length===0)return;let r=t.map(n=>`${n.path} (${n.packageName})`);throw new f(void 0,{operation:`run ${e.app} e2e against the local dev server`,remediation:"check the backend rows in `infra-kit dev-status`, fix or restart it, then re-run",stderrExcerpt:`routes held local but their backend is not responding: ${r.join(", ")}`})},YS=async(e,t)=>{if(e.env===null||!jt(e.env))return;let r=await(t.protectedEnvAccess??Je)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?new x({status:"refused",env:e.env},2,{operation:n,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e.env}" is withheld from agents in this project`}):new f(void 0,{operation:n,remediation:"load a non-protected env (`infra-kit env-load -c dev`), or set `protectedEnvs` in infra-kit.json",stderrExcerpt:`"${e.env}" is a protected environment`})},XS=(e,t)=>new Promise((r,n)=>{let o=HS("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...El.env,[e.baseUrlEnv]:e.baseUrl},stdio:["inherit",at.enabled||ie()?2:"inherit","inherit"]});o.once("error",n),o.once("close",s=>{r(s??1)})}),li=async(e,t={})=>{let r=await Sl(e.app,t);p.info(qS(r));let n=(t.env??El.env)[r.baseUrlEnv];n&&n!==r.baseUrl&&p.info(` ${r.baseUrlEnv} was ${n} in this shell; the run uses ${r.baseUrl}`),r.mode==="local"?zS(r):await YS(r,t);let o={...r,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Ig({...o,ran:!1,exitCode:null});r.mode==="cloud"&&await W(e.yes,`Run ${r.app} e2e against ${r.baseUrl} ("${r.env}", shared)?`,{plan:o});let s=await(t.runPlaywright??XS)(r,e.playwrightArgs??[]);return s!==0&&(El.exitCode=s),Ig({...o,ran:!0,exitCode:s})},Ig=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),ZS={app:V.string(),testsDir:V.string(),target:V.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:V.string(),mode:V.enum(["local","cloud"]).describe("local: this worktree\u2019s dev server serves the target. cloud: it does not; the run uses the env-loaded baseUrlEnv, or e2e.cloud at env."),baseUrl:V.string().describe("The URL the run was pointed at, via the baseUrlEnv variable."),baseUrlEnv:V.string(),release:V.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:V.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),localUrl:V.string().describe("The local address probed, whether or not anything answered."),routes:V.array(V.object({path:V.string(),packageName:V.string(),source:V.enum(["local","cloud"]),target:V.string().nullable(),live:V.boolean().nullable()})).describe("Local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:V.array(V.string()),ran:V.boolean().describe("False for --dry-run."),exitCode:V.number().nullable().describe("Playwright\u2019s exit code; null when it did not run.")},xl=R({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree\u2019s local dev server when it serves the target, else against the deployed app at INFRA_KIT_ENV. dryRun resolves and reports the target and the proxy topology without running. A cloud run is confirm-gated; a protected env (prod) follows protectedEnvs.",requiresHumanConfirm:!0,inputSchema:{app:V.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:V.boolean().optional(),yes:V.boolean().optional()},outputSchema:ZS,handler:e=>li(e)});import Tl from"node:fs";import Dg from"node:path";import{z as Po}from"zod";var QS=e=>[...e.map(t=>`unset ${t}`),`unset ${it}`,`unset ${Er}`,`unset ${xr}`,`unset ${Qo}`,`unset ${Tr}`],di=async()=>{let e=bt(),t=Dg.join(e,kt);if(!Tl.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=es(t),n=QS(r),o=Dg.resolve(e,Zo);Tl.mkdirSync(e,{recursive:!0,mode:448}),ts(o,`${n.join(`
|
|
364
362
|
`)}
|
|
365
|
-
`,384),Tl.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Cl=R({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:
|
|
366
|
-
`),o.length===0)return p.info("No environments found."),p.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),p.info(" or add a token for one manually."),_g({project:e,envs:o});for(let s of
|
|
363
|
+
`,384),Tl.rmSync(t,{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}},Cl=R({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:Po.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Po.string().describe("Path to the file that must be sourced to apply"),variableCount:Po.number().describe("Number of variables cleared"),unsetStatements:Po.array(Po.string()).describe("Unset statements generated")},handler:()=>di()});import eE from"node:process";import{z as Vt}from"zod";var pi=(e,t,r)=>e.map(({env:n,source:o})=>({env:n,source:o,hasToken:!!(r||t[n])})),Ng=["Environment","Source","Token"],tE=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=Ng.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(Ng),o,...t.map(n)]},ui=async()=>{let e=await We(),t=await un(),r=await ue(),n=eE.env[de],o=pi(t,r?.envs??{},n);if(p.info(`Doppler project: ${e}
|
|
364
|
+
`),o.length===0)return p.info("No environments found."),p.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),p.info(" or add a token for one manually."),_g({project:e,envs:o});for(let s of tE(o))p.info(s);return _g({project:e,envs:o})},_g=({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}},$l=R({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:Vt.string().describe("Detected Doppler project name"),configs:Vt.array(Vt.string()).describe("Every environment name known to this project"),tokens:Vt.array(Vt.object({env:Vt.string().describe("Environment / Doppler config name"),source:Vt.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:Vt.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:ui});import iE from"@inquirer/select";import{Buffer as aE}from"node:buffer";import cE from"node:fs";import lE from"node:path";import Ol from"node:process";import{z as yn}from"zod";import{$ as mi}from"zx";import Fg from"node:process";import{z as Mg}from"zod";var jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rE=async e=>{try{return await e}catch{return[]}},nE=async e=>{let t=await ue().catch(()=>null);return pi(e,t?.envs??{},Fg.env[de]).filter(r=>!r.hasToken).map(r=>r.env)},Al=()=>({get message(){return`Choose the environment to load into terminal session ${Fg.env[He]??`UNKNOWN \u2014 ${He} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>jg(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await rE(un());if(e.length===0)return p.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await nE(e);return Mg.object({config:Mg.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:{...jg(t)?t:{},config:r}}});import{z as oE}from"zod";var sE=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return p.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},Ne=async e=>{if(!ie()||!e.provider.isFormable(e.params))return;let t=await sE(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:oE.toJSONSchema(t);throw new x({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 dE="DOPPLER_CONFIG",Lg=new Set(["DOPPLER_TOKEN",de]),Vg=!1,pE=e=>{e.length===0||Vg||(Vg=!0,p.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Wg=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!Lg.has(i));return pE(e.filter(([i])=>Lg.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${vn(a)}`),`${it}=${vn(t)}`,`${Er}=${vn(t)}`,`${xr}=${vn(r)}`,`${Qo}=${vn(n)}`,`${Tr}=${vn(o)}`,"set +a"]},uE=async()=>{try{return await S()}catch{return""}},Jg=async({config:e})=>{let t=await We(),r=await uE(),n=await gE(t,e),o=new Date().toISOString(),i=`${Wg({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
|
|
367
365
|
`)}
|
|
368
|
-
`,a=bt(),c=
|
|
369
|
-
Fix: run \`infra-kit env-token-set ${t}\` with a token scoped to "${t}".`)},
|
|
366
|
+
`,a=bt(),c=lE.resolve(a,kt);return cE.mkdirSync(a,{recursive:!0,mode:448}),ts(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},Ug=Al(),fi=async e=>{let{config:t}=e;await Ne({provider:Ug,params:e,operation:"env-load",argument:"config"});let r="";if(t)r=t;else{if(Q())throw new x({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 pr();h.setInteractive(),r=await I(i=>iE({message:"Select environment config",choices:s.map(a=>({name:a,value:a}))},i),{output:Ol.stderr,whenHeadless:"refuse"})}h.addOption("--config",r);let n=await Jg({config:r});h.print();let o={filePath:n.filePath,variableCount:n.variableCount,project:n.project,config:n.config,sessionId:Ol.env[He]??null};return{content:k(JSON.stringify(o,null,2)),structuredContent:o}},Bg=1024*1024,mE=3e4,fE=["DOPPLER_TOKEN","DOPPLER_PROJECT","DOPPLER_CONFIG"],wn=(e,t=Ol.env)=>{let r={...t};for(let n of fE)delete r[n];return r.DOPPLER_TOKEN=e,r},gE=async(e,t)=>{let{token:r}=await co(t),n=wn(r),o=mi.quiet;mi.quiet=!0;try{let s;try{s=await mi({env:n})`doppler secrets download --no-file --format json --project ${e} --config ${t}`.timeout(mE)}catch(a){throw hE(a,e,t)}yE(s.stdout);let i=hi(s.stdout);return gi(i,t),i}finally{mi.quiet=o}},gi=(e,t)=>{let r=e.find(([n])=>n===dE)?.[1];if(!(r===void 0||r===t))throw new sn(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.
|
|
367
|
+
Fix: run \`infra-kit env-token-set ${t}\` with a token scoped to "${t}".`)},hE=(e,t,r)=>{let n=$r(e)??(e instanceof Error?e.message:String(e)),o=ir(n);return o==="auth"?new sn(r,ar(n)):o==="unknown"?e instanceof Error?e:new Error(String(e)):new Error(el({kind:o,project:t,config:r,available:null}))},yE=e=>{let t=aE.byteLength(e,"utf-8");if(t>Bg)throw new Error(`doppler returned unexpectedly large output (${t} bytes > ${Bg}) \u2014 refusing to write to disk`)},vn=e=>`'${e.replaceAll("'","'\\''")}'`,vE=/^[A-Z_]\w*$/i,hi=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(!vE.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},Il=R({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:yn.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to have the human choose from a form.')},formProvider:Ug,outputSchema:{filePath:yn.string().describe("Path to the file that must be sourced to apply variables"),variableCount:yn.number().describe("Number of variables loaded"),project:yn.string().describe("Doppler project name"),config:yn.string().describe("Doppler config name"),sessionId:yn.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:fi});import wE from"node:path";import So from"node:process";import{z as kn}from"zod";var yi=async()=>{p.info("Environment session status:");let e=bt(),t=So.env[He],r=wE.join(e,kt),n=0,o=0,s=So.env[Er]??null,i=So.env[xr]??null,a=So.env[Tr]??null;if(s){let l=es(r);l.length>0&&(o=l.length,n=l.filter(u=>u in So.env).length);let d=a?.replace(/\.\d{3}Z$/,"")??null;if(p.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${d}, session: ${t})
|
|
370
368
|
`),o>0&&n<o){let u=o-n;p.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 p.info(` Session ${t}: no env loaded
|
|
371
|
-
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},
|
|
372
|
-
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}},Nl=R({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:
|
|
373
|
-
\u{1F4CB} Merge plan:`);for(let r of e)p.info(` ${r.branch} \u2014 ${zg(r)}`);for(let r of t)p.info(` ${r.branch} \u2014 skipped: ${r.reason}`)}
|
|
374
|
-
\u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await
|
|
375
|
-
`)[0]??""}`);let P=await
|
|
376
|
-
\u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let u=await
|
|
377
|
-
`)[0],observedLanded:g.map(y=>y.branch)}}
|
|
378
|
-
`)[0];p.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!_l.has(i.status));return Ml({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},
|
|
379
|
-
\u2139\uFE0F This will push ${v} branch(es), re-running CI on ${v} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await W(u,`Are you sure you want to merge dev into these branches: ${P.join(", ")}?`,{throwOnDecline:!0,plan:
|
|
369
|
+
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:k(JSON.stringify(c,null,2)),structuredContent:c}},Dl=R({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:kn.string().describe("Current terminal session ID"),sessionLoadedCount:kn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:kn.number().describe("Total number of cached var names"),sessionConfig:kn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:kn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:kn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:yi});import kE from"node:process";import{z as Bt}from"zod";var Gg="****",bn=e=>typeof e!="string"||e.length<8?Gg:`${Gg}${e.slice(-4)}`;var Kg=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${de}`:"store",redactedToken:bn(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),bE=["ENV","SOURCE","TOKEN","PRESENT"],Hg=(e,t)=>{let r=[...bE,...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())},vi=async({check:e}={})=>{let t=await pr(),r=await ue(),n=kE.env[de],o=Kg(t,r?.envs??{},n);if(e){let a=await We();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],d=await tl({childEnv:wn(l),project:a,config:c.env});c.status=d.outcome}}for(let a of Hg(o,!!e))p.info(a);let s=o.filter(a=>!a.present);s.length>0&&p.info(`
|
|
370
|
+
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}},Nl=R({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:vi});import{z as b}from"zod";import{$ as RE}from"zx";var PE=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),SE=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,EE=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(", ")},Ml=e=>({content:k(JSON.stringify(e,null,2)),structuredContent:e}),_l=new Set(["up-to-date","fast-forward","merged"]),xE=(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=Te(ve(a))}catch(l){throw new f(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new f(void 0,{operation:`select release branch for "${a}"`,stderrExcerpt:l?`${c} is skipped: ${l}`:`${c} is not an open regular release branch`,remediation:`pass one of: ${t.join(", ")}`})}i.add(c)}return t.filter(a=>i.has(a))},TE={"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"},zg=e=>{let t=TE[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},CE=(e,t)=>{p.info(`
|
|
371
|
+
\u{1F4CB} Merge plan:`);for(let r of e)p.info(` ${r.branch} \u2014 ${zg(r)}`);for(let r of t)p.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},$E=(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`},AE=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=K(i.branch);return a?[[ne(a),zg(i)]]:[]}));return Nt(se({branches:r,descriptions:s}),{required:!0})},OE=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 P of y)p.info(`\u2139\uFE0F ${P} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await oo(t,Zm(i));a(c.nowUpToDate);let l=c.kept,d=new Map;if(s&&l.length>0){p.info(`
|
|
372
|
+
\u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await ef({worktreePath:r,refs:l,command:s});d=y.failed;for(let[v,C]of y.failed)p.info(`\u2717 ${v} failed verification \u2014 not pushing it. ${C.split(`
|
|
373
|
+
`)[0]??""}`);let P=await oo(t,y.kept);a(P.nowUpToDate),l=P.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:d};p.info(`
|
|
374
|
+
\u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let u=await ps(t,l);if(u.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:d};let g=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Or(t,y.branch)===y.sha})))).filter(y=>y.landed);return g.length>0&&p.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${g.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,abortedBy:u.stderr?.split(`
|
|
375
|
+
`)[0],observedLanded:g.map(y=>y.branch)}},IE=e=>{let t=["keepConflicts","continue","abort"].filter(n=>e[n]),r={keepConflicts:"--keep-conflicts",continue:"--continue",abort:"--abort"};if(t.length>1||t.length===1&&e.dryRun){let n=[...t.map(o=>r[o]),...e.dryRun?["--dry-run"]:[]];throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:`${n.join(" and ")} cannot be combined`,remediation:"pass at most one of --keep-conflicts, --continue, --abort; --dry-run only on a plain run"})}if(e.tree!==void 0&&!e.continue)throw new f(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},qg=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
|
|
376
|
+
`)[0];p.info(a?` ${i.branch} \u2014 ${i.status}: ${a}`:` ${i.branch} \u2014 ${i.status}`)}let o=n?[]:t.filter(i=>i.status!=="aborted"),s=o.filter(i=>!_l.has(i.status));return Ml({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},DE=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Le();if(e.abort)return qg(await Ef({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return qg(await Pf({cwd:s,versions:r,all:t,verify:i,trees:Sf(e.tree),confirmedCommand:o}))},wi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;IE(e);let a=o===!0?Qm:o||void 0;if(await Pc({operation:"merge dev into release branches"}),e.continue||e.abort)return DE(e);let c=[],l=[];for(let B of await F()){let j=SE(B);j?l.push({branch:B.branch,reason:j}):c.push(B.branch)}if(c.length===0)return p.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${EE(l)})`),h.print(),Ml(PE(n,l));let d=await Le();try{await RE({cwd:d,quiet:!0})`git fetch origin --prune`}catch(B){throw new f(B,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let u=r===void 0?c:xE(r,c,l),m=await fu({cwd:d},async B=>{let j=Bs(B.remove);try{return await NE({cwd:d,worktree:B,toPlan:u,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{j()}}),{entries:g,selected:y,pushed:P,pushAborted:v,abortedBy:C,declined:_,verifyFailed:O,handOffs:E}=m,G=await St(d).catch(()=>[]);return jE({entries:g,selected:y,pushed:P,pushAborted:v,abortedBy:C,declined:_,verifyFailed:O,handOffs:E,dryRun:n,worktrees:G,skipped:l})},NE=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:d,confirmedCommand:u}=e,m=d?await $e(t,"origin/dev"):null,g=await Xm({cwd:t,worktreePath:r.path,branches:n}),y={entries:g,pushed:!1,pushAborted:!1,declined:!1};if(CE(g,s),c)return{...y,selected:n};let P=await AE({entries:g,toPlan:n,all:i,explicit:a!==void 0});P.length===o.length?h.addOption("--all",!0):h.addOption("--versions",P);let v=g.filter(E=>P.includes(E.branch)&&E.mergeSha).length;v>0&&p.info(`
|
|
377
|
+
\u2139\uFE0F This will push ${v} branch(es), re-running CI on ${v} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await W(u,`Are you sure you want to merge dev into these branches: ${P.join(", ")}?`,{throwOnDecline:!0,plan:_E(g,P,s)})}catch(E){if(!ct(E))throw E;return{...y,selected:P,declined:!0}}u||h.addOption("--yes",!0);let C=await OE({cwd:t,worktreePath:r.path,entries:g,selected:P,verify:l}),_=g.filter(E=>P.includes(E.branch)&&E.status==="conflict").map(E=>E.branch),O=d&&m&&_.length>0?await kf({cwd:t,branches:_,devSha:m}):void 0;return{entries:g,selected:P,declined:!1,...C,handOffs:O}},_E=(e,t,r)=>({entries:e.filter(n=>t.includes(n.branch)).map(n=>({branch:n.branch,status:n.status,...n.conflictPaths?{conflictPaths:n.conflictPaths}:{},...n.status==="conflict"?{lockfileOnly:Fc(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),ME=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
|
|
380
378
|
`:`# ${e.branch} \u2014 ${e.status}
|
|
381
|
-
${
|
|
382
|
-
`,
|
|
379
|
+
${$E(e.branch,t)}
|
|
380
|
+
`,jE=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:d,skipped:u}=e,m=new Set(n?t.filter(v=>r.includes(v.branch)&&v.mergeSha&&!l?.has(v.branch)).map(v=>v.branch):[]),g=t.filter(v=>r.includes(v.branch)).map(v=>{let C=!!v.mergeSha,_=e.verifyFailed?.get(v.branch),O=o&&C?"push-aborted":v.status,E=_?"verify-failed":O,G=d?.get(v.branch);return{branch:v.branch,status:E,mergeSha:v.mergeSha,conflictPaths:v.conflictPaths,pushed:m.has(v.branch),reason:_??G?.reason??v.reason,...G?.resolution?{resolution:G.resolution}:{}}}),y=g.filter(v=>!_l.has(v.status));for(let v of g){let C=t.find(_=>_.branch===v.branch);p.info({branch:v.branch,status:v.status,mergeSha:v.mergeSha,conflictCount:v.conflictPaths?.length??0,durationMs:C?.durationMs,pushed:v.pushed,msg:"merge-dev branch result"})}if(i||a)p.info(i?`
|
|
383
381
|
Operation cancelled \u2014 nothing was pushed.
|
|
384
382
|
`:`
|
|
385
383
|
\u{1F50D} Dry run \u2014 nothing was pushed.
|
|
386
384
|
`);else if(y.length>0){p.info(`
|
|
387
385
|
\u26A0\uFE0F ${y.length} branch(es) did not merge.
|
|
388
|
-
`);for(let v of y)p.info(
|
|
389
|
-
`);h.print();let P=a||i;return Ml({successfulMerges:P?0:g.filter(v=>_l.has(v.status)).length,failedMerges:P?0:y.length,failedBranches:P?[]:y.map(v=>v.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(v=>P?{...v,pushed:!1}:v),skipped:u})},jl=R({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:b.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:b.union([b.string(),b.array(b.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:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.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. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.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:vi});import{z as To}from"zod";import{$ as _e}from"zx";var Yg=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Wt=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=Yg(t.stderr,500);o&&(r.stderr=o);let s=Yg(t.stdout,200);return s&&(r.stdout=s),r};var So=e=>{let{removed:t,failed:r}=e;if(t.length>0){p.info("\u274C Removed worktrees:");for(let n of t)p.info(n);p.info("")}if(r.length>0){p.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)p.warn(`${n} \u2014 ${o}`);p.warn("")}t.length===0&&r.length===0&&p.info("\u2139\uFE0F No worktrees to remove")};var Eo=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 Q()?new x({status:"partial_failure",...n},1,s):new f(void 0,s)};import ki from"node:fs/promises";import{$ as eh}from"zx";var _E=new Set([".omc",".DS_Store"]),ME=new Set(["state","sessions"]),jE=2e3,FE="check 'git worktree list' for the path; uncommitted changes block removal",LE=e=>new Promise(t=>{setTimeout(t,e)}),Fl=e=>typeof e=="object"&&e!==null?e.code:void 0,Xg=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Zg=async e=>{try{return Xg(await ki.realpath(e))}catch{return Xg(e)}},VE=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await St(t),o=await Zg(r);for(let s of n)if(await Zg(s.path)===o)return!0;return!1}catch{return!0}},BE=async e=>{let t;try{t=await ki.readdir(e)}catch(n){return{kind:Fl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>_E.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await ki.readdir(`${e}/.omc`)).every(s=>ME.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Fl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Qg=async e=>{try{return await ki.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Fl(t)==="ENOTEMPTY"?"busy":"failed"}},WE=async e=>{let{worktreePath:t,sleep:r}=e,n=await Qg(t);return n!=="busy"?n==="removed":(await r(jE),await Qg(t)==="removed")},wi=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return p.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},JE=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await VE({projectRoot:n,worktreePath:r}))return wi(t,o,FE);let i=await BE(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 WE({worktreePath:r,sleep:s})?wi(t,o,a):(p.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"})},UE=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await Mu(i,o);if(!a.closed&&"error"in a)return wi(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await eh`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return JE({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},yr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=LE}=e,i=t.length>0?await Dr():"unreachable",a=await Promise.all(t.map(l=>UE({branch:l,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let l of a)l.status==="removed"?c.removed.push(l.branch):c.failed.push({branch:l.branch,reason:l.reason});return o&&c.removed.length===t.length&&await eh`git worktree prune`,c};var xo=async(e,t)=>{if(!(await Ce("release")).includes(e))return[];let n=await S(),o=`${n}${ge}`,{removed:s,failed:i}=await yr({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 bn=async(e,t,r)=>{try{return await r()}catch(n){throw p.debug({err:Wt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},GE=async e=>{let t=va(e),r=await _e`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},th=async()=>{let e=await _e`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},KE=async e=>{let t=mt(e),r=await xc(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 Gr(t);if(!n)throw p.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=Xn(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}},HE=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await oe(),o=await It(se({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw p.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}},qE=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Qe(r),s=await Tc(n);if(s.state==="MERGED"){p.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 bn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin --delete-branch`})},zE=async e=>{let t=Y(e),r=va(e),n=await th();if(n){let s=n.number;return n.title!==r&&(p.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await bn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await _e`gh pr edit ${s} --title ${r}`})),s}await bn(`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 _e`gh pr create --base main --head dev --title ${r} --body ""`});let o=await th();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},YE=async e=>{let t=Y(e);if(await GE(e)){p.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await zE(e);await bn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin`})},XE=async()=>{_e.quiet=!1,await bn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await _e`gh workflow run deploy-all.yml --ref main -f environment=prod`}),_e.quiet=!0},ZE=async()=>{await bn("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 _e`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},QE=async e=>{try{await cs(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ls(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},ex=async e=>{let t=await ut();if(!t){p.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await $c({versionName:r},t)}catch(r){let n=Qn(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";p.error({err:Wt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},bi=async e=>{let{version:t,confirmedCommand:r}=e;await be({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await KE(t):await HE(),i=K(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=Y(i);if(h.addOption("--version",a),p.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),Q())throw new x({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 W(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),_e.quiet=!0;let l=`${await S()}${ge}`;await xo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await qE({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await YE(i),await XE(),await ZE(),await QE(n),_e.quiet=!1,await ex(i),p.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Ll=R({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:To.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:To.string().describe("The release branch that was delivered"),version:To.string().describe("The version that was delivered"),type:To.enum(["regular","hotfix"]).describe("Release type"),success:To.boolean().describe("Whether the delivery was successful")},handler:bi});import{z as vt}from"zod";import{$ as zl}from"zx";import{z as Ao}from"zod";import rh from"node:fs/promises";import Vl from"node:path";var nh=".github/workflows",tx=/script_name:\s*(?<service>[a-z0-9-]+)/,rx=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,nx=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Bl=async e=>{let t=Vl.resolve(e,nh),r;try{r=await rh.readdir(t)}catch{return new Map}return oh(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Co=async(e,t)=>oh(Vl.resolve(e,nh),[t]),oh=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await rh.readFile(Vl.resolve(e,n),"utf-8")}catch{continue}ox(o,r)}return r},ox=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=tx.exec(r)?.groups?.service??rx.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(nx)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},Wl=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import sx from"node:fs/promises";import ix from"node:path";import ax from"yaml";var cx=".github/workflows",lx="skip_terraform_deploy",$o=async(e,t)=>{let r=ix.resolve(e,cx,t),n;try{n=ax.parse(await sx.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!==lx).map(([i])=>i)};var sh="dev",Jl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ih=(e,t)=>e[t]===void 0,ah=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Ul=async e=>{try{return await e}catch{return[]}},dx=async()=>{let e=await F();return nr(e.map(t=>t.branch))},px=(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},vr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(p.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Ul(dx());if(l.length===0)return null;let d=ah(c,"version");return Ao.enum([...new Set([...l,sh])]).optional().describe(`Which release to deploy from. "${sh}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=gt(await Ul(ht(t)),await Je());if(l.length===0)return null;let d=l.filter(ln),u=l.filter(g=>!ln(g)),m=ah(c,"env");return Ao.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${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 S(),l=await Ul($o(c,t));if(l.length===0)return null;let d=await Co(c,t);return Ao.array(Ao.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${px(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Jl(c)?r.some(l=>ih(c,l)):!1,buildRequestedSchema:async c=>{let l=Jl(c)?c:{},d={};if(r.includes("version")){let u=await s(l);if(u===null)return o("releases");d.version=u}if(r.includes("env")){let u=await i(l);if(u===null)return o("envs");d.env=u}if(r.includes("services")&&ih(l,"services")){let u=await a();if(u===null)return o("services");d.services=u}return Object.keys(d).length===0?o("fields"):Ao.object(d)},toArgs:(c,l)=>{let d={...Jl(l)?l:{}};for(let u of r){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;d[u]=m}}return d}}};import ux from"@inquirer/select";var Rn=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 D(r=>ux({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import mx from"@inquirer/confirm";var Oo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ie()&&fs(o,{branch:r,env:n}),h.setInteractive();let s=await D(i=>mx({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import fx from"@inquirer/select";import gx from"node:process";var Gl=()=>!ie()&&gx.stdin.isTTY===!0,hx={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Kl=async()=>D(e=>fx({message:"\u{1F680} Where should this deploy run?",choices:Jt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:hx[t]}))},e),{whenHeadless:"refuse"});var Jt=["ci","local"],yx={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},ch=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Jt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ie()?new x({status:"argument_required",argument:"from",agentMode:A.source},2,r):new f(void 0,r)}let t=Jt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Jt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Hl=(e,t)=>{let n=yx[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}`})},ql=async e=>e||!Gl()?ch(e):Kl();var Do=async e=>{if(e)return e==="dev"?"dev":mt(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await oe();return It([{value:"dev",label:"dev"},...se({branches:r,descriptions:o,types:n})])};var lh="deploy-all.yml",dh=vr({workflowFile:lh,fields:["version","env"],toolName:"gh-release-deploy-all"}),Ri=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Ne({provider:dh,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await Do(t),i=ro(s);h.addOption("--version",i);let a=await Je(),c=gt(await ht(lh),a),l="";r?l=r:(h.setInteractive(),l=await Rn(c,"launch deploy-all workflow")),h.addOption("--env",l),dr(l,"launch deploy-all workflow",a),fo({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await Oo({confirmedCommand:o,branch:s,env:l})){p.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}try{zl.quiet=!0,await zl`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,zl.quiet=!1,p.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw p.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"})}},Yl=R({name:"gh-release-deploy-all",formProvider:dh,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:vt.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:vt.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:vt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:vt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:vt.string().describe("The release branch that was deployed"),version:vt.string().describe("The version that was deployed"),environment:vt.string().describe("The environment deployed to"),skipTerraformDeploy:vt.boolean().describe("Whether terraform deployment was skipped"),success:vt.boolean().describe("Whether the deployment was successful")},handler:Ri});import vx from"@inquirer/checkbox";import{z as Pe}from"zod";import{$ as Xl}from"zx";var wr="deploy-selected-services.yml",ph=vr({workflowFile:wr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Pi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ne({provider:ph,params:e,operation:"launch deploy-selected workflow",argument:O=>O[0]??"version"});let i=await Do(t),a=ro(i);h.addOption("--version",a);let c=await Je(),l=gt(await ht(wr),c),d="";r?d=r:(h.setInteractive(),d=await Rn(l,"launch deploy-selected workflow")),h.addOption("--env",d),dr(d,"launch deploy-selected workflow",c),fo({env:d,branch:i});let u=await S(),m=await $o(u,wr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${wr}`,stderrExcerpt:`no services found in .github/workflows/${wr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await D(O=>vx({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(E=>({name:E,value:E}))},O),{whenHeadless:"refuse"})),h.addOption("--services",g),g.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=g.filter(O=>!m.includes(O));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 P=await Co(u,wr),v=g.filter(O=>{let E=P.get(O);return E!==void 0&&!E.includes(d)});if(v.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:v.map(O=>`${O} deploys only to: ${(P.get(O)??[]).join(", ")}`).join("; "),stderrExcerpt:`${wr} gates these services out of ${d}: ${v.join(", ")}`});let C=o??!1;C&&h.addOption("--skip-terraform",!0);let _=O=>{let E={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:C,success:O};return{content:k(JSON.stringify(E,null,2)),structuredContent:E}};if(!await Oo({confirmedCommand:s,branch:i,env:d}))return p.info("Deployment cancelled"),_(!1);try{Xl.quiet=!0;let O=g.flatMap(G=>["-f",`${G}=true`]);return await Xl`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${O} ${C?["-f","skip_terraform_deploy=true"]:[]}`,Xl.quiet=!1,p.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),_(!0)}catch(O){throw p.error({error:O},"\u274C Error launching workflow"),new f(O,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Zl=R({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:ph,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:Pe.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:Pe.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:Pe.array(Pe.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:Pe.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Pe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Pe.string().describe("The release branch that was deployed"),version:Pe.string().describe("The version that was deployed"),environment:Pe.string().describe("The environment deployed to"),services:Pe.array(Pe.string()).describe("The services that were deployed"),skipTerraformDeploy:Pe.boolean().describe("Whether terraform deployment was skipped"),success:Pe.boolean().describe("Whether the deployment was successful")},handler:Pi});import{z as Ut}from"zod";var Si=async()=>{let t=(await F()).flatMap(i=>{let a=K(i.branch);return a?[{version:Y(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await js(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=to(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",u=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${u}`});p.info(`All release branches:
|
|
386
|
+
`);for(let v of y)p.info(ME(v,c))}else p.info(`\u2705 All merges completed successfully!
|
|
387
|
+
`);h.print();let P=a||i;return Ml({successfulMerges:P?0:g.filter(v=>_l.has(v.status)).length,failedMerges:P?0:y.length,failedBranches:P?[]:y.map(v=>v.branch),totalBranches:g.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:g.map(v=>P?{...v,pushed:!1}:v),skipped:u})},jl=R({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:b.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:b.union([b.string(),b.array(b.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:b.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:b.union([b.boolean(),b.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. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:b.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:b.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:b.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:b.union([b.string(),b.array(b.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:b.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:b.number().describe("Number of branches that reached their desired state"),failedMerges:b.number().describe("Number of branches that did not"),failedBranches:b.array(b.string()).describe("List of branches that did not merge"),totalBranches:b.number().describe("Total number of branches processed"),dryRun:b.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:b.object({attempted:b.boolean(),aborted:b.boolean(),abortedBy:b.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:b.array(b.object({branch:b.string(),status:b.string(),mergeSha:b.string().optional(),conflictPaths:b.array(b.string()).optional(),pushed:b.boolean(),reason:b.string().optional(),resolution:b.object({worktreePath:b.string(),baseSha:b.string(),devSha:b.string(),conflictPaths:b.array(b.string()),lockfileOnly:b.boolean(),rererePreResolved:b.array(b.string()),state:b.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:b.object({code:b.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:b.array(b.string()).optional(),detail:b.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:b.array(b.object({branch:b.string(),reason:b.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:wi});import{z as Co}from"zod";import{$ as _e}from"zx";var Yg=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Wt=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=Yg(t.stderr,500);o&&(r.stderr=o);let s=Yg(t.stdout,200);return s&&(r.stdout=s),r};var Eo=e=>{let{removed:t,failed:r}=e;if(t.length>0){p.info("\u274C Removed worktrees:");for(let n of t)p.info(n);p.info("")}if(r.length>0){p.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)p.warn(`${n} \u2014 ${o}`);p.warn("")}t.length===0&&r.length===0&&p.info("\u2139\uFE0F No worktrees to remove")};var xo=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 Q()?new x({status:"partial_failure",...n},1,s):new f(void 0,s)};import bi from"node:fs/promises";import{$ as eh}from"zx";var FE=new Set([".omc",".DS_Store"]),LE=new Set(["state","sessions"]),VE=2e3,BE="check 'git worktree list' for the path; uncommitted changes block removal",WE=e=>new Promise(t=>{setTimeout(t,e)}),Fl=e=>typeof e=="object"&&e!==null?e.code:void 0,Xg=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Zg=async e=>{try{return Xg(await bi.realpath(e))}catch{return Xg(e)}},JE=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await St(t),o=await Zg(r);for(let s of n)if(await Zg(s.path)===o)return!0;return!1}catch{return!0}},UE=async e=>{let t;try{t=await bi.readdir(e)}catch(n){return{kind:Fl(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>FE.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await bi.readdir(`${e}/.omc`)).every(s=>LE.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Fl(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Qg=async e=>{try{return await bi.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Fl(t)==="ENOTEMPTY"?"busy":"failed"}},GE=async e=>{let{worktreePath:t,sleep:r}=e,n=await Qg(t);return n!=="busy"?n==="removed":(await r(VE),await Qg(t)==="removed")},ki=(e,t,r)=>{let n=new f(t,{operation:`remove worktree for ${e}`,remediation:r});return p.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},KE=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await JE({projectRoot:n,worktreePath:r}))return ki(t,o,BE);let i=await UE(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 GE({worktreePath:r,sleep:s})?ki(t,o,a):(p.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"})},HE=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await ju(i,o);if(!a.closed&&"error"in a)return ki(t,a.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await eh`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(c){return KE({branch:t,worktreePath:i,projectRoot:n,error:c,sleep:s})}},yr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=WE}=e,i=t.length>0?await Ir():"unreachable",a=await Promise.all(t.map(l=>HE({branch:l,worktreeDir:r,projectRoot:n,orcaProbe:i,sleep:s}))),c={removed:[],failed:[]};for(let l of a)l.status==="removed"?c.removed.push(l.branch):c.failed.push({branch:l.branch,reason:l.reason});return o&&c.removed.length===t.length&&await eh`git worktree prune`,c};var To=async(e,t)=>{if(!(await Ce("release")).includes(e))return[];let n=await S(),o=`${n}${ge}`,{removed:s,failed:i}=await yr({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 Rn=async(e,t,r)=>{try{return await r()}catch(n){throw p.debug({err:Wt(n)},`Failed to ${e}`),new f(n,{operation:e,remediation:t})}},qE=async e=>{let t=va(e),r=await _e`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},th=async()=>{let e=await _e`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},zE=async e=>{let t=ft(e),r=await xc(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 Gr(t);if(!n)throw p.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=Zn(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}},YE=async()=>{let e=await F(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await oe(),o=await Dt(se({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw p.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}},XE=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=Qe(r),s=await Tc(n);if(s.state==="MERGED"){p.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 Rn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin --delete-branch`})},ZE=async e=>{let t=Y(e),r=va(e),n=await th();if(n){let s=n.number;return n.title!==r&&(p.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Rn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await _e`gh pr edit ${s} --title ${r}`})),s}await Rn(`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 _e`gh pr create --base main --head dev --title ${r} --body ""`});let o=await th();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},QE=async e=>{let t=Y(e);if(await qE(e)){p.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await ZE(e);await Rn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await _e`gh pr merge ${n} --squash --admin`})},ex=async()=>{_e.quiet=!1,await Rn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await _e`gh workflow run deploy-all.yml --ref main -f environment=prod`}),_e.quiet=!0},tx=async()=>{await Rn("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 _e`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},rx=async e=>{try{await ls(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ds(e)}catch(t){p.warn({err:Wt(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},nx=async e=>{let t=await mt();if(!t){p.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await $c({versionName:r},t)}catch(r){let n=eo(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";p.error({err:Wt(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ri=async e=>{let{version:t,confirmedCommand:r}=e;await be({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await zE(t):await YE(),i=K(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=Y(i);if(h.addOption("--version",a),p.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),Q())throw new x({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 W(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),_e.quiet=!0;let l=`${await S()}${ge}`;await To(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await XE({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await QE(i),await ex(),await tx(),await rx(n),_e.quiet=!1,await nx(i),p.info(`Successfully delivered ${n} to production!`),h.print();let d={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}},Ll=R({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:Co.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:Co.string().describe("The release branch that was delivered"),version:Co.string().describe("The version that was delivered"),type:Co.enum(["regular","hotfix"]).describe("Release type"),success:Co.boolean().describe("Whether the delivery was successful")},handler:Ri});import{z as vt}from"zod";import{$ as zl}from"zx";import{z as Oo}from"zod";import rh from"node:fs/promises";import Vl from"node:path";var nh=".github/workflows",ox=/script_name:\s*(?<service>[a-z0-9-]+)/,sx=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,ix=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Bl=async e=>{let t=Vl.resolve(e,nh),r;try{r=await rh.readdir(t)}catch{return new Map}return oh(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},$o=async(e,t)=>oh(Vl.resolve(e,nh),[t]),oh=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await rh.readFile(Vl.resolve(e,n),"utf-8")}catch{continue}ax(o,r)}return r},ax=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=ox.exec(r)?.groups?.service??sx.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(ix)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},Wl=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import cx from"node:fs/promises";import lx from"node:path";import dx from"yaml";var px=".github/workflows",ux="skip_terraform_deploy",Ao=async(e,t)=>{let r=lx.resolve(e,px,t),n;try{n=dx.parse(await cx.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!==ux).map(([i])=>i)};var sh="dev",Jl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ih=(e,t)=>e[t]===void 0,ah=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Ul=async e=>{try{return await e}catch{return[]}},mx=async()=>{let e=await F();return nr(e.map(t=>t.branch))},fx=(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},vr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(p.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Ul(mx());if(l.length===0)return null;let d=ah(c,"version");return Oo.enum([...new Set([...l,sh])]).optional().describe(`Which release to deploy from. "${sh}" deploys from the dev branch instead of a release branch. ${d===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${d}".`}`)},i=async c=>{let l=gt(await Ul(ht(t)),await Je());if(l.length===0)return null;let d=l.filter(dn),u=l.filter(g=>!dn(g)),m=ah(c,"env");return Oo.enum(l).optional().describe(`Target environment. Shared with the whole team: ${d.length>0?d.join(", "):"none"}. Personal accounts: ${u.length>0?u.join(", "):"none"}. This list is read from .github/workflows/${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 S(),l=await Ul(Ao(c,t));if(l.length===0)return null;let d=await $o(c,t);return Oo.array(Oo.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${fx(l,d)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Jl(c)?r.some(l=>ih(c,l)):!1,buildRequestedSchema:async c=>{let l=Jl(c)?c:{},d={};if(r.includes("version")){let u=await s(l);if(u===null)return o("releases");d.version=u}if(r.includes("env")){let u=await i(l);if(u===null)return o("envs");d.env=u}if(r.includes("services")&&ih(l,"services")){let u=await a();if(u===null)return o("services");d.services=u}return Object.keys(d).length===0?o("fields"):Oo.object(d)},toArgs:(c,l)=>{let d={...Jl(l)?l:{}};for(let u of r){let m=c[u];if(m!==void 0){if(u==="services"&&(!Array.isArray(m)||m.length===0))return null;d[u]=m}}return d}}};import gx from"@inquirer/select";var Pn=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 I(r=>gx({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import hx from"@inquirer/confirm";var Io=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;ie()&&gs(o,{branch:r,env:n}),h.setInteractive();let s=await I(i=>hx({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import yx from"@inquirer/select";import vx from"node:process";var Gl=()=>!ie()&&vx.stdin.isTTY===!0,wx={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Kl=async()=>I(e=>yx({message:"\u{1F680} Where should this deploy run?",choices:Jt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:wx[t]}))},e),{whenHeadless:"refuse"});var Jt=["ci","local"],kx={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},ch=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Jt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw ie()?new x({status:"argument_required",argument:"from",agentMode:A.source},2,r):new f(void 0,r)}let t=Jt.find(r=>r===e);if(!t)throw new f(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Jt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Hl=(e,t)=>{let n=kx[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}`})},ql=async e=>e||!Gl()?ch(e):Kl();var Do=async e=>{if(e)return e==="dev"?"dev":ft(e);h.setInteractive();let t=await F(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await oe();return Dt([{value:"dev",label:"dev"},...se({branches:r,descriptions:o,types:n})])};var lh="deploy-all.yml",dh=vr({workflowFile:lh,fields:["version","env"],toolName:"gh-release-deploy-all"}),Pi=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Ne({provider:dh,params:e,operation:"launch deploy-all workflow",argument:u=>u[0]??"version"});let s=await Do(t),i=no(s);h.addOption("--version",i);let a=await Je(),c=gt(await ht(lh),a),l="";r?l=r:(h.setInteractive(),l=await Pn(c,"launch deploy-all workflow")),h.addOption("--env",l),dr(l,"launch deploy-all workflow",a),go({env:l,branch:s});let d=n??!1;if(d&&h.addOption("--skip-terraform",!0),!await Io({confirmedCommand:o,branch:s,env:l})){p.info("Deployment cancelled");let u={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}try{zl.quiet=!0,await zl`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,zl.quiet=!1,p.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),h.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(u){throw p.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"})}},Yl=R({name:"gh-release-deploy-all",formProvider:dh,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:vt.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:vt.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:vt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:vt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:vt.string().describe("The release branch that was deployed"),version:vt.string().describe("The version that was deployed"),environment:vt.string().describe("The environment deployed to"),skipTerraformDeploy:vt.boolean().describe("Whether terraform deployment was skipped"),success:vt.boolean().describe("Whether the deployment was successful")},handler:Pi});import bx from"@inquirer/checkbox";import{z as Pe}from"zod";import{$ as Xl}from"zx";var wr="deploy-selected-services.yml",ph=vr({workflowFile:wr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Si=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Ne({provider:ph,params:e,operation:"launch deploy-selected workflow",argument:O=>O[0]??"version"});let i=await Do(t),a=no(i);h.addOption("--version",a);let c=await Je(),l=gt(await ht(wr),c),d="";r?d=r:(h.setInteractive(),d=await Pn(l,"launch deploy-selected workflow")),h.addOption("--env",d),dr(d,"launch deploy-selected workflow",c),go({env:d,branch:i});let u=await S(),m=await Ao(u,wr);if(m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${wr}`,stderrExcerpt:`no services found in .github/workflows/${wr}`});let g=[];if(n&&n.length>0?g=n:(h.setInteractive(),g=await I(O=>bx({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(E=>({name:E,value:E}))},O),{whenHeadless:"refuse"})),h.addOption("--services",g),g.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=g.filter(O=>!m.includes(O));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 P=await $o(u,wr),v=g.filter(O=>{let E=P.get(O);return E!==void 0&&!E.includes(d)});if(v.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:v.map(O=>`${O} deploys only to: ${(P.get(O)??[]).join(", ")}`).join("; "),stderrExcerpt:`${wr} gates these services out of ${d}: ${v.join(", ")}`});let C=o??!1;C&&h.addOption("--skip-terraform",!0);let _=O=>{let E={releaseBranch:i,version:a,environment:d,services:g,skipTerraformDeploy:C,success:O};return{content:k(JSON.stringify(E,null,2)),structuredContent:E}};if(!await Io({confirmedCommand:s,branch:i,env:d}))return p.info("Deployment cancelled"),_(!1);try{Xl.quiet=!0;let O=g.flatMap(G=>["-f",`${G}=true`]);return await Xl`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${O} ${C?["-f","skip_terraform_deploy=true"]:[]}`,Xl.quiet=!1,p.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${g.join(", ")}`),h.print(),_(!0)}catch(O){throw p.error({error:O},"\u274C Error launching workflow"),new f(O,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Zl=R({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:ph,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:Pe.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:Pe.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:Pe.array(Pe.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:Pe.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Pe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Pe.string().describe("The release branch that was deployed"),version:Pe.string().describe("The version that was deployed"),environment:Pe.string().describe("The environment deployed to"),services:Pe.array(Pe.string()).describe("The services that were deployed"),skipTerraformDeploy:Pe.boolean().describe("Whether terraform deployment was skipped"),success:Pe.boolean().describe("Whether the deployment was successful")},handler:Si});import{z as Ut}from"zod";var Ei=async()=>{let t=(await F()).flatMap(i=>{let a=K(i.branch);return a?[{version:Y(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Fs(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=ro(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",d=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",u=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${d}${u}`});p.info(`All release branches:
|
|
390
388
|
`),p.info(`
|
|
391
389
|
${o.join(`
|
|
392
390
|
`)}
|
|
393
|
-
`);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}},Ql=R({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:Ut.array(Ut.object({version:Ut.string().describe("Release version"),type:Ut.enum(["regular","hotfix"]).describe("Release type"),description:Ut.string().nullable().describe("Jira version description"),releaseDate:Ut.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Ut.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Ut.number().describe("Number of release branches")},handler:
|
|
394
|
-
`)};import
|
|
395
|
-
`).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),
|
|
396
|
-
${
|
|
397
|
-
`)),sd({env:m,accountId:B,names:y,built:E,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await
|
|
391
|
+
`);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}},Ql=R({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:Ut.array(Ut.object({version:Ut.string().describe("Release version"),type:Ut.enum(["regular","hotfix"]).describe("Release type"),description:Ut.string().nullable().describe("Jira version description"),releaseDate:Ut.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Ut.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Ut.number().describe("Number of release branches")},handler:Ei});import Rx from"node:process";var ed=e=>({...e}),td=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=Rx.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,d]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=d}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}},xi=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(`
|
|
392
|
+
`)};import Mx from"@inquirer/checkbox";import jx from"@inquirer/confirm";import Fx from"@inquirer/select";import{spawn as Lx}from"node:child_process";import Vx from"node:process";import{z}from"zod";import{$ as _o}from"zx";import{$ as No}from"zx";var Px=async e=>{let t=No.quiet;No.quiet=!0;try{let r=`/${e}/environment`,n=await No`aws sts get-caller-identity --query Account --output text`,o=await No`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{No.quiet=t}},uh=(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`})},mh=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"})},fh=(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`})},rd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;dr(t,`deploy to "${t}"`,i),fh(t,s),mh({env:t,isShared:n,isClean:o});let a=await Px(r);return uh(t,a),{identity:a}};import gh from"node:fs/promises";import Ti from"node:path";var Sx="devops/scripts",Ex=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,xx=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,Tx=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,Cx=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,nd=async e=>{let t=Ti.resolve(e,Sx),r;try{r=await gh.readdir(t)}catch{return[]}let n=await Bl(e);return(await Promise.all(r.map(s=>({entry:s,match:Ex.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=Ti.resolve(t,s),c=i?.groups?.service??"",l=Ax(await $x(a));return{name:c,scriptPath:a,allowedEnvs:Wl(Ox(l),n.get(c)),ssmPrefix:Dx(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},$x=async e=>{try{return await gh.readFile(e,"utf-8")}catch{return""}},Ax=e=>e.split(`
|
|
393
|
+
`).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),Ox=e=>{let t=e.reduce((n,{text:o})=>n??xx.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},Ix=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Dx=e=>{for(let{line:t,text:r}of e){let n=Cx.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=Tx.exec(r)?.groups?.arg;if(o!==void 0&&Ix(o))return{unparseable:{line:t,text:r.trim()}}}return null},Nx=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ti.basename(r.scriptPath)]);return t},_x=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ti.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("; ")})},hh=e=>{_x(e);let t=Nx(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},Ci=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),od=(e,t)=>e.filter(r=>Ci(r,t));var id="deploy-all.yml",vh="/bin/sh",Bx=async()=>{let e=_o.quiet;_o.quiet=!0;try{let t=await _o`gh run list --workflow=${id} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{_o.quiet=e}},Wx=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await I(o=>Mx({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},Jx=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()&&gs(i,{env:t,services:n,accountId:o,shared:r}),r?I(a=>Fx({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):I(a=>jx({message:i,default:!1},a),{whenHeadless:"refuse"})},Ux=(e,t,r)=>new Promise((n,o)=>{let s=Lx(vh,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),Gx=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){p.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await Ux(a,r,n);if(c!==0){i.push(a.name),p.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),p.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},Kx=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&&!Ci(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))},sd=e=>{let{env:t,accountId:r,names:n,built:o,deployed:s,failed:i,dryRun:a,success:c}=e,l={environment:t,accountId:r,services:n,deployed:s,failed:i,contract:ed(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},Hx=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:(h.setInteractive(),Wx(r,o))},wh=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await S(),c=await nd(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 l=hh(c);await Ne({provider:ad[t],params:e,operation:"deploy locally",argument:"env"});let d=await Je(),u=gt(await ht(id),d),m=r??"";m||(h.setInteractive(),m=await Pn(u,"deploy locally")),h.addOption("--env",m);let g=od(c,m);if(g.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 Hx({selection:t,eligible:g,service:n,env:m}),P=Kx({names:y,services:c,env:m});if(t==="selected")for(let xe of y)h.addOption("--service",xe);let v=dn(m),C=await Ar(),_=(await _o`git rev-parse HEAD`.quiet()).stdout.trim(),O=await cu(),E=td({env:m,branch:C,sha:_,isClean:O});i&&p.info(`Deploy contract for ${m}:
|
|
394
|
+
${xi(E)}`);let B=(await rd({env:m,project:l,isShared:v,isClean:O,runningEnvs:await Bx(),protectedEnvAccess:d})).identity.accountId;if(s)return p.info([`Would deploy to "${m}" (AWS account ${B}) from this machine`,`Preflight parameter: /${l}/environment`,xi(E),"Commands:",...P.map(xe=>` ${vh} ${xe.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
|
|
395
|
+
`)),sd({env:m,accountId:B,names:y,built:E,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await Jx({env:m,isShared:v,names:y,accountId:B}))return p.info("Deployment cancelled"),sd({env:m,accountId:B,names:y,built:E,deployed:[],failed:[],dryRun:!1,success:!1});E.stripped.length>0&&p.info(`Stripped ambient VITE_* from the build env: ${E.stripped.join(", ")}`);let{deployed:j,failed:Ke}=await Gx({chosen:P,childEnv:E.childEnv,cwd:a,env:m});return Ke.length>0&&(p.error(`Partial deploy to "${m}": succeeded [${j.join(", ")||"none"}], failed [${Ke.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Vx.exitCode=1),h.print(),sd({env:m,accountId:B,names:y,built:E,deployed:j,failed:Ke,dryRun:!1,success:Ke.length===0})},kh=async e=>wh(e,"all"),bh=async e=>wh(e,"selected"),Rh='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.',Ph={env:z.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:z.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:z.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},Sh={environment:z.string().describe("Environment deployed to"),accountId:z.string().describe("AWS account the deploy targeted"),services:z.array(z.string()).describe("Services requested"),deployed:z.array(z.string()).describe("Services that completed successfully"),failed:z.array(z.string()).describe("Services that failed"),contract:z.record(z.string(),z.string()).describe("Build contract passed to the scripts"),strippedVars:z.array(z.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:z.boolean().describe("Whether this was a dry run"),success:z.boolean().describe("Whether every requested service deployed")},yh=e=>vr({workflowFile:id,fields:["env"],toolName:e}),ad={all:yh("local-deploy-all"),selected:yh("local-deploy-selected")},cd=R({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Rh}`,requiresHumanConfirm:!0,formProvider:ad.all,inputSchema:Ph,outputSchema:Sh,handler:kh}),ld=R({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Rh}`,requiresHumanConfirm:!0,formProvider:ad.selected,inputSchema:{...Ph,service:z.array(z.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:Sh,handler:bh});import Yx from"@inquirer/confirm";import $i from"@inquirer/input";import Ch from"@inquirer/select";import pd from"node:process";import{z as J}from"zod";import{z as Mo}from"zod";var Sn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Th=2500,Eh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xh=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,qx=async()=>{let e=await vo();return{regular:gn(e,"regular"),hotfix:gn(e,"hotfix")}},zx=(e,t)=>e===null?(p.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?(p.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).`,dd=(e={})=>{let t=e.hintBudgetMs??Th;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=>Eh(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Sn(qx(),t);return Mo.object({type:Mo.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Mo.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. ${zx(r,t)}`),description:Mo.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Mo.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=xh(r.description),a=xh(r.releaseDate),c=ai(o);return{...Eh(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var Xx='"1.2.5" or "next"',ud=(e,t)=>{try{return yl(e,t)}catch(r){throw r instanceof mr?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 ou?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}},Zx=async(e,t)=>{let r=gn(e,t),n=r?` [${r}]`:"",o=(await I(i=>$i({message:` Version (e.g. ${Xx})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(p.error("No version provided. Exiting..."),pd.exit(1)),s},Qx=async()=>{let e=(await I(t=>$i({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(p.error("No name provided. Exiting..."),pd.exit(1));try{as(e)}catch(t){let r=t instanceof Error?t.message:String(t);p.error(`${r} Exiting...`),pd.exit(1)}return e},eT=async()=>(await I(e=>$i({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:yo},e),{whenHeadless:"refuse"})).trim(),tT=async e=>{h.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 I(m=>Ch({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 I(m=>Ch({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"},m),{whenHeadless:"refuse"}),l;if(a==="name"){let m=await Qx();l=ud([{name:m,type:c}],[])[0]}else{let m=await Zx(await n(),c);l=ud([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Ft(`v${l.id.raw}`))}let d=(await I(m=>$i({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),u=await eT();o.push({...l,...d!==""?{description:d}:{},...u!==""?{releaseDate:u}:{}}),s=await I(m=>Yx({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},rT=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 ")},$h=e=>{for(let t of e)h.addOption("--release",hl(t))},nT=async(e,t)=>{if(e&&e.length>0){let n=vl(e)?await t():[],o=ud(e,n);return $h(o),o}if(Q())throw new x({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 tT(t);return $h(r),r},oT=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"})},sT=async(e,t)=>{let r=e.map(rT).join(`
|
|
398
396
|
- `);await W(t,`Create the following ${e.length} release(s)?
|
|
399
397
|
- ${r}
|
|
400
|
-
`),h.addOption("--yes",!0)},
|
|
401
|
-
`),{result:i}}catch(s){let i=
|
|
402
|
-
`),{failure:{version:n,error:a.message}}}},
|
|
398
|
+
`),h.addOption("--yes",!0)},iT=async e=>{let{entry:t,jiraConfig:r}=e,n=Y(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Jr({operation:`create release ${o}`});let s=await Oc(t.type),i=await Ic({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return p.info(`\u2705 Successfully created release: ${o} (${t.type})`),p.info(`\u{1F517} GitHub PR: ${i.prUrl}`),p.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
|
|
399
|
+
`),{result:i}}catch(s){let i=eo(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 p.error(`\u274C ${a.message}
|
|
400
|
+
`),{failure:{version:n,error:a.message}}}},aT=(e,t,r)=>{t===e?p.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(p.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),p.warn(`\u274C ${r} release(s) failed.`)):p.error(`\u274C All ${e} release branch(es) failed to create.`)},Ah=dd(),Ai=async e=>{let{releases:t,confirmedCommand:r}=e;await be({operation:"create release"}),await Ne({provider:Ah,params:e,operation:"create release",argument:"release"});let n=await Yr(),o=null,i=await nT(t,async()=>(o===null&&(o=await vo()),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"});oT(i),await zn({operation:"create release",base:Qe(i[0].type)}),await sT(i,!!r);let a=[],c=[];for(let d of i){let{result:u,failure:m}=await iT({entry:d,jiraConfig:n});u&&a.push(u),m&&c.push(m)}aT(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(d=>d.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},md=R({name:"release-create",requiresHumanConfirm:!0,formProvider:Ah,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:J.array(J.object({version:J.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:J.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:J.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:J.string().optional().describe("Optional description for the Jira version."),releaseDate:ll.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:J.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:J.array(J.string()).describe("List of created release branch names"),successCount:J.number().describe("Number of releases created successfully"),failureCount:J.number().describe("Number of releases that failed"),releases:J.array(J.object({version:J.string().describe("Version number"),type:J.enum(["regular","hotfix"]).describe("Release type"),branchName:J.string().describe("Release branch name"),prUrl:J.string().describe("GitHub PR URL"),jiraVersionUrl:J.string().describe("Jira version URL"),releaseDate:J.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:J.array(J.object({version:J.string().describe("Version number that failed"),error:J.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Ai});import Oh from"@inquirer/input";import{z as Me}from"zod";var Ih=["description","releaseDate"],cT=async()=>{let e=await F(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await oe(),o=await Dt(se({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},lT=async e=>{let r=(await F()).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},dT=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await I(o=>Oh({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},pT=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await I(o=>Oh({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:yo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:ur(n)},uT=e=>{if(e!==void 0)return e===""?null:e},mT=async e=>(h.setInteractive(),{description:await dT(e.description),releaseDate:await pT(e.releaseDate)}),fd=e=>e??"(none)",fT=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${fd(t.releaseDate)} \u2192 ${fd(r.releaseDate)}`,Oi=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=uT(n),i=await Yr(),a;t?(a=ft(t),await lT(a)):(h.setInteractive(),a=(await cT()).branch);let c=K(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 l=Y(c);h.addOption("--version",l);let d=ne(c),u=await ut(d,i);if(!u)throw new f(void 0,{operation:`edit release ${d}`,remediation:`create the Jira fix version "${d}" first or pick a different release`});let m={description:u.description??"",releaseDate:u.releaseDate||null},g=r!==void 0||s!==void 0;if(!g&&ie())throw new x({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=g?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await mT(m),P=Ih.filter(G=>y[G]!==m[G]),v=P.includes("description"),C=P.includes("releaseDate"),_=rr(i,u),O=G=>{let B={version:l,branch:a,jiraVersionUrl:_,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:P,changed:G};return{content:k(JSON.stringify(B,null,2)),structuredContent:B}};if(P.length===0)return p.info(`No change \u2014 ${d} already has description "${m.description}" and release date ${fd(m.releaseDate)}`),h.print(),O(!1);v&&h.addOption("--description",y.description),C&&h.addOption("--release-date",y.releaseDate??"");let E=P.map(G=>fT(G,m,y));return await W(o,`Update ${d}?
|
|
403
401
|
${E.join(`
|
|
404
402
|
`)}
|
|
405
|
-
`),h.addOption("--yes",!0),await zr({versionId:u.id,...v?{description:y.description}:{},...C?{releaseDate:y.releaseDate}:{}},i),v&&await
|
|
406
|
-
`),h.print(),O(!0)},gd=R({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:Me.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Me.string().optional().describe("New description. Empty string clears the description."),releaseDate:dl.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Me.string().describe("Release version"),branch:Me.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Me.string().describe("Jira fix version URL"),previousDescription:Me.string().describe("The description before the update"),newDescription:Me.string().describe("The description after the update"),previousReleaseDate:Me.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Me.string().nullable().describe("The planned release date after the update, or null"),changedFields:Me.array(Me.enum(
|
|
407
|
-
`,"utf-8"),{added:c,skipped:l}};import{$ as
|
|
408
|
-
`,"utf-8");let d=[],u=[];for(let m of r){let g=Di.resolve(m);c.has(g)?d.push(m):u.push(m)}return{removed:d,notFound:u}};import _h from"node:path";var
|
|
409
|
-
`).map(r=>r.trimEnd()).filter(r=>r.length>0),
|
|
410
|
-
`)},Ni=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},OT=e=>typeof e=="string"?e:e.outcome;async function jo(e,t,r){try{let n=await r(),o=OT(n);return t.push({step:e}),p.info({step:e,outcome:o},`\u2705 ${_i[e]} \u2014 ${o}`),n}catch(n){throw new Ni(e,n)}}var DT=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),p.warn({err:Wt(n),step:e},`\u26A0\uFE0F ${_i[e]} failed (non-blocking)`)}},IT=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,NT=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(u=>IT(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.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Vh.indexOf(r)+1} of ${Vh.length} (${_i[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},_T=async e=>{let t=await xo(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}},MT=e=>{let t=e.map(s=>({provider:s.provider,outcome:jT(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}},jT=e=>e.removed.length>0?"verified":"attempted",FT=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await DT("ide-folders",r,async()=>{let o=await kr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=MT(o)}),p.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${_i["ide-folders"]} \u2014 ${n.outcome}`),n},LT=async e=>{let t=await Gr(e.branch);if(Jh({...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 bd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},VT=async e=>(await Ar()===e.branch&&await bd`git switch ${e.baseBranch}`,await cs(e.branch),await lu(e.branch)?Ue({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"),BT=async e=>(await ls(e.branch),e.remoteTipSha?"deleted":"absent"),WT=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}\``;Ue({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}`})},JT=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await WT(e,e.jira,e.jiraConfig),p.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Ac({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),UT=(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}),GT=async(e,t,r)=>{let n=await jo("worktree",r,()=>_T(e)),o=await FT(e,n.removedBranches,r),s=await jo("pr",r,()=>LT(e));p.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await jo("local-branch",r,()=>VT(e)),a=await jo("remote-branch",r,()=>BT(e)),c=await jo("jira",r,()=>JT(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},KT=async(e,t)=>{let r=[];try{return UT(e,await GT(e,t,r))}catch(n){throw n instanceof Ni?NT({plan:e,step:n.step,done:r,cause:n.reason}):n}},HT=async e=>{if(e)return mt(e);h.setInteractive();let[t,r]=await Promise.all([oe(),F()]),n=r.map(s=>s.branch);n.length===0&&Ue({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 It(se({branches:n,descriptions:t,types:o}))}catch(s){throw we(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"})}},Uh=kd(),Mi=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await be({operation:Rr}),await I(),await Ne({provider:Uh,params:e,operation:Rr,argument:"version"}),wT(e);try{let s=await CT(await HT(r),e);p.debug({plan:Wh(s)},"release remove: resolved plan"),Jh(s),kT(s,e),bT(s),await qn({operation:`remove release ${s.label}`,base:s.baseBranch}),RT(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await W(t,AT(s,!!o),{throwOnDecline:!0,plan:{...Wh(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await KT(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw we(s)||at(s)||s instanceof f?s:(p.error({err:Wt(s)},"\u274C Error removing release"),new f(s,{operation:Rr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Rd=R({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:Uh,inputSchema:{version:M.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:M.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:M.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:M.string().describe("The release branch that was targeted"),version:M.string().describe('The release label (e.g. "1.2.5")'),baseBranch:M.string().describe("The branch HEAD was moved to before the local delete"),worktree:M.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:M.object({outcome:M.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:M.array(M.object({provider:M.string(),outcome:M.enum(["verified","attempted","skipped"]),removed:M.array(M.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:M.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:M.number().nullable().describe("The pull request number, or null when none exists"),localBranch:M.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:M.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:M.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:M.string().nullable().describe("The origin tip before deletion"),jira:M.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:M.object({id:M.string(),name:M.string(),url:M.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Mi});import{spawnSync as XT}from"node:child_process";import{homedir as ZT}from"node:os";import QT from"node:process";var qT=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},zT=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},YT=(e,t)=>{let r=qT(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},Fo=(e,t)=>{let r=[...zT(e),...YT(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Lo=e=>e.steps.map(Rt);var eC=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],tC=e=>{let t={...Lp(e)};for(let r of eC)delete t[r];return t},Pd=(e,t,r={})=>{let n=r.spawnSync??XT,o=r.env??QT.env,s=(r.agentMode??Q)(),i=Lo(e),a=Fo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:oC({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??rC}):{ran:!1,commands:i,refusedBecause:a.reasons}},rC=e=>{p.info(e)},Kh=64,nC=Kh*1024*1024,oC=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=tC(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:nC,cwd:ZT(),env:s}),l=dC(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},sC=5,iC=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Gh=e=>e==null?[]:String(e).split(`
|
|
411
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),aC=e=>{let t=Gh(e.stderr),r=Gh(e.stdout),n=[...t,...r].filter(s=>iC.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-sC).join(" / ")},cC="ENOBUFS",lC=e=>e.error?.code===cC,dC=e=>{if(lC(e))return`terminated after exceeding the ${Kh} 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=aC(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var pC=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},uC=e=>{let t=Ie(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},mC=(e,t)=>{let r=uC(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=Fo(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Lo(r),context:n}},ji=async(e=lr,t=po())=>{let r=await mo(lr,t),n={owner:null,present:pC(r)},o=il(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>mC(s.get(a),n)),context:n}};var Sd=(e,t)=>({...Vo(e),action:"skipped",commands:e.commands,detail:t}),Vo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Hh=(e,t)=>e.action==="none"?Sd(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?Sd(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Vo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},fC=(e,t)=>t.ran?t.ok?{...Vo(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Vo(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Vo(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Ed=async e=>{let t=e.run??Pd,{plans:r}=await ji(e.ids,e.probeDeps),n=[];for(let o of r){let s=Hh(o,e.mode);if(s!==null){n.push(s);continue}n.push(fC(o,t(o.recipe,o.context)))}return n},xd=async(e,t)=>{let{plans:r}=await ji(e,t);return r.map(n=>Hh(n,"converge")??Sd(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import AC from"node:process";import{z as T}from"zod";var Td={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},gC=Object.keys(Td).sort((e,t)=>Td[e]-Td[t]),qh={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},zh=new Set(["manual","warn","fail"]),Cd=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return qe(e)}},hC=e=>e.reduce((t,r)=>qh[r]>qh[t]?r:t,"skipped"),Xh=e=>e.message.trim(),yC=e=>["written","unchanged","skipped"].map(r=>{let n=e.filter(o=>o.outcome===r).length;return n>0?`${n} ${r}`:""}).filter(r=>r.length>0).join(" \xB7 "),Yh=e=>e.message===nn,vC=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Xh(r):e.length>1?yC(e):t?"activate with the last line below":"see below"},wC=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Cd(i.outcome)),n=t.filter(i=>zh.has(Cd(i.outcome))).map(Xh),o=t.filter(i=>!zh.has(Cd(i.outcome))&&!Yh(i)),s={name:e,status:hC(r),message:vC(o,t.some(Yh))};return n.length>0?{...s,notes:n}:s},kC=e=>({label:"Local setup",rows:gC.map(t=>wC(t,e.filter(r=>r.step===t)))}),bC=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return qe(e.action)}},RC=(e,t)=>{let r=bC(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},PC=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>RC(r,t))}),SC=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return qe(e)}},EC=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return qe(e)}},xC=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 qe(e)}},TC=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 qe(e.outcome)}},CC=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return qe(e)}},$C=e=>({label:"Portless service",rows:[{name:"link",status:SC(e.link),message:xC(e.link)},{name:"node",status:EC(e.node.outcome),message:TC(e.node)},CC(e.service,e.command)]}),Zh=(e,t)=>[kC(e.init),PC(e.tools,t),$C(e.portless)],Qh=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var OC=()=>{let{link:e,node:t}=os();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},DC=async e=>{let t=eu(e.link).outcome,r=Qp(e.node),n=ns(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return{link:t,node:r,service:"skipped",command:null};let{state:o,stableNode:s}=await $g(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Pt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},ty="--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.",IC=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(ty);return{ids:e.tools??t??lr,mode:r?"update":"converge",skipTools:n}},ey=(e,t)=>e instanceof rn?e.step:t.at(-1)?.step??"zshrc",NC=async()=>{let e=[];try{await Xc(t=>{e.push(t)})}catch(t){e.push({step:ey(t,e),outcome:"failed",message:`The ${ey(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},_C=(e,t)=>{let r=t instanceof Error?t.message:String(t);return e.map(n=>({id:n,action:"failed",before:{present:!1,onPath:!1,version:null,manager:"unknown"},commands:[],detail:`the dependency step failed before reaching this tool: ${r}`}))},MC=async(e,t)=>{try{return e.skipTools?await xd(e.ids,t.probeDeps):await Ed({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return _C(e.ids,r)}},jC=e=>({step:e.step,outcome:e.outcome,message:e.message}),Fi=async(e={})=>{let t=IC(e),r=await NC(),n=await MC(t,e),o=await DC(e.portlessDeps??OC()),s=Zh({init:r,tools:n,portless:o},{skipTools:t.skipTools});Dt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),p.info(nn),Qh(s)&&(AC.exitCode=1);let i={init:r.map(jC),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},FC=T.object({step:T.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:T.enum(["written","unchanged","skipped","manual","warned","failed"]).describe("What that step did: changed something, found nothing to change, did not run, left a command for a human to run (the message carries it), failed non-fatally, or threw and ended the init half (setup exits 1)"),message:T.string().describe("The same line a human running this would have read")}),LC=T.object({id:T.string().describe("Dependency id"),action:T.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:T.object({present:T.boolean(),onPath:T.boolean(),version:T.string().nullable(),manager:T.string()}).describe("The tool\u2019s state before this run"),commands:T.array(T.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:T.string().describe("Why, in one line")}),VC=T.object({link:T.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:T.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:T.enum(["absent","converged","drifted","skipped"]).describe("The installed portless system service against the link and node: not installed, already running through both, installed but pointing elsewhere, or not judged because portless is not installed"),command:T.string().nullable().describe("The sudo `service install` command a human has to run; present if and only if service is absent or drifted, null otherwise")}),BC={init:T.array(FC).describe("One entry per init step, in the order they ran"),tools:T.array(LC).describe("One result per requested dependency"),portlessService:VC.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:T.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:T.boolean().describe("Whether anything was installed or updated"),report:T.array(T.object({label:T.string().describe("Section heading"),rows:T.array(T.object({name:T.string().describe("Init step, tool id, or portless part"),status:T.enum(["ok","changed","skipped","manual","warn","fail"]).describe("ok: nothing to change; changed: changed something; skipped: did not run; manual: not run by the CLI, the notes hold the command a human runs; warn: advisory problem; fail: failed (setup exits 1)"),message:T.string().describe("The row message, as printed"),notes:T.array(T.string()).optional().describe("Lines printed under the row, verbatim: the manual commands, warnings and failures")}))})).describe("The exact rows of the table printed on stderr; setup exits 1 iff a row is fail"),allSucceeded:T.boolean().describe("Whether no tool failed (a refusal is not a failure)")},WC={tools:T.array(T.enum(lr)).optional().describe("Which tools to act on. Omit for all six."),mode:T.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:T.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},$d=R({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:WC,outputSchema:BC,requiresHumanConfirm:!0,handler:e=>Fi({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as ny}from"node:fs";import oy from"node:path";import QC from"node:process";import{z as wt}from"zod";import{createHash as JC}from"node:crypto";import{readFileSync as UC}from"node:fs";var Pr=e=>JC("sha256").update(UC(e)).digest("hex");import{readFileSync as YC,writeFileSync as XC}from"node:fs";import Wi from"node:path";import{z as ot}from"zod";var X="vendor",GC=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),KC=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),HC=[".tsbuildinfo"],Ad=e=>GC.has(e),Od=e=>KC.has(e)?!0:HC.some(t=>e.endsWith(t)),Li=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Ad(o))||Od(r)};import{readdirSync as qC}from"node:fs";import Dd from"node:path";var zC=e=>e.split(Dd.sep).join("/"),Vi=e=>{let t=[],r=n=>{for(let o of qC(n,{withFileTypes:!0})){let s=Dd.join(n,o.name);if(o.isDirectory()){if(Ad(o.name))continue;r(s);continue}Od(o.name)||t.push(zC(Dd.relative(e,s)))}};return r(e),t.sort()};var je=".sync-manifest.json",Bi=1,ZC=ot.object({schemaVersion:ot.number().optional(),source:ot.string(),commit:ot.string(),syncedAt:ot.string(),fileCount:ot.number(),files:ot.record(ot.string(),ot.string())}),Id=e=>(e.schemaVersion??Bi)>Bi,ry=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Vi(e);for(let o of n)try{r[o]=Pr(Wi.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},Bo=e=>{let t=Wi.join(e,je),r;try{r=YC(t,"utf8")}catch{throw new Error(`Missing ${je} at ${t}`)}let n=ZC.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${je} at ${t}: ${ot.prettifyError(n.error)}`);return n.data},Nd=(e,t,r)=>{let n=ry(e,r),o={schemaVersion:Bi,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return XC(Wi.join(e,je),`${JSON.stringify(o,null,2)}
|
|
412
|
-
`),o},_d=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!
|
|
413
|
-
${e} (${t.length}):`);for(let r of t.slice(0,Md))p.info(` ${r}`);t.length>Md&&p.info(` \u2026and ${t.length-Md} more`)}},
|
|
414
|
-
`)},
|
|
403
|
+
`),h.addOption("--yes",!0),await zr({versionId:u.id,...v?{description:y.description}:{},...C?{releaseDate:y.releaseDate}:{}},i),v&&await _s({branch:a,body:Qn(_,y.description)}),p.info(`\u2705 Updated ${P.join(" and ")} for ${d}`),p.info(`\u{1F517} Jira Version: ${_}`),p.info(`\u{1F517} PR branch: ${a}
|
|
404
|
+
`),h.print(),O(!0)},gd=R({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:Me.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Me.string().optional().describe("New description. Empty string clears the description."),releaseDate:dl.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Me.string().describe("Release version"),branch:Me.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Me.string().describe("Jira fix version URL"),previousDescription:Me.string().describe("The description before the update"),newDescription:Me.string().describe("The description after the update"),previousReleaseDate:Me.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Me.string().nullable().describe("The planned release date after the update, or null"),changedFields:Me.array(Me.enum(Ih)).describe("The fields whose value actually changed"),changed:Me.boolean().describe("Whether anything actually changed")},handler:Oi});import{z as M}from"zod";import{$ as bd}from"zx";import Dh from"node:fs/promises";import Ii from"node:path";var hd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Ii.dirname(t),o;try{o=await Dh.readFile(t,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${t}: ${d.message}`)}let s;try{s=JSON.parse(o)}catch(d){throw new Error(`Failed to parse ${t} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],a=new Set(i.map(d=>Ii.resolve(n,d.path))),c=[],l=[];for(let d of r){let u=Ii.resolve(d);if(a.has(u)){l.push(d);continue}let m=Ii.relative(n,u);i.push({path:m}),a.add(u),c.push(d)}return s.folders=i,await Dh.writeFile(t,`${JSON.stringify(s,null,2)}
|
|
405
|
+
`,"utf-8"),{added:c,skipped:l}};import{$ as gT}from"zx";var yd=async e=>{await gT`cursor ${e}`};import Nh from"node:fs/promises";import Di from"node:path";var vd=async e=>{let{workspacePath:t,folderPaths:r}=e,n=Di.dirname(t),o;try{o=await Nh.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=>Di.resolve(m))),c=new Set,l=i.filter(m=>{let g=Di.resolve(n,m.path);return a.has(g)?(c.add(g),!1):!0});s.folders=l,await Nh.writeFile(t,`${JSON.stringify(s,null,2)}
|
|
406
|
+
`,"utf-8");let d=[],u=[];for(let m of r){let g=Di.resolve(m);c.has(g)?d.push(m):u.push(m)}return{removed:d,notFound:u}};import _h from"node:path";var jo=(e,t)=>_h.isAbsolute(e)?e:_h.resolve(t,e);var wd=async e=>{let{projectRoot:t,worktreeDir:r,branches:n}=e,o=await D(),s=Tt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await hT({ide:c,projectRoot:t,folderPaths:i}));return a},hT=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return p.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=jo(t.config.workspaceConfigPath,r),{added:s,skipped:i}=await hd({workspacePath:o,folderPaths:n}),a=i.length>0?` (${i.length} already present)`:"";return p.info(`\u2705 Added ${s.length} folder(s) to ${o}${a}`),await yd(o),{ran:!0,provider:"cursor",added:s.length,skipped:i.length}};var kr=async e=>{let{projectRoot:t,worktreeDir:r,removedWorktrees:n}=e;if(n.length===0)return[];let o=await D(),s=Tt(o),i=n.map(c=>`${r}/${c}`),a=[];for(let c of s)a.push(await yT({ide:c,projectRoot:t,folderPaths:i}));return a},yT=async e=>{let{ide:t,projectRoot:r,folderPaths:n}=e;if(!t.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let o=jo(t.config.workspaceConfigPath,r);try{let{removed:s}=await vd({workspacePath:o,folderPaths:n});return s.length>0&&p.info(`\u2705 Removed ${s.length} folder(s) from ${o}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return p.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${o}`),{provider:"cursor",supported:!0,removed:[]}}};var br=["workspace","none"];import{z as Mh}from"zod";var Lh=2500,Ni="release-remove",jh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vT=e=>e.version===void 0||e.version==="",wT=async()=>{try{return{outcome:"listed",prs:await F()}}catch(e){return e instanceof f&&e.operation===Xn?{outcome:"empty"}:{outcome:"failed"}}},Fh=(e,t)=>(e===null?p.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Ni}`}):e.outcome==="failed"?p.info({msg:`Tool execution form enumeration failed (gh pr list): ${Ni}`}):p.info({msg:`Tool execution form options empty (open release PRs): ${Ni}`}),null),kT=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Ls(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ne(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},bT=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(p.info({msg:`Tool execution form descriptions unavailable (timeout): ${Ni}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},kd=(e={})=>{let t=e.fetchBudgetMs??Lh;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=>jh(r)&&vT(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Sn(wT(),t),Sn(oe(),t)]);if(r===null||r.outcome!=="listed")return Fh(r,t);let o=kT(r.prs,n);return o.length===0?Fh({outcome:"empty"},t):Mh.object({version:Mh.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${bT(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:{...jh(n)?n:{},version:r.version}}};var Vh=["worktree","ide-folders","pr","local-branch","remote-branch","jira"],Mi={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"},Rr="remove a release",Ue=e=>{throw p.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new f(void 0,e)},Bh=(e,t)=>{throw p.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new x({...e,agentMode:A.source},2,t)},RT=e=>{Q()&&(e.version||Bh({status:"argument_required",argument:"version"},{operation:Rr,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&&Bh({status:"refused"},{operation:Rr,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"}))},Jh=e=>{e.pr?.state==="MERGED"&&Ue({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`})},PT=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ue({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)&&Ue({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||Ue({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)`}))},ST=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ue({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"})},ET=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ue({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(", ")}`})},xT=async e=>(await bd`git -C ${e} status --porcelain`).stdout.split(`
|
|
407
|
+
`).map(r=>r.trimEnd()).filter(r=>r.length>0),TT=async e=>{try{let{terminals:t}=await Mu(e);return t.filter(r=>r.connected).length}catch(t){return p.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},CT=async e=>{let t=await vs([e]);if(t!==null)throw p.warn({operation:Rr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new x({status:"refused",reason:"orca_caller_inside_target",agentMode:A.source},2,{operation:Rr,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`})},$T=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await mt();if(!n)return r;let o=await ut(ne(e),n),s=t.moveIssuesTo?await AT(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await js(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:rr(n,o)}}},AT=async(e,t)=>{let r=await ut(e,t);return r||Ue({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}"`})},OT=async(e,t)=>{let r=K(e);r||Ue({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 S(),o=`${n}${ge}`,s=`${o}/${e}`,[i,a,c,l]=await Promise.all([Ce("release"),Gr(e),$e(n,`refs/heads/${e}`),Or(n,e)]),d=i.includes(e);return d&&await CT(s),{...await $T(r,t),branch:e,id:r,label:Y(r),baseBranch:a?.baseRefName??Qe("regular"),projectRoot:n,worktreeDir:o,worktreePath:s,worktreePresent:d,orcaTerminalCount:d?await TT(s):0,worktreeDirty:d?await xT(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Wh=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}),IT=(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}`},DT=(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: ${IT(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
|
|
408
|
+
`)},_i=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},NT=e=>typeof e=="string"?e:e.outcome;async function Fo(e,t,r){try{let n=await r(),o=NT(n);return t.push({step:e}),p.info({step:e,outcome:o},`\u2705 ${Mi[e]} \u2014 ${o}`),n}catch(n){throw new _i(e,n)}}var _T=async(e,t,r)=>{try{await r(),t.push({step:e})}catch(n){t.push({step:e,detail:"attempted"}),p.warn({err:Wt(n),step:e},`\u26A0\uFE0F ${Mi[e]} failed (non-blocking)`)}},MT=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.detail?`${t.step} (${t.detail})`:t.step,jT=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(u=>MT(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.`,l=`completed: ${s}. ${i}${a}${c}`,d=o instanceof f?o.remediation:void 0;return new f(o,{operation:`remove release ${t.label} \u2014 step ${Vh.indexOf(r)+1} of ${Vh.length} (${Mi[r]})`,remediation:d?`${d} \u2014 ${l}`:l})},FT=async e=>{let t=await To(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}},LT=e=>{let t=e.map(s=>({provider:s.provider,outcome:VT(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}},VT=e=>e.removed.length>0?"verified":"attempted",BT=async(e,t,r)=>{let n={outcome:"attempted",providers:[]};return await _T("ide-folders",r,async()=>{let o=await kr({projectRoot:e.projectRoot,worktreeDir:e.worktreeDir,removedWorktrees:t});n=LT(o)}),p.info({outcome:n.outcome,step:"ide-folders"},`\u2705 ${Mi["ide-folders"]} \u2014 ${n.outcome}`),n},WT=async e=>{let t=await Gr(e.branch);if(Jh({...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 bd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},JT=async e=>(await Ar()===e.branch&&await bd`git switch ${e.baseBranch}`,await ls(e.branch),await du(e.branch)?Ue({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"),UT=async e=>(await ds(e.branch),e.remoteTipSha?"deleted":"absent"),GT=async(e,t,r)=>{let n=await js(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}\``;Ue({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}`})},KT=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await GT(e,e.jira,e.jiraConfig),p.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Ac({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),HT=(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}),qT=async(e,t,r)=>{let n=await Fo("worktree",r,()=>FT(e)),o=await BT(e,n.removedBranches,r),s=await Fo("pr",r,()=>WT(e));p.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let i=await Fo("local-branch",r,()=>JT(e)),a=await Fo("remote-branch",r,()=>UT(e)),c=await Fo("jira",r,()=>KT(e,t));return{worktree:n,ideFolders:o,pr:s,localBranch:i,remoteBranch:a,jira:c}},zT=async(e,t)=>{let r=[];try{return HT(e,await qT(e,t,r))}catch(n){throw n instanceof _i?jT({plan:e,step:n.step,done:r,cause:n.reason}):n}},YT=async e=>{if(e)return ft(e);h.setInteractive();let[t,r]=await Promise.all([oe(),F()]),n=r.map(s=>s.branch);n.length===0&&Ue({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 Dt(se({branches:n,descriptions:t,types:o}))}catch(s){throw we(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"})}},Uh=kd(),ji=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await be({operation:Rr}),await D(),await Ne({provider:Uh,params:e,operation:Rr,argument:"version"}),RT(e);try{let s=await OT(await YT(r),e);p.debug({plan:Wh(s)},"release remove: resolved plan"),Jh(s),PT(s,e),ST(s),await zn({operation:`remove release ${s.label}`,base:s.baseBranch}),ET(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await W(t,DT(s,!!o),{throwOnDecline:!0,plan:{...Wh(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await zT(s,e);return h.print(),{content:k(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw we(s)||ct(s)||s instanceof f?s:(p.error({err:Wt(s)},"\u274C Error removing release"),new f(s,{operation:Rr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Rd=R({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:Uh,inputSchema:{version:M.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:M.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:M.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:M.string().describe("The release branch that was targeted"),version:M.string().describe('The release label (e.g. "1.2.5")'),baseBranch:M.string().describe("The branch HEAD was moved to before the local delete"),worktree:M.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),ideFolders:M.object({outcome:M.enum(["verified","attempted","skipped"]).describe('"verified" only when an editor reported a real diff; "skipped" when no editor is configured'),providers:M.array(M.object({provider:M.string(),outcome:M.enum(["verified","attempted","skipped"]),removed:M.array(M.string()).describe("Folder paths confirmed removed")}))}).describe("Per-editor outcome of stripping the worktree folder"),pr:M.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:M.number().nullable().describe("The pull request number, or null when none exists"),localBranch:M.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:M.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:M.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:M.string().nullable().describe("The origin tip before deletion"),jira:M.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:M.object({id:M.string(),name:M.string(),url:M.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:ji});import{spawnSync as eC}from"node:child_process";import{homedir as tC}from"node:os";import rC from"node:process";var XT=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},ZT=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},QT=(e,t)=>{let r=XT(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=[...ZT(e),...QT(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Vo=e=>e.steps.map(Rt);var nC=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],oC=e=>{let t={...Vp(e)};for(let r of nC)delete t[r];return t},Pd=(e,t,r={})=>{let n=r.spawnSync??eC,o=r.env??rC.env,s=(r.agentMode??Q)(),i=Vo(e),a=Lo(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:aC({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??sC}):{ran:!1,commands:i,refusedBecause:a.reasons}},sC=e=>{p.info(e)},Kh=64,iC=Kh*1024*1024,aC=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=oC(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:iC,cwd:tC(),env:s}),l=mC(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},cC=5,lC=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Gh=e=>e==null?[]:String(e).split(`
|
|
409
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),dC=e=>{let t=Gh(e.stderr),r=Gh(e.stdout),n=[...t,...r].filter(s=>lC.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-cC).join(" / ")},pC="ENOBUFS",uC=e=>e.error?.code===pC,mC=e=>{if(uC(e))return`terminated after exceeding the ${Kh} 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=dC(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var fC=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},gC=e=>{let t=De(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},hC=(e,t)=>{let r=gC(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:Vo(r),context:n}},Fi=async(e=lr,t=uo())=>{let r=await fo(lr,t),n={owner:null,present:fC(r)},o=il(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>hC(s.get(a),n)),context:n}};var Sd=(e,t)=>({...Bo(e),action:"skipped",commands:e.commands,detail:t}),Bo=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Hh=(e,t)=>e.action==="none"?Sd(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?Sd(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Bo(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},yC=(e,t)=>t.ran?t.ok?{...Bo(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Bo(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Bo(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Ed=async e=>{let t=e.run??Pd,{plans:r}=await Fi(e.ids,e.probeDeps),n=[];for(let o of r){let s=Hh(o,e.mode);if(s!==null){n.push(s);continue}n.push(yC(o,t(o.recipe,o.context)))}return n},xd=async(e,t)=>{let{plans:r}=await Fi(e,t);return r.map(n=>Hh(n,"converge")??Sd(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import DC from"node:process";import{z as T}from"zod";var Td={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,shell:10},vC=Object.keys(Td).sort((e,t)=>Td[e]-Td[t]),qh={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},zh=new Set(["manual","warn","fail"]),Cd=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return qe(e)}},wC=e=>e.reduce((t,r)=>qh[r]>qh[t]?r:t,"skipped"),Xh=e=>e.message.trim(),kC=e=>["written","unchanged","skipped"].map(r=>{let n=e.filter(o=>o.outcome===r).length;return n>0?`${n} ${r}`:""}).filter(r=>r.length>0).join(" \xB7 "),Yh=e=>e.message===on,bC=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Xh(r):e.length>1?kC(e):t?"activate with the last line below":"see below"},RC=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Cd(i.outcome)),n=t.filter(i=>zh.has(Cd(i.outcome))).map(Xh),o=t.filter(i=>!zh.has(Cd(i.outcome))&&!Yh(i)),s={name:e,status:wC(r),message:bC(o,t.some(Yh))};return n.length>0?{...s,notes:n}:s},PC=e=>({label:"Local setup",rows:vC.map(t=>RC(t,e.filter(r=>r.step===t)))}),SC=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return qe(e.action)}},EC=(e,t)=>{let r=SC(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},xC=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>EC(r,t))}),TC=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return qe(e)}},CC=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return qe(e)}},$C=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 qe(e)}},AC=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 qe(e.outcome)}},OC=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return qe(e)}},IC=e=>({label:"Portless service",rows:[{name:"link",status:TC(e.link),message:$C(e.link)},{name:"node",status:CC(e.node.outcome),message:AC(e.node)},OC(e.service,e.command)]}),Zh=(e,t)=>[PC(e.init),xC(e.tools,t),IC(e.portless)],Qh=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var NC=()=>{let{link:e,node:t}=ss();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},_C=async e=>{let t=tu(e.link).outcome,r=eu(e.node),n=os(e.link.home,e.target.exists)??e.link.resolveBin();if(n===null)return{link:t,node:r,service:"skipped",command:null};let{state:o,stableNode:s}=await $g(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Pt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},ty="--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.",MC=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(ty);return{ids:e.tools??t??lr,mode:r?"update":"converge",skipTools:n}},ey=(e,t)=>e instanceof nn?e.step:t.at(-1)?.step??"zshrc",jC=async()=>{let e=[];try{await Xc(t=>{e.push(t)})}catch(t){e.push({step:ey(t,e),outcome:"failed",message:`The ${ey(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},FC=(e,t)=>{let r=t instanceof Error?t.message:String(t);return e.map(n=>({id:n,action:"failed",before:{present:!1,onPath:!1,version:null,manager:"unknown"},commands:[],detail:`the dependency step failed before reaching this tool: ${r}`}))},LC=async(e,t)=>{try{return e.skipTools?await xd(e.ids,t.probeDeps):await Ed({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return FC(e.ids,r)}},VC=e=>({step:e.step,outcome:e.outcome,message:e.message}),Li=async(e={})=>{let t=MC(e),r=await jC(),n=await LC(t,e),o=await _C(e.portlessDeps??NC()),s=Zh({init:r,tools:n,portless:o},{skipTools:t.skipTools});It({title:"infra-kit setup",sections:s},{ascii:e.ascii}),p.info(on),Qh(s)&&(DC.exitCode=1);let i={init:r.map(VC),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:k(JSON.stringify(i,null,2)),structuredContent:i}},BC=T.object({step:T.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","shell"]).describe("Which init step this reports on"),outcome:T.enum(["written","unchanged","skipped","manual","warned","failed"]).describe("What that step did: changed something, found nothing to change, did not run, left a command for a human to run (the message carries it), failed non-fatally, or threw and ended the init half (setup exits 1)"),message:T.string().describe("The same line a human running this would have read")}),WC=T.object({id:T.string().describe("Dependency id"),action:T.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:T.object({present:T.boolean(),onPath:T.boolean(),version:T.string().nullable(),manager:T.string()}).describe("The tool\u2019s state before this run"),commands:T.array(T.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:T.string().describe("Why, in one line")}),JC=T.object({link:T.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:T.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:T.enum(["absent","converged","drifted","skipped"]).describe("The installed portless system service against the link and node: not installed, already running through both, installed but pointing elsewhere, or not judged because portless is not installed"),command:T.string().nullable().describe("The sudo `service install` command a human has to run; present if and only if service is absent or drifted, null otherwise")}),UC={init:T.array(BC).describe("One entry per init step, in the order they ran"),tools:T.array(WC).describe("One result per requested dependency"),portlessService:JC.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:T.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:T.boolean().describe("Whether anything was installed or updated"),report:T.array(T.object({label:T.string().describe("Section heading"),rows:T.array(T.object({name:T.string().describe("Init step, tool id, or portless part"),status:T.enum(["ok","changed","skipped","manual","warn","fail"]).describe("ok: nothing to change; changed: changed something; skipped: did not run; manual: not run by the CLI, the notes hold the command a human runs; warn: advisory problem; fail: failed (setup exits 1)"),message:T.string().describe("The row message, as printed"),notes:T.array(T.string()).optional().describe("Lines printed under the row, verbatim: the manual commands, warnings and failures")}))})).describe("The exact rows of the table printed on stderr; setup exits 1 iff a row is fail"),allSucceeded:T.boolean().describe("Whether no tool failed (a refusal is not a failure)")},GC={tools:T.array(T.enum(lr)).optional().describe("Which tools to act on. Omit for all six."),mode:T.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:T.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},$d=R({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:GC,outputSchema:UC,requiresHumanConfirm:!0,handler:e=>Li({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as ny}from"node:fs";import oy from"node:path";import r$ from"node:process";import{z as wt}from"zod";import{createHash as KC}from"node:crypto";import{readFileSync as HC}from"node:fs";var Pr=e=>KC("sha256").update(HC(e)).digest("hex");import{readFileSync as QC,writeFileSync as e$}from"node:fs";import Ji from"node:path";import{z as st}from"zod";var X="vendor",qC=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),zC=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),YC=[".tsbuildinfo"],Ad=e=>qC.has(e),Od=e=>zC.has(e)?!0:YC.some(t=>e.endsWith(t)),Vi=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Ad(o))||Od(r)};import{readdirSync as XC}from"node:fs";import Id from"node:path";var ZC=e=>e.split(Id.sep).join("/"),Bi=e=>{let t=[],r=n=>{for(let o of XC(n,{withFileTypes:!0})){let s=Id.join(n,o.name);if(o.isDirectory()){if(Ad(o.name))continue;r(s);continue}Od(o.name)||t.push(ZC(Id.relative(e,s)))}};return r(e),t.sort()};var je=".sync-manifest.json",Wi=1,t$=st.object({schemaVersion:st.number().optional(),source:st.string(),commit:st.string(),syncedAt:st.string(),fileCount:st.number(),files:st.record(st.string(),st.string())}),Dd=e=>(e.schemaVersion??Wi)>Wi,ry=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Bi(e);for(let o of n)try{r[o]=Pr(Ji.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},Wo=e=>{let t=Ji.join(e,je),r;try{r=QC(t,"utf8")}catch{throw new Error(`Missing ${je} at ${t}`)}let n=t$.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${je} at ${t}: ${st.prettifyError(n.error)}`);return n.data},Nd=(e,t,r)=>{let n=ry(e,r),o={schemaVersion:Wi,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return e$(Ji.join(e,je),`${JSON.stringify(o,null,2)}
|
|
410
|
+
`),o},_d=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Vi(c))),n=Bi(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Pr(Ji.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 Md=30,jd=(e,t)=>{if(t.length!==0){p.info(`
|
|
411
|
+
${e} (${t.length}):`);for(let r of t.slice(0,Md))p.info(` ${r}`);t.length>Md&&p.info(` \u2026and ${t.length-Md} more`)}},Ui=async(e={})=>{let t=e.cwd??await S(),r=oy.join(t,X),n={modified:[],added:[],removed:[],fileCount:0};if(!ny(r)){p.info(`\u2139\uFE0F No ${X}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}if(!ny(oy.join(r,je))){p.error(`\u274C Missing ${X}/${je}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let o=Wo(r);if(Dd(o)){p.error(`\u274C ${X}/${je} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:a}=_d(r,o),c=s.length>0||i.length>0||a.length>0;c?(p.error(`\u274C ${X}/ has drifted from ${X}/${je}.`),p.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),jd("Modified",s),jd("Added (not in manifest)",i),jd("Removed (in manifest, now missing)",a)):p.info(`\u2705 ${X}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:k(JSON.stringify(l,null,2)),structuredContent:l}},n$={status:wt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:wt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:wt.number(),modified:wt.array(wt.string()),added:wt.array(wt.string()),removed:wt.array(wt.string())},Fd=R({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:n$,handler:()=>Ui({cwd:r$.cwd()})});import sy from"node:process";import{z as Jo}from"zod";var iy=async e=>{try{return await e()}catch{return null}},Gi=async()=>{let e=q.version;p.info(e);let t=await iy(S),r=t===null?null:await iy(()=>Le(t)),n={version:e,cwd:sy.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:sy.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},Ld=R({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:Jo.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Jo.string().describe("The working directory of this process"),repoRoot:Jo.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Jo.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Jo.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Gi});import cy from"@inquirer/confirm";import o$ from"node:path";import{z as U}from"zod";import{$ as Uo}from"zx";var Ki="create worktrees",s$=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Vd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Hi=async e=>{let{confirmedCommand:t,all:r,versions:n,githubDesktop:o,orca:s}=e,i=e.ide??e.cursor;await be({operation:Ki});try{let a=await Ce("release"),c=await S(),l=`${c}${ge}`;await ay(`${l}/${Cr.release}`),await ay(`${l}/${Cr.feature}`);let d=[];if(n)d=n.split(",").map(j=>Te(ve(j.trim())));else{let j=await F(),Ke=j.map(xe=>xe.branch);if(Ke.length===0){p.info("\u2139\uFE0F No open release branches found"),h.print();let xe={createdWorktrees:[],count:0,...Vd()};return{content:k(JSON.stringify(xe,null,2)),structuredContent:xe}}if(r)d=Ke;else{h.setInteractive();let xe=new Map(j.map(Xo=>[Xo.branch,Xo.type])),fa=await oe();d=await Nt(se({branches:Ke,descriptions:fa,types:xe}),{required:!0})}}r?h.addOption("--all",!0):h.addOption("--versions",nr(d));let u=await D(),m=i??(Tt(u).length>0?"workspace":"none");h.addOption("--ide",m);let g=await i$(o,u),y=await a$(s,u),P=await Le(c),v=o$.basename(P),C=y?await c$({explicit:s!==void 0,mainRepoRoot:P}):null;await W(t,l$(C,v)),t||h.addOption("--yes",!0);let _=C?await d$(C,P):null,{branchesToCreate:O}=f$({selectedReleaseBranches:d,currentWorktrees:a}),E=await g$(O,l);if(h$(E),m==="workspace"&&await wd({projectRoot:c,worktreeDir:l,branches:E}),g)for(let j of E)await Uo`github ${l}/${j}`,await Uo`sleep 5`;let G=_?await u$({registration:_,createdWorktrees:E,worktreeDir:l,mainRepoRoot:P,repoName:v,config:u}):Vd();m$(G),h.print();let B={createdWorktrees:E,count:E.length,...G};return{content:k(JSON.stringify(B,null,2)),structuredContent:B}}catch(a){throw we(a)||a instanceof x?a:(p.debug({err:a},"Error managing worktrees"),new f(a,{operation:Ki,remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},i$=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await I(o=>cy({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},a$=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await I(o=>cy({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&h.setInteractive(),h.addOption(n?"--orca":"--no-orca",!0),n},ly=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"},c$=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Ir();if(n!=="ready"){let{reason:s,text:i}=ly(n);if(t)throw p.warn({operation:Ki},`\u26D4 --orca was passed but ${i}`),new x({status:"refused",reason:s,agentMode:A.source},2,{operation:Ki,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 p.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await Fu(r);return{probe:n,registered:o.registered,visibility:o.visibility}},l$=(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(`
|
|
412
|
+
`)},d$=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:ly(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Lu(t);return{kind:"ready",visibility:r}}catch(r){return p.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 ys?r.code:void 0}}},p$=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,u$=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Vd();if(t.kind==="skip"){for(let u of r)a.orcaSkipped.push({branch:u,reason:t.reason,code:t.code});return a}let c=ku(i),l=r.length===1&&t.visibility!=="hide",d=Bu();for(let u of r){let m=`${n}/${u}`;try{let{layout:g}=await Wu({cwd:m,title:Ju({branch:u}),focus:l,layout:"full",panes:c,poll:d});await Vu(o,m)?a.orcaOpened.push({branch:u,layout:g}):a.orcaHidden.push({branch:u,path:m,fix:p$(s)})}catch(g){p.warn({error:g,branch:u},`\u26A0\uFE0F Failed to open Orca terminals for ${u}`),g instanceof ys&&g.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:u,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:u,reason:"orca_error",code:g instanceof ys?g.code:void 0})}}return a},m$=e=>{for(let t of e.orcaOpened)p.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)p.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})`:"";p.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},ay=async e=>{await Uo`mkdir -p ${e}`},f$=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>cs(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},g$=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o}`;return await Uo`git worktree add ${s} ${o}`,await Uo({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"});p.error({error:s.reason,msg:a.message})}return n},h$=e=>{if(e.length>0){p.info("\u2705 Created git worktrees:");for(let t of e)p.info(t);p.info("")}else p.info("\u2139\uFE0F No new git worktrees to create")},Bd=R({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:U.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:U.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:U.enum(br).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:U.enum(br).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:U.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:U.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:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created"),orcaOpened:U.array(U.object({branch:U.string(),layout:U.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:U.array(U.object({branch:U.string(),reason:U.enum(s$),code:U.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:U.array(U.object({branch:U.string(),path:U.string(),fix:U.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:Hi});import{z as En}from"zod";var qi=async()=>{await D();let e=await Ce("release");if(e.length===0)return p.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([F(),oe()]),n=new Map(t.map(c=>[c.branch,c.type])),o=e.flatMap(c=>{let l=K(c);if(!l)return[];let d=Y(l),u=n.get(c)||"regular",m=r.get(ne(l))||null;return[{version:d,type:u,description:m}]}),s=Math.max(...o.map(c=>c.version.length)),i=o.map(c=>{let l=ro(c.version,c.type,s);return c.description?`${l} ${c.description}`:l});p.info(`\u{1F33F} Active worktrees:
|
|
415
413
|
|
|
416
414
|
${i.join(`
|
|
417
|
-
`)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},Wd=R({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:Sn.array(Sn.object({version:Sn.string().describe("Release version"),type:Sn.enum(["regular","hotfix"]).describe("Release type"),description:Sn.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Sn.number().describe("Number of worktrees")},handler:Hi});import{z as Sr}from"zod";var f$=e=>{if(Q()){if(e.all)throw new x({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 x({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"})}},g$=(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(", ")}`})},h$=async(e,t)=>{let r=await ys(t.map(n=>`${e}/${n}`));if(r!==null)throw new x({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`})},qi=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await be({operation:"remove worktrees"}),await I(),f$({all:r,versions:n});try{let o=await Ce("release");if(o.length===0){p.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let s=await S(),i=`${s}${ge}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(d=>Te(ve(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([oe(),F()]),m=new Map(u.map(g=>[g.branch,g.type]));a=await Nt(se({branches:o,descriptions:d,types:m}),{required:!0})}g$(a,o);let c=a.length===o.length;c?h.addOption("--all",!0):h.addOption("--versions",nr(a)),await h$(i,a),await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let l=await yr({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await kr({projectRoot:s,worktreeDir:i,removedWorktrees:l.removed}),So(l),h.print(),Eo({result:l,operation:"remove worktrees"})}catch(o){throw we(o)||o instanceof f?o:(p.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"}))}},Jd=R({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:Sr.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:Sr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Sr.array(Sr.string()).describe("List of removed git worktree branches"),failedWorktrees:Sr.array(Sr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Sr.number().describe("Number of git worktrees removed")},handler:qi});import{z as Uo}from"zod";var zi=async e=>{let{confirmedCommand:t}=e;await be({operation:"sync worktrees"}),await I();try{let r=await Ce("release"),n=await S(),o=`${n}${ge}`,s=await Is();await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=y$({releasePRsList:s,currentWorktrees:r}),a=await yr({branches:i,worktreeDir:o,projectRoot:n});return await kr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),So(a),h.print(),Eo({result:a,operation:"sync worktrees"})}catch(r){throw we(r)||r instanceof f?r:(p.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"}))}},y$=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>as(s)).filter(s=>!t.includes(s))}},Ud=R({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:Uo.array(Uo.string()).describe("List of removed worktree branches"),failedWorktrees:Uo.array(Uo.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Uo.number().describe("Number of worktrees removed during sync")},handler:zi});var Gd=[{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"}],fr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:gc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:xl,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:jl,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Ql,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:md,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:gd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Yl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Zl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Ll,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Rd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:cd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:ld,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Bd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Wd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Jd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Ud,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Il,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:$l,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Dl,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Cl,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Nl,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:uc,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:Fd,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:$d,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:bl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:pc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Ld,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 Kd=e=>fr.filter(t=>t.menuGroup===e),Hd=e=>fr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var v$=(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},dy=e=>Gd.flatMap(({key:t,label:r})=>Kd(t).flatMap(n=>{let o=v$(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import qd from"node:process";var w$="MODULE_TYPELESS_PACKAGE_JSON",k$=(e,t)=>typeof e=="object"&&e!==null?e.code:t,py=!1,zd=()=>{if(py)return;py=!0;let e=qd.emitWarning.bind(qd);qd.emitWarning=((t,...r)=>{k$(r[0],r[1])!==w$&&e(t,...r)})};import{Command as BA,InvalidArgumentError as WA}from"commander";import{resolve as JA}from"node:path";import Fe from"node:process";import{cd as UA}from"zx";import uy from"node:process";import{$ as b$}from"zx";var Yd=async()=>{let e=await te(),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 ee(i.path)}))),r=t.at(-1)?.exists===!0,n=await co(e.userProject,r),o=r?lo(n):"";p.info(`Project name: ${e.projectName}
|
|
415
|
+
`)}`);let a={worktrees:o,count:o.length};return{content:k(JSON.stringify(a,null,2)),structuredContent:a}},Wd=R({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:qi});import{z as Sr}from"zod";var y$=e=>{if(Q()){if(e.all)throw new x({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 x({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"})}},v$=(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(", ")}`})},w$=async(e,t)=>{let r=await vs(t.map(n=>`${e}/${n}`));if(r!==null)throw new x({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`})},zi=async e=>{let{confirmedCommand:t,all:r,versions:n}=e;await be({operation:"remove worktrees"}),await D(),y$({all:r,versions:n});try{let o=await Ce("release");if(o.length===0){p.info("\u2139\uFE0F No active worktrees to remove"),h.print();let d={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(d,null,2)),structuredContent:d}}let s=await S(),i=`${s}${ge}`,a=[];if(r)a=o;else if(n)a=n.split(",").map(d=>Te(ve(d.trim())));else{h.setInteractive();let[d,u]=await Promise.all([oe(),F()]),m=new Map(u.map(g=>[g.branch,g.type]));a=await Nt(se({branches:o,descriptions:d,types:m}),{required:!0})}v$(a,o);let c=a.length===o.length;c?h.addOption("--all",!0):h.addOption("--versions",nr(a)),await w$(i,a),await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let l=await yr({branches:a,worktreeDir:i,projectRoot:s,pruneFolder:c});return await kr({projectRoot:s,worktreeDir:i,removedWorktrees:l.removed}),Eo(l),h.print(),xo({result:l,operation:"remove worktrees"})}catch(o){throw we(o)||o instanceof f?o:(p.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"}))}},Jd=R({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:Sr.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:Sr.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Sr.array(Sr.string()).describe("List of removed git worktree branches"),failedWorktrees:Sr.array(Sr.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Sr.number().describe("Number of git worktrees removed")},handler:zi});import{z as Go}from"zod";var Yi=async e=>{let{confirmedCommand:t}=e;await be({operation:"sync worktrees"}),await D();try{let r=await Ce("release"),n=await S(),o=`${n}${ge}`,s=await Ns();await W(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=k$({releasePRsList:s,currentWorktrees:r}),a=await yr({branches:i,worktreeDir:o,projectRoot:n});return await kr({projectRoot:n,worktreeDir:o,removedWorktrees:a.removed}),Eo(a),h.print(),xo({result:a,operation:"sync worktrees"})}catch(r){throw we(r)||r instanceof f?r:(p.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"}))}},k$=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>cs(s)).filter(s=>!t.includes(s))}},Ud=R({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:Yi});var Gd=[{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"}],fr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:gc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:xl,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:jl,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Ql,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:md,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:gd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Yl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Zl,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Ll,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Rd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:cd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:ld,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Bd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Wd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Jd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Ud,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Dl,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:$l,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Il,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Cl,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:Nl,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:uc,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:Fd,mcpExposed:!0,mutating:!1,groupPath:["vendor","check"]},{cliName:"vendor-config",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["vendor","config"]},{cliName:"vendor-sync",menuGroup:"vendor",mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["vendor","sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:$d,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:bl,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:pc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Ld,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 Kd=e=>fr.filter(t=>t.menuGroup===e),Hd=e=>fr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var b$=(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},dy=e=>Gd.flatMap(({key:t,label:r})=>Kd(t).flatMap(n=>{let o=b$(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import qd from"node:process";var R$="MODULE_TYPELESS_PACKAGE_JSON",P$=(e,t)=>typeof e=="object"&&e!==null?e.code:t,py=!1,zd=()=>{if(py)return;py=!0;let e=qd.emitWarning.bind(qd);qd.emitWarning=((t,...r)=>{P$(r[0],r[1])!==R$&&e(t,...r)})};import{Command as JA,InvalidArgumentError as UA}from"commander";import{resolve as GA}from"node:path";import Fe from"node:process";import{cd as KA}from"zx";import uy from"node:process";import{$ as S$}from"zx";var Yd=async()=>{let e=await te(),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 ee(i.path)}))),r=t.at(-1)?.exists===!0,n=await lo(e.userProject,r),o=r?po(n):"";p.info(`Project name: ${e.projectName}
|
|
418
416
|
`),p.info(`Config merge chain (later overrides earlier):
|
|
419
|
-
`);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";p.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}},Xd=async()=>{let e=await te(),t=uy.env.EDITOR||uy.env.VISUAL||"vi",r=await
|
|
420
|
-
`))}
|
|
421
|
-
`),ep=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await We(),{token:s,source:i}=await
|
|
422
|
-
`;import
|
|
417
|
+
`);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";p.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}},Xd=async()=>{let e=await te(),t=uy.env.EDITOR||uy.env.VISUAL||"vi",r=await Qr(e);r.createdConfig&&p.info(en(r)),p.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await S$({stdio:"inherit"})`${t} ${e.userProject}`,Ct();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var my="https://dashboard.doppler.com/workplace/projects",E$=(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}"): ${my}/${e}`],Zd=async({env:e})=>{let r=!!(await ue())?.envs[e];await _u(e);let n=await We(),o=await lt();r?p.info(`Removed the "${e}" service token from ${w(o)}.`):p.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of E$(n,e))p.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${my}/${n}`};return{content:k(JSON.stringify(s,null,2)),structuredContent:s}};import x$ from"@inquirer/password";import Zi from"node:process";import{$ as Xi}from"zx";var T$=async({stdin:e,fromEnv:t})=>{if(e)return{token:await C$(),source:"stdin"};if(t){let n=Zi.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}return h.setInteractive(),{token:(await I(n=>x$({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:Zi.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},C$=async()=>{let e=[];Zi.stdin.setEncoding("utf8");for await(let t of Zi.stdin)e.push(t);return e.join("").trim()},Qd="DOPPLER_CONFIG",$$=3e4,A$=async(e,t,r)=>{let n=Xi.quiet;Xi.quiet=!0;let o;try{o=(await Xi({env:wn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout($$)).stdout}catch(s){throw O$(s,r)}finally{Xi.quiet=n}return hi(o)},O$=(e,t)=>{let r=$r(e)??(e instanceof Error?e.message:String(e));if(ir(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=ar(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(`
|
|
418
|
+
`))},I$=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Qd}.`,"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(`
|
|
419
|
+
`),ep=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await We(),{token:s,source:i}=await T$({stdin:t,fromEnv:r});if(!s)throw new Error("No token provided \u2014 nothing was written.");let a=await A$(s,o,e);gi(a,e);let c=a.some(([u])=>u===Qd);if(!c&&!n)throw new Error(I$(e));await Nu(e,s);let l=await lt();p.info(`Stored the "${e}" service token (${bn(s)}) in ${w(l)} (mode 0600).`),c||p.warn(`Scope was NOT verified (no ${Qd} in the payload) \u2014 written because --force was given.`);let d={env:e,source:i,redactedToken:bn(s),storePath:l,scopeVerified:c};return h.print(),{content:k(JSON.stringify(d,null,2)),structuredContent:d}};var tp=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:d}=e,u=await ql(n);if(r&&h.addOption("--from",u),Hl(u,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":d}),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"?Pi({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Si({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},rp=async e=>tp(e,"all"),np=async e=>tp(e,"selected"),Qi=async(e,t)=>{let r=`release deploy-${t} --from local`;return p.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),tp({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as gy}from"@slip-stream-kit/config/internal";import op from"node:fs/promises";import sp from"node:path";import fy from"node:process";import{pathToFileURL as D$}from"node:url";var hy="~/projects",ip=async(e={})=>{if(e.init){await _$(e.cwd);return}await N$()},N$=async()=>{let e=rn(),t=await ee(e);if(p.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){p.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),fy.exitCode=1;return}let{workspaceDir:r,targets:n}=await Zs(),o=Xs(r),s=await ee(o);p.info(`workspaceDir: ${r} (resolved: ${o}) ${s?"[\u2713 exists]":"[ ] not found"}`),p.info("Targets:");let i=s;for(let a of n){let c=sp.join(o,a),l=await ee(c);l||(i=!1);let d=l?"[\u2713]":"[ ]",u=l?"":" (not found \u2014 clone or remove)";p.info(` ${d} ${a} ${w(c)}${u}`)}i||(fy.exitCode=1)},_$=async e=>{let t=rn();if(await ee(t)){p.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await S(),n=await M$(r);await op.mkdir(sp.dirname(t),{recursive:!0}),await op.writeFile(t,j$(n),"utf-8"),p.info(`\u2713 Created ${w(t)}`),n.length>0&&p.info(` Seeded ${n.length} target(s) from the source ${gy}.`),p.info(` Edit \`workspaceDir\` (placeholder: ${hy}) to point at where your repos live.`),n.length===0&&p.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},M$=async e=>{try{let t=sp.join(e,gy),r=await op.stat(t),s=(await import(`${D$(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[]},j$=e=>`${JSON.stringify({workspaceDir:hy,targets:e},null,2)}
|
|
420
|
+
`;import vp from"node:process";import{chmodSync as G$,copyFileSync as K$,lstatSync as H$,mkdirSync as xy,readdirSync as q$,readlinkSync as z$,rmdirSync as Ty,symlinkSync as Y$,unlinkSync as X$,writeFileSync as Z$}from"node:fs";import ye from"node:path";import{lstatSync as F$,readlinkSync as yy}from"node:fs";import L$ from"node:path";var V$=new Set(["ENOENT","ENOTDIR"]),ea=e=>{let t;try{t=F$(e)}catch(r){if(V$.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:yy(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Pr(e)}:{kind:"other"}},vy=(e,t)=>{let r=L$.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:yy(r)}:{kind:"file",executable:t.mode==="100755",sha:Pr(r)};return{...t,fingerprint:n}},wy=(e,t)=>t===null||e.kind!==t.kind?!1:e.kind==="link"&&t.kind==="link"?e.text===t.text:e.kind==="file"&&t.kind==="file"?e.executable===t.executable&&e.sha===t.sha:!1;import{$ as B$}from"zx";var Z=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await B$({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ta=e=>e.slice(0,7),Gt=e=>e.split("\0").filter(t=>t.length>0);import W$ from"node:path";var ap=`${X}/`,Kt=`${X}/README.md`,Ko=`${X}/${je}`,by=e=>e.startsWith(ap),ky=e=>{let t=W$.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},Ry=e=>{let t=ky(e.path),r=e.target===void 0?t:ky(e.target);return{path:t,target:r,vendored:by(r)}},Py=e=>e.copy.map(Ry),Ho=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),qo=(e,t)=>e.filter(r=>!Ho(r.path,t)),ra=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,xn=e=>[...new Set(e)].sort(),Sy=e=>e.startsWith(ap)?e.slice(ap.length):null;var na=e=>`# vendor/ \u2014 mirrored from ${e}
|
|
423
421
|
|
|
424
422
|
**DO NOT EDIT files in this folder here.**
|
|
425
423
|
|
|
@@ -430,19 +428,19 @@ fail \`ik vendor check\` in CI.
|
|
|
430
428
|
To change a vendored package, edit it in \`${e}\` and re-run the sync there.
|
|
431
429
|
|
|
432
430
|
See \`.sync-manifest.json\` for the source commit and per-file checksums.
|
|
433
|
-
`;var
|
|
434
|
-
`).trim()||String(e)},
|
|
435
|
-
`).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},
|
|
436
|
-
`)[0]??"git rev-parse failed"}}},
|
|
437
|
-
`).slice(0,
|
|
431
|
+
`;var J$=new Set(["100644","100755","120000"]),U$=(e,t)=>{let r=new Map;for(let n of Gt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!J$.has(s)||Ho(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},cp=async(e,t,r)=>{let n=await Z(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return U$(n,r)},Ey=async e=>Gt(await Z(e,["--literal-pathspecs","ls-files","-z","--",X]));var Tn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],Cy=e=>{let t=ea(e);t!==null&&(t.kind==="other"?Ty(e):X$(e))},Q$=(e,t,r)=>{let n=ye.join(e,r.source),o=ye.join(t,r.target);if(xy(ye.dirname(o),{recursive:!0}),Cy(o),r.mode==="120000"){Y$(z$(n),o);return}K$(n,o),G$(o,r.mode==="100755"?493:420)},eA=async(e,t)=>{let r=new Set;for(let n of Gt(await Z(e,["ls-files","-z"]))){if(t.has(n))continue;let o=ye.posix.dirname(n);for(;o!==".";)r.add(o),o=ye.posix.dirname(o)}return r},tA=async(e,t)=>{if(t.length===0)return;let r=await eA(e,new Set(t)),n=[...new Set(t.map(o=>ye.dirname(ye.join(e,o))))];n.sort((o,s)=>s.length-o.length);for(let o of n){let s=o;for(;s!==e&&s.startsWith(e)&&!(!H$(s,{throwIfNoEntry:!1})?.isDirectory()||q$(s).length>0||r.has(ye.relative(e,s).split(ye.sep).join("/")));)Ty(s),s=ye.dirname(s)}},$y=(e,t,r)=>{let n=new Set(r),o=e.filter(a=>a.vendored).flatMap(a=>a.targetPaths),s=t.filter(a=>!n.has(a)),i=[...o,Kt,...s].map(Sy).filter(a=>a!==null&&!Vi(a));return xn(i)},Ay=async(e,t,r,n)=>{let o=ye.join(e,X);xy(o,{recursive:!0}),Z$(ye.join(e,Kt),na(t.name));let s=$y(r,await Ey(e),n);Nd(o,{source:t.name,commit:t.headSha},s)},lp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Tn(t));let n=ye.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)Cy(ye.join(n,a));await tA(n,o);let s=t.entries.flatMap(a=>a.writes);for(let a of s)Q$(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await Ay(n,e,t.entries,o),{touched:xn([...o,...i,Kt,Ko]),manifestWritten:!0}):{touched:xn([...o,...i]),manifestWritten:!1}},dp=async(e,t)=>(await Ay(e,t,[],[]),[Kt,Ko]);var pp=(e,t)=>`[ROOT] vendor: sync from ${e}@${ta(t)}`,rA=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
|
|
432
|
+
`).trim()||String(e)},up=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await Z(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Z(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:rA(s)}}};var nA=20,oA=20,Oy=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],Iy=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let d of qo(e.files,r)){let u=ra(d.path,n);if(s.push(u),wy(d.fingerprint,t.onDisk[u]??null))continue;let m=o.has(u)?"modified":"added";i.push({source:d.path,target:u,mode:d.mode,change:m})}let a=new Set(s),c=qo(t.tracked.map(d=>({path:d})),r).map(d=>d.path).filter(d=>!a.has(d)),l=i.filter(d=>d.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length}}},zo=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),mp=e=>e.entries.map(t=>t.entry.target),sA=(e,t,r)=>{let n=["git","-C",t.root,"--literal-pathspecs","status","--",...mp(e)];return zo(t,"fail",`blocked: ${r.length} uncommitted path(s) under synced paths`,[...Oy(r,nA),Rt(n)])},iA=(e,t)=>{if(e.kind==="unknown-sha")return{notes:[],warnings:["no manifest commit recorded, so the source commits since the last sync are unknown"]};let r=ta(e.sha);return e.kind==="unresolvable"?{notes:[],warnings:[`manifest commit ${r} is not in ${t}, so the changelog is unknown`]}:{notes:[`${e.lines.length} ${t} commit(s) since ${r}`,...Oy(e.lines,oA)],warnings:[]}},aA=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},cA=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},lA=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return xn([...n,...r?t.headVendorMeta:[]])},dA=(e,t)=>{if(t.dirty.length>0)return sA(e,t,t.dirty);let r=e.entries.map((l,d)=>{let u=t.entries[d]??{target:l.entry.target,tracked:[],onDisk:{}};return Iy(l,u,e.exclude)}),n=r.some(l=>l.vendored),o=r.some(l=>l.writes.length+l.deletes.length>0),s=n&&(!t.readmeCurrent||!t.manifestPresent),i={...zo(t,"ok","up to date"),branch:t.branch,entries:r,writeVendorMeta:n};if(!o&&!s)return i;let a=iA(t.changelog,e.name),c=r.map(aA).filter(l=>l!==null);return{...i,status:"changed",message:`${cA(r)} on ${t.branch}`,notes:[...c,...s?["vendor/README.md and manifest rewritten"]:[],...a.notes],warnings:a.warnings,recoveryPaths:lA(r,t,n)}},oa=(e,t)=>{switch(t.kind){case"missing":return zo(t,"skipped",`not checked out at ${t.root}`);case"source":return zo(t,"skipped","this is the source repo");case"not-git":return zo(t,"fail",`not a git repo: ${t.reason}`);case"repo":return dA(e,t)}};import{existsSync as pA,readFileSync as uA,realpathSync as sa}from"node:fs";import ia from"node:path";var fp=async(e,t)=>{let r=t.exclude??[],n=(await Z(e,["rev-parse","HEAD"])).trim(),o=await Le(e),s=await Promise.all(Py(t).map(async i=>{let a=await cp(e,i.path,r);return{entry:i,files:a.map(c=>vy(e,c))}}));return{root:e,selfRoots:[...new Set([sa(e),sa(o)])],name:ia.basename(o),headSha:n,entries:s,exclude:r}},aa=e=>{let t=Gt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},mA=async(e,t)=>{let r=await Z(t,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...mp(e)]);return aa(r).filter(n=>!Ho(n,e.exclude))},fA=async(e,t)=>Promise.all(e.entries.map(async({entry:r,files:n})=>{let o=await cp(t,r.target,e.exclude),s={};for(let i of qo(n,e.exclude)){let a=ra(i.path,r);s[a]=ea(ia.join(t,a))}return{target:r.target,tracked:o.map(i=>i.path),onDisk:s}})),gA=async e=>{try{return Gt(await Z(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",Kt,Ko]))}catch{return[]}},hA=e=>{try{return Wo(ia.join(e,X)).commit}catch{return null}},yA=async(e,t)=>{if(t===null)return{kind:"unknown-sha"};if(await $e(e.root,t)===null)return{kind:"unresolvable",sha:t};let r=e.entries.map(({entry:s})=>s.path),o=(await Z(e.root,["--literal-pathspecs","log","--oneline",`${t}..HEAD`,"--",...r])).split(`
|
|
433
|
+
`).filter(s=>s.length>0);return{kind:"log",sha:t,lines:o}},vA=(e,t)=>{try{return uA(ia.join(e,Kt),"utf8")===na(t)}catch{return!1}},wA=async e=>{try{return{toplevel:(await Z(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
|
|
434
|
+
`)[0]??"git rev-parse failed"}}},kA=async e=>{try{return(await Z(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},ca=async(e,t)=>{if(!pA(t.root))return{...t,kind:"missing"};let r=sa(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await wA(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(sa(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=hA(t.root),[s,i,a,c,l]=await Promise.all([kA(t.root),mA(e,t.root),fA(e,t.root),gA(t.root),yA(e,o)]);return{...t,kind:"repo",branch:s,dirty:i,entries:a,headVendorMeta:c,readmeCurrent:vA(t.root,e.name),manifestPresent:o!==null,changelog:l}};var bA=20,RA=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],PA=(e,t)=>{let{plan:r}=e,n=t.manifestOnly?"manifest":"sync";if(e.error!==void 0)return{name:n,status:"fail",message:`apply failed: ${e.error}`,notes:["restore the tracked paths with:",Rt(Tn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:RA(r,t)}},SA=e=>e.ok?{name:"commit",status:"ok",message:"committed the synced paths"}:{name:"commit",status:"fail",message:"git refused the commit; the files stay written",notes:e.output.split(`
|
|
435
|
+
`).slice(0,bA)},EA=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[PA(e,t),...r,...e.commit?[SA(e.commit)]:[]]}},xA={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},gp=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:xA[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>EA(o,r))],hints:n}},Dy=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail"));var TA=20,hp=async(e,t)=>(await Z(e,t,{allowFailure:!0})).trim(),CA=async e=>aa(await Z(e,["status","--porcelain","-z","--untracked-files=normal"])),$A=async e=>(await hp(e,["for-each-ref","--contains","HEAD","--format=%(refname)","refs/remotes/origin/"])).length>0?null:{name:"HEAD pushed",status:"warn",message:"HEAD is on no origin/* ref, so every target will record a commit nobody else can resolve",notes:["git push"]},AA=async e=>{let[t,r]=await Promise.all([hp(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),hp(e,["rev-parse","--abbrev-ref","HEAD"])]);if(t.length===0)return{name:"default branch",status:"warn",message:"origin has no default branch recorded (origin/HEAD)"};let n=t.replace(/^origin\//u,"");return r===n?null:{name:"default branch",status:"warn",message:`syncing from ${r||"a detached HEAD"}, not the origin default branch ${n}`}},Ny=async e=>{let t=await CA(e);if(t.length>0){let n=t.slice(0,TA),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new x({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([$A(e),AA(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import OA from"node:path";var _y=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new x({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=Xs(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>({name:s,root:OA.join(n,s)}))},IA="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",DA=async(e,t)=>{let r=await ca(e,t),n=oa(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${IA} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},My=async(e,t,r)=>Promise.all(t.map(async n=>r?DA(e,n):oa(e,await ca(e,n))));var wp="sync vendored files",NA=()=>{if(Q())throw new x({status:"refused",agentMode:A.source},2,{operation:wp,stderrExcerpt:"vendor sync is human-only: refused in agent mode regardless of --yes",remediation:"ask a human to run `infra-kit vendor sync` from their own shell \u2014 a sync is never confirmed by an agent"})},_A=()=>{if(!vp.stdin.isTTY)throw new x({status:"refused",reason:"no-tty"},2,{operation:wp,stderrExcerpt:"the apply needs a real terminal on stdin",remediation:"run `infra-kit vendor sync --yes` from a real terminal; Claude Code's `!` prefix is not one"})},MA=async()=>{let e=await D({autoMigrate:"off"});if(e.vendorSource)return e.vendorSource;throw new x({status:"refused",reason:"not-a-vendor-source"},1,{operation:wp,stderrExcerpt:"this repo is not a vendor source; `infra-kit vendor sync` runs only in a repo whose infra-kit.json has a vendorSource block",remediation:"run it from the source repo, or point -C at it"})},jy=(e,t)=>{vp.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
|
|
438
436
|
${Rt(t)}
|
|
439
|
-
`)},
|
|
440
|
-
`),$(e)),HA=e=>e.description("List all release branches").action(async()=>{$(await Si())}),qA=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".',GA,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(gl),o=n.length>0?n:void 0;$(await $i({releases:o,confirmedCommand:t.yes}))}),zA=e=>{if(e==="")return e;try{return ur(e)}catch(t){throw t instanceof un?new WA(t.message):t}},YA=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)',zA).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Ai({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),zy=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Jt.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"),XA=e=>zy(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await rp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),ZA=e=>zy(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=>{$(await np({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),QA=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=>{$(await bi({version:t.version,confirmedCommand:t.yes}))}),eO=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=>{$(await Mi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),tO=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await zi({confirmedCommand:t.yes}))}),rO=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=Hy(t.ide,"--ide")??Hy(t.cursor,"--cursor");$(await Ki({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),nO=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await Hi())}),oO=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=>{$(await qi({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),sO=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=>{$(await ip({init:t.init}))}),iO=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ji();$(t),t.structuredContent.ok||(Fe.exitCode=1)}),aO=e=>e.description("Mirror the source repo's vendorSource files into every target in ~/.infra-kit/vendor.json (human-only)").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan (needs a real terminal on stdin)").option("--check","Preview only; exit 1 when any target would change").option("--commit","Commit exactly the synced paths in each target after it syncs").option("--manifest-only","Rewrite vendor/README.md and vendor/.sync-manifest.json only; copy nothing").action(async(t,r)=>{let n;try{n=await wp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!at(a))throw a;p.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),cO=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await Yd())}),lO=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Xd())}),dO=new Set(["version"]),ua=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Pp=()=>{let e=new BA().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");KA(t.command("merge-dev")),HA(t.command("list")),qA(t.command("create")),YA(t.command("edit")),XA(t.command("deploy-all")),ZA(t.command("deploy-selected")),QA(t.command("deliver")),eO(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");rO(r.command("add")),nO(r.command("list")),oO(r.command("remove")),tO(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");cO(n.command("path")),lO(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{$(await As())});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=>{$(await Zi({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=>{$(await Zi({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){p.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await $s({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:d}=c.structuredContent,u=(d??[]).some(m=>m.action==="failed");(!l||u)&&(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return iO(i.command("check")),sO(i.command("config")),aO(i.command("sync")),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 ai({fix:!!a.fix});it.enabled||Rc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Fe.exitCode=1),$(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 (the default)").option("--no-watch","Build once and never restart on 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:l}=await import("./dev-server.js"),d=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,preset:a},d,it.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await Ds())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree\u2019s dev server, else the deployed app at INFRA_KIT_ENV").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{$(await ci({app:c.app,dryRun:c.dryRun,yes:c.yes,playwrightArgs:a}))}),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").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{$(await Fi({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await Ui())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await hi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await pi())}),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=>{qy(await mi({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{qy(await li())}),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)=>{$(await ep({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=>{$(await yi({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=>{$(await Zd({env:a}))}),e.commands.forEach(ru),bp(e),Rp(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&UA(JA(Fe.cwd(),l)),h.start(ua(c)),it.enabled=!!c.optsWithGlobals().json,it.enabled&&(p.level="warn"),A.source=ss({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),dO.has(ua(c))||await Uc()}),e.hook("postAction",(a,c)=>{let l=ua(c);if(Hd(l))return;let u=h.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",g=`infra-kit ${l}${m}`;Uy({equivalent:la(g,!0)})}),e};import pO from"node:process";var uO={exit:pO.exit,emit:$,logger:p},Yy=(e,t=uO)=>we(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof x?(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 Sp=(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 mO from"node:fs";import Xy from"node:path";import zo from"node:process";var ev=new Set([...yu,He,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),tv=null,ma=new Set,Ep=null,Zy=!1;var Qy=e=>{try{return mO.statSync(e)}catch{return null}},fO=()=>{if(Zy)return null;try{return bt()}catch{return Zy=!0,p.debug(`session-env: ${He} unset \u2014 no overlay`),null}},gO=e=>{let t=Xy.join(e,kt),r=Xy.join(e,Xo),n=Qy(t),o=Qy(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"}},hO=e=>e.kind==="load"?{kind:"load",vars:Dp(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Ip(e.file),signature:e.signature}:e;var yO=()=>{let e=fO();if(e===null)return{kind:"no-session"};let t=gO(e);return t.signature===Ep?null:hO(t)},vO=()=>{for(let e of ma){let t=tv[e];t===void 0?delete zo.env[e]:zo.env[e]=t}ma.clear()},wO=(e,t,r)=>{if(ev.has(t)){e.skipped.push(t);return}zo.env[t]=r,ma.add(t),e.set.push(t)},kO=(e,t)=>{if(ev.has(t)){e.skipped.push(t);return}delete zo.env[t],ma.add(t),e.unset.push(t)},bO=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))wO(t,r,n);if(e.kind==="clear")for(let r of e.unset)kO(t,r);return t},RO=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,xp=(e=yO())=>{if(tv??={...zo.env},e===null||e.kind==="no-session"||e.signature===Ep)return{set:[],unset:[],changed:!1};vO();let{set:t,unset:r,skipped:n}=bO(e);return Ep=e.signature,n.length>0&&p.warn(`session-env: skipped protected names [${n.join(", ")}]`),p.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${RO(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as JO}from"chalk";import{spawn as UO}from"node:child_process";import Se from"node:process";import{Chalk as PO}from"chalk";var Tn=new PO({level:1}),Ge={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."},SO={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"}},rv={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},nv={unicode:"\u2500",ascii:"-"},EO=3,Tp=e=>e,xO={ok:e=>Tn.green(e),findings:e=>Tn.yellow(e),failed:e=>Tn.red(e),cancelled:e=>Tn.gray(e)},$p=e=>e?{dim:t=>Tn.dim(t),bold:t=>Tn.bold(t)}:{dim:Tp,bold:Tp},TO=(e,t)=>e?xO[t]:Tp,Cp=e=>[...e].length,CO=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Cp(e)<=r?e:[...e].slice(0,r).join("")},ov=e=>{let t=$p(e.color===!0).dim,r=SO[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(CO(n,e.width))},sv=(e,t={})=>{let r=$p(t.color===!0);return`${r.dim(Ge.reproPrefix.trim())} ${r.bold(e)}`},$O=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,AO=(e,t)=>e==="findings"?t!=null?`${t} ${Ge.findingsSuffix}`:Ge.findingsPlain:{ok:Ge.ok,failed:Ge.failed,cancelled:Ge.cancelled}[e],OO=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<EO?"":` ${n(r.repeat(o))}`},iv=e=>{let t=e.color===!0,r=$p(t),n=TO(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ge.reproPrefix:Ge.nonReproPrefix,i=o?rv[e.outcome].ascii:rv[e.outcome].unicode,a=AO(e.outcome,e.findingsCount),c=[$O(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
441
|
-
`)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,u=`${Ge.sep}${c.join(Ge.sep)}`,m
|
|
442
|
-
`)};var
|
|
443
|
-
`,cv=(e,t)=>{lv(e),e.stdin.on("data",t),e.listener=t},lv=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},dv=(e,t)=>{
|
|
437
|
+
`)},jA=async(e,t,r)=>r?(jy(t,Tn(t)),dp(t.root,e)):(await lp({source:e,plan:t,onBeforeFirstWrite:o=>{jy(t,o)}})).touched,FA=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await jA(e,t,!!r.manifestOnly)}catch(s){return{plan:t,applied:!1,error:s instanceof Error?s.message:String(s)}}if(!r.commit)return{plan:t,applied:!0};let o=await up(t.root,n,pp(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},LA=async(e,t,r)=>{let n=[];for(let o of t)n.push(await FA(e,o,r));return n},Fy=e=>e.map(t=>({name:t.name,root:t.root,status:t.status,message:t.message,notes:t.notes,warnings:t.warnings,branch:t.branch})),yp=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&It(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:Fy(s).map((a,c)=>{let l=r[c];return{...a,applied:l.applied,error:l.error,commit:l.commit}}),changed:s.some(a=>a.status==="changed"),failed:Dy(t),report:t.sections}}},VA=async e=>{let t=await S(),r=await Ny(t),n=await MA(),o=await Zs(),s=_y(o,e.targets??[]),i=await fp(t,n),a=await My(i,s,!!e.manifestOnly);return{source:i,sourceRows:r,plans:a}},kp=async(e={})=>{NA();let{source:t,sourceRows:r,plans:n}=await VA(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=gp(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return yp({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!at.enabled;if(l&&It(a),l&&!vp.stdin.isTTY)return yp({mode:"preview",report:a,outcomes:o,source:t,print:!1});await W(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:Fy(n),throwOnDecline:!0}),_A();let d=await LA(t,n,e),u=gp(r,d,{...s,mode:"applied"});return yp({mode:"applied",report:u,outcomes:d,source:t,print:!0})};var la=(e,t=!0)=>({line:e,reproducible:t});import da from"node:fs";import BA from"node:os";import WA from"node:path";import Wy from"node:process";var pa="INFRA_KIT_SESSION_REPORT",bp=null,Ly=!1,Vy=[],Jy=(e=Wy.env)=>{Ly||(bp=e[pa]??null,Ly=!0,delete e[pa])};var Uy=(e,t)=>{if(!bp)return;let r=e.summary??(Vy.length>0?[...Vy]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{da.writeFileSync(s,i)});try{o(bp,JSON.stringify(n))}catch{}},By=0,Gy=e=>{let t=e?.tmpdir?.()??BA.tmpdir(),r=e?.pid??Wy.pid;return By+=1,WA.join(t,`infra-kit-session-${r}-${By}.json`)},Ky=(e,t)=>{if(!(t?.exists??(i=>da.existsSync(i)))(e))return null;let n=t?.read??(i=>da.readFileSync(i,"utf-8")),o=t?.unlink??(i=>da.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Rp=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(Rp)};var Pp=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Pp)};var HA=(e,t)=>[...t,e],Hy=(e,t)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&br.includes(e))return e;throw new Error(`Invalid ${t} value "${String(e)}". Expected one of: ${br.join(", ")}.`)}},qA=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").option("--keep-conflicts","On the confirmed run, leave each conflicted branch mid-merge in <root>-worktrees/merge-dev/ for resolution").option("--continue","Check, preview, then commit and push the selected resolutions left by --keep-conflicts").option("--abort","Discard the selected resolutions left by --keep-conflicts").option("--tree <branch=sha>","With --continue --yes: the approved tree per branch, as a --continue preview prints it (repeatable)",(t,r)=>[...r??[],t]).action(async t=>{let r=await tf(()=>wi({all:t.all,versions:t.versions,dryRun:t.dryRun,verify:t.verify,keepConflicts:t.keepConflicts,continue:t.continue,abort:t.abort,tree:t.tree,confirmedCommand:t.yes}));$(r),r.structuredContent.failedMerges>0&&(Fe.exitCode=1)}),qy=e=>(Fe.stdout.write(`${e.structuredContent.filePath}
|
|
438
|
+
`),$(e)),zA=e=>e.description("List all release branches").action(async()=>{$(await Ei())}),YA=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".',HA,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(gl),o=n.length>0?n:void 0;$(await Ai({releases:o,confirmedCommand:t.yes}))}),XA=e=>{if(e==="")return e;try{return ur(e)}catch(t){throw t instanceof mn?new UA(t.message):t}},ZA=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)',XA).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Oi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),zy=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Jt.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"),QA=e=>zy(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await rp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),eO=e=>zy(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=>{$(await np({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),tO=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=>{$(await Ri({version:t.version,confirmedCommand:t.yes}))}),rO=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=>{$(await ji({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),nO=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await Yi({confirmedCommand:t.yes}))}),oO=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=Hy(t.ide,"--ide")??Hy(t.cursor,"--cursor");$(await Hi({confirmedCommand:t.yes,all:t.all,versions:t.versions,ide:r,githubDesktop:t.githubDesktop,orca:t.orca}))}),sO=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await qi())}),iO=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=>{$(await zi({confirmedCommand:t.yes,all:t.all,versions:t.versions}))}),aO=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=>{$(await ip({init:t.init}))}),cO=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ui();$(t),t.structuredContent.ok||(Fe.exitCode=1)}),lO=e=>e.description("Mirror the source repo's vendorSource files into every target in ~/.infra-kit/vendor.json (human-only)").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan (needs a real terminal on stdin)").option("--check","Preview only; exit 1 when any target would change").option("--commit","Commit exactly the synced paths in each target after it syncs").option("--manifest-only","Rewrite vendor/README.md and vendor/.sync-manifest.json only; copy nothing").action(async(t,r)=>{let n;try{n=await kp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!ct(a))throw a;p.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),dO=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await Yd())}),pO=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Xd())}),uO=new Set(["version"]),ua=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Sp=()=>{let e=new JA().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");qA(t.command("merge-dev")),zA(t.command("list")),YA(t.command("create")),ZA(t.command("edit")),QA(t.command("deploy-all")),eO(t.command("deploy-selected")),tO(t.command("deliver")),rO(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");oO(r.command("add")),sO(r.command("list")),iO(r.command("remove")),nO(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");dO(n.command("path")),pO(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").action(async()=>{$(await Os())});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=>{$(await Qi({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=>{$(await Qi({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){p.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await As({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:d}=c.structuredContent,u=(d??[]).some(m=>m.action==="failed");(!l||u)&&(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return cO(i.command("check")),aO(i.command("config")),lO(i.command("sync")),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 ci({fix:!!a.fix});at.enabled||Rc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(d=>d.name==="plugin installed"&&d.status==="fail")&&(Fe.exitCode=1),$(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 (the default)").option("--no-watch","Build once and never restart on 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:l}=await import("./dev-server.js"),d=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,preset:a},d,at.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await Ds())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree\u2019s dev server, else the deployed app at INFRA_KIT_ENV").argument("[playwrightArgs...]","Passed to `playwright test` (put them after `--`)").option("--app <name>","App folder whose apps/<app>/tests package to run (inferred from cwd when omitted)").option("--dry-run","Resolve and print the target and proxy topology without running").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{$(await li({app:c.app,dryRun:c.dryRun,yes:c.yes,playwrightArgs:a}))}),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").option("--ascii","Render the report with ASCII markers instead of unicode glyphs (row messages are unchanged)").action(async a=>{$(await Li({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await Gi())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await yi())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await ui())}),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=>{qy(await fi({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{qy(await di())}),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)=>{$(await ep({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=>{$(await vi({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=>{$(await Zd({env:a}))}),e.commands.forEach(nu),Rp(e),Pp(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&KA(GA(Fe.cwd(),l)),h.start(ua(c)),at.enabled=!!c.optsWithGlobals().json,at.enabled&&(p.level="warn"),A.source=is({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),uO.has(ua(c))||await Uc()}),e.hook("postAction",(a,c)=>{let l=ua(c);if(Hd(l))return;let u=h.snapshot()?.formattedOptions??"",m=u?` ${u}`:"",g=`infra-kit ${l}${m}`;Uy({equivalent:la(g,!0)})}),e};import mO from"node:process";var fO={exit:mO.exit,emit:$,logger:p},Yy=(e,t=fO)=>we(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof x?(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 Ep=(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 gO from"node:fs";import Xy from"node:path";import Yo from"node:process";var ev=new Set([...vu,He,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),tv=null,ma=new Set,xp=null,Zy=!1;var Qy=e=>{try{return gO.statSync(e)}catch{return null}},hO=()=>{if(Zy)return null;try{return bt()}catch{return Zy=!0,p.debug(`session-env: ${He} unset \u2014 no overlay`),null}},yO=e=>{let t=Xy.join(e,kt),r=Xy.join(e,Zo),n=Qy(t),o=Qy(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"}},vO=e=>e.kind==="load"?{kind:"load",vars:Dp(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Np(e.file),signature:e.signature}:e;var wO=()=>{let e=hO();if(e===null)return{kind:"no-session"};let t=yO(e);return t.signature===xp?null:vO(t)},kO=()=>{for(let e of ma){let t=tv[e];t===void 0?delete Yo.env[e]:Yo.env[e]=t}ma.clear()},bO=(e,t,r)=>{if(ev.has(t)){e.skipped.push(t);return}Yo.env[t]=r,ma.add(t),e.set.push(t)},RO=(e,t)=>{if(ev.has(t)){e.skipped.push(t);return}delete Yo.env[t],ma.add(t),e.unset.push(t)},PO=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))bO(t,r,n);if(e.kind==="clear")for(let r of e.unset)RO(t,r);return t},SO=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Tp=(e=wO())=>{if(tv??={...Yo.env},e===null||e.kind==="no-session"||e.signature===xp)return{set:[],unset:[],changed:!1};kO();let{set:t,unset:r,skipped:n}=PO(e);return xp=e.signature,n.length>0&&p.warn(`session-env: skipped protected names [${n.join(", ")}]`),p.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${SO(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as GO}from"chalk";import{spawn as KO}from"node:child_process";import Se from"node:process";import{Chalk as EO}from"chalk";var Cn=new EO({level:1}),Ge={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."},xO={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"}},rv={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},nv={unicode:"\u2500",ascii:"-"},TO=3,Cp=e=>e,CO={ok:e=>Cn.green(e),findings:e=>Cn.yellow(e),failed:e=>Cn.red(e),cancelled:e=>Cn.gray(e)},Ap=e=>e?{dim:t=>Cn.dim(t),bold:t=>Cn.bold(t)}:{dim:Cp,bold:Cp},$O=(e,t)=>e?CO[t]:Cp,$p=e=>[...e].length,AO=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return $p(e)<=r?e:[...e].slice(0,r).join("")},ov=e=>{let t=Ap(e.color===!0).dim,r=xO[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(AO(n,e.width))},sv=(e,t={})=>{let r=Ap(t.color===!0);return`${r.dim(Ge.reproPrefix.trim())} ${r.bold(e)}`},OO=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,IO=(e,t)=>e==="findings"?t!=null?`${t} ${Ge.findingsSuffix}`:Ge.findingsPlain:{ok:Ge.ok,failed:Ge.failed,cancelled:Ge.cancelled}[e],DO=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<TO?"":` ${n(r.repeat(o))}`},iv=e=>{let t=e.color===!0,r=Ap(t),n=$O(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?Ge.reproPrefix:Ge.nonReproPrefix,i=o?rv[e.outcome].ascii:rv[e.outcome].unicode,a=IO(e.outcome,e.findingsCount),c=[OO(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
439
|
+
`)[0];l!=null&&l.length>0&&c.push(l);let d=`${i} ${a}`,u=`${Ge.sep}${c.join(Ge.sep)}`,m=$p(d)+$p(u),g=DO(m,e.width,o?nv.ascii:nv.unicode,r.dim),y=[`${n(d)}${r.dim(u)}${g}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(Ge.envNotice)),y.join(`
|
|
440
|
+
`)};var NO=new Set([130,143]),av=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&NO.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import _O from"node:process";var MO={3:"quit",4:"quit",26:"suspend",27:"quit"},jO=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":MO[t]??"continue"},FO=150,LO="\r\x1B[2K",VO=`\r
|
|
441
|
+
`,cv=(e,t)=>{lv(e),e.stdin.on("data",t),e.listener=t},lv=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},dv=(e,t)=>{Au(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),cv(e,t)},pv=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(LO)),lv(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Ou()},BO=e=>{e.settled||(e.settled=!0,pv(e))},uv=(e,t)=>{let r=ov({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},WO=async e=>{await new Promise(t=>{setTimeout(t,e)})},JO=(e,t,r)=>{pv(e),t(),dv(e,r),uv(e,VO)},UO=async e=>new Promise(t=>{let r=n=>{let o=jO(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){JO(e,s,r);return}t("palette")};cv(e,r),uv(e,"")}),mv=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??_O.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return dv(n,()=>{}),e.armed(),await WO(t.drainMs??FO),await UO(n)}finally{BO(n)}};import fv from"node:process";var Ht={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},gv=(e,t)=>{let r=t?.write??(s=>{fv.stderr.write(s)}),n=t?.stdin??fv.stdin,o=[Ht.saveCursor,Ht.scrollRegion,Ht.restoreCursor,Ht.column,Ht.sgr,Ht.cursor,Ht.wrap];e.entersAltScreen===!0&&o.push(Ht.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var hv=e=>`infra-kit ${e.groupPath.join(" ")}`,HO=()=>{qO();let e=Se.stderr.columns;return e!=null&&e>0?e:void 0},qO=()=>{let e=Se.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},zO=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),YO=async(e,t,r)=>{let n=Gy(),o={...t.env,[pa]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let u=t.spawn(Se.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await zO(u)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Ky(n),c=av(i.code,i.signal,a!=null,e.longRunning),l=hv(e),d=a?.equivalent??la(l,!0);return iv({equivalent:d,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(d.reproducible&&d.line===l)})},XO=1e3,ZO=(e,t)=>e!=null&&t-e<=XO,Op=e=>{e.resetTerminal(),e.exit(0)},QO=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Op(t)},s=()=>{let c=e();if(c==="palette"){Op(t);return}if(!ZO(r,t.now())){if(c==="pause"){Op(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}},yv=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),eI=Se.platform==="win32"?void 0:()=>{Iu()},tI=(e,t)=>r=>mv(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:eI}),vv=async(e,t)=>{let r={spawn:t.spawn??KO,now:t.now??(()=>Date.now()),env:t.env??Se.env,cliPath:t.cliPath,ascii:t.ascii??!(Se.stdout.isTTY&&Se.env.TERM!=="dumb"),color:t.color??GO.level>0,columns:t.columns??HO,resetTerminal:t.resetTerminal??(d=>{gv(d)})},n=t.write??(d=>Se.stderr.write(d)),o="palette",s=t.signals??{register:(d,u)=>{Se.on(d,u)},unregister:(d,u)=>{Se.off(d,u)},exit:d=>{Se.exit(d)},raise:d=>{Se.kill(Se.pid,d)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:QO(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??tI(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let d=await t.renderPalette(e);if(d==null)return;let u=t.resolveCommand(d);if(!u)continue;let m=sv(hv(u),{color:r.color});n(`
|
|
444
442
|
${m}
|
|
445
|
-
`),a.childStarted();let g=await
|
|
443
|
+
`),a.childStarted();let g=await YO(u,r,()=>{o="child"});if(n(`
|
|
446
444
|
${g}
|
|
447
|
-
`),await l(c)==="quit")return}}finally{a.dispose()}};zd();Jy();var Rv=
|
|
445
|
+
`),await l(c)==="quit")return}}finally{a.dispose()}};zd();Jy();var Rv=Sp(),kv=async(e=Ee.argv)=>{Tp(),Cu(e);try{await Rv.parseAsync(e)}catch(t){Yy(t)}},iI=()=>{try{if(Ee.env.INFRA_KIT_NO_LOCATION_WARN||Ee.argv.includes("--json"))return;Lp({selfRealPath:oI(bv(import.meta.url)),cwd:Ee.cwd(),env:Ee.env,realpath:he,home:sI(),exists:nI})&&p.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};iI();ru((e,t)=>{p.debug(e,t)});Kc(q.version);var Pv=()=>dy(Rv.commands),aI=async()=>{let e=Pv(),t=null;try{if(Ee.stdout.isTTY&&Ee.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-XLDVLQEG.js");t=await r(e)}else{let r=Ep(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new wv(" "),new wv(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await I(o=>rI({message:"Select a command to run",choices:n},o),{output:Ee.stderr})}}catch(r){if(!we(r))throw r}return t},cI=async()=>{let{runCommandPalette:e}=await import("./boot-XLDVLQEG.js"),t=bv(import.meta.url),r=new Map(fr.map(n=>[n.groupPath.join(" "),n]));await vv(Pv(),{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(Ee.argv.length<=2){let e={stdoutIsTTY:!!Ee.stdout.isTTY,stdinIsTTY:!!Ee.stdin.isTTY,stderrIsTTY:!!Ee.stderr.isTTY};if(yv(Ee.env,e))await cI();else{let t=await aI();t&&await kv(["node","infra-kit",...t.split(" ")])}}else await kv();
|
|
448
446
|
//# sourceMappingURL=cli.js.map
|