infra-kit 0.28.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-MDZSYRGS.js → chunk-AP6XMHE6.js} +2 -2
- package/dist/{chunk-WTS3O3LM.js → chunk-O4RQPFGL.js} +2 -2
- package/dist/{chunk-WTS3O3LM.js.map → chunk-O4RQPFGL.js.map} +1 -1
- package/dist/{chunk-W4CZUPXZ.js → chunk-SNXJBY5K.js} +3 -3
- package/dist/{chunk-QJCOLFRN.js → chunk-UOIGSAK3.js} +2 -2
- package/dist/{chunk-STVQOKMC.js → chunk-VESUSL3H.js} +2 -2
- package/dist/cli.js +130 -125
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +2 -2
- package/dist/{dev-wizard-run-ALE5IJB6.js → dev-wizard-run-2JUUBEQ2.js} +2 -2
- package/dist/{env-load-HNJGRHKJ.js → env-load-6QTE5JS7.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- /package/dist/{chunk-MDZSYRGS.js.map → chunk-AP6XMHE6.js.map} +0 -0
- /package/dist/{chunk-W4CZUPXZ.js.map → chunk-SNXJBY5K.js.map} +0 -0
- /package/dist/{chunk-QJCOLFRN.js.map → chunk-UOIGSAK3.js.map} +0 -0
- /package/dist/{chunk-STVQOKMC.js.map → chunk-VESUSL3H.js.map} +0 -0
- /package/dist/{dev-wizard-run-ALE5IJB6.js.map → dev-wizard-run-2JUUBEQ2.js.map} +0 -0
- /package/dist/{env-load-HNJGRHKJ.js.map → env-load-6QTE5JS7.js.map} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
3
|
-
${i}`:"")},
|
|
2
|
+
import{c as Wm,e as _r,f as Xm,g as $t,h as Ks,i as Zm,j as Qm,k as ef,l as tf,m as rf,n as nf,o as of,p as sf,s as pc,t as lf,u as Se}from"./chunk-UOIGSAK3.js";import{a as Xp,b as De,c as Zp,d as Xa,e as Qp,f as em,g as tm,h as rm,i as Un,j as nm,k as om,l as sm,m as im,n as am,o as Vn,p as cm,q as lm,r as um,s as dm,t as Za,u as _s,v as Et,w as pm,x as Ms,y as mm}from"./chunk-XES5EOEE.js";import{a as ie,b as J,c as Tt,d as Jn,e as nc,f as Vs,g as Ws,h as oc,i as Kn,j as Zt,k as sc,l as Gs,m as jm,n as Hn,o as qn,p as ac,q as cc,r as lc,s as Km,u as uc}from"./chunk-7A4LVTRJ.js";import{b as Bn,c as Is,d as za,e as Kp,f as Ns,g as Hp,i as qp,k as Yp,m as we,o as zp}from"./chunk-AWFGP6GY.js";import{a as Vm}from"./chunk-TVG47UHG.js";import{B as zn,D as fc,H as gc,I as hc,a as R,b as C,c as Hm,d as qm,e as Qt,f as Ym,g as er,h as zm,i as dc,j as af,k as Yn,l as At,m as Mr,n as ze,o as Hs,p as Ot,q as cf,r as qs,s as uf,t as df,u as Xe,y as mc}from"./chunk-SNXJBY5K.js";import{a as v,b as mt,c as Fm,d as Lm,e as N,f as Js,g as U,i as Ct,j as Je,k as Gm,l as ic,m as Jm}from"./chunk-VESUSL3H.js";import{$ as Nm,A as km,B as bm,C as Rm,D as Ls,E as Bs,F as Ie,G as Wn,H as Nr,I as Us,J as Sm,K as Em,L as Pm,M as ec,N as tc,O as xm,P as d,Q as Ne,R as ee,S as k,T as Ge,U as Tm,V as Cm,W as $m,X as Om,Y as Dm,Z as Im,_ as Pt,a as Xt,aa as rc,b as O,ba as _m,c as fm,ca as Mm,d as _,da as z,e as pe,ea as G,f as q,fa as Gn,g as js,ga as xt,h as gm,ha as A,i as g,j as hm,k as Fs,l as Y,m as ge,n as ke,o as ym,p as Qa,q as se,r as Q,s as Dr,t as vm,u as Ye,v as he,w as $,x as Re,y as Ir,z as wm}from"./chunk-AP6XMHE6.js";import{a as Am}from"./chunk-MFAFQVTW.js";import{a as B}from"./chunk-O4RQPFGL.js";import{a as Cr,b as Ts,c as Cs,d as Ln,e as Up,f as $r,g as $s,h as As,i as Vp,j as Os,k as Ds,l as Wp,m as Gp,n as pt,o as Ar,p as St,q as de,r as Jp,s as Or}from"./chunk-I23MDR4X.js";import{a as Bm,b as Um}from"./chunk-QWVLAZ6N.js";import cj,{Separator as Kk}from"@inquirer/select";import{existsSync as lj,realpathSync as uj}from"node:fs";import{homedir as dj}from"node:os";import Oe from"node:process";import{fileURLToPath as qk}from"node:url";import rg from"node:process";import{z as je}from"zod";import kf from"node:fs";import Fr from"node:path";import{packageConfigSchema as ff}from"@slip-stream-kit/config/internal";import gf from"node:fs/promises";import Ys from"node:path";import{pathToFileURL as nb}from"node:url";import{z as hf}from"zod";import pf from"node:path";var Xn=["frontend","backend","lib","e2e","mobile"],Xk={ui:"frontend",api:"backend",tests:"e2e"},Zk="mobile-app",Qk=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],eb=(e,t)=>{let r=pf.relative(t,e).split(pf.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=Xk[o];if(s)return s}return r.at(-1)===Zk?"mobile":null},tb=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of Qk)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},Zn=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??eb(e,t)??tb(r)??"lib";var Dt={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},mf=2e3,yc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${mf}} 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"},Qn={requiredScripts:["build","test","qa","infra-kit-check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","infra-kit-check"]},eo=(e,t=Dt)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import rb from"node:fs/promises";var Ee=async e=>{try{return await rb.access(e),!0}catch{return!1}};var ae="infra-kit.config.ts",tr=async e=>{try{let t=await gf.readFile(Ys.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},vc=async e=>{let t=await gf.stat(e),o=(await import(`${nb(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ae} at ${e} has no default export`);return typeof o=="function"?await o():o},rr=async e=>{let t=Ys.join(e,ae);if(await Ee(t))try{let n=(await vc(t))?.type;return Xn.find(o=>o===n)}catch{return}},yf=e=>e,to=async(e,t=Dt)=>{let r=Ys.join(e,ae);if(!await Ee(r))throw new Error(`${ae} not found at ${r}`);let n=await vc(r),o=ff.safeParse(n);if(!o.success)throw new Error(`Invalid ${ae} at ${r}: ${hf.prettifyError(o.error)}`);return eo(yf(o.data),t)},It=async e=>{let t=Ys.join(e,ae);if(!await Ee(t))return;let r=ff.safeParse(await vc(t));if(!r.success)throw new Error(`Invalid ${ae} at ${t}: ${hf.prettifyError(r.error)}`);return yf(r.data)};import vf from"node:fs/promises";import zs from"node:path";import ob from"yaml";var sb="pnpm-workspace.yaml",ib=async e=>(await vf.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>zs.join(e,r.name)),ab=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await ib(n));continue}let o=zs.join(n,t);await Ee(o)&&r.push(o)}return r},cb=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await ab(r,n);return r},Pe=async e=>{let t=await vf.readFile(zs.join(e,sb),"utf-8"),n=((ob.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await cb(e,s);for(let a of i)await Ee(zs.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import ro from"node:path";var no=async e=>{let t=ro.resolve(e);for(;t!==ro.dirname(t);){if(await Ee(ro.join(t,"package.json")))return t;t=ro.dirname(t)}if(await Ee(ro.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},Nt=(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}`:"")},wc=(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},wf=(e,t,r)=>`${e}
|
|
4
4
|
${t}
|
|
5
|
-
${r}`,
|
|
5
|
+
${r}`,jr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=wf(r,t,n),i=Ze(e,r,n);if(o==="replace-in-place"&&i){let l=e.indexOf(r),u=e.indexOf(n)+n.length;return e.slice(0,l)+s+e.slice(u)}let c=(i?Nt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
6
6
|
${s}
|
|
7
7
|
`:`${s}
|
|
8
|
-
`};var _e="<!-- infra-kit:begin -->",Qe="<!-- infra-kit:end -->",
|
|
8
|
+
`};var _e="<!-- infra-kit:begin -->",Qe="<!-- infra-kit:end -->",kc="<!-- infra-kit:version ",et="<!-- infra-kit:package:begin -->",ft="<!-- infra-kit:package:end -->",nr="<!-- infra-kit:package:version ";var lb=e=>{let t=e.indexOf(et)+et.length;return e.slice(t,e.indexOf(ft))},ub=e=>{let t=e.indexOf(nr);if(t===-1)return null;let r=e.slice(t+nr.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Xn.find(n=>n===r)??null},or=e=>{if(e===null)return{state:"missing"};if(!Ze(e,et,ft))return e.includes(et)||e.includes(ft)?{state:"malformed"}:Ze(e,_e,Qe)?{state:"foreign-block"}:{state:"no-block"};let t=lb(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=wc(t,nr),o=ub(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import db from"node:fs";var sr=e=>{try{return db.readFileSync(e,"utf-8")}catch{return null}};var bf="pnpm-workspace.yaml",pb="CLAUDE.md",Rc=e=>{let t=Fr.resolve(e);for(;t!==Fr.dirname(t);){if(kf.existsSync(Fr.join(t,bf)))return t;t=Fr.dirname(t)}return kf.existsSync(Fr.join(t,bf))?t:null},bc=new Map,Xs=()=>{bc.clear()},mb=async e=>{let t;try{t=await Pe(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Fr.join(r,pb),o=sr(n);if(o!==null&&or(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Lr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=bc.get(e);if(t)return t;let r=await mb(e);return bc.set(e,r),r};import ir from"node:fs";import _t from"node:path";var Rf=`---
|
|
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 Sf=`# {{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 Ef="# {{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- {{checksBullet}}\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- HTTP Basic Auth credentials are `E2E__BASIC_AUTH_USERNAME` / `E2E__BASIC_AUTH_PASSWORD` (double underscore) in every suite \u2014 the names the dev proxy injects and the shared CI job exports. Pass them to `use.httpCredentials`; never invent a per-app name (`E2E_CLIENT_BASIC_AUTH_*`) or fall back to one. `infra-kit audit` fails the package otherwise.\n- Every spec cleans up what it creates, in teardown.\n- Selectors live in Page Objects, never inline in specs.\n- `playwright.config.ts` takes `baseURL`, `ignoreHTTPSErrors` and `webServer` from `infraKitE2e()` (`@slip-stream-kit/config/playwright`). Every run is local by default \u2014 this worktree's dev server, reused or started for the run \u2014 and cloud only with `INFRA_KIT_E2E=cloud` (`infra-kit e2e --cloud`) or on CI, against the URL the loaded env holds in the target app's `deployedUrlEnv` (`ik env-load -c <env>`). Read the base URL from Playwright's `baseURL`, never from that variable: locally it still holds the deployed URL. The one exception is a suite that must run against a production build it serves itself: it declares `e2e: { server: 'static' }` in `infra-kit.config.ts` and sets `baseURL` and `webServer` itself.\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 once a person approves (see Repair).\n\nLint enforces the mechanical part: `@wl/e2e-file-layout` the Structure folders and the `.spec.ts` suffix, `@wl/e2e-file-order` imports first and then the class, the `extend` call, the `test.*` calls, the mock function or a `lib/` file's exports \u2014 constants and helpers below, `@wl/e2e-page-object-member-order` fields \u2192 constructor \u2192 getters \u2192 public \u2192 private methods, `@wl/e2e-top-level-describe` one top-level describe holding the setup, hooks and tests, `@wl/e2e-describe-order` setup \u2192 hooks \u2192 tests inside it, `@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\n## Repair\n\nFor a failing spec, before editing anything:\n\n- Classify the failure: product defect, intentional product change, test defect, test data or environment, or flake. Say which, and why, in the change.\n- Diagnose from `infra-kit e2e --json`: read `failures[]` (title, `file:line`, error) and open its `tracePath` with `pnpm exec playwright show-trace`, rather than reading the full log. Re-run one test with `infra-kit e2e --json -- <spec> --grep \"<title>\"`.\n- Never take the expected behaviour from what the UI shows now. It comes from the spec's intent, the ticket, or a person; when it is unclear, stop and report instead of editing.\n- Never without a person's explicit approval: delete or weaken an assertion, add `test.skip` / `test.fixme` / `test.fail`, update a snapshot or visual baseline, widen a timeout, or add retries. A product defect is reported, not tested around.\n";var Pf="# {{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- {{checksBullet}}\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- A loaded env var that breaks local dev \u2014 one meant for another build mode, e.g. a mobile-only absolute origin that bypasses the proxy \u2014 goes in `dev.env.unset` (or `dev.env.set` to override it) in `infra-kit.config.ts`. Never remove it from Doppler or patch it out in `vite.config.ts`.\n- Use the tokens in `DESIGN.md` rather than ad-hoc colors, spacing, or type scales.\n";var xf=`# {{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.
|
|
@@ -116,7 +116,7 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
116
116
|
- {{surfaceBullet}}
|
|
117
117
|
- {{buildBullet}}
|
|
118
118
|
- No app-specific logic belongs here.
|
|
119
|
-
`;var
|
|
119
|
+
`;var Tf=`# {{packageName}}
|
|
120
120
|
|
|
121
121
|
Workspace package at \`{{relDir}}\` \u2014 type: **{{type}}**.
|
|
122
122
|
This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_ the markers, never inside.
|
|
@@ -138,42 +138,42 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
138
138
|
- The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
|
|
139
139
|
- The web build feeds the native shell, so a device run needs a rebuild first.
|
|
140
140
|
- Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
|
|
141
|
-
`;var
|
|
142
|
-
`)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},
|
|
143
|
-
`),t);return
|
|
144
|
-
`).replace(
|
|
145
|
-
`};var
|
|
146
|
-
`)};var
|
|
147
|
-
`)};import Lr from"node:fs";import ab from"node:path";var Ws=e=>{let t;try{t=Lr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Zn=(e,t)=>{let r=Qn(e,t);return r!=="unchanged"&&(Lr.mkdirSync(ab.dirname(e),{recursive:!0}),Lr.writeFileSync(e,t,"utf-8")),r},Qn=(e,t)=>{Ws(e);let r=Lr.existsSync(e)?Lr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},pc=(e,t,r)=>{let n=Lr.readFileSync(e,"utf-8");if(!Ze(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},df=(e,t,r)=>Ze(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,mc=(e,t,r,n)=>{let o=df(e,r,n),s=df(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 Js="<!-- infra-kit:import:begin -->",Ks="<!-- infra-kit:import:end -->",cb="AGENTS.md",pf="CLAUDE.md",lb="README.md",fc="DESIGN.md",ub=["frontend","mobile"],db=e=>sr.existsSync(e)?sr.readFileSync(e,"utf-8"):null,gc=(e,t)=>{try{return sr.readdirSync(e).includes(t)}catch{return!1}},Gs=(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},mf=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=db(e),a=i===null?"":o?.(i)??i,c=Nr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return Qn(e,c);let l=Zn(e,c);return pc(e,r,n),i!==null&&mc(a,c,r,n),l},pb=(e,t)=>{if(!sr.existsSync(e))return"unchanged";Ws(e);let r=sr.readFileSync(e,"utf-8"),n=Dt(r,_e,Qe);return n===null?"unchanged":n.trim()===""?(t||sr.rmSync(e),"removed"):t?Qn(e,n):Zn(e,n)},mb=(e,t,r)=>mf({filePath:e,dryRun:r,body:dc(t),startMarker:_e,endMarker:Qe,prepare:n=>Dt(n,Js,Ks)??n}),eo=async(e,{version:t,dryRun:r=!1})=>{let n=Nt.join(e,pf),o=Nt.join(e,cb),s=[];try{s.push({path:n,action:mb(n,t,r)})}catch(i){s.push(Gs(n,i))}try{s.push({path:o,action:pb(o,r)})}catch(i){s.push(Gs(o,i))}return s},fb=(e,t,r,n)=>{if(!ub.includes(r)||gc(e,fc))return null;let o=Nt.join(e,fc),s=cc(t);try{return{path:o,action:n?Qn(o,s):Zn(o,s),type:r}}catch(i){return Gs(o,i,r)}},to=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Nt.join(e,pf),a=await er(e),c=a.name??Nt.basename(e),l=Kn({packageDir:e,repoRoot:t,pkgJson:a,declaredType:o}),u=uc({version:r,type:l,packageName:c,relDir:Nt.relative(t,e).split(Nt.sep).join("/"),hasReadme:gc(e,lb),hasDesign:gc(e,fc),hasE2eDoc:sr.existsSync(Nt.join(t,lc)),scripts:Object.keys(a.scripts??{}),hasPublicSurface:a.exports!==void 0||a.bin!==void 0}),p=[];try{p.push({path:i,action:mf({filePath:i,body:u,startMarker:et,endMarker:mt,dryRun:s}),type:l})}catch(m){p.push(Gs(i,m,l))}if(n){let m=fb(e,c,l,s);m&&p.push(m)}return p};import Mb from"node:path";import ff from"node:path";var hc="agent-guidance",ro="CLAUDE.md",gb="\u2014 run: infra-kit audit --fix",hb={missing:`${ro} missing`,"no-block":`${ro} has no infra-kit block (expected ${et} \u2026 ${mt})`,malformed:`${ro} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${ro} carries the ROOT infra-kit block (${_e}); a package needs the package block`},yb=e=>e.adopted?` (workspace adopted: ${ff.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",yc=(e,t)=>{let r=nr(or(ff.join(e,ro)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:hc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${hb[r.state]} ${gb}`,o=r.state==="missing"?`${n}${yb(t)}`:n;return t.adopted?{name:hc,status:"fail",message:o}:{name:hc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import vb from"node:path";var vc=async(e,t=Ot)=>{try{let r=await Yn(e,t);return{check:{name:se,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:se,status:"fail",message:r.message},rules:null}}},gf="infra-kit.json",wb=async e=>await Ee(vb.join(e,se))?{name:se,status:"fail",message:'retired at the repo root \u2014 root audit rules live in infra-kit.json "audit". Run `infra-kit audit --fix --root` to move them and delete the file'}:null,wc=async(e,t=Hn)=>{let r=await wb(e),n=r?[r]:[];try{let{audit:o={}}=await W();return{checks:[{name:gf,status:"pass",message:"present and valid"},...n],rules:qn(o,t)}}catch(o){return{checks:[{name:gf,status:"fail",message:o.message},...n],rules:null}}};import Hs from"node:fs/promises";import Br from"node:path";import{$ as kb}from"zx";var no="playwright.config.ts",bb=[{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'"},{name:"infra-kit-e2e",pattern:/\binfraKitE2e\b/u,expected:"baseURL, ignoreHTTPSErrors and webServer from infraKitE2e() ('@slip-stream-kit/config/playwright')"}],hf=e=>Object.entries(tc).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"}}),Rb="infra-kit-e2e",yf=async(e,t={})=>{let r=Br.join(e,no),n=await Hs.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${no}`,status:"fail",message:`missing ${no}`}]:bb.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===Rb?{name:s,status:"pass",message:"not required \u2014 e2e.server is 'static', the suite serves its own build"}:o.pattern.test(n)?{name:s,status:"pass",message:"present"}:{name:s,status:"fail",message:`${no} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},Sb=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,Eb=/\.[cm]?[jt]sx?$/u,kc=async(e,t)=>(await Hs.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&Eb.test(n.name)).map(n=>Br.join(n.parentPath,n.name)),Pb=async e=>{let t=await kc(Br.join(e,"src"),!0);for(let r of[Br.join(e,no),...t]){let n=await Hs.readFile(r,"utf-8").catch(()=>"");if(Sb.test(n))return!0}return!1},vf=async e=>{let t="e2e-auth:gitignored";if(!await Pb(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await kb({cwd:e,quiet:!0,nothrow:!0})`git -c core.excludesFile=/dev/null check-ignore -q .auth/storage-state.json`;if(r.exitCode===0)return{name:t,status:"pass",message:".auth/ is gitignored"};if(r.exitCode===1)return{name:t,status:"fail",message:"the suite saves auth state under .auth/, which git would commit \u2014 add `.auth/` to .gitignore"};let n=r.stderr.trim()||`exit ${r.exitCode}`;return{name:t,status:"fail",message:`could not ask git whether .auth/ is ignored: ${n}`}},bc="E2E__BASIC_AUTH_USERNAME",Rc="E2E__BASIC_AUTH_PASSWORD",xb=/\bE2E_\w*BASIC_AUTH_\w+/gu,Tb=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,Cb=/\/\*[\s\S]*?\*\//gu,$b=/(^|[^:])\/\/[^\n]*/gu,Ab=e=>/USER(?:NAME)?$/u.test(e)?bc:Rc,Ob=e=>e.replace(Cb,"").replace($b,"$1"),wf=async e=>{let t="e2e-env:basic-auth",r=[...await kc(e,!1),...await kc(Br.join(e,"src"),!0)],n=[];for(let o of r){let s=await Hs.readFile(o,"utf-8").catch(()=>""),i=new Set([...Ob(s).matchAll(xb)].map(a=>a[0]).filter(a=>Tb.test(a)&&a!==bc&&a!==Rc));for(let a of i)n.push(`${a} \u2192 ${Ab(a)} (${Br.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${bc} / ${Rc}`}:{name:t,status:"fail",message:`basic auth has one name pair in every suite \u2014 rename, with no fallback to the old name: ${n.join("; ")}`}},Sc=async(e,t,r={})=>[...hf(t),...await yf(e,r),await vf(e),await wf(e)];import Ib from"node:fs/promises";import Db from"node:path";var Ec=async(e,t)=>Promise.all(t.map(async r=>{let n=await Ib.stat(Db.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 Pc=(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 Nb from"node:fs/promises";import _b from"node:path";var Ur="turbo.json",xc=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await Nb.readFile(_b.join(e,Ur),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Ur,status:"fail",message:`cannot read/parse ${Ur}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Ur,status:"fail",message:`no "tasks" object defined in ${Ur}`}]: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 ${Ur}`}})};var jb=async(e,t)=>{let{check:r,rules:n}=await vc(e,t);return{checks:[r],rules:n}},Fb={adopted:!1,workspaceRoot:null},Lb=async(e,t,r)=>Kn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await tr(e)}),Bb=async e=>(await It(e).catch(()=>{}))?.e2e?.server==="static",Tc=async(e,t=Ot,r={})=>{let n=await er(e),o=n.name??Mb.basename(e),{checks:s,rules:i}=r.isRoot?await wc(e,t):await jb(e,t);r.isRoot||s.push(yc(e,r.adoption??Fb)),i&&(s.push(...Pc(n.scripts??{},i.requiredScripts)),s.push(...await Ec(e,i.requiredFiles)),s.push(...await xc(e,i.turboTasks))),!r.isRoot&&await Lb(e,n,r.repoRoot)==="e2e"&&s.push(...await Sc(e,n.scripts??{},{staticServer:await Bb(e)}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var Cc=["plugin","marketplace","add",xt],$c=["plugin","install",G,"--scope","project"],kf=(e,t)=>Xt({projectPath:e,home:t}).kind==="installed",qs=e=>((e??"").split(`
|
|
148
|
-
`).find(r=>r.trim().length>0)??"").trim(),
|
|
149
|
-
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${
|
|
141
|
+
`;var Cf="# 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` = `infra-kit`, the global CLI)\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. Without `-c`, an agent loads the project's `defaultEnv` (set yours with `ik config-set defaultEnv <env>`); with none set it is refused and must ask the human.\n- `ik dev [app]` / `ik dev-status` \u2014 run this worktree's dev servers, or report what is running. An app (`ik dev client`) runs its api and ui plus every backend its proxy routes can run locally; no name runs every app. App names are per-repo: an unknown one is refused with the apps as choices, never guess one.\n- `ik e2e [--app <app>]` \u2014 run an app's Playwright suite locally: against this worktree's dev server when it runs, otherwise the package's `infraKitE2e()` Playwright config starts `ik dev <app> --reuse` for the run and stops it after. Plain `playwright test` / `pnpm e2e-test` behave the same way. `--cloud` runs against the deployed app instead \u2014 the URL the loaded env (`ik env-load -c <env>`) holds in the target app's `deployedUrlEnv` \u2014 previews, and needs `--yes`; `--dry-run` prints the target.\n- `ik worktrees add` / `worktrees list` / `worktrees remove` / `worktrees sync` \u2014 manage release and feature git worktrees. `ik worktrees add --feature <name> [--base <dev|main|release>]` creates `feature/<name>` at `<root>-worktrees/feature/<name>`, cut from `dev` by default (the default branch in a repo without `dev`); `worktrees remove --feature <name>` removes it. To close the worktree a session runs in (\"close this worktree\"), run `infra-kit worktrees remove --self` from inside it: it previews, and its `--yes` re-run hands the removal to an Orca tab of the main checkout, which closes every tab of the worktree \u2014 this session included. The `/infra-kit:worktrees` skill is the agent entry point for feature worktrees \u2014 never create one with raw `git worktree add` or Claude Code's `EnterWorktree`, which skip `pnpm install`, the editor/Orca wiring and the `feature/` layout.\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 their `infra-kit.config.ts` rules (`--root`: the repo root against the `audit` block in `infra-kit.json`).\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- Config is split by level: repo-wide settings live in the root `infra-kit.json` (personal overrides in `~/.infra-kit/`), per-package settings in that package's `infra-kit.config.ts`. The root has no `infra-kit.config.ts`.\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`. 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`, `vendor sync`) previews its plan and exits without acting; re-run the same argv with `--yes` to execute. Never put a mutating command behind a prefix allow \u2014 that makes the `--yes` re-run unprompted (`ik doctor` warns on such a pattern).\n- `env-load`, `env-clear` and `infra-kit setup` have no confirm step and run once: the host's prompt on the argv is the approval. `release deliver` is human-only and is refused under agent mode.\n- A command that needs a human choice returns a structured `argument_required` refusal naming the option; pass the value instead of retrying.\n\n## Writing code\n\n- Comment the **why**, never the **what**. If a comment would only restate what the code already says (a name, a type, an obvious assignment), delete it \u2014 and if code needs a comment to be _understood_, prefer renaming/refactoring until it reads on its own. Reserve comments for the genuinely non-obvious: external quirks, ordering constraints, fail-safe branches, workarounds, business-logic definitions. Keep them compact. When a comment explains a bug, outage, or upstream issue, link the source of truth instead of describing it.\n- 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 Br={"root/body":Cf.trimEnd(),"package/frontend":Pf.trimEnd(),"package/backend":Sf.trimEnd(),"package/lib":xf.trimEnd(),"package/e2e":Ef.trimEnd(),"package/mobile":Tf.trimEnd(),"design/skeleton":Rf.trimEnd()};var Sc=/\{\{(\w+)\}\}/g,bb=/^- \{\{(\w+)\}\}$/,Rb=e=>new Set([...e.matchAll(Sc)].map(t=>t[1])),Sb=(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(", ")}`)},Eb=(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(", ")}`)},Pb=(e,t)=>e.filter(r=>{let n=bb.exec(r);return n===null||t[n[1]]!==""}),xb=(e,t)=>{for(let r of e)for(let n of r.matchAll(Sc)){let o=t[n[1]];if(o!==void 0&&o.includes(`
|
|
142
|
+
`)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},Ur=(e,t)=>{let r=Rb(e);Eb(r,t),Sb(r,t);let n=Pb(e.split(`
|
|
143
|
+
`),t);return xb(n,t),n.join(`
|
|
144
|
+
`).replace(Sc,(o,s)=>t[s])};var Tb="name: TODO",Ec=e=>{let t=Ur(Br["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(Tb,()=>r)}
|
|
145
|
+
`};var Cb=(e,t)=>`${nr}${e} ${t} -->`,$b="`README.md` \u2014 what this package is and how to run it.",Pc="docs/e2e-playwright.md",Ab=`\`${Pc}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,Ob=["ts-check","eslint-check","test"],Db="The public surface is what `package.json` exposes \u2014 its `exports` map, or `bin` for a CLI; changing it is a breaking change for every dependent package.",Ib="Run `pnpm run build` before a dependent package can see a change.",$f=(e,t)=>e?.includes(t)??!0,Nb=e=>{let t=Ob.filter(r=>$f(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},xc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=Ur(Br[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?$b:"",checksBullet:Nb(a),...r==="e2e"?{e2eDocBullet:i?Ab:""}:{},...r==="lib"?{surfaceBullet:c?Db:"",buildBullet:$f(a,"build")?Ib:""}:{}});return[Cb(t,r),"",l,""].join(`
|
|
146
|
+
`)};var _b=e=>`${kc}${e} -->`,Tc=e=>{let t=Ur(Br["root/body"],{});return[_b(e),"",t,""].join(`
|
|
147
|
+
`)};import Vr from"node:fs";import Mb from"node:path";var Zs=e=>{let t;try{t=Vr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},oo=(e,t)=>{let r=so(e,t);return r!=="unchanged"&&(Vr.mkdirSync(Mb.dirname(e),{recursive:!0}),Vr.writeFileSync(e,t,"utf-8")),r},so=(e,t)=>{Zs(e);let r=Vr.existsSync(e)?Vr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Cc=(e,t,r)=>{let n=Vr.readFileSync(e,"utf-8");if(!Ze(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Af=(e,t,r)=>Ze(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,$c=(e,t,r,n)=>{let o=Af(e,r,n),s=Af(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 ei="<!-- infra-kit:import:begin -->",ti="<!-- infra-kit:import:end -->",jb="AGENTS.md",Of="CLAUDE.md",Fb="README.md",Ac="DESIGN.md",Lb=["frontend","mobile"],Bb=e=>ir.existsSync(e)?ir.readFileSync(e,"utf-8"):null,Oc=(e,t)=>{try{return ir.readdirSync(e).includes(t)}catch{return!1}},Qs=(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},Df=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=Bb(e),a=i===null?"":o?.(i)??i,c=jr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return so(e,c);let l=oo(e,c);return Cc(e,r,n),i!==null&&$c(a,c,r,n),l},Ub=(e,t)=>{if(!ir.existsSync(e))return"unchanged";Zs(e);let r=ir.readFileSync(e,"utf-8"),n=Nt(r,_e,Qe);return n===null?"unchanged":n.trim()===""?(t||ir.rmSync(e),"removed"):t?so(e,n):oo(e,n)},Vb=(e,t,r)=>Df({filePath:e,dryRun:r,body:Tc(t),startMarker:_e,endMarker:Qe,prepare:n=>Nt(n,ei,ti)??n}),io=async(e,{version:t,dryRun:r=!1})=>{let n=_t.join(e,Of),o=_t.join(e,jb),s=[];try{s.push({path:n,action:Vb(n,t,r)})}catch(i){s.push(Qs(n,i))}try{s.push({path:o,action:Ub(o,r)})}catch(i){s.push(Qs(o,i))}return s},Wb=(e,t,r,n)=>{if(!Lb.includes(r)||Oc(e,Ac))return null;let o=_t.join(e,Ac),s=Ec(t);try{return{path:o,action:n?so(o,s):oo(o,s),type:r}}catch(i){return Qs(o,i,r)}},ao=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=_t.join(e,Of),a=await tr(e),c=a.name??_t.basename(e),l=Zn({packageDir:e,repoRoot:t,pkgJson:a,declaredType:o}),u=xc({version:r,type:l,packageName:c,relDir:_t.relative(t,e).split(_t.sep).join("/"),hasReadme:Oc(e,Fb),hasDesign:Oc(e,Ac),hasE2eDoc:ir.existsSync(_t.join(t,Pc)),scripts:Object.keys(a.scripts??{}),hasPublicSurface:a.exports!==void 0||a.bin!==void 0}),p=[];try{p.push({path:i,action:Df({filePath:i,body:u,startMarker:et,endMarker:ft,dryRun:s}),type:l})}catch(m){p.push(Qs(i,m,l))}if(n){let m=Wb(e,c,l,s);m&&p.push(m)}return p};import dR from"node:path";import If from"node:path";var Dc="agent-guidance",co="CLAUDE.md",Gb="\u2014 run: infra-kit audit --fix",Jb={missing:`${co} missing`,"no-block":`${co} has no infra-kit block (expected ${et} \u2026 ${ft})`,malformed:`${co} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${co} carries the ROOT infra-kit block (${_e}); a package needs the package block`},Kb=e=>e.adopted?` (workspace adopted: ${If.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Ic=(e,t)=>{let r=or(sr(If.join(e,co)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Dc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${Jb[r.state]} ${Gb}`,o=r.state==="missing"?`${n}${Kb(t)}`:n;return t.adopted?{name:Dc,status:"fail",message:o}:{name:Dc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import Hb from"node:path";var Nc=async(e,t=Dt)=>{try{let r=await to(e,t);return{check:{name:ae,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ae,status:"fail",message:r.message},rules:null}}},Nf="infra-kit.json",qb=async e=>await Ee(Hb.join(e,ae))?{name:ae,status:"fail",message:'retired at the repo root \u2014 root audit rules live in infra-kit.json "audit". Run `infra-kit audit --fix --root` to move them and delete the file'}:null,_c=async(e,t=Qn)=>{let r=await qb(e),n=r?[r]:[];try{let{audit:o={}}=await G();return{checks:[{name:Nf,status:"pass",message:"present and valid"},...n],rules:eo(o,t)}}catch(o){return{checks:[{name:Nf,status:"fail",message:o.message},...n],rules:null}}};import ri from"node:fs/promises";import Wr from"node:path";import{$ as Yb}from"zx";var lo="playwright.config.ts",zb=[{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'"},{name:"infra-kit-e2e",pattern:/\binfraKitE2e\b/u,expected:"baseURL, ignoreHTTPSErrors and webServer from infraKitE2e() ('@slip-stream-kit/config/playwright')"}],_f=e=>Object.entries(yc).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"}}),Xb="infra-kit-e2e",Mf=async(e,t={})=>{let r=Wr.join(e,lo),n=await ri.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${lo}`,status:"fail",message:`missing ${lo}`}]:zb.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===Xb?{name:s,status:"pass",message:"not required \u2014 e2e.server is 'static', the suite serves its own build"}:o.pattern.test(n)?{name:s,status:"pass",message:"present"}:{name:s,status:"fail",message:`${lo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},Zb=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,Qb=/\.[cm]?[jt]sx?$/u,Mc=async(e,t)=>(await ri.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&Qb.test(n.name)).map(n=>Wr.join(n.parentPath,n.name)),eR=async e=>{let t=await Mc(Wr.join(e,"src"),!0);for(let r of[Wr.join(e,lo),...t]){let n=await ri.readFile(r,"utf-8").catch(()=>"");if(Zb.test(n))return!0}return!1},jf=async e=>{let t="e2e-auth:gitignored";if(!await eR(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await Yb({cwd:e,quiet:!0,nothrow:!0})`git -c core.excludesFile=/dev/null check-ignore -q .auth/storage-state.json`;if(r.exitCode===0)return{name:t,status:"pass",message:".auth/ is gitignored"};if(r.exitCode===1)return{name:t,status:"fail",message:"the suite saves auth state under .auth/, which git would commit \u2014 add `.auth/` to .gitignore"};let n=r.stderr.trim()||`exit ${r.exitCode}`;return{name:t,status:"fail",message:`could not ask git whether .auth/ is ignored: ${n}`}},jc="E2E__BASIC_AUTH_USERNAME",Fc="E2E__BASIC_AUTH_PASSWORD",tR=/\bE2E_\w*BASIC_AUTH_\w+/gu,rR=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,nR=/\/\*[\s\S]*?\*\//gu,oR=/(^|[^:])\/\/[^\n]*/gu,sR=e=>/USER(?:NAME)?$/u.test(e)?jc:Fc,iR=e=>e.replace(nR,"").replace(oR,"$1"),Ff=async e=>{let t="e2e-env:basic-auth",r=[...await Mc(e,!1),...await Mc(Wr.join(e,"src"),!0)],n=[];for(let o of r){let s=await ri.readFile(o,"utf-8").catch(()=>""),i=new Set([...iR(s).matchAll(tR)].map(a=>a[0]).filter(a=>rR.test(a)&&a!==jc&&a!==Fc));for(let a of i)n.push(`${a} \u2192 ${sR(a)} (${Wr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${jc} / ${Fc}`}:{name:t,status:"fail",message:`basic auth has one name pair in every suite \u2014 rename, with no fallback to the old name: ${n.join("; ")}`}},Lc=async(e,t,r={})=>[..._f(t),...await Mf(e,r),await jf(e),await Ff(e)];import aR from"node:fs/promises";import cR from"node:path";var Bc=async(e,t)=>Promise.all(t.map(async r=>{let n=await aR.stat(cR.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 Uc=(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 lR from"node:fs/promises";import uR from"node:path";var Gr="turbo.json",Vc=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await lR.readFile(uR.join(e,Gr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Gr,status:"fail",message:`cannot read/parse ${Gr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Gr,status:"fail",message:`no "tasks" object defined in ${Gr}`}]: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 ${Gr}`}})};var pR=async(e,t)=>{let{check:r,rules:n}=await Nc(e,t);return{checks:[r],rules:n}},mR={adopted:!1,workspaceRoot:null},fR=async(e,t,r)=>Zn({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await rr(e)}),gR=async e=>(await It(e).catch(()=>{}))?.e2e?.server==="static",Wc=async(e,t=Dt,r={})=>{let n=await tr(e),o=n.name??dR.basename(e),{checks:s,rules:i}=r.isRoot?await _c(e,t):await pR(e,t);r.isRoot||s.push(Ic(e,r.adoption??mR)),i&&(s.push(...Uc(n.scripts??{},i.requiredScripts)),s.push(...await Bc(e,i.requiredFiles)),s.push(...await Vc(e,i.turboTasks))),!r.isRoot&&await fR(e,n,r.repoRoot)==="e2e"&&s.push(...await Lc(e,n.scripts??{},{staticServer:await gR(e)}));let a=s.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:s,passed:a}};var Gc=["plugin","marketplace","add",Tt],Jc=["plugin","install",J,"--scope","project"],Lf=(e,t)=>Zt({projectPath:e,home:t}).kind==="installed",ni=e=>((e??"").split(`
|
|
148
|
+
`).find(r=>r.trim().length>0)??"").trim(),hR=(e,t)=>{if(Kn(t))return null;d.debug({msg:`Running: ${Jn} ${Gc.join(" ")}`});let r=e({args:Gc});return r.ok?null:{step:"marketplace",error:ni(r.output)}},yR=(e,t)=>{d.debug({msg:`Running: ${Jn} ${Ws.join(" ")}`});let r=e({args:Ws});if(!r.ok)return{status:"update-failed",error:ni(r.output)};d.debug({msg:`Running: ${Jn} ${Vs.join(" ")}`});let n=e({args:Vs,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:ni(n.output)}},Kc=e=>{let{projectRoot:t,home:r}=e,n=e.run??oc;if(!n({args:nc}).ok)return{status:"claude-missing"};if(Lf(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:yR(n,t);let o=hR(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${Jn} ${Jc.join(" ")}`});let s=n({args:Jc,cwd:t});return s.ok?Lf(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:ni(s.output)}};import vR from"node:fs";import wR from"node:path";var Me=".mcp.json",tt="mcpServers",kR="infra-kit",bR=["mcp"],RR="/infra-kit/dist/mcp.js",Hc=" ",ar=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bf=e=>{if(!ar(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===kR&&r[0]===bR[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(RR)):!1},Uf=e=>/\n([ \t]+)"/.exec(e)?.[1]??Hc,qc=e=>{try{return{kind:"raw",raw:vR.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},Yc=e=>{try{return JSON.parse(e)}catch{return}},zc=e=>e instanceof Error?e.message:String(e),Jr=e=>{let t=qc(wR.join(e,Me));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=Yc(t.raw);if(!ar(r)||!ar(r[tt]))return{kind:"unparseable"};let n=r[tt];if(ie in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Bf(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import oi from"node:fs";import SR from"node:path";var gt=`claude plugin install ${J} --scope project`,Kr=`claude plugin marketplace update ${ie} && claude plugin update ${J} --scope project`,Xc=`claude plugin marketplace add ${Tt}`,Gf=" ",Jf=()=>({source:{source:"github",repo:Tt}}),ER=()=>({extraKnownMarketplaces:{[ie]:Jf()},enabledPlugins:{[J]:!0}}),Kf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),PR=e=>/\n([ \t]+)"/.exec(e)?.[1]??Gf,Vf=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Kf(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Wf=e=>[Vf(e,"extraKnownMarketplaces",ie,Jf()),Vf(e,"enabledPlugins",J,!0)].filter(r=>r!==null),xR=e=>{try{return oi.readFileSync(e,"utf-8")}catch{return null}},TR=e=>(oi.mkdirSync(SR.dirname(e),{recursive:!0}),oi.writeFileSync(e,`${JSON.stringify(ER(),null,Gf)}
|
|
149
|
+
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ie}`,`enabledPlugins.${J}`]}),Zc=(e,{write:t=!0}={})=>{let r=xR(e);if(r===null)return t?TR(e):{status:"withheld",path:e,added:Wf({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Kf(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${J}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Wf(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=PR(r),i=r.endsWith(`
|
|
150
150
|
`)?`
|
|
151
|
-
`:"";return
|
|
151
|
+
`:"";return oi.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};import AR from"node:path";import OR from"node:process";import Qc from"node:fs/promises";import Hf from"node:path";var CR="infra-kit.json",qf=["requiredScripts","requiredFiles","turbo"],uo=(e,t)=>[{path:e,action:"failed",message:t}],$R=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yf=async e=>{let t=Hf.join(e,ae),r=Hf.join(e,CR),n;try{n=await It(e)}catch(c){return uo(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!qf.includes(c));if(s.length>0)return uo(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(qf.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await Qc.stat(r),l=await Qc.readFile(r,"utf8"),u=JSON.parse(l);if(!$R(u))return uo(r,"is not a JSON object");if("audit"in u)return uo(r,`already has an "audit" block \u2014 merge ${ae}'s rules into it by hand, then delete ${ae}`);await Cm({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return uo(r,c.message)}try{await Qc.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var DR=["unchanged","created"],IR=["unchanged","created","updated","removed","failed"],zf=async(e,t,r)=>{let n=await rr(e);return ao(e,{repoRoot:t,version:B.version,design:r,declaredType:n})},NR=async(e,t)=>{if(e.root)return[...await Yf(t),...await io(t,{version:B.version})];if(e.all){let n=[];for(let o of await Pe(t))n.push(...await zf(o,t,e.design));return n}let r=await no(e.cwd??OR.cwd());return zf(r,t,e.design)},_R=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 ${IR.filter(n=>DR.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${B.version})`},MR=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=AR.relative(t,r.path),o=r.type?` (${r.type})`:"",s=r.action==="failed"&&r.message?` \u2014 ${r.message}`:"";d.info(` ${r.action.padEnd(9)} ${n}${o}${s}`)}d.info(_R(e))},jR=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Xf=async(e,t)=>{let r=await $();Xs();let n=await Lr(t),o=await NR(e,r);MR(o,r),Xs();let s=await Lr(t),i=!e.all&&!e.root;return{fixed:o.map(jR),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Qf from"node:fs";import eg from"node:path";var el="ik-mcp",Zf=(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:el,args:r}};var si="run `infra-kit setup` (or `infra-kit audit --root --fix`)",FR=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),tl=e=>ar(e)&&e.command===el,LR=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),BR=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Zf(i,a),l=e[i];if(l!==void 0&&!tl(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 ${si}, or drop mcp.${i} from infra-kit.json`});continue}if(tl(l)&&l.type===c.type&&FR(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=LR(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: ${si}`:`"${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: ${si}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!tl(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}},UR=(e,t,r)=>{let n=r===null?Hc:Uf(r),o=r===null||r.endsWith(`
|
|
152
152
|
`)?`
|
|
153
|
-
`:"";try{return
|
|
154
|
-
`,420),
|
|
155
|
-
${
|
|
156
|
-
`),
|
|
153
|
+
`:"";try{return Qf.mkdirSync(eg.dirname(e),{recursive:!0}),Qf.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${zc(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},po=({projectRoot:e,proxies:t,write:r})=>{let n=eg.join(e,Me),o=qc(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${zc(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:Yc(s);if(!ar(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${si}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[tt];if(a!==void 0&&!ar(a))return d.warn(`${n} has a "${tt}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=BR(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=UR(n,{...i,[tt]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var tg=async(e,t)=>{let r;try{r=(await G()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=po({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 VR="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",WR=async e=>e.root?[{dir:await $(),baseline:Qn,isRoot:!0}]:e.all?(await Pe(await $())).map(r=>({dir:r})):[{dir:await no(e.cwd??rg.cwd())}],GR=async e=>e.root||e.all?await $():e.cwd??rg.cwd(),JR=async()=>{try{return await $()}catch{return}},KR=e=>{let t=0,r=0;for(let i of e)for(let a of i.checks)t+=1,a.status!=="pass"&&(r+=1,d.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 d.info(n?`\u2705 audit passed \u2014 ${s}`:`\u274C audit failed \u2014 ${r}/${s}`),n},HR=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Xf(e,t);return n&&d.info(VR),r},qR=e=>{if(Jr(e).kind!=="stale")return null;let t=`${Me} still registers "${ie}" \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 "${ie}" entry by hand in a PR, keeping its siblings`;return d.info(`[INFO] mcp mcp:legacy-key: ${t}`),{packageDir:e,packageName:"mcp",checks:[{name:"mcp:legacy-key",status:"pass",message:t}],passed:!0}},ii=async(e={})=>{let t=Rc(await GR(e)),r=e.fix?await HR(e,t):void 0,n=await WR(e),o=await Lr(t),s=await JR(),i=[];for(let l of n)i.push(await Wc(l.dir,l.baseline,{adoption:o,isRoot:l.isRoot,repoRoot:s}));if(e.root){let l=await tg(n[0].dir,e.fix===!0);l&&i.push(l);let u=qR(n[0].dir);u&&i.push(u)}let c={allPassed:KR(i),packages:i.map(l=>({name:l.packageName,passed:l.passed,checks:l.checks}))};return r&&(c.fixed=r),{content:R(JSON.stringify(c,null,2)),structuredContent:c}},YR={all:je.boolean().optional().describe("Audit every non-vendor workspace package"),root:je.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},zR={allPassed:je.boolean().describe("Whether every audited package passed all checks"),packages:je.array(je.object({name:je.string(),passed:je.boolean(),checks:je.array(je.object({name:je.string(),status:je.enum(["pass","fail"]),message:je.string()}))})).describe("Per-package check results")},rl=C({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:YR,outputSchema:zR,handler:e=>ii({all:e.all,root:e.root})});import{z as Mt}from"zod";import nl from"node:fs/promises";import XR from"node:path";var Hr=()=>Object.keys(Im.shape),ZR=new Set(["protectedEnvs"]),mo={project:"per-project override",global:"user-global override"},ai=(e,t)=>{if(pe()&&ZR.has(e))throw new A({status:"refused",agentMode:_.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!Hr().includes(e)){if(e.includes(".")){let r=e.split(".")[0]??e;throw new Error(`Nested keys are not supported: override layers merge per top-level key, so "${e}" would replace the whole "${r}" section. Set "${r}" to its full JSON value instead, or use \`infra-kit config edit\`.`)}throw new Error(`Unknown config key "${e}". Top-level keys: ${Hr().join(", ")}.`)}},ng=e=>{try{return JSON.parse(e)}catch{return e}},QR=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eS=async e=>{let t;try{t=await nl.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${k(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!QR(r))throw new Error(`${k(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},tS=async(e,t)=>{t===null?await nl.rm(e,{force:!0}):St(e,t,420),Gn()},ci=async(e,t,r)=>{let n=await z(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await eS(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await nl.mkdir(XR.dirname(o),{recursive:!0}),St(o,`${JSON.stringify(c,null,2)}
|
|
154
|
+
`,420),Gn();try{await G({autoMigrate:"off"})}catch(l){throw await tS(o,s),new Error(`${l.message}
|
|
155
|
+
${k(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},ol=async({key:e,value:t,global:r})=>{ai(e,"config-set");let n=r?"global":"project",o=ng(t),{file:s,previous:i}=await ci(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${mo[n]} (${k(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:R(JSON.stringify(a,null,2)),structuredContent:a}};var li=async({key:e}={})=>{let[t,r]=await Promise.all([G(),z()]),n=t;if(e===void 0){let s=Object.keys(t).sort();d.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),d.info(` source: ${r.main}`)}else{if(!Hr().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${Hr().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},rS={config:Mt.record(Mt.string(),Mt.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, worktrees, and protectedEnvs."),configPath:Mt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Mt.string().optional().describe("The top-level key asked for, when one was."),value:Mt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Mt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},sl=C({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-set` / `config-unset` (top-level keys) or `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:{key:Mt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:rS,handler:e=>li(e)});import cS from"node:fs";import{z as ce}from"zod";import go from"node:fs";import qr from"node:path";import nS from"node:process";var oS=qr.join(".infra-kit","dev-context"),sS=".infra-kit",og=(e,t)=>{let r=qr.resolve(e);for(;;){let n=qr.join(r,t);if(go.existsSync(n))return n;let o=qr.dirname(r);if(o===r)return;r=o}},iS=e=>{let t=og(e,oS);if(t)return t;let r=og(e,sS);return r?qr.join(r,"dev-context"):void 0},il=e=>typeof e=="number"&&Number.isFinite(e)?e:0,fo=e=>typeof e=="string"?e:"",aS=(e,t,r)=>{let n=qr.join(e,t);try{let o=go.statSync(n),s=JSON.parse(go.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:fo(i.package),port:il(i.port),alias:fo(i.alias),origin:fo(i.origin),release:fo(i.release),env:fo(i.env),pid:il(i.pid),writtenAt:il(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},ho=(e=nS.cwd())=>{let t=Date.now(),r=iS(e);if(!r||!go.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=go.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>aS(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 ui=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Un,n=ho(e.cwd),o=t(),s=await Promise.all(n.apps.map(async p=>{let m=Math.max(0,Math.round((o-p.mtimeMs)/1e3)),f=await r(p.port);return{app:p.app,package:p.package,port:p.port,pid:p.pid,alias:p.alias,origin:p.origin,release:p.release,env:p.env||null,writtenAt:p.writtenAt>0?new Date(p.writtenAt).toISOString():null,fragmentMtime:new Date(p.mtimeMs).toISOString(),ageSeconds:m,live:f}})),i=s.length>0,a=n.fragmentDir??null,c=a!==null&&(cS.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){d.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",f=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${f}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}},lS={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."),env:ce.string().nullable().describe("INFRA_KIT_ENV the dev session runs with \u2014 where its UIs proxy cloud routes. Null when none was loaded, or the fragment predates the field."),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.")},al=C({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:lS,handler:()=>ui()});import{spawnSync as ny}from"node:child_process";import ne from"node:fs";import oy from"node:os";import fe from"node:path";import at from"node:process";import{z as ye}from"zod";import{execFileSync as uS}from"node:child_process";var sg=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},dS=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],pS=e=>dS.some(t=>t.test(e)),mS="/bin/ps",fS=()=>uS(mS,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
156
|
+
`),ig=(e=fS)=>{try{return e().some(pS)}catch{return!0}};import{Chalk as gS}from"chalk";import cl from"node:process";var ll={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},hS=new Set(["warn","fail"]),yS=24,Yr=" ",ag=" ",vS=(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:[""]},cg=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},wS=e=>{let t=new gS({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)}},lg=(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),kS=(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=lg(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}},bS=(e,t,r,n)=>{let o=kS(cg(e.rows),e.rows.length,t,r),s=Math.max(1,n-Yr.length-e.label.length-o.plainWidth);return`${Yr}${t.header(e.label)}${" ".repeat(s)}${o.text}`},RS=(e,t,r,n,o)=>{let s=hS.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=ag.length+i+1+t+2,p=Math.max(yS,o-u),[m,...f]=vS(e.message,p),w=" ".repeat(u),h=b=>s?b:r.dim(b);return[`${ag}${c(n[e.status])} ${l} ${h(m??"")}`.trimEnd(),...f.map(b=>`${w}${h(b)}`),...(e.notes??[]).map(b=>`${w}${b}`.trimEnd())]},SS=(e,t,r,n,o)=>{let s=cg(t),i=n.rule.repeat(Math.max(12,Math.min(o-Yr.length,56))),a=lg(s,()=>"warned"),c=[r.ok(`${s.ok} passed`),...a.map(u=>r[u.status](u.plain))].join(` ${n.separator} `),l=(e.hints??[]).map(u=>` ${r.dim(u)}`);return[`${Yr}${r.dim(i)}`,`${Yr}${c}${l.join("")}`]},ul=(e,t={})=>{let r=t.width??80,n=wS(t.color??!1),o=t.unicode??!0?ll.unicode:ll.ascii,s=e.sections.filter(u=>u.rows.length>0),i=s.flatMap(u=>u.rows),a=n.bold(e.title);if(i.length===0)return[a,"",`${Yr}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[bS(u,n,o,r),...u.rows.flatMap(p=>RS(p,c,n,o,r)),""]);return[a,"",...l,...SS(e,i,n,o,r)]},ES=new Set(["","0","false","none"]),PS=["LC_ALL","LC_CTYPE","LANG"],xS=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!ES.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,TS=(e,t)=>{if(t)return!1;let r=PS.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},dl=(e={})=>{let t=e.env??cl.env,r=e.stream??cl.stderr;return{color:xS(t,r),unicode:TS(t,e.ascii??!1),width:r.columns??80}},rt=(e,t={})=>{(t.write??(n=>{cl.stderr.write(n)}))(`${ul(e,dl(t)).join(`
|
|
157
157
|
`)}
|
|
158
|
-
`)};var
|
|
159
|
-
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:
|
|
158
|
+
`)};var CS="Tools & CLIs",$S="Shell & integration",AS="Project config",OS="Doppler env tokens",DS="Dev proxy (portless)",IS="Claude Code plugin",NS=`portless serving TLS on :${Pt}`,pl=[[CS,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[$S,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block"]],[AS,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[OS,["tokens.json present","env tokens configured","tokens.json perms"]],[DS,["portless installed","portless node","portless service target",NS,"portless CA chain valid","portless CA trusted","portless routes"]],[IS,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],ug="Other",_S=pl.map(([e])=>e),MS=new Map(pl.flatMap(([e,t])=>t.map(r=>[r,e]))),BB=pl.flatMap(([,e])=>e),ml=new Set(["portless routes","tokens.json perms"]),jS=e=>{let t=new Map;for(let n of e){let o=MS.get(n.name)??ug,s=t.get(o);s?s.push(n):t.set(o,[n])}return[..._S,ug].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var FS=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ne(e)}},LS=e=>{let t=e.filter(r=>r.status==="fail"&&ml.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:jS(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:FS(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var fl=(e,t={})=>{rt(LS(e),t)};var BS=e=>e.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"),US=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>BS(t[1])),VS=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:US(t[1])},WS=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},GS=e=>{let t=e.split(`
|
|
159
|
+
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:WS(t.slice(10))},dg=(e,t)=>{try{return e==="darwin"?VS(t):e==="linux"?GS(t):null}catch{return null}};import{Buffer as Ag}from"node:buffer";import Te from"node:fs/promises";import ot from"node:path";import Og from"node:process";import{$ as bi}from"zx";import JS from"node:process";var yo=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var pg=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(q())throw new A({status:"argument_required",argument:e,agentMode:_.source},2,t);if(!JS.stdin.isTTY)throw new g(void 0,t)},jt=async e=>{pg("version");let{runBranchPicker:t}=await import("./boot-LC2ESPY6.js"),r=await t(e);if(r===null)throw new yo;return r},Ft=async(e,t)=>{pg("versions");let{runBranchMultiPicker:r}=await import("./boot-LC2ESPY6.js"),n=await r(e,t);if(n===null)throw new yo;return n};import{$ as wg}from"zx";import{$ as XB}from"zx";import{$ as Xr}from"zx";import{$ as mg}from"zx";var gl=async e=>{let{operation:t}=e;try{await mg({quiet:!0})`git rev-parse --git-dir`}catch(r){throw new g(r,{operation:t,remediation:"run this from inside a git repository"})}try{await mg({quiet:!0})`git remote get-url origin`}catch(r){throw new g(r,{operation:t,remediation:"this repository has no `origin` remote to fetch from or push to"})}},HS=4,zr=async e=>{let{operation:t}=e,r=await wm();if(r.length===0)return;d.error(`working tree has uncommitted changes:
|
|
160
160
|
${r.join(`
|
|
161
|
-
`)}`);let n=r.slice(0,
|
|
162
|
-
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},
|
|
163
|
-
`);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}},
|
|
161
|
+
`)}`);let n=r.slice(0,HS),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},vo=async e=>{let{operation:t,base:r}=e;if(await Ir()===r)return;let n=(await Ye(await $())).find(o=>o.branch===r);if(n)throw new g(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}`})},xe=async e=>{let{operation:t}=e;if(await bm())throw new g(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 zr({operation:t})};var qS=e=>e.map(t=>({pr:t,id:Y(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>vm(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),wo=200,fg=(e,t)=>{e.length<wo||d.warn({source:t,limit:wo},`\u26A0\uFE0F ${t} returned ${wo} PRs \u2014 the page is full, so older release PRs may be missing`)},YS=async()=>{let[e,t]=await Promise.all([Xr`gh pr list --limit ${wo} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Xr`gh pr list --limit ${wo} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);fg(r,"release PR discovery (base dev)"),fg(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)}))},ko="find open release PRs",gg=async()=>{try{let e=await YS();if(e.length===0)throw new g(void 0,{operation:ko,remediation:"open a release PR first, or check you are in the right repo"});return qS(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},di=async()=>(await gg()).map(t=>t.headRefName),zS=e=>{let t=bo(e.baseRefName);if(t===null)throw new g(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=hl(e.title)!==t;return(r||e.dualBase)&&d.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}},L=async()=>(await gg()).map(zS),pi=async e=>{let{branch:t,body:r}=e;try{await Xr({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw d.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},XS=async(e,t)=>{let r=Xr({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){d.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&&d.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},mi=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=ym(t,n),a=nt(n),c=Xr({quiet:!0}),l=ke(t),u=Ro(r,o);try{await zr({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new g(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 ${p.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 ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await XS(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Xr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as yl}from"zx";var Zr=async e=>{let t=await yl`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},vl=async e=>{let t=await yl`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},wl=async e=>{try{let t=await yl`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new g(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import Eo from"node:process";var ZS="x-seraph-loginreason",QS="AUTHENTICATED_FAILED",eE=(e,t=160)=>{let r=e.split(`
|
|
162
|
+
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},yg=(e,t)=>t===QS||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",hg=(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}`,Qr=class extends Error{status;kind;body;context;constructor(t){let r=yg(t.status,t.seraphLoginReason),n=eE(t.body);super(n===""?`${t.context}: ${hg(r,t.status)}`:`${t.context}: ${hg(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},So=e=>e instanceof Qr,vg=e=>e.headers.get(ZS);var en=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Qr({status:e.status,seraphLoginReason:vg(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},cr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,kl=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 en(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},tn=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 en(a,"Failed to get Jira project versions"),await a.json()},ht=async(e,t)=>(await tn(t)).find(o=>o.name===e)||null,rn=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 en(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}},bl=async(e,t)=>{let{versionName:r}=e,n=await ht(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await rn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},nn=async()=>{let e=Eo.env.JIRA_BASE_URL,t=Eo.env.JIRA_TOKEN||Eo.env.JIRA_API_TOKEN,r=Eo.env.JIRA_PROJECT_ID,n=Eo.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(`
|
|
163
|
+
`);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}},yt=async()=>{try{return await nn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var fi=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 en(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Rl=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 en(c,"Failed to remove Jira version")};var kg="dev",bg={regular:"dev",hotfix:"main"},nt=e=>bg[e],bo=e=>{let t=Object.entries(bg).find(([,r])=>r===e);return t?t[0]:null},Ro=(e,t)=>(t??"").trim()!==""?`${e}
|
|
164
164
|
|
|
165
165
|
${t}`:`${e}
|
|
166
|
-
`,
|
|
167
|
-
`)||`the verify command exited with code ${n??"unknown"} and printed nothing`},
|
|
168
|
-
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},
|
|
169
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),
|
|
170
|
-
`)},
|
|
171
|
-
`).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),
|
|
172
|
-
`)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},
|
|
173
|
-
${l}`:l}).join(""),c=
|
|
174
|
-
\u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?d.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):d.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},
|
|
175
|
-
\u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await
|
|
176
|
-
`)[0]}}},
|
|
166
|
+
`,Sl=async(e="regular")=>{let t=nt(e),r=wg({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 wg({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 g(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()},tE=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await ht(t,r);if(!s)return(await kl({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 g(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 rn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},El=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=se(t),c=await tE({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=cr(r,c),u=await mi({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:Q(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},gi=async()=>{let e=new Map,t=await yt();if(!t)return e;try{let r=await tn(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){d.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},le=async()=>{let e=await gi();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Po=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},hl=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",hi=e=>e.flatMap(t=>{let r=Y(t);return r?[{branch:t,id:r,label:Q(r)}]:[]}),vt=e=>{try{return ke(ge(e))}catch(t){throw new g(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)})}},xo=e=>{if(e===kg)return kg;let t=Y(e);return t?Q(t):e},wt=e=>e.flatMap(t=>{let r=Y(t);return r?[Q(r)]:[]}),rE=(e,t)=>t?t.get(e)||"regular":void 0,ue=e=>{let{branches:t,descriptions:r,types:n}=e;return hi(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(se(s)),type:rE(o,n)}))};import Rg from"node:fs/promises";import nE from"node:path";import{$ as Pl}from"zx";var V="pnpm-lock.yaml",oE=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Eg=async(e,t)=>{let r=nE.join(e,V),n=`${t}:${V}`;try{let o=await Pl({cwd:e,quiet:!0})`git show ${n}`;await Rg.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${V} to start from: ${Sg(o)}`}}try{await Pl({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${V}: ${Sg(o)}`}}return oE.test(await Rg.readFile(r,"utf8"))?{ok:!1,reason:`${V} still carries conflict markers after pnpm ran`}:(await Pl({cwd:e,quiet:!0})`git add -- ${V}`,{ok:!0})},Sg=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as lr}from"zx";var xl="Merge remote-tracking branch 'origin/dev' into ",sE=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},iE=2048,aE=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-iE)).filter(s=>s.length>0).join(`
|
|
167
|
+
`)||`the verify command exited with code ${n??"unknown"} and printed nothing`},cE=async e=>{try{return(await lr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
|
|
168
|
+
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},lE=async(e,t)=>{let r=sE(t),n=await cE(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await Pm(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Pg=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await Ie(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 uE({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},uE=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await Ie(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Wn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await ec(r),await lr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${xl}${n}`;await lr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await lr({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 lE(r,i)}}finally{await tc(r)}},xg=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Tg="pnpm install --frozen-lockfile",Cg=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await ec(t),await lr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await lr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,aE(a))}finally{await tc(t)}return{kept:o,failed:s}},To=async(e,t,r="origin/dev")=>{await lr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Wn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import Tl from"node:process";var yi=new Set,vi=e=>(yi.add(e),()=>{yi.delete(e)}),dE=async()=>{for(let e of[...yi])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}yi.clear()},pE=["SIGINT","SIGTERM"],$g=async(e,t={})=>{let{register:r=(i,a)=>{Tl.on(i,a)},unregister:n=(i,a)=>{Tl.off(i,a)},exit:o=i=>{Tl.exit(i)}}=t,s=new Map;for(let i of pE){let a=()=>{dE().then(()=>{o(Wm(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var mE="pnpm install --frozen-lockfile --ignore-scripts",fE="pnpm install --frozen-lockfile",Dg=64*1024,jg=4096,$o=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-jg)},F=async(e,t)=>(await bi({cwd:e,quiet:!0})`git ${t}`).stdout,Cl=e=>e.split(`
|
|
169
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),Ri=e=>e.split("\0").filter(t=>t.length>0),wi=async(e,t)=>{try{return(await F(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Fg=async e=>ot.resolve(e,(await F(e,["rev-parse","--git-common-dir"])).trim()),$l=e=>e.then(()=>!0,()=>!1),Co=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),Al=e=>e?.length===1&&e[0]===V,Lg=async e=>ot.join(await Fg(e),"infra-kit","merge-dev-resolutions"),Ol=async(e,t)=>ot.join(await Lg(e),`${Sm(t)}.json`),Bg=async e=>{try{return JSON.parse(await Te.readFile(e,"utf8"))}catch{return null}},sn=async(e,t)=>{let r=await Ol(e,t.branch);await Te.mkdir(ot.dirname(r),{recursive:!0}),await Te.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
170
|
+
`)},Ug=async e=>{let t=await Lg(e),r=await Te.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Bg(ot.join(t,o))))).filter(o=>o!==null)},Vg=async e=>Promise.all((await Ug(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await $l(Te.stat(t.worktreePath))}))),Ig=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),Dl=async(e,t,r)=>{await F(e,["worktree","remove","--force",r]).catch(()=>Te.rm(r,{recursive:!0,force:!0})),await Te.rm(await Ol(e,t),{force:!0}).catch(()=>{}),await F(e,["worktree","prune"]).catch(()=>{})},Wg=async e=>Ri(await F(e,["diff","--name-only","-z","--diff-filter=U"])),ki=async e=>Ri(await F(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),gE=async(e,t)=>{let r=(await F(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await $l(Te.stat(ot.join(await Fg(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Cl(await F(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},Gg=e=>e.split("/").includes("node_modules"),Si=async(e,t)=>{let r=new Set(t.conflictPaths),n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=Ri(await F(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await hE(e),...o].filter(a=>!r.has(a)),i=(await ki(e)).filter(a=>!n.has(a)&&!Gg(a));return[...new Set([...s,...i,...await yE(e)])].sort()},hE=async e=>{let t=Ri(await F(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},yE=async e=>(await F(e,["ls-files","-v"])).split(`
|
|
171
|
+
`).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),vE=async e=>{let t=`:(exclude)${V}`;try{return await F(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 g(r,{operation:"check the staged resolution for conflict markers"});let i=new Set;for(let a of n.split(`
|
|
172
|
+
`)){let c=/^(.*):\d+: leftover conflict marker/.exec(a);c?.[1]&&i.add(c[1])}return[...i].sort()}},wE=async(e,t)=>{let r=[];for(let n of t)(await $l(Te.lstat(ot.join(e,n)))||(await F(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await F(e,["--literal-pathspecs","add","-A","--",...r])},Ng=async e=>(await F(e,["write-tree"])).trim(),Jg=async e=>(await F(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),kE=e=>e?`${fE} && ${e}`:mE,bE=async(e,t)=>{try{return await bi({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:$o(r)}}},Kg=async(e,t)=>{let r=(await F(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await F(e,["diff","--cached","--stat",l,"--",V])).trim(),o=t.conflictPaths.includes(V)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await F(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${V}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let u=/^diff --git a\/(.*) b\//.exec(l)?.[1];return u&&i.has(u)?`# rerere (recorded resolution)
|
|
173
|
+
${l}`:l}).join(""),c=Ag.byteLength(a)>Dg;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Ag.from(a).subarray(0,Dg).toString():a,resolutionDiffTruncated:c}},Hg=async e=>{let{cwd:t,branches:r,devSha:n}=e,o=new Map;for(let s of r)o.set(s,await RE(t,s,n));return o},RE=async(e,t,r)=>{let n=await Bg(await Ol(e,t));if(n)return{resolution:Ig(n,"exists"),reason:`resolution-exists: ${n.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let o=await Ie(e,`origin/${t}`);if(!o)return{reason:`origin/${t} does not exist on origin`};let s=Em(e,t),i=()=>Dl(e,t,s),a=vi(i);try{await F(e,["worktree","prune"]),await Te.mkdir(ot.dirname(s),{recursive:!0}),await F(e,["worktree","add","--detach",s,o]),await bi({cwd:s,quiet:!0})`git merge --no-commit ${r} -m ${xl+t}`.catch(()=>{});let c=await Wg(s);if(c.length===0)return await i(),{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let l=await wi(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 F(e,["--version"])).trim()})`};let u=await gE(s,c),p=Al(c),m={branch:t,worktreePath:s,baseSha:o,devSha:r,conflictPaths:c,autoMergeTree:l,rererePreResolved:u,ignoredAtHandoff:await ki(s),lockfileOnly:p,cliVersion:B.version,createdAt:new Date().toISOString()};return await sn(e,m),{resolution:Ig(m,p?"lockfile-only":"needs-agent")}}catch(c){return await i(),{reason:$o(c)}}finally{a()}},qg=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Ug(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=ke(ge(c)),u=o.find(p=>p.branch===l);if(!u)throw new g(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 u});if(n||o.length===0)return o;let i=await Ft(ue({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},SE=async(e,t)=>{let r=await Te.realpath(t).catch(()=>null);if(!r)return!1;let n=await Ye(e);for(let o of n)if(await Te.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},on=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Yg=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 SE(e,n))return on(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await wi(n,"HEAD"),i=await wi(n,"MERGE_HEAD");return s===t.baseSha&&i===t.devSha?CE(e,t,o,r):EE(t,o,s,i)},EE=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return on(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 Jg(o),i=n?null:await wi(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 on(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Si(o,e);return c.length>0?on(t,"out-of-scope-edit","only the conflicted paths may change",c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:e.conflictPaths.includes(V),...await Kg(o,e)}},_g=async(e,t)=>{let r=Cl(await F(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},PE=async(e,t)=>{let r=t.worktreePath,n=await _g(r,V),o=t.lockfileBlob,s=await Eg(r,t.devSha);if(!s.ok)return{code:"verify-failed",detail:s.reason,paths:[V]};let i=await _g(r,V);if(i!==null&&i!==o&&(t.lockfileBlob=i,await sn(e,t)),n!==null&&n!==i)return n===o?{code:"tree-changed",detail:`rebuilding ${V} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[V]}:{code:"out-of-scope-edit",detail:`${V} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[V]};let a=await Si(r,t);return a.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:a}:null},xE=async(e,t)=>{let r=t.worktreePath;await wE(r,t.conflictPaths.filter(i=>i!==V));let n=await Si(r,t);if(n.length>0)return{code:"out-of-scope-edit",detail:"only the conflicted paths may change",paths:n};let o=(await Wg(r)).filter(i=>i!==V);if(o.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:o};let s;try{s=await vE(r)}catch(i){return{code:"markers-remaining",detail:`the marker check could not run: ${$o(i)}`}}return s.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:s}:t.conflictPaths.includes(V)?PE(e,t):null},TE=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 ki(o)),i=await bE(o,n),a=(await ki(o)).filter(c=>!s.has(c)&&!Gg(c)&&ot.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await sn(e,t),i},CE=async(e,t,r,n)=>{let o=t.worktreePath,s=await xE(e,t);if(s)return{...r,blocked:s};let i=t.conflictPaths.includes(V),a=await Ng(o),c=await TE(e,t,a,kE(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return on(l,"verify-failed",c.reason??"the verify command failed");let u=await Si(o,t),p=Cl(await F(o,["diff","--name-only"]));return u.length>0||p.length>0||await Ng(o)!==a?on(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await sn(e,t)),{...l,...await Kg(o,t)})},$E=12e4,AE=async(e,t=$E)=>{let r=bi({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Og.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Og.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:$o(s)};let i=(await F(e,["rev-parse","--git-path","index.lock"])).trim();return await Te.rm(ot.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},OE={"verify-failed":"verify-failed","tree-changed":"tree-changed"},DE=e=>{let t=e.blocked;return{branch:e.branch,status:OE[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},IE=async(e,t,r,n)=>{let o=r.worktreePath,s=(u,p,m={})=>({branch:t.branch,status:u,conflictPaths:t.conflictPaths,pushed:!1,reason:p,...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 AE(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await F(o,["rev-parse","HEAD"])).trim(),c=(await F(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await sn(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 Jg(o);if(l.length!==2||l[0]!==r.baseSha||l[1]!==r.devSha){let u={code:"parents-mismatch",detail:`commit parents are ${l.join(" ")}, expected ${r.baseSha} ${r.devSha}`};return s("blocked",`parents-mismatch: ${u.detail}`,{mergeSha:a,blocked:u})}return{sha:a}},NE=async(e,t,r)=>{let n=(c,l,u)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...u?{blocked:u}:{}}),o;try{o=(await To(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${$o(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 Ie(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Wn(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)},_E=e=>{d.info(`
|
|
174
|
+
\u{1F4CB} Resolution preview:`);for(let t of e)t.blocked?d.info(` ${t.branch} \u2014 BLOCKED ${t.blocked.code}: ${t.blocked.detail}`):d.info(` ${t.branch} \u2014 ready${t.committed?" (already committed)":""}: tree ${t.treeSha}`)},zg=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await qg({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Co();if(i)return Mg(t,a,o,s);let c=[];for(let m of a){let f=await Yg(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await sn(t,m)),c.push(f)}_E(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new A({status:"refused",plan:l,agentMode:_.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 p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await U(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:ME(p)})}catch(m){if(!mt(m))throw m;return{...Co(),declined:!0}}return Mg(t,a,o,p)},Xg=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 g(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},ME=e=>{let t=[],r=!1;for(let o of Lm())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"]},jE=async(e,t,r,n)=>{let o=await Yg(e,t,r);if(o.blocked)return DE(o);let s=await IE(e,o,t,n);if(!("sha"in s))return s;let i=await NE(e,t,s.sha);return i==="keep"?s:i},FE=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}));d.info(`
|
|
175
|
+
\u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await Us(e,r),o=[];for(let s of t){let i=n.pushed||await Nr(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(-jg)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
|
|
176
|
+
`)[0]}}},Mg=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await jE(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await FE(e,s),a=[...o,...i.results],c=t.filter(u=>a.some(p=>p.branch===u.branch&&(p.pushed||p.status==="up-to-date")));for(let u of c)await Dl(e,u.branch,u.worktreePath);let l=t.map(u=>u.branch);return a.sort((u,p)=>l.indexOf(u.branch)-l.indexOf(p.branch)),{results:a,atomicPush:i.atomicPush,declined:!1}},Zg=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await qg({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Co();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await U(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!mt(a))throw a;return{...Co(),declined:!0}}for(let a of s)await Dl(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Co(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import LE from"node:fs";import BE from"node:os";import UE from"node:path";var VE="infra-kit.json",WE="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)",GE="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 $()}catch{return null}let t=e.trim();return t===""||t===BE.homedir()?null:t},Qg=async()=>{let e=await Ao();return e===null&&d.info(WE),e},JE=async()=>{let e=await Ao();return e===null?null:LE.existsSync(UE.join(e,VE))?e:(d.info(GE),null)};var KE=async e=>{try{return await Pe(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},eh=async({dryRun:e=!1}={})=>{let t=await JE(),r=B.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await io(t,{version:r,dryRun:e})];for(let o of await KE(t)){let s=await rr(o);n.push(...await ao(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import me from"node:fs";import Ai from"node:os";import re from"node:path";import Wl from"node:process";import Il from"node:fs";import th from"node:os";import rh from"node:path";import HE from"node:process";import{z as Pi}from"zod";var nh=e=>{try{return Il.readFileSync(e,"utf-8")}catch{return null}},an="claude in chrome",qE="com.anthropic.claude_code_browser_extension",Ei="run `/chrome` inside Claude Code to set up Claude in Chrome",YE={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},zE=e=>{try{return Il.accessSync(e,Il.constants.X_OK),!0}catch{return!1}},oh=e=>{try{return JSON.parse(e)}catch{return null}},XE=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Oo=(e={})=>{let t=e.platform??HE.platform,r=e.home??th.homedir(),n=e.readText??nh,o=e.isExecutable??zE,s=YE[t];if(s===void 0)return{name:an,status:"skip",message:`no Chrome native host location known for ${t}`};let i=rh.join(r,...s,`${qE}.json`),a=n(i);if(a===null)return{name:an,status:"warn",message:`Chrome native host not registered \u2014 ${Ei}`};let c=Pi.object({path:Pi.string().min(1)}).safeParse(oh(a));if(!c.success)return{name:an,status:"fail",message:`${k(i)} has no host path \u2014 ${Ei} again`};let l=c.data.path;if(!o(l))return{name:an,status:"fail",message:`Chrome native host ${k(l)} is missing or not executable \u2014 ${Ei} again`};let u=XE.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:an,status:"fail",message:`Chrome native host runs ${k(u)}, which no longer exists \u2014 ${Ei} again`}:{name:an,status:"pass",message:`Native host registered (${k(l)}); /infra-kit:doctor checks the live connection`}},Nl=(e={})=>{let t=e.home??th.homedir(),r=e.readText??nh,n=Pi.object({claudeInChromeDefaultEnabled:Pi.boolean().optional()}).safeParse(oh(r(rh.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import Ti from"node:fs/promises";import ZE from"node:path";import QE from"node:process";var sh=` // "envManagement": { // required in layer 1; provider-tagged
|
|
177
177
|
// "provider": "doppler",
|
|
178
178
|
// "config": { "name": "my-doppler-project" }
|
|
179
179
|
// },
|
|
@@ -278,7 +278,7 @@ ${l}`:l}).join(""),c=dg.byteLength(a)>mg;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
278
278
|
// // also fixes its modes), or by hand: both are supported, which is why the store carries no
|
|
279
279
|
// // repo-identity field and no mandatory version. Pasting a token into an
|
|
280
280
|
// // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
|
|
281
|
-
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,
|
|
281
|
+
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,_l=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
|
|
282
282
|
//
|
|
283
283
|
// Merge chain (later layers override earlier ones at top-level keys):
|
|
284
284
|
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
@@ -299,9 +299,9 @@ ${l}`:l}).join(""),c=dg.byteLength(a)>mg;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
299
299
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
300
300
|
// user-global layer \u2014 it is shown here only to document the full, valid config shape.
|
|
301
301
|
{
|
|
302
|
-
${
|
|
302
|
+
${sh}
|
|
303
303
|
}
|
|
304
|
-
`,
|
|
304
|
+
`,Ml=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
305
305
|
//
|
|
306
306
|
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
|
|
307
307
|
// <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
|
|
@@ -317,9 +317,9 @@ ${Bg}
|
|
|
317
317
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
318
318
|
// override layer \u2014 it is shown here only to document the full, valid config shape.
|
|
319
319
|
{
|
|
320
|
-
${
|
|
320
|
+
${sh}
|
|
321
321
|
}
|
|
322
|
-
`,
|
|
322
|
+
`,jl=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
|
|
323
323
|
//
|
|
324
324
|
// Machine-local registry the vendor commands (sync/manifest/diff) read to know
|
|
325
325
|
// where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
|
|
@@ -331,102 +331,107 @@ ${Bg}
|
|
|
331
331
|
// "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
|
|
332
332
|
// "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
|
|
333
333
|
}
|
|
334
|
-
`;var
|
|
335
|
-
`,"utf-8");let o=
|
|
334
|
+
`;var ih=!1,eP=e=>e.replace(/\.json$/,".example.jsonc"),tP=async e=>{try{return await Ti.readFile(e,"utf-8")}catch{return null}},cn=async e=>{let t=e.userProject,r=eP(t);await Ti.mkdir(ZE.dirname(t),{recursive:!0});let n=!await ee(t);n&&await Ti.writeFile(t,`{}
|
|
335
|
+
`,"utf-8");let o=Ml(e.projectName),s=await tP(r)!==o;return s&&await Ti.writeFile(r,o,"utf-8"),n&&Gn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},ln=e=>`Created ${k(e.configPath)} \u2014 see ${k(e.examplePath)} for the annotated reference.`,Fl=async()=>{if(QE.env.INFRA_KIT_NO_SEED||ih)return;ih=!0;let e;try{e=await z()}catch{return}if(await ee(e.main))try{let t=await cn(e);t.createdConfig?d.info(ln(t)):t.refreshedExample&&d.debug(`Refreshed ${k(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${k(e.userProject)} (config bootstrap failed).`})}};import{spawn as pP}from"node:child_process";import gh from"node:fs";import mn from"node:process";import{fileURLToPath as hh}from"node:url";import Ci from"node:fs";import un from"node:path";var ah="auto-setup.json",rP="auto-setup.log",nP="auto-setup.lock",ch="auto-setup.notified",oP=3,sP=3600*1e3,iP=()=>un.join(pt(),ah),dn=()=>un.join(pt(),rP),lh=()=>un.join(pt(),nP),aP=()=>un.join(pt(),ch),cP=new Set(["ok","attention","failed"]),lP=e=>{if(typeof e!="object"||e===null)return!1;let{root:t,status:r,notes:n}=e;return(t===null||typeof t=="string")&&typeof r=="string"&&cP.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},uP=e=>{if(typeof e!="object"||e===null)return!1;let{version:t,attempts:r,startedMs:n,finishedMs:o,runs:s}=e;return typeof t=="string"&&typeof r=="number"&&Number.isInteger(r)&&typeof n=="number"&&Number.isFinite(n)&&(o===null||typeof o=="number"&&Number.isFinite(o))&&Array.isArray(s)&&s.every(lP)},pn=(e=t=>Ci.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(iP()));return uP(t)?t:null}catch{return null}},uh=e=>{let t=pt();Ci.mkdirSync(t,{recursive:!0}),St(un.join(t,ah),JSON.stringify(e),384)},dP=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),dh=(e=t=>Ci.readFileSync(t,"utf8"))=>{try{let t=Number(e(aP()).trim());return Number.isFinite(t)?t:null}catch{return null}},ph=e=>{let t=pt();Ci.mkdirSync(t,{recursive:!0}),St(un.join(t,ch),String(e),384)},mh=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<sP?!1:e.version!==t?!0:dP(e)&&e.attempts<oP};var fh=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Ll=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return fh.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?qp(o,s,i)?"local-install":null:"not-a-tty"};var mP=e=>{pP(mn.execPath,[e,"--parent-pid",String(mn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},fP=()=>hh(new URL("./update-check.js",import.meta.url)),gP=()=>gh.realpathSync(hh(new URL("./cli.js",import.meta.url))),hP=/^[\w@./+ -]+$/,yP=e=>hP.test(e),vP=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Hn(e.latestVersion,t)&&e.updateCommand.every(yP)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ns(e.updateCommand)}`)},wP=(e,t,r,n,o)=>{if(e===null||e.finishedMs===null||e.version!==t||r===e.finishedMs)return;let s=e.runs.filter(c=>c.status==="failed").length,i=e.runs.filter(c=>c.status==="attention").length;if(s+i===0)return;let a=[s>0?`${s} failed`:null,i>0?`${i} need you`:null].filter(Boolean);n(`infra-kit ${e.version} background setup: ${a.join(", ")} \u2014 see ${k(dn())}, or run: infra-kit setup`),o(e.finishedMs)},Bl=(e,t={})=>{try{let r=t.argv??mn.argv,n=t.env??mn.env,o=t.isTty??!!mn.stdout.isTTY,s=t.cwd??mn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??gP(),c=t.readCache??qn,l=t.spawnChild??mP,u=t.fileExists??(w=>gh.existsSync(w)),p=t.notify??(w=>{d.info(w)});if(Ll({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:we})!==null)return;let m=c();vP(m,e,p);try{wP((t.readAutoSetup??pn)(),e,(t.readNotified??dh)(),p,t.writeNotified??ph)}catch{}if(!ac(m,i))return;let f=t.childPath??fP();if(!u(f))return;l(f)}catch{}};import it from"node:fs/promises";import st from"node:path";import{pathToFileURL as RP}from"node:url";import SP from"yaml";import{z as hn}from"zod";import kP from"node:fs/promises";import Ul from"node:os";import Vl from"node:path";import{z as bP}from"zod";import{z as Do}from"zod";var yh="vendor.json",vh=Do.object({workspaceDir:Do.string().min(1),source:Do.string().min(1),targets:Do.array(Do.string()).min(1)}).strict().refine(e=>!e.targets.includes(e.source),{message:'the source repo must not also be listed in "targets"',path:["targets"]});var fn=()=>Vl.join(Ul.homedir(),Up,yh),gn=e=>{if(e==="~")return Ul.homedir();if(e.startsWith("~/"))return Vl.join(Ul.homedir(),e.slice(2));if(Vl.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},$i=async()=>{let e=fn(),t;try{t=await kP.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, which one is the source and which to stamp. Run \`infra-kit vendor config --init\` to scaffold it, or create it manually as JSON:
|
|
336
336
|
|
|
337
337
|
{
|
|
338
338
|
"workspaceDir": "~/projects",
|
|
339
339
|
"source": "my-starter",
|
|
340
340
|
"targets": ["my-repo"]
|
|
341
341
|
}
|
|
342
|
-
`)}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=
|
|
343
|
-
`,"utf-8"),await it.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${
|
|
344
|
-
`,"utf-8"),await it.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${
|
|
345
|
-
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},
|
|
346
|
-
`)[0]??n;return Ge.withheld?[
|
|
347
|
-
`),s=0;for(;s<o.length&&
|
|
342
|
+
`)}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=vh.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${bP.prettifyError(n.error)}`);return n.data};var wh=e=>e.replace(/\.json$/,".yml"),kh=async()=>{let e;try{e=await z()}catch{return}let t={label:"infra-kit.json",yml:wh(e.main),json:e.main,schema:Nm},r=[...Ge.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:st.join(st.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:rc},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:wh(e.userProject),json:e.userProject,schema:rc}],n=0;for(let o of r){let[s,i]=await Promise.all([ee(o.yml),ee(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${k(o.yml)} \u2014 ${k(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await it.readFile(o.yml,"utf-8"),c=SP.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${k(o.yml)} \u2014 invalid config: ${hn.prettifyError(l.error)}`);continue}await it.mkdir(st.dirname(o.json),{recursive:!0}),await it.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
|
|
343
|
+
`,"utf-8"),await it.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${k(o.yml)} \u2192 ${k(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${k(o.yml)} \u2014 ${a.message}`)}}}n>0&&xt()},bh=async()=>{let e;try{e=await z()}catch{return}let t=st.dirname(e.userGlobal),r=[{from:st.join(t,"config.json"),to:e.userGlobal},{from:st.join(t,"config.example.jsonc"),to:st.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){d.info(`\u26A0 Skipped ${k(o)} \u2014 ${k(s)} already exists (remove the stale file manually)`);continue}try{await it.mkdir(st.dirname(s),{recursive:!0}),await it.rename(o,s),d.info(`\u2713 Renamed ${k(o)} \u2192 ${k(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${k(o)} \u2014 ${c.message}`)}}}n>0&&xt()},EP=hn.object({workspaceDir:hn.string().min(1),targets:hn.array(hn.string()).min(1)}).strict(),Rh=async()=>{let e=fn(),t=st.dirname(e),r=st.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ee(r),ee(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${k(r)} \u2014 ${k(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await it.stat(r),c=(await import(`${RP(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=EP.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${k(r)} \u2014 invalid factory config: ${hn.prettifyError(p.error)}`);return}await it.mkdir(t,{recursive:!0}),await it.writeFile(e,`${JSON.stringify(p.data,null,2)}
|
|
344
|
+
`,"utf-8"),await it.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${k(r)} \u2192 ${k(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 ${k(e)} directly to change them.`):d.info(`\u2713 Migrated ${k(r)} \u2192 ${k(e)}`)}catch(s){d.info(`\u26A0 Skipped ${k(r)} \u2014 ${s.message}`)}}},Sh=async()=>{let e=await PP(),t=0;for(let r of e)if(await ee(r))try{let n=await $m(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${k(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof Tm?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${k(r)} \u2014 ${o}`)}t>0&&xt()},PP=async()=>{try{let e=await z();return Ge.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[Mm()]}};var ur="# -- infra-kit:begin --",Lt="# -- infra-kit:end --",xP=[["# region infra-kit","# endregion infra-kit"]],TP="# infra-kit shell functions",yn=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},vn="Run `source ~/.zshrc` or open a new terminal to activate.",CP={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Fe=async(e,t)=>{try{return await t()}catch(r){throw new yn(e,r)}},Gl=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Fe("zshrc",()=>{r(OP())}),await Fe("zshenv",()=>{r(DP())}),await Fe("migrations",async()=>{await NP(),IP(),r(CP)}),await Fe("user-config",()=>{r(MP())});let n=await Fe("guidance",async()=>{let{entries:s,root:i}=await BP();return r(...s),i}),o=await Fe("plugin-pointer",async()=>Qg());return r(...VP(o,n)),await Fe("worktrees",async()=>{r(...await HP(o))}),await Fe("plugin-pointer",async()=>{await YP(o,r)}),await Fe("mcp-proxies",async()=>{r(...await XP(o))}),await Fe("project-config",async()=>{r(...await jP(o))}),await Fe("token-perms",async()=>{r(await AP())}),await Fe("chrome",()=>{r($P())}),r(..._P()),t},$P=()=>{let e=Oo();return e.status==="skip"?{step:"chrome",outcome:"skipped",message:e.message,level:"debug"}:e.status!=="pass"?{step:"chrome",outcome:"manual",message:`${e.message}, then choose "Enabled by default"`,level:"info"}:Nl()?{step:"chrome",outcome:"unchanged",message:"Claude in Chrome is set up and enabled by default",level:"debug"}:{step:"chrome",outcome:"manual",message:'Claude in Chrome is set up but off by default \u2014 run `/chrome` inside Claude Code and choose "Enabled by default"',level:"info"}},AP=async()=>{let e=await Gm();return e===null?{step:"token-perms",outcome:"skipped",message:"No token store to protect",level:"debug"}:e.length===0?{step:"token-perms",outcome:"unchanged",message:"Token store is 0600 (0700 dirs)",level:"debug"}:{step:"token-perms",outcome:"written",message:`Tightened the token store to 0600 (0700 dirs): ${e.join("; ")}`,level:"info"}};var Ph=e=>{let t=re.dirname(e);return me.existsSync(re.join(e,".git"))?e:t===e?null:Ph(t)},xh=(e,t,r,n)=>{if(!Ge.withheld)return null;if(r===n)return{step:e,outcome:"unchanged",message:`Managed block in ${t} is up to date`,level:"debug"};let o=t;try{o=me.realpathSync(t)}catch{}return Ph(re.dirname(o))===null?null:No(e,Ai.homedir(),o,["the infra-kit block updated"])},Th=e=>me.existsSync(e)?me.readFileSync(e,"utf-8"):null,OP=()=>{let e=re.join(Ai.homedir(),".zshrc"),t=Th(e),r=t===null?"":QP(t),n=jr({content:r,body:Ah(),startMarker:ur,endMarker:Lt,placement:"append-end"}),o=xh("zshrc",e,t,n);return o!==null?o:(me.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},DP=()=>{let e=re.join(Ai.homedir(),".zshenv"),t=Th(e),r=jr({content:t??"",body:Jl(),startMarker:ur,endMarker:Lt}),n=xh("zshenv",e,t,r);return n!==null?n:(me.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},IP=()=>{me.rmSync(re.join(pt(),"projects"),{recursive:!0,force:!0})},NP=async()=>{await kh(),await bh(),await Sh(),await Rh()},_P=()=>{let e=Wl.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:vn,level:"info"}),t},MP=()=>{let e=re.join(Ai.homedir(),".infra-kit"),t=re.join(e,"infra-kit.json");return me.mkdirSync(e,{recursive:!0}),me.writeFileSync(re.join(e,"infra-kit.example.jsonc"),_l(),"utf-8"),me.writeFileSync(re.join(e,"vendor.example.jsonc"),jl(),"utf-8"),me.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(me.writeFileSync(t,`{}
|
|
345
|
+
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},jP=async e=>{if(Wl.env.INFRA_KIT_NO_SEED)return[Io("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Io("skipped","not inside a git repository")];try{let t=await z();if(!me.existsSync(t.main))return[Io("skipped",`no project config at ${t.main}`)];let r=await cn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:ln(r),level:"info"}]:[Io("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Io("warned",t instanceof Error?t.message:String(t))]}},Io=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),FP=e=>{let t=[];return e.some(r=>r.type===void 0)&&t.push("infra-kit audit --fix --root"),e.some(r=>r.type!==void 0)&&t.push("infra-kit audit --fix --all"),t},LP=(e,t)=>{let r=t.filter(s=>s.action==="failed"),n=t.filter(s=>s.action!=="unchanged"&&s.action!=="failed"),o=[];return n.length===0?o.push({step:"guidance",outcome:"unchanged",message:`Agent-instruction files current (infra-kit ${e})`,level:"info"}):o.push({step:"guidance",outcome:"skipped",message:`${n.length} agent-instruction files differ from infra-kit ${e} \u2014 setup does not rewrite them; run:`,level:"info"},...FP(n).map(s=>({step:"guidance",outcome:"manual",message:s,level:"info"}))),r.length>0&&o.push({step:"guidance",outcome:"warned",message:`${r.length} agent-instruction files could not be checked \u2014 run: infra-kit audit --root && infra-kit audit --all`,level:"warn"}),o},BP=async()=>{let{skipped:e,root:t,version:r,written:n}=await eh({dryRun:!0});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:LP(r,n)}},Oi=e=>`cd ${Xp(e)} && infra-kit setup --skip-tools`,No=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${Oi(t)}`,level:"info"}),UP=(e,t)=>{let r=re.relative(e,t.path);return t.status==="withheld"?No("plugin-pointer",e,r,t.added):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"}},Eh=(e,t)=>{let r=Me;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?ie: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 ${tt} from ${re.join(e,Me)} \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 "${ie}" key`:`no ${r}`})`,level:"info"}},VP=(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 ${J} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],WP=()=>[Xc,gt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),GP=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${B.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${B.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]},JP=(e,t)=>e.status==="skipped-cli-stale"?GP(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${J} 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: ${Kr}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${J} (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"},...WP()]:[{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: ${gt}`,level:"warn"}],Ch={stale:!1},KP=async()=>{let e=qn(),t=e===null?await lc(Wl.env):e.latestVersion;return t===null||!uc(t,B.version)?Ch:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Hp(t)}},HP=async e=>{if(e===null)return[];let r=`${await Re(e)}${de}`,n=Object.values(Or).filter(o=>!me.existsSync(re.join(r,o)));for(let o of Object.values(Or))me.mkdirSync(re.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"}]},qP=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${J} is installed; the update worker keeps it current`,level:"debug"}]:[No("plugin-pointer",e,".claude/settings.json",[`the ${J} plugin installed`])],YP=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(UP(e,Zc(re.join(e,".claude","settings.json"),{write:!Ge.withheld})));let r=Zt({projectPath:e}).kind==="installed";if(Ge.withheld){t(...qP(e,r),Eh(e,Jr(e)));return}let n=r?await KP():Ch;t(...JP(Kc({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(Eh(e,Jr(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: ${gt}`,level:"warn"})}},$h=(e,t)=>{let r=re.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},zP=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=$h(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,No("mcp-proxies",e,re.relative(e,t.path),s)]},XP=async e=>{if(e===null)return[];if(!me.existsSync(re.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 G()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
|
|
346
|
+
`)[0]??n;return Ge.withheld?[No("mcp-proxies",e,"infra-kit.json",[`a config fix or migration (${o})`])]:[{step:"mcp-proxies",outcome:"warned",message:` ik-mcp entries not synced \u2014 infra-kit.json could not be loaded (${o})`,level:"warn"}]}return!t||Object.keys(t).length===0?[]:Ge.withheld?zP(e,po({projectRoot:e,proxies:t,write:!1})):$h(e,po({projectRoot:e,proxies:t,write:!0}))},ZP=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"),QP=e=>{let t=Nt(e,ur,Lt);if(t!==null)return t;for(let[a,c]of xP){let l=Nt(e,a,c);if(l!==null)return l}let r=e.indexOf(TP);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
|
|
347
|
+
`),s=0;for(;s<o.length&&ZP(o[s]);)s++;let i=o.slice(s).join(`
|
|
348
348
|
`);return n+(i?`
|
|
349
|
-
${i}`:"")},
|
|
350
|
-
`)},
|
|
351
|
-
${
|
|
352
|
-
${
|
|
353
|
-
`),
|
|
354
|
-
${
|
|
355
|
-
${
|
|
356
|
-
${t.stderr}`}},resolveBinPath:async e=>{let t=await
|
|
357
|
-
`).map(t=>{let r=t.indexOf(" ");return r===-1?null:q(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),qP=async()=>{let e=await KP({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return HP(e.stdout)},YP=async()=>{let e=await ht();return e?(await Zr(e)).map(r=>r.name):[]},Mo=async()=>{let[e,t]=await Promise.allSettled([qP(),YP()]);return e.status==="rejected"&&d.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&d.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),Ll({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import zP from"node:fs";import XP from"node:path";var Kl=[".claude/settings.json",".claude/settings.local.json"],ZP=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],QP=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),ex=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},tx=(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(QP).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},rx=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},nx=()=>mr.filter(e=>e.mutating),ox=e=>{let t=ex(e);return t===null?[]:nx().filter(r=>ZP.some(n=>rx(r).some(o=>tx(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},sx=(e,t)=>{let r;try{r=zP.readFileSync(XP.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}},Ch=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Kl){let n=sx(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=ox(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var ix=e=>e.every(t=>t.status!=="fail"),ax=["brew","git","gh","doppler","aws"],cx=async e=>{let t=await Do(ax,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},wt=async(e,t,r,n)=>{try{return await hn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},lx=async()=>{let e="orca installed",t=await Ct();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)"}},Bh=(e,t,r,n)=>{let o=de.join(Lh.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!te.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=te.readFileSync(o,"utf-8"),a=i.indexOf(lr),c=i.indexOf(Ft);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Ft.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`}},ux=()=>Bh("zshrc init block",".zshrc","shell",ph()),dx=()=>Bh("zshenv session block",".zshenv","session-env",Al()),px=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await P(),r=de.join(t,"pnpm-workspace.yaml");if(!te.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=te.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}`}}},mx=async()=>{try{return Pt(),{config:await W(),error:null}}catch(e){return{config:null,error:e}}},fx=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)"}},gx=384,Hl=448,hx=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(", "),yx=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}}})),vx=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Je,o=t.resolveToken??Om;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 yx(await Ls(),o);return{name:r,status:"pass",message:hx(s)}},wx=()=>at.env[Qt]||void 0,kx=async(e={})=>{let t="tokens.json present",r=e.readStore??Je,n=e.storePath??Tt;if((e.readEnvToken??wx)())return{name:t,status:"skip",message:`${Qt} is set; that channel takes precedence over the store`};let s;try{s=v(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 ${Qt} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},jo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},bx=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Tt,o=t.statPath??Rx,s=t.chmodPath??te.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(jo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${v(i)} (see tokens.json present)`};let a=de.dirname(i),c=de.dirname(a),l=de.dirname(c),p=[{target:l,expected:Hl,actual:jo(l,o)},{target:c,expected:Hl,actual:jo(c,o)},{target:a,expected:Hl,actual:jo(a,o)},{target:i,expected:gx,actual:jo(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${v(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${v(f.target)} is ${$h(f.actual)}, expected ${$h(f.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit setup --skip-tools\` or \`infra-kit doctor --fix\`.`};for(let f of p)s(f.target,f.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},$h=e=>`0${e.toString(8).padStart(3,"0")}`,Rx=e=>{try{return te.statSync(e)}catch{return null}},Sx=async()=>{let e="user override path";try{let t=await Y(),r=te.existsSync(t.userProject),n=await $o(t.userProject,r),o=r?Ao(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${v(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},Ex=async()=>{let e="legacy user-global config",t;try{t=await Y()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=de.join(de.dirname(t.userGlobal),"config.json");return te.existsSync(r)?te.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${v(r)} \u2014 ${v(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${v(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"}},Ah=/^\d+\.\d+\.\d+$/,Px=(e,t)=>e===t||!Ah.test(e)||!Ah.test(t)?!1:kn([`v${e}`,`v${t}`])[0]===`v${e}`,xx=async(e,t)=>{let r;try{r=await Pe(e)}catch{return[]}let n=[];for(let o of r){let s=nr(or(de.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&Px(s.version,t)&&n.push(s.version)}return n},Tx=async(e,t)=>{let r=await xx(e,t);if(r.length===0)return"";let n=kn(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`},Cx=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await Y()).main}catch{return e}if(!te.existsSync(t))return e;let r=de.dirname(t),n=de.join(r,"CLAUDE.md"),o=te.existsSync(n)?te.readFileSync(n,"utf-8"):"",s=Ze(o,_e,Qe),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await Tx(r,U.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},$x=async()=>{try{let e=(await Y()).main;return te.existsSync(e)?de.dirname(e):null}catch{return null}},Ax=e=>{let t=vm();return t===null||!Un(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Wr}`},Ox=e=>{let t=e.kind==="installed"?_s(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 ${G} version ${t}${Ax(t)}`}},Oh=3,Ih=(e,t)=>ve(e)===ve(t),Ix=e=>{if(e===void 0||e.gitRoot===null)return"";let t=v(e.gitRoot);if(e.projectDir!==null){if(Ih(e.projectDir,e.gitRoot))return"";let r=Nn(e.gitRoot,ve(e.projectDir),ve)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${v(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return Ih(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${v(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},Dx=(e,t)=>{let r="plugin installed",n=Ix(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${v(l)}`;return{name:r,status:"pass",message:`Plugin ${G} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${G} is not installed. Run: ${ft}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":v(c.projectPath)),s=o.length-Oh,i=s>0?` and ${s} more`:"",a=`${o.slice(0,Oh).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${G} is installed for ${a} only, not this project. Run: ${ft}${n}`}},Nx=()=>wt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var _x=(e,...t)=>{try{return JSON.parse(te.readFileSync(de.join(e,...t),"utf-8"))}catch{return null}},Mx=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=_s(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=_x(r,Me),o=n!==null&&typeof n=="object"?n[tt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Dh=e=>`Plugin ${G} ${e===null?"(version unreadable)":e}`,jx=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: ${ft}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Dh(e.version)} still carries an MCP server in its ${Me}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Wr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Dh(e.version)} is skills-only \u2014 no ${Me}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},Fx=(e,t)=>{let r=Xt(e===null?{}:{projectPath:e}),n=Bn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${oe} is known to Claude Code`:`Marketplace ${oe} is not registered. Run: claude plugin marketplace add ${xt}`},Dx(r,t),Ox(r),jx(Mx(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},Lx=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${v(cn())}, or run: infra-kit setup`}},Bx=({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(", ")},Ux=e=>{let t="Agent mode",r=Cs(e),n=Bx(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})`}},Nh=4,Vx=e=>{let t=e.slice(0,Nh).join(", "),r=e.length-Nh;return r>0?`${t} +${r} more`:t},Wx=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Ch(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"} (${Vx(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 ${Kl.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`}},Gx=(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`},Jx=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 Sg(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?v(i.worktreePath):"worktree missing";return`${i.branch} (${Gx(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`}},Uh=e=>Ma(["trust"],{bin:e}),Kx=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),_h="ERR_TLS_CERT_ALTNAME_INVALID",Vh=()=>`portless serving TLS on :${Et}`,Hx=async(e,t,r)=>{let n=Vh();return await e(Et,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Et}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Et}. Install it once (needs root): \`${St(t,r)}\`.`}},qx=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(u=>u.name)],c=(await Promise.all(i.map(async u=>({servername:u,result:await e(Et,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${v(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(_h)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${_h} for servername(s) ${c.map(u=>u.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(u=>Kx.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${v(r)}. Its CA was regenerated \u2014 run \`${Uh(n)}\`, or reinstall: \`${St(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},Yx=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${v(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${Uh(r)}\` (no sudo needed).`}},zx=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 \`${Ma(["alias","--remove","<name>"],{bin:r})}\`.`}},Ut="portless service target",Lo=e=>({name:Ut,status:"warn",message:e}),Wh=e=>e==="darwin"?_p:e==="linux"?Mp:null,Xx=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Np}`:`sudo systemctl restart ${jp}`,Zx="/bin/ps",Qx=e=>{try{let t=Fh(Zx,["-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}},Mh=e=>{try{return te.readFileSync(e,"utf-8")}catch{return null}},eT=e=>{try{return te.statSync(e).mtime}catch{return null}},tT=2e3,rT=e=>{try{let t=Fh(e,["-p","process.version"],{encoding:"utf-8",timeout:tT}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},nT=(e,t)=>({platform:e.platform??at.platform,readServiceFile:e.readServiceFile??Mh,readFile:e.readFile??Mh,exists:e.exists??te.existsSync,realpath:e.realpath??ve,mtime:e.mtime??eT,execPath:e.execPath??at.execPath,home:e.home??Lh.homedir(),cwd:e.cwd??at.cwd(),repoRoot:e.repoRoot??Eo,stateDir:(e.stateDir??Lp)(),processStartTime:e.processStartTime??Qx,version:e.version??at.version,arch:e.arch??at.arch,nodeVersionOf:e.nodeVersionOf??rT,isGlobal:e.isGlobal??Ts().node.isGlobal,nodeFs:e.nodeFs??te,stableNode:null,stableNodeSidecar:null,bin:t}),Bo="portless node",fr="~/.infra-kit/node",Fo=e=>({row:{name:Bo,status:"fail",message:e},stableNode:null,sidecar:null}),jh=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},oT=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,sT=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,iT=e=>{let t=Gp(e.home),r=jh(e.nodeFs.lstatSync,t);if(r===void 0)return Fo(`${fr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Fo(`${fr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Jp(e.home,e.nodeFs);if(n===null)return Fo(`${fr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=jh(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 Fo(`${fr} is Node ${n.version} (${n.method} of ${v(n.source)}); infra-kit runs ${e.version} at ${v(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!sT(c,e))return Fo(`${fr} does not run as Node ${e.version} (${oT(c)}). Re-run through the current Node: \`${St(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Bo,status:"pass",message:`${fr} is Node ${n.version} (${n.arch}, ${n.method} of ${v(n.source)})`},stableNode:t,sidecar:n}},aT=e=>{if(Wh(e.platform)===null)return{row:{name:Bo,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=iT(e);return e.isGlobal()?t:{...t,row:{name:Bo,status:"skip",message:`not a global install; the global infra-kit keeps ${fr} current`}}},Gh=(e,t)=>{let r=nT(e,t),n=aT(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},cT=(e,t)=>{let r=t.readFile(de.join(e,"package.json"));try{let n=r===null?null:ge.object({version:ge.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},lT=e=>{let t=Number.parseInt(e.readFile(de.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},uT=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},dT=(e,t,r)=>{let n=lT(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(uT(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(de.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},pT=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Nn(await t.repoRoot()??r,e,t.realpath)},gr=e=>({state:"drifted",row:e}),mT=async(e,t,r)=>{let n=St(r.bin,r);if(!r.exists(e))return gr({name:Ut,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=de.join(ja(r.home),"dist","cli.js");if(t!==o)return gr(Lo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(xs(r.home,r.exists)===null)return gr({name:Ut,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(ja(r.home));if(await pT(s,r))return gr({name:Ut,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=fT(e,n,r);if(i!==null)return i;let a=cT(s,r),c=dT(s,a,r);return c!==null?{state:"converged",row:Lo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${Xx(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Ut,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},fT=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:gr(Lo(`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:gr(Lo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Jh=async e=>{let t=Wh(e.platform);if(t===null)return{state:"absent",row:{name:Ut,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Ut,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=Kf(e.platform,r)??[];return n===void 0||o===void 0?gr(Lo(`could not parse ${t} \u2014 re-run \`${St(e.bin,e)}\` to rewrite it.`)):mT(n,o,e)},Kh=async(e,t)=>{let{seams:r}=Gh(e,t);return{state:(await Jh(r)).state,stableNode:r.stableNode}},gT=()=>[Bo,Ut,Vh(),"portless CA chain valid","portless CA trusted","portless routes"],hT=async(e={})=>{let t=e.resolveBin??Dp,r=e.isProxyServing??Fp,n=e.handshake??Vp,o=e.caTrusted??Up,s=e.routes??Mn,i=e.isListening??_n,a=(e.caPath??Bp)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...gT().map(b=>({name:b,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=Gh(e,c),m=s(),f=await Hx(r,c,u),y=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await qx(n,m,a,c,u);return[l,p,(await Jh(u)).row,f,y,Yx(o(),a,c),await zx(m,i,c)]},yT=async(e={})=>{let t="portless routes",r=e.routes??Mn,n=e.isListening??_n,o=e.devSessionRunning??Uf,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async u=>({name:u.name,port:u.port,live:await n(u.port)}))),{prunable:a,withheld:c}=Bf(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??Wp().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Ai=async(e={})=>{let t=await mx(),r=cx(e.probeDeps??Oo()),n=async(m,f)=>{let[y,b]=await Promise.all([f,r]),w=b.get(m);return w===void 0?y:{...y,detail:w}},o=await Promise.all([n("brew",wt("brew installed",Le("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",wt("git installed",Le("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",wt("gh installed",Le("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),wt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",wt("doppler installed",Le("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",wt("aws installed",Le("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")),wt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),wt("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"),lx(),Promise.resolve(ux()),Promise.resolve(dx()),px(),Promise.resolve(fx(t)),kx(),vx(t),bx(e.fix??!1),Sx(),Ex()]),s=await hT(e.portlessDeps);if(e.fix){let m=await yT(),f=s.findIndex(y=>y.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await $x(),a=await Eo(),c={projectDir:at.env.CLAUDE_PROJECT_DIR||null,cwd:at.cwd(),gitRoot:a},l=[await Nx(),...Fx(i,c),Po(),Ux({env:at.env,stdinIsTTY:at.stdin.isTTY===!0,flag:_.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:Wx(a)],u=[...o,await Jx(a),...s,...await Cx(),...l,Lx(ln(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Xc.has(m.name),detail:m.detail})),allPassed:ix(u),cliVersion:U.version};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}},ql=E({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:ge.array(ge.object({name:ge.string().describe("Name of the check"),status:ge.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:ge.string().describe("Details about the check result"),fixable:ge.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ge.object({manager:ge.string().describe("Which package manager owns this install, read from its resolved path"),version:ge.string().nullable().describe("The version the tool reported, or null"),present:ge.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ge.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:ge.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:ge.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Ai()});import{E2E_MODE_ENV as GT}from"@slip-stream-kit/config/internal";import ru from"node:fs";import JT from"node:os";import Vo from"node:path";import Di from"node:process";import{z as R}from"zod";var ct=(e,t,r)=>new C({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as vT,loadDev as wT,readAppAliasName as kT,readCloudOrigin as bT,readLocalContext as qh}from"@slip-stream-kit/config/internal";import Hh from"node:fs";import hr from"node:path";import Oi from"node:process";import{z as Yl}from"zod";var RT=async e=>{let t=hr.join(e,"apps"),r=Hh.existsSync(t)?Hh.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=hr.join(t,o,"tests"),a=(await It(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},ST=(e,t)=>{let[r,n]=hr.relative(e,t).split(hr.sep);return r==="apps"&&n?n:void 0},ET=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(ST(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 g(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` 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 C({status:"argument_required",argument:a,choices:Yl.toJSONSchema(Yl.object({app:Yl.enum(i)})),agentMode:_.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(", ")}`})},PT=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}})),xT=e=>lo(e).apps.find(t=>t.env!=="")?.env??null,zl=async(e,t={})=>{let r=t.cwd??Oi.cwd(),n=t.projectRoot??await P(),o=(t.env??Oi.env)[xr]||null,s=t.healthProbe??za,i=ET(await RT(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=hr.join(n,"apps",c,l),p=(await er(u)).name,m=(await It(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${hr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Wm(u),y=kT(p,u),b=`${y}.localhost`,w=`https://${b}`,x=0;if(l==="ui")x=(t.listRoutes??Mn)().find(T=>T.name===b||T.name===y)?.port??0;else{let T=qh(u).info.get(p);x=T?.port??0,w=T?.origin??w}let D=x>0&&await s({tag:a,port:x,kind:l})==="ok",N=D?xT(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:N,localUrl:w,served:D}},Yh=e=>{let{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}=e;return{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}},Xl=async(e,t={})=>{let r=t.healthProbe??za,n=qh(e.targetDir),o=e.kind==="ui"?await wT(e.targetDir):void 0,s=o?.proxy?vT({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:bT(e.deployedUrlEnv??void 0,t.env??Oi.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Yh(e),mode:"local",baseUrl:e.localUrl,routes:await PT(s,i,r)}},Zl=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw ct("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${hr.join(e.targetDir,"infra-kit.config.ts")} and keep the URL per environment in Doppler`,stderrExcerpt:`${o} names no variable holding its deployed URL`});let s=(t.env??Oi.env)[n];if(!r||!s){let i=s?xr:n;throw ct("env_not_loaded",{missing:i},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${xr}, and ${i} is not set`})}return{...Yh(e),mode:"cloud",baseUrl:s,routes:[]}};import TT from"node:fs";import CT from"node:path";import{stripVTControlCharacters as $T}from"node:util";import{z as A}from"zod";var zh=2e3,Xh="--reporter=line,json",Zh=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Qh=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Ql=A.object({message:A.string().optional()}),ey=A.object({type:A.string()}),AT=A.object({status:A.string(),retry:A.number(),error:Ql.optional(),errors:A.array(Ql).optional(),annotations:A.array(ey).optional(),attachments:A.array(A.object({name:A.string(),path:A.string().optional()})).optional()}),OT=A.object({projectName:A.string(),status:A.string(),expectedStatus:A.string().optional(),annotations:A.array(ey).optional(),results:A.array(AT)}),IT=A.object({title:A.string(),file:A.string(),line:A.number().optional(),tests:A.array(OT)}),ty=A.lazy(()=>A.object({title:A.string(),specs:A.array(IT).optional(),suites:A.array(ty).optional()})),DT=A.object({config:A.object({rootDir:A.string().optional()}).optional(),suites:A.array(ty),errors:A.array(Ql).optional(),stats:A.object({expected:A.number(),unexpected:A.number(),flaky:A.number(),skipped:A.number()})}),ry=e=>{let t=$T(e);return t.length>zh?`${t.slice(0,zh)}\u2026`:t},NT=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:ry(t)},_T=e=>e.status==="unexpected"||e.status==="flaky",MT=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},jT=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),FT=(e,t)=>{let r=e.filter(_T),n=r.at(-1);if(!n)return null;let o=n.results.findLast(i=>i.status!=="passed"&&i.status!=="skipped"),s=r.length===e.length&&n.status==="unexpected";return{...t,status:s?"unexpected":"flaky",retry:o?.retry??0,runs:e.length,failedRuns:r.length,error:o?NT(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},LT=e=>{let t=DT.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=new Map,c=0,l=(p,m)=>{let f=new Set(m.flatMap(w=>[...jT(w)])),y=m.some(w=>w.expectedStatus==="failed");if(!y&&!f.has("fixme")&&!f.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};y&&(b.fail+=1),f.has("fixme")?b.fixme+=1:f.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let f of p.specs??[]){let y=r?.rootDir?CT.resolve(r.rootDir,f.file):f.file,b=[...m,f.title].join(" \u203A ");l(y,f.tests);for(let[w,x]of MT(f.tests)){let D=FT(x,{title:b,file:y,line:f.line??null,project:w});D&&(D.runs>1&&D.failedRuns<D.runs&&(c+=1),i.push(D))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[ry(p.message)])}},ny=e=>{try{return LT(JSON.parse(TT.readFileSync(e,"utf8")))}catch{return null}};import Uo from"node:fs";import sy from"node:path";import Ii from"node:process";var BT=e=>sy.join(e,"node_modules",".cache","infra-kit-e2e.lock"),UT=e=>{try{return Ii.kill(e,0),!0}catch(t){return t.code==="EPERM"}},oy=e=>{try{return Uo.writeFileSync(e,String(Ii.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},eu=e=>{try{let t=Number.parseInt(Uo.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},iy=e=>{let t=BT(e);if(Uo.mkdirSync(sy.dirname(t),{recursive:!0}),!oy(t)){let r=eu(t);if(r!==null&&r!==Ii.pid&&UT(r))return{holder:r};if(Uo.rmSync(t,{force:!0}),!oy(t))return{holder:eu(t)??0}}return{release:()=>{eu(t)===Ii.pid&&Uo.rmSync(t,{force:!0})}}};import{spawn as VT}from"node:child_process";import WT from"node:os";import tu from"node:process";var ay=(e,t,r)=>new Promise((n,o)=>{let s=VT(e,t,r),i=tu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)tu.off(l,a)};for(let l of i)tu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+WT.constants.signals[u]:1))})});var KT=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],HT=e=>KT.some(t=>{try{return ru.readFileSync(Vo.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),nu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,qT=(e,t)=>{let r=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl}`];e.mode==="cloud"?r.push(` deployed app at env "${e.env}"`):t?r.push(` dev server for ${e.target} on release "${e.release}", already running`):r.push(` nothing serves ${e.target} yet; the Playwright config starts it and stops it after the run`);for(let n of e.routes){let o="";n.live!==null&&(o=n.live?" \u2014 live":" \u2014 NOT responding"),r.push(` ${n.path.padEnd(24)} ${n.source.padEnd(5)} ${n.target??"(unresolved)"}${o}`)}return r.join(`
|
|
358
|
-
`)},
|
|
349
|
+
${i}`:"")},Ah=()=>{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(`
|
|
350
|
+
`)},Oh=()=>`${ur}
|
|
351
|
+
${Ah()}
|
|
352
|
+
${Lt}`,Jl=()=>["# 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.","# A load applies only at or under a directory its env-load.root names (no file: anywhere).","# 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',' local _ik_roots="$_ik_dir/env-load.root" _ik_pwd=${PWD:A} _ik_root',' if [[ -r "$_ik_roots" ]]; then',' for _ik_root in "${(@f)$(<$_ik_roots)}"; do',' [[ -n "$_ik_root" && ( "$_ik_pwd" == "$_ik_root" || "$_ik_pwd" == "$_ik_root"/* ) ]] && break'," _ik_root="," done",' [[ -n "$_ik_root" ]] || return'," fi",' source "$_ik_load"',' elif [[ -r "$_ik_clear" ]]; then',' source "$_ik_clear"'," fi"," }","fi"].join(`
|
|
353
|
+
`),Kl=()=>`${ur}
|
|
354
|
+
${Jl()}
|
|
355
|
+
${Lt}`;import ex from"node:fs/promises";var _o=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await ex.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}}},Mo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import rx from"node:fs";import nx from"node:os";import Dh from"node:path";import ox from"node:process";import{$ as tx}from"zx";var wn=()=>tx({quiet:!0});var sx=()=>[Dh.join(nx.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],ix=async e=>{try{return(await wn()`command -v ${e}`).stdout.trim()||null}catch{return null}},jo=()=>({runCommand:async e=>{let t=await wn()`${e}`;return{stdout:`${t.stdout}
|
|
356
|
+
${t.stderr}`}},resolveBinPath:async e=>{let t=await ix(e);return t!==null?t:sx().map(r=>Dh.join(r,e)).find(r=>rx.existsSync(r))??null},realpath:we,platform:ox.platform});var Bt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),kn=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,bn=["darwin","linux"],_i=e=>t=>za(t,e)?"homebrew":"unknown",Mi=(e,t)=>r=>r===null?null:t(e(r),r),ql=e=>Mi(_i(e.kegName),t=>t==="homebrew"?Bt(["brew","upgrade",e.brewFormula]):null),Ih=e=>Is(e,"Homebrew")||Is(e,"homebrew")?"homebrew":"unknown",ax={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:kn,platforms:bn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Ih,updateFor:Mi(Ih,e=>e==="homebrew"?Bt(["brew","update"]):null)},Hl={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Mh="https://awscli.amazonaws.com/v2/install.sh",jh={steps:[["/bin/bash","-c",`curl -fsSL ${Mh} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},cx="/usr/local/aws-cli",lx=e=>Bn(cx,e,we)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Mh} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:jh,Nh=e=>za(e,Hl.kegName)?"homebrew":Is(e,"aws-cli")?"script":"unknown",ux={id:"aws",binName:"aws",...Hl,probeArgv:["aws","--version"],versionFrom:kn,platforms:bn,prerequisites:[],bootstrapInstall:jh,identify:Nh,updateFor:Mi(Nh,(e,t)=>e==="homebrew"?Bt(["brew","upgrade",Hl.brewFormula]):e==="script"?lx(t):null)},Di={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},dx={id:"git",binName:"git",...Di,probeArgv:["git","--version"],versionFrom:kn,platforms:bn,prerequisites:["brew"],bootstrapInstall:Bt(["brew","install",Di.brewInstallSpec]),identify:_i(Di.kegName),updateFor:ql(Di)},Ii={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},px={id:"gh",binName:"gh",...Ii,probeArgv:["gh","--version"],versionFrom:kn,platforms:bn,prerequisites:["brew"],bootstrapInstall:Bt(["brew","install",Ii.brewInstallSpec]),identify:_i(Ii.kegName),updateFor:ql(Ii)},Ni={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},mx={id:"doppler",binName:"doppler",...Ni,probeArgv:["doppler","--version"],versionFrom:kn,platforms:bn,prerequisites:["brew"],bootstrapInstall:Bt(["brew","install","gnupg"],["brew","install",Ni.brewInstallSpec]),identify:_i(Ni.kegName),updateFor:ql(Ni)},Fo="portless",_h=e=>Kp(e,Fo)===null?"unknown":"npm",fx={id:"portless",binName:Fo,npmPackage:Fo,probeArgv:["portless","--version"],versionFrom:kn,platforms:[...bn,"win32"],prerequisites:[],bootstrapInstall:Bt(["npm","install","-g",Fo]),identify:_h,updateFor:Mi(_h,e=>e==="npm"?Bt(["npm","install","-g",`${Fo}@latest`]):null)},Yl={brew:ax,git:dx,aws:ux,gh:px,doppler:mx,portless:fx},dr=Object.keys(Yl),Le=e=>Yl[e],zl=(e,t)=>e.platforms.includes(t),Xl=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 Le(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Fh=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Lh=async(e,t)=>{try{return await e(t)}catch{return null}},gx=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Bh=async(e,t)=>{if(!zl(e,t.platform))return Fh(e.id);let r=await Lh(t.runCommand,e.probeArgv),n=await gx(t,e.binName);if(r==null&&n==null)return Fh(e.id);let o=r??(n==null?null:await Lh(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)}},Lo=async(e,t)=>Promise.all(e.map(r=>Bh(Le(r),t)));import{$ as bx}from"zx";import{z as Uh}from"zod";var Vh=/^\d{4}-\d{2}-\d{2}$/,Bo=e=>{if(!Vh.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},Wh=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,Rn=class extends Error{constructor(t){super(Wh(t)),this.name="InvalidReleaseDateError"}},pr=e=>{let t=e.trim();if(!Bo(t))throw new Rn(t);return t},Uo=e=>{let t=e.trim();return t===""||Bo(t)?!0:Wh(t)},Zl=Uh.string().refine(Bo,{message:"Expected a calendar date in yyyy-mm-dd form."}),Ql=Uh.string().refine(e=>e===""||Bo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Ut=e=>e.slice(1).split(".").map(Number),Sn=e=>[...e].sort((t,r)=>{let[n,o,s]=Ut(t),[i,a,c]=Ut(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var Jh="next",hx=/^v?(\d+)\.(\d+)\.(\d+)$/,yx=e=>e.replace(/^.*release\//,""),eu=e=>{let t=yx(e.trim()),r=hx.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},Gh=e=>`${e[0]}.${e[1]}.${e[2]}`,tu=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=eu(o);if(!s)continue;let i=Gh(s);n.has(i)||(n.add(i),r.push(s))}return Sn(r.map(o=>Gh(o))).map(o=>Ut(`v${o}`))},mr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},ru=(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`},En=(e,t)=>{try{return ru(e,t)}catch(r){if(r instanceof mr)return null;throw r}},nu=e=>e.trim().toLowerCase()===Jh,Fi=e=>nu(e)||eu(e)!==null?{version:e}:{name:e},vx=e=>e==="regular"||e==="hotfix",Kh=e=>"name"in e,wx=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:pr(n)}},ou=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=wx(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 u=l.toLowerCase();if(!vx(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return ji({...Fi(n),type:s},{description:i,releaseDate:o})},su=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},ji=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},kx=e=>{let t=e.name.trim();return Fs(t),ji({id:{kind:"name",name:t,raw:t},type:e.type},e)},iu=(e,t)=>{let r=[...t];return e.map(n=>{if(Kh(n))return kx(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(nu(o)){let a=ru(r,n.type);return r.push(Ut(`v${a}`)),ji({id:ge(a),type:n.type},n)}let s=eu(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),ji({id:ge(i),type:n.type},n)})},au=e=>e.some(t=>!Kh(t)&&nu(t.version));var Rx=e=>e.split(`
|
|
357
|
+
`).map(t=>{let r=t.indexOf(" ");return r===-1?null:Y(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),Sx=async()=>{let e=await bx({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return Rx(e.stdout)},Ex=async()=>{let e=await yt();return e?(await tn(e)).map(r=>r.name):[]},Vo=async()=>{let[e,t]=await Promise.allSettled([Sx(),Ex()]);return e.status==="rejected"&&d.warn({err:e.reason},"Failed to list remote release branches; continuing without them"),t.status==="rejected"&&d.warn({err:t.reason},"Failed to fetch Jira versions; continuing without them"),tu({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import Px from"node:fs";import xx from"node:path";var cu=[".claude/settings.json",".claude/settings.local.json"],Tx=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],Cx=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),$x=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},Ax=(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(Cx).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},Ox=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},Dx=()=>fr.filter(e=>e.mutating),Ix=e=>{let t=$x(e);return t===null?[]:Dx().filter(r=>Tx.some(n=>Ox(r).some(o=>Ax(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},Nx=(e,t)=>{let r;try{r=Px.readFileSync(xx.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}},Hh=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of cu){let n=Nx(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=Ix(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var _x=e=>e.every(t=>t.status!=="fail"),Mx=["brew","git","gh","doppler","aws"],jx=async e=>{let t=await Lo(Mx,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},kt=async(e,t,r,n)=>{try{return await wn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},Fx=async()=>{let e="orca installed",t=await $t();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)"}},sy=(e,t,r,n)=>{let o=fe.join(oy.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ne.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ne.readFileSync(o,"utf-8"),a=i.indexOf(ur),c=i.indexOf(Lt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Lt.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`}},Lx=()=>sy("zshrc init block",".zshrc","shell",Oh()),Bx=()=>sy("zshenv session block",".zshenv","session-env",Kl()),Ux=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await $(),r=fe.join(t,"pnpm-workspace.yaml");if(!ne.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ne.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}`}}},Vx=async()=>{try{return xt(),{config:await G(),error:null}}catch(e){return{config:null,error:e}}},Wx=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)"}},Gx=384,lu=448,Jx=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(", "),Kx=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}}})),Hx=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Je,o=t.resolveToken??zm;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 Kx(await qs(),o);return{name:r,status:"pass",message:Jx(s)}},qx=()=>at.env[er]||void 0,Yx=async(e={})=>{let t="tokens.json present",r=e.readStore??Je,n=e.storePath??Ct;if((e.readEnvToken??qx)())return{name:t,status:"skip",message:`${er} is set; that channel takes precedence over the store`};let s;try{s=k(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 ${er} 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},zx=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Ct,o=t.statPath??Xx,s=t.chmodPath??ne.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 ${k(i)} (see tokens.json present)`};let a=fe.dirname(i),c=fe.dirname(a),l=fe.dirname(c),p=[{target:l,expected:lu,actual:Wo(l,o)},{target:c,expected:lu,actual:Wo(c,o)},{target:a,expected:lu,actual:Wo(a,o)},{target:i,expected:Gx,actual:Wo(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${k(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${k(f.target)} is ${qh(f.actual)}, expected ${qh(f.expected)}`).join("; ");if(!e)return{name:r,status:"fail",message:`${m}. Fix: run \`infra-kit setup --skip-tools\` or \`infra-kit doctor --fix\`.`};for(let f of p)s(f.target,f.expected);return{name:r,status:"pass",message:`Tightened ${p.length} path(s): ${m}`}},qh=e=>`0${e.toString(8).padStart(3,"0")}`,Xx=e=>{try{return ne.statSync(e)}catch{return null}},Zx=async()=>{let e="user override path";try{let t=await z(),r=ne.existsSync(t.userProject),n=await _o(t.userProject,r),o=r?Mo(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${k(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},Qx=async()=>{let e="legacy user-global config",t;try{t=await z()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=fe.join(fe.dirname(t.userGlobal),"config.json");return ne.existsSync(r)?ne.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${k(r)} \u2014 ${k(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${k(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"}},Yh=/^\d+\.\d+\.\d+$/,eT=(e,t)=>e===t||!Yh.test(e)||!Yh.test(t)?!1:Sn([`v${e}`,`v${t}`])[0]===`v${e}`,tT=async(e,t)=>{let r;try{r=await Pe(e)}catch{return[]}let n=[];for(let o of r){let s=or(sr(fe.join(o,"CLAUDE.md")));s.state==="ok"&&s.version!==void 0&&eT(s.version,t)&&n.push(s.version)}return n},rT=async(e,t)=>{let r=await tT(e,t);if(r.length===0)return"";let n=Sn(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`},nT=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await z()).main}catch{return e}if(!ne.existsSync(t))return e;let r=fe.dirname(t),n=fe.join(r,"CLAUDE.md"),o=ne.existsSync(n)?ne.readFileSync(n,"utf-8"):"",s=Ze(o,_e,Qe),i=s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools",a=await rT(r,B.version);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:`${i}${a}`}]},oT=async()=>{try{let e=(await z()).main;return ne.existsSync(e)?fe.dirname(e):null}catch{return null}},sT=e=>{let t=jm();return t===null||!Hn(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${Kr}`},iT=e=>{let t=e.kind==="installed"?Gs(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${J} version ${t}${sT(t)}`}},zh=3,Xh=(e,t)=>we(e)===we(t),aT=e=>{if(e===void 0||e.gitRoot===null)return"";let t=k(e.gitRoot);if(e.projectDir!==null){if(Xh(e.projectDir,e.gitRoot))return"";let r=Bn(e.gitRoot,we(e.projectDir),we)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${k(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return Xh(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${k(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},cT=(e,t)=>{let r="plugin installed",n=aT(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${k(l)}`;return{name:r,status:"pass",message:`Plugin ${J} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${J} is not installed. Run: ${gt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":k(c.projectPath)),s=o.length-zh,i=s>0?` and ${s} more`:"",a=`${o.slice(0,zh).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${J} is installed for ${a} only, not this project. Run: ${gt}${n}`}},lT=()=>kt("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var uT=(e,...t)=>{try{return JSON.parse(ne.readFileSync(fe.join(e,...t),"utf-8"))}catch{return null}},dT=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=Gs(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=uT(r,Me),o=n!==null&&typeof n=="object"?n[tt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},Zh=e=>`Plugin ${J} ${e===null?"(version unreadable)":e}`,pT=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: ${gt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${Zh(e.version)} still carries an MCP server in its ${Me}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${Kr}), then restart Claude Code`}}return{name:t,status:"pass",message:`${Zh(e.version)} is skills-only \u2014 no ${Me}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},mT=(e,t)=>{let r=Zt(e===null?{}:{projectPath:e}),n=Kn();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ie} is known to Claude Code`:`Marketplace ${ie} is not registered. Run: claude plugin marketplace add ${Tt}`},cT(r,t),iT(r),pT(dT(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${B.version}`}]},fT=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${k(dn())}, or run: infra-kit setup`}},gT=({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(", ")},hT=e=>{let t="Agent mode",r=js(e),n=gT(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})`}},Qh=4,yT=e=>{let t=e.slice(0,Qh).join(", "),r=e.length-Qh;return r>0?`${t} +${r} more`:t},vT=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Hh(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"} (${yT(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 ${cu.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`}},wT=(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`},kT=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 Vg(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?k(i.worktreePath):"worktree missing";return`${i.branch} (${wT(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`}},iy=e=>Xa(["trust"],{bin:e}),bT=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),ey="ERR_TLS_CERT_ALTNAME_INVALID",ay=()=>`portless serving TLS on :${Pt}`,RT=async(e,t,r)=>{let n=ay();return await e(Pt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Pt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Pt}. Install it once (needs root): \`${Et(t,r)}\`.`}},ST=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(u=>u.name)],c=(await Promise.all(i.map(async u=>({servername:u,result:await e(Pt,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${k(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(ey)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${ey} for servername(s) ${c.map(u=>u.servername).join(", ")} \u2014 doctor's probe is wrong, your trust store is not implicated. Please report this.`}:l.some(u=>bT.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${k(r)}. Its CA was regenerated \u2014 run \`${iy(n)}\`, or reinstall: \`${Et(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},ET=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${k(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${iy(r)}\` (no sudo needed).`}},PT=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 \`${Xa(["alias","--remove","<name>"],{bin:r})}\`.`}},Vt="portless service target",Jo=e=>({name:Vt,status:"warn",message:e}),cy=e=>e==="darwin"?em:e==="linux"?tm:null,xT=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Qp}`:`sudo systemctl restart ${rm}`,TT="/bin/ps",CT=e=>{try{let t=ny(TT,["-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}},ty=e=>{try{return ne.readFileSync(e,"utf-8")}catch{return null}},$T=e=>{try{return ne.statSync(e).mtime}catch{return null}},AT=2e3,OT=e=>{try{let t=ny(e,["-p","process.version"],{encoding:"utf-8",timeout:AT}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},DT=(e,t)=>({platform:e.platform??at.platform,readServiceFile:e.readServiceFile??ty,readFile:e.readFile??ty,exists:e.exists??ne.existsSync,realpath:e.realpath??we,mtime:e.mtime??$T,execPath:e.execPath??at.execPath,home:e.home??oy.homedir(),cwd:e.cwd??at.cwd(),repoRoot:e.repoRoot??Ao,stateDir:(e.stateDir??om)(),processStartTime:e.processStartTime??CT,version:e.version??at.version,arch:e.arch??at.arch,nodeVersionOf:e.nodeVersionOf??OT,isGlobal:e.isGlobal??Ms().node.isGlobal,nodeFs:e.nodeFs??ne,stableNode:null,stableNodeSidecar:null,bin:t}),Ko="portless node",gr="~/.infra-kit/node",Go=e=>({row:{name:Ko,status:"fail",message:e},stableNode:null,sidecar:null}),ry=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},IT=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,NT=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,_T=e=>{let t=lm(e.home),r=ry(e.nodeFs.lstatSync,t);if(r===void 0)return Go(`${gr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Go(`${gr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=um(e.home,e.nodeFs);if(n===null)return Go(`${gr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=ry(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 Go(`${gr} is Node ${n.version} (${n.method} of ${k(n.source)}); infra-kit runs ${e.version} at ${k(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!NT(c,e))return Go(`${gr} does not run as Node ${e.version} (${IT(c)}). Re-run through the current Node: \`${Et(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Ko,status:"pass",message:`${gr} is Node ${n.version} (${n.arch}, ${n.method} of ${k(n.source)})`},stableNode:t,sidecar:n}},MT=e=>{if(cy(e.platform)===null)return{row:{name:Ko,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=_T(e);return e.isGlobal()?t:{...t,row:{name:Ko,status:"skip",message:`not a global install; the global infra-kit keeps ${gr} current`}}},ly=(e,t)=>{let r=DT(e,t),n=MT(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},jT=(e,t)=>{let r=t.readFile(fe.join(e,"package.json"));try{let n=r===null?null:ye.object({version:ye.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},FT=e=>{let t=Number.parseInt(e.readFile(fe.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},LT=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},BT=(e,t,r)=>{let n=FT(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(LT(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(fe.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},UT=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:Bn(await t.repoRoot()??r,e,t.realpath)},hr=e=>({state:"drifted",row:e}),VT=async(e,t,r)=>{let n=Et(r.bin,r);if(!r.exists(e))return hr({name:Vt,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=fe.join(Za(r.home),"dist","cli.js");if(t!==o)return hr(Jo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(_s(r.home,r.exists)===null)return hr({name:Vt,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(Za(r.home));if(await UT(s,r))return hr({name:Vt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=WT(e,n,r);if(i!==null)return i;let a=jT(s,r),c=BT(s,a,r);return c!==null?{state:"converged",row:Jo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${xT(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Vt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},WT=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:hr(Jo(`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(Jo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),uy=async e=>{let t=cy(e.platform);if(t===null)return{state:"absent",row:{name:Vt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Vt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=dg(e.platform,r)??[];return n===void 0||o===void 0?hr(Jo(`could not parse ${t} \u2014 re-run \`${Et(e.bin,e)}\` to rewrite it.`)):VT(n,o,e)},dy=async(e,t)=>{let{seams:r}=ly(e,t);return{state:(await uy(r)).state,stableNode:r.stableNode}},GT=()=>[Ko,Vt,ay(),"portless CA chain valid","portless CA trusted","portless routes"],JT=async(e={})=>{let t=e.resolveBin??Zp,r=e.isProxyServing??nm,n=e.handshake??am,o=e.caTrusted??im,s=e.routes??Vn,i=e.isListening??Un,a=(e.caPath??sm)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...GT().map(h=>({name:h,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=ly(e,c),m=s(),f=await RT(r,c,u),w=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await ST(n,m,a,c,u);return[l,p,(await uy(u)).row,f,w,ET(o(),a,c),await PT(m,i,c)]},KT=async(e={})=>{let t="portless routes",r=e.routes??Vn,n=e.isListening??Un,o=e.devSessionRunning??ig,s=r();if(s.length===0)return{name:t,status:"pass",message:"No portless routes registered"};let i=await Promise.all(s.map(async u=>({name:u.name,port:u.port,live:await n(u.port)}))),{prunable:a,withheld:c}=sg(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??cm().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Li=async(e={})=>{let t=await Vx(),r=jx(e.probeDeps??jo()),n=async(m,f)=>{let[w,h]=await Promise.all([f,r]),y=h.get(m);return y===void 0?w:{...w,detail:y}},o=await Promise.all([n("brew",kt("brew installed",Le("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",kt("git installed",Le("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",kt("gh installed",Le("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),kt("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",kt("doppler installed",Le("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",kt("aws installed",Le("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")),kt("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),kt("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"),Fx(),Promise.resolve(Lx()),Promise.resolve(Bx()),Ux(),Promise.resolve(Wx(t)),Yx(),Hx(t),zx(e.fix??!1),Zx(),Qx()]),s=await JT(e.portlessDeps);if(e.fix){let m=await KT(),f=s.findIndex(w=>w.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await oT(),a=await Ao(),c={projectDir:at.env.CLAUDE_PROJECT_DIR||null,cwd:at.cwd(),gitRoot:a},l=[await lT(),...mT(i,c),Oo(),hT({env:at.env,stdinIsTTY:at.stdin.isTTY===!0,flag:_.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:vT(a)],u=[...o,await kT(a),...s,...await nT(),...l,fT(pn(),B.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:ml.has(m.name),detail:m.detail})),allPassed:_x(u),cliVersion:B.version};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}},uu=C({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:ye.array(ye.object({name:ye.string().describe("Name of the check"),status:ye.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:ye.string().describe("Details about the check result"),fixable:ye.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:ye.object({manager:ye.string().describe("Which package manager owns this install, read from its resolved path"),version:ye.string().nullable().describe("The version the tool reported, or null"),present:ye.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:ye.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:ye.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:ye.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Li()});import{E2E_MODE_ENV as wC}from"@slip-stream-kit/config/internal";import vu from"node:fs";import kC from"node:os";import qo from"node:path";import Vi from"node:process";import{z as E}from"zod";var ct=(e,t,r)=>new A({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as HT,loadDev as qT,readAppAliasName as YT,readCloudOrigin as zT,readLocalContext as my}from"@slip-stream-kit/config/internal";import py from"node:fs";import yr from"node:path";import Bi from"node:process";import{z as du}from"zod";var XT=async e=>{let t=yr.join(e,"apps"),r=py.existsSync(t)?py.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=yr.join(t,o,"tests"),a=(await It(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},ZT=(e,t)=>{let[r,n]=yr.relative(e,t).split(yr.sep);return r==="apps"&&n?n:void 0},QT=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(ZT(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 g(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` 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 A({status:"argument_required",argument:a,choices:du.toJSONSchema(du.object({app:du.enum(i)})),agentMode:_.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(", ")}`})},eC=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}})),tC=e=>ho(e).apps.find(t=>t.env!=="")?.env??null,pu=async(e,t={})=>{let r=t.cwd??Bi.cwd(),n=t.projectRoot??await $(),o=(t.env??Bi.env)[$r]||null,s=t.healthProbe??pc,i=QT(await XT(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=yr.join(n,"apps",c,l),p=(await tr(u)).name,m=(await It(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${yr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=lf(u),w=YT(p,u),h=`${w}.localhost`,y=`https://${h}`,b=0;if(l==="ui")b=(t.listRoutes??Vn)().find(S=>S.name===h||S.name===w)?.port??0;else{let S=my(u).info.get(p);b=S?.port??0,y=S?.origin??y}let P=b>0&&await s({tag:a,port:b,kind:l})==="ok",T=P?tC(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:T,localUrl:y,served:P}},fy=e=>{let{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}=e;return{app:t,testsDir:r,target:n,packageName:o,deployedUrlEnv:s,release:i,env:a,servedEnv:c,localUrl:l}},mu=async(e,t={})=>{let r=t.healthProbe??pc,n=my(e.targetDir),o=e.kind==="ui"?await qT(e.targetDir):void 0,s=o?.proxy?HT({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:zT(e.deployedUrlEnv??void 0,t.env??Bi.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...fy(e),mode:"local",baseUrl:e.localUrl,routes:await eC(s,i,r)}},fu=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw ct("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${yr.join(e.targetDir,"infra-kit.config.ts")} and keep the URL per environment in Doppler`,stderrExcerpt:`${o} names no variable holding its deployed URL`});let s=(t.env??Bi.env)[n];if(!r||!s){let i=s?$r:n;throw ct("env_not_loaded",{missing:i},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${$r}, and ${i} is not set`})}return{...fy(e),mode:"cloud",baseUrl:s,routes:[]}};import rC from"node:fs";import nC from"node:path";import{stripVTControlCharacters as oC}from"node:util";import{z as D}from"zod";var gy=2e3,hy="--reporter=line,json",yy=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),vy=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),gu=D.object({message:D.string().optional()}),wy=D.object({type:D.string()}),sC=D.object({status:D.string(),retry:D.number(),error:gu.optional(),errors:D.array(gu).optional(),annotations:D.array(wy).optional(),attachments:D.array(D.object({name:D.string(),path:D.string().optional()})).optional()}),iC=D.object({projectName:D.string(),status:D.string(),expectedStatus:D.string().optional(),annotations:D.array(wy).optional(),results:D.array(sC)}),aC=D.object({title:D.string(),file:D.string(),line:D.number().optional(),tests:D.array(iC)}),ky=D.lazy(()=>D.object({title:D.string(),specs:D.array(aC).optional(),suites:D.array(ky).optional()})),cC=D.object({config:D.object({rootDir:D.string().optional()}).optional(),suites:D.array(ky),errors:D.array(gu).optional(),stats:D.object({expected:D.number(),unexpected:D.number(),flaky:D.number(),skipped:D.number()})}),by=e=>{let t=oC(e);return t.length>gy?`${t.slice(0,gy)}\u2026`:t},lC=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:by(t)},uC=e=>e.status==="unexpected"||e.status==="flaky",dC=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},pC=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),mC=(e,t)=>{let r=e.filter(uC),n=r.at(-1);if(!n)return null;let o=n.results.findLast(i=>i.status!=="passed"&&i.status!=="skipped"),s=r.length===e.length&&n.status==="unexpected";return{...t,status:s?"unexpected":"flaky",retry:o?.retry??0,runs:e.length,failedRuns:r.length,error:o?lC(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},fC=e=>{let t=cC.safeParse(e);if(!t.success)return null;let{config:r,suites:n,errors:o,stats:s}=t.data,i=[],a=new Map,c=0,l=(p,m)=>{let f=new Set(m.flatMap(y=>[...pC(y)])),w=m.some(y=>y.expectedStatus==="failed");if(!w&&!f.has("fixme")&&!f.has("skip"))return;let h=a.get(p)??{file:p,fail:0,fixme:0,skip:0};w&&(h.fail+=1),f.has("fixme")?h.fixme+=1:f.has("skip")&&(h.skip+=1),a.set(p,h)},u=(p,m)=>{for(let f of p.specs??[]){let w=r?.rootDir?nC.resolve(r.rootDir,f.file):f.file,h=[...m,f.title].join(" \u203A ");l(w,f.tests);for(let[y,b]of dC(f.tests)){let P=mC(b,{title:h,file:w,line:f.line??null,project:y});P&&(P.runs>1&&P.failedRuns<P.runs&&(c+=1),i.push(P))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[by(p.message)])}},Ry=e=>{try{return fC(JSON.parse(rC.readFileSync(e,"utf8")))}catch{return null}};import Ho from"node:fs";import Ey from"node:path";import Ui from"node:process";var gC=e=>Ey.join(e,"node_modules",".cache","infra-kit-e2e.lock"),hC=e=>{try{return Ui.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Sy=e=>{try{return Ho.writeFileSync(e,String(Ui.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},hu=e=>{try{let t=Number.parseInt(Ho.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},Py=e=>{let t=gC(e);if(Ho.mkdirSync(Ey.dirname(t),{recursive:!0}),!Sy(t)){let r=hu(t);if(r!==null&&r!==Ui.pid&&hC(r))return{holder:r};if(Ho.rmSync(t,{force:!0}),!Sy(t))return{holder:hu(t)??0}}return{release:()=>{hu(t)===Ui.pid&&Ho.rmSync(t,{force:!0})}}};import{spawn as yC}from"node:child_process";import vC from"node:os";import yu from"node:process";var xy=(e,t,r)=>new Promise((n,o)=>{let s=yC(e,t,r),i=yu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)yu.off(l,a)};for(let l of i)yu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+vC.constants.signals[u]:1))})});var bC=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],RC=e=>bC.some(t=>{try{return vu.readFileSync(qo.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),wu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,SC=(e,t)=>{let r=[`${e.app} e2e \u2192 ${e.mode.toUpperCase()} ${e.baseUrl}`];e.mode==="cloud"?r.push(` deployed app at env "${e.env}"`):t?r.push(` dev server for ${e.target} on release "${e.release}", already running`):r.push(` nothing serves ${e.target} yet; the Playwright config starts it and stops it after the run`);for(let n of e.routes){let o="";n.live!==null&&(o=n.live?" \u2014 live":" \u2014 NOT responding"),r.push(` ${n.path.padEnd(24)} ${n.source.padEnd(5)} ${n.target??"(unresolved)"}${o}`)}return r.join(`
|
|
358
|
+
`)},EC=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 ct("dead_local_routes",{routes:r},{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(", ")}`})},PC=async(e,t)=>{if(e.env===null||!af(e.env))return;let r=await(t.protectedEnvAccess??ze)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?ct("protected_env",{env:e.env,humanMayRun:!0},{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`}):ct("protected_env",{env:e.env,humanMayRun:!1},{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`})},xC=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw ct("served_env_mismatch",{servedEnv:e.servedEnv,env:e.env},{operation:`run ${e.app} e2e against the local dev server`,remediation:`load the same env (\`infra-kit env-load -c ${e.servedEnv}\`), or restart \`infra-kit dev\` under "${e.env??"none"}"`,stderrExcerpt:`the dev server serving ${e.target} runs with env "${e.servedEnv}", this shell with "${e.env??"none"}"`})},TC=async(e,t)=>{if(e.served){xC(e);let p=await mu(e,t);return EC(p),p}if(!RC(e.testsDir))throw ct("no_dev_server",{devCommand:wu(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${wu(e)}\`), or wire \`infraKitE2e()\` from @slip-stream-kit/config/playwright into its playwright.config.ts`,stderrExcerpt:`nothing serves ${e.target} and ${e.testsDir}'s Playwright config does not start it`});let{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:u}=e;return{app:r,testsDir:n,target:o,packageName:s,deployedUrlEnv:i,release:a,env:c,servedEnv:l,localUrl:u,mode:"local",baseUrl:u,routes:[]}},CC=(e,t,r)=>xy("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Vi.env,...r,[wC]:e.mode},stdio:["inherit",Xt.enabled||q()?2:"inherit","inherit"]}),$C=(e,t)=>{let r=t.findIndex(s=>s==="--output"||s.startsWith("--output="));if(r!==-1){let s=t[r]==="--output"?t[r+1]??"":t[r].slice(9);return{args:t,outputDir:qo.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=qo.join(e.testsDir,"test-results",`ik-e2e-${n}-${Vi.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},AC=e=>{if(e.mode==="cloud")return()=>{};let t=Py(e.testsDir);if("holder"in t)throw ct("run_in_progress",{pid:t.holder},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${t.holder}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (pid ${t.holder}) is using its dev server`});return t.release},Wi=async(e,t={})=>{let r=await pu(e.app,t),n=e.cloud?fu(r,t):await TC(r,t);d.info(SC(n,r.served)),n.mode==="cloud"&&await PC(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?wu(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return bu({...o,ran:!1,exitCode:null,...ku});n.mode==="cloud"&&await U(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=AC(n);try{return await OC(o,t.runPlaywright??CC)}finally{s()}},OC=async(e,t)=>{if(!q()||vy(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(Vi.exitCode=i),bu({...e,ran:!0,exitCode:i,...ku,report:q()?"caller-reporter":"off"})}let{args:r,outputDir:n}=$C(e,e.playwrightArgs),o=vu.mkdtempSync(qo.join(kC.tmpdir(),"ik-e2e-report-")),s=qo.join(o,"report.json");try{let i=await t(e,[hy,...r],yy(s));i!==0&&(Vi.exitCode=i);let a=Ry(s);return bu({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...ku,report:"unavailable"},outputDir:n})}finally{vu.rmSync(o,{recursive:!0,force:!0})}},ku={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},bu=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),DC={app:E.string(),testsDir:E.string(),target:E.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:E.string(),mode:E.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:E.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:E.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:E.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:E.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:E.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:E.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:E.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:E.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:E.array(E.object({path:E.string(),packageName:E.string(),source:E.enum(["local","cloud"]),target:E.string().nullable(),live:E.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:E.array(E.string()),ran:E.boolean().describe("False for --dry-run."),exitCode:E.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:E.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:E.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:E.object({expected:E.number(),unexpected:E.number(),flaky:E.number(),skipped:E.number(),repeatFlaky:E.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:E.array(E.object({title:E.string().describe("Describe path and test title, joined with \u203A."),file:E.string(),line:E.number().nullable(),project:E.string(),status:E.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:E.number().describe("The retry index of the failed attempt reported here."),runs:E.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:E.number().describe("How many of those runs failed."),error:E.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:E.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:E.array(E.object({file:E.string(),fail:E.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:E.number().describe("test.fixme \u2014 skipped as unfinished."),skip:E.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:E.array(E.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},Ru=C({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:E.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:E.boolean().optional(),yes:E.boolean().optional(),cloud:E.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:E.array(E.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:DC,handler:e=>Wi(e)});import Gi from"node:fs";import Su from"node:path";import{z as Yo}from"zod";var IC=e=>[...e.map(t=>`unset ${t}`),`unset ${$r}`,`unset ${$s}`,`unset ${As}`,`unset ${Vp}`,`unset ${Os}`],Ji=async()=>{let e=Ar(),t=Su.join(e,Cr);if(!Gi.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Ds(t),n=IC(r),o=Su.resolve(e,Ts);Gi.mkdirSync(e,{recursive:!0,mode:448}),St(o,`${n.join(`
|
|
359
359
|
`)}
|
|
360
|
-
`,384),
|
|
360
|
+
`,384),Gi.rmSync(t,{force:!0}),Gi.rmSync(Su.join(e,Cs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}},Eu=C({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:Yo.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Yo.string().describe("Path to the file that must be sourced to apply"),variableCount:Yo.number().describe("Number of variables cleared"),unsetStatements:Yo.array(Yo.string()).describe("Unset statements generated")},handler:()=>Ji()});import NC from"node:path";import zo from"node:process";import{z as Pn}from"zod";var Ki=async()=>{d.info("Environment session status:");let e=Ar(),t=zo.env[Ln],r=NC.join(e,Cr),n=0,o=0,s=zo.env[$s]??null,i=zo.env[As]??null,a=zo.env[Os]??null;if(s){let l=Ds(r);l.length>0&&(o=l.length,n=l.filter(p=>p in zo.env).length);let u=a?.replace(/\.\d{3}Z$/,"")??null;if(d.info(` ${s}: ${n} of ${o} vars loaded (project: ${i}, loadedAt: ${u}, session: ${t})
|
|
361
361
|
`),o>0&&n<o){let p=o-n;d.warn(` ${p} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else d.info(` Session ${t}: no env loaded
|
|
362
|
-
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:
|
|
363
|
-
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:
|
|
364
|
-
\u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${
|
|
365
|
-
\u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let
|
|
366
|
-
`)[0]??""}`);let
|
|
367
|
-
\u2B06\uFE0F Pushing atomically: ${l.map(
|
|
368
|
-
`)[0],observedLanded:f.map(
|
|
369
|
-
`)[0];d.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=>!
|
|
370
|
-
\u2139\uFE0F This will push ${
|
|
362
|
+
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:R(JSON.stringify(c,null,2)),structuredContent:c}},Pu=C({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:Pn.string().describe("Current terminal session ID"),sessionLoadedCount:Pn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Pn.number().describe("Total number of cached var names"),sessionConfig:Pn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Pn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Pn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Ki});import _C from"node:process";import{z as Wt}from"zod";var Ty="****",be=e=>typeof e!="string"||e.length<8?Ty:`${Ty}${e.slice(-4)}`;var Cy=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${er}`:"store",redactedToken:be(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),MC=["ENV","SOURCE","TOKEN","PRESENT"],$y=(e,t)=>{let r=[...MC,...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())},Hi=async({check:e}={})=>{let t=await qs(),r=await Je(),n=_C.env[er],o=Cy(t,r?.envs??{},n);if(e){let a=await Qt();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await Ym({childEnv:zn(l),project:a,config:c.env});c.status=u.outcome}}for(let a of $y(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
|
|
363
|
+
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}},xu=C({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:Wt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Wt.array(Wt.object({env:Wt.string().describe("Environment / Doppler config name"),source:Wt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Wt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Wt.boolean().describe("Whether a token is configured for this environment"),status:Wt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:Hi});import{z as x}from"zod";import{$ as jC}from"zx";var FC=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),LC=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,BC=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(", ")},Cu=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),Tu=new Set(["up-to-date","fast-forward","merged"]),UC=(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=ke(ge(a))}catch(l){throw new g(l,{operation:`resolve release selector "${a}"`,remediation:`pass one of: ${t.join(", ")}`})}if(!o.has(c)){let l=s.get(c);throw new g(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))},VC={"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"},Oy=e=>{let t=VC[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},WC=(e,t)=>{d.info(`
|
|
364
|
+
\u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${Oy(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},GC=(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`},JC=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;v.setInteractive();let s=new Map(t.flatMap(i=>{let a=Y(i.branch);return a?[[se(a),Oy(i)]]:[]}));return Ft(ue({branches:r,descriptions:s}),{required:!0})},KC=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(w=>o.includes(w.branch)),a=w=>{for(let h of w)d.info(`\u2139\uFE0F ${h} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await To(t,xg(i));a(c.nowUpToDate);let l=c.kept,u=new Map;if(s&&l.length>0){d.info(`
|
|
365
|
+
\u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let w=await Cg({worktreePath:r,refs:l,command:s});u=w.failed;for(let[y,b]of w.failed)d.info(`\u2717 ${y} failed verification \u2014 not pushing it. ${b.split(`
|
|
366
|
+
`)[0]??""}`);let h=await To(t,w.kept);a(h.nowUpToDate),l=h.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};d.info(`
|
|
367
|
+
\u2B06\uFE0F Pushing atomically: ${l.map(w=>w.branch).join(", ")}`);let p=await Us(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let f=(await Promise.all(l.map(async w=>({branch:w.branch,landed:await Nr(t,w.branch)===w.sha})))).filter(w=>w.landed);return f.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${f.map(w=>w.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:u,abortedBy:p.stderr?.split(`
|
|
368
|
+
`)[0],observedLanded:f.map(w=>w.branch)}},HC=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 g(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 g(void 0,{operation:"choose the merge-dev mode",stderrExcerpt:"--tree belongs to --continue",remediation:"run the rerun a --continue preview printed, unchanged"})},Ay=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
|
|
369
|
+
`)[0];d.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=>!Tu.has(i.status));return Cu({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},qC=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Re();if(e.abort)return Ay(await Zg({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Ay(await zg({cwd:s,versions:r,all:t,verify:i,trees:Xg(e.tree),confirmedCommand:o}))},qi=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;HC(e);let a=o===!0?Tg:o||void 0;if(await gl({operation:"merge dev into release branches"}),e.continue||e.abort)return qC(e);let c=[],l=[];for(let j of await L()){let dt=LC(j);dt?l.push({branch:j.branch,reason:dt}):c.push(j.branch)}if(c.length===0)return d.info(l.length===0?"\u2139\uFE0F No open release branches found":`\u2139\uFE0F No open regular release branches \u2014 ${l.length} skipped (${BC(l)})`),v.print(),Cu(FC(n,l));let u=await Re();try{await jC({cwd:u,quiet:!0})`git fetch origin --prune`}catch(j){throw new g(j,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:UC(r,c,l),m=await xm({cwd:u},async j=>{let dt=vi(j.remove);try{return await YC({cwd:u,worktree:j,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{dt()}}),{entries:f,selected:w,pushed:h,pushAborted:y,abortedBy:b,declined:P,verifyFailed:T,handOffs:S}=m,Z=await Ye(u).catch(()=>[]);return ZC({entries:f,selected:w,pushed:h,pushAborted:y,abortedBy:b,declined:P,verifyFailed:T,handOffs:S,dryRun:n,worktrees:Z,skipped:l})},YC=async e=>{let{cwd:t,worktree:r,toPlan:n,candidates:o,skipped:s,all:i,versions:a,dryRun:c,verify:l,keepConflicts:u,confirmedCommand:p}=e,m=u?await Ie(t,"origin/dev"):null,f=await Pg({cwd:t,worktreePath:r.path,branches:n}),w={entries:f,pushed:!1,pushAborted:!1,declined:!1};if(WC(f,s),c)return{...w,selected:n};let h=await JC({entries:f,toPlan:n,all:i,explicit:a!==void 0});h.length===o.length?v.addOption("--all",!0):v.addOption("--versions",h);let y=f.filter(S=>h.includes(S.branch)&&S.mergeSha).length;y>0&&d.info(`
|
|
370
|
+
\u2139\uFE0F This will push ${y} branch(es), re-running CI on ${y} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await U(p,`Are you sure you want to merge dev into these branches: ${h.join(", ")}?`,{throwOnDecline:!0,plan:zC(f,h,s)})}catch(S){if(!mt(S))throw S;return{...w,selected:h,declined:!0}}p||v.addOption("--yes",!0);let b=await KC({cwd:t,worktreePath:r.path,entries:f,selected:h,verify:l}),P=f.filter(S=>h.includes(S.branch)&&S.status==="conflict").map(S=>S.branch),T=u&&m&&P.length>0?await Hg({cwd:t,branches:P,devSha:m}):void 0;return{entries:f,selected:h,declined:!1,...b,handOffs:T}},zC=(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:Al(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),XC=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
|
|
371
371
|
`:`# ${e.branch} \u2014 ${e.status}
|
|
372
|
-
${
|
|
373
|
-
`,
|
|
372
|
+
${GC(e.branch,t)}
|
|
373
|
+
`,ZC=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p}=e,m=new Set(n?t.filter(y=>r.includes(y.branch)&&y.mergeSha&&!l?.has(y.branch)).map(y=>y.branch):[]),f=t.filter(y=>r.includes(y.branch)).map(y=>{let b=!!y.mergeSha,P=l?.has(y.branch)??!1,T=l?.get(y.branch),S=o&&b?"push-aborted":y.status,Z=P?"verify-failed":S,j=u?.get(y.branch);return{branch:y.branch,status:Z,mergeSha:y.mergeSha,conflictPaths:y.conflictPaths,pushed:m.has(y.branch),reason:T??j?.reason??y.reason,...j?.resolution?{resolution:j.resolution}:{}}}),w=f.filter(y=>!Tu.has(y.status));for(let y of f){let b=t.find(P=>P.branch===y.branch);d.info({branch:y.branch,status:y.status,mergeSha:y.mergeSha,conflictCount:y.conflictPaths?.length??0,durationMs:b?.durationMs,pushed:y.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
|
|
374
374
|
Operation cancelled \u2014 nothing was pushed.
|
|
375
375
|
`:`
|
|
376
376
|
\u{1F50D} Dry run \u2014 nothing was pushed.
|
|
377
|
-
`);else if(
|
|
378
|
-
\u26A0\uFE0F ${
|
|
379
|
-
`);for(let
|
|
380
|
-
`);
|
|
381
|
-
`).filter(r=>r.trim().length>0)}catch{return[]}},DC=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await IC(i);if(a.length>0)return Ho(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),yy);let c=await Nm(i,o);if(!c.closed&&"error"in c)return Ho(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await gu`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return OC({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},vr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=TC}=e,i=t.length>0?await Ct():"unreachable",a=await Promise.all(t.map(l=>DC({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 gu`git worktree prune`,c};var qo=async(e,t)=>{if(!(await fe("release")).includes(e))return[];let n=await P(),o=`${n}${le}`,{removed:s,failed:i}=await vr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...t,stderrExcerpt:a?.reason})}return s};var Sn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:yr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},NC=async e=>{let t=Fa(e),r=await Be`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},vy=async()=>{let e=await Be`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},_C=async e=>{let t=yt(e),r=await rl(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new g(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 Yr(t);if(!n)throw d.error(`\u274C No PR found for branch ${t}.`),new g(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=go(n.baseRefName);if(!o)throw new g(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}},MC=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 ae(),o=await Mt(ce({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new g(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}},jC=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=nt(r),s=await nl(n);if(s.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new g(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 g(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 Sn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin --delete-branch`})},FC=async e=>{let t=X(e),r=Fa(e),n=await vy();if(n){let s=n.number;return n.title!==r&&(d.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await Sn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await Be`gh pr edit ${s} --title ${r}`})),s}await Sn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await Be`gh pr create --base main --head dev --title ${r} --body ""`});let o=await vy();if(!o)throw new g(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},LC=async e=>{let t=X(e);if(await NC(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await FC(e);await Sn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin`})},BC=async()=>{Be.quiet=!1,await Sn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await Be`gh workflow run deploy-all.yml --ref main -f environment=prod`}),Be.quiet=!0},UC=async()=>{await Sn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await Be`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},VC=async e=>{try{await As(e)}catch(t){d.warn({err:yr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Os(e)}catch(t){d.warn({err:yr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},WC=async e=>{let t=await ht();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ne(e);await sl({versionName:r},t)}catch(r){let n=yo(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:yr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Ui=async e=>{let{version:t,confirmedCommand:r}=e;await xe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await _C(t):await MC(),i=q(n);if(!i)throw new g(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=X(i);if(h.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),we())throw new C({status:"refused",agentMode:_.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 L(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),Be.quiet=!0;let l=`${await P()}${le}`;await qo(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await jC({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await LC(i),await BC(),await UC(),await VC(n),Be.quiet=!1,await WC(i),d.info(`Successfully delivered ${n} to production!`),h.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}},hu=E({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:Yo.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:Yo.string().describe("The release branch that was delivered"),version:Yo.string().describe("The version that was delivered"),type:Yo.enum(["regular","hotfix"]).describe("Release type"),success:Yo.boolean().describe("Whether the delivery was successful")},handler:Ui});import{z as kt}from"zod";import{$ as xu}from"zx";import{z as Zo}from"zod";import wy from"node:fs/promises";import yu from"node:path";var ky=".github/workflows",GC=/script_name:\s*(?<service>[a-z0-9-]+)/,JC=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,KC=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,vu=async e=>{let t=yu.resolve(e,ky),r;try{r=await wy.readdir(t)}catch{return new Map}return by(t,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},zo=async(e,t)=>by(yu.resolve(e,ky),[t]),by=async(e,t)=>{let r=new Map;for(let n of t){let o;try{o=await wy.readFile(yu.resolve(e,n),"utf-8")}catch{continue}HC(o,r)}return r},HC=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=GC.exec(r)?.groups?.service??JC.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(KC)].map(s=>s.groups?.env??"");o.length!==0&&t.set(n,[...new Set([...t.get(n)??[],...o])])}},wu=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import qC from"node:fs/promises";import YC from"node:path";import zC from"yaml";var XC=".github/workflows",ZC="skip_terraform_deploy",Xo=async(e,t)=>{let r=YC.resolve(e,XC,t),n;try{n=zC.parse(await qC.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!==ZC).map(([i])=>i)};var Ry="dev",ku=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sy=(e,t)=>e[t]===void 0,Ey=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},bu=async e=>{try{return await e}catch{return[]}},QC=async()=>{let e=await F();return vt(e.map(t=>t.branch))},e$=(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},wr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await bu(QC());if(l.length===0)return null;let u=Ey(c,"version");return Zo.enum([...new Set([...l,Ry])]).optional().describe(`Which release to deploy from. "${Ry}" deploys from the dev branch instead of a release branch. ${u===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${u}".`}`)},i=async c=>{let l=$t(await bu(At(t)),await ze());if(l.length===0)return null;let u=l.filter(Wn),p=l.filter(f=>!Wn(f)),m=Ey(c,"env");return Zo.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${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 P(),l=await bu(Xo(c,t));if(l.length===0)return null;let u=await zo(c,t);return Zo.array(Zo.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${e$(l,u)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>ku(c)?r.some(l=>Sy(c,l)):!1,buildRequestedSchema:async c=>{let l=ku(c)?c:{},u={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");u.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");u.env=p}if(r.includes("services")&&Sy(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):Zo.object(u)},toArgs:(c,l)=>{let u={...ku(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;u[p]=m}}return u}}};import t$ from"@inquirer/select";var En=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return I(r=>t$({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import r$ from"@inquirer/confirm";var Qo=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;H()&&Ms(o,{branch:r,env:n}),h.setInteractive();let s=await I(i=>r$({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import n$ from"@inquirer/select";import o$ from"node:process";var Ru=()=>!H()&&o$.stdin.isTTY===!0,s$={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Su=async()=>I(e=>n$({message:"\u{1F680} Where should this deploy run?",choices:Wt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:s$[t]}))},e),{whenHeadless:"refuse"});var Wt=["ci","local"],i$={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Py=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Wt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw H()?new C({status:"argument_required",argument:"from",agentMode:_.source},2,r):new g(void 0,r)}let t=Wt.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Wt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Eu=(e,t)=>{let n=i$[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},Pu=async e=>e||!Ru()?Py(e):Su();var es=async e=>{if(e)return e==="dev"?"dev":yt(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 ae();return Mt([{value:"dev",label:"dev"},...ce({branches:r,descriptions:o,types:n})])};var xy="deploy-all.yml",Ty=wr({workflowFile:xy,fields:["version","env"],toolName:"gh-release-deploy-all"}),Vi=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Xe({provider:Ty,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await es(t),i=ko(s);h.addOption("--version",i);let a=await ze(),c=$t(await At(xy),a),l="";r?l=r:(h.setInteractive(),l=await En(c,"launch deploy-all workflow")),h.addOption("--env",l),Dr(l,"launch deploy-all workflow",a),Fs({env:l,branch:s});let u=n??!1;if(u&&h.addOption("--skip-terraform",!0),!await Qo({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:k(JSON.stringify(p,null,2)),structuredContent:p}}try{xu.quiet=!0,await xu`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,xu.quiet=!1,d.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:u,success:!0};return{content:k(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Tu=E({name:"gh-release-deploy-all",formProvider:Ty,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:kt.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:kt.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:kt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:kt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:kt.string().describe("The release branch that was deployed"),version:kt.string().describe("The version that was deployed"),environment:kt.string().describe("The environment deployed to"),skipTerraformDeploy:kt.boolean().describe("Whether terraform deployment was skipped"),success:kt.boolean().describe("Whether the deployment was successful")},handler:Vi});import a$ from"@inquirer/checkbox";import{z as Ce}from"zod";import{$ as Cu}from"zx";var kr="deploy-selected-services.yml",Cy=wr({workflowFile:kr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Wi=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Xe({provider:Cy,params:e,operation:"launch deploy-selected workflow",argument:N=>N[0]??"version"});let i=await es(t),a=ko(i);h.addOption("--version",a);let c=await ze(),l=$t(await At(kr),c),u="";r?u=r:(h.setInteractive(),u=await En(l,"launch deploy-selected workflow")),h.addOption("--env",u),Dr(u,"launch deploy-selected workflow",c),Fs({env:u,branch:i});let p=await P(),m=await Xo(p,kr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${kr}`,stderrExcerpt:`no services found in .github/workflows/${kr}`});let f=[];if(n&&n.length>0?f=n:(h.setInteractive(),f=await I(N=>a$({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(T=>({name:T,value:T}))},N),{whenHeadless:"refuse"})),h.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let y=f.filter(N=>!m.includes(N));if(y.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${y.join(", ")}`});let b=await zo(p,kr),w=f.filter(N=>{let T=b.get(N);return T!==void 0&&!T.includes(u)});if(w.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:w.map(N=>`${N} deploys only to: ${(b.get(N)??[]).join(", ")}`).join("; "),stderrExcerpt:`${kr} gates these services out of ${u}: ${w.join(", ")}`});let x=o??!1;x&&h.addOption("--skip-terraform",!0);let D=N=>{let T={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:x,success:N};return{content:k(JSON.stringify(T,null,2)),structuredContent:T}};if(!await Qo({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),D(!1);try{Cu.quiet=!0;let N=f.flatMap(ye=>["-f",`${ye}=true`]);return await Cu`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${N} ${x?["-f","skip_terraform_deploy=true"]:[]}`,Cu.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),h.print(),D(!0)}catch(N){throw d.error({error:N},"\u274C Error launching workflow"),new g(N,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},$u=E({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Cy,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:Ce.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:Ce.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:Ce.array(Ce.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:Ce.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ce.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was deployed"),version:Ce.string().describe("The version that was deployed"),environment:Ce.string().describe("The environment deployed to"),services:Ce.array(Ce.string()).describe("The services that were deployed"),skipTerraformDeploy:Ce.boolean().describe("Whether terraform deployment was skipped"),success:Ce.boolean().describe("Whether the deployment was successful")},handler:Wi});import{z as Gt}from"zod";var Gi=async()=>{let t=(await F()).flatMap(i=>{let a=q(i.branch);return a?[{version:X(a),jiraKey:ne(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await ii(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=wo(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",u=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${u}${p}`});d.info(`All release branches:
|
|
377
|
+
`);else if(w.length>0){d.info(`
|
|
378
|
+
\u26A0\uFE0F ${w.length} branch(es) did not merge.
|
|
379
|
+
`);for(let y of w)d.info(XC(y,c))}else d.info(`\u2705 All merges completed successfully!
|
|
380
|
+
`);v.print();let h=a||i;return Cu({successfulMerges:h?0:f.filter(y=>Tu.has(y.status)).length,failedMerges:h?0:w.length,failedBranches:h?[]:w.map(y=>y.branch),totalBranches:f.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:f.map(y=>h?{...y,pushed:!1}:y),skipped:p})},$u=C({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:x.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:x.union([x.string(),x.array(x.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:x.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:x.union([x.boolean(),x.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:x.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:x.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:x.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:x.union([x.string(),x.array(x.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:x.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:x.number().describe("Number of branches that reached their desired state"),failedMerges:x.number().describe("Number of branches that did not"),failedBranches:x.array(x.string()).describe("List of branches that did not merge"),totalBranches:x.number().describe("Total number of branches processed"),dryRun:x.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:x.object({attempted:x.boolean(),aborted:x.boolean(),abortedBy:x.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:x.array(x.object({branch:x.string(),status:x.string(),mergeSha:x.string().optional(),conflictPaths:x.array(x.string()).optional(),pushed:x.boolean(),reason:x.string().optional(),resolution:x.object({worktreePath:x.string(),baseSha:x.string(),devSha:x.string(),conflictPaths:x.array(x.string()),lockfileOnly:x.boolean(),rererePreResolved:x.array(x.string()),state:x.enum(["needs-agent","lockfile-only","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch"),blocked:x.object({code:x.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:x.array(x.string()).optional(),detail:x.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:x.array(x.object({branch:x.string(),reason:x.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:qi});import{z as ts}from"zod";import{$ as Be}from"zx";var Dy=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},vr=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=Dy(t.stderr,500);o&&(r.stderr=o);let s=Dy(t.stdout,200);return s&&(r.stdout=s),r};var Xo=e=>{let{removed:t,failed:r}=e;if(t.length>0){d.info("\u274C Removed worktrees:");for(let n of t)d.info(n);d.info("")}if(r.length>0){d.warn("\u26A0\uFE0F Not removed:");for(let{branch:n,reason:o}of r)d.warn(`${n} \u2014 ${o}`);d.warn("")}t.length===0&&r.length===0&&d.info("\u2139\uFE0F No worktrees to remove")};var Zo=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=R(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 pe()?new A({status:"partial_failure",...n},1,s):new g(void 0,s)};import Yi from"node:fs/promises";import{$ as Ou}from"zx";var QC=new Set([".omc",".DS_Store"]),e$=new Set(["state","sessions"]),t$=2e3,My="check 'git worktree list' for the path; uncommitted changes block removal",r$=e=>new Promise(t=>{setTimeout(t,e)}),Au=e=>typeof e=="object"&&e!==null?e.code:void 0,Iy=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Ny=async e=>{try{return Iy(await Yi.realpath(e))}catch{return Iy(e)}},n$=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await Ye(t),o=await Ny(r);for(let s of n)if(await Ny(s.path)===o)return!0;return!1}catch{return!0}},o$=async e=>{let t;try{t=await Yi.readdir(e)}catch(n){return{kind:Au(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>QC.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await Yi.readdir(`${e}/.omc`)).every(s=>e$.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:Au(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},_y=async e=>{try{return await Yi.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return Au(t)==="ENOTEMPTY"?"busy":"failed"}},s$=async e=>{let{worktreePath:t,sleep:r}=e,n=await _y(t);return n!=="busy"?n==="removed":(await r(t$),await _y(t)==="removed")},Qo=(e,t,r)=>{let n=new g(t,{operation:`remove worktree for ${e}`,remediation:r});return d.error({error:t,branch:e,msg:n.message}),{branch:e,status:"failed",reason:n.message}},i$=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await n$({projectRoot:n,worktreePath:r}))return Qo(t,o,My);let i=await o$(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 s$({worktreePath:r,sleep:s})?Qo(t,o,a):(d.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"})},a$=async e=>{try{return(await Ou`git -C ${e} status --porcelain`).stdout.split(`
|
|
381
|
+
`).filter(r=>r.trim().length>0)}catch{return[]}},c$=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await a$(i);if(a.length>0)return Qo(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),My);let c=await Qm(i,o);if(!c.closed&&"error"in c)return Qo(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await Ou`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return i$({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},wr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=r$}=e,i=t.length>0?await $t():"unreachable",a=await Promise.all(t.map(l=>c$({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 Ou`git worktree prune`,c};var es=async(e,t)=>{if(!(await he("release")).includes(e))return[];let n=await $(),o=`${n}${de}`,{removed:s,failed:i}=await wr({branches:[e],worktreeDir:o,projectRoot:n});if(!s.includes(e)){let a=i.find(c=>c.branch===e);throw new g(void 0,{...t,stderrExcerpt:a?.reason})}return s};var xn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:vr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},l$=async e=>{let t=Qa(e),r=await Be`gh pr list --head dev --base main --state merged --json number,state,title,baseRefName,headRefName --limit 20`;return JSON.parse(r.stdout).find(s=>s.title===t)??null},jy=async()=>{let e=await Be`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},u$=async e=>{let t=vt(e),r=await vl(t);if(r.length>1){let s=r.map(i=>`#${i.number} \u2192 ${i.baseRefName}`).join(", ");throw new g(void 0,{operation:`deliver release ${t}`,remediation:`the branch has open PRs to both dev and main (${s}); close the one that should not be delivered`})}let n=r[0]??await Zr(t);if(!n)throw d.error(`\u274C No PR found for branch ${t}.`),new g(void 0,{operation:`deliver release ${t}`,remediation:`confirm a PR exists ('gh pr list --head ${t} --state all')`});let o=bo(n.baseRefName);if(!o)throw new g(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}},d$=async()=>{let e=await L(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));v.setInteractive();let n=await le(),o=await jt(ue({branches:t,descriptions:n,types:r})),s=e.find(i=>i.branch===o);if(!s)throw d.error(`\u274C Release branch ${o} not found in open PRs.`),new g(void 0,{operation:`deliver release ${o}`,remediation:`confirm an open PR exists for ${o} ('gh pr list')`});if(s.dualBase)throw new g(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}},p$=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=nt(r),s=await wl(n);if(s.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new g(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 g(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 xn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin --delete-branch`})},m$=async e=>{let t=Q(e),r=Qa(e),n=await jy();if(n){let s=n.number;return n.title!==r&&(d.info(`Adopting open dev \u2192 main PR #${s} ("${n.title}") and retitling for ${t}`),await xn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await Be`gh pr edit ${s} --title ${r}`})),s}await xn(`create RC PR (dev \u2192 main) for ${t}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await Be`gh pr create --base main --head dev --title ${r} --body ""`});let o=await jy();if(!o)throw new g(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},f$=async e=>{let t=Q(e);if(await l$(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await m$(e);await xn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await Be`gh pr merge ${n} --squash --admin`})},g$=async()=>{Be.quiet=!1,await xn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await Be`gh workflow run deploy-all.yml --ref main -f environment=prod`}),Be.quiet=!0},h$=async()=>{await xn("sync main back into dev","run manually: git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push",async()=>{await Be`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},y$=async e=>{try{await Ls(e)}catch(t){d.warn({err:vr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Bs(e)}catch(t){d.warn({err:vr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},v$=async e=>{let t=await yt();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=se(e);await bl({versionName:r},t)}catch(r){let n=So(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:vr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},zi=async e=>{let{version:t,confirmedCommand:r}=e;await xe({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await u$(t):await d$(),i=Y(n);if(!i)throw new g(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=Q(i);if(v.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),pe())throw new A({status:"refused",agentMode:_.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 U(r,`Are you sure you want to deliver version ${n} to production?`),v.addOption("--yes",!0),Be.quiet=!0;let l=`${await $()}${de}`;await es(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await p$({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await f$(i),await g$(),await h$(),await y$(n),Be.quiet=!1,await v$(i),d.info(`Successfully delivered ${n} to production!`),v.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}},Du=C({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:ts.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:ts.string().describe("The release branch that was delivered"),version:ts.string().describe("The version that was delivered"),type:ts.enum(["regular","hotfix"]).describe("Release type"),success:ts.boolean().describe("Whether the delivery was successful")},handler:zi});import{z as bt}from"zod";import{$ as Yu}from"zx";import{z as os}from"zod";import qy from"node:fs/promises";import Bu from"node:path";import{DEPLOY_CONFIG_FILE as Xi,deployConfigSchema as w$}from"@slip-stream-kit/config/internal";import k$ from"node:fs/promises";import b$ from"node:path";import{pathToFileURL as R$}from"node:url";import{z as S$}from"zod";var kr=async e=>{let t=b$.join(e,Xi);try{await k$.access(t)}catch{return}let r=await import(R$(t).href);if(r.default===void 0)throw new Error(`${Xi} at ${t} has no default export`);let n=w$.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${Xi} at ${t}:
|
|
382
|
+
${S$.prettifyError(n.error)}`);let o=[...P$(n.data),...E$(n.data)];if(o.length>0)throw new Error(`Invalid ${Xi} at ${t}:
|
|
383
|
+
${o.join(`
|
|
384
|
+
`)}`);return n.data},E$=e=>e.replaceV1!==!0?[]:dc.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),P$=e=>{let t=new Set([...e.environments,...dc]);return Object.entries(e.services).flatMap(([r,n])=>["envs","skipEnvs"].flatMap(o=>(n[o]??[]).filter(s=>!t.has(s)).map(s=>`\u2716 services.${r}.${o}: unknown environment '${s}' (known: ${[...t].join(", ")})`)))};var Iu=e=>{let t=new Map;for(let[r,n]of Object.entries(e.services)){if(n.envs!==void 0){t.set(r,[...n.envs]);continue}let o=n.skipEnvs??[],s=e.environments.filter(i=>!o.includes(i));s.length<e.environments.length&&t.set(r,s)}return t};var Uy="b16ab9c88dc04a2237481f439da5e489ffda7844",Vy=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${Uy}`,x$=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${Uy}`,Qi="install-deps",Fy=25,Tn="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",ea="skip_terraform_deploy",Wy={pilot:{all:{file:"deploy-all-v2.yml",title:"91 \u{1F9EA} Deploy all (v2)",concurrency:"deploy-all"},selected:{file:"deploy-selected-v2.yml",title:"92 \u{1F9EA} Deploy selected (v2)",concurrency:"deploy-selected"}},v1:{all:{file:"deploy-all.yml",title:"01 \u2699\uFE0F Deploy all",concurrency:"deploy-all"},selected:{file:"deploy-selected-services.yml",title:"02 \u2699\uFE0F Deploy selected services",concurrency:"deploy-selected"}}},Gy=(e,t)=>Wy[e.replaceV1===!0?"v1":"pilot"][t],Jy=e=>Object.values(Wy[e]).map(({file:t})=>`.github/workflows/${t}`),_u=Jy("pilot"),Mu=Jy("v1"),Zi=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),T$=(e,t)=>Object.entries(e.services).flatMap(([r,n])=>{if(t==="all"&&n.deployAll===!1)return[];let o=e.environments.filter(s=>(n.envs?.includes(s)??!0)&&!(n.skipEnvs?.includes(s)??!1));return o.length===0?[]:[{name:r,service:n,gate:o.length===e.environments.length?void 0:o}]}),K=e=>`\${{ ${e} }}`,Nu=e=>K(`secrets[format('{0}_${e}', inputs.environment)]`),C$=e=>[Qi,...e.terraform,...e.preDeploy],Ky=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),$$=e=>[`needs.${Qi}.result == 'success'`,...Ky(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],A$=(e,t,r)=>{let n=[];return t==="selected"&&n.push(`inputs.${e.name}`),e.gate!==void 0&&n.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),n.push("!cancelled()",...$$(r)),K(n.join(" && "))},ju=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],Hy=e=>e===void 0?[]:[` if: ${e}`],Fu=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${K("github.ref")}`,` environment: ${K("inputs.environment")}`," secrets: inherit"],O$=(e,t)=>{let r=t.extraEnv??[],n=e.service.runner===void 0?[]:[` runner: ${e.service.runner}`],o=t.deployTimeoutMinutes===void 0?[]:[` timeout-minutes: ${t.deployTimeoutMinutes}`],s=r.length===0?[]:[" extra-env: |",...r.map(i=>{let a=K(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${Vy}`," with:",` environment: ${K("inputs.environment")}`,` ref: ${K("github.ref")}`,` sha: ${K("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${B.version}`,...n,...o," secrets:",` aws-access-key-id: ${Nu("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${Nu("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${Nu("AWS_REGION")}`,` serverless-access-key: ${K("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${K("secrets.SLACK_TOKEN")}`,` slack-channel: ${K("secrets.SLACK_CHANNEL")}`,...s]},D$=(e,t,r,n)=>{let o=e.service.workflow===void 0?O$(e,n):Fu(e.service.workflow);return["",` deploy-${e.name}:`,...ju(C$(r)),...Hy(A$(e,t,r)),...o]},Ly=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],I$=(e,t,r)=>{let n=[" environment:"," type: choice"," description: 'Environment for deploy'"," required: true",` default: '${e.defaultEnvironment??e.environments[0]}'`," options:",...e.environments.map(i=>` - ${i}`)],o=(e.terraform??[]).length>0?Ly(ea,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return Ly(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},N$=e=>e.map(t=>K(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),_$=(e,t,r)=>{let{title:n,concurrency:o}=Gy(e,t),s=(e.terraform??[]).length>0?K(`inputs.${ea} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${N$(r)}`:"";return[`${Tn}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${K("inputs.environment")}]${s}${i}'`,"",`# The v1 ${t==="all"?"deploy-all":"deploy-selected"} group: two runs of this kind, v1 or v2, never deploy into one`,"# environment at once.","concurrency:",` group: ${o}-${K("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},M$=e=>{let t=K(`!inputs.${ea}`);return["",` ${Zi(e)}:`,` if: ${t}`,...Fu(e)]},j$=(e,t)=>{let r=t.length===0?void 0:K(["!cancelled()",...Ky(t)].join(" && "));return["",` ${Zi(e)}:`,...ju(t),...Hy(r),...Fu(e)]},F$=()=>["",` ${Qi}:`,` uses: ${x$}`," with:",` ref: ${K("github.ref")}`,` sha: ${K("github.sha")}`," secrets:",` slack-token: ${K("secrets.SLACK_TOKEN")}`,` slack-channel: ${K("secrets.SLACK_CHANNEL")}`],L$=(e,t)=>{let r=new Set;for(let n of e){if(r.has(n))throw new Error(`${t} would declare job \`${n}\` twice; rename one of the workflows`);r.add(n)}},B$=(e,t)=>[""," notify-success:",...ju(t),` if: ${K("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],By=(e,t)=>{let r=T$(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(Zi),preDeploy:o.map(Zi)},{file:i}=Gy(e,t),a=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(a>Fy){let p=n.length>0?`environment, ${ea}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${p} and one checkbox per service); GitHub allows ${Fy}. Fold services that always deploy together into one deploy script.`)}let c=r.map(p=>`deploy-${p.name}`);L$([Qi,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let u=`${[..._$(e,t,r),...I$(e,t,r),"","permissions:"," contents: read","","jobs:",...F$(),...n.flatMap(M$),...o.flatMap(p=>j$(p,s.terraform)),...r.flatMap(p=>D$(p,t,s,e)),...e.notifySuccess===void 0?[]:B$(e.notifySuccess,c)].join(`
|
|
385
|
+
`).replace(`jobs:
|
|
386
|
+
|
|
387
|
+
`,`jobs:
|
|
388
|
+
`)}
|
|
389
|
+
`;return{path:`.github/workflows/${i}`,content:u}},Lu=e=>[By(e,"all"),By(e,"selected")];var Yy=".github/workflows",U$=/script_name:\s*(?<service>[a-z0-9-]+)/,V$=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,W$=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Uu=async e=>{let t=Bu.resolve(e,Yy),r;try{r=await qy.readdir(t)}catch{return new Map}return zy(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},rs=async(e,t)=>zy(e,[t]),zy=async(e,t)=>{let r=Bu.resolve(e,Yy),n=new Map,o=!1;for(let s of t){let i;try{i=await qy.readFile(Bu.resolve(r,s),"utf-8")}catch{continue}i.startsWith(Tn)?o=!0:J$(i,n)}return o&&Xy(n,await G$(e)),n},G$=async e=>{try{let t=await kr(e);return t?.replaceV1===!0?Iu(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},Xy=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},J$=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=U$.exec(r)?.groups?.service??V$.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(W$)].map(s=>s.groups?.env??"");o.length!==0&&Xy(t,new Map([[n,o]]))}},Vu=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import K$ from"node:fs/promises";import H$ from"node:path";import q$ from"yaml";var Y$=".github/workflows",z$="skip_terraform_deploy",ns=async(e,t)=>{let r=H$.resolve(e,Y$,t),n;try{n=q$.parse(await K$.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!==z$).map(([i])=>i)};var Zy="dev",Wu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qy=(e,t)=>e[t]===void 0,ev=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Gu=async e=>{try{return await e}catch{return[]}},X$=async()=>{let e=await L();return wt(e.map(t=>t.branch))},Z$=(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},br=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Gu(X$());if(l.length===0)return null;let u=ev(c,"version");return os.enum([...new Set([...l,Zy])]).optional().describe(`Which release to deploy from. "${Zy}" deploys from the dev branch instead of a release branch. ${u===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${u}".`}`)},i=async c=>{let l=At(await Gu(Ot(t)),await ze());if(l.length===0)return null;let u=l.filter(Yn),p=l.filter(f=>!Yn(f)),m=ev(c,"env");return os.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${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 $(),l=await Gu(ns(c,t));if(l.length===0)return null;let u=await rs(c,t);return os.array(os.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${Z$(l,u)} A service the chosen environment gates out is REFUSED before dispatch, not skipped in silence. Selecting none discards the form and falls back to the caller's arguments.`)};return{message:`Choose the arguments for ${n}. Anything left blank keeps what the caller sent.`,isFormable:c=>Wu(c)?r.some(l=>Qy(c,l)):!1,buildRequestedSchema:async c=>{let l=Wu(c)?c:{},u={};if(r.includes("version")){let p=await s(l);if(p===null)return o("releases");u.version=p}if(r.includes("env")){let p=await i(l);if(p===null)return o("envs");u.env=p}if(r.includes("services")&&Qy(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):os.object(u)},toArgs:(c,l)=>{let u={...Wu(l)?l:{}};for(let p of r){let m=c[p];if(m!==void 0){if(p==="services"&&(!Array.isArray(m)||m.length===0))return null;u[p]=m}}return u}}};import Q$ from"@inquirer/select";var Cn=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return N(r=>Q$({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import eA from"@inquirer/confirm";var ss=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;q()&&Js(o,{branch:r,env:n}),v.setInteractive();let s=await N(i=>eA({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&v.addOption("--yes",!0),s};import tA from"@inquirer/select";import rA from"node:process";var Ju=()=>!q()&&rA.stdin.isTTY===!0,nA={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Ku=async()=>N(e=>tA({message:"\u{1F680} Where should this deploy run?",choices:Gt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:nA[t]}))},e),{whenHeadless:"refuse"});var Gt=["ci","local"],oA={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},tv=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Gt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw q()?new A({status:"argument_required",argument:"from",agentMode:_.source},2,r):new g(void 0,r)}let t=Gt.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Gt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Hu=(e,t)=>{let n=oA[e==="ci"?"local":"ci"].filter(o=>{let s=t[o];return s!==void 0&&s!==!1});if(n.length!==0)throw new g(void 0,{operation:`deploy --from ${e}`,remediation:e==="ci"?"drop the flag, or use --from local to deploy from this machine":"drop the flag, or use --from ci to dispatch the release workflow",stderrExcerpt:`${n.join(", ")} ${n.length===1?"is":"are"} not valid with --from ${e}`})},qu=async e=>e||!Ju()?tv(e):Ku();var is=async e=>{if(e)return e==="dev"?"dev":vt(e);v.setInteractive();let t=await L(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await le();return jt([{value:"dev",label:"dev"},...ue({branches:r,descriptions:o,types:n})])};var rv="deploy-all.yml",nv=br({workflowFile:rv,fields:["version","env"],toolName:"gh-release-deploy-all"}),ta=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Xe({provider:nv,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await is(t),i=xo(s);v.addOption("--version",i);let a=await ze(),c=At(await Ot(rv),a),l="";r?l=r:(v.setInteractive(),l=await Cn(c,"launch deploy-all workflow")),v.addOption("--env",l),Mr(l,"launch deploy-all workflow",a),Hs({env:l,branch:s});let u=n??!1;if(u&&v.addOption("--skip-terraform",!0),!await ss({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}}try{Yu.quiet=!0,await Yu`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Yu.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),v.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content:R(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},zu=C({name:"gh-release-deploy-all",formProvider:nv,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:bt.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:bt.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:bt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:bt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:bt.string().describe("The release branch that was deployed"),version:bt.string().describe("The version that was deployed"),environment:bt.string().describe("The environment deployed to"),skipTerraformDeploy:bt.boolean().describe("Whether terraform deployment was skipped"),success:bt.boolean().describe("Whether the deployment was successful")},handler:ta});import sA from"@inquirer/checkbox";import{z as Ce}from"zod";import{$ as Xu}from"zx";var Rr="deploy-selected-services.yml",ov=br({workflowFile:Rr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),ra=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Xe({provider:ov,params:e,operation:"launch deploy-selected workflow",argument:T=>T[0]??"version"});let i=await is(t),a=xo(i);v.addOption("--version",a);let c=await ze(),l=At(await Ot(Rr),c),u="";r?u=r:(v.setInteractive(),u=await Cn(l,"launch deploy-selected workflow")),v.addOption("--env",u),Mr(u,"launch deploy-selected workflow",c),Hs({env:u,branch:i});let p=await $(),m=await ns(p,Rr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Rr}`,stderrExcerpt:`no services found in .github/workflows/${Rr}`});let f=[];if(n&&n.length>0?f=n:(v.setInteractive(),f=await N(T=>sA({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(S=>({name:S,value:S}))},T),{whenHeadless:"refuse"})),v.addOption("--services",f),f.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${m.join(", ")}`,stderrExcerpt:"no services selected"});let w=f.filter(T=>!m.includes(T));if(w.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${w.join(", ")}`});let h=await rs(p,Rr),y=f.filter(T=>{let S=h.get(T);return S!==void 0&&!S.includes(u)});if(y.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:y.map(T=>`${T} deploys only to: ${(h.get(T)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Rr} gates these services out of ${u}: ${y.join(", ")}`});let b=o??!1;b&&v.addOption("--skip-terraform",!0);let P=T=>{let S={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:b,success:T};return{content:R(JSON.stringify(S,null,2)),structuredContent:S}};if(!await ss({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),P(!1);try{Xu.quiet=!0;let T=f.flatMap(Z=>["-f",`${Z}=true`]);return await Xu`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${T} ${b?["-f","skip_terraform_deploy=true"]:[]}`,Xu.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),v.print(),P(!0)}catch(T){throw d.error({error:T},"\u274C Error launching workflow"),new g(T,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Zu=C({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:ov,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:Ce.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:Ce.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:Ce.array(Ce.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:Ce.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ce.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ce.string().describe("The release branch that was deployed"),version:Ce.string().describe("The version that was deployed"),environment:Ce.string().describe("The environment deployed to"),services:Ce.array(Ce.string()).describe("The services that were deployed"),skipTerraformDeploy:Ce.boolean().describe("Whether terraform deployment was skipped"),success:Ce.boolean().describe("Whether the deployment was successful")},handler:ra});import{z as Jt}from"zod";var na=async()=>{let t=(await L()).flatMap(i=>{let a=Y(i.branch);return a?[{version:Q(a),jiraKey:se(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await gi(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Po(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",u=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${u}${p}`});d.info(`All release branches:
|
|
382
390
|
`),d.info(`
|
|
383
391
|
${o.join(`
|
|
384
392
|
`)}
|
|
385
|
-
`);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:
|
|
386
|
-
`)};import
|
|
387
|
-
`).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),
|
|
388
|
-
${
|
|
389
|
-
`)),
|
|
390
|
-
- `);await
|
|
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:R(JSON.stringify(s,null,2)),structuredContent:s}},Qu=C({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:Jt.array(Jt.object({version:Jt.string().describe("Release version"),type:Jt.enum(["regular","hotfix"]).describe("Release type"),description:Jt.string().nullable().describe("Jira version description"),releaseDate:Jt.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:Jt.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:Jt.number().describe("Number of release branches")},handler:na});import iA from"node:process";var as="local-deploy";var ed=e=>({...e}),td=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=iA.env}=e,i={VITE_DOMAIN_ENV:t,VITE_BRANCH_NAME:r,VITE_COMMIT_HASH:o?n:`${n}-dirty`},a={},c=[];for(let[l,u]of Object.entries(s)){if(l.startsWith("VITE_")){c.push(l);continue}a[l]=u}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",INFRA_KIT_DEPLOY_VIA:as},contract:i,stripped:c}},oa=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(`
|
|
394
|
+
`)};import kA from"@inquirer/checkbox";import bA from"@inquirer/confirm";import RA from"@inquirer/select";import{spawn as SA}from"node:child_process";import EA from"node:process";import{z as X}from"zod";import{$ as ls}from"zx";import{$ as cs}from"zx";var aA=async e=>{let t=cs.quiet;cs.quiet=!0;try{let r=`/${e}/environment`,n=await cs`aws sts get-caller-identity --query Account --output text`,o=await cs`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new g(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{cs.quiet=t}},sv=(e,t)=>{if(t.stage!==e)throw new g(void 0,{operation:"verify the target environment",remediation:"switch AWS_PROFILE to the account for this environment, or pass the env this account is",stderrExcerpt:`you asked for "${e}", but AWS account ${t.accountId} reports "${t.stage}" \u2014 refusing to deploy to an environment you did not name`})},iv=e=>{let{env:t,isShared:r,isClean:n}=e;if(!(!r||n))throw new g(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"})},av=(e,t)=>{if(t.includes(e))throw new g(void 0,{operation:`deploy to "${e}"`,remediation:"wait for the CI run to finish, or watch it with `gh run watch`",stderrExcerpt:`a CI deploy to "${e}" is already in flight \u2014 running both would interleave`})},rd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Mr(t,`deploy to "${t}"`,i),av(t,s),iv({env:t,isShared:n,isClean:o});let a=await aA(r);return sv(t,a),{identity:a}};import cv from"node:fs/promises";import sa from"node:path";var cA="devops/scripts",lA=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,uA=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,dA=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,pA=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,nd=async e=>{let t=sa.resolve(e,cA),r;try{r=await cv.readdir(t)}catch{return[]}let n=await Uu(e);return(await Promise.all(r.map(s=>({entry:s,match:lA.exec(s)})).filter(s=>s.match!==null).map(async({entry:s,match:i})=>{let a=sa.resolve(t,s),c=i?.groups?.service??"",l=fA(await mA(a));return{name:c,scriptPath:a,allowedEnvs:Vu(gA(l),n.get(c)),ssmPrefix:yA(l)}}))).sort((s,i)=>s.name.localeCompare(i.name))},mA=async e=>{try{return await cv.readFile(e,"utf-8")}catch{return""}},fA=e=>e.split(`
|
|
395
|
+
`).map((t,r)=>({line:r+1,text:t})).filter(({text:t})=>!t.trimStart().startsWith("#")),gA=e=>{let t=e.reduce((n,{text:o})=>n??uA.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},hA=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},yA=e=>{for(let{line:t,text:r}of e){let n=pA.exec(r)?.groups?.prefix;if(n!==void 0)return n;let o=dA.exec(r)?.groups?.arg;if(o!==void 0&&hA(o))return{unparseable:{line:t,text:r.trim()}}}return null},vA=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],sa.basename(r.scriptPath)]);return t},wA=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${sa.basename(r.scriptPath)}:${n}: ${o}`]});if(t.length!==0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"write the parameter name as a literal `/<project>/environment` so infra-kit can preflight it",stderrExcerpt:t.join("; ")})},lv=e=>{wA(e);let t=vA(e),[r,...n]=t.keys();if(r===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'add `aws ssm get-parameter --name "/<project>/environment"` to at least one devops/scripts/deploy-*.sh',stderrExcerpt:`none of ${e.length} deploy scripts reads /<project>/environment`});if(n.length>0){let o=[...t.entries()].sort(([,s],[,i])=>s.length-i.length).map(([s,i])=>`${s}: ${i.join(", ")}`).join("; ");throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:"make every deploy script read the same /<project>/environment parameter",stderrExcerpt:`${t.size} different prefixes across ${e.length} deploy scripts \u2014 ${o}`})}return r},ia=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),od=(e,t)=>e.filter(r=>ia(r,t));var id="deploy-all.yml",dv="/bin/sh",PA=async()=>{let e=ls.quiet;ls.quiet=!0;try{let t=await ls`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{ls.quiet=e}},xA=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await N(o=>kA({message:`Deploy which services to ${t}?`,choices:r,pageSize:20},o),{whenHeadless:{refuse:"service"}});if(n.length===0)throw new g(void 0,{operation:"select services",remediation:"pick at least one service, or use `local deploy-all`",stderrExcerpt:"no services selected"});return n},TA=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 q()&&Js(i,{env:t,services:n,accountId:o,shared:r}),r?N(a=>RA({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):N(a=>bA({message:i,default:!1},a),{whenHeadless:"refuse"})},CA=(e,t,r)=>new Promise((n,o)=>{let s=SA(dv,[e.scriptPath],{cwd:r,env:t,stdio:"inherit"});s.on("error",o),s.on("close",i=>{n(i??1)})}),$A=async e=>{let{chosen:t,childEnv:r,cwd:n,env:o}=e,s=[],i=[];for(let a of t){d.info(`\u2192 ${a.name} \u2192 ${o}`);let c=await CA(a,r,n);if(c!==0){i.push(a.name),d.error(`\u2717 ${a.name} failed (exit ${c})`);break}s.push(a.name),d.info(`\u2713 ${a.name}`)}return{deployed:s,failed:i}},AA=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 g(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&&!ia(c,n)});if(i.length>0)throw new g(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:R(JSON.stringify(l,null,2)),structuredContent:l}},OA=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:(v.setInteractive(),xA(r,o))},pv=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await $(),c=await nd(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has devops/scripts/deploy-*.sh",stderrExcerpt:`no deploy scripts found under ${a}/devops/scripts`});let l=lv(c);await Xe({provider:ad[t],params:e,operation:"deploy locally",argument:"env"});let u=await ze(),p=At(await Ot(id),u),m=r??"";m||(v.setInteractive(),m=await Cn(p,"deploy locally")),v.addOption("--env",m);let f=od(c,m);if(f.length===0)throw new g(void 0,{operation:`deploy to "${m}"`,remediation:"pick an environment these services allow",stderrExcerpt:`no service on disk is enabled for "${m}"`});let w=await OA({selection:t,eligible:f,service:n,env:m}),h=AA({names:w,services:c,env:m});if(t==="selected")for(let Tr of w)v.addOption("--service",Tr);let y=Yn(m),b=await Ir(),P=(await ls`git rev-parse HEAD`.quiet()).stdout.trim(),T=await km(),S=td({env:m,branch:b,sha:P,isClean:T});i&&d.info(`Deploy contract for ${m}:
|
|
396
|
+
${oa(S)}`);let j=(await rd({env:m,project:l,isShared:y,isClean:T,runningEnvs:await PA(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${j}) from this machine`,`Preflight parameter: /${l}/environment`,oa(S),"Commands:",...h.map(Tr=>` ${dv} ${Tr.scriptPath}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
|
|
397
|
+
`)),sd({env:m,accountId:j,names:w,built:S,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await TA({env:m,isShared:y,names:w,accountId:j}))return d.info("Deployment cancelled"),sd({env:m,accountId:j,names:w,built:S,deployed:[],failed:[],dryRun:!1,success:!1});S.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${S.stripped.join(", ")}`);let{deployed:dt,failed:zt}=await $A({chosen:h,childEnv:S.childEnv,cwd:a,env:m});return zt.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${dt.join(", ")||"none"}], failed [${zt.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),EA.exitCode=1),v.print(),sd({env:m,accountId:j,names:w,built:S,deployed:dt,failed:zt,dryRun:!1,success:zt.length===0})},mv=async e=>pv(e,"all"),fv=async e=>pv(e,"selected"),gv='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.',hv={env:X.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:X.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:X.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},yv={environment:X.string().describe("Environment deployed to"),accountId:X.string().describe("AWS account the deploy targeted"),services:X.array(X.string()).describe("Services requested"),deployed:X.array(X.string()).describe("Services that completed successfully"),failed:X.array(X.string()).describe("Services that failed"),contract:X.record(X.string(),X.string()).describe("Build contract passed to the scripts"),strippedVars:X.array(X.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:X.boolean().describe("Whether this was a dry run"),success:X.boolean().describe("Whether every requested service deployed")},uv=e=>br({workflowFile:id,fields:["env"],toolName:e}),ad={all:uv("local-deploy-all"),selected:uv("local-deploy-selected")},cd=C({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${gv}`,requiresHumanConfirm:!0,formProvider:ad.all,inputSchema:hv,outputSchema:yv,handler:mv}),ld=C({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${gv}`,requiresHumanConfirm:!0,formProvider:ad.selected,inputSchema:{...hv,service:X.array(X.string()).min(1).describe('Service names as in devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:yv,handler:fv});import NA from"@inquirer/confirm";import aa from"@inquirer/input";import bv from"@inquirer/select";import dd from"node:process";import{z as W}from"zod";import{z as us}from"zod";var $n=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var kv=2500,vv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),wv=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,DA=async()=>{let e=await Vo();return{regular:En(e,"regular"),hotfix:En(e,"hotfix")}},IA=(e,t)=>e===null?(d.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?(d.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).`,ud=(e={})=>{let t=e.hintBudgetMs??kv;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=>vv(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await $n(DA(),t);return us.object({type:us.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:us.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. ${IA(r,t)}`),description:us.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:us.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=wv(r.description),a=wv(r.releaseDate),c=Fi(o);return{...vv(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var _A='"1.2.5" or "next"',pd=(e,t)=>{try{return iu(e,t)}catch(r){throw r instanceof mr?new g(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 hm?new g(r,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):r}},MA=async(e,t)=>{let r=En(e,t),n=r?` [${r}]`:"",o=(await N(i=>aa({message:` Version (e.g. ${_A})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),dd.exit(1)),s},jA=async()=>{let e=(await N(t=>aa({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),dd.exit(1));try{Fs(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),dd.exit(1)}return e},FA=async()=>(await N(e=>aa({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Uo},e),{whenHeadless:"refuse"})).trim(),LA=async e=>{v.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 N(m=>bv({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 N(m=>bv({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 jA();l=pd([{name:m,type:c}],[])[0]}else{let m=await MA(await n(),c);l=pd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Ut(`v${l.id.raw}`))}let u=(await N(m=>aa({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await FA();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await N(m=>NA({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},BA=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 ")},Rv=e=>{for(let t of e)v.addOption("--release",su(t))},UA=async(e,t)=>{if(e&&e.length>0){let n=au(e)?await t():[],o=pd(e,n);return Rv(o),o}if(pe())throw new A({status:"argument_required",argument:"release",agentMode:_.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 LA(t);return Rv(r),r},VA=e=>{if(new Set(e.map(r=>r.type)).size>1)throw new g(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},WA=async(e,t)=>{let r=e.map(BA).join(`
|
|
398
|
+
- `);await U(t,`Create the following ${e.length} release(s)?
|
|
391
399
|
- ${r}
|
|
392
|
-
`),
|
|
393
|
-
`),{result:i}}catch(s){let i=
|
|
394
|
-
`),{failure:{version:n,error:a.message}}}},
|
|
395
|
-
${
|
|
400
|
+
`),v.addOption("--yes",!0)},GA=async e=>{let{entry:t,jiraConfig:r}=e,n=Q(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await zr({operation:`create release ${o}`});let s=await Sl(t.type),i=await El({id:t.id,jiraConfig:r,description:t.description,...t.releaseDate===void 0?{}:{releaseDate:t.releaseDate},type:t.type,baseSha:s});return d.info(`\u2705 Successfully created release: ${o} (${t.type})`),d.info(`\u{1F517} GitHub PR: ${i.prUrl}`),d.info(`\u{1F517} Jira Version: ${i.jiraVersionUrl}
|
|
401
|
+
`),{result:i}}catch(s){let i=So(s)?s:void 0,a=new g(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 d.error(`\u274C ${a.message}
|
|
402
|
+
`),{failure:{version:n,error:a.message}}}},JA=(e,t,r)=>{t===e?d.info(`\u2705 All ${e} release branch(es) were created successfully.`):t>0?(d.warn(`\u26A0\uFE0F ${t} of ${e} release branches were created successfully.`),d.warn(`\u274C ${r} release(s) failed.`)):d.error(`\u274C All ${e} release branch(es) failed to create.`)},Sv=ud(),ca=async e=>{let{releases:t,confirmedCommand:r}=e;await xe({operation:"create release"}),await Xe({provider:Sv,params:e,operation:"create release",argument:"release"});let n=await nn(),o=null,i=await UA(t,async()=>(o===null&&(o=await Vo()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});VA(i),await vo({operation:"create release",base:nt(i[0].type)}),await WA(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await GA({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}JA(i.length,a.length,c.length),v.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},md=C({name:"release-create",requiresHumanConfirm:!0,formProvider:Sv,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:W.array(W.object({version:W.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:W.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:W.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:W.string().optional().describe("Optional description for the Jira version."),releaseDate:Zl.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:W.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:W.array(W.string()).describe("List of created release branch names"),successCount:W.number().describe("Number of releases created successfully"),failureCount:W.number().describe("Number of releases that failed"),releases:W.array(W.object({version:W.string().describe("Version number"),type:W.enum(["regular","hotfix"]).describe("Release type"),branchName:W.string().describe("Release branch name"),prUrl:W.string().describe("GitHub PR URL"),jiraVersionUrl:W.string().describe("Jira version URL"),releaseDate:W.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:W.array(W.object({version:W.string().describe("Version number that failed"),error:W.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:ca});import Ev from"@inquirer/input";import{z as Ue}from"zod";var Pv=["description","releaseDate"],KA=async()=>{let e=await L(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await le(),o=await jt(ue({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},HA=async e=>{let r=(await L()).find(n=>n.branch===e);if(!r)throw new g(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},qA=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await N(o=>Ev({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},YA=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await N(o=>Ev({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Uo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:pr(n)},zA=e=>{if(e!==void 0)return e===""?null:e},XA=async e=>(v.setInteractive(),{description:await qA(e.description),releaseDate:await YA(e.releaseDate)}),fd=e=>e??"(none)",ZA=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${fd(t.releaseDate)} \u2192 ${fd(r.releaseDate)}`,la=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=zA(n),i=await nn(),a;t?(a=vt(t),await HA(a)):(v.setInteractive(),a=(await KA()).branch);let c=Y(a);if(!c)throw new g(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=Q(c);v.addOption("--version",l);let u=se(c),p=await ht(u,i);if(!p)throw new g(void 0,{operation:`edit release ${u}`,remediation:`create the Jira fix version "${u}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},f=r!==void 0||s!==void 0;if(!f&&q())throw new A({status:"argument_required",argument:"description",agentMode:_.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 w=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await XA(m),h=Pv.filter(Z=>w[Z]!==m[Z]),y=h.includes("description"),b=h.includes("releaseDate"),P=cr(i,p),T=Z=>{let j={version:l,branch:a,jiraVersionUrl:P,previousDescription:m.description,newDescription:w.description,previousReleaseDate:m.releaseDate,newReleaseDate:w.releaseDate,changedFields:h,changed:Z};return{content:R(JSON.stringify(j,null,2)),structuredContent:j}};if(h.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${fd(m.releaseDate)}`),v.print(),T(!1);y&&v.addOption("--description",w.description),b&&v.addOption("--release-date",w.releaseDate??"");let S=h.map(Z=>ZA(Z,m,w));return await U(o,`Update ${u}?
|
|
403
|
+
${S.join(`
|
|
396
404
|
`)}
|
|
397
|
-
`),
|
|
398
|
-
`),
|
|
399
|
-
`).map(r=>r.trimEnd()).filter(r=>r.length>0),
|
|
400
|
-
`)},
|
|
401
|
-
`).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=
|
|
402
|
-
`).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},
|
|
405
|
+
`),v.addOption("--yes",!0),await rn({versionId:p.id,...y?{description:w.description}:{},...b?{releaseDate:w.releaseDate}:{}},i),y&&await pi({branch:a,body:Ro(P,w.description)}),d.info(`\u2705 Updated ${h.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${P}`),d.info(`\u{1F517} PR branch: ${a}
|
|
406
|
+
`),v.print(),T(!0)},gd=C({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:Ue.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ue.string().optional().describe("New description. Empty string clears the description."),releaseDate:Ql.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ue.string().describe("Release version"),branch:Ue.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ue.string().describe("Jira fix version URL"),previousDescription:Ue.string().describe("The description before the update"),newDescription:Ue.string().describe("The description after the update"),previousReleaseDate:Ue.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ue.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ue.array(Ue.enum(Pv)).describe("The fields whose value actually changed"),changed:Ue.boolean().describe("Whether anything actually changed")},handler:la});import{z as oe}from"zod";import{$ as yd}from"zx";import{z as xv}from"zod";var $v=2500,ua="release-remove",Tv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),QA=e=>e.version===void 0||e.version==="",eO=async()=>{try{return{outcome:"listed",prs:await L()}}catch(e){return e instanceof g&&e.operation===ko?{outcome:"empty"}:{outcome:"failed"}}},Cv=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${ua}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${ua}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${ua}`}),null),tO=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return hi(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(se(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},rO=(e,t,r)=>{let n=e.map(o=>o.prose).join("; ");return t!==null?`Open release PRs right now: ${n}. `:(d.info({msg:`Tool execution form descriptions unavailable (timeout): ${ua}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},hd=(e={})=>{let t=e.fetchBudgetMs??$v;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=>Tv(r)&&QA(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([$n(eO(),t),$n(le(),t)]);if(r===null||r.outcome!=="listed")return Cv(r,t);let o=tO(r.prs,n);return o.length===0?Cv({outcome:"empty"},t):xv.object({version:xv.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${rO(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:{...Tv(n)?n:{},version:r.version}}};var Av=["worktree","pr","local-branch","remote-branch","jira"],Iv={worktree:"remove the worktree",pr:"close the PR","local-branch":"delete the local branch","remote-branch":"delete the remote branch",jira:"remove the Jira fix version"},Sr="remove a release",Ke=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Ov=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new A({...e,agentMode:_.source},2,t)},nO=e=>{pe()&&(e.version||Ov({status:"argument_required",argument:"version"},{operation:Sr,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&&Ov({status:"refused"},{operation:Sr,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"}))},Nv=e=>{e.pr?.state==="MERGED"&&Ke({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`})},oO=(e,t)=>{if(t.skipJira||(e.jiraConfig||Ke({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)&&Ke({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||Ke({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)`}))},sO=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;Ke({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"})},iO=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||Ke({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(", ")}`})},aO=async e=>(await yd`git -C ${e} status --porcelain`).stdout.split(`
|
|
407
|
+
`).map(r=>r.trimEnd()).filter(r=>r.length>0),cO=async e=>{try{let{terminals:t}=await Zm(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},lO=async e=>{let t=await Ks([e]);if(t!==null)throw d.warn({operation:Sr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new A({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:Sr,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`})},uO=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await yt();if(!n)return r;let o=await ht(se(e),n),s=t.moveIssuesTo?await dO(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await fi(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:cr(n,o)}}},dO=async(e,t)=>{let r=await ht(e,t);return r||Ke({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}"`})},pO=async(e,t)=>{let r=Y(e);r||Ke({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=`${`${n}${de}`}/${e}`,[i,a,c,l]=await Promise.all([he("release"),Zr(e),Ie(n,`refs/heads/${e}`),Nr(n,e)]),u=i.includes(e);return u&&await lO(s),{...await uO(r,t),branch:e,id:r,label:Q(r),baseBranch:a?.baseRefName??nt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await cO(s):0,worktreeDirty:u?await aO(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Dv=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}),mO=(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}`},fO=(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: ${mO(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
|
|
408
|
+
`)},da=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},gO=e=>typeof e=="string"?e:e.outcome;async function ds(e,t,r){try{let n=await r(),o=gO(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${Iv[e]} \u2014 ${o}`),n}catch(n){throw new da(e,n)}}var hO=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,yO=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>hO(t,p)).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}`,u=o instanceof g?o.remediation:void 0;return new g(o,{operation:`remove release ${t.label} \u2014 step ${Av.indexOf(r)+1} of ${Av.length} (${Iv[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},vO=async e=>(await es(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`})).includes(e.branch)?"removed":"absent",wO=async e=>{let t=await Zr(e.branch);if(Nv({...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 yd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},kO=async e=>(await Ir()===e.branch&&await yd`git switch ${e.baseBranch}`,await Ls(e.branch),await Rm(e.branch)?Ke({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"),bO=async e=>(await Bs(e.branch),e.remoteTipSha?"deleted":"absent"),RO=async(e,t,r)=>{let n=await fi(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}\``;Ke({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}`})},SO=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await RO(e,e.jira,e.jiraConfig),d.info({jiraVersionId:e.jira.version.id,jiraVersionName:e.jira.version.name},"\u{1F5D1}\uFE0F removing Jira fix version"),await Rl({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),EO=(e,t)=>({branch:e.branch,version:e.label,baseBranch:e.baseBranch,worktree:t.worktree,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}),PO=async(e,t,r)=>{let n=await ds("worktree",r,()=>vO(e)),o=await ds("pr",r,()=>wO(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await ds("local-branch",r,()=>kO(e)),i=await ds("remote-branch",r,()=>bO(e)),a=await ds("jira",r,()=>SO(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},xO=async(e,t)=>{let r=[];try{return EO(e,await PO(e,t,r))}catch(n){throw n instanceof da?yO({plan:e,step:n.step,done:r,cause:n.reason}):n}},TO=async e=>{if(e)return vt(e);v.setInteractive();let[t,r]=await Promise.all([le(),L()]),n=r.map(s=>s.branch);n.length===0&&Ke({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 jt(ue({branches:n,descriptions:t,types:o}))}catch(s){throw Se(s)?s:new g(s,{operation:"select a release to remove",remediation:"pass `--version <ref>` (e.g. `--version 1.2.5`); the picker needs an interactive terminal"})}},_v=hd(),pa=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await xe({operation:Sr}),await G(),await Xe({provider:_v,params:e,operation:Sr,argument:"version"}),nO(e);try{let s=await pO(await TO(r),e);d.debug({plan:Dv(s)},"release remove: resolved plan"),Nv(s),oO(s,e),sO(s),await vo({operation:`remove release ${s.label}`,base:s.baseBranch}),iO(s),v.addOption("--version",s.label),n&&v.addOption("--move-issues-to",n),o&&v.addOption("--skip-jira",!0),await U(t,fO(s,!!o),{throwOnDecline:!0,plan:{...Dv(s),skipJira:!!o}}),t||v.addOption("--yes",!0);let i=await xO(s,e);return v.print(),{content:R(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Se(s)||mt(s)||s instanceof g?s:(d.error({err:vr(s)},"\u274C Error removing release"),new g(s,{operation:Sr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},vd=C({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), 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:_v,inputSchema:{version:oe.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:oe.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:oe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:oe.string().describe("The release branch that was targeted"),version:oe.string().describe('The release label (e.g. "1.2.5")'),baseBranch:oe.string().describe("The branch HEAD was moved to before the local delete"),worktree:oe.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:oe.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:oe.number().nullable().describe("The pull request number, or null when none exists"),localBranch:oe.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:oe.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:oe.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:oe.string().nullable().describe("The origin tip before deletion"),jira:oe.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:oe.object({id:oe.string(),name:oe.string(),url:oe.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:pa});import{spawn as OO}from"node:child_process";import DO from"node:fs";import{homedir as IO}from"node:os";import fa from"node:process";import ma from"node:fs";import An from"node:path";var CO=e=>{try{return ma.statSync(e).isFile()?ma.readFileSync(e,"utf8"):null}catch{return null}},$O=e=>{try{return ma.realpathSync(e)}catch{return e}},AO=(e,t)=>{let o=t(An.join(e,".git"))?.split(`
|
|
409
|
+
`).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=An.resolve(e,o),i=`${An.sep}.git${An.sep}worktrees${An.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},Mv=(e={})=>{let t=e.listInstallations??sc,r=e.exists??ma.existsSync,n=e.readGitFile??CO,o=e.realpath??$O,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=AO(i.projectPath,n);if(!r(An.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var NO=180*1e3,_O=900*1e3,MO=4*1024*1024,jO=2e3,FO=e=>new Promise(t=>{let r={stdout:"",stderr:""},n=!1,o=!1,s,i=(u,p)=>{n||(n=!0,clearTimeout(s),t({status:u,stdout:r.stdout,stderr:r.stderr,error:p}))},a=OO(e.command,[...e.args],{cwd:e.cwd,env:e.env,stdio:["ignore","pipe","pipe"],detached:!0,windowsHide:!0});s=setTimeout(()=>{o=!0;try{a.pid!==void 0&&fa.kill(-a.pid,"SIGKILL")}catch{}i(null,`timed out after ${Math.round(e.timeoutMs/1e3)}s`)},e.timeoutMs);let c=u=>p=>{r[u].length<MO&&(r[u]+=p.toString("utf8"))};a.stdout.on("data",c("stdout")),a.stderr.on("data",c("stderr")),a.on("error",u=>{i(null,u.message)});let l=(u,p)=>{i(u,o||p===null?null:`killed by ${p}`)};a.on("close",l),a.on("exit",(u,p)=>{setTimeout(()=>{l(u,p)},jO).unref()})}),LO=({cwd:e,timeoutMs:t})=>FO({command:fa.execPath,args:[fa.argv[1]??"","setup","--unattended","--json"],cwd:e,env:Km(fa.env),timeoutMs:t}),BO=e=>{DO.writeFileSync(dn(),e,{mode:384})},UO=e=>{try{let t=JSON.parse(e);return!Array.isArray(t?.init)||!Array.isArray(t.tools)||typeof t.portlessService!="object"?null:t}catch{return null}},VO=new RegExp("\x1B\\[[0-9;]*m","g"),WO=e=>{if(e.error!==null)return e.error;try{let n=JSON.parse(e.stdout),o=n?.message??n?.error;if(typeof o=="string"&&o!=="")return o}catch{}let t=e.stderr.replace(VO,"").split(`
|
|
410
|
+
`).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},GO=(e,t)=>{let r=[],n=[];for(let a of e.init)a.outcome==="failed"?r.push(a.message):(a.outcome==="manual"||a.outcome==="warned")&&n.push(a.message);for(let a of e.tools)a.action==="failed"?r.push(`${a.id}: ${a.detail}`):a.before.present||n.push(`${a.id} is not installed \u2014 run: infra-kit setup --tools ${a.id}`);let{link:o,node:s,command:i}=e.portlessService;return(o==="failed"||s==="failed")&&r.push(`portless: link ${o}, node ${s}`),i!==null&&n.push(i),r.length===0&&t!==0&&r.push(`setup exited ${String(t)}`),r.length>0?{status:"failed",notes:[...r,...n]}:{status:n.length>0?"attention":"ok",notes:n}},jv=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":Oi(e);if(o<=0)return{root:e,status:"failed",notes:[`out of time budget \u2014 run: ${s}`]};try{let i=await r.runSetupChild({cwd:t,timeoutMs:Math.min(NO,o)}),a=i.error===null?UO(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${WO(i)} \u2014 run: ${s}`]}:{root:e,...GO(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},JO=e=>{let t=e.find(n=>n.root===null),r=new Set(t?.notes??[]);return e.map(n=>{if(n.root===null||n.status==="failed")return n;let o=n.notes.filter(s=>!r.has(s));return{...n,notes:o,status:n.status==="attention"&&o.length===0?"ok":n.status}})},KO=e=>{let t=[`infra-kit ${e.version} unattended setup \u2014 ${new Date(e.finishedMs??e.startedMs).toISOString()} (attempt ${e.attempts})`];for(let r of e.runs){t.push("",`${r.status.padEnd(9)} ${r.root??"machine"}`);for(let n of r.notes)t.push(` ${n}`)}return`${t.join(`
|
|
403
411
|
`)}
|
|
404
|
-
`},
|
|
405
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),dO=e=>{let t=lv(e.stderr),r=lv(e.stdout),n=[...t,...r].filter(s=>uO.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-lO).join(" / ")},pO="ENOBUFS",mO=e=>e.error?.code===pO,fO=e=>{if(mO(e))return`terminated after exceeding the ${uv} 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=dO(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var gO=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},hO=e=>{let t=Le(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},yO=(e,t)=>{let r=hO(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=ss(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:is(r),context:n}},ra=async(e=ur,t=Oo())=>{let r=await Do(ur,t),n={owner:null,present:gO(r)},o=_l(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>yO(s.get(a),n)),context:n}};var Zu=(e,t)=>({...as(e),action:"skipped",commands:e.commands,detail:t}),as=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),dv=(e,t)=>e.action==="none"?Zu(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?Zu(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...as(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},vO=(e,t)=>t.ran?t.ok?{...as(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...as(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...as(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Qu=async e=>{let t=e.run??Xu,{plans:r}=await ra(e.ids,e.probeDeps),n=[];for(let o of r){let s=dv(o,e.mode);if(s!==null){n.push(s);continue}n.push(vO(o,t(o.recipe,o.context)))}return n},ed=async(e,t)=>{let{plans:r}=await ra(e,t);return r.map(n=>dv(n,"converge")??Zu(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import NO from"node:process";import{z as O}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,"token-perms":10,chrome:11,shell:12},wO=Object.keys(td).sort((e,t)=>td[e]-td[t]),pv={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},mv=new Set(["manual","warn","fail"]),rd=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 Ne(e)}},kO=e=>e.reduce((t,r)=>pv[r]>pv[t]?r:t,"skipped"),gv=e=>e.message.trim(),bO=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 "),fv=e=>e.message===gn,RO=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?gv(r):e.length>1?bO(e):t?"activate with the last line below":"see below"},SO=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>rd(i.outcome)),n=t.filter(i=>mv.has(rd(i.outcome))).map(gv),o=t.filter(i=>!mv.has(rd(i.outcome))&&!fv(i)),s={name:e,status:kO(r),message:RO(o,t.some(fv))};return n.length>0?{...s,notes:n}:s},EO=e=>({label:"Local setup",rows:wO.map(t=>SO(t,e.filter(r=>r.step===t)))}),PO=(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 Ne(e.action)}},xO=(e,t)=>{let r=PO(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},TO=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>xO(r,t))}),CO=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 Ne(e)}},$O=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 Ne(e)}},AO=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 Ne(e)}},OO=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 Ne(e.outcome)}},IO=(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 Ne(e)}},DO=e=>({label:"Portless service",rows:[{name:"link",status:CO(e.link),message:AO(e.link)},{name:"node",status:$O(e.node.outcome),message:OO(e.node)},IO(e.service,e.command)]}),hv=(e,t)=>[EO(e.init),TO(e.tools,t),DO(e.portless)],yv=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var _O=()=>{let{link:e,node:t}=Ts();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},MO=async e=>{let t=Hp(e.link).outcome,r=Kp(e.node),n=xs(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 Kh(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=St(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},wv="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",kv="--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.",jO=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.unattended===!0,o=e.skipTools===!0||n;if(n&&(e.tools!==void 0||r))throw new Error(wv);if(o&&(e.tools!==void 0||r))throw new Error(kv);return{ids:e.tools??t??ur,mode:r?"update":"converge",skipTools:o}},vv=(e,t)=>e instanceof fn?e.step:t.at(-1)?.step??"zshrc",FO=async()=>{let e=[];try{await Cl(t=>{e.push(t)})}catch(t){e.push({step:vv(t,e),outcome:"failed",message:`The ${vv(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},LO=(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}`}))},BO=async(e,t)=>{try{return e.skipTools?await ed(e.ids,t.probeDeps):await Qu({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return LO(e.ids,r)}},UO=e=>({step:e.step,outcome:e.outcome,message:e.message}),na=async(e={})=>{let t=jO(e);Ge.withheld=e.unattended===!0;let r=await FO(),n=await BO(t,e),o=await MO(e.portlessDeps??_O()),s=hv({init:r,tools:n,portless:o},{skipTools:t.skipTools});rt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(gn),yv(s)&&(NO.exitCode=1);let i={init:r.map(UO),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}},VO=O.object({step:O.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","token-perms","chrome","shell"]).describe("Which init step this reports on"),outcome:O.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:O.string().describe("The same line a human running this would have read")}),WO=O.object({id:O.string().describe("Dependency id"),action:O.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:O.object({present:O.boolean(),onPath:O.boolean(),version:O.string().nullable(),manager:O.string()}).describe("The tool\u2019s state before this run"),commands:O.array(O.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:O.string().describe("Why, in one line")}),GO=O.object({link:O.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:O.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:O.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:O.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")}),JO={init:O.array(VO).describe("One entry per init step, in the order they ran"),tools:O.array(WO).describe("One result per requested dependency"),portlessService:GO.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:O.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:O.boolean().describe("Whether anything was installed or updated"),report:O.array(O.object({label:O.string().describe("Section heading"),rows:O.array(O.object({name:O.string().describe("Init step, tool id, or portless part"),status:O.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:O.string().describe("The row message, as printed"),notes:O.array(O.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:O.boolean().describe("Whether no tool failed (a refusal is not a failure)")},KO={tools:O.array(O.enum(ur)).optional().describe("Which tools to act on. Omit for all six."),mode:O.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:O.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},nd=E({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, check the agent-instruction files (never rewritten here: drift is reported with the `audit --fix` command that refreshes them), 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:KO,outputSchema:JO,requiresHumanConfirm:!0,handler:e=>na({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Rv}from"node:fs";import Sv from"node:path";import nI from"node:process";import{z as bt}from"zod";import{createHash as HO}from"node:crypto";import{readFileSync as qO}from"node:fs";var Rr=e=>HO("sha256").update(qO(e)).digest("hex");import{readFileSync as eI,writeFileSync as tI}from"node:fs";import aa from"node:path";import{z as lt}from"zod";var Q="vendor",YO=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),zO=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),XO=[".tsbuildinfo"],od=e=>YO.has(e),sd=e=>zO.has(e)?!0:XO.some(t=>e.endsWith(t)),oa=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>od(o))||sd(r)};import{readdirSync as ZO}from"node:fs";import id from"node:path";var QO=e=>e.split(id.sep).join("/"),sa=e=>{let t=[],r=n=>{for(let o of ZO(n,{withFileTypes:!0})){let s=id.join(n,o.name);if(o.isDirectory()){if(od(o.name))continue;r(s);continue}sd(o.name)||t.push(QO(id.relative(e,s)))}};return r(e),t.sort()};var Ve=".sync-manifest.json",ia=1,rI=lt.object({schemaVersion:lt.number().optional(),source:lt.string(),commit:lt.string(),syncedAt:lt.string(),fileCount:lt.number(),files:lt.record(lt.string(),lt.string())}),ad=e=>(e.schemaVersion??ia)>ia,bv=(e,t)=>{let r={},n=t?[...new Set(t)].sort():sa(e);for(let o of n)try{r[o]=Rr(aa.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},cs=e=>{let t=aa.join(e,Ve),r;try{r=eI(t,"utf8")}catch{throw new Error(`Missing ${Ve} at ${t}`)}let n=rI.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ve} at ${t}: ${lt.prettifyError(n.error)}`);return n.data},cd=(e,t,r)=>{let n=bv(e,r),o={schemaVersion:ia,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return tI(aa.join(e,Ve),`${JSON.stringify(o,null,2)}
|
|
406
|
-
`),o},
|
|
407
|
-
${e} (${t.length}):`);for(let r of t.slice(0,ud))d.info(` ${r}`);t.length>ud&&d.info(` \u2026and ${t.length-ud} more`)}},ca=async(e={})=>{let t=e.cwd??await P(),r=Sv.join(t,Q),n={modified:[],added:[],removed:[],fileCount:0};if(!Rv(r)){d.info(`\u2139\uFE0F No ${Q}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}if(!Rv(Sv.join(r,Ve))){d.error(`\u274C Missing ${Q}/${Ve}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let o=cs(r);if(ad(o)){d.error(`\u274C ${Q}/${Ve} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=ld(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${Q}/ has drifted from ${Q}/${Ve}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),dd("Modified",s),dd("Added (not in manifest)",i),dd("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${Q}/ 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}},oI={status:bt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:bt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:bt.number(),modified:bt.array(bt.string()),added:bt.array(bt.string()),removed:bt.array(bt.string())},pd=E({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:oI,handler:()=>ca({cwd:nI.cwd()})});import Ev from"node:process";import{z as ls}from"zod";var Pv=async e=>{try{return await e()}catch{return null}},la=async()=>{let e=U.version;d.info(e);let t=await Pv(P),r=t===null?null:await Pv(()=>Re(t)),n={version:e,cwd:Ev.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Ev.env.CLAUDE_PROJECT_DIR||null};return{content:k(JSON.stringify(n,null,2)),structuredContent:n}},md=E({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:ls.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:ls.string().describe("The working directory of this process"),repoRoot:ls.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:ls.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:ls.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:la});import Fv from"@inquirer/confirm";import uI from"node:path";import{z as M}from"zod";import{$ as ds}from"zx";import sI from"@inquirer/input";import Tv from"@inquirer/select";import{$ as Jt}from"zx";var us="dev",iI="main",fd="feature/",Cv=["new","local","remote"],ua=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${fd}${t}`},$v=async()=>{let e=await Jt({nothrow:!0,quiet:!0})`git symbolic-ref --quiet --short refs/remotes/origin/HEAD`,t=e.exitCode===0?e.stdout.trim().replace(/^origin\//,""):"";return t===""?null:t},aI=2,gd=async()=>{let e=await Jt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${us}`;if(e.exitCode===0)return us;if(e.exitCode!==aI)throw new g(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${us} exists`});return await $v()??us},Av=async e=>{let t=e?.trim();return t?t===us||t===iI||t===await $v()?t:ke(me(t)):gd()},Ov=async()=>I(e=>Tv({message:"What kind of worktree?",choices:[{name:"Release \u2014 worktrees for open release branches",value:"release"},{name:"Feature \u2014 a new or existing feature/* branch",value:"feature"}]},e),{whenHeadless:{value:"release"}}),Iv=async()=>I(e=>sI({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>ua(t)===fd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Dv=async(e,t)=>e.length===0?t:I(r=>Tv({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),cI=async e=>{let t=await Jt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===fd||t.exitCode!==0)throw new g(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},xv=async e=>(await Jt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,lI=async e=>(await Jt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Nv=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(ua))];for(let s of n)await cI(s);if(!await xv(r))throw new g(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await lI(s)?o.push({branch:s,base:r,source:"local"}):await xv(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},_v=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await Jt`git worktree add ${t} ${r}`:o==="remote"?await Jt`git worktree add --track -b ${r} ${t} origin/${r}`:await Jt`git worktree add --no-track -b ${r} ${t} origin/${n}`},Mv=e=>e.source==="new"?` \u2022 ${e.branch}: new branch from origin/${e.base}`:` \u2022 ${e.branch}: existing ${e.source==="local"?"local":"remote"} branch (base not applied)`;var ps="create worktrees",dI=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],hd=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),da=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await xe({operation:ps}),pI(e);try{let o=await P(),s=`${o}${le}`;await jv(`${s}/${Cr.release}`),await jv(`${s}/${Cr.feature}`);let i=await mI(e),a=i==="feature"?await gI(e):await fI(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),h.print();let D={kind:i,createdWorktrees:[],count:0,features:[],...hd()};return{content:k(JSON.stringify(D,null,2)),structuredContent:D}}let c=await W(),l=await hI(r,c),u=await yI(n,c),p=await Re(o),m=uI.basename(p),f=u?await vI({explicit:n!==void 0,mainRepoRoot:p}):null;await L(t,wI(f,m,a.previewLines)),t||h.addOption("--yes",!0);let y=f?await kI(f,p):null,b=await PI(a.targets,s);if(xI(b),l)for(let D of b)await ds`github ${s}/${D}`,await ds`sleep 5`;let w=y?await RI({registration:y,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):hd();SI(w),h.print();let x={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(D=>b.includes(D.branch)),...w};return{content:k(JSON.stringify(x,null,2)),structuredContent:x}}catch(o){throw Se(o)||o instanceof C?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:ps,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},pI=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new g(void 0,{operation:ps,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},mI=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Ov()),fI=async e=>{let{all:t,versions:r}=e,n=await fe("release"),o=[];if(r)o=r.split(",").map(a=>ke(me(a.trim())));else{let a=await F(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{h.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await ae();o=await jt(ce({branches:c,descriptions:u,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",vt(o));let{branchesToCreate:s}=EI({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>ds`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},gI=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await Iv()],n===void 0)){let l=(await F()).map(u=>u.branch);n=await Dv(l,await gd())}let o=await Av(n),s=await Nv({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await fe("feature"),a=s.filter(l=>i.includes(l.branch)?(d.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:u=>_v(l,u)})),features:a,previewLines:a.map(Mv)}},hI=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await I(o=>Fv({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},yI=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await I(o=>Fv({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},Lv=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"},vI=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Ct();if(n!=="ready"){let{reason:s,text:i}=Lv(n);if(t)throw d.warn({operation:ps},`\u26D4 --orca was passed but ${i}`),new C({status:"refused",reason:s,agentMode:_.source},2,{operation:ps,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 d.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await _m(r);return{probe:n,registered:o.registered,visibility:o.visibility}},wI=(e,t,r)=>{let n=["Are you sure you want to proceed with these worktree changes?",...r];return e?.probe==="ready"&&!e.registered&&n.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),n.join(`
|
|
408
|
-
`)},
|
|
412
|
+
`},HO=e=>({version:e.version??B.version,home:e.home??IO(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>cc({lockPath:lh()})),readRecord:e.readRecord??pn,writeRecord:e.writeRecord??uh,discoverProjects:e.discoverProjects??(()=>Mv()),runSetupChild:e.runSetupChild??LO,writeLog:e.writeLog??BO}),qO=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},YO=async e=>{let t=e.readRecord(),r=e.clock();if(!mh(t,e.version,r))return"not-due";let n=t?.version===e.version?t.attempts+1:1;e.writeRecord({version:e.version,attempts:n,startedMs:r,finishedMs:null,runs:[]});let o=r+_O,s=await jv(null,e.home,e,o),i=qO(e),a=[i.error===null?s:{root:null,status:"failed",notes:[...s.notes,`could not list projects: ${i.error}`]}];for(let l of i.projects)a.push(await jv(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:JO(a)};e.writeRecord(c);try{e.writeLog(KO(c))}catch{}return"ran"},Fv=async(e={})=>{try{let t=HO(e),r=t.acquireLock();if(r===null)return"already-running";try{return await YO(t)}finally{r()}}catch{return"not-due"}},wd=async(e={})=>{let t=await Fv(e);return{content:R(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as QO}from"node:child_process";import{homedir as eD}from"node:os";import tD from"node:process";var zO=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},XO=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},ZO=(e,t)=>{let r=zO(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},ps=(e,t)=>{let r=[...XO(e),...ZO(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},ms=e=>e.steps.map(De);var rD=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],nD=e=>{let t={...zp(e)};for(let r of rD)delete t[r];return t},kd=(e,t,r={})=>{let n=r.spawnSync??QO,o=r.env??tD.env,s=(r.agentMode??pe)(),i=ms(e),a=ps(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:iD({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??oD}):{ran:!1,commands:i,refusedBecause:a.reasons}},oD=e=>{d.info(e)},Bv=64,sD=Bv*1024*1024,iD=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=nD(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:sD,cwd:eD(),env:s}),l=pD(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},aD=5,cD=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Lv=e=>e==null?[]:String(e).split(`
|
|
413
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),lD=e=>{let t=Lv(e.stderr),r=Lv(e.stdout),n=[...t,...r].filter(s=>cD.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-aD).join(" / ")},uD="ENOBUFS",dD=e=>e.error?.code===uD,pD=e=>{if(dD(e))return`terminated after exceeding the ${Bv} 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=lD(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var mD=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},fD=e=>{let t=Le(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},gD=(e,t)=>{let r=fD(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=ps(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:ms(r),context:n}},ga=async(e=dr,t=jo())=>{let r=await Lo(dr,t),n={owner:null,present:mD(r)},o=Xl(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>gD(s.get(a),n)),context:n}};var bd=(e,t)=>({...fs(e),action:"skipped",commands:e.commands,detail:t}),fs=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Uv=(e,t)=>e.action==="none"?bd(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?bd(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...fs(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},hD=(e,t)=>t.ran?t.ok?{...fs(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...fs(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...fs(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Rd=async e=>{let t=e.run??kd,{plans:r}=await ga(e.ids,e.probeDeps),n=[];for(let o of r){let s=Uv(o,e.mode);if(s!==null){n.push(s);continue}n.push(hD(o,t(o.recipe,o.context)))}return n},Sd=async(e,t)=>{let{plans:r}=await ga(e,t);return r.map(n=>Uv(n,"converge")??bd(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import DD from"node:process";import{z as I}from"zod";var Ed={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,"token-perms":10,chrome:11,shell:12},yD=Object.keys(Ed).sort((e,t)=>Ed[e]-Ed[t]),Vv={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},Wv=new Set(["manual","warn","fail"]),Pd=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 Ne(e)}},vD=e=>e.reduce((t,r)=>Vv[r]>Vv[t]?r:t,"skipped"),Jv=e=>e.message.trim(),wD=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 "),Gv=e=>e.message===vn,kD=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Jv(r):e.length>1?wD(e):t?"activate with the last line below":"see below"},bD=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>Pd(i.outcome)),n=t.filter(i=>Wv.has(Pd(i.outcome))).map(Jv),o=t.filter(i=>!Wv.has(Pd(i.outcome))&&!Gv(i)),s={name:e,status:vD(r),message:kD(o,t.some(Gv))};return n.length>0?{...s,notes:n}:s},RD=e=>({label:"Local setup",rows:yD.map(t=>bD(t,e.filter(r=>r.step===t)))}),SD=(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 Ne(e.action)}},ED=(e,t)=>{let r=SD(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},PD=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>ED(r,t))}),xD=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 Ne(e)}},TD=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 Ne(e)}},CD=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 Ne(e)}},$D=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 Ne(e.outcome)}},AD=(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 Ne(e)}},OD=e=>({label:"Portless service",rows:[{name:"link",status:xD(e.link),message:CD(e.link)},{name:"node",status:TD(e.node.outcome),message:$D(e.node)},AD(e.service,e.command)]}),Kv=(e,t)=>[RD(e.init),PD(e.tools,t),OD(e.portless)],Hv=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var ID=()=>{let{link:e,node:t}=Ms();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},ND=async e=>{let t=pm(e.link).outcome,r=dm(e.node),n=_s(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 dy(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Et(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},Yv="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",zv="--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.",_D=e=>{let t=Array.isArray(e.update)?e.update:void 0,r=e.update===!0||t!==void 0,n=e.unattended===!0,o=e.skipTools===!0||n;if(n&&(e.tools!==void 0||r))throw new Error(Yv);if(o&&(e.tools!==void 0||r))throw new Error(zv);return{ids:e.tools??t??dr,mode:r?"update":"converge",skipTools:o}},qv=(e,t)=>e instanceof yn?e.step:t.at(-1)?.step??"zshrc",MD=async()=>{let e=[];try{await Gl(t=>{e.push(t)})}catch(t){e.push({step:qv(t,e),outcome:"failed",message:`The ${qv(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},jD=(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}`}))},FD=async(e,t)=>{try{return e.skipTools?await Sd(e.ids,t.probeDeps):await Rd({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return jD(e.ids,r)}},LD=e=>({step:e.step,outcome:e.outcome,message:e.message}),ha=async(e={})=>{let t=_D(e);Ge.withheld=e.unattended===!0;let r=await MD(),n=await FD(t,e),o=await ND(e.portlessDeps??ID()),s=Kv({init:r,tools:n,portless:o},{skipTools:t.skipTools});rt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(vn),Hv(s)&&(DD.exitCode=1);let i={init:r.map(LD),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:R(JSON.stringify(i,null,2)),structuredContent:i}},BD=I.object({step:I.enum(["zshrc","zshenv","migrations","user-config","guidance","worktrees","plugin-pointer","mcp-server","mcp-proxies","project-config","token-perms","chrome","shell"]).describe("Which init step this reports on"),outcome:I.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:I.string().describe("The same line a human running this would have read")}),UD=I.object({id:I.string().describe("Dependency id"),action:I.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:I.object({present:I.boolean(),onPath:I.boolean(),version:I.string().nullable(),manager:I.string()}).describe("The tool\u2019s state before this run"),commands:I.array(I.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:I.string().describe("Why, in one line")}),VD=I.object({link:I.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:I.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:I.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:I.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")}),WD={init:I.array(BD).describe("One entry per init step, in the order they ran"),tools:I.array(UD).describe("One result per requested dependency"),portlessService:VD.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:I.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:I.boolean().describe("Whether anything was installed or updated"),report:I.array(I.object({label:I.string().describe("Section heading"),rows:I.array(I.object({name:I.string().describe("Init step, tool id, or portless part"),status:I.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:I.string().describe("The row message, as printed"),notes:I.array(I.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:I.boolean().describe("Whether no tool failed (a refusal is not a failure)")},GD={tools:I.array(I.enum(dr)).optional().describe("Which tools to act on. Omit for all six."),mode:I.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:I.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},xd=C({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, check the agent-instruction files (never rewritten here: drift is reported with the `audit --fix` command that refreshes them), 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:GD,outputSchema:WD,requiresHumanConfirm:!0,handler:e=>ha({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as Zv}from"node:fs";import Qv from"node:path";import tI from"node:process";import{z as Rt}from"zod";import{createHash as JD}from"node:crypto";import{readFileSync as KD}from"node:fs";var Er=e=>JD("sha256").update(KD(e)).digest("hex");import{readFileSync as ZD,writeFileSync as QD}from"node:fs";import ka from"node:path";import{z as lt}from"zod";var te="vendor",HD=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),qD=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),YD=[".tsbuildinfo"],Td=e=>HD.has(e),Cd=e=>qD.has(e)?!0:YD.some(t=>e.endsWith(t)),ya=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>Td(o))||Cd(r)};import{readdirSync as zD}from"node:fs";import $d from"node:path";var XD=e=>e.split($d.sep).join("/"),va=e=>{let t=[],r=n=>{for(let o of zD(n,{withFileTypes:!0})){let s=$d.join(n,o.name);if(o.isDirectory()){if(Td(o.name))continue;r(s);continue}Cd(o.name)||t.push(XD($d.relative(e,s)))}};return r(e),t.sort()};var Ve=".sync-manifest.json",wa=1,eI=lt.object({schemaVersion:lt.number().optional(),source:lt.string(),commit:lt.string(),syncedAt:lt.string(),fileCount:lt.number(),files:lt.record(lt.string(),lt.string())}),Ad=e=>(e.schemaVersion??wa)>wa,Xv=(e,t)=>{let r={},n=t?[...new Set(t)].sort():va(e);for(let o of n)try{r[o]=Er(ka.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},gs=e=>{let t=ka.join(e,Ve),r;try{r=ZD(t,"utf8")}catch{throw new Error(`Missing ${Ve} at ${t}`)}let n=eI.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ve} at ${t}: ${lt.prettifyError(n.error)}`);return n.data},Od=(e,t,r)=>{let n=Xv(e,r),o={schemaVersion:wa,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return QD(ka.join(e,Ve),`${JSON.stringify(o,null,2)}
|
|
414
|
+
`),o},Dd=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!ya(c))),n=va(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Er(ka.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 Id=30,Nd=(e,t)=>{if(t.length!==0){d.info(`
|
|
415
|
+
${e} (${t.length}):`);for(let r of t.slice(0,Id))d.info(` ${r}`);t.length>Id&&d.info(` \u2026and ${t.length-Id} more`)}},ba=async(e={})=>{let t=e.cwd??await $(),r=Qv.join(t,te),n={modified:[],added:[],removed:[],fileCount:0};if(!Zv(r)){d.info(`\u2139\uFE0F No ${te}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}if(!Zv(Qv.join(r,Ve))){d.error(`\u274C Missing ${te}/${Ve}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let o=gs(r);if(Ad(o)){d.error(`\u274C ${te}/${Ve} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=Dd(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${te}/ has drifted from ${te}/${Ve}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Nd("Modified",s),Nd("Added (not in manifest)",i),Nd("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${te}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},rI={status:Rt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:Rt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:Rt.number(),modified:Rt.array(Rt.string()),added:Rt.array(Rt.string()),removed:Rt.array(Rt.string())},_d=C({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:rI,handler:()=>ba({cwd:tI.cwd()})});import ew from"node:process";import{z as hs}from"zod";var tw=async e=>{try{return await e()}catch{return null}},Ra=async()=>{let e=B.version;d.info(e);let t=await tw($),r=t===null?null:await tw(()=>Re(t)),n={version:e,cwd:ew.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:ew.env.CLAUDE_PROJECT_DIR||null};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},Md=C({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:hs.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:hs.string().describe("The working directory of this process"),repoRoot:hs.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:hs.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:hs.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ra});import fw from"@inquirer/confirm";import cI from"node:path";import{z as M}from"zod";import{$ as vs}from"zx";import nI from"@inquirer/input";import nw from"@inquirer/select";import{$ as Kt}from"zx";var ys="dev",oI="main",jd="feature/",ow=["new","local","remote"],Sa=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${jd}${t}`},sw=async()=>{let e=await Kt({nothrow:!0,quiet:!0})`git symbolic-ref --quiet --short refs/remotes/origin/HEAD`,t=e.exitCode===0?e.stdout.trim().replace(/^origin\//,""):"";return t===""?null:t},sI=2,Fd=async()=>{let e=await Kt({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${ys}`;if(e.exitCode===0)return ys;if(e.exitCode!==sI)throw new g(void 0,{operation:"create feature worktree",remediation:"check the network and your access to origin, or pass --base explicitly",stderrExcerpt:e.stderr.trim()||`could not ask origin whether ${ys} exists`});return await sw()??ys},iw=async e=>{let t=e?.trim();return t?t===ys||t===oI||t===await sw()?t:ke(ge(t)):Fd()},aw=async()=>N(e=>nw({message:"What kind of worktree?",choices:[{name:"Release \u2014 worktrees for open release branches",value:"release"},{name:"Feature \u2014 a new or existing feature/* branch",value:"feature"}]},e),{whenHeadless:{value:"release"}}),cw=async()=>N(e=>nI({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Sa(t)===jd?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),lw=async(e,t)=>e.length===0?t:N(r=>nw({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),iI=async e=>{let t=await Kt({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===jd||t.exitCode!==0)throw new g(void 0,{operation:"create feature worktree",remediation:"pass a feature name made of letters, digits, `-`, `_`, `.` or `/`, e.g. --feature checkout-v2",stderrExcerpt:`"${e}" is not a valid branch name`})},rw=async e=>(await Kt({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,aI=async e=>(await Kt({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,uw=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Sa))];for(let s of n)await iI(s);if(!await rw(r))throw new g(void 0,{operation:"create feature worktree",remediation:"pass --base dev, --base main or an existing release branch (`infra-kit release list` lists them); a repo with neither dev nor a recorded default branch needs `git remote set-head origin --auto`",stderrExcerpt:`base branch origin/${r} not found`});let o=[];for(let s of n)await aI(s)?o.push({branch:s,base:r,source:"local"}):await rw(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},dw=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await Kt`git worktree add ${t} ${r}`:o==="remote"?await Kt`git worktree add --track -b ${r} ${t} origin/${r}`:await Kt`git worktree add --no-track -b ${r} ${t} origin/${n}`},pw=e=>e.source==="new"?` \u2022 ${e.branch}: new branch from origin/${e.base}`:` \u2022 ${e.branch}: existing ${e.source==="local"?"local":"remote"} branch (base not applied)`;var ws="create worktrees",lI=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Ld=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Ea=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await xe({operation:ws}),uI(e);try{let o=await $(),s=`${o}${de}`;await mw(`${s}/${Or.release}`),await mw(`${s}/${Or.feature}`);let i=await dI(e),a=i==="feature"?await mI(e):await pI(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),v.print();let P={kind:i,createdWorktrees:[],count:0,features:[],...Ld()};return{content:R(JSON.stringify(P,null,2)),structuredContent:P}}let c=await G(),l=await fI(r,c),u=await gI(n,c),p=await Re(o),m=cI.basename(p),f=u?await hI({explicit:n!==void 0,mainRepoRoot:p}):null;await U(t,yI(f,m,a.previewLines)),t||v.addOption("--yes",!0);let w=f?await vI(f,p):null,h=await SI(a.targets,s);if(EI(h),l)for(let P of h)await vs`github ${s}/${P}`,await vs`sleep 5`;let y=w?await kI({registration:w,createdWorktrees:h,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):Ld();bI(y),v.print();let b={kind:i,createdWorktrees:h,count:h.length,features:a.features.filter(P=>h.includes(P.branch)),...y};return{content:R(JSON.stringify(b,null,2)),structuredContent:b}}catch(o){throw Se(o)||o instanceof A?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:ws,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},uI=e=>{let t=e.all||e.versions!==void 0,r=e.feature!==void 0||e.base!==void 0;if(t&&r)throw new g(void 0,{operation:ws,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},dI=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(v.setInteractive(),aw()),pI=async e=>{let{all:t,versions:r}=e,n=await he("release"),o=[];if(r)o=r.split(",").map(a=>ke(ge(a.trim())));else{let a=await L(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{v.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await le();o=await Ft(ue({branches:c,descriptions:u,types:l}),{required:!0})}}t?v.addOption("--all",!0):v.addOption("--versions",wt(o));let{branchesToCreate:s}=RI({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>vs`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},mI=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(v.setInteractive(),r=[await cw()],n===void 0)){let l=(await L()).map(u=>u.branch);n=await lw(l,await Fd())}let o=await iw(n),s=await uw({names:r,base:o});v.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),v.addOption("--base",o);let i=await he("feature"),a=s.filter(l=>i.includes(l.branch)?(d.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:u=>dw(l,u)})),features:a,previewLines:a.map(pw)}},fI=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await N(o=>fw({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&v.setInteractive(),v.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},gI=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await N(o=>fw({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&v.setInteractive(),v.addOption(n?"--orca":"--no-orca",!0),n},gw=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"},hI=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await $t();if(n!=="ready"){let{reason:s,text:i}=gw(n);if(t)throw d.warn({operation:ws},`\u26D4 --orca was passed but ${i}`),new A({status:"refused",reason:s,agentMode:_.source},2,{operation:ws,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 d.warn(`\u26A0\uFE0F ${i} \u2014 worktrees will be created but not opened in Orca`),{probe:n,registered:!1,visibility:void 0}}let o=await ef(r);return{probe:n,registered:o.registered,visibility:o.visibility}},yI=(e,t,r)=>{let n=["Are you sure you want to proceed with these worktree changes?",...r];return e?.probe==="ready"&&!e.registered&&n.push(` \u2022 will register ${t} in Orca (orca repo add); its worktrees start hidden in Orca's sidebar until you choose Show`),n.join(`
|
|
416
|
+
`)},vI=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:gw(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await tf(t);return{kind:"ready",visibility:r}}catch(r){return d.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 _r?r.code:void 0}}},wI=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,kI=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Ld();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=_m(i),l=r.length===1&&t.visibility!=="hide",u=nf();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await of({cwd:m,title:sf({branch:p}),focus:l,layout:"full",panes:c,poll:u});await rf(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:wI(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof _r&&f.code==="orca_worktree_not_selectable"?a.orcaSkipped.push({branch:p,reason:"orca_worktree_not_selectable"}):a.orcaSkipped.push({branch:p,reason:"orca_error",code:f instanceof _r?f.code:void 0})}}return a},bI=e=>{for(let t of e.orcaOpened)d.info(`\u{1FA9F} Opened ${t.branch} in Orca (${t.layout})`);for(let t of e.orcaHidden)d.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})`:"";d.info(`\u21A9\uFE0F ${t.branch} not opened in Orca: ${t.reason}${r}`)}},mw=async e=>{await vs`mkdir -p ${e}`},RI=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Dr(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},SI=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await vs({cwd:s})`pnpm install`,o.branch})),n=[];for(let[o,s]of r.entries())if(s.status==="fulfilled")n.push(s.value);else{let i=e[o]?.branch,a=new g(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});d.error({error:s.reason,msg:a.message})}return n},EI=e=>{if(e.length>0){d.info("\u2705 Created git worktrees:");for(let t of e)d.info(t);d.info("")}else d.info("\u2139\uFE0F No new git worktrees to create")},Bd=C({name:"worktrees-add",description:`Create local git worktrees under the worktrees directory and run "pnpm install" in each: release worktrees for open release branches ("versions" / all=true), or feature worktrees ("feature", optional "base") \u2014 each name becomes a feature/<name> branch at <root>-worktrees/feature/<name>, cut from origin/<base> (default dev, or the default branch of a repo without dev; main; or any release branch) with no upstream, or checked out as-is when the branch already exists locally or on origin. Mutates the local filesystem. When invoked via MCP, pass "versions" (comma-separated), all=true, or "feature" \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:{feature:M.string().optional().describe('Comma-separated feature names (e.g. "checkout-v2" or "feature/checkout-v2"); each becomes a feature/<name> worktree. Cannot be combined with "versions" or "all".'),base:M.string().optional().describe(`Base for NEW feature branches: "dev" (default; the repo's default branch when it has no dev), "main", or a release ref ("1.4.0", "release/v1.4.0", "release/<name>"). Not applied to a feature branch that already exists. Implies a feature run.`),all:M.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:M.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:M.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:M.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:M.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:M.array(M.object({branch:M.string(),base:M.string(),source:M.enum(ow)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:M.array(M.string()).describe("List of created git worktree branches"),count:M.number().describe("Number of git worktrees created"),orcaOpened:M.array(M.object({branch:M.string(),layout:M.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:M.array(M.object({branch:M.string(),reason:M.enum(lI),code:M.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:M.array(M.object({branch:M.string(),path:M.string(),fix:M.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:Ea});import{z as Ht}from"zod";var Pa=async()=>{await G();let[e,t]=await Promise.all([he("release"),he("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await PI(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
|
|
409
417
|
|
|
410
|
-
${
|
|
418
|
+
${xI(r).join(`
|
|
411
419
|
`)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
|
|
412
420
|
|
|
413
421
|
${t.join(`
|
|
414
422
|
`)}`),d.info(n.join(`
|
|
415
423
|
|
|
416
|
-
`));let o={worktrees:r,count:r.length,features:t};return{content:
|
|
417
|
-
`).filter(r=>r.trim().length>0),_I=async e=>{let[t,r]=await Promise.all([Bv(e.worktreePath),Bv(e.mainRoot)]);t.length>0&&Sr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Sr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Ct();n!=="ready"&&Sr(`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},MI=async e=>{let t=Ie(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${OI}; ${t} && { sleep ${II}; exit; }`;try{return(await Im(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Ir?new g(n,{operation:Uv,remediation:`run \`infra-kit worktrees remove ${Ie(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Vv=async e=>{let t=await NI();await _I(t),h.addOption("--self",!0),await L(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||h.addOption("--yes",!0);let r=await MI(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),h.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:k(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var jI=e=>{if(we()){if(e.all)throw new C({status:"refused",agentMode:_.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&&!e.feature)throw new C({status:"argument_required",argument:"versions",agentMode:_.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},FI=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new g(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(", ")}`})},LI=async(e,t)=>{let r=await js(t.map(n=>`${e}/${n}`));if(r!==null)throw new C({status:"refused",reason:"orca_caller_inside_target",agentMode:_.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`})},BI=e=>e?e.split(",").map(t=>ke(me(t.trim()))):[],UI=e=>e?e.split(",").filter(t=>t.trim()!=="").map(ua):[],VI=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",vt(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},fa=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new g(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return Vv(t)}await xe({operation:"remove worktrees"}),await W(),jI({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([fe("release"),fe("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),h.print();let y={removedWorktrees:[],failedWorktrees:[],count:0};return{content:k(JSON.stringify(y,null,2)),structuredContent:y}}let l=await P(),u=`${l}${le}`,p=[];if(r)p=c;else if(n||o)p=[...BI(n),...UI(o)];else{h.setInteractive();let[y,b]=await Promise.all([ae(),F()]),w=new Map(b.map(x=>[x.branch,x.type]));p=await jt([...ce({branches:i,descriptions:y,types:w}),...a.map(x=>({value:x,label:x,type:"feature"}))],{required:!0})}FI(p,c);let m=p.length===c.length;m?h.addOption("--all",!0):VI(p),await LI(u,p),await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let f=await vr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Jo(f),h.print(),Ko({result:f,operation:"remove worktrees"})}catch(i){throw Se(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},wd=E({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches ("versions") and/or feature branches ("feature"). Over MCP you MUST pass "versions" or "feature" (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 target must be an active worktree, or the call errors without removing anything. What survives: the release and feature 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:We.string().optional().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). This or "feature" is required: each must name an active worktree, or the call errors before removing anything.'),feature:We.string().optional().describe('Comma-separated feature names to remove (e.g. "checkout-v2" or "feature/checkout-v2"). This or "versions" is required; each must name an active feature worktree.'),confirm:We.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:We.array(We.string()).describe("List of removed git worktree branches"),failedWorktrees:We.array(We.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:We.number().describe("Number of git worktrees removed"),handedOff:We.object({branch:We.string(),worktreePath:We.string(),terminal:We.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:fa});import{z as ms}from"zod";var ga=async e=>{let{confirmedCommand:t}=e;await xe({operation:"sync worktrees"}),await W();try{let r=await fe("release"),n=await P(),o=`${n}${le}`,s=await ri();await L(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=WI({releasePRsList:s,currentWorktrees:r}),a=await vr({branches:i,worktreeDir:o,projectRoot:n});return Jo(a),h.print(),Ko({result:a,operation:"sync worktrees"})}catch(r){throw Se(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},WI=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>$r(s)).filter(s=>!t.includes(s))}},kd=E({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:ms.array(ms.string()).describe("List of removed worktree branches"),failedWorktrees:ms.array(ms.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ms.number().describe("Number of worktrees removed during sync")},handler:ga});var bd=[{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"}],mr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Jc,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:iu,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:mu,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Au,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:Gu,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Ku,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Tu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:$u,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:hu,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Yu,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Lu,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Bu,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:yd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:vd,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:wd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:kd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:lu,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Jm,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:ec,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:cu,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:uu,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Wc,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{cliName:"config-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-set"]},{cliName:"config-unset",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-unset"]},{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:pd,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,groupPath:["vendor","sync"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:nd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:ql,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Bc,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:md,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:"environment",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 Rd=e=>mr.filter(t=>t.menuGroup===e),Sd=e=>mr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var GI=(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},Wv=e=>bd.flatMap(({key:t,label:r})=>Rd(t).flatMap(n=>{let o=GI(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Ed from"node:process";var JI="MODULE_TYPELESS_PACKAGE_JSON",KI=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Gv=!1,Pd=()=>{if(Gv)return;Gv=!0;let e=Ed.emitWarning.bind(Ed);Ed.emitWarning=((t,...r)=>{KI(r[0],r[1])!==JI&&e(t,...r)})};import{Command as XN,InvalidArgumentError as ZN,Option as Kw}from"commander";import{resolve as QN}from"node:path";import $e from"node:process";import{cd as e_}from"zx";import Jv from"node:process";import{$ as HI}from"zx";var xd=async()=>{let e=await Y(),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 Z(i.path)}))),r=t.at(-1)?.exists===!0,n=await $o(e.userProject,r),o=r?Ao(n):"";d.info(`Project name: ${e.projectName}
|
|
424
|
+
`));let o={worktrees:r,count:r.length,features:t};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},PI=async e=>{let[t,r]=await Promise.all([L(),le()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=Y(o);if(!s)return[];let i=Q(s),a=n.get(o)||"regular",c=r.get(se(s))||null;return[{version:i,type:a,description:c}]})},xI=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=Po(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Ud=C({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description, plus feature worktrees (feature/* branches). Read-only.",inputSchema:{},outputSchema:{worktrees:Ht.array(Ht.object({version:Ht.string().describe("Release version"),type:Ht.enum(["regular","hotfix"]).describe("Release type"),description:Ht.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:Ht.number().describe("Number of release worktrees"),features:Ht.array(Ht.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:Pa});import{z as We}from"zod";import TI from"node:fs/promises";import{$ as CI}from"zx";var yw="remove this worktree",$I=2,AI=3,xa=async e=>{try{return await TI.realpath(e)}catch{return e}},Pr=(e,t)=>{throw new g(void 0,{operation:yw,remediation:e,stderrExcerpt:t})},OI=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=wt([e]);return Dr(e)&&t?["--versions",t]:Pr("only feature/* and release worktrees created by `infra-kit worktrees add` can be removed with --self",`branch ${e} is neither a feature nor a release branch`)},DI=async()=>{let e=await xa(await $()),t=await xa(await Re(e));e===t&&Pr("run --self from inside the worktree to remove, or name it with --feature / --versions","this is the main checkout, not a linked worktree");let r=null;for(let o of await Ye(t))await xa(o.path)===e&&(r=o.branch);if(!r)return Pr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await xa(`${t}${de}/${r}`);return n!==e&&Pr("remove it with `git worktree remove` from the main checkout",`${e} is not an infra-kit worktree (expected ${n})`),{worktreePath:e,mainRoot:t,branch:r,targetArgs:OI(r)}},hw=async e=>(await CI({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
|
|
425
|
+
`).filter(r=>r.trim().length>0),II=async e=>{let[t,r]=await Promise.all([hw(e.worktreePath),hw(e.mainRoot)]);t.length>0&&Pr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Pr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await $t();n!=="ready"&&Pr(`run \`infra-kit worktrees remove ${De(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},NI=async e=>{let t=De(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${$I}; ${t} && { sleep ${AI}; exit; }`;try{return(await Xm(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof _r?new g(n,{operation:yw,remediation:`run \`infra-kit worktrees remove ${De(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},vw=async e=>{let t=await DI();await II(t),v.addOption("--self",!0),await U(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||v.addOption("--yes",!0);let r=await NI(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),v.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:R(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var _I=e=>{if(pe()){if(e.all)throw new A({status:"refused",agentMode:_.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&&!e.feature)throw new A({status:"argument_required",argument:"versions",agentMode:_.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},MI=(e,t)=>{let r=e.filter(n=>!t.includes(n));if(r.length>0)throw new g(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(", ")}`})},jI=async(e,t)=>{let r=await Ks(t.map(n=>`${e}/${n}`));if(r!==null)throw new A({status:"refused",reason:"orca_caller_inside_target",agentMode:_.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`})},FI=e=>e?e.split(",").map(t=>ke(ge(t.trim()))):[],LI=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Sa):[],BI=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&v.addOption("--versions",wt(r)),t.length>0&&v.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Ta=async e=>{let{confirmedCommand:t,all:r,versions:n,feature:o,self:s}=e;if(s){if(r||n||o)throw new g(void 0,{operation:"remove worktrees",remediation:"pass --self alone, or name targets with --versions / --feature",stderrExcerpt:"--self cannot be combined with --all, --versions or --feature"});return vw(t)}await xe({operation:"remove worktrees"}),await G(),_I({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([he("release"),he("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),v.print();let w={removedWorktrees:[],failedWorktrees:[],count:0};return{content:R(JSON.stringify(w,null,2)),structuredContent:w}}let l=await $(),u=`${l}${de}`,p=[];if(r)p=c;else if(n||o)p=[...FI(n),...LI(o)];else{v.setInteractive();let[w,h]=await Promise.all([le(),L()]),y=new Map(h.map(b=>[b.branch,b.type]));p=await Ft([...ue({branches:i,descriptions:w,types:y}),...a.map(b=>({value:b,label:b,type:"feature"}))],{required:!0})}MI(p,c);let m=p.length===c.length;m?v.addOption("--all",!0):BI(p),await jI(u,p),await U(t,"Are you sure you want to proceed with these worktree changes?"),t||v.addOption("--yes",!0);let f=await wr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Xo(f),v.print(),Zo({result:f,operation:"remove worktrees"})}catch(i){throw Se(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Vd=C({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches ("versions") and/or feature branches ("feature"). Over MCP you MUST pass "versions" or "feature" (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 target must be an active worktree, or the call errors without removing anything. What survives: the release and feature 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:We.string().optional().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). This or "feature" is required: each must name an active worktree, or the call errors before removing anything.'),feature:We.string().optional().describe('Comma-separated feature names to remove (e.g. "checkout-v2" or "feature/checkout-v2"). This or "versions" is required; each must name an active feature worktree.'),confirm:We.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:We.array(We.string()).describe("List of removed git worktree branches"),failedWorktrees:We.array(We.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:We.number().describe("Number of git worktrees removed"),handedOff:We.object({branch:We.string(),worktreePath:We.string(),terminal:We.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Ta});import{z as ks}from"zod";var Ca=async e=>{let{confirmedCommand:t}=e;await xe({operation:"sync worktrees"}),await G();try{let r=await he("release"),n=await $(),o=`${n}${de}`,s=await di();await U(t,"Are you sure you want to proceed with these worktree changes?"),t||v.addOption("--yes",!0);let{branchesToRemove:i}=UI({releasePRsList:s,currentWorktrees:r}),a=await wr({branches:i,worktreeDir:o,projectRoot:n});return Xo(a),v.print(),Zo({result:a,operation:"sync worktrees"})}catch(r){throw Se(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},UI=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Dr(s)).filter(s=>!t.includes(s))}},Wd=C({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:ks.array(ks.string()).describe("List of removed worktree branches"),failedWorktrees:ks.array(ks.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ks.number().describe("Number of worktrees removed during sync")},handler:Ca});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:al,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:Ru,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:$u,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Qu,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:zu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Zu,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:Du,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:vd,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:Ud,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Vd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Wd,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Pu,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:df,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:hc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Eu,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:xu,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:sl,mcpExposed:!0,mutating:!1,groupPath:["config-get"]},{cliName:"config-set",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-set"]},{cliName:"config-unset",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["config-unset"]},{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:_d,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,groupPath:["vendor","sync"]},{cliName:"deploy-run",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["deploy-run"]},{cliName:"deploy-sync",menuGroup:null,mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["deploy-sync"]},{cliName:"setup",menuGroup:"setup",mcpTool:xd,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:uu,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:rl,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Md,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:"environment",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 Jd=e=>fr.filter(t=>t.menuGroup===e),Kd=e=>fr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var VI=(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},ww=e=>Gd.flatMap(({key:t,label:r})=>Jd(t).flatMap(n=>{let o=VI(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Hd from"node:process";var WI="MODULE_TYPELESS_PACKAGE_JSON",GI=(e,t)=>typeof e=="object"&&e!==null?e.code:t,kw=!1,qd=()=>{if(kw)return;kw=!0;let e=Hd.emitWarning.bind(Hd);Hd.emitWarning=((t,...r)=>{GI(r[0],r[1])!==WI&&e(t,...r)})};import{Command as Y_,InvalidArgumentError as z_,Option as bk}from"commander";import{resolve as X_}from"node:path";import $e from"node:process";import{cd as Z_}from"zx";import bw from"node:process";import{$ as JI}from"zx";var Yd=async()=>{let e=await z(),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 _o(e.userProject,r),o=r?Mo(n):"";d.info(`Project name: ${e.projectName}
|
|
418
426
|
`),d.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}`:"";d.info(`${a} ${i.label.padEnd(22)} ${
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
`)}
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
`),rw=async(e,t,r,n)=>{let o=await vD(e,t,r);Za(o,r);let s=o.some(([i])=>i===Ud);if(!s&&!n)throw new Error(kD(r));return s},tw="\0new-env",bD=async()=>{if(H()||!ut.stdin.isTTY)throw new C({status:"argument_required",argument:"env",agentMode:_.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([Vm(),Je()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await I(s=>fD({message:"Which environment is the token for?",choices:[...e.map(({env:i})=>({name:`${i.padEnd(r)} ${t?.envs[i]?"set \u2014 replace":"not set"}`,value:i})),{name:"+ new env\u2026",value:tw}]},s),{output:ut.stderr,whenHeadless:"refuse"});return n!==tw?n:(await I(s=>pD({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:ut.stderr,whenHeadless:"refuse"})).trim()},RD=async(e,t,r)=>I(n=>dD({message:`Replace the "${e}" token ${be(t)} with ${be(r)}?`,default:!0},n),{output:ut.stderr,whenHeadless:"refuse"}),SD=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${be(r)})`;case"replaced":return`Replaced the "${e}" service token ${be(n??"")} \u2192 ${be(r)}`;case"unchanged":return`The "${e}" service token is already ${be(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${be(n??"")} \u2014 nothing was written`;default:return Ne(t)}},Vd=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Zt(),s=e??await bD(),{token:i,source:a}=await hD({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await rw(i,o,s,n),l=(await Je())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await RD(s,l,i)?u="kept":(await Ja({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Tt();d.info(`${SD(s,u,i,l)} in ${v(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Ud} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:be(i),previousRedactedToken:l===void 0?null:be(l),storePath:p,scopeVerified:c};return h.print(),{content:k(JSON.stringify(m,null,2)),structuredContent:m}},ED=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,nw=e=>{let t=e.split(/\r?\n/).flatMap((n,o)=>{let s=n.trim();if(s===""||s.startsWith("#"))return[];let i=s.indexOf("="),a=i>0?s.slice(0,i).trim():"",c=i>0?ED(s.slice(i+1).trim()):"";if(!/^\S+$/.test(a)||c==="")throw new Error(`Token file line ${o+1} is not \`<env>=<token>\` \u2014 nothing was written.`);return[{env:a,token:c}]});if(t.length===0)throw new Error("The token file holds no `<env>=<token>` lines \u2014 nothing was written.");let r=new Set;for(let{env:n}of t){if(r.has(n))throw new Error(`"${n}" appears twice in the token file \u2014 nothing was written.`);r.add(n)}return t},PD=e=>(e instanceof Error?e.message:String(e)).split(`
|
|
428
|
-
`)[0]??"",xD=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",TD=async(e,t,r,n)=>{let o=be(e.token);try{let s=await rw(e.token,t,e.env,n);return{env:e.env,status:xD(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:PD(s)}}},Wd=async({fromFile:e,force:t})=>{let r=await Zt(),n=nw(await gD.readFile(e,"utf8")),o=await Je(),s=await Promise.all(n.map(p=>TD(p,r,o?.envs[p.env],t))),i=Object.fromEntries(n.filter((p,m)=>s[m]?.status==="stored"||s[m]?.status==="replaced").map(({env:p,token:m})=>[p,m]));Object.keys(i).length>0&&await Ja(i);let a=await Tt(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${v(e)} \u2192 ${v(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${v(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(ut.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:k(JSON.stringify(u,null,2)),structuredContent:u}};var Gd=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:u}=e,p=await Pu(n);if(r&&h.addOption("--from",p),Eu(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new g(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"?Vi({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Wi({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Jd=async e=>Gd(e,"all"),Kd=async e=>Gd(e,"selected"),wa=async(e,t)=>{let r=`release deploy-${t} --from local`;return d.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),Gd({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as sw}from"@slip-stream-kit/config/internal";import Hd from"node:fs/promises";import Tn from"node:path";import ow from"node:process";import{pathToFileURL as CD}from"node:url";var iw="~/projects",qd=async(e={})=>{if(e.init){await AD(e.cwd);return}await $D()},$D=async()=>{let e=dn(),t=await Z(e);if(d.info(`Factory config: ${v(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),ow.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await ki(),s=pn(r),i=await Z(s),a=Tn.join(s,n),c=await Z(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${v(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=Tn.join(s,u),m=await Z(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${v(p)}${y}`)}l||(ow.exitCode=1)},AD=async e=>{let t=dn();if(await Z(t)){d.info(`Factory config already exists at ${v(t)} \u2014 leaving it untouched.`);return}let r=e??await P(),n=await OD(r);await Hd.mkdir(Tn.dirname(t),{recursive:!0}),await Hd.writeFile(t,ID(Tn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${v(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${sw}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${iw}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Tn.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&d.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},OD=async e=>{try{let t=Tn.join(e,sw),r=await Hd.stat(t),s=(await import(`${CD(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[]},ID=(e,t)=>`${JSON.stringify({workspaceDir:iw,source:e,targets:t},null,2)}
|
|
429
|
-
`;import{existsSync as BN}from"node:fs";import UN from"node:fs/promises";import Nw from"node:path";import _w from"node:process";import{z as VN}from"zod";import{chmodSync as BD,copyFileSync as UD,lstatSync as VD,mkdirSync as hw,readdirSync as WD,readlinkSync as GD,rmSync as JD,rmdirSync as yw,symlinkSync as KD,unlinkSync as HD,writeFileSync as qD}from"node:fs";import he from"node:path";import{lstatSync as DD,readlinkSync as aw}from"node:fs";import ND from"node:path";var _D=new Set(["ENOENT","ENOTDIR"]),ka=e=>{let t;try{t=DD(e)}catch(r){if(_D.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:aw(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Rr(e)}:{kind:"other"}},cw=(e,t)=>{let r=ND.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:aw(r)}:{kind:"file",executable:t.mode==="100755",sha:Rr(r)};return{...t,fingerprint:n}},lw=(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 MD}from"zx";var J=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await MD({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ba=e=>e.slice(0,7),He=e=>e.split("\0").filter(t=>t.length>0);import jD from"node:path";var Yd=`${Q}/`,Ht=`${Q}/README.md`,fs=`${Q}/${Ve}`,dw=e=>e.startsWith(Yd),uw=e=>{let t=jD.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},pw=e=>{let t=uw(e.path),r=e.target===void 0?t:uw(e.target);return{path:t,target:r,vendored:dw(r),module:e.module??null}},mw=e=>e.copy.map(pw),gs=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),hs=(e,t)=>e.filter(r=>!gs(r.path,t)),Ra=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Cn=e=>[...new Set(e)].sort(),fw=e=>e.startsWith(Yd)?e.slice(Yd.length):null;var Sa=e=>`# vendor/ \u2014 mirrored from ${e}
|
|
427
|
+
`);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${k(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}},zd=async()=>{let e=await z(),t=bw.env.EDITOR||bw.env.VISUAL||"vi",r=await cn(e);r.createdConfig&&d.info(ln(r)),d.info(`Opening ${k(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await JI({stdio:"inherit"})`${t} ${e.userProject}`,xt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Xd=async({key:e,global:t})=>{ai(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await ci(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${mo[r]} (${k(n)})`:`${e} is not set in the ${mo[r]} (${k(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}};import xw from"node:fs/promises";import Rs from"node:path";import ZI from"node:process";import{pathToFileURL as QI}from"node:url";import{execFile as KI,spawn as HI}from"node:child_process";import bs from"node:fs/promises";import On from"node:path";import Rw from"node:process";import{promisify as qI}from"node:util";var YI=qI(KI),Sw="3.39.0",zI=10*1024*1024,Zd=10,Dn=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},XI=(e,t,r)=>new Promise((n,o)=>{let s=HI(e,t,{cwd:r.cwd,env:r.env,stdio:"inherit"});s.on("error",o),s.on("exit",(i,a)=>{i===0?n():o(new Error(`${e} exited with ${a??i}`))})}),Aa={run:XI,capture:async(e,t,r)=>{let{stdout:n}=await YI(e,t,{...r,maxBuffer:zI});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{Rw.stdout.write(`${e}
|
|
428
|
+
`)}},$a=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),Ew=async e=>{let t=JSON.parse(await bs.readFile(On.join(e,"package.json"),"utf-8")),r=t.devDependencies?.turbo??t.dependencies?.turbo,n=r?.replace(/^[\^~=v]+/,"");if(n===void 0||!/^\d+\.\d+\.\d+/.test(n))throw new Error(`the root package.json must pin turbo to an exact version (found ${r??"none"})`);return n},ep=async e=>{let t=await bs.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=On.join(e,r.name);return r.name==="node_modules"?bs.rm(n,{recursive:!0,force:!0}):ep(n)}))},Qd=async(e,t,r)=>{let n=r.appPath??t;if(n===void 0)throw new Error("pass app and appPath, or put the deploy script in the app it deploys");if(r.app!==void 0)return{app:r.app,appPath:n};try{let o=JSON.parse(await bs.readFile(On.join(e,n,"package.json"),"utf-8"));if(o.name)return{app:o.name,appPath:n}}catch{}throw new Error(`${n} has no package.json name to deploy; pass app explicitly`)},tp=({root:e,service:t,scriptDir:r,env:n=Rw.env,deps:o=Aa})=>{let s=async(h,y,b,P={})=>{o.log(`COMMAND: ${[y,...b].join(" ")}`);try{await o.run(y,b,{cwd:P.cwd??e,env:P.env??n})}catch(T){throw new Error(`${h} failed: ${T.message}`)}},i=async(h,y,b={})=>{let{attempts:P=8,initialDelaySeconds:T=3,maxDelaySeconds:S=60}=b,Z=async j=>{try{return await y()}catch(dt){if(j>=P)throw new Error(`${h} failed after ${P} attempts: ${dt.message}`);let zt=Math.min(S,T*2**(j-1)),Tr=Math.round((zt/2+o.random()*zt/2)*10)/10;return o.log(`Attempt ${j}/${P} failed. Retrying in ${Tr}s...`),await o.sleep(Tr*1e3),Z(j+1)}};return Z(1)},a=async(h,y,b=n)=>{o.log(`COMMAND: aws ${y.join(" ")}`),await i(h,()=>o.run("aws",y,{cwd:e,env:$a(b)}))},c=async(h,y={})=>{await s(`aws ${h.slice(0,2).join(" ")}`,"aws",h,{cwd:y.cwd,env:$a(y.env??n)})},l=async h=>{let y=Array.from({length:Math.ceil(h.length/Zd)},(T,S)=>h.slice(S*Zd,(S+1)*Zd)),b=await Promise.all(y.map(async T=>{let S=await o.capture("aws",["ssm","get-parameters","--names",...T,"--output","json"],{cwd:e,env:$a(n)});return JSON.parse(S)})),P=b.flatMap(T=>T.InvalidParameters??[]);if(P.length>0)throw new Error(`SSM parameters not found: ${P.join(", ")}`);return Object.fromEntries(b.flatMap(T=>(T.Parameters??[]).map(S=>[S.Name,S.Value])))},u=async h=>{let y=[`turbo@${await Ew(e)}`,...h?[`serverless@${Sw}`]:[]];await s("Install tools","pnpm",["add","-g",...y])},p=async(h,y)=>{let b=On.join(e,"out"),P={...n,...y.buildEnv},T=y.buildTask??P.TURBO_BUILD_TASK??"build";return await bs.rm(b,{recursive:!0,force:!0}),await s(`Prune to ${h}`,"turbo",["prune",h],{env:P}),await s("Install dependencies","pnpm",["install"],{cwd:b,env:P}),await s(`Build ${h}`,"pnpm",["exec","turbo",T,`--filter=${h}`,"--env-mode=loose"],{cwd:b,env:P}),y.installProd&&(o.log("COMMAND: remove every node_modules under ./out"),await ep(b),await s("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:b,env:P}),await s("Show node_modules size","du",["-sm","./node_modules/"],{cwd:b})),b},m=async(h,y,b)=>{if(y!==void 0){o.log(`Running ${h} hooks...`);try{await y(b)}catch(P){throw new Error(`${h} hooks failed: ${P.message}`)}o.log(`${h} hooks completed successfully`)}};return{root:e,service:t,ssm:l,aws:c,run:(h,y,b={})=>o.run(h,y,{cwd:b.cwd??e,env:b.env??n}),capture:(h,y,b={})=>o.capture(h,y,{cwd:b.cwd??e,env:b.env??n}),retry:i,skip:h=>{throw new Dn(h)},pruneAndBuild:p,deployBackendApi:async h=>{let{app:y,appPath:b}=await Qd(e,r,h);await u(!0);let P={...n,...h.buildEnv},T=await p(y,{installProd:!0,buildTask:h.buildTask,buildEnv:h.buildEnv}),S={stage:h.stage,outDir:T,appDir:On.join(T,b)};await m("Pre-deployment",h.preDeploy,S),await s("Deploy with Serverless","serverless",["deploy","--stage",h.stage,"--force"],{cwd:S.appDir,env:P}),h.restApiId===void 0?o.log(`Skipping API Gateway deployment for ${y}: no restApiId.`):await a("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",h.restApiId,"--stage-name","api"],P),await m("Post-deployment",h.postDeploy,S)},deployFrontendUi:async h=>{let{app:y,appPath:b}=await Qd(e,r,h);await u(!1);let P={...n,...h.buildEnv},T=await p(y,{installProd:!1,buildTask:h.buildTask,buildEnv:h.buildEnv}),S={stage:h.stage,outDir:T,appDir:On.join(T,b)},Z=`s3://${h.bucket}${h.destPath??""}`,j=h.sourcePath??"./dist";await s("Sync to S3","aws",["s3","sync",j,Z,...h.syncFlags??[],"--only-show-errors"],{cwd:S.appDir,env:$a(P)}),await a("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",h.cloudfrontId,"--paths",h.invalidationPath??"/*"],P),await m("Post-deployment",h.postDeploy,S)}}};var Pw=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),eN=async(e,t)=>{let r=Rs.join(e,"devops","scripts",`deploy-${t}.sh`);try{await xw.access(r)}catch{throw new g(void 0,{operation:`deploy ${t}`,remediation:`set services['${t}'].deploy in infra-kit.deploy.ts, e.g. 'apps/<app>/deploy.ts'`,stderrExcerpt:`${t} has no deploy in infra-kit.deploy.ts and no devops/scripts/deploy-${t}.sh`})}return r},tN=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
|
|
429
|
+
`,"%0A")}`,rN=(e,t)=>{let r=(e??"").split(`
|
|
430
|
+
`).filter(n=>n.trim()!=="").map(n=>{let o=n.indexOf("="),s=n.slice(0,Math.max(o,0));if(!/^[A-Z_][A-Z0-9_]*$/.test(s))throw new g(void 0,{operation:"deploy-run",remediation:"write each extra-env line as KEY=VALUE with an upper-case KEY",stderrExcerpt:"an extra-env line is not KEY=VALUE"});return[s,n.slice(o+1)]});for(let[,n]of r)n!==""&&t(tN(n));return Object.fromEntries(r)},nN=async e=>{try{await xw.access(e)}catch{throw new g(void 0,{operation:`run ${Rs.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(QI(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${Rs.basename(e)}`,remediation:"export the deploy as `export default (async (toolkit) => { \u2026 }) satisfies DeployScript`",stderrExcerpt:"the script has no default-exported function"});return t.default},rp=async e=>{let{service:t,env:r=ZI.env}=e;if(!/^[a-z0-9-]+$/.test(t))throw new g(void 0,{operation:"deploy-run",remediation:"pass the service as infra-kit.deploy.ts names it, e.g. client-be",stderrExcerpt:`invalid service name '${t}'`});if(pe()&&r.INFRA_KIT_DEPLOY_VIA!==as)throw new A({status:"refused",agentMode:_.source},2,{operation:`deploy ${t}`,remediation:"ask a human to run `infra-kit deploy-run` from their own shell, or deploy through `infra-kit release deploy-selected` (CI) or `infra-kit local deploy-selected`, which check the environment first",stderrExcerpt:"deploy-run deploys with whatever AWS credentials are loaded: refused in agent mode"});let n=e.cwd??await $(),o=e.deps??Aa,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...rN(s,o.log)},c=(await kr(n))?.services[t]?.deploy;if(c===void 0)await o.run("sh",[await eN(n,t)],{cwd:n,env:a});else{let l=await nN(Rs.join(n,c)),u=tp({root:n,service:t,scriptDir:Rs.dirname(c),env:a,deps:o});try{await l(u)}catch(p){if(!(p instanceof Dn))throw p;return d.info(`\u23ED\uFE0F ${t} skipped: ${p.message}`),Pw({status:"skipped",service:t,reason:p.message})}}return d.info(`\u2705 ${t} deployed`),Pw({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as Ss}from"@slip-stream-kit/config/internal";import Da from"node:fs/promises";import Ia from"node:path";var np=async e=>{try{return await Da.readFile(e,"utf-8")}catch{return}},Oa=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),oN={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},Tw=async(e,t)=>(await Promise.all(t.map(async n=>{let o=Ia.join(e,n);return(await np(o))?.startsWith(Tn)?[{path:n,absolute:o}]:[]}))).flat(),sN=async(e,t)=>t.replaceV1!==!0?[]:(await Tw(e,_u)).map(r=>({...r,status:"removed"})),iN=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await np(Ia.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${Ss} do not exist: ${n.join(", ")}`)},aN=async(e,t)=>{if(t.replaceV1===!0)return;let r=await Tw(e,Mu);if(r.length===0)return;let n=r.map(o=>o.path).join(", ");throw new Error(`${n} ${r.length===1?"was":"were"} generated under replaceV1, which ${Ss} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},op=async(e={})=>{let t=e.cwd??await $(),r=await kr(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Ss} at ${t}, nothing to generate.`),Oa({status:"missing-config",ok:!!e.check,files:[]});await aN(t,r),await iN(t,r);let n=await Promise.all(Lu(r).map(async a=>{let c=Ia.join(t,a.path),l=await np(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await sN(t,r),s=[...n.filter(a=>a.status!=="unchanged"),...o],i=[...n,...o].map(({path:a,status:c})=>({path:a,status:c}));if(s.length===0)return d.info(`\u2705 Deploy workflows match ${Ss}.`),Oa({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${Ss}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${oN[a.status]})`);return Oa({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await Da.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await Da.mkdir(Ia.dirname(a.absolute),{recursive:!0}),await Da.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return Oa({status:"written",ok:!0,files:i})};var Cw="https://dashboard.doppler.com/workplace/projects",cN=(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}"): ${Cw}/${e}`],sp=async({env:e})=>{let r=!!(await Je())?.envs[e];await Jm(e);let n=await Qt(),o=await Ct();r?d.info(`Removed the "${e}" service token from ${k(o)}.`):d.info(`No "${e}" service token was stored in ${k(o)} \u2014 nothing to remove.`);for(let i of cN(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Cw}/${n}`};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}};import lN from"@inquirer/confirm";import uN from"@inquirer/input";import dN from"@inquirer/password";import pN from"@inquirer/select";import mN from"node:fs/promises";import ut from"node:process";import{$ as Na}from"zx";var fN=async({stdin:e,fromEnv:t})=>{if(e)return{token:await $w(),source:"stdin"};if(t){let n=ut.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!ut.stdin.isTTY){let n=await $w();if(n)return{token:n,source:"stdin"};if(!q())throw new Error("stdin is not a terminal and carried no token \u2014 pipe one in (`op read \u2026 | infra-kit env-token-set <env>`) or pass --from-env <VAR>.")}return v.setInteractive(),{token:(await N(n=>dN({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:ut.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},$w=async()=>{let e=[];ut.stdin.setEncoding("utf8");for await(let t of ut.stdin)e.push(t);return e.join("").trim()},ip="DOPPLER_CONFIG",gN=3e4,hN=async(e,t,r)=>{let n=Na.quiet;Na.quiet=!0;let o;try{o=(await Na({env:zn(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(gN)).stdout}catch(s){throw yN(s,r)}finally{Na.quiet=n}return gc(o)},yN=(e,t)=>{let r=gm(e)??(e instanceof Error?e.message:String(e));if(Hm(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=qm(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(`
|
|
431
|
+
`))},vN=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${ip}.`,"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(`
|
|
432
|
+
`),Ow=async(e,t,r,n)=>{let o=await hN(e,t,r);fc(o,r);let s=o.some(([i])=>i===ip);if(!s&&!n)throw new Error(vN(r));return s},Aw="\0new-env",wN=async()=>{if(q()||!ut.stdin.isTTY)throw new A({status:"argument_required",argument:"env",agentMode:_.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([cf(),Je()]),r=Math.max(0,...e.map(({env:s})=>s.length));v.setInteractive();let n=await N(s=>pN({message:"Which environment is the token for?",choices:[...e.map(({env:i})=>({name:`${i.padEnd(r)} ${t?.envs[i]?"set \u2014 replace":"not set"}`,value:i})),{name:"+ new env\u2026",value:Aw}]},s),{output:ut.stderr,whenHeadless:"refuse"});return n!==Aw?n:(await N(s=>uN({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:ut.stderr,whenHeadless:"refuse"})).trim()},kN=async(e,t,r)=>N(n=>lN({message:`Replace the "${e}" token ${be(t)} with ${be(r)}?`,default:!0},n),{output:ut.stderr,whenHeadless:"refuse"}),bN=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${be(r)})`;case"replaced":return`Replaced the "${e}" service token ${be(n??"")} \u2192 ${be(r)}`;case"unchanged":return`The "${e}" service token is already ${be(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${be(n??"")} \u2014 nothing was written`;default:return Ne(t)}},ap=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Qt(),s=e??await wN(),{token:i,source:a}=await fN({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Ow(i,o,s,n),l=(await Je())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await kN(s,l,i)?u="kept":(await ic({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Ct();d.info(`${bN(s,u,i,l)} in ${k(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${ip} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:be(i),previousRedactedToken:l===void 0?null:be(l),storePath:p,scopeVerified:c};return v.print(),{content:R(JSON.stringify(m,null,2)),structuredContent:m}},RN=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,Dw=e=>{let t=e.split(/\r?\n/).flatMap((n,o)=>{let s=n.trim();if(s===""||s.startsWith("#"))return[];let i=s.indexOf("="),a=i>0?s.slice(0,i).trim():"",c=i>0?RN(s.slice(i+1).trim()):"";if(!/^\S+$/.test(a)||c==="")throw new Error(`Token file line ${o+1} is not \`<env>=<token>\` \u2014 nothing was written.`);return[{env:a,token:c}]});if(t.length===0)throw new Error("The token file holds no `<env>=<token>` lines \u2014 nothing was written.");let r=new Set;for(let{env:n}of t){if(r.has(n))throw new Error(`"${n}" appears twice in the token file \u2014 nothing was written.`);r.add(n)}return t},SN=e=>(e instanceof Error?e.message:String(e)).split(`
|
|
433
|
+
`)[0]??"",EN=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",PN=async(e,t,r,n)=>{let o=be(e.token);try{let s=await Ow(e.token,t,e.env,n);return{env:e.env,status:EN(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:SN(s)}}},cp=async({fromFile:e,force:t})=>{let r=await Qt(),n=Dw(await mN.readFile(e,"utf8")),o=await Je(),s=await Promise.all(n.map(p=>PN(p,r,o?.envs[p.env],t))),i=Object.fromEntries(n.filter((p,m)=>s[m]?.status==="stored"||s[m]?.status==="replaced").map(({env:p,token:m})=>[p,m]));Object.keys(i).length>0&&await ic(i);let a=await Ct(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${k(e)} \u2192 ${k(a)}:`);for(let p of s){let m=p.error?` ${p.error}`:"";d.info(` ${p.env.padEnd(c)} ${p.status.padEnd(9)} ${p.redactedToken}${m}`)}d.warn(`${k(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(ut.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}};var lp=async(e,t,r=!0)=>{let{from:n,version:o,env:s,services:i,skipTerraform:a,yes:c,dryRun:l,printEnv:u}=e,p=await qu(n);if(r&&v.addOption("--from",p),Hu(p,{"--version":o,"--skip-terraform":a,"--dry-run":l,"--print-env":u}),p==="local")throw new g(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"?ta({version:o,env:s,skipTerraform:a,confirmedCommand:c}):ra({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},up=async e=>lp(e,"all"),dp=async e=>lp(e,"selected"),_a=async(e,t)=>{let r=`release deploy-${t} --from local`;return d.warn(`\`local deploy-${t}\` is deprecated and will be removed \u2014 use \`${r}\` instead.`),lp({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Nw}from"@slip-stream-kit/config/internal";import pp from"node:fs/promises";import In from"node:path";import Iw from"node:process";import{pathToFileURL as xN}from"node:url";var _w="~/projects",mp=async(e={})=>{if(e.init){await CN(e.cwd);return}await TN()},TN=async()=>{let e=fn(),t=await ee(e);if(d.info(`Factory config: ${k(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Iw.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await $i(),s=gn(r),i=await ee(s),a=In.join(s,n),c=await ee(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${k(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=In.join(s,u),m=await ee(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",w=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${k(p)}${w}`)}l||(Iw.exitCode=1)},CN=async e=>{let t=fn();if(await ee(t)){d.info(`Factory config already exists at ${k(t)} \u2014 leaving it untouched.`);return}let r=e??await $(),n=await $N(r);await pp.mkdir(In.dirname(t),{recursive:!0}),await pp.writeFile(t,AN(In.basename(r),n),"utf-8"),d.info(`\u2713 Created ${k(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${Nw}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${_w}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${In.basename(r)} (this repo); change it if the source is another repo.`),n.length===0&&d.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},$N=async e=>{try{let t=In.join(e,Nw),r=await pp.stat(t),s=(await import(`${xN(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[]},AN=(e,t)=>`${JSON.stringify({workspaceDir:_w,source:e,targets:t},null,2)}
|
|
434
|
+
`;import{existsSync as F_}from"node:fs";import L_ from"node:fs/promises";import lk from"node:path";import uk from"node:process";import{z as B_}from"zod";import{chmodSync as FN,copyFileSync as LN,lstatSync as BN,mkdirSync as Jw,readdirSync as UN,readlinkSync as VN,rmSync as WN,rmdirSync as Kw,symlinkSync as GN,unlinkSync as JN,writeFileSync as KN}from"node:fs";import ve from"node:path";import{lstatSync as ON,readlinkSync as Mw}from"node:fs";import DN from"node:path";var IN=new Set(["ENOENT","ENOTDIR"]),Ma=e=>{let t;try{t=ON(e)}catch(r){if(IN.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:Mw(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Er(e)}:{kind:"other"}},jw=(e,t)=>{let r=DN.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:Mw(r)}:{kind:"file",executable:t.mode==="100755",sha:Er(r)};return{...t,fingerprint:n}},Fw=(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 NN}from"zx";var H=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await NN({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ja=e=>e.slice(0,7),He=e=>e.split("\0").filter(t=>t.length>0);import _N from"node:path";var fp=`${te}/`,qt=`${te}/README.md`,Es=`${te}/${Ve}`,Bw=e=>e.startsWith(fp),Lw=e=>{let t=_N.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},Uw=e=>{let t=Lw(e.path),r=e.target===void 0?t:Lw(e.target);return{path:t,target:r,vendored:Bw(r),module:e.module??null}},Vw=e=>e.copy.map(Uw),Ps=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),xs=(e,t)=>e.filter(r=>!Ps(r.path,t)),Fa=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Nn=e=>[...new Set(e)].sort(),Ww=e=>e.startsWith(fp)?e.slice(fp.length):null;var La=e=>`# vendor/ \u2014 mirrored from ${e}
|
|
430
435
|
|
|
431
436
|
**DO NOT EDIT files in this folder here.**
|
|
432
437
|
|
|
@@ -437,19 +442,19 @@ fail \`ik vendor check\` in CI.
|
|
|
437
442
|
To change a vendored package, edit it in \`${e}\` and re-run the sync there.
|
|
438
443
|
|
|
439
444
|
See \`.sync-manifest.json\` for the source commit and per-file checksums.
|
|
440
|
-
`;var
|
|
441
|
-
`).trim()||String(e)},
|
|
442
|
-
`).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},
|
|
443
|
-
`)[0]??"git rev-parse failed"}}},
|
|
444
|
-
`).slice(0,
|
|
445
|
-
${
|
|
446
|
-
`)},
|
|
447
|
-
`),$(e)),n_=e=>e.description("List all release branches").action(async()=>{$(await Gi())}),o_=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".',t_,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Vl),o=n.length>0?n:void 0;$(await Yi({releases:o,confirmedCommand:t.yes}))}),s_=e=>{if(e==="")return e;try{return dr(e)}catch(t){throw t instanceof wn?new ZN(t.message):t}},i_=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)',s_).option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await zi({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),qw=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Wt.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),a_=e=>qw(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{$(await Jd({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),c_=e=>qw(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 Kd({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),l_=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 Ui({version:t.version,confirmedCommand:t.yes}))}),u_=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 Qi({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),d_=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{$(await ga({confirmedCommand:t.yes}))}),p_=e=>e.description("Add git worktrees for release branches or feature 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("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").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=>{$(await da({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),m_=e=>e.description("List all git worktrees with detailed information").action(async()=>{$(await pa())}),f_=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{$(await fa({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),g_=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 qd({init:t.init}))}),h_=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await ca();$(t),t.structuredContent.ok||($e.exitCode=1)}),y_=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan").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 lp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!pt(a))throw a;d.info("Operation cancelled.");return}$(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&($e.exitCode=1)}),v_=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{$(await xd())}),w_=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{$(await Td())}),k_=new Set(["version"]),Ia=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},mp=()=>{let e=new XN().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");r_(t.command("merge-dev")),n_(t.command("list")),o_(t.command("create")),i_(t.command("edit")),a_(t.command("deploy-all")),c_(t.command("deploy-selected")),l_(t.command("deliver")),u_(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");p_(r.command("add")),m_(r.command("list")),f_(r.command("remove")),d_(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");v_(n.command("path")),w_(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{$(await ei({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{$(await Vc({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{$(await Cd({key:a,global:c.global}))});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 wa({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 wa({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){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),$e.exitCode=1;return}let c=await Xs({all:a.all,root:a.root,fix:a.fix,design:a.design});$(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&($e.exitCode=1)}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await Ld({check:a.check});$(c),c.structuredContent.ok||($e.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return h_(i.command("check")),g_(i.command("config")),y_(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});zt.enabled||Zc(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&($e.exitCode=1),$(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (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("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").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"),u=!!($e.stdout.isTTY&&$e.stdin.isTTY);await l({...c,appName:a},u,zt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{$(await ti())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").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("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{$(await Ni({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,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)").addOption(new Kw("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Kw("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){$(await zu());return}$(await na({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{$(await la())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{$(await ji())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{$(await Gm())}),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). Omitted: the picker opens on defaultEnv; headless runs load it").action(async a=>{Hw(await Xa({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Hw(await Mi())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");$(await Wd({fromFile:c.fromFile,force:c.force}));return}$(await Vd({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 Fi({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 Bd({env:a}))}),e.commands.forEach(Yp),dp(e),pp(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&e_(QN($e.cwd(),l)),h.start(Ia(c)),zt.enabled=!!c.optsWithGlobals().json,zt.enabled&&(d.level="warn"),_.source=Cs({env:$e.env,stdinIsTTY:$e.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),k_.has(Ia(c))||await Rl()}),e.hook("postAction",(a,c)=>{let l=Ia(c);if(Sd(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Ww({equivalent:$a(f,!0)})}),e};import b_ from"node:process";var R_={exit:b_.exit,emit:$,logger:d},Yw=(e,t=R_)=>Se(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof C?(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 fp=(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 S_ from"node:fs";import gp from"node:path";import On from"node:process";var Zw=new Set([...dm,Dn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Qw=null,Da=new Set,hp=null,zw=!1;var Xw=e=>{try{return S_.statSync(e)}catch{return null}},E_=()=>{if(zw)return null;try{return Tr()}catch{return zw=!0,d.debug(`session-env: ${Dn} unset \u2014 no overlay`),null}},P_=e=>{let t=gp.join(e,Pr),r=gp.join(e,vs),n=Xw(t),o=Xw(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?xp(gp.join(e,ws),On.cwd())?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:{kind:"none",signature:"none"}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},x_=e=>e.kind==="load"?{kind:"load",vars:Ep(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Pp(e.file),signature:e.signature}:e;var T_=()=>{let e=E_();if(e===null)return{kind:"no-session"};let t=P_(e);return t.signature===hp?null:x_(t)},C_=()=>{for(let e of Da){let t=Qw[e];t===void 0?delete On.env[e]:On.env[e]=t}Da.clear()},$_=(e,t,r)=>{if(Zw.has(t)){e.skipped.push(t);return}On.env[t]=r,Da.add(t),e.set.push(t)},A_=(e,t)=>{if(Zw.has(t)){e.skipped.push(t);return}delete On.env[t],Da.add(t),e.unset.push(t)},O_=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))$_(t,r,n);if(e.kind==="clear")for(let r of e.unset)A_(t,r);return t},I_=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,yp=(e=T_())=>{if(Qw??={...On.env},e===null||e.kind==="no-session"||e.signature===hp)return{set:[],unset:[],changed:!1};C_();let{set:t,unset:r,skipped:n}=O_(e);return hp=e.signature,n.length>0&&d.warn(`session-env: skipped protected names [${n.join(", ")}]`),d.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${I_(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as Q_}from"chalk";import{spawn as eM}from"node:child_process";import Ae from"node:process";import{Chalk as D_}from"chalk";var In=new D_({level:1}),qe={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."},N_={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"}},ek={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},tk={unicode:"\u2500",ascii:"-"},__=3,vp=e=>e,M_={ok:e=>In.green(e),findings:e=>In.yellow(e),failed:e=>In.red(e),cancelled:e=>In.gray(e)},kp=e=>e?{dim:t=>In.dim(t),bold:t=>In.bold(t)}:{dim:vp,bold:vp},j_=(e,t)=>e?M_[t]:vp,wp=e=>[...e].length,F_=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return wp(e)<=r?e:[...e].slice(0,r).join("")},rk=e=>{let t=kp(e.color===!0).dim,r=N_[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(F_(n,e.width))},nk=(e,t={})=>{let r=kp(t.color===!0);return`${r.dim(qe.reproPrefix.trim())} ${r.bold(e)}`},L_=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,B_=(e,t)=>e==="findings"?t!=null?`${t} ${qe.findingsSuffix}`:qe.findingsPlain:{ok:qe.ok,failed:qe.failed,cancelled:qe.cancelled}[e],U_=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<__?"":` ${n(r.repeat(o))}`},ok=e=>{let t=e.color===!0,r=kp(t),n=j_(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?qe.reproPrefix:qe.nonReproPrefix,i=o?ek[e.outcome].ascii:ek[e.outcome].unicode,a=B_(e.outcome,e.findingsCount),c=[L_(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
448
|
-
`)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${qe.sep}${c.join(qe.sep)}`,m=
|
|
449
|
-
`)};var
|
|
450
|
-
`,
|
|
445
|
+
`;var MN=new Set(["100644","100755","120000"]),jN=(e,t)=>{let r=new Map;for(let n of He(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!MN.has(s)||Ps(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},gp=async(e,t,r)=>{let n=await H(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return jN(n,r)},Gw=async e=>He(await H(e,["--literal-pathspecs","ls-files","-z","--",te]));var _n=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],Hw=e=>{let t=Ma(e);t!==null&&(t.kind==="other"?Kw(e):JN(e))},HN=(e,t,r)=>{let n=ve.join(e,r.source),o=ve.join(t,r.target);if(Jw(ve.dirname(o),{recursive:!0}),Hw(o),r.mode==="120000"){GN(VN(n),o);return}LN(n,o),FN(o,r.mode==="100755"?493:420)},qN=async(e,t)=>{let r=new Set;for(let n of He(await H(e,["ls-files","-z"]))){if(t.has(n))continue;let o=ve.posix.dirname(n);for(;o!==".";)r.add(o),o=ve.posix.dirname(o)}return r},YN=async(e,t)=>{if(t.length===0)return;let r=await qN(e,new Set(t)),n=[...new Set(t.map(o=>ve.dirname(ve.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)&&!(!BN(s,{throwIfNoEntry:!1})?.isDirectory()||UN(s).length>0||r.has(ve.relative(e,s).split(ve.sep).join("/")));)Kw(s),s=ve.dirname(s)}},qw=(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,qt,...s].map(Ww).filter(a=>a!==null&&!ya(a));return Nn(i)},Yw=async(e,t,r,n)=>{let o=ve.join(e,te);Jw(o,{recursive:!0}),KN(ve.join(e,qt),La(t.name));let s=qw(r,await Gw(e),n);Od(o,{source:t.name,commit:t.headSha},s)},hp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(_n(t));let n=ve.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)Hw(ve.join(n,a));await YN(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&WN(ve.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)HN(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await Yw(n,e,t.entries,o),{touched:Nn([...o,...i,qt,Es]),manifestWritten:!0}):{touched:Nn([...o,...i]),manifestWritten:!1}},yp=async(e,t)=>(await Yw(e,t,[],[]),[qt,Es]);var vp=(e,t)=>`[ROOT] vendor: sync from ${e}@${ja(t)}`,zN=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
|
|
446
|
+
`).trim()||String(e)},wp=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 H(e,["--literal-pathspecs","add","-A",...o],{input:n}),await H(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:zN(s)}}};var zw=20,XN=20,bp=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],kp=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of xs(e.files,r)){let p=Fa(u.path,n);if(s.push(p),Fw(u.fingerprint,t.onDisk[p]??null))continue;let m=o.has(p)?"modified":"added";i.push({source:u.path,target:p,mode:u.mode,change:m})}let a=new Set(s),c=xs(t.tracked.map(u=>({path:u})),r).map(u=>u.path).filter(u=>!a.has(u)),l=i.filter(u=>u.change==="added").length;return{...n,targetPaths:s,writes:i,deletes:c,counts:{added:l,modified:i.length-l,removed:c.length},pruned:!1}},xr=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Rp=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),ZN=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...Rp(e,r)];return xr(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...bp(n,zw),De(o)])},QN=(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=ja(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}`,...bp(e.lines,XN)],warnings:[]}},e_=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},t_=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},r_=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Nn([...n,...r?t.headVendorMeta:[]])},n_=e=>e.entries.filter(t=>t.scope==="release"&&t.tracked.length>0).map(t=>`${t.target}: not in vendorTarget.modules, left in place for this repo to own`),o_=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return ZN(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return xr(t,"fail","blocked: a module this repo dropped is still a dependency",[...bp(t.pruneConflicts,zw)]);let n=e.entries.flatMap((f,w)=>{let h=t.entries[w]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return h.scope==="release"?[]:h.scope==="sync"?[kp(f,h,e.exclude)]:[{...kp({...f,files:[]},h,e.exclude),pruned:!0}]}),o=n.some(f=>f.vendored),s=n.some(f=>f.writes.length+f.deletes.length>0),i=o&&(!t.readmeCurrent||!t.manifestPresent),a={...xr(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=QN(t.changelog,e.name),l=t.manifestSource!==null&&t.manifestSource!==e.name?[`vendor/ was last synced from ${t.manifestSource}, not ${e.name}: this sync replaces it`]:[],u=n.map(e_).filter(f=>f!==null),m=t.entries.some(f=>f.scope==="prune"&&f.tracked.length>0)?["vendored modules removed: run pnpm install to update the lockfile"]:[];return{...a,status:"changed",message:`${t_(n)} on ${t.branch}`,notes:[...u,...m,...n_(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:r_(n,t,o)}},Ba=(e,t)=>{switch(t.kind){case"missing":return xr(t,"skipped",`not checked out at ${t.root}`);case"source":return xr(t,"skipped","this is the source repo");case"not-git":return xr(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return xr(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return o_(e,t)}};import{existsSync as p_,readFileSync as m_,realpathSync as Ua}from"node:fs";import Va from"node:path";import{readFileSync as Xw}from"node:fs";import Mn from"node:path";var s_=["dependencies","devDependencies","peerDependencies","optionalDependencies"],i_=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},Zw=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=i_(e);if(t.kind==="modules"){let n=t.modules.filter(o=>!r.includes(o));if(n.length>0){let o=r.length>0?r.join(", "):"none";return{reason:`unknown module(s) ${n.join(", ")} in vendorTarget.modules; the source offers: ${o}`}}}return e.map(({entry:n})=>n.module===null||t.kind==="all"||t.modules.includes(n.module)?"sync":n.vendored?"prune":"release")},Qw=e=>{try{return JSON.parse(Xw(e,"utf8"))}catch{return null}},a_=(e,t)=>t.files.flatMap(r=>{let n=Mn.posix.relative(t.entry.path,r.path);if(Mn.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=Qw(Mn.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),c_=e=>s_.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),ek=(e,t)=>{let r=e.indexOf(t);for(;r>=0;){if(!/[\w-]/.test(e[r+t.length]??""))return!0;r=e.indexOf(t,r+1)}return!1},l_=["*.sh","*.yml","*.yaml"],u_=(e,t,r)=>{let n=c_(t).includes(r)?[`${e} depends on ${r}`]:[],o=t.scripts!==null&&typeof t.scripts=="object"?t.scripts:{};for(let[s,i]of Object.entries(o))typeof i=="string"&&ek(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},d_=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...l_];return He(await H(e,n,{allowFailure:!0})).filter(s=>r(s)&&ek(Xw(Mn.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},tk=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of a_(e,c))n.set(l,c.entry.module??"");if(n.size===0)return[];let o=r.map(({target:c})=>`${c}/`),s=c=>!o.some(l=>c.startsWith(l)),i=He(await H(t,["ls-files","-z","--","*package.json"])).filter(c=>Mn.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=Qw(Mn.join(t,p));return m===null?[]:u_(p,m,c)});u.push(...await d_(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var Sp=async(e,t)=>{let r=t.exclude??[],n=(await H(e,["rev-parse","HEAD"])).trim(),o=await Re(e),s=await Promise.all(Vw(t).map(async i=>{let a=await gp(e,i.path,r);return{entry:i,files:a.map(c=>jw(e,c))}}));return{root:e,selfRoots:[...new Set([Ua(e),Ua(o)])],name:Va.basename(o),headSha:n,entries:s,exclude:r}},Wa=e=>{let t=He(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},f_=async(e,t,r)=>{let n=Rp(e,t);if(n.length===0)return[];let o=await H(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return Wa(o).filter(s=>!Ps(s,e.exclude))},g_=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await gp(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of xs(l,e.exclude)){let p=Fa(u.path,n);c[p]=Ma(Va.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),h_=async e=>{try{return He(await H(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",qt,Es]))}catch{return[]}},y_=e=>{try{let{commit:t,source:r}=gs(Va.join(e,te));return{commit:t,source:r}}catch{return null}},v_=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await Ie(e.root,r)===null)return{kind:"unresolvable",sha:r};let n=e.entries.filter((i,a)=>t[a]==="sync").map(({entry:i})=>i.path);if(n.length===0)return{kind:"log",sha:r,lines:[]};let s=(await H(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
|
|
447
|
+
`).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},w_=(e,t)=>{try{return m_(Va.join(e,qt),"utf8")===La(t)}catch{return!1}},k_=async e=>{try{return{toplevel:(await H(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
|
|
448
|
+
`)[0]??"git rev-parse failed"}}},b_=async e=>{try{return(await H(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},Ga=async(e,t)=>{if(!p_(t.root))return{...t,kind:"missing"};let r=Ua(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await k_(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Ua(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=Zw(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=y_(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([b_(t.root),f_(e,o,t.root),g_(e,o,t.root),h_(t.root),v_(e,o,i)]),m=l.flatMap((f,w)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[w],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:w_(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await tk(e.root,t.root,m)}};var R_=20,S_=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],E_=(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:",De(_n(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:S_(r,t)}},P_=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(`
|
|
449
|
+
`).slice(0,R_)},x_=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[E_(e,t),...r,...e.commit?[P_(e.commit)]:[]]}},T_={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},Ep=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:T_[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>x_(o,r))],hints:n}},rk=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),nk=(e,t,r)=>{let n=new Set(e.sections.flatMap(s=>s.rows.map(i=>`${s.label}\0${i.name}\0${i.status}`))),o=t.sections.map(s=>({label:s.label,rows:s.rows.filter(i=>!n.has(`${s.label}\0${i.name}\0${i.status}`))}));return{...t,sections:o,emptyMessage:`synced ${r.join(", ")}`}};var C_=20,Pp=async(e,t)=>(await H(e,t,{allowFailure:!0})).trim(),$_=async e=>Wa(await H(e,["status","--porcelain","-z","--untracked-files=normal"])),A_=async e=>(await Pp(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"]},O_=async e=>{let[t,r]=await Promise.all([Pp(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),Pp(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}`}},ok=async e=>{let t=await $_(e);if(t.length>0){let n=t.slice(0,C_),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new A({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),O_(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import __ from"node:path";import{readFileSync as D_}from"node:fs";import I_ from"node:path";import{z as N_}from"zod";var sk=e=>{let t;try{t=D_(I_.join(e,"infra-kit.json"),"utf8")}catch{return{kind:"all"}}let r;try{r=JSON.parse(t)?.vendorTarget}catch(o){return{kind:"invalid",reason:`infra-kit.json is not valid JSON: ${o.message}`}}if(r===void 0)return{kind:"all"};let n=Dm.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:N_.prettifyError(n.error)}};var ik=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new A({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=gn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=__.join(n,s);return{name:s,root:i,selection:sk(i)}})},M_="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",j_=async(e,t)=>{let r=await Ga(e,t),n=Ba(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${M_} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},ak=async(e,t,r)=>Promise.all(t.map(async n=>r?j_(e,n):Ba(e,await Ga(e,n))));var dk="sync vendored files",U_=e=>{let t=lk.join(gn(e.workspaceDir),e.source);if(F_(t))return t;throw new A({status:"refused",reason:"source-missing",source:t},1,{operation:dk,stderrExcerpt:`the source repo ${e.source} is not checked out at ${t}`,remediation:'clone it there, or fix "source" / "workspaceDir" in ~/.infra-kit/vendor.json'})},xp=(e,t)=>new A({status:"refused",reason:"not-a-vendor-source"},1,{operation:dk,stderrExcerpt:`${e} ${t}`,remediation:`add a vendorSource block to the source repo's committed infra-kit.json, or point "source" at the repo that has one`}),V_=async e=>{let t=lk.join(e,"infra-kit.json"),r;try{r=JSON.parse(await L_.readFile(t,"utf8"))}catch(s){throw xp(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw xp(t,"has no vendorSource block");let o=Om.safeParse(n);if(!o.success)throw xp(t,`has an invalid vendorSource: ${B_.prettifyError(o.error)}`);return o.data},ck=(e,t)=>{uk.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
|
|
450
|
+
${De(t)}
|
|
451
|
+
`)},W_=async(e,t,r)=>r?(ck(t,_n(t)),yp(t.root,e)):(await hp({source:e,plan:t,onBeforeFirstWrite:o=>{ck(t,o)}})).touched,G_=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await W_(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 wp(t.root,n,vp(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},J_=async(e,t,r)=>{let n=[];for(let o of t)n.push(await G_(e,o,r));return n},pk=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})),Tp=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&rt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:pk(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:rk(t),report:t.sections}}},K_=async e=>{let t=await $i(),r=U_(t),n=await ok(r),o=await V_(r),s=ik(t,e.targets??[]),i=await Sp(r,o),a=await ak(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},Cp=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await K_(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=Ep(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return Tp({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!q();if(l&&!uk.stdin.isTTY)return rt(a),Tp({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&rt({...a,hints:[]}),await U(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:pk(n),throwOnDecline:!0});let u=await J_(t,n,e),p=Ep(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);rt(nk(a,p,m))}return Tp({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var Ja=(e,t=!0)=>({line:e,reproducible:t});import Ka from"node:fs";import H_ from"node:os";import q_ from"node:path";import hk from"node:process";var Ha="INFRA_KIT_SESSION_REPORT",$p=null,mk=!1,fk=[],yk=(e=hk.env)=>{mk||($p=e[Ha]??null,mk=!0,delete e[Ha])};var vk=(e,t)=>{if(!$p)return;let r=e.summary??(fk.length>0?[...fk]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{Ka.writeFileSync(s,i)});try{o($p,JSON.stringify(n))}catch{}},gk=0,wk=e=>{let t=e?.tmpdir?.()??H_.tmpdir(),r=e?.pid??hk.pid;return gk+=1,q_.join(t,`infra-kit-session-${r}-${gk}.json`)},kk=(e,t)=>{if(!(t?.exists??(i=>Ka.existsSync(i)))(e))return null;let n=t?.read??(i=>Ka.readFileSync(i,"utf-8")),o=t?.unlink??(i=>Ka.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var Ap=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(Ap)};var Op=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)"),e.commands.forEach(Op)};var Q_=(e,t)=>[...t,e],eM=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 $g(()=>qi({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}));O(r),r.structuredContent.failedMerges>0&&($e.exitCode=1)}),Rk=e=>($e.stdout.write(`${e.structuredContent.filePath}
|
|
452
|
+
`),O(e)),tM=e=>e.description("List all release branches").action(async()=>{O(await na())}),rM=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".',Q_,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(ou),o=n.length>0?n:void 0;O(await ca({releases:o,confirmedCommand:t.yes}))}),nM=e=>{if(e==="")return e;try{return pr(e)}catch(t){throw t instanceof Rn?new z_(t.message):t}},oM=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)',nM).option("-y, --yes","Skip confirmation prompt").action(async t=>{O(await la({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Sk=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Gt.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"),sM=e=>Sk(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{O(await up({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),iM=e=>Sk(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=>{O(await dp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),aM=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=>{O(await zi({version:t.version,confirmedCommand:t.yes}))}),cM=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=>{O(await pa({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),lM=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{O(await Ca({confirmedCommand:t.yes}))}),uM=e=>e.description("Add git worktrees for release branches or feature 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("-f, --feature <names>","Feature worktrees by comma, each on a feature/<name> branch, e.g. checkout-v2").option("-b, --base <branch>","Base for new feature branches: dev (default; the default branch without one), main, or a release, e.g. 1.4.0").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=>{O(await Ea({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),dM=e=>e.description("List all git worktrees with detailed information").action(async()=>{O(await Pa())}),pM=e=>e.description("Remove git worktrees for release or feature branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release and feature worktrees").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-f, --feature <names>","Feature worktrees by comma, e.g. checkout-v2").option("--self","Remove the worktree this runs in, closing its Orca tabs (handed off to Orca)").action(async t=>{O(await Ta({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),mM=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=>{O(await mp({init:t.init}))}),fM=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await ba();O(t),t.structuredContent.ok||($e.exitCode=1)}),gM=e=>e.description("Mirror vendorSource files from the ~/.infra-kit/vendor.json source into every target, from any directory").argument("[targets...]","Narrow to these target names from ~/.infra-kit/vendor.json").option("-y, --yes","Apply the previewed plan").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 Cp({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!mt(a))throw a;d.info("Operation cancelled.");return}O(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&($e.exitCode=1)}),hM=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{O(await Yd())}),yM=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{O(await zd())}),vM=new Set(["version"]),qa=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},Dp=()=>{let e=new Y_().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");eM(t.command("merge-dev")),tM(t.command("list")),rM(t.command("create")),oM(t.command("edit")),sM(t.command("deploy-all")),iM(t.command("deploy-selected")),aM(t.command("deliver")),cM(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");uM(r.command("add")),dM(r.command("list")),pM(r.command("remove")),lM(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");hM(n.command("path")),yM(n.command("edit")),e.command("config-get").description("Print the fully merged infra-kit config (project + user-global + per-project override layers)").argument("[key]","Print only this top-level key (e.g. worktrees)").action(async a=>{O(await li({key:a}))}),e.command("config-set").description("Set a top-level key in this project\u2019s per-machine config override (validated before it is kept)").argument("<key>","Top-level config key (e.g. protectedEnvs, worktrees)").argument("<value>",`JSON value, or a bare string (e.g. cli-only, '{"openInOrca":true}')`).option("--global","Write ~/.infra-kit/infra-kit.json (every project on this machine) instead").action(async(a,c,l)=>{O(await ol({key:a,value:c,global:l.global}))}),e.command("config-unset").description("Remove a top-level key from this project\u2019s per-machine config override").argument("<key>","Top-level config key").option("--global","Remove it from ~/.infra-kit/infra-kit.json instead").action(async(a,c)=>{O(await Xd({key:a,global:c.global}))});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=>{O(await _a({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=>{O(await _a({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){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),$e.exitCode=1;return}let c=await ii({all:a.all,root:a.root,fix:a.fix,design:a.design});O(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&($e.exitCode=1)}),e.command("deploy-run").description("Deploy a service: its deploy.ts from infra-kit.deploy.ts, else its devops/scripts .sh (what the CI deploy job runs)").argument("<service>","The service as infra-kit.deploy.ts names it, e.g. client-be").action(async a=>{O(await rp({service:a}))}),e.command("deploy-sync").description("Generate the deploy-all / deploy-selected workflows from infra-kit.deploy.ts").option("--check","Compare only; exit 1 when the committed workflows differ from the manifest").action(async a=>{let c=await op({check:a.check});O(c),c.structuredContent.ok||($e.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");return fM(i.command("check")),mM(i.command("config")),gM(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 Li({fix:!!a.fix});Xt.enabled||fl(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&($e.exitCode=1),O(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (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("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").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"),u=!!($e.stdout.isTTY&&$e.stdin.isTTY);await l({...c,appName:a},u,Xt.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{O(await ui())}),e.command("e2e").description("Run an app\u2019s Playwright e2e against this worktree (dev reused or started), or --cloud").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("--cloud","Run against the deployed app at INFRA_KIT_ENV instead of this worktree").option("-y, --yes","Skip the confirmation a cloud run asks for").action(async(a,c)=>{O(await Wi({app:c.app,dryRun:c.dryRun,yes:c.yes,cloud:c.cloud,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)").addOption(new bk("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new bk("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){O(await wd());return}O(await ha({tools:a.tools,update:a.update,skipTools:a.skipTools,ascii:!!a.ascii,unattended:a.unattended}))}),e.command("version").description("Print the installed infra-kit CLI version").action(async()=>{O(await Ra())}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{O(await Ki())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{O(await uf())}),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). Omitted: the picker opens on defaultEnv; headless runs load it").action(async a=>{Rk(await mc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Rk(await Ji())}),e.command("env-token-set").description("Add or replace the Doppler service token for an env (masked prompt or piped stdin; validated against Doppler before writing)").argument("[env]","Environment / Doppler config the token is scoped to (e.g. dev); omitted \u2192 picker, incl. a new env").option("--stdin","Read the token from stdin (implied when stdin is piped, e.g. `op read \u2026 | ik env-token-set dev`)").option("--from-env <var>","Read the token from the named environment variable (the NAME, never the value)").option("--from-file <path>","Import several tokens from a `<env>=<token>` file, each validated on its own").option("--force","Store even when the token\u2019s scope could not be verified. Never overrides a real mismatch.").action(async(a,c)=>{if(c.fromFile){if(a||c.stdin||c.fromEnv)throw new Error("--from-file names its envs itself \u2014 drop <env>, --stdin and --from-env.");O(await cp({fromFile:c.fromFile,force:c.force}));return}O(await ap({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=>{O(await Hi({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=>{O(await sp({env:a}))}),e.commands.forEach(fm),Ap(e),Op(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&Z_(X_($e.cwd(),l)),v.start(qa(c)),Xt.enabled=!!c.optsWithGlobals().json,Xt.enabled&&(d.level="warn"),_.source=js({env:$e.env,stdinIsTTY:$e.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),vM.has(qa(c))||await Fl()}),e.hook("postAction",(a,c)=>{let l=qa(c);if(Kd(l))return;let p=v.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;vk({equivalent:Ja(f,!0)})}),e};import wM from"node:process";var kM={exit:wM.exit,emit:O,logger:d},Ek=(e,t=kM)=>Se(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof A?(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 Ip=(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 bM from"node:fs";import Np from"node:path";import jn from"node:process";var Tk=new Set([...Am,Ln,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Ck=null,Ya=new Set,_p=null,Pk=!1;var xk=e=>{try{return bM.statSync(e)}catch{return null}},RM=()=>{if(Pk)return null;try{return Ar()}catch{return Pk=!0,d.debug(`session-env: ${Ln} unset \u2014 no overlay`),null}},SM=e=>{let t=Np.join(e,Cr),r=Np.join(e,Ts),n=xk(t),o=xk(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Jp(Np.join(e,Cs),jn.cwd())?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:{kind:"none",signature:"none"}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},EM=e=>e.kind==="load"?{kind:"load",vars:Wp(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Gp(e.file),signature:e.signature}:e;var PM=()=>{let e=RM();if(e===null)return{kind:"no-session"};let t=SM(e);return t.signature===_p?null:EM(t)},xM=()=>{for(let e of Ya){let t=Ck[e];t===void 0?delete jn.env[e]:jn.env[e]=t}Ya.clear()},TM=(e,t,r)=>{if(Tk.has(t)){e.skipped.push(t);return}jn.env[t]=r,Ya.add(t),e.set.push(t)},CM=(e,t)=>{if(Tk.has(t)){e.skipped.push(t);return}delete jn.env[t],Ya.add(t),e.unset.push(t)},$M=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))TM(t,r,n);if(e.kind==="clear")for(let r of e.unset)CM(t,r);return t},AM=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Mp=(e=PM())=>{if(Ck??={...jn.env},e===null||e.kind==="no-session"||e.signature===_p)return{set:[],unset:[],changed:!1};xM();let{set:t,unset:r,skipped:n}=$M(e);return _p=e.signature,n.length>0&&d.warn(`session-env: skipped protected names [${n.join(", ")}]`),d.debug(`session-env applied: set [${t.join(", ")}] unset [${r.join(", ")}] (${AM(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as XM}from"chalk";import{spawn as ZM}from"node:child_process";import Ae from"node:process";import{Chalk as OM}from"chalk";var Fn=new OM({level:1}),qe={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."},DM={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"}},$k={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Ak={unicode:"\u2500",ascii:"-"},IM=3,jp=e=>e,NM={ok:e=>Fn.green(e),findings:e=>Fn.yellow(e),failed:e=>Fn.red(e),cancelled:e=>Fn.gray(e)},Lp=e=>e?{dim:t=>Fn.dim(t),bold:t=>Fn.bold(t)}:{dim:jp,bold:jp},_M=(e,t)=>e?NM[t]:jp,Fp=e=>[...e].length,MM=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Fp(e)<=r?e:[...e].slice(0,r).join("")},Ok=e=>{let t=Lp(e.color===!0).dim,r=DM[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(MM(n,e.width))},Dk=(e,t={})=>{let r=Lp(t.color===!0);return`${r.dim(qe.reproPrefix.trim())} ${r.bold(e)}`},jM=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,FM=(e,t)=>e==="findings"?t!=null?`${t} ${qe.findingsSuffix}`:qe.findingsPlain:{ok:qe.ok,failed:qe.failed,cancelled:qe.cancelled}[e],LM=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<IM?"":` ${n(r.repeat(o))}`},Ik=e=>{let t=e.color===!0,r=Lp(t),n=_M(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?qe.reproPrefix:qe.nonReproPrefix,i=o?$k[e.outcome].ascii:$k[e.outcome].unicode,a=FM(e.outcome,e.findingsCount),c=[jM(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
453
|
+
`)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${qe.sep}${c.join(qe.sep)}`,m=Fp(u)+Fp(p),f=LM(m,e.width,o?Ak.ascii:Ak.unicode,r.dim),w=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&w.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&w.push(r.dim(qe.envNotice)),w.join(`
|
|
454
|
+
`)};var BM=new Set([130,143]),Nk=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&BM.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import UM from"node:process";var VM={3:"quit",4:"quit",26:"suspend",27:"quit"},WM=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":VM[t]??"continue"},GM=150,JM="\r\x1B[2K",KM=`\r
|
|
455
|
+
`,_k=(e,t)=>{Mk(e),e.stdin.on("data",t),e.listener=t},Mk=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},jk=(e,t)=>{Bm(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),_k(e,t)},Fk=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(JM)),Mk(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Um()},HM=e=>{e.settled||(e.settled=!0,Fk(e))},Lk=(e,t)=>{let r=Ok({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},qM=async e=>{await new Promise(t=>{setTimeout(t,e)})},YM=(e,t,r)=>{Fk(e),t(),jk(e,r),Lk(e,KM)},zM=async e=>new Promise(t=>{let r=n=>{let o=WM(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){YM(e,s,r);return}t("palette")};_k(e,r),Lk(e,"")}),Bk=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??UM.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return jk(n,()=>{}),e.armed(),await qM(t.drainMs??GM),await zM(n)}finally{HM(n)}};import Uk from"node:process";var Yt={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},Vk=(e,t)=>{let r=t?.write??(s=>{Uk.stderr.write(s)}),n=t?.stdin??Uk.stdin,o=[Yt.saveCursor,Yt.scrollRegion,Yt.restoreCursor,Yt.column,Yt.sgr,Yt.cursor,Yt.wrap];e.entersAltScreen===!0&&o.push(Yt.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var Wk=e=>`infra-kit ${e.groupPath.join(" ")}`,QM=()=>{ej();let e=Ae.stderr.columns;return e!=null&&e>0?e:void 0},ej=()=>{let e=Ae.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},tj=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),rj=async(e,t,r)=>{let n=wk(),o={...t.env,[Ha]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Ae.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await tj(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=kk(n),c=Nk(i.code,i.signal,a!=null,e.longRunning),l=Wk(e),u=a?.equivalent??Ja(l,!0);return Ik({equivalent:u,outcome:c,durationMs:t.now()-s,summary:a?.summary,envNotice:e.sessionEnvNotice,ascii:t.ascii,color:t.color,width:t.columns(),showEquivalent:!(u.reproducible&&u.line===l)})},nj=1e3,oj=(e,t)=>e!=null&&t-e<=nj,Bp=e=>{e.resetTerminal(),e.exit(0)},sj=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Bp(t)},s=()=>{let c=e();if(c==="palette"){Bp(t);return}if(!oj(r,t.now())){if(c==="pause"){Bp(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}},Gk=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),ij=Ae.platform==="win32"?void 0:()=>{Vm()},aj=(e,t)=>r=>Bk(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:ij}),Jk=async(e,t)=>{let r={spawn:t.spawn??ZM,now:t.now??(()=>Date.now()),env:t.env??Ae.env,cliPath:t.cliPath,ascii:t.ascii??!(Ae.stdout.isTTY&&Ae.env.TERM!=="dumb"),color:t.color??XM.level>0,columns:t.columns??QM,resetTerminal:t.resetTerminal??(u=>{Vk(u)})},n=t.write??(u=>Ae.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Ae.on(u,p)},unregister:(u,p)=>{Ae.off(u,p)},exit:u=>{Ae.exit(u)},raise:u=>{Ae.kill(Ae.pid,u)},now:()=>Date.now(),resetTerminal:()=>{o==="pause"&&n("\r\x1B[2K"),r.resetTerminal({entersAltScreen:!1})}},i={dispose:()=>{},childStarted:()=>{},quitRequested:()=>!1},a=t.installSignals===!1?i:sj(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??aj(n,r);try{for(;;){if(a.quitRequested())return;o="palette";let u=await t.renderPalette(e);if(u==null)return;let p=t.resolveCommand(u);if(!p)continue;let m=Dk(Wk(p),{color:r.color});n(`
|
|
451
456
|
${m}
|
|
452
|
-
`),a.childStarted();let f=await
|
|
457
|
+
`),a.childStarted();let f=await rj(p,r,()=>{o="child"});if(n(`
|
|
453
458
|
${f}
|
|
454
|
-
`),await l(c)==="quit")return}}finally{a.dispose()}};
|
|
459
|
+
`),await l(c)==="quit")return}}finally{a.dispose()}};qd();yk();var Yk=Dp(),Hk=async(e=Oe.argv)=>{Mp(),Fm(e);try{await Yk.parseAsync(e)}catch(t){Ek(t)}},pj=()=>{try{if(Oe.env.INFRA_KIT_NO_LOCATION_WARN||Oe.argv.includes("--json"))return;Yp({selfRealPath:uj(qk(import.meta.url)),cwd:Oe.cwd(),env:Oe.env,realpath:we,home:dj(),exists:lj})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};pj();mm((e,t)=>{d.debug(e,t)});Bl(B.version);var zk=()=>ww(Yk.commands),mj=async()=>{let e=zk(),t=null;try{if(Oe.stdout.isTTY&&Oe.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-LC2ESPY6.js");t=await r(e)}else{let r=Ip(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new Kk(" "),new Kk(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await N(o=>cj({message:"Select a command to run",choices:n},o),{output:Oe.stderr})}}catch(r){if(!Se(r))throw r}return t},fj=async()=>{let{runCommandPalette:e}=await import("./boot-LC2ESPY6.js"),t=qk(import.meta.url),r=new Map(fr.map(n=>[n.groupPath.join(" "),n]));await Jk(zk(),{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(Oe.argv.length<=2){let e={stdoutIsTTY:!!Oe.stdout.isTTY,stdinIsTTY:!!Oe.stdin.isTTY,stderrIsTTY:!!Oe.stderr.isTTY};if(Gk(Oe.env,e))await fj();else{let t=await mj();t&&await Hk(["node","infra-kit",...t.split(" ")])}}else await Hk();
|
|
455
460
|
//# sourceMappingURL=cli.js.map
|