infra-kit 0.36.0 → 0.38.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-BPOPODWW.js → chunk-5PMUXOX4.js} +2 -2
- package/dist/{chunk-3JFITLZG.js → chunk-6US7THWK.js} +2 -2
- package/dist/{chunk-SBG3HRSC.js → chunk-AWE4RK22.js} +2 -2
- package/dist/{chunk-TCQXTDVZ.js → chunk-GCCNZ3K2.js} +2 -2
- package/dist/{chunk-TCQXTDVZ.js.map → chunk-GCCNZ3K2.js.map} +1 -1
- package/dist/{chunk-TGEAIKD6.js → chunk-VX2YTWVQ.js} +2 -2
- package/dist/cli.js +133 -132
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +2 -2
- package/dist/{dev-wizard-run-PAHX7EMH.js → dev-wizard-run-ZWHZLG4O.js} +2 -2
- package/dist/{env-load-XBKASGXP.js → env-load-FHJGD7JO.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- /package/dist/{chunk-BPOPODWW.js.map → chunk-5PMUXOX4.js.map} +0 -0
- /package/dist/{chunk-3JFITLZG.js.map → chunk-6US7THWK.js.map} +0 -0
- /package/dist/{chunk-SBG3HRSC.js.map → chunk-AWE4RK22.js.map} +0 -0
- /package/dist/{chunk-TGEAIKD6.js.map → chunk-VX2YTWVQ.js.map} +0 -0
- /package/dist/{dev-wizard-run-PAHX7EMH.js.map → dev-wizard-run-ZWHZLG4O.js.map} +0 -0
- /package/dist/{env-load-XBKASGXP.js.map → env-load-FHJGD7JO.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 Tf,e as Jr,f as _f,g as Wt,h as li,i as Mf,j as jf,k as Ff,l as Lf,m as Bf,n as Uf,o as Wf,p as Vf,s as jc,t as Kf,u as Oe}from"./chunk-6US7THWK.js";import{a as Nm,b as Ue,c as _m,d as Rc,e as Mm,f as jm,g as Fm,h as Lm,i as Xn,j as Bm,k as Um,l as Wm,m as Vm,n as Gm,o as Zn,p as Jm,q as Km,r as Hm,s as qm,t as Sc,u as Zs,v as jt,w as Ym,x as Qs,y as zm}from"./chunk-PP44RGIU.js";import{a as ue,b as q,c as Bt,d as to,e as Cc,f as si,g as ii,h as $c,i as ro,j as ur,k as Ac,l as ai,m as bf,n as St,o as no,p as Dc,q as Ic,r as Nc,s as Af,u as _c}from"./chunk-QS7RKE5P.js";import{b as zn,c as zs,d as bc,e as $m,f as Xs,g as Am,i as Om,k as Dm,m as xe,o as Im}from"./chunk-REDCBY4O.js";import{a as xf}from"./chunk-V2ZLQPLI.js";import{B as so,D as Lc,H as Bc,I as Uc,a as b,b as C,c as Of,d as Df,e as dr,f as If,g as pr,h as Nf,i as Mc,j as Gf,k as oo,l as Vt,m as Kr,n as it,o as ui,p as Gt,q as Jf,r as di,s as Hf,t as qf,u as at,y as Fc}from"./chunk-AWE4RK22.js";import{a as h,b as Et,c as Rf,d as Sf,e as _,f as ci,g as J,i as Ut,j as Qe,k as Cf,l as Oc,m as $f}from"./chunk-VX2YTWVQ.js";import{$ as Ft,A as nf,B as of,C as sf,D as ri,E as ni,F as Ce,G as Qn,H as Gr,I as oi,J as af,K as cf,L as lf,M as Pc,N as xc,O as uf,P as d,Q as We,R as oe,S as w,T as Ze,U as df,V as pf,W as mf,X as O,Y as gf,Z as hf,_ as yf,a as lr,aa as vf,b as D,ba as Tc,c as Xm,ca as wf,d as j,da as kf,e as he,ea as ee,f as X,fa as K,g as ei,ga as eo,h as Zm,ha as Lt,i as g,j as Qm,k as ti,l as Q,m as ke,n as Te,o as ef,p as Ec,q as le,r as ne,s as Wr,t as tf,u as st,v as be,w as $,x as Ae,y as Vr,z as rf}from"./chunk-5PMUXOX4.js";import{a as ff}from"./chunk-MFAFQVTW.js";import{a as L}from"./chunk-GCCNZ3K2.js";import{a as Fr,b as Gs,c as Js,d as Yn,e as Em,f as Lr,g as Ks,h as Hs,i as Pm,j as qs,k as Ys,l as xm,m as Tm,n as Rt,o as Br,p as Mt,q as ge,r as Cm,s as Ur}from"./chunk-GCOYOWGH.js";import{a as Ef,b as Pf}from"./chunk-QWVLAZ6N.js";import yL,{Separator as mR}from"@inquirer/select";import{existsSync as vL,realpathSync as wL}from"node:fs";import{homedir as kL}from"node:os";import Be from"node:process";import{fileURLToPath as gR}from"node:url";import Yg from"node:process";import{z as Ne}from"zod";import rg from"node:fs";import qr from"node:path";import{packageConfigSchema as Xf}from"@slip-stream-kit/config/internal";import Zf from"node:fs/promises";import pi from"node:path";import{pathToFileURL as ER}from"node:url";import{z as Qf}from"zod";import Yf from"node:path";var io=["frontend","backend","lib","e2e","mobile"],vR={ui:"frontend",api:"backend",tests:"e2e"},wR="mobile-app",kR=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],bR=(e,t)=>{let r=Yf.relative(t,e).split(Yf.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=vR[o];if(s)return s}return r.at(-1)===wR?"mobile":null},RR=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of kR)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},ao=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??bR(e,t)??RR(r)??"lib";var ct={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},zf=2e3,Wc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${zf}} 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"},mr={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"]},co=(e,t=ct)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import SR from"node:fs/promises";var De=async e=>{try{return await SR.access(e),!0}catch{return!1}};var de="infra-kit.config.ts",fr=async e=>{try{let t=await Zf.readFile(pi.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Vc=async e=>{let t=await Zf.stat(e),o=(await import(`${ER(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${de} at ${e} has no default export`);return typeof o=="function"?await o():o},Pt=async e=>{let t=pi.join(e,de);if(await De(t))try{let n=(await Vc(t))?.type;return io.find(o=>o===n)}catch{return}},eg=e=>e,lo=async(e,t=ct)=>{let r=pi.join(e,de);if(!await De(r))throw new Error(`${de} not found at ${r}`);let n=await Vc(r),o=Xf.safeParse(n);if(!o.success)throw new Error(`Invalid ${de} at ${r}: ${Qf.prettifyError(o.error)}`);return co(eg(o.data),t)},lt=async e=>{let t=pi.join(e,de);if(!await De(t))return;let r=Xf.safeParse(await Vc(t));if(!r.success)throw new Error(`Invalid ${de} at ${t}: ${Qf.prettifyError(r.error)}`);return eg(r.data)};import tg from"node:fs/promises";import mi from"node:path";import PR from"yaml";var xR="pnpm-workspace.yaml",TR=async e=>(await tg.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>mi.join(e,r.name)),CR=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await TR(n));continue}let o=mi.join(n,t);await De(o)&&r.push(o)}return r},$R=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await CR(r,n);return r},Re=async e=>{let t=await tg.readFile(mi.join(e,xR),"utf-8"),n=((PR.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await $R(e,s);for(let a of i)await De(mi.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import uo from"node:path";var po=async e=>{let t=uo.resolve(e);for(;t!==uo.dirname(t);){if(await De(uo.join(t,"package.json")))return t;t=uo.dirname(t)}if(await De(uo.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 Ve=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Jt=(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}`:"")},gr=(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},fi=(e,t,r)=>`${e}
|
|
4
4
|
${t}
|
|
5
|
-
${r}`,
|
|
5
|
+
${r}`,Hr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=fi(r,t,n),i=Ve(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?Jt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
6
6
|
${s}
|
|
7
7
|
`:`${s}
|
|
8
|
-
`};var
|
|
8
|
+
`};var Se="<!-- infra-kit:begin -->",Ie="<!-- infra-kit:end -->",hr="<!-- infra-kit:version ",Ge="<!-- infra-kit:package:begin -->",et="<!-- infra-kit:package:end -->",xt="<!-- infra-kit:package:version ";var AR=e=>{let t=e.indexOf(Ge)+Ge.length;return e.slice(t,e.indexOf(et))},OR=e=>{let t=e.indexOf(xt);if(t===-1)return null;let r=e.slice(t+xt.length).match(/^\S+\s+([^\s>]+)/)?.[1];return io.find(n=>n===r)??null},Tt=e=>{if(e===null)return{state:"missing"};if(!Ve(e,Ge,et))return e.includes(Ge)||e.includes(et)?{state:"malformed"}:Ve(e,Se,Ie)?{state:"foreign-block"}:{state:"no-block"};let t=AR(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=gr(t,xt),o=OR(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import DR from"node:fs";var ut=e=>{try{return DR.readFileSync(e,"utf-8")}catch{return null}};var ng="pnpm-workspace.yaml",IR="CLAUDE.md",Jc=e=>{let t=qr.resolve(e);for(;t!==qr.dirname(t);){if(rg.existsSync(qr.join(t,ng)))return t;t=qr.dirname(t)}return rg.existsSync(qr.join(t,ng))?t:null},Gc=new Map,gi=()=>{Gc.clear()},NR=async e=>{let t;try{t=await Re(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=qr.join(r,IR),o=ut(n);if(o!==null&&Tt(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Yr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Gc.get(e);if(t)return t;let r=await NR(e);return Gc.set(e,r),r};import yr from"node:fs";import Kt from"node:path";var og=`---
|
|
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 sg=`# {{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 ig="# {{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 loaded env provides. 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`, the release pass is `/infra-kit:ultraqa`) or wherever `CI` is set (no dev server can run there), 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 ag="# {{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 cg=`# {{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 lg=`# {{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,49 +138,49 @@ 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 zr from"node:fs";import QR from"node:path";var fi=e=>{let t;try{t=zr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},po=(e,t)=>{let r=mo(e,t);return r!=="unchanged"&&(zr.mkdirSync(QR.dirname(e),{recursive:!0}),zr.writeFileSync(e,t,"utf-8")),r},mo=(e,t)=>{fi(e);let r=zr.existsSync(e)?zr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},qc=(e,t,r)=>{let n=zr.readFileSync(e,"utf-8");if(!We(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},ug=(e,t,r)=>We(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Yc=(e,t,r,n)=>{let o=ug(e,r,n),s=ug(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 hi="<!-- infra-kit:import:begin -->",yi="<!-- infra-kit:import:end -->",eS="AGENTS.md",dg="CLAUDE.md",tS="README.md",zc="DESIGN.md",rS=["frontend","mobile"],nS=e=>gr.existsSync(e)?gr.readFileSync(e,"utf-8"):null,Xc=(e,t)=>{try{return gr.readdirSync(e).includes(t)}catch{return!1}},gi=(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},pg=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=nS(e),a=i===null?"":o?.(i)??i,c=Jr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return mo(e,c);let l=po(e,c);return qc(e,r,n),i!==null&&Yc(a,c,r,n),l},oS=(e,t)=>{if(!gr.existsSync(e))return"unchanged";fi(e);let r=gr.readFileSync(e,"utf-8"),n=Vt(r,be,De);return n===null?"unchanged":n.trim()===""?(t||gr.rmSync(e),"removed"):t?mo(e,n):po(e,n)},sS=(e,t,r)=>pg({filePath:e,dryRun:r,body:uo(t),startMarker:be,endMarker:De,prepare:n=>Vt(n,hi,yi)??n}),fo=async(e,{version:t,dryRun:r=!1})=>{let n=Gt.join(e,dg),o=Gt.join(e,eS),s=[];try{s.push({path:n,action:sS(n,t,r)})}catch(i){s.push(gi(n,i))}try{s.push({path:o,action:oS(o,r)})}catch(i){s.push(gi(o,i))}return s},iS=(e,t,r,n)=>{if(!rS.includes(r)||Xc(e,zc))return null;let o=Gt.join(e,zc),s=Jc(t);try{return{path:o,action:n?mo(o,s):po(o,s),type:r}}catch(i){return gi(o,i,r)}},vi=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await pr(e),s=o.name??Gt.basename(e),i=so({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:Hc({version:r,type:i,packageName:s,relDir:Gt.relative(t,e).split(Gt.sep).join("/"),hasReadme:Xc(e,tS),hasDesign:Xc(e,zc),hasE2eDoc:gr.existsSync(Gt.join(t,Kc)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},go=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Gt.join(e,dg),{body:a,type:c,packageName:l}=await vi(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:pg({filePath:i,body:a,startMarker:Ve,endMarker:Qe,dryRun:s}),type:c})}catch(p){u.push(gi(i,p,c))}if(n){let p=iS(e,l,c,s);p&&u.push(p)}return u};import CS from"node:path";import mg from"node:path";var Zc="agent-guidance",ho="CLAUDE.md",aS="\u2014 run: infra-kit audit --fix",cS={missing:`${ho} missing`,"no-block":`${ho} has no infra-kit block (expected ${Ve} \u2026 ${Qe})`,malformed:`${ho} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${ho} carries the ROOT infra-kit block (${be}); a package needs the package block`},lS=e=>e.adopted?` (workspace adopted: ${mg.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Qc=(e,t)=>{let r=Et(lt(mg.join(e,ho)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Zc,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${cS[r.state]} ${aS}`,o=r.state==="missing"?`${n}${lS(t)}`:n;return t.adopted?{name:Zc,status:"fail",message:o}:{name:Zc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import uS from"node:path";var el=async(e,t=at)=>{try{let r=await ao(e,t);return{check:{name:ue,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:ue,status:"fail",message:r.message},rules:null}}},fg="infra-kit.json",dS=async e=>await Oe(uS.join(e,ue))?{name:ue,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,tl=async(e,t=dr)=>{let r=await dS(e),n=r?[r]:[];try{let{audit:o={}}=await H();return{checks:[{name:fg,status:"pass",message:"present and valid"},...n],rules:io(o,t)}}catch(o){return{checks:[{name:fg,status:"fail",message:o.message},...n],rules:null}}};import wi from"node:fs/promises";import Xr from"node:path";import{$ as pS}from"zx";var yo="playwright.config.ts",mS=[{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')"}],gg=e=>Object.entries(Bc).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"}}),fS="infra-kit-e2e",hg=async(e,t={})=>{let r=Xr.join(e,yo),n=await wi.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${yo}`,status:"fail",message:`missing ${yo}`}]:mS.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===fS?{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:`${yo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},gS=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,hS=/\.[cm]?[jt]sx?$/u,rl=async(e,t)=>(await wi.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&hS.test(n.name)).map(n=>Xr.join(n.parentPath,n.name)),yS=async e=>{let t=await rl(Xr.join(e,"src"),!0);for(let r of[Xr.join(e,yo),...t]){let n=await wi.readFile(r,"utf-8").catch(()=>"");if(gS.test(n))return!0}return!1},yg=async e=>{let t="e2e-auth:gitignored";if(!await yS(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await pS({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}`}},nl="E2E__BASIC_AUTH_USERNAME",ol="E2E__BASIC_AUTH_PASSWORD",vS=/\bE2E_\w*BASIC_AUTH_\w+/gu,wS=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,kS=/\/\*[\s\S]*?\*\//gu,bS=/(^|[^:])\/\/[^\n]*/gu,RS=e=>/USER(?:NAME)?$/u.test(e)?nl:ol,SS=e=>e.replace(kS,"").replace(bS,"$1"),vg=async e=>{let t="e2e-env:basic-auth",r=[...await rl(e,!1),...await rl(Xr.join(e,"src"),!0)],n=[];for(let o of r){let s=await wi.readFile(o,"utf-8").catch(()=>""),i=new Set([...SS(s).matchAll(vS)].map(a=>a[0]).filter(a=>wS.test(a)&&a!==nl&&a!==ol));for(let a of i)n.push(`${a} \u2192 ${RS(a)} (${Xr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${nl} / ${ol}`}:{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("; ")}`}},sl=async(e,t,r={})=>[...gg(t),...await hg(e,r),await yg(e),await vg(e)];import ES from"node:fs/promises";import PS from"node:path";var il=async(e,t)=>Promise.all(t.map(async r=>{let n=await ES.stat(PS.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 al=(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 xS from"node:fs/promises";import TS from"node:path";var Zr="turbo.json",cl=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await xS.readFile(TS.join(e,Zr),"utf-8");r=JSON.parse(o)}catch(o){return[{name:Zr,status:"fail",message:`cannot read/parse ${Zr}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:Zr,status:"fail",message:`no "tasks" object defined in ${Zr}`}]: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 ${Zr}`}})};var $S=async(e,t)=>{let{check:r,rules:n}=await el(e,t);return{checks:[r],rules:n}},AS={adopted:!1,workspaceRoot:null},OS=async(e,t,r)=>so({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Rt(e)}),DS=async e=>(await ct(e).catch(()=>{}))?.e2e?.server==="static",ll=async(e,t=at,r={})=>{let n=await pr(e),o=n.name??CS.basename(e),{checks:s,rules:i}=r.isRoot?await tl(e,t):await $S(e,t);r.isRoot||s.push(Qc(e,r.adoption??AS)),i&&(s.push(...al(n.scripts??{},i.requiredScripts)),s.push(...await il(e,i.requiredFiles)),s.push(...await cl(e,i.turboTasks))),!r.isRoot&&await OS(e,n,r.repoRoot)==="e2e"&&s.push(...await sl(e,n.scripts??{},{staticServer:await DS(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var ul=["plugin","marketplace","add",Ft],dl=["plugin","install",Y,"--scope","project"],wg=(e,t)=>cr({projectPath:e,home:t}).kind==="installed",ki=e=>((e??"").split(`
|
|
148
|
-
`).find(r=>r.trim().length>0)??"").trim(),
|
|
149
|
-
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${
|
|
141
|
+
`;var ug="# 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 zr={"root/body":ug.trimEnd(),"package/frontend":ag.trimEnd(),"package/backend":sg.trimEnd(),"package/lib":cg.trimEnd(),"package/e2e":ig.trimEnd(),"package/mobile":lg.trimEnd(),"design/skeleton":og.trimEnd()};var Kc=/\{\{(\w+)\}\}/g,WR=/^- \{\{(\w+)\}\}$/,VR=e=>new Set([...e.matchAll(Kc)].map(t=>t[1])),GR=(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(", ")}`)},JR=(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(", ")}`)},KR=(e,t)=>e.filter(r=>{let n=WR.exec(r);return n===null||t[n[1]]!==""}),HR=(e,t)=>{for(let r of e)for(let n of r.matchAll(Kc)){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})`)}},Xr=(e,t)=>{let r=VR(e);JR(r,t),GR(r,t);let n=KR(e.split(`
|
|
143
|
+
`),t);return HR(n,t),n.join(`
|
|
144
|
+
`).replace(Kc,(o,s)=>t[s])};var qR="name: TODO",Hc=e=>{let t=Xr(zr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(qR,()=>r)}
|
|
145
|
+
`};var YR=(e,t)=>`${xt}${e} ${t} -->`,zR="`README.md` \u2014 what this package is and how to run it.",qc="docs/e2e-playwright.md",XR=`\`${qc}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,ZR=["ts-check","eslint-check","test"],QR="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.",eS="Run `pnpm run build` before a dependent package can see a change.",dg=(e,t)=>e?.includes(t)??!0,tS=e=>{let t=ZR.filter(r=>dg(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},Yc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=Xr(zr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?zR:"",checksBullet:tS(a),...r==="e2e"?{e2eDocBullet:i?XR:""}:{},...r==="lib"?{surfaceBullet:c?QR:"",buildBullet:dg(a,"build")?eS:""}:{}});return[YR(t,r),"",l,""].join(`
|
|
146
|
+
`)};var rS=e=>`${hr}${e} -->`,mo=e=>{let t=Xr(zr["root/body"],{});return[rS(e),"",t,""].join(`
|
|
147
|
+
`)};import Zr from"node:fs";import nS from"node:path";var hi=e=>{let t;try{t=Zr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},fo=(e,t)=>{let r=go(e,t);return r!=="unchanged"&&(Zr.mkdirSync(nS.dirname(e),{recursive:!0}),Zr.writeFileSync(e,t,"utf-8")),r},go=(e,t)=>{hi(e);let r=Zr.existsSync(e)?Zr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},zc=(e,t,r)=>{let n=Zr.readFileSync(e,"utf-8");if(!Ve(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},pg=(e,t,r)=>Ve(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Xc=(e,t,r,n)=>{let o=pg(e,r,n),s=pg(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 vi="<!-- infra-kit:import:begin -->",wi="<!-- infra-kit:import:end -->",oS="AGENTS.md",mg="CLAUDE.md",sS="README.md",Zc="DESIGN.md",iS=["frontend","mobile"],aS=e=>yr.existsSync(e)?yr.readFileSync(e,"utf-8"):null,Qc=(e,t)=>{try{return yr.readdirSync(e).includes(t)}catch{return!1}},yi=(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},fg=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=aS(e),a=i===null?"":o?.(i)??i,c=Hr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return go(e,c);let l=fo(e,c);return zc(e,r,n),i!==null&&Xc(a,c,r,n),l},cS=(e,t)=>{if(!yr.existsSync(e))return"unchanged";hi(e);let r=yr.readFileSync(e,"utf-8"),n=Jt(r,Se,Ie);return n===null?"unchanged":n.trim()===""?(t||yr.rmSync(e),"removed"):t?go(e,n):fo(e,n)},lS=(e,t,r)=>fg({filePath:e,dryRun:r,body:mo(t),startMarker:Se,endMarker:Ie,prepare:n=>Jt(n,vi,wi)??n}),ho=async(e,{version:t,dryRun:r=!1})=>{let n=Kt.join(e,mg),o=Kt.join(e,oS),s=[];try{s.push({path:n,action:lS(n,t,r)})}catch(i){s.push(yi(n,i))}try{s.push({path:o,action:cS(o,r)})}catch(i){s.push(yi(o,i))}return s},uS=(e,t,r,n)=>{if(!iS.includes(r)||Qc(e,Zc))return null;let o=Kt.join(e,Zc),s=Hc(t);try{return{path:o,action:n?go(o,s):fo(o,s),type:r}}catch(i){return yi(o,i,r)}},ki=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await fr(e),s=o.name??Kt.basename(e),i=ao({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:Yc({version:r,type:i,packageName:s,relDir:Kt.relative(t,e).split(Kt.sep).join("/"),hasReadme:Qc(e,sS),hasDesign:Qc(e,Zc),hasE2eDoc:yr.existsSync(Kt.join(t,qc)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},yo=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Kt.join(e,mg),{body:a,type:c,packageName:l}=await ki(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:fg({filePath:i,body:a,startMarker:Ge,endMarker:et,dryRun:s}),type:c})}catch(p){u.push(yi(i,p,c))}if(n){let p=uS(e,l,c,s);p&&u.push(p)}return u};import DS from"node:path";import gg from"node:path";var el="agent-guidance",vo="CLAUDE.md",dS="\u2014 run: infra-kit audit --fix",pS={missing:`${vo} missing`,"no-block":`${vo} has no infra-kit block (expected ${Ge} \u2026 ${et})`,malformed:`${vo} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${vo} carries the ROOT infra-kit block (${Se}); a package needs the package block`},mS=e=>e.adopted?` (workspace adopted: ${gg.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",tl=(e,t)=>{let r=Tt(ut(gg.join(e,vo)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:el,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${pS[r.state]} ${dS}`,o=r.state==="missing"?`${n}${mS(t)}`:n;return t.adopted?{name:el,status:"fail",message:o}:{name:el,status:"pass",message:`not yet adopted \u2014 ${o}`}};import fS from"node:path";var rl=async(e,t=ct)=>{try{let r=await lo(e,t);return{check:{name:de,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:de,status:"fail",message:r.message},rules:null}}},hg="infra-kit.json",gS=async e=>await De(fS.join(e,de))?{name:de,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,nl=async(e,t=mr)=>{let r=await gS(e),n=r?[r]:[];try{let{audit:o={}}=await K();return{checks:[{name:hg,status:"pass",message:"present and valid"},...n],rules:co(o,t)}}catch(o){return{checks:[{name:hg,status:"fail",message:o.message},...n],rules:null}}};import bi from"node:fs/promises";import Qr from"node:path";import{$ as hS}from"zx";var wo="playwright.config.ts",yS=[{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')"}],yg=e=>Object.entries(Wc).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"}}),vS="infra-kit-e2e",vg=async(e,t={})=>{let r=Qr.join(e,wo),n=await bi.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${wo}`,status:"fail",message:`missing ${wo}`}]:yS.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===vS?{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:`${wo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},wS=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,kS=/\.[cm]?[jt]sx?$/u,ol=async(e,t)=>(await bi.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&kS.test(n.name)).map(n=>Qr.join(n.parentPath,n.name)),bS=async e=>{let t=await ol(Qr.join(e,"src"),!0);for(let r of[Qr.join(e,wo),...t]){let n=await bi.readFile(r,"utf-8").catch(()=>"");if(wS.test(n))return!0}return!1},wg=async e=>{let t="e2e-auth:gitignored";if(!await bS(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await hS({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}`}},sl="E2E__BASIC_AUTH_USERNAME",il="E2E__BASIC_AUTH_PASSWORD",RS=/\bE2E_\w*BASIC_AUTH_\w+/gu,SS=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,ES=/\/\*[\s\S]*?\*\//gu,PS=/(^|[^:])\/\/[^\n]*/gu,xS=e=>/USER(?:NAME)?$/u.test(e)?sl:il,TS=e=>e.replace(ES,"").replace(PS,"$1"),kg=async e=>{let t="e2e-env:basic-auth",r=[...await ol(e,!1),...await ol(Qr.join(e,"src"),!0)],n=[];for(let o of r){let s=await bi.readFile(o,"utf-8").catch(()=>""),i=new Set([...TS(s).matchAll(RS)].map(a=>a[0]).filter(a=>SS.test(a)&&a!==sl&&a!==il));for(let a of i)n.push(`${a} \u2192 ${xS(a)} (${Qr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${sl} / ${il}`}:{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("; ")}`}},al=async(e,t,r={})=>[...yg(t),...await vg(e,r),await wg(e),await kg(e)];import CS from"node:fs/promises";import $S from"node:path";var cl=async(e,t)=>Promise.all(t.map(async r=>{let n=await CS.stat($S.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 ll=(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 AS from"node:fs/promises";import OS from"node:path";var en="turbo.json",ul=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await AS.readFile(OS.join(e,en),"utf-8");r=JSON.parse(o)}catch(o){return[{name:en,status:"fail",message:`cannot read/parse ${en}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:en,status:"fail",message:`no "tasks" object defined in ${en}`}]: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 ${en}`}})};var IS=async(e,t)=>{let{check:r,rules:n}=await rl(e,t);return{checks:[r],rules:n}},NS={adopted:!1,workspaceRoot:null},_S=async(e,t,r)=>ao({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Pt(e)}),MS=async e=>(await lt(e).catch(()=>{}))?.e2e?.server==="static",dl=async(e,t=ct,r={})=>{let n=await fr(e),o=n.name??DS.basename(e),{checks:s,rules:i}=r.isRoot?await nl(e,t):await IS(e,t);r.isRoot||s.push(tl(e,r.adoption??NS)),i&&(s.push(...ll(n.scripts??{},i.requiredScripts)),s.push(...await cl(e,i.requiredFiles)),s.push(...await ul(e,i.turboTasks))),!r.isRoot&&await _S(e,n,r.repoRoot)==="e2e"&&s.push(...await al(e,n.scripts??{},{staticServer:await MS(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var pl=["plugin","marketplace","add",Bt],ml=["plugin","install",q,"--scope","project"],bg=(e,t)=>ur({projectPath:e,home:t}).kind==="installed",Ri=e=>((e??"").split(`
|
|
148
|
+
`).find(r=>r.trim().length>0)??"").trim(),jS=(e,t)=>{if(ro(t))return null;d.debug({msg:`Running: ${to} ${pl.join(" ")}`});let r=e({args:pl});return r.ok?null:{step:"marketplace",error:Ri(r.output)}},FS=(e,t)=>{d.debug({msg:`Running: ${to} ${ii.join(" ")}`});let r=e({args:ii});if(!r.ok)return{status:"update-failed",error:Ri(r.output)};d.debug({msg:`Running: ${to} ${si.join(" ")}`});let n=e({args:si,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:Ri(n.output)}},fl=e=>{let{projectRoot:t,home:r}=e,n=e.run??$c;if(!n({args:Cc}).ok)return{status:"claude-missing"};if(bg(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:FS(n,t);let o=jS(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${to} ${ml.join(" ")}`});let s=n({args:ml,cwd:t});return s.ok?bg(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:Ri(s.output)}};import LS from"node:fs";import BS from"node:path";var Je=".mcp.json",dt="mcpServers",US="infra-kit",WS=["mcp"],VS="/infra-kit/dist/mcp.js",gl=" ",vr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rg=e=>{if(!vr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===US&&r[0]===WS[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(VS)):!1},Sg=e=>/\n([ \t]+)"/.exec(e)?.[1]??gl,hl=e=>{try{return{kind:"raw",raw:LS.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},yl=e=>{try{return JSON.parse(e)}catch{return}},vl=e=>e instanceof Error?e.message:String(e),tn=e=>{let t=hl(BS.join(e,Je));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=yl(t.raw);if(!vr(r)||!vr(r[dt]))return{kind:"unparseable"};let n=r[dt];if(ue in n)return{kind:"stale"};let o=Object.keys(n).find(s=>Rg(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Si from"node:fs";import GS from"node:path";var Ct=`claude plugin install ${q} --scope project`,rn=`claude plugin marketplace update ${ue} && claude plugin update ${q} --scope project`,wl=`claude plugin marketplace add ${Bt}`,xg=" ",Tg=()=>({source:{source:"github",repo:Bt}}),JS=()=>({extraKnownMarketplaces:{[ue]:Tg()},enabledPlugins:{[q]:!0}}),Cg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),KS=e=>/\n([ \t]+)"/.exec(e)?.[1]??xg,Eg=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!Cg(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Pg=e=>[Eg(e,"extraKnownMarketplaces",ue,Tg()),Eg(e,"enabledPlugins",q,!0)].filter(r=>r!==null),HS=e=>{try{return Si.readFileSync(e,"utf-8")}catch{return null}},qS=e=>(Si.mkdirSync(GS.dirname(e),{recursive:!0}),Si.writeFileSync(e,`${JSON.stringify(JS(),null,xg)}
|
|
149
|
+
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${ue}`,`enabledPlugins.${q}`]}),kl=(e,{write:t=!0}={})=>{let r=HS(e);if(r===null)return t?qS(e):{status:"withheld",path:e,added:Pg({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!Cg(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${q}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Pg(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=KS(r),i=r.endsWith(`
|
|
150
150
|
`)?`
|
|
151
|
-
`:"";return
|
|
152
|
-
`,"utf-8")}return o},
|
|
151
|
+
`:"";return Si.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var YS="empty-rules",zS=["requiredScripts","requiredFiles"],$g=(e,t,r)=>zS.filter(n=>e[n]?.length===0).map(n=>({name:YS,status:"warn",message:`${r} sets ${n}: [], which disables the check instead of relaxing it \u2014 delete the key to inherit the defaults (${t[n].join(", ")}), or list what this target really has`})),Ag=async(e,t)=>{try{if(t){let{audit:r={}}=await K();return $g(r,mr,'infra-kit.json "audit"')}return $g(await lt(e)??{},ct,"infra-kit.config.ts")}catch{return[]}};import QS from"node:path";import eE from"node:process";import bl from"node:fs/promises";import Og from"node:path";var XS="infra-kit.json",Dg=["requiredScripts","requiredFiles","turbo"],ko=(e,t)=>[{path:e,action:"failed",message:t}],ZS=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ig=async e=>{let t=Og.join(e,de),r=Og.join(e,XS),n;try{n=await lt(e)}catch(c){return ko(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Dg.includes(c));if(s.length>0)return ko(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Dg.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await bl.stat(r),l=await bl.readFile(r,"utf8"),u=JSON.parse(l);if(!ZS(u))return ko(r,"is not a JSON object");if("audit"in u)return ko(r,`already has an "audit" block \u2014 merge ${de}'s rules into it by hand, then delete ${de}`);await pf({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return ko(r,c.message)}try{await bl.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var tE=["unchanged","created"],rE=["unchanged","created","updated","removed","failed"],Ng=async(e,t,r)=>{let n=await Pt(e);return yo(e,{repoRoot:t,version:L.version,design:r,declaredType:n})},nE=async(e,t)=>{if(e.root)return[...await Ig(t),...await ho(t,{version:L.version})];if(e.all){let n=[];for(let o of await Re(t))n.push(...await Ng(o,t,e.design));return n}let r=await po(e.cwd??eE.cwd());return Ng(r,t,e.design)},oE=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 ${rE.filter(n=>tE.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${L.version})`},sE=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=QS.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(oE(e))},iE=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},_g=async(e,t)=>{let r=await $();gi();let n=await Yr(t),o=await nE(e,r);sE(o,r),gi();let s=await Yr(t),i=!e.all&&!e.root;return{fixed:o.map(iE),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Ei from"node:fs/promises";import Pi from"node:path";import aE from"yaml";var bo="dependency-drift",Rl="@slip-stream-kit/",cE="infra-kit",lE=["dependencies","devDependencies","optionalDependencies"],Fg=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),El=e=>e.startsWith("catalog:"),uE=(e,t,r)=>{if(!El(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},Mg=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},dE=(e,t)=>{let r=Mg(e),n=Mg(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},pE=e=>{let t=new Map;for(let r of e){let n=t.get(r.name);n?n.push(r):t.set(r.name,[r])}return t},Sl=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),mE=(e,t)=>[...pE(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!El(s.spec));return o.length===0?[]:[{name:`${bo}:catalog`,status:"warn",message:`${r} has a catalog entry (${t.default[r]}) but ${Sl(o)} bypass it \u2014 run \`ik audit --fix --root\` to rewrite them to "catalog:", then pnpm install`}]}return new Set(n.map(o=>o.spec)).size<=1?[]:[{name:`${bo}:catalog`,status:"warn",message:`${r} is pinned at more than one range: ${Sl(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),fE=(e,t,r)=>{let n=new Map;for(let o of e){let s=uE(o.spec,t,o.name);s!==void 0&&dE(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${bo}:lockstep`,status:"warn",message:`${o} is behind the infra-kit ${r} lockstep release \u2014 bump it to ^${r}`}))},gE=e=>{let t=e.filter(r=>r.name===cE);return t.length===0?[]:[{name:`${bo}:infra-kit-pin`,status:"warn",message:`${Sl(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},hE=(e,t,r)=>{let n=e.filter(i=>!Fg(i.spec)),o=n.filter(i=>i.name.startsWith(Rl)),s=[...mE(o,t),...fE(o,t,r),...gE(n)];return s.length>0?s:[{name:bo,status:"pass",message:`no ${Rl}* or infra-kit dependency drift`}]},yE=async e=>{try{return JSON.parse(await Ei.readFile(e,"utf-8"))}catch{return null}},vE=async e=>{try{let t=aE.parse(await Ei.readFile(Pi.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},wE=async e=>{let t=await Re(e).catch(()=>[]);return[e,...t].map(r=>Pi.join(r,"package.json"))},jg=async e=>{let t=[];for(let r of await wE(e)){let n=await yE(r);if(!n)continue;let o=Pi.relative(e,r);for(let s of lE){let i=n[s]??{};for(let[a,c]of Object.entries(i))typeof c=="string"&&t.push({file:o,section:s,name:a,spec:c})}}return t},kE=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(Rl)&&!Fg(s.spec)&&!El(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=Pi.join(e,s),a=await Ei.readFile(i,"utf-8"),c=JSON.parse(a);for(let u of n)u.file===s&&(c[u.section][u.name]="catalog:");let l=a.match(/^[ \t]+(?=")/m)?.[0]??" ";await Ei.writeFile(i,`${JSON.stringify(c,null,l)}
|
|
152
|
+
`,"utf-8")}return o},Lg=async(e,t,r=L.version)=>{let n=await vE(e),o=await jg(e),s=t?await kE(e,o,n):[],i=s.length>0?await jg(e):o;return{checks:hE(i,n,r),rewritten:s}};import Ug from"node:path";var xi="agent-guidance:drift",bE={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Bg=(e,t)=>e.split(`
|
|
153
153
|
`).filter(r=>!r.startsWith(t)).join(`
|
|
154
|
-
`),
|
|
154
|
+
`),Wg=({content:e,expectedBody:t,startMarker:r,endMarker:n,versionPrefix:o,current:s,scope:i})=>{let a=e.slice(e.indexOf(r),e.indexOf(n)+n.length),c=fi(r,t,n);if(Bg(a,o)===Bg(c,o))return{name:xi,status:"pass",message:`matches infra-kit ${s}`};let l=gr(a,o),u=bE[i];return l!==null&&St(l,s)?{name:xi,status:"warn",message:`block from infra-kit ${l} is newer than this CLI (${s}) \u2014 CLI behind the block, run \`pnpm add -g infra-kit@${l}\``}:l!==null&&St(s,l)?{name:xi,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:xi,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},Vg=(e,t=L.version)=>{let r=ut(Ug.join(e,"CLAUDE.md"));return r===null||!Ve(r,Se,Ie)?null:Wg({content:r,expectedBody:mo(t),startMarker:Se,endMarker:Ie,versionPrefix:hr,current:t,scope:"root"})},Gg=async(e,t,r,n=L.version)=>{let o=ut(Ug.join(e,"CLAUDE.md"));if(o===null||Tt(o).state!=="ok")return null;let s;try{({body:s}=await ki(e,{repoRoot:t,version:n,declaredType:await Pt(e)}))}catch{return null}return Wg({content:o,expectedBody:s,startMarker:Ge,endMarker:et,versionPrefix:xt,current:n,scope:r})};import Kg from"node:fs";import Hg from"node:path";var Pl="ik-mcp",Jg=(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:Pl,args:r}};var Ti="run `infra-kit setup` (or `infra-kit audit --root --fix`)",RE=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),xl=e=>vr(e)&&e.command===Pl,SE=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),EE=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Jg(i,a),l=e[i];if(l!==void 0&&!xl(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 ${Ti}, or drop mcp.${i} from infra-kit.json`});continue}if(xl(l)&&l.type===c.type&&RE(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=SE(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: ${Ti}`:`"${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: ${Ti}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!xl(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}},PE=(e,t,r)=>{let n=r===null?gl:Sg(r),o=r===null||r.endsWith(`
|
|
155
155
|
`)?`
|
|
156
|
-
`:"";try{return
|
|
156
|
+
`:"";try{return Kg.mkdirSync(Hg.dirname(e),{recursive:!0}),Kg.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${vl(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Ro=({projectRoot:e,proxies:t,write:r})=>{let n=Hg.join(e,Je),o=hl(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${vl(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:yl(s);if(!vr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Ti}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[dt];if(a!==void 0&&!vr(a))return d.warn(`${n} has a "${dt}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=EE(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=PE(n,{...i,[dt]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var qg=async(e,t)=>{let r;try{r=(await K()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Ro({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(a=>a.status!=="unchanged"&&a.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(a=>({name:`mcp:${a.name}`,status:"fail",message:a.message})),i=s.every(a=>a.status!=="fail");return{packageDir:e,packageName:"mcp",checks:s,passed:i}};var xE="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",TE=async e=>e.root?[{dir:await $(),baseline:mr,isRoot:!0}]:e.all?(await Re(await $())).map(r=>({dir:r})):[{dir:await po(e.cwd??Yg.cwd())}],CE=async e=>e.root||e.all?await $():e.cwd??Yg.cwd(),$E=async()=>{try{return await $()}catch{return}},AE=e=>{let t=0,r=0,n=0;for(let c of e)for(let l of c.checks)t+=1,l.status==="fail"?(r+=1,d.info(`[FAIL] ${c.packageName} ${l.name}: ${l.message}`)):l.status==="warn"&&(n+=1,d.info(`[WARN] ${c.packageName} ${l.name}: ${l.message}`));let o=e.every(c=>c.passed),s=(c,l)=>`${c} ${l}${c===1?"":"s"}`,i=`${s(t,"check")}, ${s(e.length,"target")}`,a=n>0?` (${s(n,"warning")})`:"";return d.info(o?`\u2705 audit passed \u2014 ${i}${a}`:`\u274C audit failed \u2014 ${r}/${i}${a}`),{allPassed:o,warnCount:n}},OE=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await _g(e,t);return n&&d.info(xE),r},DE=e=>{if(tn(e).kind!=="stale")return null;let t=`${Je} still registers "${ue}" \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 "${ue}" 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}},IE=e=>e.root?"root":e.all?"all":"package",NE=async(e,t,r)=>{let n=await Ag(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await Gg(e.dir,r??e.dir,IE(t));return a?[a,...n]:n}let o=Vg(e.dir),{checks:s,rewritten:i}=await Lg(e.dir,t.fix===!0);for(let a of i)d.info(` ${"updated".padEnd(9)} ${a} (@slip-stream-kit/* \u2192 catalog:)`);return[...o?[o]:[],...n,...s]},Ci=async(e={})=>{let t=Jc(await CE(e)),r=e.fix?await OE(e,t):void 0,n=await TE(e),o=await Yr(t),s=await $E(),i=[];for(let u of n){let p=await dl(u.dir,u.baseline,{adoption:o,isRoot:u.isRoot,repoRoot:s});p.checks.push(...await NE(u,e,s)),p.passed=p.checks.every(m=>m.status!=="fail"),i.push(p)}if(e.root){let u=await qg(n[0].dir,e.fix===!0);u&&i.push(u);let p=DE(n[0].dir);p&&i.push(p)}let{allPassed:a,warnCount:c}=AE(i),l={allPassed:a,warnCount:c,packages:i.map(u=>({name:u.packageName,passed:u.passed,checks:u.checks}))};return r&&(l.fixed=r),{content:b(JSON.stringify(l,null,2)),structuredContent:l}},_E={all:Ne.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ne.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},ME={allPassed:Ne.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:Ne.number().int().describe("How many checks reported a warning"),packages:Ne.array(Ne.object({name:Ne.string(),passed:Ne.boolean(),checks:Ne.array(Ne.object({name:Ne.string(),status:Ne.enum(["pass","warn","fail"]),message:Ne.string()}))})).describe("Per-package check results")},Tl=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:_E,outputSchema:ME,handler:e=>Ci({all:e.all,root:e.root})});import{z as F}from"zod";import{$ as KE}from"zx";var Cl=1.959963984540054,jE=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],$l=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,Al=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],FE=/This reverts commit ([0-9a-f]{7,40})/u,Xg=/^Revert "(.*)"(?: \(#\d+\))?$/u,Zg="",$i="",Qg=`--format=${Zg}%H${$i}%ct${$i}%B${$i}`,eh=e=>e.split(Zg).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split($i),i=o.trim();return{hash:r,committedAt:Number(n),subject:i.split(`
|
|
157
157
|
`)[0]??"",body:i,files:s.split(`
|
|
158
|
-
`).map(a=>a.trim()).filter(Boolean)}}),
|
|
159
|
-
`),
|
|
160
|
-
`)),{content:b(JSON.stringify(t,null,2)),structuredContent:t}},
|
|
161
|
-
`,420),
|
|
162
|
-
${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},
|
|
163
|
-
`),
|
|
158
|
+
`).map(a=>a.trim()).filter(Boolean)}}),LE=e=>jE.some(t=>t.test(e.body))?"agent":"human",Ol=e=>Xg.test(e.subject),BE=e=>!Ol(e)&&$l.test(e.subject),UE=(e,t)=>{if(t===0)return null;let r=e/t,n=Cl*Cl,o=1+n/t,s=(r+n/(2*t))/o,i=Cl*Math.sqrt(r*(1-r)/t+n/(4*t*t))/o;return{low:Math.max(0,s-i),high:Math.min(1,s+i)}},Ai=e=>Math.round(e*1e4)/1e4,zg=(e,t)=>{let r=UE(e,t);return{hits:e,n:t,rate:t===0?null:Ai(e/t),ci95:r&&{low:Ai(r.low),high:Ai(r.high)}}},WE=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!Ol(n))continue;let o=e.slice(0,r),s=FE.exec(n.body)?.[1],i=Xg.exec(n.subject)?.[1],a=s?o.find(c=>c.hash.startsWith(s)):o.findLast(c=>c.subject===i);a&&t.add(a.hash)}return t},VE=(e,t)=>{let r=new Set(e.files.filter(n=>!Al.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},GE=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&BE(n)&&VE(e,n)),th=(e,t)=>{let r=WE(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(LE(u))),i=s.filter(({commit:u})=>!Ol(u)),a=i.filter(({commit:u})=>t-u.committedAt>=259200),c=i.filter(({commit:u})=>r.has(u.hash)).length,l=a.filter(({commit:u,position:p})=>GE(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:zg(c,i.length),followUpFixRate:zg(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},Dl=(e,t)=>{let r=[e.n<30?`agent n=${e.n}`:null,t.n<30?`human n=${t.n}`:null].filter(Boolean);return r.length>0||e.rate===null||t.rate===null||!e.ci95||!t.ci95?{suppressed:!0,reason:`${r.join(", ")} < 30`,difference:null,intervalsOverlap:null}:{suppressed:!1,reason:null,difference:Ai(e.rate-t.rate),intervalsOverlap:e.ci95.low<=t.ci95.high&&t.ci95.low<=e.ci95.high}};var So=90,HE=864e5,qE=async(e,t)=>{if(await Ce(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await KE({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${Qg}`;return eh(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},ih=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*HE).toISOString(),o=await qE(e,n),s=th(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:Dl(s.agent.revertRate,s.human.revertRate),followUpFixRate:Dl(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:$l.source,followUpWindowHours:72,followUpIgnoredFiles:Al,mergesExcluded:!0}}},Oi=e=>`${(e*100).toFixed(1)}%`,rh=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${Oi(e.rate)} (${e.hits}/${e.n}, 95% CI ${Oi(e.ci95.low)}\u2013${Oi(e.ci95.high)})`,Il=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${rh(t.revertRate)}`,` ${72}h follow-up-fix rate: ${rh(t.followUpFixRate)}`].join(`
|
|
159
|
+
`),Di=async({since:e=So})=>{let t=await ih({cwd:await $(),sinceDays:e,nowMs:Date.now()}),{classes:r,comparison:n}=t;d.info(`Change stats for ${t.repoRoot} \u2014 last ${e} days (${t.from.slice(0,10)} \u2192 ${t.until.slice(0,10)}, merges excluded)`),d.info(Il("agent",r.agent)),d.info(Il("human",r.human)),d.info(Il("total",r.total));let o=(s,i)=>{if(i.suppressed)return` ${s}: comparison suppressed (${i.reason})`;let a=i.intervalsOverlap?"intervals overlap":"intervals do not overlap";return` ${s}: agent \u2212 human = ${Oi(i.difference??0)} (${a})`};return d.info(["Agent vs human:",o("revert rate",n.revertRate),o("follow-up-fix rate",n.followUpFixRate)].join(`
|
|
160
|
+
`)),{content:b(JSON.stringify(t,null,2)),structuredContent:t}},nh=F.object({hits:F.number().describe("Changes that hit the metric"),n:F.number().describe("Changes the rate is computed over"),rate:F.number().nullable().describe("hits / n, rounded to 4 places; null when n is 0"),ci95:F.object({low:F.number(),high:F.number()}).nullable().describe("Wilson 95% score interval; null when n is 0")}),Nl=F.object({commits:F.number().describe("Non-merge commits in range for this class"),reverts:F.number().describe("Of those, revert commits (excluded from both rate denominators)"),changes:F.number().describe("Non-revert commits \u2014 the revert-rate denominator"),revertRate:nh.describe("Changes later reverted by an in-range commit"),followUpFixRate:nh.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),oh=F.object({suppressed:F.boolean().describe("True when either class has n below minN"),reason:F.string().nullable(),difference:F.number().nullable().describe("agent rate \u2212 human rate"),intervalsOverlap:F.boolean().nullable().describe("Whether the two Wilson intervals overlap")}),_l=C({name:"change-stats",description:"Read-only change-failure baseline for the git repo at cwd: commits classified agent (Claude trailers) vs human, with revert rate and 72h follow-up-fix rate per class, each with n and a Wilson 95% interval. The agent-vs-human comparison is suppressed when either n < 30.",inputSchema:{since:F.number().int().positive().optional().describe(`Window in days, ending now (default ${So})`)},outputSchema:{repoRoot:F.string().describe("git toplevel the stats were read from"),sinceDays:F.number(),from:F.string().describe("ISO start of the window"),until:F.string().describe("ISO end of the window (now)"),classes:F.object({agent:Nl,human:Nl,total:Nl}),comparison:F.object({minN:F.number(),revertRate:oh,followUpFixRate:oh}),heuristics:F.object({agentTrailers:F.array(F.string()),fixSubjectPattern:F.string(),followUpWindowHours:F.number(),followUpIgnoredFiles:F.array(F.string()),mergesExcluded:F.boolean()})},handler:Di});import{z as Ht}from"zod";import Ml from"node:fs/promises";import YE from"node:path";var nn=()=>Object.keys(yf.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),zE=new Set(["protectedEnvs"]),Eo={project:"per-project override",global:"user-global override"},Ii=(e,t)=>{if(he()&&zE.has(e))throw new O({status:"refused",agentMode:j.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(!nn().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: ${nn().join(", ")}.`)}},ah=e=>{try{return JSON.parse(e)}catch{return e}},XE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ZE=async e=>{let t;try{t=await Ml.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 ${w(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!XE(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},QE=async(e,t)=>{t===null?await Ml.rm(e,{force:!0}):Mt(e,t,420),eo()},Ni=async(e,t,r)=>{let n=await ee(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await ZE(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Ml.mkdir(YE.dirname(o),{recursive:!0}),Mt(o,`${JSON.stringify(c,null,2)}
|
|
161
|
+
`,420),eo();try{await K({autoMigrate:"off"})}catch(l){throw await QE(o,s),new Error(`${l.message}
|
|
162
|
+
${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},jl=async({key:e,value:t,global:r})=>{Ii(e,"config-set");let n=r?"global":"project",o=ah(t),{file:s,previous:i}=await Ni(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${Eo[n]} (${w(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:b(JSON.stringify(a,null,2)),structuredContent:a}};var _i=async({key:e}={})=>{let[t,r]=await Promise.all([K(),ee()]),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(!nn().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${nn().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:b(JSON.stringify(o,null,2)),structuredContent:o}},eP={config:Ht.record(Ht.string(),Ht.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:Ht.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Ht.string().optional().describe("The top-level key asked for, when one was."),value:Ht.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Ht.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Fl=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:Ht.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:eP,handler:e=>_i(e)});import iP from"node:fs";import{z as pe}from"zod";import xo from"node:fs";import on from"node:path";import tP from"node:process";var rP=on.join(".infra-kit","dev-context"),nP=".infra-kit",ch=(e,t)=>{let r=on.resolve(e);for(;;){let n=on.join(r,t);if(xo.existsSync(n))return n;let o=on.dirname(r);if(o===r)return;r=o}},oP=e=>{let t=ch(e,rP);if(t)return t;let r=ch(e,nP);return r?on.join(r,"dev-context"):void 0},Ll=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Po=e=>typeof e=="string"?e:"",sP=(e,t,r)=>{let n=on.join(e,t);try{let o=xo.statSync(n),s=JSON.parse(xo.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Po(i.package),port:Ll(i.port),alias:Po(i.alias),origin:Po(i.origin),release:Po(i.release),env:Po(i.env),pid:Ll(i.pid),writtenAt:Ll(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},To=(e=tP.cwd())=>{let t=Date.now(),r=oP(e);if(!r||!xo.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=xo.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>sP(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 Mi=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Xn,n=To(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&&(iP.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:b(JSON.stringify(u,null,2)),structuredContent:u}},aP={active:pe.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:pe.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:pe.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:pe.array(pe.object({app:pe.string().describe("App folder name (the fragment filename without .json)."),package:pe.string().describe("The app package name the vite helper reads to decide a local route."),port:pe.number().describe("The actual bound port the dev server is listening on."),pid:pe.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:pe.string().describe("Registered portless hostname for the app."),origin:pe.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:pe.string().describe("Release slug the runner recorded for this worktree."),env:pe.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:pe.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:pe.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:pe.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:pe.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.")},Bl=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:aP,handler:()=>Mi()});import{spawnSync as dv}from"node:child_process";import ae from"node:fs";import pv from"node:os";import ve from"node:path";import ht from"node:process";import{z as Ee}from"zod";import{execFileSync as cP}from"node:child_process";var lh=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},lP=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],uP=e=>lP.some(t=>t.test(e)),dP="/bin/ps",pP=()=>cP(dP,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
163
|
+
`),uh=(e=pP)=>{try{return e().some(uP)}catch{return!0}};import{Chalk as mP}from"chalk";import Ul from"node:process";var Wl={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},fP=new Set(["warn","fail"]),gP=24,sn=" ",dh=" ",hP=(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:[""]},ph=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},yP=e=>{let t=new mP({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)}},mh=(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),vP=(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=mh(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}},wP=(e,t,r,n)=>{let o=vP(ph(e.rows),e.rows.length,t,r),s=Math.max(1,n-sn.length-e.label.length-o.plainWidth);return`${sn}${t.header(e.label)}${" ".repeat(s)}${o.text}`},kP=(e,t,r,n,o)=>{let s=fP.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=dh.length+i+1+t+2,p=Math.max(gP,o-u),[m,...f]=hP(e.message,p),y=" ".repeat(u),E=A=>s?A:r.dim(A);return[`${dh}${c(n[e.status])} ${l} ${E(m??"")}`.trimEnd(),...f.map(A=>`${y}${E(A)}`),...(e.notes??[]).map(A=>`${y}${A}`.trimEnd())]},bP=(e,t,r,n,o)=>{let s=ph(t),i=n.rule.repeat(Math.max(12,Math.min(o-sn.length,56))),a=mh(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[`${sn}${r.dim(i)}`,`${sn}${c}${l.join("")}`]},Vl=(e,t={})=>{let r=t.width??80,n=yP(t.color??!1),o=t.unicode??!0?Wl.unicode:Wl.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,"",`${sn}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[wP(u,n,o,r),...u.rows.flatMap(p=>kP(p,c,n,o,r)),""]);return[a,"",...l,...bP(e,i,n,o,r)]},RP=new Set(["","0","false","none"]),SP=["LC_ALL","LC_CTYPE","LANG"],EP=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!RP.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,PP=(e,t)=>{if(t)return!1;let r=SP.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Gl=(e={})=>{let t=e.env??Ul.env,r=e.stream??Ul.stderr;return{color:EP(t,r),unicode:PP(t,e.ascii??!1),width:r.columns??80}},pt=(e,t={})=>{(t.write??(n=>{Ul.stderr.write(n)}))(`${Vl(e,Gl(t)).join(`
|
|
164
164
|
`)}
|
|
165
|
-
`)};var
|
|
166
|
-
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:
|
|
165
|
+
`)};var xP="Tools & CLIs",TP="Shell & integration",CP="Project config",$P="Doppler env tokens",AP="Dev proxy (portless)",OP="Claude Code plugin",DP=`portless serving TLS on :${Ft}`,Jl=[[xP,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[TP,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[CP,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[$P,["tokens.json present","env tokens configured","tokens.json perms"]],[AP,["portless installed","portless node","portless service target",DP,"portless CA chain valid","portless CA trusted","portless routes"]],[OP,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],fh="Other",IP=Jl.map(([e])=>e),NP=new Map(Jl.flatMap(([e,t])=>t.map(r=>[r,e]))),xV=Jl.flatMap(([,e])=>e),Kl=new Set(["portless routes","tokens.json perms"]),_P=e=>{let t=new Map;for(let n of e){let o=NP.get(n.name)??fh,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...IP,fh].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var MP=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return We(e)}},jP=e=>{let t=e.filter(r=>r.status==="fail"&&Kl.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:_P(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:MP(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Hl=(e,t={})=>{pt(jP(e),t)};var FP=e=>e.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"),LP=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>FP(t[1])),BP=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:LP(t[1])},UP=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},WP=e=>{let t=e.split(`
|
|
166
|
+
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:UP(t.slice(10))},gh=(e,t)=>{try{return e==="darwin"?BP(t):e==="linux"?WP(t):null}catch{return null}};import{Buffer as Nh}from"node:buffer";import Me from"node:fs/promises";import tt from"node:path";import _h from"node:process";import{$ as Hi}from"zx";import VP from"node:process";var Co=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var hh=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(X())throw new O({status:"argument_required",argument:e,agentMode:j.source},2,t);if(!VP.stdin.isTTY)throw new g(void 0,t)},qt=async e=>{hh("version");let{runBranchPicker:t}=await import("./boot-ST2534PA.js"),r=await t(e);if(r===null)throw new Co;return r},Yt=async(e,t)=>{hh("versions");let{runBranchMultiPicker:r}=await import("./boot-ST2534PA.js"),n=await r(e,t);if(n===null)throw new Co;return n};import{$ as Sh}from"zx";import{$ as jV}from"zx";import{$ as cn}from"zx";import{$ as yh}from"zx";var ql=async e=>{let{operation:t}=e;try{await yh({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 yh({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"})}},JP=4,an=async e=>{let{operation:t}=e,r=await rf();if(r.length===0)return;d.error(`working tree has uncommitted changes:
|
|
167
167
|
${r.join(`
|
|
168
|
-
`)}`);let n=r.slice(0,
|
|
169
|
-
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},
|
|
170
|
-
`);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}},
|
|
168
|
+
`)}`);let n=r.slice(0,JP),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}`})},$o=async e=>{let{operation:t,base:r}=e;if(await Vr()===r)return;let n=(await st(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}`})},_e=async e=>{let{operation:t}=e;if(await of())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 an({operation:t})};var KP=e=>e.map(t=>({pr:t,id:Q(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>tf(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Ao=200,vh=(e,t)=>{e.length<Ao||d.warn({source:t,limit:Ao},`\u26A0\uFE0F ${t} returned ${Ao} PRs \u2014 the page is full, so older release PRs may be missing`)},HP=async()=>{let[e,t]=await Promise.all([cn`gh pr list --limit ${Ao} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,cn`gh pr list --limit ${Ao} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);vh(r,"release PR discovery (base dev)"),vh(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)}))},Oo="find open release PRs",wh=async()=>{try{let e=await HP();if(e.length===0)throw new g(void 0,{operation:Oo,remediation:"open a release PR first, or check you are in the right repo"});return KP(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},ji=async()=>(await wh()).map(t=>t.headRefName),qP=e=>{let t=Do(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=Yl(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}},G=async()=>(await wh()).map(qP),Fi=async e=>{let{branch:t,body:r}=e;try{await cn({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}},YP=async(e,t)=>{let r=cn({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`)},Li=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=ef(t,n),a=mt(n),c=cn({quiet:!0}),l=Te(t),u=Io(r,o);try{await an({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 YP(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await cn({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as zl}from"zx";var ln=async e=>{let t=await zl`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Xl=async e=>{let t=await zl`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Bi=async e=>{try{let t=await zl`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 _o from"node:process";var zP="x-seraph-loginreason",XP="AUTHENTICATED_FAILED",ZP=(e,t=160)=>{let r=e.split(`
|
|
169
|
+
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},bh=(e,t)=>t===XP||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",kh=(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}`,un=class extends Error{status;kind;body;context;constructor(t){let r=bh(t.status,t.seraphLoginReason),n=ZP(t.body);super(n===""?`${t.context}: ${kh(r,t.status)}`:`${t.context}: ${kh(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},No=e=>e instanceof un,Rh=e=>e.headers.get(zP);var dn=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new un({status:e.status,seraphLoginReason:Rh(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},wr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,Zl=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 dn(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},pn=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 dn(a,"Failed to get Jira project versions"),await a.json()},$t=async(e,t)=>(await pn(t)).find(o=>o.name===e)||null,mn=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 dn(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}},Ql=async(e,t)=>{let{versionName:r}=e,n=await $t(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await mn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},fn=async()=>{let e=_o.env.JIRA_BASE_URL,t=_o.env.JIRA_TOKEN||_o.env.JIRA_API_TOKEN,r=_o.env.JIRA_PROJECT_ID,n=_o.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(`
|
|
170
|
+
`);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}},At=async()=>{try{return await fn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Ui=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 dn(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},eu=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 dn(c,"Failed to remove Jira version")};var Eh="dev",Ph={regular:"dev",hotfix:"main"},mt=e=>Ph[e],Do=e=>{let t=Object.entries(Ph).find(([,r])=>r===e);return t?t[0]:null},Io=(e,t)=>(t??"").trim()!==""?`${e}
|
|
171
171
|
|
|
172
172
|
${t}`:`${e}
|
|
173
|
-
`,
|
|
174
|
-
`)||`the verify command exited with code ${n??"unknown"} and printed nothing`},
|
|
175
|
-
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},
|
|
176
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),
|
|
177
|
-
`)},
|
|
178
|
-
`).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),
|
|
179
|
-
`)){let l=/^(.*):\d+: leftover conflict marker/.exec(c);l?.[1]&&a.add(l[1])}return[...a].sort()}},
|
|
180
|
-
${l}`:l}).join(""),c=
|
|
181
|
-
\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}`)},
|
|
182
|
-
\u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await
|
|
183
|
-
`)[0]}}},
|
|
173
|
+
`,tu=async(e="regular")=>{let t=mt(e),r=Sh({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 Sh({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()},QP=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await $t(t,r);if(!s)return(await Zl({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 mn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},ru=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=le(t),c=await QP({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=wr(r,c),u=await Li({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:ne(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Wi=async()=>{let e=new Map,t=await At();if(!t)return e;try{let r=await pn(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},me=async()=>{let e=await Wi();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Mo=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Yl=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Vi=e=>e.flatMap(t=>{let r=Q(t);return r?[{branch:t,id:r,label:ne(r)}]:[]}),Ot=e=>{try{return Te(ke(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)})}},jo=e=>{if(e===Eh)return Eh;let t=Q(e);return t?ne(t):e},Dt=e=>e.flatMap(t=>{let r=Q(t);return r?[ne(r)]:[]}),ex=(e,t)=>t?t.get(e)||"regular":void 0,fe=e=>{let{branches:t,descriptions:r,types:n}=e;return Vi(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(le(s)),type:ex(o,n)}))};import xh from"node:fs/promises";import tx from"node:path";import{$ as nu}from"zx";var V="pnpm-lock.yaml",rx=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Ch=async(e,t)=>{let r=tx.join(e,V),n=`${t}:${V}`;try{let o=await nu({cwd:e,quiet:!0})`git show ${n}`;await xh.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${V} to start from: ${Th(o)}`}}try{await nu({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${V}: ${Th(o)}`}}return rx.test(await xh.readFile(r,"utf8"))?{ok:!1,reason:`${V} still carries conflict markers after pnpm ran`}:(await nu({cwd:e,quiet:!0})`git add -- ${V}`,{ok:!0})},Th=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as kr}from"zx";var ou="Merge remote-tracking branch 'origin/dev' into ",nx=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},ox=2048,sx=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-ox)).filter(s=>s.length>0).join(`
|
|
174
|
+
`)||`the verify command exited with code ${n??"unknown"} and printed nothing`},ix=async e=>{try{return(await kr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
|
|
175
|
+
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},ax=async(e,t)=>{let r=nx(t),n=await ix(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await lf(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},$h=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await Ce(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 cx({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},cx=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await Ce(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Qn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await Pc(r),await kr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${ou}${n}`;await kr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await kr({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 ax(r,i)}}finally{await xc(r)}},Ah=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),Oh="pnpm install --frozen-lockfile",Dh=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await Pc(t),await kr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await kr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,sx(a))}finally{await xc(t)}return{kept:o,failed:s}},Fo=async(e,t,r="origin/dev")=>{await kr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Qn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import su from"node:process";var Gi=new Set,Ji=e=>(Gi.add(e),()=>{Gi.delete(e)}),lx=async()=>{for(let e of[...Gi])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}Gi.clear()},ux=["SIGINT","SIGTERM"],Ih=async(e,t={})=>{let{register:r=(i,a)=>{su.on(i,a)},unregister:n=(i,a)=>{su.off(i,a)},exit:o=i=>{su.exit(i)}}=t,s=new Map;for(let i of ux){let a=()=>{lx().then(()=>{o(Tf(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var dx="pnpm install --frozen-lockfile --ignore-scripts",iu="pnpm install --frozen-lockfile",Mh=64*1024,Uh=4096,Bo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Uh)},U=async(e,t)=>(await Hi({cwd:e,quiet:!0})`git ${t}`).stdout,cu=e=>e.split(`
|
|
176
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),hn=e=>e.split("\0").filter(t=>t.length>0),br=async(e,t)=>{try{return(await U(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Wh=async e=>tt.resolve(e,(await U(e,["rev-parse","--git-common-dir"])).trim()),lu=e=>e.then(()=>!0,()=>!1),Lo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),uu=e=>e?.length===1&&e[0]===V,Vh=async e=>tt.join(await Wh(e),"infra-kit","merge-dev-resolutions"),du=async(e,t)=>tt.join(await Vh(e),`${af(t)}.json`),Gh=async e=>{try{return JSON.parse(await Me.readFile(e,"utf8"))}catch{return null}},yn=async(e,t)=>{let r=await du(e,t.branch);await Me.mkdir(tt.dirname(r),{recursive:!0}),await Me.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
177
|
+
`)},Jh=async e=>{let t=await Vh(e),r=await Me.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Gh(tt.join(t,o))))).filter(o=>o!==null)},Kh=async e=>Promise.all((await Jh(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await lu(Me.stat(t.worktreePath))}))),jh=(e,t)=>({worktreePath:e.worktreePath,baseSha:e.baseSha,devSha:e.devSha,conflictPaths:e.conflictPaths,...e.editablePaths?{editablePaths:e.editablePaths}:{},lockfileOnly:e.lockfileOnly,rererePreResolved:e.rererePreResolved,state:t}),px=e=>e.editablePaths??e.conflictPaths,mx=e=>tt.posix.basename(e)==="package.json",pu=e=>e.conflictPaths.includes(V)||e.lockfileBlob!==void 0,Hh=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(V);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=hn(await U(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await fu(e),...r].some(mx)},qh=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",mu=async(e,t,r)=>{await U(e,["worktree","remove","--force",r]).catch(()=>Me.rm(r,{recursive:!0,force:!0})),await Me.rm(await du(e,t),{force:!0}).catch(()=>{}),await U(e,["worktree","prune"]).catch(()=>{})},Yh=async e=>hn(await U(e,["diff","--name-only","-z","--diff-filter=U"])),Ki=async e=>hn(await U(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),fx=async(e,t)=>{let r=(await U(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await lu(Me.stat(tt.join(await Wh(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(cu(await U(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},zh=e=>e.split("/").includes("node_modules"),qi=async(e,t)=>{let r=new Set(px(t));t.editablePaths&&await Hh(e,t)&&r.add(V);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=hn(await U(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await fu(e),...o].filter(a=>!r.has(a)),i=(await Ki(e)).filter(a=>!n.has(a)&&!zh(a));return[...new Set([...s,...i,...await gx(e)])].sort()},fu=async e=>{let t=hn(await U(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},gx=async e=>(await U(e,["ls-files","-v"])).split(`
|
|
178
|
+
`).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),hx=async(e,t)=>{let r=`:(exclude)${V}`;try{return await U(e,["diff","--cached","--check",t,"--",".",r]),[]}catch(n){let{stdout:o="",stderr:s="",exitCode:i}=n;if(s.trim().length>0||o.trim().length===0||i!==1&&i!==2)throw new g(n,{operation:"check the staged resolution for conflict markers"});let a=new Set;for(let c of o.split(`
|
|
179
|
+
`)){let l=/^(.*):\d+: leftover conflict marker/.exec(c);l?.[1]&&a.add(l[1])}return[...a].sort()}},yx=async(e,t)=>{let r=[];for(let n of t)(await lu(Me.lstat(tt.join(e,n)))||(await U(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await U(e,["--literal-pathspecs","add","-A","--",...r])},au=async e=>(await U(e,["write-tree"])).trim(),Xh=async e=>(await U(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),vx=e=>{let t=`${iu} && `;if(e!==iu)return e?.startsWith(t)?e.slice(t.length):e},wx=e=>e?`${iu} && ${e}`:dx,kx=async(e,t)=>{try{return await Hi({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Bo(r)}}},Zh=async(e,t)=>{let r=(await U(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await U(e,["diff","--cached","--stat",l,"--",V])).trim(),o=pu(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await U(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)
|
|
180
|
+
${l}`:l}).join(""),c=Nh.byteLength(a)>Mh;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Nh.from(a).subarray(0,Mh).toString():a,resolutionDiffTruncated:c}},Qh=async e=>{let{cwd:t,conflicted:r,verifyFailed:n,devSha:o,verify:s}=e,i=new Map;for(let a of r)i.set(a,await Fh(t,a,o,"conflict"));for(let a of n)i.set(a,await Fh(t,a,o,"verify-failed",s));return i},bx=async(e,t,r)=>{let n=async(a,c)=>hn(await U(e,["diff","--name-only","-z","--no-renames",`${a}...${c}`])),o=await n(t,r),s=await n(r,t);return{editablePaths:[...new Set([...o,...s])].filter(a=>a!==V).sort(),lockfileBothSides:o.includes(V)&&s.includes(V)}},Rx=async(e,t,r,n)=>{let o=await Yh(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await br(e,"HEAD"),a=await br(e,"MERGE_HEAD");return i!==r||a!==n?{reason:"the merge no longer reproduces (already up to date?) \u2014 re-run release merge-dev"}:{conflictPaths:[],...await bx(e,r,n),autoMergeTree:await au(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await br(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await fx(e,o),lockfileOnly:uu(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await U(e,["--version"])).trim()})`}},Sx={conflict:"needs-agent","verify-failed":"verify-failed"},Fh=async(e,t,r,n,o)=>{let s=await Gh(await du(e,t));if(s)return{resolution:jh(s,"exists"),reason:`resolution-exists: ${s.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let i=await Ce(e,`origin/${t}`);if(!i)return{reason:`origin/${t} does not exist on origin`};let a=cf(e,t),c=()=>mu(e,t,a),l=Ji(c);try{await U(e,["worktree","prune"]),await Me.mkdir(tt.dirname(a),{recursive:!0}),await U(e,["worktree","add","--detach",a,i]),await Hi({cwd:a,quiet:!0})`git merge --no-commit ${r} -m ${ou+t}`.catch(()=>{});let u=await Rx(a,n,i,r);if("reason"in u)return await c(),u;let p={branch:t,worktreePath:a,baseSha:i,devSha:r,...u,...n==="verify-failed"&&o?{handOffVerify:o}:{},ignoredAtHandoff:await Ki(a),cliVersion:L.version,createdAt:new Date().toISOString()};return await yn(e,p),{resolution:jh(p,p.lockfileOnly?"lockfile-only":Sx[n])}}catch(u){return await c(),{reason:Bo(u)}}finally{l()}},ey=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Jh(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=Te(ke(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 Yt(fe({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},Ex=async(e,t)=>{let r=await Me.realpath(t).catch(()=>null);if(!r)return!1;let n=await st(e);for(let o of n)if(await Me.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},gn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),ty=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 Ex(e,n))return gn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await br(n,"HEAD"),i=await br(n,"MERGE_HEAD"),a=r??vx(t.handOffVerify);return s===t.baseSha&&i===t.devSha?$x(e,t,o,a):Px(t,o,s,i)},Px=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return gn(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 Xh(o),i=n?null:await br(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 gn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await qi(o,e);return c.length>0?gn(t,"out-of-scope-edit",qh(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:pu(e),...await Zh(o,e)}},Lh=async(e,t)=>{let r=cu(await U(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},xx=async(e,t)=>{let r=t.worktreePath,n=await Lh(r,V),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await br(r,`${t.autoMergeTree}:${V}`),i=await Ch(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[V]};let a=await Lh(r,V);if(a!==null&&a!==o&&(t.lockfileBlob=a,await yn(e,t)),n!==null&&n!==a&&!s)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 c=await qi(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},Tx=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await fu(r)).filter(c=>n.has(c)):t.conflictPaths;await yx(r,o.filter(c=>c!==V));let s=await qi(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:qh(t),paths:s};let i=(await Yh(r)).filter(c=>c!==V);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await hx(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Bo(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await Hh(r,t)?xx(e,t):null},Cx=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 kx(o,n),a=(await Ki(o)).filter(c=>!s.has(c)&&!zh(c)&&tt.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await yn(e,t),i},$x=async(e,t,r,n)=>{let o=t.worktreePath,s=await Tx(e,t);if(s)return{...r,blocked:s};let i=pu(t),a=await au(o),c=await Cx(e,t,a,wx(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return gn(l,"verify-failed",c.reason??"the verify command failed");let u=await qi(o,t),p=cu(await U(o,["diff","--name-only"]));return u.length>0||p.length>0||await au(o)!==a?gn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await yn(e,t)),{...l,...await Zh(o,t)})},Ax=12e4,Ox=async(e,t=Ax)=>{let r=Hi({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{..._h.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&_h.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Bo(s)};let i=(await U(e,["rev-parse","--git-path","index.lock"])).trim();return await Me.rm(tt.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},Dx={"verify-failed":"verify-failed","tree-changed":"tree-changed"},Ix=e=>{let t=e.blocked;return{branch:e.branch,status:Dx[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},Nx=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 Ox(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await U(o,["rev-parse","HEAD"])).trim(),c=(await U(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await yn(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 Xh(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}},_x=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 Fo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Bo(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 Ce(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Qn(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)},Mx=e=>{d.info(`
|
|
181
|
+
\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}`)},ry=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await ey({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Lo();if(i)return Bh(t,a,o,s);let c=[];for(let m of a){let f=await ty(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await yn(t,m)),c.push(f)}Mx(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new O({status:"refused",plan:l,agentMode:j.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 J(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:jx(p)})}catch(m){if(!Et(m))throw m;return{...Lo(),declined:!0}}return Bh(t,a,o,p)},ny=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},jx=e=>{let t=[],r=!1;for(let o of Sf())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"]},Fx=async(e,t,r,n)=>{let o=await ty(e,t,r);if(o.blocked)return Ix(o);let s=await Nx(e,o,t,n);if(!("sha"in s))return s;let i=await _x(e,t,s.sha);return i==="keep"?s:i},Lx=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(`
|
|
182
|
+
\u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await oi(e,r),o=[];for(let s of t){let i=n.pushed||await Gr(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(-Uh)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
|
|
183
|
+
`)[0]}}},Bh=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await Fx(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await Lx(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 mu(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}},oy=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await ey({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Lo();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await J(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!Et(a))throw a;return{...Lo(),declined:!0}}for(let a of s)await mu(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Lo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Bx from"node:fs";import Ux from"node:os";import Wx from"node:path";var Vx="infra-kit.json",Gx="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)",Jx="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Uo=async()=>{let e;try{e=await $()}catch{return null}let t=e.trim();return t===""||t===Ux.homedir()?null:t},sy=async()=>{let e=await Uo();return e===null&&d.info(Gx),e},Kx=async()=>{let e=await Uo();return e===null?null:Bx.existsSync(Wx.join(e,Vx))?e:(d.info(Jx),null)};var Hx=async e=>{try{return await Re(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},iy=async({dryRun:e=!1}={})=>{let t=await Kx(),r=L.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await ho(t,{version:r,dryRun:e})];for(let o of await Hx(t)){let s=await Pt(o);n.push(...await yo(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import ye from"node:fs";import ta from"node:os";import ie from"node:path";import Pu from"node:process";import gu from"node:fs";import ay from"node:os";import cy from"node:path";import qx from"node:process";import{z as zi}from"zod";var ly=e=>{try{return gu.readFileSync(e,"utf-8")}catch{return null}},vn="claude in chrome",Yx="com.anthropic.claude_code_browser_extension",Yi="run `/chrome` inside Claude Code to set up Claude in Chrome",zx={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},Xx=e=>{try{return gu.accessSync(e,gu.constants.X_OK),!0}catch{return!1}},uy=e=>{try{return JSON.parse(e)}catch{return null}},Zx=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Wo=(e={})=>{let t=e.platform??qx.platform,r=e.home??ay.homedir(),n=e.readText??ly,o=e.isExecutable??Xx,s=zx[t];if(s===void 0)return{name:vn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=cy.join(r,...s,`${Yx}.json`),a=n(i);if(a===null)return{name:vn,status:"warn",message:`Chrome native host not registered \u2014 ${Yi}`};let c=zi.object({path:zi.string().min(1)}).safeParse(uy(a));if(!c.success)return{name:vn,status:"fail",message:`${w(i)} has no host path \u2014 ${Yi} again`};let l=c.data.path;if(!o(l))return{name:vn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${Yi} again`};let u=Zx.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:vn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${Yi} again`}:{name:vn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},hu=(e={})=>{let t=e.home??ay.homedir(),r=e.readText??ly,n=zi.object({claudeInChromeDefaultEnabled:zi.boolean().optional()}).safeParse(uy(r(cy.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import Zi from"node:fs/promises";import Qx from"node:path";import eT from"node:process";var dy=` // // Editor tooling only \u2014 a JSON Schema URL for completion and validation. Ignored at runtime.
|
|
184
184
|
// "$schema": "https://\u2026/infra-kit.schema.json",
|
|
185
185
|
//
|
|
186
186
|
// // The committed file's shape version. A CLI that reads an older version refuses the file and
|
|
@@ -293,7 +293,7 @@ ${l}`:l}).join(""),c=Dh.byteLength(a)>Nh;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
293
293
|
// // also fixes its modes), or by hand: both are supported, which is why the store carries no
|
|
294
294
|
// // repo-identity field and no mandatory version. Pasting a token into an
|
|
295
295
|
// // infra-kit.json (any layer) is REJECTED: the loader refuses to parse it and tells you to revoke
|
|
296
|
-
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,
|
|
296
|
+
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,yu=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
|
|
297
297
|
//
|
|
298
298
|
// Merge chain (later layers override earlier ones at top-level keys):
|
|
299
299
|
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
@@ -315,9 +315,9 @@ ${l}`:l}).join(""),c=Dh.byteLength(a)>Nh;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
315
315
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
316
316
|
// user-global layer \u2014 it is shown here only to document the full, valid config shape.
|
|
317
317
|
{
|
|
318
|
-
${
|
|
318
|
+
${dy}
|
|
319
319
|
}
|
|
320
|
-
`,
|
|
320
|
+
`,vu=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
321
321
|
//
|
|
322
322
|
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
|
|
323
323
|
// <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
|
|
@@ -333,9 +333,9 @@ ${ly}
|
|
|
333
333
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
334
334
|
// override layer \u2014 it is shown here only to document the full, valid config shape.
|
|
335
335
|
{
|
|
336
|
-
${
|
|
336
|
+
${dy}
|
|
337
337
|
}
|
|
338
|
-
`,
|
|
338
|
+
`,wu=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
|
|
339
339
|
//
|
|
340
340
|
// Machine-local registry the vendor commands (sync/manifest/diff) read to know
|
|
341
341
|
// where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
|
|
@@ -347,109 +347,110 @@ ${ly}
|
|
|
347
347
|
// "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
|
|
348
348
|
// "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
|
|
349
349
|
}
|
|
350
|
-
`;var
|
|
351
|
-
`,"utf-8");let o=
|
|
350
|
+
`;var py=!1,tT=e=>e.replace(/\.json$/,".example.jsonc"),rT=async e=>{try{return await Zi.readFile(e,"utf-8")}catch{return null}},wn=async e=>{let t=e.userProject,r=tT(t);await Zi.mkdir(Qx.dirname(t),{recursive:!0});let n=!await oe(t);n&&await Zi.writeFile(t,`{}
|
|
351
|
+
`,"utf-8");let o=vu(e.projectName),s=await rT(r)!==o;return s&&await Zi.writeFile(r,o,"utf-8"),n&&eo(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},kn=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,ku=async()=>{if(eT.env.INFRA_KIT_NO_SEED||py)return;py=!0;let e;try{e=await ee()}catch{return}if(await oe(e.main))try{let t=await wn(e);t.createdConfig?d.info(kn(t)):t.refreshedExample&&d.debug(`Refreshed ${w(t.examplePath)} to match the current schema.`)}catch(t){d.debug({err:t,msg:`Skipped seeding ${w(e.userProject)} (config bootstrap failed).`})}};import{spawn as mT}from"node:child_process";import by from"node:fs";import En from"node:process";import{fileURLToPath as Ry}from"node:url";import Qi from"node:fs";import bn from"node:path";var my="auto-setup.json",nT="auto-setup.log",oT="auto-setup.lock",fy="auto-setup.notified",sT=3,iT=3600*1e3,aT=()=>bn.join(Rt(),my),Rn=()=>bn.join(Rt(),nT),gy=()=>bn.join(Rt(),oT),cT=()=>bn.join(Rt(),fy),lT=new Set(["ok","attention","failed"]),uT=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"&&lT.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},dT=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(uT)},Sn=(e=t=>Qi.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(aT()));return dT(t)?t:null}catch{return null}},hy=e=>{let t=Rt();Qi.mkdirSync(t,{recursive:!0}),Mt(bn.join(t,my),JSON.stringify(e),384)},pT=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),yy=(e=t=>Qi.readFileSync(t,"utf8"))=>{try{let t=Number(e(cT()).trim());return Number.isFinite(t)?t:null}catch{return null}},vy=e=>{let t=Rt();Qi.mkdirSync(t,{recursive:!0}),Mt(bn.join(t,fy),String(e),384)},wy=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<iT?!1:e.version!==t?!0:pT(e)&&e.attempts<sT};var ky=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],bu=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return ky.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Om(o,s,i)?"local-install":null:"not-a-tty"};var fT=e=>{mT(En.execPath,[e,"--parent-pid",String(En.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},gT=()=>Ry(new URL("./update-check.js",import.meta.url)),hT=()=>by.realpathSync(Ry(new URL("./cli.js",import.meta.url))),yT=/^[\w@./+ -]+$/,vT=e=>yT.test(e),wT=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||St(e.latestVersion,t)&&e.updateCommand.every(vT)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Xs(e.updateCommand)}`)},kT=(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 ${w(Rn())}, or run: infra-kit setup`),o(e.finishedMs)},Ru=(e,t={})=>{try{let r=t.argv??En.argv,n=t.env??En.env,o=t.isTty??!!En.stdout.isTTY,s=t.cwd??En.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??hT(),c=t.readCache??no,l=t.spawnChild??fT,u=t.fileExists??(y=>by.existsSync(y)),p=t.notify??(y=>{d.info(y)});if(bu({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:xe})!==null)return;let m=c();wT(m,e,p);try{kT((t.readAutoSetup??Sn)(),e,(t.readNotified??yy)(),p,t.writeNotified??vy)}catch{}if(!Dc(m,i))return;let f=t.childPath??gT();if(!u(f))return;l(f)}catch{}};import gt from"node:fs/promises";import ft from"node:path";import{pathToFileURL as ST}from"node:url";import ET from"yaml";import{z as Tn}from"zod";import bT from"node:fs/promises";import Su from"node:os";import Eu from"node:path";import{z as RT}from"zod";import{z as Vo}from"zod";var Sy="vendor.json",Ey=Vo.object({workspaceDir:Vo.string().min(1),source:Vo.string().min(1),targets:Vo.array(Vo.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 Pn=()=>Eu.join(Su.homedir(),Em,Sy),xn=e=>{if(e==="~")return Su.homedir();if(e.startsWith("~/"))return Eu.join(Su.homedir(),e.slice(2));if(Eu.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},ea=async()=>{let e=Pn(),t;try{t=await bT.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:
|
|
352
352
|
|
|
353
353
|
{
|
|
354
354
|
"workspaceDir": "~/projects",
|
|
355
355
|
"source": "my-starter",
|
|
356
356
|
"targets": ["my-repo"]
|
|
357
357
|
}
|
|
358
|
-
`)}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=
|
|
359
|
-
`,"utf-8"),await
|
|
360
|
-
`,"utf-8"),await
|
|
361
|
-
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},
|
|
362
|
-
`)[0]??n;return
|
|
363
|
-
`),s=0;for(;s<o.length&&
|
|
358
|
+
`)}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=Ey.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${RT.prettifyError(n.error)}`);return n.data};var Py=e=>e.replace(/\.json$/,".yml"),xy=async()=>{let e;try{e=await ee()}catch{return}let t={label:"infra-kit.json",yml:Py(e.main),json:e.main,schema:vf},r=[...Ze.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:ft.join(ft.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Tc},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Py(e.userProject),json:e.userProject,schema:Tc}],n=0;for(let o of r){let[s,i]=await Promise.all([oe(o.yml),oe(o.json)]);if(s){if(i){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${w(o.json)} already exists (remove the stale .yml manually)`);continue}try{let a=await gt.readFile(o.yml,"utf-8"),c=ET.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${Tn.prettifyError(l.error)}`);continue}await gt.mkdir(ft.dirname(o.json),{recursive:!0}),await gt.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
|
|
359
|
+
`,"utf-8"),await gt.rm(o.yml,{force:!0}),d.info(`\u2713 Migrated ${w(o.yml)} \u2192 ${w(o.json)}`),n++}catch(a){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 ${a.message}`)}}}n>0&&Lt()},Ty=async()=>{let e;try{e=await ee()}catch{return}let t=ft.dirname(e.userGlobal),r=[{from:ft.join(t,"config.json"),to:e.userGlobal},{from:ft.join(t,"config.example.jsonc"),to:ft.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([oe(o),oe(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await gt.mkdir(ft.dirname(s),{recursive:!0}),await gt.rename(o,s),d.info(`\u2713 Renamed ${w(o)} \u2192 ${w(s)}`),n++}catch(c){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${c.message}`)}}}n>0&&Lt()},PT=Tn.object({workspaceDir:Tn.string().min(1),targets:Tn.array(Tn.string()).min(1)}).strict(),Cy=async()=>{let e=Pn(),t=ft.dirname(e),r=ft.join(t,"vendor.config.ts"),[n,o]=await Promise.all([oe(r),oe(e)]);if(n){if(o){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${w(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await gt.stat(r),c=(await import(`${ST(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=PT.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${Tn.prettifyError(p.error)}`);return}await gt.mkdir(t,{recursive:!0}),await gt.writeFile(e,`${JSON.stringify(p.data,null,2)}
|
|
360
|
+
`,"utf-8"),await gt.rm(r,{force:!0}),l?d.info(`\u26A0 Migrated ${w(r)} \u2192 ${w(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${w(e)} directly to change them.`):d.info(`\u2713 Migrated ${w(r)} \u2192 ${w(e)}`)}catch(s){d.info(`\u26A0 Skipped ${w(r)} \u2014 ${s.message}`)}}},$y=async()=>{let e=await xT(),t=0;for(let r of e)if(await oe(r))try{let n=await mf(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof df?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Lt()},xT=async()=>{try{let e=await ee();return Ze.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[kf()]}};var Rr="# -- infra-kit:begin --",zt="# -- infra-kit:end --",TT=[["# region infra-kit","# endregion infra-kit"]],CT="# infra-kit shell functions",Cn=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},$n="Run `source ~/.zshrc` or open a new terminal to activate.",$T={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Ke=async(e,t)=>{try{return await t()}catch(r){throw new Cn(e,r)}},xu=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Ke("zshrc",()=>{r(DT())}),await Ke("zshenv",()=>{r(IT())}),await Ke("migrations",async()=>{await _T(),NT(),r($T)}),await Ke("user-config",()=>{r(jT())});let n=await Ke("guidance",async()=>{let{entries:s,root:i}=await UT();return r(...s),i}),o=await Ke("plugin-pointer",async()=>sy());return r(...VT(o,n)),await Ke("worktrees",async()=>{r(...await qT(o))}),await Ke("plugin-pointer",async()=>{await zT(o,r)}),await Ke("mcp-proxies",async()=>{r(...await ZT(o))}),await Ke("project-config",async()=>{r(...await FT(o))}),await Ke("token-perms",async()=>{r(await OT())}),await Ke("chrome",()=>{r(AT())}),r(...MT()),t},AT=()=>{let e=Wo();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"}:hu()?{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"}},OT=async()=>{let e=await Cf();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 Oy=e=>{let t=ie.dirname(e);return ye.existsSync(ie.join(e,".git"))?e:t===e?null:Oy(t)},Dy=(e,t,r,n)=>{if(!Ze.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=ye.realpathSync(t)}catch{}return Oy(ie.dirname(o))===null?null:Jo(e,ta.homedir(),o,["the infra-kit block updated"])},Iy=e=>ye.existsSync(e)?ye.readFileSync(e,"utf-8"):null,DT=()=>{let e=ie.join(ta.homedir(),".zshrc"),t=Iy(e),r=t===null?"":eC(t),n=Hr({content:r,body:My(),startMarker:Rr,endMarker:zt,placement:"append-end"}),o=Dy("zshrc",e,t,n);return o!==null?o:(ye.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},IT=()=>{let e=ie.join(ta.homedir(),".zshenv"),t=Iy(e),r=Hr({content:t??"",body:Tu(),startMarker:Rr,endMarker:zt}),n=Dy("zshenv",e,t,r);return n!==null?n:(ye.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},NT=()=>{ye.rmSync(ie.join(Rt(),"projects"),{recursive:!0,force:!0})},_T=async()=>{await xy(),await Ty(),await $y(),await Cy()},MT=()=>{let e=Pu.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:$n,level:"info"}),t},jT=()=>{let e=ie.join(ta.homedir(),".infra-kit"),t=ie.join(e,"infra-kit.json");return ye.mkdirSync(e,{recursive:!0}),ye.writeFileSync(ie.join(e,"infra-kit.example.jsonc"),yu(),"utf-8"),ye.writeFileSync(ie.join(e,"vendor.example.jsonc"),wu(),"utf-8"),ye.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ye.writeFileSync(t,`{}
|
|
361
|
+
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},FT=async e=>{if(Pu.env.INFRA_KIT_NO_SEED)return[Go("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Go("skipped","not inside a git repository")];try{let t=await ee();if(!ye.existsSync(t.main))return[Go("skipped",`no project config at ${t.main}`)];let r=await wn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:kn(r),level:"info"}]:[Go("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Go("warned",t instanceof Error?t.message:String(t))]}},Go=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),LT=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},BT=(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"},...LT(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},UT=async()=>{let{skipped:e,root:t,version:r,written:n}=await iy({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:BT(r,n)}},ra=e=>`cd ${Nm(e)} && infra-kit setup --skip-tools`,Jo=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${ra(t)}`,level:"info"}),WT=(e,t)=>{let r=ie.relative(e,t.path);return t.status==="withheld"?Jo("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"}},Ay=(e,t)=>{let r=Je;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?ue: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 ${dt} from ${ie.join(e,Je)} \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 "${ue}" key`:`no ${r}`})`,level:"info"}},VT=(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 ${q} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],GT=()=>[wl,Ct].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),JT=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${L.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${L.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:Xs(e.updateCommand),level:"info"}]:[r]},KT=(e,t)=>e.status==="skipped-cli-stale"?JT(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${q} 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: ${rn}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${q} (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"},...GT()]:[{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: ${Ct}`,level:"warn"}],Ny={stale:!1},HT=async()=>{let e=no(),t=e===null?await Nc(Pu.env):e.latestVersion;return t===null||!_c(t,L.version)?Ny:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Am(t)}},qT=async e=>{if(e===null)return[];let r=`${await Ae(e)}${ge}`,n=Object.values(Ur).filter(o=>!ye.existsSync(ie.join(r,o)));for(let o of Object.values(Ur))ye.mkdirSync(ie.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"}]},YT=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${q} is installed; the update worker keeps it current`,level:"debug"}]:[Jo("plugin-pointer",e,".claude/settings.json",[`the ${q} plugin installed`])],zT=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(WT(e,kl(ie.join(e,".claude","settings.json"),{write:!Ze.withheld})));let r=ur({projectPath:e}).kind==="installed";if(Ze.withheld){t(...YT(e,r),Ay(e,tn(e)));return}let n=r?await HT():Ny;t(...KT(fl({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(Ay(e,tn(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: ${Ct}`,level:"warn"})}},_y=(e,t)=>{let r=ie.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},XT=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=_y(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,Jo("mcp-proxies",e,ie.relative(e,t.path),s)]},ZT=async e=>{if(e===null)return[];if(!ye.existsSync(ie.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 K()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
|
|
362
|
+
`)[0]??n;return Ze.withheld?[Jo("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?[]:Ze.withheld?XT(e,Ro({projectRoot:e,proxies:t,write:!1})):_y(e,Ro({projectRoot:e,proxies:t,write:!0}))},QT=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"),eC=e=>{let t=Jt(e,Rr,zt);if(t!==null)return t;for(let[a,c]of TT){let l=Jt(e,a,c);if(l!==null)return l}let r=e.indexOf(CT);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
|
|
363
|
+
`),s=0;for(;s<o.length&&QT(o[s]);)s++;let i=o.slice(s).join(`
|
|
364
364
|
`);return n+(i?`
|
|
365
|
-
${i}`:"")},
|
|
366
|
-
`)},
|
|
367
|
-
${
|
|
368
|
-
${
|
|
369
|
-
`),
|
|
370
|
-
${
|
|
371
|
-
${
|
|
372
|
-
${t.stderr}`}},resolveBinPath:async e=>{let t=await
|
|
373
|
-
`).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),kC=async()=>{let e=await vC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return wC(e.stdout)},bC=async()=>{let e=await Tt();return e?(await un(e)).map(r=>r.name):[]},Xo=async()=>{let[e,t]=await Promise.allSettled([kC(),bC()]);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"),_u({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import RC from"node:fs";import SC from"node:path";var Wu=[".claude/settings.json",".claude/settings.local.json"],EC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],PC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),xC=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},TC=(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(PC).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},CC=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},$C=()=>Er.filter(e=>e.mutating),AC=e=>{let t=xC(e);return t===null?[]:$C().filter(r=>EC.some(n=>CC(r).some(o=>TC(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},OC=(e,t)=>{let r;try{r=RC.readFileSync(SC.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}},Xy=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Wu){let n=OC(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=AC(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var DC=e=>e.every(t=>t.status!=="fail"),IC=["brew","git","gh","doppler","aws"],NC=async e=>{let t=await qo(IC,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},At=async(e,t,r,n)=>{try{return await Cn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},_C=async()=>{let e="orca installed",t=await Bt();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)"}},dv=(e,t,r,n)=>{let o=ye.join(uv.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ie.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ie.readFileSync(o,"utf-8"),a=i.indexOf(kr),c=i.indexOf(qt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+qt.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`}},MC=()=>dv("zshrc init block",".zshrc","shell",_y()),jC=()=>dv("zshenv session block",".zshenv","session-env",xu()),FC=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await A(),r=ye.join(t,"pnpm-workspace.yaml");if(!ie.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ie.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}`}}},LC=async()=>{try{return jt(),{config:await H(),error:null}}catch(e){return{config:null,error:e}}},BC=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)"}},UC=384,Vu=448,WC=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(", "),VC=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}}})),GC=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Ze,o=t.resolveToken??Df;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 VC(await li(),o);return{name:r,status:"pass",message:WC(s)}},JC=()=>gt.env[ur]||void 0,KC=async(e={})=>{let t="tokens.json present",r=e.readStore??Ze,n=e.storePath??Lt;if((e.readEnvToken??JC)())return{name:t,status:"skip",message:`${ur} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${ur} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},Zo=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},HC=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Lt,o=t.statPath??qC,s=t.chmodPath??ie.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(Zo(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=ye.dirname(i),c=ye.dirname(a),l=ye.dirname(c),p=[{target:l,expected:Vu,actual:Zo(l,o)},{target:c,expected:Vu,actual:Zo(c,o)},{target:a,expected:Vu,actual:Zo(a,o)},{target:i,expected:UC,actual:Zo(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${w(f.target)} is ${Zy(f.actual)}, expected ${Zy(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}`}},Zy=e=>`0${e.toString(8).padStart(3,"0")}`,qC=e=>{try{return ie.statSync(e)}catch{return null}},YC=async()=>{let e="user override path";try{let t=await ee(),r=ie.existsSync(t.userProject),n=await Go(t.userProject,r),o=r?Jo(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},zC=async()=>{let e="legacy user-global config",t;try{t=await ee()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ye.join(ye.dirname(t.userGlobal),"config.json");return ie.existsSync(r)?ie.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Qy=/^\d+\.\d+\.\d+$/,ev=(e,t)=>e===t||!Qy.test(e)||!Qy.test(t)?!1:Dn([`v${e}`,`v${t}`])[0]===`v${e}`,XC=async e=>{let t;try{t=await ke(e)}catch{return[]}return t.flatMap(r=>{let n=Et(lt(ye.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},tv=e=>Dn(e.map(t=>`v${t}`)).map(t=>t.slice(1)),ZC=async(e,t,r)=>{let n="Guidance version",o=mr(t,fr),s=await XC(e),a=(o===null?s:[o,...s]).filter(p=>kt(p,r));if(a.length>0){let p=tv(a).at(-1);return{name:n,status:"warn",message:`${a.length} guidance ${a.length===1?"block was":"blocks were"} generated by a newer infra-kit (newest ${p}, current ${r}) \u2014 CLI behind the block, run: pnpm add -g infra-kit@${p}`}}let c=o!==null&&ev(o,r),l=s.filter(p=>ev(p,r));if(!c&&l.length===0)return{name:n,status:"pass",message:`guidance blocks match infra-kit ${r}`};let u=[...c?[`the root block is from infra-kit ${o} \u2014 run: infra-kit audit --fix --root`]:[],...l.length>0?[`${l.length} package guidance ${l.length===1?"block was":"blocks were"} generated by an older infra-kit (oldest ${tv(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},QC=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"},{name:"Guidance version",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await ee()).main}catch{return e}if(!ie.existsSync(t))return e;let r=ye.dirname(t),n=ye.join(r,"CLAUDE.md"),o=ie.existsSync(n)?ie.readFileSync(n,"utf-8"):"",s=We(o,be,De);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools"},await ZC(r,o,L.version)]},e$=async()=>{try{let e=(await ee()).main;return ie.existsSync(e)?ye.dirname(e):null}catch{return null}},t$=e=>{let t=wf();return t===null||!kt(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${en}`},r$=e=>{let t=e.kind==="installed"?si(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 ${Y} version ${t}${t$(t)}`}},rv=3,nv=(e,t)=>Ee(e)===Ee(t),n$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(nv(e.projectDir,e.gitRoot))return"";let r=qn(e.gitRoot,Ee(e.projectDir),Ee)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return nv(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},o$=(e,t)=>{let r="plugin installed",n=n$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${Y} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${Y} is not installed. Run: ${Pt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-rv,i=s>0?` and ${s} more`:"",a=`${o.slice(0,rv).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${Y} is installed for ${a} only, not this project. Run: ${Pt}${n}`}},s$=()=>At("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 i$=(e,...t)=>{try{return JSON.parse(ie.readFileSync(ye.join(e,...t),"utf-8"))}catch{return null}},a$=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=si(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=i$(r,Ge),o=n!==null&&typeof n=="object"?n[ut]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},ov=e=>`Plugin ${Y} ${e===null?"(version unreadable)":e}`,c$=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${Pt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${ov(e.version)} still carries an MCP server in its ${Ge}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${en}), then restart Claude Code`}}return{name:t,status:"pass",message:`${ov(e.version)} is skills-only \u2014 no ${Ge}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},l$=(e,t)=>{let r=cr(e===null?{}:{projectPath:e}),n=eo();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${le} is known to Claude Code`:`Marketplace ${le} is not registered. Run: claude plugin marketplace add ${Ft}`},o$(r,t),r$(r),c$(a$(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${L.version}`}]},u$=(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 ${w(kn())}, or run: infra-kit setup`}},d$=({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(", ")},p$=e=>{let t="Agent mode",r=Zs(e),n=d$(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})`}},sv=4,m$=e=>{let t=e.slice(0,sv).join(", "),r=e.length-sv;return r>0?`${t} +${r} more`:t},f$=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Xy(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"} (${m$(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 ${Wu.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`}},g$=(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`},h$=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 Gh(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${g$(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`}},pv=e=>kc(["trust"],{bin:e}),y$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),iv="ERR_TLS_CERT_ALTNAME_INVALID",mv=()=>`portless serving TLS on :${Mt}`,v$=async(e,t,r)=>{let n=mv();return await e(Mt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Mt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Mt}. Install it once (needs root): \`${_t(t,r)}\`.`}},w$=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(Mt,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(iv)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${iv} 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=>y$.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${pv(n)}\`, or reinstall: \`${_t(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},k$=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${pv(r)}\` (no sudo needed).`}},b$=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 \`${kc(["alias","--remove","<name>"],{bin:r})}\`.`}},Xt="portless service target",es=e=>({name:Xt,status:"warn",message:e}),fv=e=>e==="darwin"?_m:e==="linux"?Mm:null,R$=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Nm}`:`sudo systemctl restart ${jm}`,S$="/bin/ps",E$=e=>{try{let t=lv(S$,["-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}},av=e=>{try{return ie.readFileSync(e,"utf-8")}catch{return null}},P$=e=>{try{return ie.statSync(e).mtime}catch{return null}},x$=2e3,T$=e=>{try{let t=lv(e,["-p","process.version"],{encoding:"utf-8",timeout:x$}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},C$=(e,t)=>({platform:e.platform??gt.platform,readServiceFile:e.readServiceFile??av,readFile:e.readFile??av,exists:e.exists??ie.existsSync,realpath:e.realpath??Ee,mtime:e.mtime??P$,execPath:e.execPath??gt.execPath,home:e.home??uv.homedir(),cwd:e.cwd??gt.cwd(),repoRoot:e.repoRoot??Lo,stateDir:(e.stateDir??Lm)(),processStartTime:e.processStartTime??E$,version:e.version??gt.version,arch:e.arch??gt.arch,nodeVersionOf:e.nodeVersionOf??T$,isGlobal:e.isGlobal??Xs().node.isGlobal,nodeFs:e.nodeFs??ie,stableNode:null,stableNodeSidecar:null,bin:t}),ts="portless node",Pr="~/.infra-kit/node",Qo=e=>({row:{name:ts,status:"fail",message:e},stableNode:null,sidecar:null}),cv=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},$$=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,A$=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,O$=e=>{let t=Gm(e.home),r=cv(e.nodeFs.lstatSync,t);if(r===void 0)return Qo(`${Pr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Qo(`${Pr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Jm(e.home,e.nodeFs);if(n===null)return Qo(`${Pr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=cv(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 Qo(`${Pr} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!A$(c,e))return Qo(`${Pr} does not run as Node ${e.version} (${$$(c)}). Re-run through the current Node: \`${_t(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:ts,status:"pass",message:`${Pr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},D$=e=>{if(fv(e.platform)===null)return{row:{name:ts,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=O$(e);return e.isGlobal()?t:{...t,row:{name:ts,status:"skip",message:`not a global install; the global infra-kit keeps ${Pr} current`}}},gv=(e,t)=>{let r=C$(e,t),n=D$(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},I$=(e,t)=>{let r=t.readFile(ye.join(e,"package.json"));try{let n=r===null?null:Re.object({version:Re.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},N$=e=>{let t=Number.parseInt(e.readFile(ye.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},_$=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},M$=(e,t,r)=>{let n=N$(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(_$(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ye.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},j$=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:qn(await t.repoRoot()??r,e,t.realpath)},xr=e=>({state:"drifted",row:e}),F$=async(e,t,r)=>{let n=_t(r.bin,r);if(!r.exists(e))return xr({name:Xt,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=ye.join(bc(r.home),"dist","cli.js");if(t!==o)return xr(es(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(zs(r.home,r.exists)===null)return xr({name:Xt,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(bc(r.home));if(await j$(s,r))return xr({name:Xt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=L$(e,n,r);if(i!==null)return i;let a=I$(s,r),c=M$(s,a,r);return c!==null?{state:"converged",row:es(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${R$(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Xt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},L$=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:xr(es(`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:xr(es(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),hv=async e=>{let t=fv(e.platform);if(t===null)return{state:"absent",row:{name:Xt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Xt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=mh(e.platform,r)??[];return n===void 0||o===void 0?xr(es(`could not parse ${t} \u2014 re-run \`${_t(e.bin,e)}\` to rewrite it.`)):F$(n,o,e)},yv=async(e,t)=>{let{seams:r}=gv(e,t);return{state:(await hv(r)).state,stableNode:r.stableNode}},B$=()=>[ts,Xt,mv(),"portless CA chain valid","portless CA trusted","portless routes"],U$=async(e={})=>{let t=e.resolveBin??Im,r=e.isProxyServing??Fm,n=e.handshake??Wm,o=e.caTrusted??Um,s=e.routes??zn,i=e.isListening??Yn,a=(e.caPath??Bm)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...B$().map(E=>({name:E,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=gv(e,c),m=s(),f=await v$(r,c,u),v=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await w$(n,m,a,c,u);return[l,p,(await hv(u)).row,f,v,k$(o(),a,c),await b$(m,i,c)]},W$=async(e={})=>{let t="portless routes",r=e.routes??zn,n=e.isListening??Yn,o=e.devSessionRunning??ch,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}=ah(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??Vm().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ca=async(e={})=>{let t=await LC(),r=NC(e.probeDeps??Ko()),n=async(m,f)=>{let[v,E]=await Promise.all([f,r]),k=E.get(m);return k===void 0?v:{...v,detail:k}},o=await Promise.all([n("brew",At("brew installed",Ke("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",At("git installed",Ke("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",At("gh installed",Ke("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),At("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",At("doppler installed",Ke("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",At("aws installed",Ke("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),At("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),At("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"),_C(),Promise.resolve(MC()),Promise.resolve(jC()),FC(),Promise.resolve(BC(t)),KC(),GC(t),HC(e.fix??!1),YC(),zC()]),s=await U$(e.portlessDeps);if(e.fix){let m=await W$(),f=s.findIndex(v=>v.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await e$(),a=await Lo(),c={projectDir:gt.env.CLAUDE_PROJECT_DIR||null,cwd:gt.cwd(),gitRoot:a},l=[await s$(),...l$(i,c),Bo(),p$({env:gt.env,stdinIsTTY:gt.stdin.isTTY===!0,flag:j.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:f$(a)],u=[...o,await h$(a),...s,...await QC(),...l,u$(bn(),L.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Gl.has(m.name),detail:m.detail})),allPassed:DC(u),cliVersion:L.version};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}},Gu=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:Re.array(Re.object({name:Re.string().describe("Name of the check"),status:Re.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:Re.string().describe("Details about the check result"),fixable:Re.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Re.object({manager:Re.string().describe("Which package manager owns this install, read from its resolved path"),version:Re.string().nullable().describe("The version the tool reported, or null"),present:Re.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Re.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:Re.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Re.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ca()});import{E2E_MODE_ENV as gA}from"@slip-stream-kit/config/internal";import Zu from"node:fs";import hA from"node:os";import ns from"node:path";import da from"node:process";import{z as x}from"zod";var ht=(e,t,r)=>new O({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as V$,loadDev as G$,readAppAliasName as J$,readCloudOrigin as K$,readLocalContext as wv}from"@slip-stream-kit/config/internal";import vv from"node:fs";import Tr from"node:path";import la from"node:process";import{z as Ju}from"zod";var H$=async e=>{let t=Tr.join(e,"apps"),r=vv.existsSync(t)?vv.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=Tr.join(t,o,"tests"),a=(await ct(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},q$=(e,t)=>{let[r,n]=Tr.relative(e,t).split(Tr.sep);return r==="apps"&&n?n:void 0},Y$=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(q$(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 O({status:"argument_required",argument:a,choices:Ju.toJSONSchema(Ju.object({app:Ju.enum(i)})),agentMode:j.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(", ")}`})},z$=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}})),X$=e=>Po(e).apps.find(t=>t.env!=="")?.env??null,Ku=async(e,t={})=>{let r=t.cwd??la.cwd(),n=t.projectRoot??await A(),o=(t.env??la.env)[jr]||null,s=t.healthProbe??_c,i=Y$(await H$(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=Tr.join(n,"apps",c,l),p=(await pr(u)).name,m=(await ct(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${Tr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Gf(u),v=J$(p,u),E=`${v}.localhost`,k=`https://${E}`,h=0;if(l==="ui")h=(t.listRoutes??zn)().find(P=>P.name===E||P.name===v)?.port??0;else{let P=wv(u).info.get(p);h=P?.port??0,k=P?.origin??k}let R=h>0&&await s({tag:a,port:h,kind:l})==="ok",S=R?X$(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:S,localUrl:k,served:R}},kv=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}},Hu=async(e,t={})=>{let r=t.healthProbe??_c,n=wv(e.targetDir),o=e.kind==="ui"?await G$(e.targetDir):void 0,s=o?.proxy?V$({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:K$(e.deployedUrlEnv??void 0,t.env??la.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...kv(e),mode:"local",baseUrl:e.localUrl,routes:await z$(s,i,r)}},qu=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw ht("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${Tr.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??la.env)[n];if(!r||!s){let i=s?jr:n;throw ht("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 ${jr}, and ${i} is not set`})}return{...kv(e),mode:"cloud",baseUrl:s,routes:[]}};import Z$ from"node:fs";import Q$ from"node:path";import{stripVTControlCharacters as eA}from"node:util";import{z as I}from"zod";var bv=2e3,Rv="--reporter=line,json",Sv=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Ev=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Yu=I.object({message:I.string().optional()}),Pv=I.object({type:I.string()}),tA=I.object({status:I.string(),retry:I.number(),error:Yu.optional(),errors:I.array(Yu).optional(),annotations:I.array(Pv).optional(),attachments:I.array(I.object({name:I.string(),path:I.string().optional()})).optional()}),rA=I.object({projectName:I.string(),status:I.string(),expectedStatus:I.string().optional(),annotations:I.array(Pv).optional(),results:I.array(tA)}),nA=I.object({title:I.string(),file:I.string(),line:I.number().optional(),tests:I.array(rA)}),xv=I.lazy(()=>I.object({title:I.string(),specs:I.array(nA).optional(),suites:I.array(xv).optional()})),oA=I.object({config:I.object({rootDir:I.string().optional()}).optional(),suites:I.array(xv),errors:I.array(Yu).optional(),stats:I.object({expected:I.number(),unexpected:I.number(),flaky:I.number(),skipped:I.number()})}),Tv=e=>{let t=eA(e);return t.length>bv?`${t.slice(0,bv)}\u2026`:t},sA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Tv(t)},iA=e=>e.status==="unexpected"||e.status==="flaky",aA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},cA=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),lA=(e,t)=>{let r=e.filter(iA),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?sA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},uA=e=>{let t=oA.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(k=>[...cA(k)])),v=m.some(k=>k.expectedStatus==="failed");if(!v&&!f.has("fixme")&&!f.has("skip"))return;let E=a.get(p)??{file:p,fail:0,fixme:0,skip:0};v&&(E.fail+=1),f.has("fixme")?E.fixme+=1:f.has("skip")&&(E.skip+=1),a.set(p,E)},u=(p,m)=>{for(let f of p.specs??[]){let v=r?.rootDir?Q$.resolve(r.rootDir,f.file):f.file,E=[...m,f.title].join(" \u203A ");l(v,f.tests);for(let[k,h]of aA(f.tests)){let R=lA(h,{title:E,file:v,line:f.line??null,project:k});R&&(R.runs>1&&R.failedRuns<R.runs&&(c+=1),i.push(R))}}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?[]:[Tv(p.message)])}},Cv=e=>{try{return uA(JSON.parse(Z$.readFileSync(e,"utf8")))}catch{return null}};import rs from"node:fs";import Av from"node:path";import ua from"node:process";var dA=e=>Av.join(e,"node_modules",".cache","infra-kit-e2e.lock"),pA=e=>{try{return ua.kill(e,0),!0}catch(t){return t.code==="EPERM"}},$v=e=>{try{return rs.writeFileSync(e,String(ua.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},zu=e=>{try{let t=Number.parseInt(rs.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},Ov=e=>{let t=dA(e);if(rs.mkdirSync(Av.dirname(t),{recursive:!0}),!$v(t)){let r=zu(t);if(r!==null&&r!==ua.pid&&pA(r))return{holder:r};if(rs.rmSync(t,{force:!0}),!$v(t))return{holder:zu(t)??0}}return{release:()=>{zu(t)===ua.pid&&rs.rmSync(t,{force:!0})}}};import{spawn as mA}from"node:child_process";import fA from"node:os";import Xu from"node:process";var Dv=(e,t,r)=>new Promise((n,o)=>{let s=mA(e,t,r),i=Xu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Xu.off(l,a)};for(let l of i)Xu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+fA.constants.signals[u]:1))})});var yA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],vA=e=>yA.some(t=>{try{return Zu.readFileSync(ns.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),Qu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,wA=(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(`
|
|
374
|
-
`)},
|
|
365
|
+
${i}`:"")},My=()=>{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(`
|
|
366
|
+
`)},jy=()=>`${Rr}
|
|
367
|
+
${My()}
|
|
368
|
+
${zt}`,Tu=()=>["# 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(`
|
|
369
|
+
`),Cu=()=>`${Rr}
|
|
370
|
+
${Tu()}
|
|
371
|
+
${zt}`;import tC from"node:fs/promises";var Ko=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await tC.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}}},Ho=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import nC from"node:fs";import oC from"node:os";import Fy from"node:path";import sC from"node:process";import{$ as rC}from"zx";var An=()=>rC({quiet:!0});var iC=()=>[Fy.join(oC.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],aC=async e=>{try{return(await An()`command -v ${e}`).stdout.trim()||null}catch{return null}},qo=()=>({runCommand:async e=>{let t=await An()`${e}`;return{stdout:`${t.stdout}
|
|
372
|
+
${t.stderr}`}},resolveBinPath:async e=>{let t=await aC(e);return t!==null?t:iC().map(r=>Fy.join(r,e)).find(r=>nC.existsSync(r))??null},realpath:xe,platform:sC.platform});var Xt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),On=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,Dn=["darwin","linux"],ia=e=>t=>bc(t,e)?"homebrew":"unknown",aa=(e,t)=>r=>r===null?null:t(e(r),r),Au=e=>aa(ia(e.kegName),t=>t==="homebrew"?Xt(["brew","upgrade",e.brewFormula]):null),Ly=e=>zs(e,"Homebrew")||zs(e,"homebrew")?"homebrew":"unknown",cC={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:On,platforms:Dn,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:Ly,updateFor:aa(Ly,e=>e==="homebrew"?Xt(["brew","update"]):null)},$u={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Wy="https://awscli.amazonaws.com/v2/install.sh",Vy={steps:[["/bin/bash","-c",`curl -fsSL ${Wy} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},lC="/usr/local/aws-cli",uC=e=>zn(lC,e,xe)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Wy} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Vy,By=e=>bc(e,$u.kegName)?"homebrew":zs(e,"aws-cli")?"script":"unknown",dC={id:"aws",binName:"aws",...$u,probeArgv:["aws","--version"],versionFrom:On,platforms:Dn,prerequisites:[],bootstrapInstall:Vy,identify:By,updateFor:aa(By,(e,t)=>e==="homebrew"?Xt(["brew","upgrade",$u.brewFormula]):e==="script"?uC(t):null)},na={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},pC={id:"git",binName:"git",...na,probeArgv:["git","--version"],versionFrom:On,platforms:Dn,prerequisites:["brew"],bootstrapInstall:Xt(["brew","install",na.brewInstallSpec]),identify:ia(na.kegName),updateFor:Au(na)},oa={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},mC={id:"gh",binName:"gh",...oa,probeArgv:["gh","--version"],versionFrom:On,platforms:Dn,prerequisites:["brew"],bootstrapInstall:Xt(["brew","install",oa.brewInstallSpec]),identify:ia(oa.kegName),updateFor:Au(oa)},sa={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},fC={id:"doppler",binName:"doppler",...sa,probeArgv:["doppler","--version"],versionFrom:On,platforms:Dn,prerequisites:["brew"],bootstrapInstall:Xt(["brew","install","gnupg"],["brew","install",sa.brewInstallSpec]),identify:ia(sa.kegName),updateFor:Au(sa)},Yo="portless",Uy=e=>$m(e,Yo)===null?"unknown":"npm",gC={id:"portless",binName:Yo,npmPackage:Yo,probeArgv:["portless","--version"],versionFrom:On,platforms:[...Dn,"win32"],prerequisites:[],bootstrapInstall:Xt(["npm","install","-g",Yo]),identify:Uy,updateFor:aa(Uy,e=>e==="npm"?Xt(["npm","install","-g",`${Yo}@latest`]):null)},Ou={brew:cC,git:pC,aws:dC,gh:mC,doppler:fC,portless:gC},Sr=Object.keys(Ou),He=e=>Ou[e],Du=(e,t)=>e.platforms.includes(t),Iu=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 He(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Gy=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Jy=async(e,t)=>{try{return await e(t)}catch{return null}},hC=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Ky=async(e,t)=>{if(!Du(e,t.platform))return Gy(e.id);let r=await Jy(t.runCommand,e.probeArgv),n=await hC(t,e.binName);if(r==null&&n==null)return Gy(e.id);let o=r??(n==null?null:await Jy(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)}},zo=async(e,t)=>Promise.all(e.map(r=>Ky(He(r),t)));import{$ as RC}from"zx";import{z as Hy}from"zod";var qy=/^\d{4}-\d{2}-\d{2}$/,Xo=e=>{if(!qy.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},Yy=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,In=class extends Error{constructor(t){super(Yy(t)),this.name="InvalidReleaseDateError"}},Er=e=>{let t=e.trim();if(!Xo(t))throw new In(t);return t},Zo=e=>{let t=e.trim();return t===""||Xo(t)?!0:Yy(t)},Nu=Hy.string().refine(Xo,{message:"Expected a calendar date in yyyy-mm-dd form."}),_u=Hy.string().refine(e=>e===""||Xo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var Zt=e=>e.slice(1).split(".").map(Number),Nn=e=>[...e].sort((t,r)=>{let[n,o,s]=Zt(t),[i,a,c]=Zt(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var Xy="next",yC=/^v?(\d+)\.(\d+)\.(\d+)$/,vC=e=>e.replace(/^.*release\//,""),Mu=e=>{let t=vC(e.trim()),r=yC.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},zy=e=>`${e[0]}.${e[1]}.${e[2]}`,ju=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Mu(o);if(!s)continue;let i=zy(s);n.has(i)||(n.add(i),r.push(s))}return Nn(r.map(o=>zy(o))).map(o=>Zt(`v${o}`))},Pr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Fu=(e,t)=>{if(e.length===0)throw new Pr;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`},_n=(e,t)=>{try{return Fu(e,t)}catch(r){if(r instanceof Pr)return null;throw r}},Lu=e=>e.trim().toLowerCase()===Xy,la=e=>Lu(e)||Mu(e)!==null?{version:e}:{name:e},wC=e=>e==="regular"||e==="hotfix",Zy=e=>"name"in e,kC=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:Er(n)}},Bu=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=kC(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(!wC(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return ca({...la(n),type:s},{description:i,releaseDate:o})},Uu=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},ca=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},bC=e=>{let t=e.name.trim();return ti(t),ca({id:{kind:"name",name:t,raw:t},type:e.type},e)},Wu=(e,t)=>{let r=[...t];return e.map(n=>{if(Zy(n))return bC(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(Lu(o)){let a=Fu(r,n.type);return r.push(Zt(`v${a}`)),ca({id:ke(a),type:n.type},n)}let s=Mu(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),ca({id:ke(i),type:n.type},n)})},Vu=e=>e.some(t=>!Zy(t)&&Lu(t.version));var SC=e=>e.split(`
|
|
373
|
+
`).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),EC=async()=>{let e=await RC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return SC(e.stdout)},PC=async()=>{let e=await At();return e?(await pn(e)).map(r=>r.name):[]},Qo=async()=>{let[e,t]=await Promise.allSettled([EC(),PC()]);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"),ju({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import xC from"node:fs";import TC from"node:path";var Gu=[".claude/settings.json",".claude/settings.local.json"],CC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],$C=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),AC=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},OC=(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($C).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},DC=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},IC=()=>xr.filter(e=>e.mutating),NC=e=>{let t=AC(e);return t===null?[]:IC().filter(r=>CC.some(n=>DC(r).some(o=>OC(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},_C=(e,t)=>{let r;try{r=xC.readFileSync(TC.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}},Qy=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Gu){let n=_C(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=NC(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var MC=e=>e.every(t=>t.status!=="fail"),jC=["brew","git","gh","doppler","aws"],FC=async e=>{let t=await zo(jC,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},It=async(e,t,r,n)=>{try{return await An()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},LC=async()=>{let e="orca installed",t=await Wt();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)"}},mv=(e,t,r,n)=>{let o=ve.join(pv.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ae.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ae.readFileSync(o,"utf-8"),a=i.indexOf(Rr),c=i.indexOf(zt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+zt.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`}},BC=()=>mv("zshrc init block",".zshrc","shell",jy()),UC=()=>mv("zshenv session block",".zshenv","session-env",Cu()),WC=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await $(),r=ve.join(t,"pnpm-workspace.yaml");if(!ae.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ae.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}`}}},VC=async()=>{try{return Lt(),{config:await K(),error:null}}catch(e){return{config:null,error:e}}},GC=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)"}},JC=384,Ju=448,KC=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(", "),HC=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}}})),qC=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Qe,o=t.resolveToken??Nf;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 HC(await di(),o);return{name:r,status:"pass",message:KC(s)}},YC=()=>ht.env[pr]||void 0,zC=async(e={})=>{let t="tokens.json present",r=e.readStore??Qe,n=e.storePath??Ut;if((e.readEnvToken??YC)())return{name:t,status:"skip",message:`${pr} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${pr} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},es=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},XC=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Ut,o=t.statPath??ZC,s=t.chmodPath??ae.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(es(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=ve.dirname(i),c=ve.dirname(a),l=ve.dirname(c),p=[{target:l,expected:Ju,actual:es(l,o)},{target:c,expected:Ju,actual:es(c,o)},{target:a,expected:Ju,actual:es(a,o)},{target:i,expected:JC,actual:es(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${w(f.target)} is ${ev(f.actual)}, expected ${ev(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}`}},ev=e=>`0${e.toString(8).padStart(3,"0")}`,ZC=e=>{try{return ae.statSync(e)}catch{return null}},QC=async()=>{let e="user override path";try{let t=await ee(),r=ae.existsSync(t.userProject),n=await Ko(t.userProject,r),o=r?Ho(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},e$=async()=>{let e="legacy user-global config",t;try{t=await ee()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ve.join(ve.dirname(t.userGlobal),"config.json");return ae.existsSync(r)?ae.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},tv=/^\d+\.\d+\.\d+$/,rv=(e,t)=>e===t||!tv.test(e)||!tv.test(t)?!1:Nn([`v${e}`,`v${t}`])[0]===`v${e}`,t$=async e=>{let t;try{t=await Re(e)}catch{return[]}return t.flatMap(r=>{let n=Tt(ut(ve.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},nv=e=>Nn(e.map(t=>`v${t}`)).map(t=>t.slice(1)),r$=async(e,t,r)=>{let n="Guidance version",o=gr(t,hr),s=await t$(e),a=(o===null?s:[o,...s]).filter(p=>St(p,r));if(a.length>0){let p=nv(a).at(-1);return{name:n,status:"warn",message:`${a.length} guidance ${a.length===1?"block was":"blocks were"} generated by a newer infra-kit (newest ${p}, current ${r}) \u2014 CLI behind the block, run: pnpm add -g infra-kit@${p}`}}let c=o!==null&&rv(o,r),l=s.filter(p=>rv(p,r));if(!c&&l.length===0)return{name:n,status:"pass",message:`guidance blocks match infra-kit ${r}`};let u=[...c?[`the root block is from infra-kit ${o} \u2014 run: infra-kit audit --fix --root`]:[],...l.length>0?[`${l.length} package guidance ${l.length===1?"block was":"blocks were"} generated by an older infra-kit (oldest ${nv(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},n$=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"},{name:"Guidance version",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await ee()).main}catch{return e}if(!ae.existsSync(t))return e;let r=ve.dirname(t),n=ve.join(r,"CLAUDE.md"),o=ae.existsSync(n)?ae.readFileSync(n,"utf-8"):"",s=Ve(o,Se,Ie);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools"},await r$(r,o,L.version)]},o$=async()=>{try{let e=(await ee()).main;return ae.existsSync(e)?ve.dirname(e):null}catch{return null}},s$=e=>{let t=bf();return t===null||!St(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${rn}`},i$=e=>{let t=e.kind==="installed"?ai(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 ${q} version ${t}${s$(t)}`}},ov=3,sv=(e,t)=>xe(e)===xe(t),a$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(sv(e.projectDir,e.gitRoot))return"";let r=zn(e.gitRoot,xe(e.projectDir),xe)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return sv(e.cwd,e.gitRoot)?"":` \u2014 if Claude Code was launched from ${w(e.cwd)} rather than ${t}, it loaded neither the plugin nor this repo's hooks; launch it at ${t}`},c$=(e,t)=>{let r="plugin installed",n=a$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${q} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${q} is not installed. Run: ${Ct}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-ov,i=s>0?` and ${s} more`:"",a=`${o.slice(0,ov).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${q} is installed for ${a} only, not this project. Run: ${Ct}${n}`}},l$=()=>It("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 u$=(e,...t)=>{try{return JSON.parse(ae.readFileSync(ve.join(e,...t),"utf-8"))}catch{return null}},d$=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ai(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=u$(r,Je),o=n!==null&&typeof n=="object"?n[dt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},iv=e=>`Plugin ${q} ${e===null?"(version unreadable)":e}`,p$=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: ${Ct}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${iv(e.version)} still carries an MCP server in its ${Je}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${rn}), then restart Claude Code`}}return{name:t,status:"pass",message:`${iv(e.version)} is skills-only \u2014 no ${Je}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},m$=(e,t)=>{let r=ur(e===null?{}:{projectPath:e}),n=ro();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ue} is known to Claude Code`:`Marketplace ${ue} is not registered. Run: claude plugin marketplace add ${Bt}`},c$(r,t),i$(r),p$(d$(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${L.version}`}]},f$=(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 ${w(Rn())}, or run: infra-kit setup`}},g$=({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(", ")},h$=e=>{let t="Agent mode",r=ei(e),n=g$(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})`}},av=4,y$=e=>{let t=e.slice(0,av).join(", "),r=e.length-av;return r>0?`${t} +${r} more`:t},v$=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Qy(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"} (${y$(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 ${Gu.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`}},w$=(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`},k$=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 Kh(e)}catch(i){return{name:r,status:"skip",message:`could not read the merge-dev state: ${i.message}`}}if(n.length===0)return{name:r,status:"pass",message:"no merge-dev hand-off in progress"};let o=n.map(i=>{let a=i.worktreeExists?w(i.worktreePath):"worktree missing";return`${i.branch} (${w$(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`}},fv=e=>Rc(["trust"],{bin:e}),b$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),cv="ERR_TLS_CERT_ALTNAME_INVALID",gv=()=>`portless serving TLS on :${Ft}`,R$=async(e,t,r)=>{let n=gv();return await e(Ft,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Ft}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Ft}. Install it once (needs root): \`${jt(t,r)}\`.`}},S$=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(Ft,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(cv)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${cv} 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=>b$.has(u))?{name:s,status:"fail",message:`The daemon is serving a certificate that does not chain to ${w(r)}. Its CA was regenerated \u2014 run \`${fv(n)}\`, or reinstall: \`${jt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},E$=(e,t,r)=>{let n="portless CA trusted";return e?{name:n,status:"pass",message:`${w(t)} matches the recorded ca.trusted fingerprint`}:{name:n,status:"fail",message:`The portless CA is not trusted (or was regenerated). Run: \`${fv(r)}\` (no sudo needed).`}},P$=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 \`${Rc(["alias","--remove","<name>"],{bin:r})}\`.`}},Qt="portless service target",rs=e=>({name:Qt,status:"warn",message:e}),hv=e=>e==="darwin"?jm:e==="linux"?Fm:null,x$=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Mm}`:`sudo systemctl restart ${Lm}`,T$="/bin/ps",C$=e=>{try{let t=dv(T$,["-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}},lv=e=>{try{return ae.readFileSync(e,"utf-8")}catch{return null}},$$=e=>{try{return ae.statSync(e).mtime}catch{return null}},A$=2e3,O$=e=>{try{let t=dv(e,["-p","process.version"],{encoding:"utf-8",timeout:A$}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},D$=(e,t)=>({platform:e.platform??ht.platform,readServiceFile:e.readServiceFile??lv,readFile:e.readFile??lv,exists:e.exists??ae.existsSync,realpath:e.realpath??xe,mtime:e.mtime??$$,execPath:e.execPath??ht.execPath,home:e.home??pv.homedir(),cwd:e.cwd??ht.cwd(),repoRoot:e.repoRoot??Uo,stateDir:(e.stateDir??Um)(),processStartTime:e.processStartTime??C$,version:e.version??ht.version,arch:e.arch??ht.arch,nodeVersionOf:e.nodeVersionOf??O$,isGlobal:e.isGlobal??Qs().node.isGlobal,nodeFs:e.nodeFs??ae,stableNode:null,stableNodeSidecar:null,bin:t}),ns="portless node",Tr="~/.infra-kit/node",ts=e=>({row:{name:ns,status:"fail",message:e},stableNode:null,sidecar:null}),uv=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},I$=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,N$=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,_$=e=>{let t=Km(e.home),r=uv(e.nodeFs.lstatSync,t);if(r===void 0)return ts(`${Tr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return ts(`${Tr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Hm(e.home,e.nodeFs);if(n===null)return ts(`${Tr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=uv(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 ts(`${Tr} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!N$(c,e))return ts(`${Tr} does not run as Node ${e.version} (${I$(c)}). Re-run through the current Node: \`${jt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:ns,status:"pass",message:`${Tr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},M$=e=>{if(hv(e.platform)===null)return{row:{name:ns,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=_$(e);return e.isGlobal()?t:{...t,row:{name:ns,status:"skip",message:`not a global install; the global infra-kit keeps ${Tr} current`}}},yv=(e,t)=>{let r=D$(e,t),n=M$(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},j$=(e,t)=>{let r=t.readFile(ve.join(e,"package.json"));try{let n=r===null?null:Ee.object({version:Ee.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},F$=e=>{let t=Number.parseInt(e.readFile(ve.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},L$=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},B$=(e,t,r)=>{let n=F$(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(L$(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ve.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},U$=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:zn(await t.repoRoot()??r,e,t.realpath)},Cr=e=>({state:"drifted",row:e}),W$=async(e,t,r)=>{let n=jt(r.bin,r);if(!r.exists(e))return Cr({name:Qt,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=ve.join(Sc(r.home),"dist","cli.js");if(t!==o)return Cr(rs(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Zs(r.home,r.exists)===null)return Cr({name:Qt,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(Sc(r.home));if(await U$(s,r))return Cr({name:Qt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=V$(e,n,r);if(i!==null)return i;let a=j$(s,r),c=B$(s,a,r);return c!==null?{state:"converged",row:rs(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${x$(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Qt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},V$=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Cr(rs(`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:Cr(rs(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),vv=async e=>{let t=hv(e.platform);if(t===null)return{state:"absent",row:{name:Qt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Qt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=gh(e.platform,r)??[];return n===void 0||o===void 0?Cr(rs(`could not parse ${t} \u2014 re-run \`${jt(e.bin,e)}\` to rewrite it.`)):W$(n,o,e)},wv=async(e,t)=>{let{seams:r}=yv(e,t);return{state:(await vv(r)).state,stableNode:r.stableNode}},G$=()=>[ns,Qt,gv(),"portless CA chain valid","portless CA trusted","portless routes"],J$=async(e={})=>{let t=e.resolveBin??_m,r=e.isProxyServing??Bm,n=e.handshake??Gm,o=e.caTrusted??Vm,s=e.routes??Zn,i=e.isListening??Xn,a=(e.caPath??Wm)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...G$().map(E=>({name:E,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=yv(e,c),m=s(),f=await R$(r,c,u),y=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await S$(n,m,a,c,u);return[l,p,(await vv(u)).row,f,y,E$(o(),a,c),await P$(m,i,c)]},K$=async(e={})=>{let t="portless routes",r=e.routes??Zn,n=e.isListening??Xn,o=e.devSessionRunning??uh,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}=lh(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??Jm().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},ua=async(e={})=>{let t=await VC(),r=FC(e.probeDeps??qo()),n=async(m,f)=>{let[y,E]=await Promise.all([f,r]),k=E.get(m);return k===void 0?y:{...y,detail:k}},o=await Promise.all([n("brew",It("brew installed",He("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",It("git installed",He("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",It("gh installed",He("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),It("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",It("doppler installed",He("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",It("aws installed",He("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")),It("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),It("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"),LC(),Promise.resolve(BC()),Promise.resolve(UC()),WC(),Promise.resolve(GC(t)),zC(),qC(t),XC(e.fix??!1),QC(),e$()]),s=await J$(e.portlessDeps);if(e.fix){let m=await K$(),f=s.findIndex(y=>y.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await o$(),a=await Uo(),c={projectDir:ht.env.CLAUDE_PROJECT_DIR||null,cwd:ht.cwd(),gitRoot:a},l=[await l$(),...m$(i,c),Wo(),h$({env:ht.env,stdinIsTTY:ht.stdin.isTTY===!0,flag:j.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:v$(a)],u=[...o,await k$(a),...s,...await n$(),...l,f$(Sn(),L.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Kl.has(m.name),detail:m.detail})),allPassed:MC(u),cliVersion:L.version};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}},Ku=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:Ee.array(Ee.object({name:Ee.string().describe("Name of the check"),status:Ee.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:Ee.string().describe("Details about the check result"),fixable:Ee.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Ee.object({manager:Ee.string().describe("Which package manager owns this install, read from its resolved path"),version:Ee.string().nullable().describe("The version the tool reported, or null"),present:Ee.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Ee.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:Ee.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Ee.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>ua()});import{E2E_MODE_ENV as wA}from"@slip-stream-kit/config/internal";import ed from"node:fs";import kA from"node:os";import ss from"node:path";import ma from"node:process";import{z as P}from"zod";var yt=(e,t,r)=>new O({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as H$,loadDev as q$,readAppAliasName as Y$,readCloudOrigin as z$,readLocalContext as bv}from"@slip-stream-kit/config/internal";import kv from"node:fs";import $r from"node:path";import da from"node:process";import{z as Hu}from"zod";var X$=async e=>{let t=$r.join(e,"apps"),r=kv.existsSync(t)?kv.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=$r.join(t,o,"tests"),a=(await lt(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},Z$=(e,t)=>{let[r,n]=$r.relative(e,t).split($r.sep);return r==="apps"&&n?n:void 0},Q$=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(Z$(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 O({status:"argument_required",argument:a,choices:Hu.toJSONSchema(Hu.object({app:Hu.enum(i)})),agentMode:j.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(", ")}`})},eA=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}})),tA=e=>To(e).apps.find(t=>t.env!=="")?.env??null,qu=async(e,t={})=>{let r=t.cwd??da.cwd(),n=t.projectRoot??await $(),o=(t.env??da.env)[Lr]||null,s=t.healthProbe??jc,i=Q$(await X$(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=$r.join(n,"apps",c,l),p=(await fr(u)).name,m=(await lt(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${$r.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Kf(u),y=Y$(p,u),E=`${y}.localhost`,k=`https://${E}`,A=0;if(l==="ui")A=(t.listRoutes??Zn)().find(R=>R.name===E||R.name===y)?.port??0;else{let R=bv(u).info.get(p);A=R?.port??0,k=R?.origin??k}let M=A>0&&await s({tag:a,port:A,kind:l})==="ok",v=M?tA(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:v,localUrl:k,served:M}},Rv=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}},Yu=async(e,t={})=>{let r=t.healthProbe??jc,n=bv(e.targetDir),o=e.kind==="ui"?await q$(e.targetDir):void 0,s=o?.proxy?H$({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:z$(e.deployedUrlEnv??void 0,t.env??da.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...Rv(e),mode:"local",baseUrl:e.localUrl,routes:await eA(s,i,r)}},zu=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw yt("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${$r.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??da.env)[n];if(!r||!s){let i=s?Lr:n;throw yt("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 ${Lr}, and ${i} is not set`})}return{...Rv(e),mode:"cloud",baseUrl:s,routes:[]}};import rA from"node:fs";import nA from"node:path";import{stripVTControlCharacters as oA}from"node:util";import{z as I}from"zod";var Sv=2e3,Ev="--reporter=line,json",Pv=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),xv=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Xu=I.object({message:I.string().optional()}),Tv=I.object({type:I.string()}),sA=I.object({status:I.string(),retry:I.number(),error:Xu.optional(),errors:I.array(Xu).optional(),annotations:I.array(Tv).optional(),attachments:I.array(I.object({name:I.string(),path:I.string().optional()})).optional()}),iA=I.object({projectName:I.string(),status:I.string(),expectedStatus:I.string().optional(),annotations:I.array(Tv).optional(),results:I.array(sA)}),aA=I.object({title:I.string(),file:I.string(),line:I.number().optional(),tests:I.array(iA)}),Cv=I.lazy(()=>I.object({title:I.string(),specs:I.array(aA).optional(),suites:I.array(Cv).optional()})),cA=I.object({config:I.object({rootDir:I.string().optional()}).optional(),suites:I.array(Cv),errors:I.array(Xu).optional(),stats:I.object({expected:I.number(),unexpected:I.number(),flaky:I.number(),skipped:I.number()})}),$v=e=>{let t=oA(e);return t.length>Sv?`${t.slice(0,Sv)}\u2026`:t},lA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:$v(t)},uA=e=>e.status==="unexpected"||e.status==="flaky",dA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},pA=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),mA=(e,t)=>{let r=e.filter(uA),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?lA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},fA=e=>{let t=cA.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(k=>[...pA(k)])),y=m.some(k=>k.expectedStatus==="failed");if(!y&&!f.has("fixme")&&!f.has("skip"))return;let E=a.get(p)??{file:p,fail:0,fixme:0,skip:0};y&&(E.fail+=1),f.has("fixme")?E.fixme+=1:f.has("skip")&&(E.skip+=1),a.set(p,E)},u=(p,m)=>{for(let f of p.specs??[]){let y=r?.rootDir?nA.resolve(r.rootDir,f.file):f.file,E=[...m,f.title].join(" \u203A ");l(y,f.tests);for(let[k,A]of dA(f.tests)){let M=mA(A,{title:E,file:y,line:f.line??null,project:k});M&&(M.runs>1&&M.failedRuns<M.runs&&(c+=1),i.push(M))}}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?[]:[$v(p.message)])}},Av=e=>{try{return fA(JSON.parse(rA.readFileSync(e,"utf8")))}catch{return null}};import os from"node:fs";import Dv from"node:path";import pa from"node:process";var gA=e=>Dv.join(e,"node_modules",".cache","infra-kit-e2e.lock"),hA=e=>{try{return pa.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Ov=e=>{try{return os.writeFileSync(e,String(pa.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},Zu=e=>{try{let t=Number.parseInt(os.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},Iv=e=>{let t=gA(e);if(os.mkdirSync(Dv.dirname(t),{recursive:!0}),!Ov(t)){let r=Zu(t);if(r!==null&&r!==pa.pid&&hA(r))return{holder:r};if(os.rmSync(t,{force:!0}),!Ov(t))return{holder:Zu(t)??0}}return{release:()=>{Zu(t)===pa.pid&&os.rmSync(t,{force:!0})}}};import{spawn as yA}from"node:child_process";import vA from"node:os";import Qu from"node:process";var Nv=(e,t,r)=>new Promise((n,o)=>{let s=yA(e,t,r),i=Qu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Qu.off(l,a)};for(let l of i)Qu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+vA.constants.signals[u]:1))})});var bA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],RA=e=>bA.some(t=>{try{return ed.readFileSync(ss.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),td=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,SA=(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(`
|
|
374
|
+
`)},EA=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 yt("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(", ")}`})},PA=async(e,t)=>{if(e.env===null||!Gf(e.env))return;let r=await(t.protectedEnvAccess??it)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?yt("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`}):yt("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`})},xA=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw yt("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"}"`})},TA=async(e,t)=>{if(e.served){xA(e);let p=await Yu(e,t);return EA(p),p}if(!RA(e.testsDir))throw yt("no_dev_server",{devCommand:td(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${td(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:[]}},CA=(e,t,r)=>Nv("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...ma.env,...r,[wA]:e.mode},stdio:["inherit",lr.enabled||X()?2:"inherit","inherit"]}),$A=(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:ss.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=ss.join(e.testsDir,"test-results",`ik-e2e-${n}-${ma.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},AA=e=>{if(e.mode==="cloud")return()=>{};let t=Iv(e.testsDir);if("holder"in t)throw yt("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},fa=async(e,t={})=>{let r=await qu(e.app,t),n=e.cloud?zu(r,t):await TA(r,t);d.info(SA(n,r.served)),n.mode==="cloud"&&await PA(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?td(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return nd({...o,ran:!1,exitCode:null,...rd});n.mode==="cloud"&&await J(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=AA(n);try{return await OA(o,t.runPlaywright??CA)}finally{s()}},OA=async(e,t)=>{if(!X()||xv(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(ma.exitCode=i),nd({...e,ran:!0,exitCode:i,...rd,report:X()?"caller-reporter":"off"})}let{args:r,outputDir:n}=$A(e,e.playwrightArgs),o=ed.mkdtempSync(ss.join(kA.tmpdir(),"ik-e2e-report-")),s=ss.join(o,"report.json");try{let i=await t(e,[Ev,...r],Pv(s));i!==0&&(ma.exitCode=i);let a=Av(s);return nd({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...rd,report:"unavailable"},outputDir:n})}finally{ed.rmSync(o,{recursive:!0,force:!0})}},rd={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},nd=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),DA={app:P.string(),testsDir:P.string(),target:P.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:P.string(),mode:P.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:P.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:P.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:P.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:P.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:P.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:P.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:P.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:P.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:P.array(P.object({path:P.string(),packageName:P.string(),source:P.enum(["local","cloud"]),target:P.string().nullable(),live:P.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:P.array(P.string()),ran:P.boolean().describe("False for --dry-run."),exitCode:P.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:P.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:P.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:P.object({expected:P.number(),unexpected:P.number(),flaky:P.number(),skipped:P.number(),repeatFlaky:P.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:P.array(P.object({title:P.string().describe("Describe path and test title, joined with \u203A."),file:P.string(),line:P.number().nullable(),project:P.string(),status:P.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:P.number().describe("The retry index of the failed attempt reported here."),runs:P.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:P.number().describe("How many of those runs failed."),error:P.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:P.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:P.array(P.object({file:P.string(),fail:P.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:P.number().describe("test.fixme \u2014 skipped as unfinished."),skip:P.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:P.array(P.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.")},od=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:P.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:P.boolean().optional(),yes:P.boolean().optional(),cloud:P.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:P.array(P.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:DA,handler:e=>fa(e)});import ga from"node:fs";import sd from"node:path";import{z as is}from"zod";var IA=e=>[...e.map(t=>`unset ${t}`),`unset ${Lr}`,`unset ${Ks}`,`unset ${Hs}`,`unset ${Pm}`,`unset ${qs}`],ha=async()=>{let e=Br(),t=sd.join(e,Fr);if(!ga.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Ys(t),n=IA(r),o=sd.resolve(e,Gs);ga.mkdirSync(e,{recursive:!0,mode:448}),Mt(o,`${n.join(`
|
|
375
375
|
`)}
|
|
376
|
-
`,384),
|
|
376
|
+
`,384),ga.rmSync(t,{force:!0}),ga.rmSync(sd.join(e,Js),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}},id=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:is.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:is.string().describe("Path to the file that must be sourced to apply"),variableCount:is.number().describe("Number of variables cleared"),unsetStatements:is.array(is.string()).describe("Unset statements generated")},handler:()=>ha()});import NA from"node:path";import as from"node:process";import{z as Mn}from"zod";var ya=async()=>{d.info("Environment session status:");let e=Br(),t=as.env[Yn],r=NA.join(e,Fr),n=0,o=0,s=as.env[Ks]??null,i=as.env[Hs]??null,a=as.env[qs]??null;if(s){let l=Ys(r);l.length>0&&(o=l.length,n=l.filter(p=>p in as.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})
|
|
377
377
|
`),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
|
|
378
|
-
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:b(JSON.stringify(c,null,2)),structuredContent:c}},
|
|
379
|
-
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:b(JSON.stringify(i,null,2)),structuredContent:i}},
|
|
380
|
-
\u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${
|
|
381
|
-
\u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let
|
|
382
|
-
`)[0]??""}`);let E=await
|
|
383
|
-
\u2B06\uFE0F Pushing atomically: ${l.map(
|
|
384
|
-
`)[0],observedLanded:f.map(
|
|
385
|
-
`)[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=>!
|
|
386
|
-
\u2139\uFE0F This will push ${k} branch(es), re-running CI on ${k} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await
|
|
378
|
+
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:b(JSON.stringify(c,null,2)),structuredContent:c}},ad=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:Mn.string().describe("Current terminal session ID"),sessionLoadedCount:Mn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Mn.number().describe("Total number of cached var names"),sessionConfig:Mn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Mn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Mn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:ya});import _A from"node:process";import{z as er}from"zod";var _v="****",$e=e=>typeof e!="string"||e.length<8?_v:`${_v}${e.slice(-4)}`;var Mv=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${pr}`:"store",redactedToken:$e(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),MA=["ENV","SOURCE","TOKEN","PRESENT"],jv=(e,t)=>{let r=[...MA,...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())},va=async({check:e}={})=>{let t=await di(),r=await Qe(),n=_A.env[pr],o=Mv(t,r?.envs??{},n);if(e){let a=await dr();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await If({childEnv:so(l),project:a,config:c.env});c.status=u.outcome}}for(let a of jv(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
|
|
379
|
+
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:b(JSON.stringify(i,null,2)),structuredContent:i}},cd=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:er.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:er.array(er.object({env:er.string().describe("Environment / Doppler config name"),source:er.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:er.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:er.boolean().describe("Whether a token is configured for this environment"),status:er.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:va});import{z as x}from"zod";import{$ as jA}from"zx";var FA=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),LA=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,BA=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(", ")},ud=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),ld=new Set(["up-to-date","fast-forward","merged"]),UA=(e,t,r)=>{let n=(Array.isArray(e)?e:e.split(",")).map(a=>a.trim()).filter(a=>a.length>0),o=new Set(t),s=new Map(r.map(a=>[a.branch,a.reason])),i=new Set;for(let a of n){let c;try{c=Te(ke(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))},WA={"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"},Lv=e=>{let t=WA[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},VA=(e,t)=>{d.info(`
|
|
380
|
+
\u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${Lv(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},GA=(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`},JA=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;h.setInteractive();let s=new Map(t.flatMap(i=>{let a=Q(i.branch);return a?[[le(a),Lv(i)]]:[]}));return Yt(fe({branches:r,descriptions:s}),{required:!0})},KA=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(y=>o.includes(y.branch)),a=y=>{for(let E of y)d.info(`\u2139\uFE0F ${E} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await Fo(t,Ah(i));a(c.nowUpToDate);let l=c.kept,u=new Map;if(s&&l.length>0){d.info(`
|
|
381
|
+
\u{1F50E} Verifying ${l.length} merge(s) with: ${s}`);let y=await Dh({worktreePath:r,refs:l,command:s});u=y.failed;for(let[k,A]of y.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${A.split(`
|
|
382
|
+
`)[0]??""}`);let E=await Fo(t,y.kept);a(E.nowUpToDate),l=E.kept}if(l.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:u};d.info(`
|
|
383
|
+
\u2B06\uFE0F Pushing atomically: ${l.map(y=>y.branch).join(", ")}`);let p=await oi(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let f=(await Promise.all(l.map(async y=>({branch:y.branch,landed:await Gr(t,y.branch)===y.sha})))).filter(y=>y.landed);return f.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${f.map(y=>y.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:u,abortedBy:p.stderr?.split(`
|
|
384
|
+
`)[0],observedLanded:f.map(y=>y.branch)}},HA=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"})},Fv=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
|
|
385
|
+
`)[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=>!ld.has(i.status));return ud({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},qA=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Ae();if(e.abort)return Fv(await oy({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Fv(await ry({cwd:s,versions:r,all:t,verify:i,trees:ny(e.tree),confirmedCommand:o}))},wa=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;HA(e);let a=o===!0?Oh:o||void 0;if(await ql({operation:"merge dev into release branches"}),e.continue||e.abort)return qA(e);let c=[],l=[];for(let S of await G()){let B=LA(S);B?l.push({branch:S.branch,reason:B}):c.push(S.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 (${BA(l)})`),h.print(),ud(FA(n,l));let u=await Ae();try{await jA({cwd:u,quiet:!0})`git fetch origin --prune`}catch(S){throw new g(S,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:UA(r,c,l),m=await uf({cwd:u},async S=>{let B=Ji(S.remove);try{return await YA({cwd:u,worktree:S,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{B()}}),{entries:f,selected:y,pushed:E,pushAborted:k,abortedBy:A,declined:M,verifyFailed:v,handOffs:R}=m,T=await st(u).catch(()=>[]);return QA({entries:f,selected:y,pushed:E,pushAborted:k,abortedBy:A,declined:M,verifyFailed:v,handOffs:R,dryRun:n,worktrees:T,skipped:l})},YA=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 Ce(t,"origin/dev"):null,f=await $h({cwd:t,worktreePath:r.path,branches:n}),y={entries:f,pushed:!1,pushAborted:!1,declined:!1};if(VA(f,s),c)return{...y,selected:n};let E=await JA({entries:f,toPlan:n,all:i,explicit:a!==void 0});E.length===o.length?h.addOption("--all",!0):h.addOption("--versions",E);let k=f.filter(S=>E.includes(S.branch)&&S.mergeSha).length;k>0&&d.info(`
|
|
386
|
+
\u2139\uFE0F This will push ${k} branch(es), re-running CI on ${k} open PR(s). If the repo dismisses stale approvals on new commits, those PRs lose them.`);try{await J(p,`Are you sure you want to merge dev into these branches: ${E.join(", ")}?`,{throwOnDecline:!0,plan:zA(f,E,s)})}catch(S){if(!Et(S))throw S;return{...y,selected:E,declined:!0}}p||h.addOption("--yes",!0);let A=await KA({cwd:t,worktreePath:r.path,entries:f,selected:E,verify:l}),M=S=>f.filter(B=>E.includes(B.branch)&&S(B)).map(B=>B.branch),v=M(S=>S.status==="conflict"),R=M(S=>S.status==="merged"&&(A.verifyFailed?.has(S.branch)??!1)),T=u&&m&&v.length+R.length>0?await Qh({cwd:t,conflicted:v,verifyFailed:R,devSha:m,verify:l}):void 0;return{entries:f,selected:E,declined:!1,...A,handOffs:T}},zA=(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:uu(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),XA=(e,t)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
|
|
387
387
|
`:`# ${e.branch} \u2014 ${e.status}
|
|
388
|
-
${
|
|
389
|
-
`,
|
|
390
|
-
hand-off: ${t}`:e??t,
|
|
388
|
+
${GA(e.branch,t)}
|
|
389
|
+
`,ZA=(e,t)=>e!==void 0&&t?`${e}
|
|
390
|
+
hand-off: ${t}`:e??t,QA=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(k=>r.includes(k.branch)&&k.mergeSha&&!l?.has(k.branch)).map(k=>k.branch):[]),f=t.filter(k=>r.includes(k.branch)).map(k=>{let A=!!k.mergeSha,M=l?.has(k.branch)??!1,v=l?.get(k.branch),R=o&&A?"push-aborted":k.status,T=M?"verify-failed":R,S=u?.get(k.branch);return{branch:k.branch,status:T,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:m.has(k.branch),reason:ZA(v,S?.reason)??k.reason,...S?.resolution?{resolution:S.resolution}:{}}}),y=f.filter(k=>!ld.has(k.status));for(let k of f){let A=t.find(M=>M.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:A?.durationMs,pushed:k.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
|
|
391
391
|
Operation cancelled \u2014 nothing was pushed.
|
|
392
392
|
`:`
|
|
393
393
|
\u{1F50D} Dry run \u2014 nothing was pushed.
|
|
394
|
-
`);else if(
|
|
395
|
-
\u26A0\uFE0F ${
|
|
396
|
-
`);for(let k of
|
|
397
|
-
`);
|
|
398
|
-
`).filter(r=>r.trim().length>0)}catch{return[]}},
|
|
399
|
-
`);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},
|
|
400
|
-
${
|
|
394
|
+
`);else if(y.length>0){d.info(`
|
|
395
|
+
\u26A0\uFE0F ${y.length} branch(es) did not merge.
|
|
396
|
+
`);for(let k of y)d.info(XA(k,c))}else d.info(`\u2705 All merges completed successfully!
|
|
397
|
+
`);h.print();let E=a||i;return ud({successfulMerges:E?0:f.filter(k=>ld.has(k.status)).length,failedMerges:E?0:y.length,failedBranches:E?[]:y.map(k=>k.branch),totalBranches:f.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:f.map(k=>E?{...k,pushed:!1}:k),skipped:p})},dd=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 \u2014 and each clean merge that failed `verify` \u2014 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()),editablePaths:x.array(x.string()).optional(),lockfileOnly:x.boolean(),rererePreResolved:x.array(x.string()),state:x.enum(["needs-agent","lockfile-only","verify-failed","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch, or for a clean merge that failed verify (`verify-failed`: edit only `editablePaths`)"),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:wa});import{z as fs}from"zod";import{$ as qe}from"zx";var Bv=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Ar=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=Bv(t.stderr,500);o&&(r.stderr=o);let s=Bv(t.stdout,200);return s&&(r.stdout=s),r};var cs=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 ls=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=b(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 he()?new O({status:"partial_failure",...n},1,s):new g(void 0,s)};import ka from"node:fs/promises";import{$ as md}from"zx";var eO=new Set([".omc",".DS_Store"]),tO=new Set(["state","sessions"]),rO=2e3,Gv="check 'git worktree list' for the path; uncommitted changes block removal",nO=e=>new Promise(t=>{setTimeout(t,e)}),pd=e=>typeof e=="object"&&e!==null?e.code:void 0,Uv=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Wv=async e=>{try{return Uv(await ka.realpath(e))}catch{return Uv(e)}},oO=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await st(t),o=await Wv(r);for(let s of n)if(await Wv(s.path)===o)return!0;return!1}catch{return!0}},sO=async e=>{let t;try{t=await ka.readdir(e)}catch(n){return{kind:pd(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>eO.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await ka.readdir(`${e}/.omc`)).every(s=>tO.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:pd(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Vv=async e=>{try{return await ka.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return pd(t)==="ENOTEMPTY"?"busy":"failed"}},iO=async e=>{let{worktreePath:t,sleep:r}=e,n=await Vv(t);return n!=="busy"?n==="removed":(await r(rO),await Vv(t)==="removed")},us=(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}},aO=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await oO({projectRoot:n,worktreePath:r}))return us(t,o,Gv);let i=await sO(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 iO({worktreePath:r,sleep:s})?us(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"})},cO=async e=>{try{return(await md`git -C ${e} status --porcelain`).stdout.split(`
|
|
398
|
+
`).filter(r=>r.trim().length>0)}catch{return[]}},lO=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await cO(i);if(a.length>0)return us(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),Gv);let c=await jf(i,o);if(!c.closed&&"error"in c)return us(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await md`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return aO({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},Or=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=nO}=e,i=t.length>0?await Wt():"unreachable",a=await Promise.all(t.map(l=>lO({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 md`git worktree prune`,c};var ds=async(e,t)=>{if(!(await be("release")).includes(e))return[];let n=await $(),o=`${n}${ge}`,{removed:s,failed:i}=await Or({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};import{$ as fd}from"zx";var ps=async(e,t)=>{let r=await fd({quiet:!0,nothrow:!0})`git merge-tree --write-tree --name-only --no-messages ${e} ${t}`;if(r.exitCode!==0&&r.exitCode!==1)throw new g(new Error(r.stderr),{operation:`rehearse merging ${t} into ${e}`,remediation:"git merge-tree --write-tree needs git >= 2.38; check `git --version` and that both refs exist"});let[n="",...o]=r.stdout.trim().split(`
|
|
399
|
+
`);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},Jv=async(e,t)=>(await fd({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),ms=(e,t)=>{if(t.conflicts.length!==0)throw new g(void 0,{operation:`deliver: ${e} would conflict`,remediation:`resolve the conflicts in ${t.conflicts.join(", ")}, push, then re-run`})},Kv=async e=>{let{releaseBranch:t,releaseType:r,releaseMerged:n,rcMerged:o}=e,s=`origin/${t}`;if(await fd({quiet:!0})`git fetch origin main dev ${n?[]:[t]}`,r==="hotfix"){let a="origin/main";if(!n){let c=await ps("origin/main",s);ms(`merging ${t} into main`,c),a=await Jv(c.tree,"origin/main")}ms("syncing main back into dev",await ps("origin/dev",a));return}let i="origin/dev";if(!n){let a=await ps("origin/dev",s);ms(`merging ${t} into dev`,a),i=await Jv(a.tree,"origin/dev")}o?ms("syncing main back into dev",await ps(i,"origin/main")):ms("merging dev into main (RC PR)",await ps("origin/main",i))};var jn=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:Ar(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},qv=async e=>{let t=Ec(e),r=await qe`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},Hv=async()=>{let e=await qe`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},uO=async e=>{let t=Ot(e),r=await Xl(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 ln(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=Do(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}},dO=async()=>{let e=await G(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));h.setInteractive();let n=await me(),o=await qt(fe({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}},pO=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=mt(r),s=await Bi(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 jn(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await qe`gh pr merge ${n} --squash --admin --delete-branch`})},mO=async e=>{let t=ne(e),r=Ec(e),n=await Hv();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 jn(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await qe`gh pr edit ${s} --title ${r}`})),s}await jn(`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 qe`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Hv();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},fO=async e=>{let t=ne(e);if(await qv(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await mO(e);await jn(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await qe`gh pr merge ${n} --squash --admin`})},gO=async()=>{qe.quiet=!1,await jn("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await qe`gh workflow run deploy-all.yml --ref main -f environment=prod`}),qe.quiet=!0},hO=async()=>{await jn("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 qe`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},yO=async e=>{try{await ri(e)}catch(t){d.warn({err:Ar(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ni(e)}catch(t){d.warn({err:Ar(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},vO=async e=>{let t=await At();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=le(e);await Ql({versionName:r},t)}catch(r){let n=No(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:Ar(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},ba=async e=>{let{version:t,confirmedCommand:r}=e;await _e({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await uO(t):await dO(),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=ne(i);if(h.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),he())throw new O({status:"refused",agentMode:j.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 Kv({releaseBranch:n,releaseType:o,releaseMerged:(await Bi(s)).state==="MERGED",rcMerged:o!=="hotfix"&&await qv(i)!==null}),await J(r,`Are you sure you want to deliver version ${n} to production?`),h.addOption("--yes",!0),qe.quiet=!0;let l=`${await $()}${ge}`;await ds(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await pO({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await fO(i),await gO(),await hO(),await yO(n),qe.quiet=!1,await vO(i),d.info(`Successfully delivered ${n} to production!`),h.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}},gd=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:fs.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:fs.string().describe("The release branch that was delivered"),version:fs.string().describe("The version that was delivered"),type:fs.enum(["regular","hotfix"]).describe("Release type"),success:fs.boolean().describe("Whether the delivery was successful")},handler:ba});import{z as Nt}from"zod";import{$ as Ad}from"zx";import{z as ws}from"zod";import sw from"node:fs/promises";import Rd from"node:path";import{DEPLOY_CONFIG_FILE as Ra,deployConfigSchema as wO}from"@slip-stream-kit/config/internal";import kO from"node:fs/promises";import bO from"node:path";import{pathToFileURL as RO}from"node:url";import{z as SO}from"zod";var vt=async e=>{let t=bO.join(e,Ra);try{await kO.access(t)}catch{return}let r=await import(RO(t).href);if(r.default===void 0)throw new Error(`${Ra} at ${t} has no default export`);let n=wO.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${Ra} at ${t}:
|
|
400
|
+
${SO.prettifyError(n.error)}`);let o=[...PO(n.data),...EO(n.data)];if(o.length>0)throw new Error(`Invalid ${Ra} at ${t}:
|
|
401
401
|
${o.join(`
|
|
402
|
-
`)}`);return n.data},
|
|
402
|
+
`)}`);return n.data},EO=e=>e.replaceV1!==!0?[]:Mc.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),PO=e=>{let t=new Set([...e.environments,...Mc]);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 gs=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 Zv="b16ab9c88dc04a2237481f439da5e489ffda7844",Qv=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${Zv}`,xO=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${Zv}`,Ea="install-deps",Yv=25,Fn="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",Pa="skip_terraform_deploy",ew={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"}}},tw=(e,t)=>ew[e.replaceV1===!0?"v1":"pilot"][t],rw=e=>Object.values(ew[e]).map(({file:t})=>`.github/workflows/${t}`),yd=rw("pilot"),vd=rw("v1"),Sa=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),TO=(e,t)=>Object.entries(e.services).flatMap(([r,n])=>{if(t==="all"&&n.deployAll===!1)return[];let o=t==="all"&&Array.isArray(n.deployAll)?n.deployAll:void 0,s=e.environments.filter(i=>(n.envs?.includes(i)??!0)&&!(n.skipEnvs?.includes(i)??!1)&&(o?.includes(i)??!0));return s.length===0?[]:[{name:r,service:n,gate:s.length===e.environments.length?void 0:s}]}),Y=e=>`\${{ ${e} }}`,hd=e=>Y(`secrets[format('{0}_${e}', inputs.environment)]`),CO=e=>[Ea,...e.terraform,...e.preDeploy],nw=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),$O=e=>[`needs.${Ea}.result == 'success'`,...nw(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],AO=(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()",...$O(r)),Y(n.join(" && "))},wd=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],ow=e=>e===void 0?[]:[` if: ${e}`],kd=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${Y("github.ref")}`,` environment: ${Y("inputs.environment")}`," secrets: inherit"],OO=(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=Y(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${Qv}`," with:",` environment: ${Y("inputs.environment")}`,` ref: ${Y("github.ref")}`,` sha: ${Y("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${L.version}`,...n,...o," secrets:",` aws-access-key-id: ${hd("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${hd("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${hd("AWS_REGION")}`,` serverless-access-key: ${Y("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${Y("secrets.SLACK_TOKEN")}`,` slack-channel: ${Y("secrets.SLACK_CHANNEL")}`,...s]},DO=(e,t,r,n)=>{let o=e.service.workflow===void 0?OO(e,n):kd(e.service.workflow);return["",` deploy-${e.name}:`,...wd(CO(r)),...ow(AO(e,t,r)),...o]},zv=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],IO=(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?zv(Pa,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return zv(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},NO=e=>e.map(t=>Y(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),_O=(e,t,r)=>{let{title:n,concurrency:o}=tw(e,t),s=(e.terraform??[]).length>0?Y(`inputs.${Pa} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${NO(r)}`:"";return[`${Fn}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${Y("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}-${Y("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},MO=e=>{let t=Y(`!inputs.${Pa}`);return["",` ${Sa(e)}:`,` if: ${t}`,...kd(e)]},jO=(e,t)=>{let r=t.length===0?void 0:Y(["!cancelled()",...nw(t)].join(" && "));return["",` ${Sa(e)}:`,...wd(t),...ow(r),...kd(e)]},FO=()=>["",` ${Ea}:`,` uses: ${xO}`," with:",` ref: ${Y("github.ref")}`,` sha: ${Y("github.sha")}`," secrets:",` slack-token: ${Y("secrets.SLACK_TOKEN")}`,` slack-channel: ${Y("secrets.SLACK_CHANNEL")}`],LO=(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)}},BO=(e,t)=>[""," notify-success:",...wd(t),` if: ${Y("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],Xv=(e,t)=>{let r=TO(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(Sa),preDeploy:o.map(Sa)},{file:i}=tw(e,t),a=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(a>Yv){let p=n.length>0?`environment, ${Pa}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${p} and one checkbox per service); GitHub allows ${Yv}. Fold services that always deploy together into one deploy script.`)}let c=r.map(p=>`deploy-${p.name}`);LO([Ea,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let u=`${[..._O(e,t,r),...IO(e,t,r),"","permissions:"," contents: read","","jobs:",...FO(),...n.flatMap(MO),...o.flatMap(p=>jO(p,s.terraform)),...r.flatMap(p=>DO(p,t,s,e)),...e.notifySuccess===void 0?[]:BO(e.notifySuccess,c)].join(`
|
|
403
403
|
`).replace(`jobs:
|
|
404
404
|
|
|
405
405
|
`,`jobs:
|
|
406
406
|
`)}
|
|
407
|
-
`;return{path:`.github/workflows/${i}`,content:u}},wd=e=>[Yv(e,"all"),Yv(e,"selected")];var ow=".github/workflows",jO=/script_name:\s*(?<service>[a-z0-9-]+)/,FO=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,LO=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,bd=async e=>{let t=kd.resolve(e,ow),r;try{r=await nw.readdir(t)}catch{return new Map}return sw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},fs=async(e,t)=>sw(e,[t]),sw=async(e,t)=>{let r=kd.resolve(e,ow),n=new Map,o=!1;for(let s of t){let i;try{i=await nw.readFile(kd.resolve(r,s),"utf-8")}catch{continue}i.startsWith(Mn)?o=!0:UO(i,n)}return o&&iw(n,await BO(e)),n},BO=async e=>{try{let t=await Ot(e);return t?.replaceV1===!0?ms(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},iw=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},UO=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=jO.exec(r)?.groups?.service??FO.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(LO)].map(s=>s.groups?.env??"");o.length!==0&&iw(t,new Map([[n,o]]))}},gs=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import WO from"node:fs/promises";import VO from"node:path";import GO from"yaml";var JO=".github/workflows",KO="skip_terraform_deploy",hs=async(e,t)=>{let r=VO.resolve(e,JO,t),n;try{n=GO.parse(await WO.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!==KO).map(([i])=>i)};var aw="dev",Rd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cw=(e,t)=>e[t]===void 0,lw=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Sd=async e=>{try{return await e}catch{return[]}},HO=async()=>{let e=await V();return $t(e.map(t=>t.branch))},qO=(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},Ar=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 Sd(HO());if(l.length===0)return null;let u=lw(c,"version");return ys.enum([...new Set([...l,aw])]).optional().describe(`Which release to deploy from. "${aw}" 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=Ut(await Sd(Wt(t)),await st());if(l.length===0)return null;let u=l.filter(ro),p=l.filter(f=>!ro(f)),m=lw(c,"env");return ys.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 A(),l=await Sd(hs(c,t));if(l.length===0)return null;let u=await fs(c,t);return ys.array(ys.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${qO(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=>Rd(c)?r.some(l=>cw(c,l)):!1,buildRequestedSchema:async c=>{let l=Rd(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")&&cw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):ys.object(u)},toArgs:(c,l)=>{let u={...Rd(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 YO from"@inquirer/select";var jn=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 _(r=>YO({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import zO from"@inquirer/confirm";var vs=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;Z()&&ii(o,{branch:r,env:n}),y.setInteractive();let s=await _(i=>zO({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import XO from"@inquirer/select";import ZO from"node:process";var Ed=()=>!Z()&&ZO.stdin.isTTY===!0,QO={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Pd=async()=>_(e=>XO({message:"\u{1F680} Where should this deploy run?",choices:Qt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:QO[t]}))},e),{whenHeadless:"refuse"});var Qt=["ci","local"],eD={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},uw=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Qt.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw Z()?new O({status:"argument_required",argument:"from",agentMode:j.source},2,r):new g(void 0,r)}let t=Qt.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Qt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},xd=(e,t)=>{let n=eD[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}`})},Td=async e=>e||!Ed()?uw(e):Pd();var ws=async e=>{if(e)return e==="dev"?"dev":Ct(e);y.setInteractive();let t=await V(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await pe();return Kt([{value:"dev",label:"dev"},...me({branches:r,descriptions:o,types:n})])};var dw="deploy-all.yml",pw=Ar({workflowFile:dw,fields:["version","env"],toolName:"gh-release-deploy-all"}),Ea=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await it({provider:pw,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await ws(t),i=_o(s);y.addOption("--version",i);let a=await st(),c=Ut(await Wt(dw),a),l="";r?l=r:(y.setInteractive(),l=await jn(c,"launch deploy-all workflow")),y.addOption("--env",l),Gr(l,"launch deploy-all workflow",a),ci({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await vs({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}}try{Cd.quiet=!0,await Cd`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Cd.quiet=!1,d.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),y.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!0};return{content:b(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"})}},$d=C({name:"gh-release-deploy-all",formProvider:pw,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:Dt.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:Dt.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:Dt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Dt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Dt.string().describe("The release branch that was deployed"),version:Dt.string().describe("The version that was deployed"),environment:Dt.string().describe("The environment deployed to"),skipTerraformDeploy:Dt.boolean().describe("Whether terraform deployment was skipped"),success:Dt.boolean().describe("Whether the deployment was successful")},handler:Ea});import tD from"@inquirer/checkbox";import{z as Me}from"zod";import{$ as Ad}from"zx";var Or="deploy-selected-services.yml",mw=Ar({workflowFile:Or,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Pa=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await it({provider:mw,params:e,operation:"launch deploy-selected workflow",argument:S=>S[0]??"version"});let i=await ws(t),a=_o(i);y.addOption("--version",a);let c=await st(),l=Ut(await Wt(Or),c),u="";r?u=r:(y.setInteractive(),u=await jn(l,"launch deploy-selected workflow")),y.addOption("--env",u),Gr(u,"launch deploy-selected workflow",c),ci({env:u,branch:i});let p=await A(),m=await hs(p,Or);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Or}`,stderrExcerpt:`no services found in .github/workflows/${Or}`});let f=[];if(n&&n.length>0?f=n:(y.setInteractive(),f=await _(S=>tD({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(P=>({name:P,value:P}))},S),{whenHeadless:"refuse"})),y.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 v=f.filter(S=>!m.includes(S));if(v.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${v.join(", ")}`});let E=await fs(p,Or),k=f.filter(S=>{let P=E.get(S);return P!==void 0&&!P.includes(u)});if(k.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:k.map(S=>`${S} deploys only to: ${(E.get(S)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Or} gates these services out of ${u}: ${k.join(", ")}`});let h=o??!1;h&&y.addOption("--skip-terraform",!0);let R=S=>{let P={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:h,success:S};return{content:b(JSON.stringify(P,null,2)),structuredContent:P}};if(!await vs({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),R(!1);try{Ad.quiet=!0;let S=f.flatMap(M=>["-f",`${M}=true`]);return await Ad`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${S} ${h?["-f","skip_terraform_deploy=true"]:[]}`,Ad.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),y.print(),R(!0)}catch(S){throw d.error({error:S},"\u274C Error launching workflow"),new g(S,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Od=C({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:mw,description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:Me.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:Me.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:Me.array(Me.string()).optional().describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:Me.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Me.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Me.string().describe("The release branch that was deployed"),version:Me.string().describe("The version that was deployed"),environment:Me.string().describe("The environment deployed to"),services:Me.array(Me.string()).describe("The services that were deployed"),skipTerraformDeploy:Me.boolean().describe("Whether terraform deployment was skipped"),success:Me.boolean().describe("Whether the deployment was successful")},handler:Pa});import{z as er}from"zod";var xa=async()=>{let t=(await V()).flatMap(i=>{let a=Q(i.branch);return a?[{version:re(a),jiraKey:ce(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Bi(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=No(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:
|
|
407
|
+
`;return{path:`.github/workflows/${i}`,content:u}},bd=e=>[Xv(e,"all"),Xv(e,"selected")];var iw=".github/workflows",UO=/script_name:\s*(?<service>[a-z0-9-]+)/,WO=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,VO=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,Sd=async e=>{let t=Rd.resolve(e,iw),r;try{r=await sw.readdir(t)}catch{return new Map}return aw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},hs=async(e,t)=>aw(e,[t]),aw=async(e,t)=>{let r=Rd.resolve(e,iw),n=new Map,o=!1;for(let s of t){let i;try{i=await sw.readFile(Rd.resolve(r,s),"utf-8")}catch{continue}i.startsWith(Fn)?o=!0:JO(i,n)}return o&&cw(n,await GO(e)),n},GO=async e=>{try{let t=await vt(e);return t?.replaceV1===!0?gs(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},cw=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},JO=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=UO.exec(r)?.groups?.service??WO.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(VO)].map(s=>s.groups?.env??"");o.length!==0&&cw(t,new Map([[n,o]]))}},ys=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import KO from"node:fs/promises";import HO from"node:path";import qO from"yaml";var YO=".github/workflows",zO="skip_terraform_deploy",vs=async(e,t)=>{let r=HO.resolve(e,YO,t),n;try{n=qO.parse(await KO.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!==zO).map(([i])=>i)};var lw="dev",Ed=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),uw=(e,t)=>e[t]===void 0,dw=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Pd=async e=>{try{return await e}catch{return[]}},XO=async()=>{let e=await G();return Dt(e.map(t=>t.branch))},ZO=(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},Dr=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 Pd(XO());if(l.length===0)return null;let u=dw(c,"version");return ws.enum([...new Set([...l,lw])]).optional().describe(`Which release to deploy from. "${lw}" 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=Vt(await Pd(Gt(t)),await it());if(l.length===0)return null;let u=l.filter(oo),p=l.filter(f=>!oo(f)),m=dw(c,"env");return ws.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 Pd(vs(c,t));if(l.length===0)return null;let u=await hs(c,t);return ws.array(ws.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${ZO(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=>Ed(c)?r.some(l=>uw(c,l)):!1,buildRequestedSchema:async c=>{let l=Ed(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")&&uw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):ws.object(u)},toArgs:(c,l)=>{let u={...Ed(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 QO from"@inquirer/select";var Ln=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 _(r=>QO({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import eD from"@inquirer/confirm";var ks=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;X()&&ci(o,{branch:r,env:n}),h.setInteractive();let s=await _(i=>eD({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&h.addOption("--yes",!0),s};import tD from"@inquirer/select";import rD from"node:process";var xd=()=>!X()&&rD.stdin.isTTY===!0,nD={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Td=async()=>_(e=>tD({message:"\u{1F680} Where should this deploy run?",choices:tr.filter(t=>t!=="local").map(t=>({name:t,value:t,description:nD[t]}))},e),{whenHeadless:"refuse"});var tr=["ci","local"],oD={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},pw=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${tr.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw X()?new O({status:"argument_required",argument:"from",agentMode:j.source},2,r):new g(void 0,r)}let t=tr.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${tr.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Cd=(e,t)=>{let n=oD[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}`})},$d=async e=>e||!xd()?pw(e):Td();var bs=async e=>{if(e)return e==="dev"?"dev":Ot(e);h.setInteractive();let t=await G(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await me();return qt([{value:"dev",label:"dev"},...fe({branches:r,descriptions:o,types:n})])};var mw="deploy-all.yml",fw=Dr({workflowFile:mw,fields:["version","env"],toolName:"gh-release-deploy-all"}),xa=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await at({provider:fw,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await bs(t),i=jo(s);h.addOption("--version",i);let a=await it(),c=Vt(await Gt(mw),a),l="";r?l=r:(h.setInteractive(),l=await Ln(c,"launch deploy-all workflow")),h.addOption("--env",l),Kr(l,"launch deploy-all workflow",a),ui({env:l,branch:s});let u=n??!1;if(u&&h.addOption("--skip-terraform",!0),!await ks({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}}try{Ad.quiet=!0,await Ad`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Ad.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:b(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"})}},Od=C({name:"gh-release-deploy-all",formProvider:fw,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:Nt.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:Nt.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:Nt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Nt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Nt.string().describe("The release branch that was deployed"),version:Nt.string().describe("The version that was deployed"),environment:Nt.string().describe("The environment deployed to"),skipTerraformDeploy:Nt.boolean().describe("Whether terraform deployment was skipped"),success:Nt.boolean().describe("Whether the deployment was successful")},handler:xa});import sD from"@inquirer/checkbox";import{z as je}from"zod";import{$ as Dd}from"zx";var Ir="deploy-selected-services.yml",gw=Dr({workflowFile:Ir,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Ta=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await at({provider:gw,params:e,operation:"launch deploy-selected workflow",argument:v=>v[0]??"version"});let i=await bs(t),a=jo(i);h.addOption("--version",a);let c=await it(),l=Vt(await Gt(Ir),c),u="";r?u=r:(h.setInteractive(),u=await Ln(l,"launch deploy-selected workflow")),h.addOption("--env",u),Kr(u,"launch deploy-selected workflow",c),ui({env:u,branch:i});let p=await $(),m=await vs(p,Ir);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Ir}`,stderrExcerpt:`no services found in .github/workflows/${Ir}`});let f=[];if(n&&n.length>0?f=n:(h.setInteractive(),f=await _(v=>sD({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(R=>({name:R,value:R}))},v),{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(v=>!m.includes(v));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 E=await hs(p,Ir),k=f.filter(v=>{let R=E.get(v);return R!==void 0&&!R.includes(u)});if(k.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:k.map(v=>`${v} deploys only to: ${(E.get(v)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Ir} gates these services out of ${u}: ${k.join(", ")}`});let A=o??!1;A&&h.addOption("--skip-terraform",!0);let M=v=>{let R={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:A,success:v};return{content:b(JSON.stringify(R,null,2)),structuredContent:R}};if(!await ks({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),M(!1);try{Dd.quiet=!0;let v=f.flatMap(T=>["-f",`${T}=true`]);return await Dd`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${v} ${A?["-f","skip_terraform_deploy=true"]:[]}`,Dd.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),h.print(),M(!0)}catch(v){throw d.error({error:v},"\u274C Error launching workflow"),new g(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Id=C({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:gw,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:je.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:je.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:je.array(je.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:je.boolean().optional().describe("Skip the terraform deployment stage."),confirm:je.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:je.string().describe("The release branch that was deployed"),version:je.string().describe("The version that was deployed"),environment:je.string().describe("The environment deployed to"),services:je.array(je.string()).describe("The services that were deployed"),skipTerraformDeploy:je.boolean().describe("Whether terraform deployment was skipped"),success:je.boolean().describe("Whether the deployment was successful")},handler:Ta});import{z as rr}from"zod";var Ca=async()=>{let t=(await G()).flatMap(i=>{let a=Q(i.branch);return a?[{version:ne(a),jiraKey:le(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Wi(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Mo(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:
|
|
408
408
|
`),d.info(`
|
|
409
409
|
${o.join(`
|
|
410
410
|
`)}
|
|
411
|
-
`);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:b(JSON.stringify(s,null,2)),structuredContent:s}},
|
|
412
|
-
`)};import
|
|
413
|
-
`).map((r,n)=>({line:n+1,text:r})).filter(({text:r})=>{let n=r.trimStart();return!t.commentPrefixes.some(o=>n.startsWith(o))}),
|
|
414
|
-
${
|
|
415
|
-
`)),
|
|
416
|
-
- `);await
|
|
411
|
+
`);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:b(JSON.stringify(s,null,2)),structuredContent:s}},Nd=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:rr.array(rr.object({version:rr.string().describe("Release version"),type:rr.enum(["regular","hotfix"]).describe("Release type"),description:rr.string().nullable().describe("Jira version description"),releaseDate:rr.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:rr.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:rr.number().describe("Number of release branches")},handler:Ca});import iD from"node:process";var Rs="local-deploy";var _d=e=>({...e}),Md=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=iD.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:Rs},contract:i,stripped:c}},$a=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(`
|
|
412
|
+
`)};import RD from"@inquirer/checkbox";import SD from"@inquirer/confirm";import ED from"@inquirer/select";import{spawn as PD}from"node:child_process";import Wd from"node:process";import{z as te}from"zod";import{$ as Ps}from"zx";import{$ as Ss}from"zx";var aD=async e=>{let t=Ss.quiet;Ss.quiet=!0;try{let r=`/${e}/environment`,n=await Ss`aws sts get-caller-identity --query Account --output text`,o=await Ss`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{Ss.quiet=t}},hw=(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`})},yw=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"})},vw=(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`})},jd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Kr(t,`deploy to "${t}"`,i),vw(t,s),yw({env:t,isShared:n,isClean:o});let a=await aD(r);return hw(t,a),{identity:a}};import Fd from"node:fs/promises";import Es from"node:path";var bw="devops/scripts",cD=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,lD=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,uD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,dD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,pD=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,mD=/`[^`]*\$\{[^`]*\/environment[^`]*`/,ww={commentPrefixes:["#"],literalPrefix:e=>dD.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=uD.exec(e)?.groups?.arg;return t!==void 0&&vD(t)}},kw={commentPrefixes:["//","/*","*"],literalPrefix:e=>pD.exec(e)?.groups?.prefix,isUnparseable:e=>mD.test(e)},Ld=async e=>{let t=await vt(e),r=await Sd(e);return(t===void 0?await fD(e,r):await gD(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},fD=async(e,t)=>{let r=Es.resolve(e,bw),n;try{n=await Fd.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=cD.exec(o)?.groups?.service;return s===void 0?[]:[Rw(s,Es.resolve(r,o),t)]}))},Rw=async(e,t,r)=>{let n=Ew(await Sw(t),ww);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:ys(yD(n),r.get(e)),ssmPrefix:Pw(n,ww)}},gD=async(e,t,r)=>{let n=gs(t);return(await Promise.all(Object.entries(t.services).map(async([s,i])=>{if(i.deploy===void 0){let l=Es.resolve(e,bw,`deploy-${s}.sh`);if(!await hD(l))return null;let u=await Rw(s,l,r);return{...u,allowedEnvs:ys(u.allowedEnvs,n.get(s))}}let a=Es.resolve(e,i.deploy),c=Ew(await Sw(a),kw);return{name:s,scriptPath:a,runner:"deploy-run",allowedEnvs:ys(n.get(s)??null,r.get(s)),ssmPrefix:Pw(c,kw)}}))).filter(s=>s!==null)},hD=async e=>{try{return await Fd.access(e),!0}catch{return!1}},Sw=async e=>{try{return await Fd.readFile(e,"utf-8")}catch{return""}},Ew=(e,t)=>e.split(`
|
|
413
|
+
`).map((r,n)=>({line:n+1,text:r})).filter(({text:r})=>{let n=r.trimStart();return!t.commentPrefixes.some(o=>n.startsWith(o))}),yD=e=>{let t=e.reduce((n,{text:o})=>n??lD.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},vD=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Pw=(e,t)=>{for(let{line:r,text:n}of e){let o=t.literalPrefix(n);if(o!==void 0)return o;if(t.isUnparseable(n))return{unparseable:{line:r,text:n.trim()}}}return null},xw=e=>{let t=Es.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},wD=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],xw(r)]);return t},kD=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${xw(r)}:${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("; ")})},bD=e=>{kD(e);let t=wD(e),[r,...n]=t.keys();if(r===void 0)throw new g(void 0,{operation:"resolve the SSM project prefix",remediation:'read the literal "/<project>/environment" in at least one deploy script: a deploy.ts in infra-kit.deploy.ts, or `aws ssm get-parameter --name "/<project>/environment"` in a 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},Tw=async(e,t)=>(await vt(e))?.project??bD(t),Aa=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Bd=(e,t)=>e.filter(r=>Aa(r,t));var Vd="deploy-all.yml",xD="/bin/sh",TD=async()=>{let e=Ps.quiet;Ps.quiet=!0;try{let t=await Ps`gh run list --workflow=${Vd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Ps.quiet=e}},CD=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await _(o=>RD({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},$D=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 X()&&ci(i,{env:t,services:n,accountId:o,shared:r}),r?_(a=>ED({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):_(a=>SD({message:i,default:!1},a),{whenHeadless:"refuse"})},$w=e=>e.runner==="sh"?[xD,[e.scriptPath]]:[Wd.execPath,[Wd.argv[1]??"","deploy-run",e.name]],AD=(e,t,r)=>new Promise((n,o)=>{let[s,i]=$w(e),a=PD(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),OD=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 AD(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}},DD=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&&!Aa(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))},Ud=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:_d(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},ID=async e=>{let{selection:t,eligible:r,service:n,env:o}=e;return t==="all"?r.map(s=>s.name):n&&n.length>0?n:(h.setInteractive(),CD(r,o))},Aw=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await $(),c=await Ld(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has infra-kit.deploy.ts or devops/scripts/deploy-*.sh",stderrExcerpt:`no deployable services found under ${a}`});let l=await Tw(a,c);await at({provider:Gd[t],params:e,operation:"deploy locally",argument:"env"});let u=await it(),p=Vt(await Gt(Vd),u),m=r??"";m||(h.setInteractive(),m=await Ln(p,"deploy locally")),h.addOption("--env",m);let f=Bd(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 y=await ID({selection:t,eligible:f,service:n,env:m}),E=DD({names:y,services:c,env:m});if(t==="selected")for(let we of y)h.addOption("--service",we);let k=oo(m),A=await Vr(),M=(await Ps`git rev-parse HEAD`.quiet()).stdout.trim(),v=await nf(),R=Md({env:m,branch:A,sha:M,isClean:v});i&&d.info(`Deploy contract for ${m}:
|
|
414
|
+
${$a(R)}`);let S=(await jd({env:m,project:l,isShared:k,isClean:v,runningEnvs:await TD(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${S}) from this machine`,`Preflight parameter: /${l}/environment`,$a(R),"Commands:",...E.map(we=>` ${$w(we).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
|
|
415
|
+
`)),Ud({env:m,accountId:S,names:y,built:R,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await $D({env:m,isShared:k,names:y,accountId:S}))return d.info("Deployment cancelled"),Ud({env:m,accountId:S,names:y,built:R,deployed:[],failed:[],dryRun:!1,success:!1});R.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${R.stripped.join(", ")}`);let{deployed:B,failed:Z}=await OD({chosen:E,childEnv:R.childEnv,cwd:a,env:m});return Z.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${B.join(", ")||"none"}], failed [${Z.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Wd.exitCode=1),h.print(),Ud({env:m,accountId:S,names:y,built:R,deployed:B,failed:Z,dryRun:!1,success:Z.length===0})},Ow=async e=>Aw(e,"all"),Dw=async e=>Aw(e,"selected"),Iw='Runs the repo\'s own deploys (infra-kit.deploy.ts via deploy-run, else 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.',Nw={env:te.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:te.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:te.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},_w={environment:te.string().describe("Environment deployed to"),accountId:te.string().describe("AWS account the deploy targeted"),services:te.array(te.string()).describe("Services requested"),deployed:te.array(te.string()).describe("Services that completed successfully"),failed:te.array(te.string()).describe("Services that failed"),contract:te.record(te.string(),te.string()).describe("Build contract passed to the scripts"),strippedVars:te.array(te.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:te.boolean().describe("Whether this was a dry run"),success:te.boolean().describe("Whether every requested service deployed")},Cw=e=>Dr({workflowFile:Vd,fields:["env"],toolName:e}),Gd={all:Cw("local-deploy-all"),selected:Cw("local-deploy-selected")},Jd=C({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Iw}`,requiresHumanConfirm:!0,formProvider:Gd.all,inputSchema:Nw,outputSchema:_w,handler:Ow}),Kd=C({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Iw}`,requiresHumanConfirm:!0,formProvider:Gd.selected,inputSchema:{...Nw,service:te.array(te.string()).min(1).describe('Service names as in infra-kit.deploy.ts or devops/scripts/deploy-<name>.sh, e.g. ["client-be"]. Required for MCP.')},outputSchema:_w,handler:Dw});import MD from"@inquirer/confirm";import Oa from"@inquirer/input";import Lw from"@inquirer/select";import qd from"node:process";import{z as H}from"zod";import{z as xs}from"zod";var Bn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Fw=2500,Mw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),jw=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,ND=async()=>{let e=await Qo();return{regular:_n(e,"regular"),hotfix:_n(e,"hotfix")}},_D=(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).`,Hd=(e={})=>{let t=e.hintBudgetMs??Fw;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=>Mw(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Bn(ND(),t);return xs.object({type:xs.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:xs.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. ${_D(r,t)}`),description:xs.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:xs.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=jw(r.description),a=jw(r.releaseDate),c=la(o);return{...Mw(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var jD='"1.2.5" or "next"',Yd=(e,t)=>{try{return Wu(e,t)}catch(r){throw r instanceof Pr?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 Qm?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}},FD=async(e,t)=>{let r=_n(e,t),n=r?` [${r}]`:"",o=(await _(i=>Oa({message:` Version (e.g. ${jD})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),qd.exit(1)),s},LD=async()=>{let e=(await _(t=>Oa({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),qd.exit(1));try{ti(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),qd.exit(1)}return e},BD=async()=>(await _(e=>Oa({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Zo},e),{whenHeadless:"refuse"})).trim(),UD=async e=>{h.setInteractive();let t=null,r=[],n=async()=>(t===null&&(t=await e(),r.push(...t)),r),o=[],s=!0;for(;s;){let i=o.length+1,a=await _(m=>Lw({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 _(m=>Lw({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 LD();l=Yd([{name:m,type:c}],[])[0]}else{let m=await FD(await n(),c);l=Yd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Zt(`v${l.id.raw}`))}let u=(await _(m=>Oa({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await BD();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await _(m=>MD({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},WD=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 ")},Bw=e=>{for(let t of e)h.addOption("--release",Uu(t))},VD=async(e,t)=>{if(e&&e.length>0){let n=Vu(e)?await t():[],o=Yd(e,n);return Bw(o),o}if(he())throw new O({status:"argument_required",argument:"release",agentMode:j.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 UD(t);return Bw(r),r},GD=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"})},JD=async(e,t)=>{let r=e.map(WD).join(`
|
|
416
|
+
- `);await J(t,`Create the following ${e.length} release(s)?
|
|
417
417
|
- ${r}
|
|
418
|
-
`),
|
|
419
|
-
`),{result:i}}catch(s){let i=
|
|
420
|
-
`),{failure:{version:n,error:a.message}}}},
|
|
421
|
-
${
|
|
418
|
+
`),h.addOption("--yes",!0)},KD=async e=>{let{entry:t,jiraConfig:r}=e,n=ne(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await an({operation:`create release ${o}`});let s=await tu(t.type),i=await ru({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}
|
|
419
|
+
`),{result:i}}catch(s){let i=No(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}
|
|
420
|
+
`),{failure:{version:n,error:a.message}}}},HD=(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.`)},Uw=Hd(),Da=async e=>{let{releases:t,confirmedCommand:r}=e;await _e({operation:"create release"}),await at({provider:Uw,params:e,operation:"create release",argument:"release"});let n=await fn(),o=null,i=await VD(t,async()=>(o===null&&(o=await Qo()),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"});GD(i),await $o({operation:"create release",base:mt(i[0].type)}),await JD(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await KD({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}HD(i.length,a.length,c.length),h.print();let l={createdBranches:a.map(u=>u.branchName),successCount:a.length,failureCount:c.length,releases:a,failedReleases:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},zd=C({name:"release-create",requiresHumanConfirm:!0,formProvider:Uw,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:H.array(H.object({version:H.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:H.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:H.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:H.string().optional().describe("Optional description for the Jira version."),releaseDate:Nu.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:H.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:H.array(H.string()).describe("List of created release branch names"),successCount:H.number().describe("Number of releases created successfully"),failureCount:H.number().describe("Number of releases that failed"),releases:H.array(H.object({version:H.string().describe("Version number"),type:H.enum(["regular","hotfix"]).describe("Release type"),branchName:H.string().describe("Release branch name"),prUrl:H.string().describe("GitHub PR URL"),jiraVersionUrl:H.string().describe("Jira version URL"),releaseDate:H.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:H.array(H.object({version:H.string().describe("Version number that failed"),error:H.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Da});import Ww from"@inquirer/input";import{z as Ye}from"zod";var Vw=["description","releaseDate"],qD=async()=>{let e=await G(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await me(),o=await qt(fe({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},YD=async e=>{let r=(await G()).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},zD=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await _(o=>Ww({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},XD=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await _(o=>Ww({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Zo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Er(n)},ZD=e=>{if(e!==void 0)return e===""?null:e},QD=async e=>(h.setInteractive(),{description:await zD(e.description),releaseDate:await XD(e.releaseDate)}),Xd=e=>e??"(none)",eI=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Xd(t.releaseDate)} \u2192 ${Xd(r.releaseDate)}`,Ia=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=ZD(n),i=await fn(),a;t?(a=Ot(t),await YD(a)):(h.setInteractive(),a=(await qD()).branch);let c=Q(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=ne(c);h.addOption("--version",l);let u=le(c),p=await $t(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&&X())throw new O({status:"argument_required",argument:"description",agentMode:j.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let y=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await QD(m),E=Vw.filter(T=>y[T]!==m[T]),k=E.includes("description"),A=E.includes("releaseDate"),M=wr(i,p),v=T=>{let S={version:l,branch:a,jiraVersionUrl:M,previousDescription:m.description,newDescription:y.description,previousReleaseDate:m.releaseDate,newReleaseDate:y.releaseDate,changedFields:E,changed:T};return{content:b(JSON.stringify(S,null,2)),structuredContent:S}};if(E.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${Xd(m.releaseDate)}`),h.print(),v(!1);k&&h.addOption("--description",y.description),A&&h.addOption("--release-date",y.releaseDate??"");let R=E.map(T=>eI(T,m,y));return await J(o,`Update ${u}?
|
|
421
|
+
${R.join(`
|
|
422
422
|
`)}
|
|
423
|
-
`),
|
|
424
|
-
`),
|
|
425
|
-
`).map(r=>r.trimEnd()).filter(r=>r.length>0),
|
|
426
|
-
`)},
|
|
427
|
-
`).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=
|
|
428
|
-
`).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},
|
|
423
|
+
`),h.addOption("--yes",!0),await mn({versionId:p.id,...k?{description:y.description}:{},...A?{releaseDate:y.releaseDate}:{}},i),k&&await Fi({branch:a,body:Io(M,y.description)}),d.info(`\u2705 Updated ${E.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${M}`),d.info(`\u{1F517} PR branch: ${a}
|
|
424
|
+
`),h.print(),v(!0)},Zd=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:Ye.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ye.string().optional().describe("New description. Empty string clears the description."),releaseDate:_u.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:Ye.string().describe("Release version"),branch:Ye.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ye.string().describe("Jira fix version URL"),previousDescription:Ye.string().describe("The description before the update"),newDescription:Ye.string().describe("The description after the update"),previousReleaseDate:Ye.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:Ye.string().nullable().describe("The planned release date after the update, or null"),changedFields:Ye.array(Ye.enum(Vw)).describe("The fields whose value actually changed"),changed:Ye.boolean().describe("Whether anything actually changed")},handler:Ia});import{z as ce}from"zod";import{$ as ep}from"zx";import{z as Gw}from"zod";var Hw=2500,Na="release-remove",Jw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tI=e=>e.version===void 0||e.version==="",rI=async()=>{try{return{outcome:"listed",prs:await G()}}catch(e){return e instanceof g&&e.operation===Oo?{outcome:"empty"}:{outcome:"failed"}}},Kw=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Na}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${Na}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${Na}`}),null),nI=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Vi(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(le(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},oI=(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): ${Na}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Qd=(e={})=>{let t=e.fetchBudgetMs??Hw;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=>Jw(r)&&tI(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Bn(rI(),t),Bn(me(),t)]);if(r===null||r.outcome!=="listed")return Kw(r,t);let o=nI(r.prs,n);return o.length===0?Kw({outcome:"empty"},t):Gw.object({version:Gw.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${oI(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:{...Jw(n)?n:{},version:r.version}}};var qw=["worktree","pr","local-branch","remote-branch","jira"],Xw={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"},Nr="remove a release",rt=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Yw=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new O({...e,agentMode:j.source},2,t)},sI=e=>{he()&&(e.version||Yw({status:"argument_required",argument:"version"},{operation:Nr,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&&Yw({status:"refused"},{operation:Nr,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"}))},Zw=e=>{e.pr?.state==="MERGED"&&rt({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`})},iI=(e,t)=>{if(t.skipJira||(e.jiraConfig||rt({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)&&rt({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||rt({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)`}))},aI=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;rt({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"})},cI=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||rt({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(", ")}`})},lI=async e=>(await ep`git -C ${e} status --porcelain`).stdout.split(`
|
|
425
|
+
`).map(r=>r.trimEnd()).filter(r=>r.length>0),uI=async e=>{try{let{terminals:t}=await Mf(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},dI=async e=>{let t=await li([e]);if(t!==null)throw d.warn({operation:Nr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new O({status:"refused",reason:"orca_caller_inside_target",agentMode:j.source},2,{operation:Nr,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`})},pI=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await At();if(!n)return r;let o=await $t(le(e),n),s=t.moveIssuesTo?await mI(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Ui(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:wr(n,o)}}},mI=async(e,t)=>{let r=await $t(e,t);return r||rt({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}"`})},fI=async(e,t)=>{let r=Q(e);r||rt({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}${ge}`}/${e}`,[i,a,c,l]=await Promise.all([be("release"),ln(e),Ce(n,`refs/heads/${e}`),Gr(n,e)]),u=i.includes(e);return u&&await dI(s),{...await pI(r,t),branch:e,id:r,label:ne(r),baseBranch:a?.baseRefName??mt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await uI(s):0,worktreeDirty:u?await lI(s):null,localTipSha:c,remoteTipSha:l,pr:a}},zw=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}),gI=(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}`},hI=(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: ${gI(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
|
|
426
|
+
`)},_a=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},yI=e=>typeof e=="string"?e:e.outcome;async function Ts(e,t,r){try{let n=await r(),o=yI(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${Xw[e]} \u2014 ${o}`),n}catch(n){throw new _a(e,n)}}var vI=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,wI=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>vI(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 ${qw.indexOf(r)+1} of ${qw.length} (${Xw[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},kI=async e=>(await ds(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",bI=async e=>{let t=await ln(e.branch);if(Zw({...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 ep`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},RI=async e=>(await Vr()===e.branch&&await ep`git switch ${e.baseBranch}`,await ri(e.branch),await sf(e.branch)?rt({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"),SI=async e=>(await ni(e.branch),e.remoteTipSha?"deleted":"absent"),EI=async(e,t,r)=>{let n=await Ui(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}\``;rt({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}`})},PI=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await EI(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 eu({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),xI=(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}),TI=async(e,t,r)=>{let n=await Ts("worktree",r,()=>kI(e)),o=await Ts("pr",r,()=>bI(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await Ts("local-branch",r,()=>RI(e)),i=await Ts("remote-branch",r,()=>SI(e)),a=await Ts("jira",r,()=>PI(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},CI=async(e,t)=>{let r=[];try{return xI(e,await TI(e,t,r))}catch(n){throw n instanceof _a?wI({plan:e,step:n.step,done:r,cause:n.reason}):n}},$I=async e=>{if(e)return Ot(e);h.setInteractive();let[t,r]=await Promise.all([me(),G()]),n=r.map(s=>s.branch);n.length===0&&rt({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 qt(fe({branches:n,descriptions:t,types:o}))}catch(s){throw Oe(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"})}},Qw=Qd(),Ma=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await _e({operation:Nr}),await K(),await at({provider:Qw,params:e,operation:Nr,argument:"version"}),sI(e);try{let s=await fI(await $I(r),e);d.debug({plan:zw(s)},"release remove: resolved plan"),Zw(s),iI(s,e),aI(s),await $o({operation:`remove release ${s.label}`,base:s.baseBranch}),cI(s),h.addOption("--version",s.label),n&&h.addOption("--move-issues-to",n),o&&h.addOption("--skip-jira",!0),await J(t,hI(s,!!o),{throwOnDecline:!0,plan:{...zw(s),skipJira:!!o}}),t||h.addOption("--yes",!0);let i=await CI(s,e);return h.print(),{content:b(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Oe(s)||Et(s)||s instanceof g?s:(d.error({err:Ar(s)},"\u274C Error removing release"),new g(s,{operation:Nr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},tp=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:Qw,inputSchema:{version:ce.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:ce.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:ce.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:ce.string().describe("The release branch that was targeted"),version:ce.string().describe('The release label (e.g. "1.2.5")'),baseBranch:ce.string().describe("The branch HEAD was moved to before the local delete"),worktree:ce.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:ce.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:ce.number().nullable().describe("The pull request number, or null when none exists"),localBranch:ce.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:ce.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:ce.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:ce.string().nullable().describe("The origin tip before deletion"),jira:ce.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:ce.object({id:ce.string(),name:ce.string(),url:ce.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Ma});import{spawn as II}from"node:child_process";import NI from"node:fs";import{homedir as _I}from"node:os";import Fa from"node:process";import ja from"node:fs";import Un from"node:path";var AI=e=>{try{return ja.statSync(e).isFile()?ja.readFileSync(e,"utf8"):null}catch{return null}},OI=e=>{try{return ja.realpathSync(e)}catch{return e}},DI=(e,t)=>{let o=t(Un.join(e,".git"))?.split(`
|
|
427
|
+
`).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=Un.resolve(e,o),i=`${Un.sep}.git${Un.sep}worktrees${Un.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},ek=(e={})=>{let t=e.listInstallations??Ac,r=e.exists??ja.existsSync,n=e.readGitFile??AI,o=e.realpath??OI,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=DI(i.projectPath,n);if(!r(Un.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var MI=180*1e3,jI=900*1e3,FI=4*1024*1024,LI=2e3,BI=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=II(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<FI&&(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)},LI).unref()})}),UI=({cwd:e,timeoutMs:t})=>BI({command:Fa.execPath,args:[Fa.argv[1]??"","setup","--unattended","--json"],cwd:e,env:Af(Fa.env),timeoutMs:t}),WI=e=>{NI.writeFileSync(Rn(),e,{mode:384})},VI=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}},GI=new RegExp("\x1B\\[[0-9;]*m","g"),JI=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(GI,"").split(`
|
|
428
|
+
`).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},KI=(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}},tk=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":ra(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(MI,o)}),a=i.error===null?VI(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${JI(i)} \u2014 run: ${s}`]}:{root:e,...KI(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},HI=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}})},qI=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(`
|
|
429
429
|
`)}
|
|
430
|
-
`},
|
|
431
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),iN=e=>{let t=tk(e.stderr),r=tk(e.stdout),n=[...t,...r].filter(s=>sN.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-oN).join(" / ")},aN="ENOBUFS",cN=e=>e.error?.code===aN,lN=e=>{if(cN(e))return`terminated after exceeding the ${rk} 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=iN(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var uN=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},dN=e=>{let t=Ke(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},pN=(e,t)=>{let r=dN(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=xs(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Ts(r),context:n}},ja=async(e=br,t=Ko())=>{let r=await qo(br,t),n={owner:null,present:uN(r)},o=Ou(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>pN(s.get(a),n)),context:n}};var rp=(e,t)=>({...Cs(e),action:"skipped",commands:e.commands,detail:t}),Cs=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),nk=(e,t)=>e.action==="none"?rp(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?rp(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Cs(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},mN=(e,t)=>t.ran?t.ok?{...Cs(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Cs(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Cs(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},np=async e=>{let t=e.run??tp,{plans:r}=await ja(e.ids,e.probeDeps),n=[];for(let o of r){let s=nk(o,e.mode);if(s!==null){n.push(s);continue}n.push(mN(o,t(o.recipe,o.context)))}return n},op=async(e,t)=>{let{plans:r}=await ja(e,t);return r.map(n=>nk(n,"converge")??rp(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import $N from"node:process";import{z as N}from"zod";var sp={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},fN=Object.keys(sp).sort((e,t)=>sp[e]-sp[t]),ok={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},sk=new Set(["manual","warn","fail"]),ip=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 Ue(e)}},gN=e=>e.reduce((t,r)=>ok[r]>ok[t]?r:t,"skipped"),ak=e=>e.message.trim(),hN=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 "),ik=e=>e.message===Tn,yN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?ak(r):e.length>1?hN(e):t?"activate with the last line below":"see below"},vN=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>ip(i.outcome)),n=t.filter(i=>sk.has(ip(i.outcome))).map(ak),o=t.filter(i=>!sk.has(ip(i.outcome))&&!ik(i)),s={name:e,status:gN(r),message:yN(o,t.some(ik))};return n.length>0?{...s,notes:n}:s},wN=e=>({label:"Local setup",rows:fN.map(t=>vN(t,e.filter(r=>r.step===t)))}),kN=(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 Ue(e.action)}},bN=(e,t)=>{let r=kN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},RN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>bN(r,t))}),SN=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 Ue(e)}},EN=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 Ue(e)}},PN=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 Ue(e)}},xN=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 Ue(e.outcome)}},TN=(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 Ue(e)}},CN=e=>({label:"Portless service",rows:[{name:"link",status:SN(e.link),message:PN(e.link)},{name:"node",status:EN(e.node.outcome),message:xN(e.node)},TN(e.service,e.command)]}),ck=(e,t)=>[wN(e.init),RN(e.tools,t),CN(e.portless)],lk=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var AN=()=>{let{link:e,node:t}=Xs();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},ON=async e=>{let t=Hm(e.link).outcome,r=Km(e.node),n=zs(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 yv(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=_t(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},dk="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",pk="--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.",DN=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(dk);if(o&&(e.tools!==void 0||r))throw new Error(pk);return{ids:e.tools??t??br,mode:r?"update":"converge",skipTools:o}},uk=(e,t)=>e instanceof xn?e.step:t.at(-1)?.step??"zshrc",IN=async()=>{let e=[];try{await Eu(t=>{e.push(t)})}catch(t){e.push({step:uk(t,e),outcome:"failed",message:`The ${uk(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},NN=(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}`}))},_N=async(e,t)=>{try{return e.skipTools?await op(e.ids,t.probeDeps):await np({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return NN(e.ids,r)}},MN=e=>({step:e.step,outcome:e.outcome,message:e.message}),Fa=async(e={})=>{let t=DN(e);Xe.withheld=e.unattended===!0;let r=await IN(),n=await _N(t,e),o=await ON(e.portlessDeps??AN()),s=ck({init:r,tools:n,portless:o},{skipTools:t.skipTools});dt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(Tn),lk(s)&&($N.exitCode=1);let i={init:r.map(MN),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:b(JSON.stringify(i,null,2)),structuredContent:i}},jN=N.object({step:N.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:N.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:N.string().describe("The same line a human running this would have read")}),FN=N.object({id:N.string().describe("Dependency id"),action:N.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:N.object({present:N.boolean(),onPath:N.boolean(),version:N.string().nullable(),manager:N.string()}).describe("The tool\u2019s state before this run"),commands:N.array(N.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:N.string().describe("Why, in one line")}),LN=N.object({link:N.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:N.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:N.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:N.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")}),BN={init:N.array(jN).describe("One entry per init step, in the order they ran"),tools:N.array(FN).describe("One result per requested dependency"),portlessService:LN.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:N.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:N.boolean().describe("Whether anything was installed or updated"),report:N.array(N.object({label:N.string().describe("Section heading"),rows:N.array(N.object({name:N.string().describe("Init step, tool id, or portless part"),status:N.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:N.string().describe("The row message, as printed"),notes:N.array(N.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:N.boolean().describe("Whether no tool failed (a refusal is not a failure)")},UN={tools:N.array(N.enum(br)).optional().describe("Which tools to act on. Omit for all six."),mode:N.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:N.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},ap=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:UN,outputSchema:BN,requiresHumanConfirm:!0,handler:e=>Fa({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as fk}from"node:fs";import gk from"node:path";import ZN from"node:process";import{z as It}from"zod";import{createHash as WN}from"node:crypto";import{readFileSync as VN}from"node:fs";var Ir=e=>WN("sha256").update(VN(e)).digest("hex");import{readFileSync as YN,writeFileSync as zN}from"node:fs";import Wa from"node:path";import{z as yt}from"zod";var oe="vendor",GN=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),JN=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),KN=[".tsbuildinfo"],cp=e=>GN.has(e),lp=e=>JN.has(e)?!0:KN.some(t=>e.endsWith(t)),La=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>cp(o))||lp(r)};import{readdirSync as HN}from"node:fs";import up from"node:path";var qN=e=>e.split(up.sep).join("/"),Ba=e=>{let t=[],r=n=>{for(let o of HN(n,{withFileTypes:!0})){let s=up.join(n,o.name);if(o.isDirectory()){if(cp(o.name))continue;r(s);continue}lp(o.name)||t.push(qN(up.relative(e,s)))}};return r(e),t.sort()};var Ye=".sync-manifest.json",Ua=1,XN=yt.object({schemaVersion:yt.number().optional(),source:yt.string(),commit:yt.string(),syncedAt:yt.string(),fileCount:yt.number(),files:yt.record(yt.string(),yt.string())}),dp=e=>(e.schemaVersion??Ua)>Ua,mk=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Ba(e);for(let o of n)try{r[o]=Ir(Wa.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},$s=e=>{let t=Wa.join(e,Ye),r;try{r=YN(t,"utf8")}catch{throw new Error(`Missing ${Ye} at ${t}`)}let n=XN.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ye} at ${t}: ${yt.prettifyError(n.error)}`);return n.data},pp=(e,t,r)=>{let n=mk(e,r),o={schemaVersion:Ua,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return zN(Wa.join(e,Ye),`${JSON.stringify(o,null,2)}
|
|
432
|
-
`),o},
|
|
433
|
-
${e} (${t.length}):`);for(let r of t.slice(0,fp))d.info(` ${r}`);t.length>fp&&d.info(` \u2026and ${t.length-fp} more`)}},Va=async(e={})=>{let t=e.cwd??await A(),r=gk.join(t,oe),n={modified:[],added:[],removed:[],fileCount:0};if(!fk(r)){d.info(`\u2139\uFE0F No ${oe}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}if(!fk(gk.join(r,Ye))){d.error(`\u274C Missing ${oe}/${Ye}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}let o=$s(r);if(dp(o)){d.error(`\u274C ${oe}/${Ye} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=mp(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${oe}/ has drifted from ${oe}/${Ye}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),gp("Modified",s),gp("Added (not in manifest)",i),gp("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${oe}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},QN={status:It.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:It.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:It.number(),modified:It.array(It.string()),added:It.array(It.string()),removed:It.array(It.string())},hp=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:QN,handler:()=>Va({cwd:ZN.cwd()})});import hk from"node:process";import{z as As}from"zod";var yk=async e=>{try{return await e()}catch{return null}},Ga=async()=>{let e=L.version;d.info(e);let t=await yk(A),r=t===null?null:await yk(()=>$e(t)),n={version:e,cwd:hk.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:hk.env.CLAUDE_PROJECT_DIR||null};return{content:b(JSON.stringify(n,null,2)),structuredContent:n}},yp=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:As.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:As.string().describe("The working directory of this process"),repoRoot:As.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:As.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:As.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ga});import Ak from"@inquirer/confirm";import s_ from"node:path";import{z as U}from"zod";import{$ as Ds}from"zx";import e_ from"@inquirer/input";import wk from"@inquirer/select";import{$ as tr}from"zx";var Os="dev",t_="main",vp="feature/",kk=["new","local","remote"],Ja=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${vp}${t}`},bk=async()=>{let e=await tr({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},r_=2,wp=async()=>{let e=await tr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Os}`;if(e.exitCode===0)return Os;if(e.exitCode!==r_)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 ${Os} exists`});return await bk()??Os},Rk=async e=>{let t=e?.trim();return t?t===Os||t===t_||t===await bk()?t:Pe(ve(t)):wp()},Sk=async()=>_(e=>wk({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"}}),Ek=async()=>_(e=>e_({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Ja(t)===vp?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Pk=async(e,t)=>e.length===0?t:_(r=>wk({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),n_=async e=>{let t=await tr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===vp||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`})},vk=async e=>(await tr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,o_=async e=>(await tr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,xk=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Ja))];for(let s of n)await n_(s);if(!await vk(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 o_(s)?o.push({branch:s,base:r,source:"local"}):await vk(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Tk=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await tr`git worktree add ${t} ${r}`:o==="remote"?await tr`git worktree add --track -b ${r} ${t} origin/${r}`:await tr`git worktree add --no-track -b ${r} ${t} origin/${n}`},Ck=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 Is="create worktrees",i_=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],kp=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Ka=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await Ne({operation:Is}),a_(e);try{let o=await A(),s=`${o}${fe}`;await $k(`${s}/${Lr.release}`),await $k(`${s}/${Lr.feature}`);let i=await c_(e),a=i==="feature"?await u_(e):await l_(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let R={kind:i,createdWorktrees:[],count:0,features:[],...kp()};return{content:b(JSON.stringify(R,null,2)),structuredContent:R}}let c=await H(),l=await d_(r,c),u=await p_(n,c),p=await $e(o),m=s_.basename(p),f=u?await m_({explicit:n!==void 0,mainRepoRoot:p}):null;await G(t,f_(f,m,a.previewLines)),t||y.addOption("--yes",!0);let v=f?await g_(f,p):null,E=await k_(a.targets,s);if(b_(E),l)for(let R of E)await Ds`github ${s}/${R}`,await Ds`sleep 5`;let k=v?await y_({registration:v,createdWorktrees:E,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):kp();v_(k),y.print();let h={kind:i,createdWorktrees:E,count:E.length,features:a.features.filter(R=>E.includes(R.branch)),...k};return{content:b(JSON.stringify(h,null,2)),structuredContent:h}}catch(o){throw Ae(o)||o instanceof O?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:Is,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},a_=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:Is,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},c_=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),Sk()),l_=async e=>{let{all:t,versions:r}=e,n=await we("release"),o=[];if(r)o=r.split(",").map(a=>Pe(ve(a.trim())));else{let a=await V(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{y.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await pe();o=await Ht(me({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",$t(o));let{branchesToCreate:s}=w_({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>Ds`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},u_=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await Ek()],n===void 0)){let l=(await V()).map(u=>u.branch);n=await Pk(l,await wp())}let o=await Rk(n),s=await xk({names:r,base:o});y.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),y.addOption("--base",o);let i=await we("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=>Tk(l,u)})),features:a,previewLines:a.map(Ck)}},d_=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await _(o=>Ak({message:"Open created worktrees in GitHub Desktop?"},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--github-desktop":"--no-github-desktop",!0),n},p_=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await _(o=>Ak({message:"Open created worktrees in Orca?",default:!0},o),{whenHeadless:{value:!1}});return e===void 0&&r===void 0&&y.setInteractive(),y.addOption(n?"--orca":"--no-orca",!0),n},Ok=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"},m_=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Bt();if(n!=="ready"){let{reason:s,text:i}=Ok(n);if(t)throw d.warn({operation:Is},`\u26D4 --orca was passed but ${i}`),new O({status:"refused",reason:s,agentMode:j.source},2,{operation:Is,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 Mf(r);return{probe:n,registered:o.registered,visibility:o.visibility}},f_=(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(`
|
|
434
|
-
`)},
|
|
430
|
+
`},YI=e=>({version:e.version??L.version,home:e.home??_I(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Ic({lockPath:gy()})),readRecord:e.readRecord??Sn,writeRecord:e.writeRecord??hy,discoverProjects:e.discoverProjects??(()=>ek()),runSetupChild:e.runSetupChild??UI,writeLog:e.writeLog??WI}),zI=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},XI=async e=>{let t=e.readRecord(),r=e.clock();if(!wy(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+jI,s=await tk(null,e.home,e,o),i=zI(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 tk(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:HI(a)};e.writeRecord(c);try{e.writeLog(qI(c))}catch{}return"ran"},rk=async(e={})=>{try{let t=YI(e),r=t.acquireLock();if(r===null)return"already-running";try{return await XI(t)}finally{r()}}catch{return"not-due"}},rp=async(e={})=>{let t=await rk(e);return{content:b(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as tN}from"node:child_process";import{homedir as rN}from"node:os";import nN from"node:process";var ZI=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},QI=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},eN=(e,t)=>{let r=ZI(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},Cs=(e,t)=>{let r=[...QI(e),...eN(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},$s=e=>e.steps.map(Ue);var oN=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],sN=e=>{let t={...Im(e)};for(let r of oN)delete t[r];return t},np=(e,t,r={})=>{let n=r.spawnSync??tN,o=r.env??nN.env,s=(r.agentMode??he)(),i=$s(e),a=Cs(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:cN({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??iN}):{ran:!1,commands:i,refusedBecause:a.reasons}},iN=e=>{d.info(e)},ok=64,aN=ok*1024*1024,cN=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=sN(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:aN,cwd:rN(),env:s}),l=fN(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},lN=5,uN=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,nk=e=>e==null?[]:String(e).split(`
|
|
431
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),dN=e=>{let t=nk(e.stderr),r=nk(e.stdout),n=[...t,...r].filter(s=>uN.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-lN).join(" / ")},pN="ENOBUFS",mN=e=>e.error?.code===pN,fN=e=>{if(mN(e))return`terminated after exceeding the ${ok} 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=dN(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var gN=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},hN=e=>{let t=He(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},yN=(e,t)=>{let r=hN(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=Cs(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:$s(r),context:n}},La=async(e=Sr,t=qo())=>{let r=await zo(Sr,t),n={owner:null,present:gN(r)},o=Iu(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>yN(s.get(a),n)),context:n}};var op=(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}}),sk=(e,t)=>e.action==="none"?op(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?op(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`},vN=(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`},sp=async e=>{let t=e.run??np,{plans:r}=await La(e.ids,e.probeDeps),n=[];for(let o of r){let s=sk(o,e.mode);if(s!==null){n.push(s);continue}n.push(vN(o,t(o.recipe,o.context)))}return n},ip=async(e,t)=>{let{plans:r}=await La(e,t);return r.map(n=>sk(n,"converge")??op(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import NN from"node:process";import{z as N}from"zod";var ap={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},wN=Object.keys(ap).sort((e,t)=>ap[e]-ap[t]),ik={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},ak=new Set(["manual","warn","fail"]),cp=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 We(e)}},kN=e=>e.reduce((t,r)=>ik[r]>ik[t]?r:t,"skipped"),lk=e=>e.message.trim(),bN=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 "),ck=e=>e.message===$n,RN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?lk(r):e.length>1?bN(e):t?"activate with the last line below":"see below"},SN=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>cp(i.outcome)),n=t.filter(i=>ak.has(cp(i.outcome))).map(lk),o=t.filter(i=>!ak.has(cp(i.outcome))&&!ck(i)),s={name:e,status:kN(r),message:RN(o,t.some(ck))};return n.length>0?{...s,notes:n}:s},EN=e=>({label:"Local setup",rows:wN.map(t=>SN(t,e.filter(r=>r.step===t)))}),PN=(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 We(e.action)}},xN=(e,t)=>{let r=PN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},TN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>xN(r,t))}),CN=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 We(e)}},$N=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 We(e)}},AN=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 We(e)}},ON=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 We(e.outcome)}},DN=(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 We(e)}},IN=e=>({label:"Portless service",rows:[{name:"link",status:CN(e.link),message:AN(e.link)},{name:"node",status:$N(e.node.outcome),message:ON(e.node)},DN(e.service,e.command)]}),uk=(e,t)=>[EN(e.init),TN(e.tools,t),IN(e.portless)],dk=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var _N=()=>{let{link:e,node:t}=Qs();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},MN=async e=>{let t=Ym(e.link).outcome,r=qm(e.node),n=Zs(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 wv(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=jt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},mk="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",fk="--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.",jN=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(mk);if(o&&(e.tools!==void 0||r))throw new Error(fk);return{ids:e.tools??t??Sr,mode:r?"update":"converge",skipTools:o}},pk=(e,t)=>e instanceof Cn?e.step:t.at(-1)?.step??"zshrc",FN=async()=>{let e=[];try{await xu(t=>{e.push(t)})}catch(t){e.push({step:pk(t,e),outcome:"failed",message:`The ${pk(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},LN=(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}`}))},BN=async(e,t)=>{try{return e.skipTools?await ip(e.ids,t.probeDeps):await sp({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return LN(e.ids,r)}},UN=e=>({step:e.step,outcome:e.outcome,message:e.message}),Ba=async(e={})=>{let t=jN(e);Ze.withheld=e.unattended===!0;let r=await FN(),n=await BN(t,e),o=await MN(e.portlessDeps??_N()),s=uk({init:r,tools:n,portless:o},{skipTools:t.skipTools});pt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info($n),dk(s)&&(NN.exitCode=1);let i={init:r.map(UN),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:b(JSON.stringify(i,null,2)),structuredContent:i}},WN=N.object({step:N.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:N.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:N.string().describe("The same line a human running this would have read")}),VN=N.object({id:N.string().describe("Dependency id"),action:N.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:N.object({present:N.boolean(),onPath:N.boolean(),version:N.string().nullable(),manager:N.string()}).describe("The tool\u2019s state before this run"),commands:N.array(N.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:N.string().describe("Why, in one line")}),GN=N.object({link:N.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:N.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:N.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:N.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")}),JN={init:N.array(WN).describe("One entry per init step, in the order they ran"),tools:N.array(VN).describe("One result per requested dependency"),portlessService:GN.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:N.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:N.boolean().describe("Whether anything was installed or updated"),report:N.array(N.object({label:N.string().describe("Section heading"),rows:N.array(N.object({name:N.string().describe("Init step, tool id, or portless part"),status:N.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:N.string().describe("The row message, as printed"),notes:N.array(N.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:N.boolean().describe("Whether no tool failed (a refusal is not a failure)")},KN={tools:N.array(N.enum(Sr)).optional().describe("Which tools to act on. Omit for all six."),mode:N.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:N.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},lp=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:KN,outputSchema:JN,requiresHumanConfirm:!0,handler:e=>Ba({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as hk}from"node:fs";import yk from"node:path";import n_ from"node:process";import{z as _t}from"zod";import{createHash as HN}from"node:crypto";import{readFileSync as qN}from"node:fs";var _r=e=>HN("sha256").update(qN(e)).digest("hex");import{readFileSync as e_,writeFileSync as t_}from"node:fs";import Ga from"node:path";import{z as wt}from"zod";var se="vendor",YN=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),zN=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),XN=[".tsbuildinfo"],up=e=>YN.has(e),dp=e=>zN.has(e)?!0:XN.some(t=>e.endsWith(t)),Ua=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>up(o))||dp(r)};import{readdirSync as ZN}from"node:fs";import pp from"node:path";var QN=e=>e.split(pp.sep).join("/"),Wa=e=>{let t=[],r=n=>{for(let o of ZN(n,{withFileTypes:!0})){let s=pp.join(n,o.name);if(o.isDirectory()){if(up(o.name))continue;r(s);continue}dp(o.name)||t.push(QN(pp.relative(e,s)))}};return r(e),t.sort()};var ze=".sync-manifest.json",Va=1,r_=wt.object({schemaVersion:wt.number().optional(),source:wt.string(),commit:wt.string(),syncedAt:wt.string(),fileCount:wt.number(),files:wt.record(wt.string(),wt.string())}),mp=e=>(e.schemaVersion??Va)>Va,gk=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Wa(e);for(let o of n)try{r[o]=_r(Ga.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},Os=e=>{let t=Ga.join(e,ze),r;try{r=e_(t,"utf8")}catch{throw new Error(`Missing ${ze} at ${t}`)}let n=r_.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${ze} at ${t}: ${wt.prettifyError(n.error)}`);return n.data},fp=(e,t,r)=>{let n=gk(e,r),o={schemaVersion:Va,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return t_(Ga.join(e,ze),`${JSON.stringify(o,null,2)}
|
|
432
|
+
`),o},gp=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!Ua(c))),n=Wa(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}_r(Ga.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 hp=30,yp=(e,t)=>{if(t.length!==0){d.info(`
|
|
433
|
+
${e} (${t.length}):`);for(let r of t.slice(0,hp))d.info(` ${r}`);t.length>hp&&d.info(` \u2026and ${t.length-hp} more`)}},Ja=async(e={})=>{let t=e.cwd??await $(),r=yk.join(t,se),n={modified:[],added:[],removed:[],fileCount:0};if(!hk(r)){d.info(`\u2139\uFE0F No ${se}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}if(!hk(yk.join(r,ze))){d.error(`\u274C Missing ${se}/${ze}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}let o=Os(r);if(mp(o)){d.error(`\u274C ${se}/${ze} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=gp(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${se}/ has drifted from ${se}/${ze}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),yp("Modified",s),yp("Added (not in manifest)",i),yp("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${se}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},o_={status:_t.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:_t.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:_t.number(),modified:_t.array(_t.string()),added:_t.array(_t.string()),removed:_t.array(_t.string())},vp=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:o_,handler:()=>Ja({cwd:n_.cwd()})});import vk from"node:process";import{z as Ds}from"zod";var wk=async e=>{try{return await e()}catch{return null}},Ka=async()=>{let e=L.version;d.info(e);let t=await wk($),r=t===null?null:await wk(()=>Ae(t)),n={version:e,cwd:vk.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:vk.env.CLAUDE_PROJECT_DIR||null};return{content:b(JSON.stringify(n,null,2)),structuredContent:n}},wp=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:Ds.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Ds.string().describe("The working directory of this process"),repoRoot:Ds.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Ds.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Ds.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ka});import Dk from"@inquirer/confirm";import u_ from"node:path";import{z as W}from"zod";import{$ as Ns}from"zx";import s_ from"@inquirer/input";import bk from"@inquirer/select";import{$ as nr}from"zx";var Is="dev",i_="main",kp="feature/",Rk=["new","local","remote"],Ha=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${kp}${t}`},Sk=async()=>{let e=await nr({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},a_=2,bp=async()=>{let e=await nr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Is}`;if(e.exitCode===0)return Is;if(e.exitCode!==a_)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 ${Is} exists`});return await Sk()??Is},Ek=async e=>{let t=e?.trim();return t?t===Is||t===i_||t===await Sk()?t:Te(ke(t)):bp()},Pk=async()=>_(e=>bk({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"}}),xk=async()=>_(e=>s_({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Ha(t)===kp?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Tk=async(e,t)=>e.length===0?t:_(r=>bk({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),c_=async e=>{let t=await nr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===kp||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`})},kk=async e=>(await nr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,l_=async e=>(await nr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Ck=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Ha))];for(let s of n)await c_(s);if(!await kk(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 l_(s)?o.push({branch:s,base:r,source:"local"}):await kk(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},$k=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await nr`git worktree add ${t} ${r}`:o==="remote"?await nr`git worktree add --track -b ${r} ${t} origin/${r}`:await nr`git worktree add --no-track -b ${r} ${t} origin/${n}`},Ak=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 _s="create worktrees",d_=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Rp=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),qa=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await _e({operation:_s}),p_(e);try{let o=await $(),s=`${o}${ge}`;await Ok(`${s}/${Ur.release}`),await Ok(`${s}/${Ur.feature}`);let i=await m_(e),a=i==="feature"?await g_(e):await f_(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),h.print();let M={kind:i,createdWorktrees:[],count:0,features:[],...Rp()};return{content:b(JSON.stringify(M,null,2)),structuredContent:M}}let c=await K(),l=await h_(r,c),u=await y_(n,c),p=await Ae(o),m=u_.basename(p),f=u?await v_({explicit:n!==void 0,mainRepoRoot:p}):null;await J(t,w_(f,m,a.previewLines)),t||h.addOption("--yes",!0);let y=f?await k_(f,p):null,E=await P_(a.targets,s);if(x_(E),l)for(let M of E)await Ns`github ${s}/${M}`,await Ns`sleep 5`;let k=y?await R_({registration:y,createdWorktrees:E,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):Rp();S_(k),h.print();let A={kind:i,createdWorktrees:E,count:E.length,features:a.features.filter(M=>E.includes(M.branch)),...k};return{content:b(JSON.stringify(A,null,2)),structuredContent:A}}catch(o){throw Oe(o)||o instanceof O?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:_s,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},p_=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:_s,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},m_=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(h.setInteractive(),Pk()),f_=async e=>{let{all:t,versions:r}=e,n=await be("release"),o=[];if(r)o=r.split(",").map(a=>Te(ke(a.trim())));else{let a=await G(),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 me();o=await Yt(fe({branches:c,descriptions:u,types:l}),{required:!0})}}t?h.addOption("--all",!0):h.addOption("--versions",Dt(o));let{branchesToCreate:s}=E_({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>Ns`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},g_=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(h.setInteractive(),r=[await xk()],n===void 0)){let l=(await G()).map(u=>u.branch);n=await Tk(l,await bp())}let o=await Ek(n),s=await Ck({names:r,base:o});h.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),h.addOption("--base",o);let i=await be("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=>$k(l,u)})),features:a,previewLines:a.map(Ak)}},h_=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await _(o=>Dk({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},y_=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await _(o=>Dk({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},Ik=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"},v_=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Wt();if(n!=="ready"){let{reason:s,text:i}=Ik(n);if(t)throw d.warn({operation:_s},`\u26D4 --orca was passed but ${i}`),new O({status:"refused",reason:s,agentMode:j.source},2,{operation:_s,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 Ff(r);return{probe:n,registered:o.registered,visibility:o.visibility}},w_=(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(`
|
|
434
|
+
`)},k_=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Ik(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await Lf(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 Jr?r.code:void 0}}},b_=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,R_=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=Rp();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=wf(i),l=r.length===1&&t.visibility!=="hide",u=Uf();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Wf({cwd:m,title:Vf({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Bf(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:b_(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof Jr&&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 Jr?f.code:void 0})}}return a},S_=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}`)}},Ok=async e=>{await Ns`mkdir -p ${e}`},E_=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Wr(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},P_=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await Ns({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},x_=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")},Sp=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:W.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:W.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:W.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:W.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:W.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:W.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:W.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:W.array(W.object({branch:W.string(),base:W.string(),source:W.enum(Rk)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:W.array(W.string()).describe("List of created git worktree branches"),count:W.number().describe("Number of git worktrees created"),orcaOpened:W.array(W.object({branch:W.string(),layout:W.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:W.array(W.object({branch:W.string(),reason:W.enum(d_),code:W.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:W.array(W.object({branch:W.string(),path:W.string(),fix:W.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:qa});import{z as or}from"zod";var Ya=async()=>{await K();let[e,t]=await Promise.all([be("release"),be("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await T_(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
|
|
435
435
|
|
|
436
|
-
${
|
|
436
|
+
${C_(r).join(`
|
|
437
437
|
`)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
|
|
438
438
|
|
|
439
439
|
${t.join(`
|
|
440
440
|
`)}`),d.info(n.join(`
|
|
441
441
|
|
|
442
|
-
`));let o={worktrees:r,count:r.length,features:t};return{content:b(JSON.stringify(o,null,2)),structuredContent:o}},
|
|
443
|
-
`).filter(r=>r.trim().length>0),A_=async e=>{let[t,r]=await Promise.all([Dk(e.worktreePath),Dk(e.mainRoot)]);t.length>0&&Nr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Nr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Bt();n!=="ready"&&Nr(`run \`infra-kit worktrees remove ${Be(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},O_=async e=>{let t=Be(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${x_}; ${t} && { sleep ${T_}; exit; }`;try{return(await If(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Vr?new g(n,{operation:Ik,remediation:`run \`infra-kit worktrees remove ${Be(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Nk=async e=>{let t=await $_();await A_(t),y.addOption("--self",!0),await G(e,`Remove ${t.branch} at ${t.worktreePath} and close every Orca tab in it (this terminal included)?`),e||y.addOption("--yes",!0);let r=await O_(t);d.info(`\u27A1\uFE0F Removal of ${t.branch} handed off to Orca (main checkout tab "ik: remove ${t.branch}")`),y.print();let n={branch:t.branch,worktreePath:t.worktreePath,terminal:r};return{content:b(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var D_=e=>{if(ge()){if(e.all)throw new O({status:"refused",agentMode:j.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 O({status:"argument_required",argument:"versions",agentMode:j.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"})}},I_=(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(", ")}`})},N_=async(e,t)=>{let r=await ai(t.map(n=>`${e}/${n}`));if(r!==null)throw new O({status:"refused",reason:"orca_caller_inside_target",agentMode:j.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`})},__=e=>e?e.split(",").map(t=>Pe(ve(t.trim()))):[],M_=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Ja):[],j_=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&y.addOption("--versions",$t(r)),t.length>0&&y.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Ya=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 Nk(t)}await Ne({operation:"remove worktrees"}),await H(),D_({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([we("release"),we("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),y.print();let v={removedWorktrees:[],failedWorktrees:[],count:0};return{content:b(JSON.stringify(v,null,2)),structuredContent:v}}let l=await A(),u=`${l}${fe}`,p=[];if(r)p=c;else if(n||o)p=[...__(n),...M_(o)];else{y.setInteractive();let[v,E]=await Promise.all([pe(),V()]),k=new Map(E.map(h=>[h.branch,h.type]));p=await Ht([...me({branches:i,descriptions:v,types:k}),...a.map(h=>({value:h,label:h,type:"feature"}))],{required:!0})}I_(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):j_(p),await N_(u,p),await G(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await $r({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return is(f),y.print(),as({result:f,operation:"remove worktrees"})}catch(i){throw Ae(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"}))}},Sp=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:ze.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:ze.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:ze.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:ze.array(ze.string()).describe("List of removed git worktree branches"),failedWorktrees:ze.array(ze.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ze.number().describe("Number of git worktrees removed"),handedOff:ze.object({branch:ze.string(),worktreePath:ze.string(),terminal:ze.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Ya});import{z as Ns}from"zod";var za=async e=>{let{confirmedCommand:t}=e;await Ne({operation:"sync worktrees"}),await H();try{let r=await we("release"),n=await A(),o=`${n}${fe}`,s=await _i();await G(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=F_({releasePRsList:s,currentWorktrees:r}),a=await $r({branches:i,worktreeDir:o,projectRoot:n});return is(a),y.print(),as({result:a,operation:"sync worktrees"})}catch(r){throw Ae(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"}))}},F_=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Br(s)).filter(s=>!t.includes(s))}},Ep=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:Ns.array(Ns.string()).describe("List of removed worktree branches"),failedWorktrees:Ns.array(Ns.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Ns.number().describe("Number of worktrees removed during sync")},handler:za});var Pp=[{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"}],Er=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Fl,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:rd,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:ld,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Dd,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:qd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:zd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:$d,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Od,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:md,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Qd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Vd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Gd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:bp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Rp,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Sp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Ep,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:sd,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Kf,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Lc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:od,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:id,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Ml,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:hp,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:ap,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Gu,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Pl,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:yp,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:Il,mcpExposed:!1,mutating:!1,groupPath:["change-stats"]},{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 xp=e=>Er.filter(t=>t.menuGroup===e),Tp=e=>Er.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var L_=(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},_k=e=>Pp.flatMap(({key:t,label:r})=>xp(t).flatMap(n=>{let o=L_(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Cp from"node:process";var B_="MODULE_TYPELESS_PACKAGE_JSON",U_=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Mk=!1,$p=()=>{if(Mk)return;Mk=!0;let e=Cp.emitWarning.bind(Cp);Cp.emitWarning=((t,...r)=>{U_(r[0],r[1])!==B_&&e(t,...r)})};import{Command as zj,InvalidArgumentError as Lb,Option as jb}from"commander";import{resolve as Xj}from"node:path";import je from"node:process";import{cd as Zj}from"zx";import jk from"node:process";import{$ as W_}from"zx";var Ap=async()=>{let e=await ee(),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 ne(i.path)}))),r=t.at(-1)?.exists===!0,n=await Go(e.userProject,r),o=r?Jo(n):"";d.info(`Project name: ${e.projectName}
|
|
442
|
+
`));let o={worktrees:r,count:r.length,features:t};return{content:b(JSON.stringify(o,null,2)),structuredContent:o}},T_=async e=>{let[t,r]=await Promise.all([G(),me()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=Q(o);if(!s)return[];let i=ne(s),a=n.get(o)||"regular",c=r.get(le(s))||null;return[{version:i,type:a,description:c}]})},C_=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=Mo(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Ep=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:or.array(or.object({version:or.string().describe("Release version"),type:or.enum(["regular","hotfix"]).describe("Release type"),description:or.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:or.number().describe("Number of release worktrees"),features:or.array(or.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:Ya});import{z as Xe}from"zod";import $_ from"node:fs/promises";import{$ as A_}from"zx";var _k="remove this worktree",O_=2,D_=3,za=async e=>{try{return await $_.realpath(e)}catch{return e}},Mr=(e,t)=>{throw new g(void 0,{operation:_k,remediation:e,stderrExcerpt:t})},I_=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=Dt([e]);return Wr(e)&&t?["--versions",t]:Mr("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`)},N_=async()=>{let e=await za(await $()),t=await za(await Ae(e));e===t&&Mr("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 st(t))await za(o.path)===e&&(r=o.branch);if(!r)return Mr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await za(`${t}${ge}/${r}`);return n!==e&&Mr("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:I_(r)}},Nk=async e=>(await A_({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
|
|
443
|
+
`).filter(r=>r.trim().length>0),__=async e=>{let[t,r]=await Promise.all([Nk(e.worktreePath),Nk(e.mainRoot)]);t.length>0&&Mr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Mr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Wt();n!=="ready"&&Mr(`run \`infra-kit worktrees remove ${Ue(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},M_=async e=>{let t=Ue(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${O_}; ${t} && { sleep ${D_}; exit; }`;try{return(await _f(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Jr?new g(n,{operation:_k,remediation:`run \`infra-kit worktrees remove ${Ue(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Mk=async e=>{let t=await N_();await __(t),h.addOption("--self",!0),await J(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 M_(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:b(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var j_=e=>{if(he()){if(e.all)throw new O({status:"refused",agentMode:j.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 O({status:"argument_required",argument:"versions",agentMode:j.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"})}},F_=(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(", ")}`})},L_=async(e,t)=>{let r=await li(t.map(n=>`${e}/${n}`));if(r!==null)throw new O({status:"refused",reason:"orca_caller_inside_target",agentMode:j.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`})},B_=e=>e?e.split(",").map(t=>Te(ke(t.trim()))):[],U_=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Ha):[],W_=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&h.addOption("--versions",Dt(r)),t.length>0&&h.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Xa=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 Mk(t)}await _e({operation:"remove worktrees"}),await K(),j_({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([be("release"),be("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:b(JSON.stringify(y,null,2)),structuredContent:y}}let l=await $(),u=`${l}${ge}`,p=[];if(r)p=c;else if(n||o)p=[...B_(n),...U_(o)];else{h.setInteractive();let[y,E]=await Promise.all([me(),G()]),k=new Map(E.map(A=>[A.branch,A.type]));p=await Yt([...fe({branches:i,descriptions:y,types:k}),...a.map(A=>({value:A,label:A,type:"feature"}))],{required:!0})}F_(p,c);let m=p.length===c.length;m?h.addOption("--all",!0):W_(p),await L_(u,p),await J(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let f=await Or({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return cs(f),h.print(),ls({result:f,operation:"remove worktrees"})}catch(i){throw Oe(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"}))}},Pp=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:Xe.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:Xe.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:Xe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Xe.array(Xe.string()).describe("List of removed git worktree branches"),failedWorktrees:Xe.array(Xe.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Xe.number().describe("Number of git worktrees removed"),handedOff:Xe.object({branch:Xe.string(),worktreePath:Xe.string(),terminal:Xe.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Xa});import{z as Ms}from"zod";var Za=async e=>{let{confirmedCommand:t}=e;await _e({operation:"sync worktrees"}),await K();try{let r=await be("release"),n=await $(),o=`${n}${ge}`,s=await ji();await J(t,"Are you sure you want to proceed with these worktree changes?"),t||h.addOption("--yes",!0);let{branchesToRemove:i}=V_({releasePRsList:s,currentWorktrees:r}),a=await Or({branches:i,worktreeDir:o,projectRoot:n});return cs(a),h.print(),ls({result:a,operation:"sync worktrees"})}catch(r){throw Oe(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"}))}},V_=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Wr(s)).filter(s=>!t.includes(s))}},xp=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: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:Za});var Tp=[{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"}],xr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Bl,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:od,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:dd,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:Nd,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:zd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Zd,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Od,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Id,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:gd,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:tp,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Jd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Kd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:Sp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Ep,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Pp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:xp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:ad,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:qf,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Uc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:id,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:cd,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Fl,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:vp,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:lp,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Ku,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Tl,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:wp,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:_l,mcpExposed:!1,mutating:!1,groupPath:["change-stats"]},{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 Cp=e=>xr.filter(t=>t.menuGroup===e),$p=e=>xr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var G_=(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},jk=e=>Tp.flatMap(({key:t,label:r})=>Cp(t).flatMap(n=>{let o=G_(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Ap from"node:process";var J_="MODULE_TYPELESS_PACKAGE_JSON",K_=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Fk=!1,Op=()=>{if(Fk)return;Fk=!0;let e=Ap.emitWarning.bind(Ap);Ap.emitWarning=((t,...r)=>{K_(r[0],r[1])!==J_&&e(t,...r)})};import{Command as oF,InvalidArgumentError as Vb,Option as Ub}from"commander";import{resolve as sF}from"node:path";import Fe from"node:process";import{cd as iF}from"zx";import Lk from"node:process";import{$ as H_}from"zx";var Dp=async()=>{let e=await ee(),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 oe(i.path)}))),r=t.at(-1)?.exists===!0,n=await Ko(e.userProject,r),o=r?Ho(n):"";d.info(`Project name: ${e.projectName}
|
|
444
444
|
`),d.info(`Config merge chain (later overrides earlier):
|
|
445
|
-
`);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},
|
|
446
|
-
`)
|
|
447
|
-
`,"
|
|
448
|
-
|
|
449
|
-
`))},
|
|
450
|
-
`),
|
|
451
|
-
`)
|
|
452
|
-
|
|
445
|
+
`);for(let i of t){let a=i.exists?" [\u2713]":" [ ]",c=i.path===e.userProject&&o!==""?` ${o}`:"";d.info(`${a} ${i.label.padEnd(22)} ${w(i.path)}${c}`)}let s={projectName:e.projectName,layers:t.map(i=>({label:i.label,path:i.path,exists:i.exists})),hasOverrides:n.hasOverrides,overrideKeys:n.overrideKeys};return{content:[{type:"text",text:JSON.stringify(s,null,2)}],structuredContent:s}},Ip=async()=>{let e=await ee(),t=Lk.env.EDITOR||Lk.env.VISUAL||"vi",r=await wn(e);r.createdConfig&&d.info(kn(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await H_({stdio:"inherit"})`${t} ${e.userProject}`,Lt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Np=async({key:e,global:t})=>{Ii(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Ni(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${Eo[r]} (${w(n)})`:`${e} is not set in the ${Eo[r]} (${w(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:b(JSON.stringify(i,null,2)),structuredContent:i}};import Kk from"node:fs/promises";import js from"node:path";import aM from"node:process";import{pathToFileURL as cM}from"node:url";import{execFile as X_,spawn as Z_}from"node:child_process";import ir from"node:fs/promises";import Q_ from"node:os";import sr from"node:path";import Wk from"node:process";import{promisify as eM}from"node:util";import Bk from"node:fs/promises";import q_ from"node:path";import{pathToFileURL as Y_}from"node:url";var z_=".infra-kit-import-from-app.mjs",Uk=async(e,t)=>{let r=q_.join(e,z_);await Bk.writeFile(r,`export const resolveHere = (specifier) => import.meta.resolve(specifier)
|
|
446
|
+
`);try{let{resolveHere:n}=await import(Y_(r).href);return await import(n(t))}finally{await Bk.rm(r,{force:!0})}};var tM=eM(X_),Vk="3.39.0",rM=10*1024*1024,nM=960,oM=60,_p=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,sM=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${_p(e)}`}},Wn=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},iM=(e,t,r)=>new Promise((n,o)=>{let s=Z_(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}`))})}),ec={run:iM,capture:async(e,t,r)=>{let{stdout:n}=await tM(e,t,{...r,maxBuffer:rM});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{Wk.stdout.write(`${e}
|
|
447
|
+
`)}},Qa=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),Gk=async e=>{let t=JSON.parse(await ir.readFile(sr.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},jp=async e=>{let t=await ir.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=sr.join(e,r.name);return r.name==="node_modules"?ir.rm(n,{recursive:!0,force:!0}):jp(n)}))},Mp=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 ir.readFile(sr.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`)},Fp=({root:e,service:t,project:r,scriptDir:n,env:o=Wk.env,deps:s=ec})=>{let i=async(v,R,T,S={})=>{s.log(`COMMAND: ${[R,...T].join(" ")}`);try{await s.run(R,T,{cwd:S.cwd??e,env:S.env??o})}catch(B){throw new Error(`${v} failed: ${B.message}`)}},a=async(v,R,T={})=>{let{attempts:S=8,initialDelaySeconds:B=3,maxDelaySeconds:Z=60}=T,we=async re=>{try{return await R()}catch(bt){if(re>=S)throw new Error(`${v} failed after ${S} attempts: ${bt.message}`);let Ws=Math.min(Z,B*2**(re-1)),Vs=Math.round((Ws/2+s.random()*Ws/2)*10)/10;return s.log(`Attempt ${re}/${S} failed. Retrying in ${Vs}s...`),await s.sleep(Vs*1e3),we(re+1)}};return we(1)},c=async(v,R,T=o)=>{s.log(`COMMAND: aws ${R.join(" ")}`),await a(v,()=>s.run("aws",R,{cwd:e,env:Qa(T)}))},l=async(v,R={})=>{await i(`aws ${v.slice(0,2).join(" ")}`,"aws",v,{cwd:R.cwd,env:Qa(R.env??o)})},u=async v=>{let R=await Promise.all(v.map(async T=>{try{let S=await s.capture("aws",["ssm","get-parameter","--name",T,"--query","Parameter.Value","--output","text"],{cwd:e,env:Qa(o)});return[T,S.trim()]}catch(S){throw new Error(`SSM parameter ${T}: ${S instanceof Error?S.message:String(S)}`)}}));return Object.fromEntries(R)},p=async v=>{let R=[`turbo@${await Gk(e)}`,...v?[`serverless@${Vk}`]:[]];await i("Install tools","pnpm",["add","-g",...R])},m=async(v,R)=>{let T=sr.join(e,"out"),S={...o,...R.buildEnv},B=R.buildTask??S.TURBO_BUILD_TASK??"build";return await ir.rm(T,{recursive:!0,force:!0}),await i(`Prune to ${v}`,"turbo",["prune",v],{env:S}),await i("Install dependencies","pnpm",["install"],{cwd:T,env:S}),await i(`Build ${v}`,"pnpm",["exec","turbo",B,`--filter=${v}`,"--env-mode=loose"],{cwd:T,env:S}),R.installProd&&(s.log("COMMAND: remove every node_modules under ./out"),await jp(T),await i("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:T,env:S}),await i("Show node_modules size","du",["-sm","./node_modules/"],{cwd:T})),T},f=(v,R,T)=>({stage:v,outDir:R,appDir:T,importFromApp:S=>Uk(T,S)}),y=async(v,R,T)=>{if(R!==void 0){s.log(`Running ${v} hooks...`);try{await R(T)}catch(S){throw new Error(`${v} hooks failed: ${S.message}`)}s.log(`${v} hooks completed successfully`)}},E=async v=>{let{app:R,appPath:T}=await Mp(e,n,v);await p(!0);let S={...o,...v.buildEnv},B=await m(R,{installProd:!0,buildTask:v.buildTask,buildEnv:v.buildEnv}),Z=f(v.stage,B,sr.join(B,T));await y("Pre-deployment",v.preDeploy,Z),await i("Deploy with Serverless","serverless",["deploy","--stage",v.stage,"--force"],{cwd:Z.appDir,env:S}),v.restApiId===void 0?s.log(`Skipping API Gateway deployment for ${R}: no restApiId.`):await c("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",v.restApiId,"--stage-name","api"],S),await y("Post-deployment",v.postDeploy,Z)},k=async v=>{let{app:R,appPath:T}=await Mp(e,n,v);await p(!1);let S={...o,...v.buildEnv},B=await m(R,{installProd:!1,buildTask:v.buildTask,buildEnv:v.buildEnv}),Z=f(v.stage,B,sr.join(B,T)),we=`s3://${v.bucket}${v.destPath??""}`,re=v.sourcePath??"./dist";await i("Sync to S3","aws",["s3","sync",re,we,...v.syncFlags??[],"--only-show-errors"],{cwd:Z.appDir,env:Qa(S)}),await c("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",v.cloudfrontId,"--paths",v.invalidationPath??"/*"],S),await y("Post-deployment",v.postDeploy,Z)},A=async(v,R,T)=>{let S=await ir.mkdtemp(sr.join(Q_.tmpdir(),"infra-kit-lambda-")),B=sr.join(S,"response.json"),Z=["lambda","invoke","--function-name",v.functionName,...T===void 0?[]:["--region",T],"--cli-binary-format","raw-in-base64-out","--payload",v.payload??R,"--cli-read-timeout",String(nM),"--cli-connect-timeout",String(oM),B],we=Date.now();s.log(`COMMAND: aws ${Z.join(" ")}`);try{let re=await s.capture("aws",Z,{cwd:e,env:{...o,AWS_PAGER:""}}).then(sM,kc=>`aws CLI failed: ${_p(kc instanceof Error?kc.message:String(kc))}`),bt=await ir.readFile(B,"utf-8").catch(()=>""),Ws=((Date.now()-we)/1e3).toFixed(1),Vs=re!==void 0&&bt?`; response: ${_p(bt)}`:"";return{outcome:`${v.functionName} (${Ws}s)`,failure:re===void 0?void 0:re+Vs}}finally{await ir.rm(S,{recursive:!0,force:!0})}};return{root:e,service:t,project:r,ssm:u,aws:l,run:(v,R,T={})=>s.run(v,R,{cwd:T.cwd??e,env:T.env??o}),capture:(v,R,T={})=>s.capture(v,R,{cwd:T.cwd??e,env:T.env??o}),retry:a,skip:v=>{throw new Wn(v)},pruneAndBuild:m,deployBackendApi:E,deployFrontendUi:k,invokeLambdas:async v=>{let{region:R,payload:T="{}",blocking:S=[],steps:B=[]}=v;for(let Z of S){let{outcome:we,failure:re}=await A(Z,T,R);if(re!==void 0)throw new Error(`Lambda ${we} failed: ${re}`);s.log(`Lambda ${we} OK`)}for(let Z of B){let we=await Promise.all(Z.map(re=>A(re,T,R).catch(bt=>({outcome:re.functionName,failure:String(bt)}))));for(let{outcome:re,failure:bt}of we)s.log(bt===void 0?`Lambda ${re} OK`:`Warning: Lambda ${re} failed, continuing: ${bt}`)}}}};var Jk=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),lM=async(e,t)=>{let r=js.join(e,"devops","scripts",`deploy-${t}.sh`);try{await Kk.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},uM=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
|
|
448
|
+
`,"%0A")}`,dM=(e,t)=>{let r=(e??"").split(`
|
|
449
|
+
`).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(uM(n));return Object.fromEntries(r)},pM=async e=>{try{await Kk.access(e)}catch{throw new g(void 0,{operation:`run ${js.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(cM(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${js.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},Lp=async e=>{let{service:t,env:r=aM.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(he()&&r.INFRA_KIT_DEPLOY_VIA!==Rs)throw new O({status:"refused",agentMode:j.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??ec,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...dM(s,o.log)},c=await vt(n),l=c?.services[t]?.deploy;if(l===void 0)await o.run("sh",[await lM(n,t)],{cwd:n,env:a});else{let u=await pM(js.join(n,l)),p=Fp({root:n,service:t,project:c?.project,scriptDir:js.dirname(l),env:a,deps:o});try{await u(p)}catch(m){if(!(m instanceof Wn))throw m;return d.info(`\u23ED\uFE0F ${t} skipped: ${m.message}`),Jk({status:"skipped",service:t,reason:m.message})}}return d.info(`\u2705 ${t} deployed`),Jk({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as Fs}from"@slip-stream-kit/config/internal";import rc from"node:fs/promises";import nc from"node:path";var Bp=async e=>{try{return await rc.readFile(e,"utf-8")}catch{return}},tc=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),mM={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},Hk=async(e,t)=>(await Promise.all(t.map(async n=>{let o=nc.join(e,n);return(await Bp(o))?.startsWith(Fn)?[{path:n,absolute:o}]:[]}))).flat(),fM=async(e,t)=>t.replaceV1!==!0?[]:(await Hk(e,yd)).map(r=>({...r,status:"removed"})),gM=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Bp(nc.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${Fs} do not exist: ${n.join(", ")}`)},hM=async(e,t)=>{if(t.replaceV1===!0)return;let r=await Hk(e,vd);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 ${Fs} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},Up=async(e={})=>{let t=e.cwd??await $(),r=await vt(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Fs} at ${t}, nothing to generate.`),tc({status:"missing-config",ok:!!e.check,files:[]});await hM(t,r),await gM(t,r);let n=await Promise.all(bd(r).map(async a=>{let c=nc.join(t,a.path),l=await Bp(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await fM(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 ${Fs}.`),tc({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${Fs}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${mM[a.status]})`);return tc({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await rc.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await rc.mkdir(nc.dirname(a.absolute),{recursive:!0}),await rc.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return tc({status:"written",ok:!0,files:i})};var qk="https://dashboard.doppler.com/workplace/projects",yM=(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}"): ${qk}/${e}`],Wp=async({env:e})=>{let r=!!(await Qe())?.envs[e];await $f(e);let n=await dr(),o=await Ut();r?d.info(`Removed the "${e}" service token from ${w(o)}.`):d.info(`No "${e}" service token was stored in ${w(o)} \u2014 nothing to remove.`);for(let i of yM(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${qk}/${n}`};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}};import vM from"@inquirer/confirm";import wM from"@inquirer/input";import kM from"@inquirer/password";import bM from"@inquirer/select";import RM from"node:fs/promises";import kt from"node:process";import{$ as oc}from"zx";var SM=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Yk(),source:"stdin"};if(t){let n=kt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!kt.stdin.isTTY){let n=await Yk();if(n)return{token:n,source:"stdin"};if(!X())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 h.setInteractive(),{token:(await _(n=>kM({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:kt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Yk=async()=>{let e=[];kt.stdin.setEncoding("utf8");for await(let t of kt.stdin)e.push(t);return e.join("").trim()},Vp="DOPPLER_CONFIG",EM=3e4,PM=async(e,t,r)=>{let n=oc.quiet;oc.quiet=!0;let o;try{o=(await oc({env:so(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(EM)).stdout}catch(s){throw xM(s,r)}finally{oc.quiet=n}return Bc(o)},xM=(e,t)=>{let r=Zm(e)??(e instanceof Error?e.message:String(e));if(Of(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Df(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(`
|
|
450
|
+
`))},TM=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Vp}.`,"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(`
|
|
451
|
+
`),Xk=async(e,t,r,n)=>{let o=await PM(e,t,r);Lc(o,r);let s=o.some(([i])=>i===Vp);if(!s&&!n)throw new Error(TM(r));return s},zk="\0new-env",CM=async()=>{if(X()||!kt.stdin.isTTY)throw new O({status:"argument_required",argument:"env",agentMode:j.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([Jf(),Qe()]),r=Math.max(0,...e.map(({env:s})=>s.length));h.setInteractive();let n=await _(s=>bM({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:zk}]},s),{output:kt.stderr,whenHeadless:"refuse"});return n!==zk?n:(await _(s=>wM({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:kt.stderr,whenHeadless:"refuse"})).trim()},$M=async(e,t,r)=>_(n=>vM({message:`Replace the "${e}" token ${$e(t)} with ${$e(r)}?`,default:!0},n),{output:kt.stderr,whenHeadless:"refuse"}),AM=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${$e(r)})`;case"replaced":return`Replaced the "${e}" service token ${$e(n??"")} \u2192 ${$e(r)}`;case"unchanged":return`The "${e}" service token is already ${$e(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${$e(n??"")} \u2014 nothing was written`;default:return We(t)}},Gp=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await dr(),s=e??await CM(),{token:i,source:a}=await SM({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Xk(i,o,s,n),l=(await Qe())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await $M(s,l,i)?u="kept":(await Oc({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Ut();d.info(`${AM(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Vp} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:$e(i),previousRedactedToken:l===void 0?null:$e(l),storePath:p,scopeVerified:c};return h.print(),{content:b(JSON.stringify(m,null,2)),structuredContent:m}},OM=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,Zk=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?OM(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},DM=e=>(e instanceof Error?e.message:String(e)).split(`
|
|
452
|
+
`)[0]??"",IM=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",NM=async(e,t,r,n)=>{let o=$e(e.token);try{let s=await Xk(e.token,t,e.env,n);return{env:e.env,status:IM(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:DM(s)}}},Jp=async({fromFile:e,force:t})=>{let r=await dr(),n=Zk(await RM.readFile(e,"utf8")),o=await Qe(),s=await Promise.all(n.map(p=>NM(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 Oc(i);let a=await Ut(),c=Math.max(...s.map(({env:p})=>p.length));d.info(`Token import from ${w(e)} \u2192 ${w(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(`${w(e)} still holds live tokens in plain text \u2014 delete it.`);let l=s.filter(p=>p.status==="failed").length;l>0&&(kt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}};var Kp=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 $d(n);if(r&&h.addOption("--from",p),Cd(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"?xa({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Ta({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Hp=async e=>Kp(e,"all"),qp=async e=>Kp(e,"selected"),sc=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.`),Kp({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as eb}from"@slip-stream-kit/config/internal";import Yp from"node:fs/promises";import Vn from"node:path";import Qk from"node:process";import{pathToFileURL as _M}from"node:url";var tb="~/projects",zp=async(e={})=>{if(e.init){await jM(e.cwd);return}await MM()},MM=async()=>{let e=Pn(),t=await oe(e);if(d.info(`Factory config: ${w(e)} ${t?"[\u2713]":"[ ]"}`),!t){d.info("\nNot found \u2014 run `infra-kit vendor config --init` to scaffold it."),Qk.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await ea(),s=xn(r),i=await oe(s),a=Vn.join(s,n),c=await oe(a);d.info(`workspaceDir: ${r} (resolved: ${s}) ${i?"[\u2713 exists]":"[ ] not found"}`),d.info(`Source: ${c?"[\u2713]":"[ ]"} ${n} ${w(a)}${c?"":" (not found \u2014 clone it)"}`),d.info("Targets:");let l=i&&c;for(let u of o){let p=Vn.join(s,u),m=await oe(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",y=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${y}`)}l||(Qk.exitCode=1)},jM=async e=>{let t=Pn();if(await oe(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await $(),n=await FM(r);await Yp.mkdir(Vn.dirname(t),{recursive:!0}),await Yp.writeFile(t,LM(Vn.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${eb}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${tb}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Vn.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.")},FM=async e=>{try{let t=Vn.join(e,eb),r=await Yp.stat(t),s=(await import(`${_M(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[]},LM=(e,t)=>`${JSON.stringify({workspaceDir:tb,source:e,targets:t},null,2)}
|
|
453
|
+
`;import{existsSync as Hj}from"node:fs";import qj from"node:fs/promises";import $b from"node:path";import Ab from"node:process";import{z as Yj}from"zod";import{chmodSync as HM,copyFileSync as qM,lstatSync as YM,mkdirSync as db,readdirSync as zM,readlinkSync as XM,rmSync as ZM,rmdirSync as pb,symlinkSync as QM,unlinkSync as ej,writeFileSync as tj}from"node:fs";import Pe from"node:path";import{lstatSync as BM,readlinkSync as rb}from"node:fs";import UM from"node:path";var WM=new Set(["ENOENT","ENOTDIR"]),ic=e=>{let t;try{t=BM(e)}catch(r){if(WM.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:rb(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:_r(e)}:{kind:"other"}},nb=(e,t)=>{let r=UM.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:rb(r)}:{kind:"file",executable:t.mode==="100755",sha:_r(r)};return{...t,fingerprint:n}},ob=(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 VM}from"zx";var z=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await VM({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},ac=e=>e.slice(0,7),nt=e=>e.split("\0").filter(t=>t.length>0);import GM from"node:path";var Xp=`${se}/`,ar=`${se}/README.md`,Ls=`${se}/${ze}`,ib=e=>e.startsWith(Xp),sb=e=>{let t=GM.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},ab=e=>{let t=sb(e.path),r=e.target===void 0?t:sb(e.target);return{path:t,target:r,vendored:ib(r),module:e.module??null}},cb=e=>e.copy.map(ab),Bs=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Us=(e,t)=>e.filter(r=>!Bs(r.path,t)),cc=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Gn=e=>[...new Set(e)].sort(),lb=e=>e.startsWith(Xp)?e.slice(Xp.length):null;var lc=e=>`# vendor/ \u2014 mirrored from ${e}
|
|
453
454
|
|
|
454
455
|
**DO NOT EDIT files in this folder here.**
|
|
455
456
|
|
|
@@ -460,19 +461,19 @@ fail \`ik vendor check\` in CI.
|
|
|
460
461
|
To change a vendored package, edit it in \`${e}\` and re-run the sync there.
|
|
461
462
|
|
|
462
463
|
See \`.sync-manifest.json\` for the source commit and per-file checksums.
|
|
463
|
-
`;var
|
|
464
|
-
`).trim()||String(e)},
|
|
465
|
-
`).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},
|
|
466
|
-
`)[0]??"git rev-parse failed"}}},
|
|
467
|
-
`).slice(0,
|
|
468
|
-
${
|
|
469
|
-
`)},
|
|
470
|
-
`),D(e)),tF=e=>e.description("List all release branches").action(async()=>{D(await xa())}),rF=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".',Qj,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Fu),o=n.length>0?n:void 0;D(await Aa({releases:o,confirmedCommand:t.yes}))}),nF=e=>{if(e==="")return e;try{return Rr(e)}catch(t){throw t instanceof On?new Lb(t.message):t}},oF=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Lb("Expected a positive whole number of days.");return t},sF=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)',nF).option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await Oa({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Bb=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Qt.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"),iF=e=>Bb(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{D(await Jp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),aF=e=>Bb(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=>{D(await Kp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),cF=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=>{D(await wa({version:t.version,confirmedCommand:t.yes}))}),lF=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=>{D(await Na({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),uF=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await za({confirmedCommand:t.yes}))}),dF=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=>{D(await Ka({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),pF=e=>e.description("List all git worktrees with detailed information").action(async()=>{D(await Ha())}),mF=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=>{D(await Ya({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),fF=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=>{D(await qp({init:t.init}))}),gF=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Va();D(t),t.structuredContent.ok||(je.exitCode=1)}),hF=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 lm({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!bt(a))throw a;d.info("Operation cancelled.");return}D(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(je.exitCode=1)}),yF=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{D(await Ap())}),vF=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{D(await Op())}),wF=new Set(["version"]),hc=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},mm=()=>{let e=new zj().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");eF(t.command("merge-dev")),tF(t.command("list")),rF(t.command("create")),sF(t.command("edit")),iF(t.command("deploy-all")),aF(t.command("deploy-selected")),cF(t.command("deliver")),lF(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");dF(r.command("add")),pF(r.command("list")),mF(r.command("remove")),uF(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");yF(n.command("path")),vF(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=>{D(await Ii({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)=>{D(await _l({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)=>{D(await Dp({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=>{D(await nc({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=>{D(await nc({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)"),je.exitCode=1;return}let c=await xi({all:a.all,root:a.root,fix:a.fix,design:a.design});D(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&(je.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=>{D(await jp({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 Lp({check:a.check});D(c),c.structuredContent.ok||(je.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");gF(i.command("check")),fF(i.command("config")),hF(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 ca({fix:!!a.fix});ar.enabled||Jl(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(je.exitCode=1),D(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=!!(je.stdout.isTTY&&je.stdin.isTTY);await l({...c,appName:a},u,ar.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{D(await Ni())}),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)=>{D(await pa({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 jb("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new jb("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){D(await ep());return}D(await Fa({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()=>{D(await Ga())}),e.command("change-stats").description("Change-failure baseline for this git repo: agent vs human commits, revert and 72h follow-up-fix rates").option("--since <days>",`Window in days, ending now (default ${bo})`,oF).action(async a=>{D(await Ai({since:a.since}))}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{D(await ga())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{D(await Jf())}),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=>{Fb(await Mc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Fb(await fa())}),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.");D(await Vp({fromFile:c.fromFile,force:c.force}));return}D(await Wp({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=>{D(await ha({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=>{D(await Bp({env:a}))});for(let a of e.commands)Ym(a);return dm(e),pm(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&Zj(Xj(je.cwd(),l)),y.start(hc(c)),ar.enabled=!!c.optsWithGlobals().json,ar.enabled&&(d.level="warn"),j.source=Zs({env:je.env,stdinIsTTY:je.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),wF.has(hc(c))||await vu()}),e.hook("postAction",(a,c)=>{let l=hc(c);if(Tp(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Nb({equivalent:mc(f,!0)})}),e};import kF from"node:process";var bF={exit:kF.exit,emit:D,logger:d},Ub=(e,t=bF)=>Ae(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof O?(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 fm=(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 RF from"node:fs";import gm from"node:path";import Jn from"node:process";var Gb=new Set([...pf,Hn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Jb=null,yc=new Set,hm=null,Wb=!1;var Vb=e=>{try{return RF.statSync(e)}catch{return null}},SF=()=>{if(Wb)return null;try{return Fr()}catch{return Wb=!0,d.debug(`session-env: ${Hn} unset \u2014 no overlay`),null}},EF=e=>{let t=gm.join(e,Mr),r=gm.join(e,Ws),n=Vb(t),o=Vb(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?xm(gm.join(e,Vs),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"}},PF=e=>e.kind==="load"?{kind:"load",vars:Em(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Pm(e.file),signature:e.signature}:e;var xF=()=>{let e=SF();if(e===null)return{kind:"no-session"};let t=EF(e);return t.signature===hm?null:PF(t)},TF=()=>{for(let e of yc){let t=Jb[e];t===void 0?delete Jn.env[e]:Jn.env[e]=t}yc.clear()},CF=(e,t,r)=>{if(Gb.has(t)){e.skipped.push(t);return}Jn.env[t]=r,yc.add(t),e.set.push(t)},$F=(e,t)=>{if(Gb.has(t)){e.skipped.push(t);return}delete Jn.env[t],yc.add(t),e.unset.push(t)},AF=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))CF(t,r,n);if(e.kind==="clear")for(let r of e.unset)$F(t,r);return t},OF=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,ym=(e=xF())=>{if(Jb??={...Jn.env},e===null||e.kind==="no-session"||e.signature===hm)return{set:[],unset:[],changed:!1};TF();let{set:t,unset:r,skipped:n}=AF(e);return hm=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(", ")}] (${OF(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as ZF}from"chalk";import{spawn as QF}from"node:child_process";import Fe from"node:process";import{Chalk as DF}from"chalk";var Kn=new DF({level:1}),nt={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."},IF={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"}},Kb={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Hb={unicode:"\u2500",ascii:"-"},NF=3,vm=e=>e,_F={ok:e=>Kn.green(e),findings:e=>Kn.yellow(e),failed:e=>Kn.red(e),cancelled:e=>Kn.gray(e)},km=e=>e?{dim:t=>Kn.dim(t),bold:t=>Kn.bold(t)}:{dim:vm,bold:vm},MF=(e,t)=>e?_F[t]:vm,wm=e=>[...e].length,jF=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return wm(e)<=r?e:[...e].slice(0,r).join("")},qb=e=>{let t=km(e.color===!0).dim,r=IF[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(jF(n,e.width))},Yb=(e,t={})=>{let r=km(t.color===!0);return`${r.dim(nt.reproPrefix.trim())} ${r.bold(e)}`},FF=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,LF=(e,t)=>e==="findings"?t!=null?`${t} ${nt.findingsSuffix}`:nt.findingsPlain:{ok:nt.ok,failed:nt.failed,cancelled:nt.cancelled}[e],BF=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<NF?"":` ${n(r.repeat(o))}`},zb=e=>{let t=e.color===!0,r=km(t),n=MF(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?nt.reproPrefix:nt.nonReproPrefix,i=o?Kb[e.outcome].ascii:Kb[e.outcome].unicode,a=LF(e.outcome,e.findingsCount),c=[FF(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
471
|
-
`)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${
|
|
472
|
-
`)};var
|
|
473
|
-
`,
|
|
464
|
+
`;var JM=new Set(["100644","100755","120000"]),KM=(e,t)=>{let r=new Map;for(let n of nt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!JM.has(s)||Bs(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},Zp=async(e,t,r)=>{let n=await z(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return KM(n,r)},ub=async e=>nt(await z(e,["--literal-pathspecs","ls-files","-z","--",se]));var Jn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],mb=e=>{let t=ic(e);t!==null&&(t.kind==="other"?pb(e):ej(e))},rj=(e,t,r)=>{let n=Pe.join(e,r.source),o=Pe.join(t,r.target);if(db(Pe.dirname(o),{recursive:!0}),mb(o),r.mode==="120000"){QM(XM(n),o);return}qM(n,o),HM(o,r.mode==="100755"?493:420)},nj=async(e,t)=>{let r=new Set;for(let n of nt(await z(e,["ls-files","-z"]))){if(t.has(n))continue;let o=Pe.posix.dirname(n);for(;o!==".";)r.add(o),o=Pe.posix.dirname(o)}return r},oj=async(e,t)=>{if(t.length===0)return;let r=await nj(e,new Set(t)),n=[...new Set(t.map(o=>Pe.dirname(Pe.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)&&!(!YM(s,{throwIfNoEntry:!1})?.isDirectory()||zM(s).length>0||r.has(Pe.relative(e,s).split(Pe.sep).join("/")));)pb(s),s=Pe.dirname(s)}},fb=(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,ar,...s].map(lb).filter(a=>a!==null&&!Ua(a));return Gn(i)},gb=async(e,t,r,n)=>{let o=Pe.join(e,se);db(o,{recursive:!0}),tj(Pe.join(e,ar),lc(t.name));let s=fb(r,await ub(e),n);fp(o,{source:t.name,commit:t.headSha},s)},Qp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Jn(t));let n=Pe.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)mb(Pe.join(n,a));await oj(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&ZM(Pe.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)rj(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await gb(n,e,t.entries,o),{touched:Gn([...o,...i,ar,Ls]),manifestWritten:!0}):{touched:Gn([...o,...i]),manifestWritten:!1}},em=async(e,t)=>(await gb(e,t,[],[]),[ar,Ls]);var tm=(e,t)=>`[ROOT] vendor: sync from ${e}@${ac(t)}`,sj=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
|
|
465
|
+
`).trim()||String(e)},rm=async(e,t,r)=>{if(t.length===0)return{ok:!0};let n=t.join("\0"),o=["--pathspec-from-file=-","--pathspec-file-nul"];try{return await z(e,["--literal-pathspecs","add","-A",...o],{input:n}),await z(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:sj(s)}}};var hb=20,ij=20,om=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],nm=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of Us(e.files,r)){let p=cc(u.path,n);if(s.push(p),ob(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=Us(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}},jr=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),sm=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),aj=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...sm(e,r)];return jr(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...om(n,hb),Ue(o)])},cj=(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=ac(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}`,...om(e.lines,ij)],warnings:[]}},lj=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},uj=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},dj=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Gn([...n,...r?t.headVendorMeta:[]])},pj=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`),mj=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return aj(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return jr(t,"fail","blocked: a module this repo dropped is still a dependency",[...om(t.pruneConflicts,hb)]);let n=e.entries.flatMap((f,y)=>{let E=t.entries[y]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return E.scope==="release"?[]:E.scope==="sync"?[nm(f,E,e.exclude)]:[{...nm({...f,files:[]},E,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={...jr(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=cj(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(lj).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:`${uj(n)} on ${t.branch}`,notes:[...u,...m,...pj(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:dj(n,t,o)}},uc=(e,t)=>{switch(t.kind){case"missing":return jr(t,"skipped",`not checked out at ${t.root}`);case"source":return jr(t,"skipped","this is the source repo");case"not-git":return jr(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return jr(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return mj(e,t)}};import{existsSync as bj,readFileSync as Rj,realpathSync as dc}from"node:fs";import pc from"node:path";import{readFileSync as yb}from"node:fs";import Kn from"node:path";var fj=["dependencies","devDependencies","peerDependencies","optionalDependencies"],gj=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},vb=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=gj(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")},wb=e=>{try{return JSON.parse(yb(e,"utf8"))}catch{return null}},hj=(e,t)=>t.files.flatMap(r=>{let n=Kn.posix.relative(t.entry.path,r.path);if(Kn.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=wb(Kn.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),yj=e=>fj.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),kb=(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},vj=["*.sh","*.yml","*.yaml"],wj=(e,t,r)=>{let n=yj(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"&&kb(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},kj=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...vj];return nt(await z(e,n,{allowFailure:!0})).filter(s=>r(s)&&kb(yb(Kn.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},bb=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of hj(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=nt(await z(t,["ls-files","-z","--","*package.json"])).filter(c=>Kn.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=wb(Kn.join(t,p));return m===null?[]:wj(p,m,c)});u.push(...await kj(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var im=async(e,t)=>{let r=t.exclude??[],n=(await z(e,["rev-parse","HEAD"])).trim(),o=await Ae(e),s=await Promise.all(cb(t).map(async i=>{let a=await Zp(e,i.path,r);return{entry:i,files:a.map(c=>nb(e,c))}}));return{root:e,selfRoots:[...new Set([dc(e),dc(o)])],name:pc.basename(o),headSha:n,entries:s,exclude:r}},mc=e=>{let t=nt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},Sj=async(e,t,r)=>{let n=sm(e,t);if(n.length===0)return[];let o=await z(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return mc(o).filter(s=>!Bs(s,e.exclude))},Ej=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await Zp(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of Us(l,e.exclude)){let p=cc(u.path,n);c[p]=ic(pc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),Pj=async e=>{try{return nt(await z(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",ar,Ls]))}catch{return[]}},xj=e=>{try{let{commit:t,source:r}=Os(pc.join(e,se));return{commit:t,source:r}}catch{return null}},Tj=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await Ce(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 z(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
|
|
466
|
+
`).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},Cj=(e,t)=>{try{return Rj(pc.join(e,ar),"utf8")===lc(t)}catch{return!1}},$j=async e=>{try{return{toplevel:(await z(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
|
|
467
|
+
`)[0]??"git rev-parse failed"}}},Aj=async e=>{try{return(await z(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},fc=async(e,t)=>{if(!bj(t.root))return{...t,kind:"missing"};let r=dc(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await $j(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(dc(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=vb(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=xj(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([Aj(t.root),Sj(e,o,t.root),Ej(e,o,t.root),Pj(t.root),Tj(e,o,i)]),m=l.flatMap((f,y)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[y],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:Cj(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await bb(e.root,t.root,m)}};var Oj=20,Dj=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],Ij=(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:",Ue(Jn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:Dj(r,t)}},Nj=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(`
|
|
468
|
+
`).slice(0,Oj)},_j=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[Ij(e,t),...r,...e.commit?[Nj(e.commit)]:[]]}},Mj={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},am=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:Mj[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>_j(o,r))],hints:n}},Rb=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),Sb=(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 jj=20,cm=async(e,t)=>(await z(e,t,{allowFailure:!0})).trim(),Fj=async e=>mc(await z(e,["status","--porcelain","-z","--untracked-files=normal"])),Lj=async e=>(await cm(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"]},Bj=async e=>{let[t,r]=await Promise.all([cm(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),cm(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}`}},Eb=async e=>{let t=await Fj(e);if(t.length>0){let n=t.slice(0,jj),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new O({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([Lj(e),Bj(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import Gj from"node:path";import{readFileSync as Uj}from"node:fs";import Wj from"node:path";import{z as Vj}from"zod";var Pb=e=>{let t;try{t=Uj(Wj.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=hf.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:Vj.prettifyError(n.error)}};var xb=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new O({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=xn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=Gj.join(n,s);return{name:s,root:i,selection:Pb(i)}})},Jj="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",Kj=async(e,t)=>{let r=await fc(e,t),n=uc(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${Jj} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},Tb=async(e,t,r)=>Promise.all(t.map(async n=>r?Kj(e,n):uc(e,await fc(e,n))));var Ob="sync vendored files",zj=e=>{let t=$b.join(xn(e.workspaceDir),e.source);if(Hj(t))return t;throw new O({status:"refused",reason:"source-missing",source:t},1,{operation:Ob,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'})},lm=(e,t)=>new O({status:"refused",reason:"not-a-vendor-source"},1,{operation:Ob,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`}),Xj=async e=>{let t=$b.join(e,"infra-kit.json"),r;try{r=JSON.parse(await qj.readFile(t,"utf8"))}catch(s){throw lm(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw lm(t,"has no vendorSource block");let o=gf.safeParse(n);if(!o.success)throw lm(t,`has an invalid vendorSource: ${Yj.prettifyError(o.error)}`);return o.data},Cb=(e,t)=>{Ab.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
|
|
469
|
+
${Ue(t)}
|
|
470
|
+
`)},Zj=async(e,t,r)=>r?(Cb(t,Jn(t)),em(t.root,e)):(await Qp({source:e,plan:t,onBeforeFirstWrite:o=>{Cb(t,o)}})).touched,Qj=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await Zj(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 rm(t.root,n,tm(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},eF=async(e,t,r)=>{let n=[];for(let o of t)n.push(await Qj(e,o,r));return n},Db=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})),um=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&pt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:Db(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:Rb(t),report:t.sections}}},tF=async e=>{let t=await ea(),r=zj(t),n=await Eb(r),o=await Xj(r),s=xb(t,e.targets??[]),i=await im(r,o),a=await Tb(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},dm=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await tF(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=am(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return um({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!X();if(l&&!Ab.stdin.isTTY)return pt(a),um({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&pt({...a,hints:[]}),await J(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:Db(n),throwOnDecline:!0});let u=await eF(t,n,e),p=am(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);pt(Sb(a,p,m))}return um({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var gc=(e,t=!0)=>({line:e,reproducible:t});import hc from"node:fs";import rF from"node:os";import nF from"node:path";import Mb from"node:process";var yc="INFRA_KIT_SESSION_REPORT",pm=null,Ib=!1,Nb=[],jb=(e=Mb.env)=>{Ib||(pm=e[yc]??null,Ib=!0,delete e[yc])};var Fb=(e,t)=>{if(!pm)return;let r=e.summary??(Nb.length>0?[...Nb]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{hc.writeFileSync(s,i)});try{o(pm,JSON.stringify(n))}catch{}},_b=0,Lb=e=>{let t=e?.tmpdir?.()??rF.tmpdir(),r=e?.pid??Mb.pid;return _b+=1,nF.join(t,`infra-kit-session-${r}-${_b}.json`)},Bb=(e,t)=>{if(!(t?.exists??(i=>hc.existsSync(i)))(e))return null;let n=t?.read??(i=>hc.readFileSync(i,"utf-8")),o=t?.unlink??(i=>hc.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var mm=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");for(let r of e.commands)mm(r)};var fm=e=>{e.options.some(r=>r.long==="--debug")||e.option("--debug","Raise the log level to debug (logs stay on stderr)");for(let r of e.commands)fm(r)};var aF=(e,t)=>[...t,e],cF=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 Ih(()=>wa({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}));D(r),r.structuredContent.failedMerges>0&&(Fe.exitCode=1)}),Wb=e=>(Fe.stdout.write(`${e.structuredContent.filePath}
|
|
471
|
+
`),D(e)),lF=e=>e.description("List all release branches").action(async()=>{D(await Ca())}),uF=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".',aF,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Bu),o=n.length>0?n:void 0;D(await Da({releases:o,confirmedCommand:t.yes}))}),dF=e=>{if(e==="")return e;try{return Er(e)}catch(t){throw t instanceof In?new Vb(t.message):t}},pF=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Vb("Expected a positive whole number of days.");return t},mF=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)',dF).option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await Ia({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Gb=e=>e.option("-f, --from <where>",`Where the deploy runs: ${tr.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"),fF=e=>Gb(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{D(await Hp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),gF=e=>Gb(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=>{D(await qp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),hF=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=>{D(await ba({version:t.version,confirmedCommand:t.yes}))}),yF=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=>{D(await Ma({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),vF=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await Za({confirmedCommand:t.yes}))}),wF=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=>{D(await qa({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),kF=e=>e.description("List all git worktrees with detailed information").action(async()=>{D(await Ya())}),bF=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=>{D(await Xa({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),RF=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=>{D(await zp({init:t.init}))}),SF=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ja();D(t),t.structuredContent.ok||(Fe.exitCode=1)}),EF=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 dm({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!Et(a))throw a;d.info("Operation cancelled.");return}D(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),PF=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{D(await Dp())}),xF=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{D(await Ip())}),TF=new Set(["version"]),vc=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},gm=()=>{let e=new oF().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");cF(t.command("merge-dev")),lF(t.command("list")),uF(t.command("create")),mF(t.command("edit")),fF(t.command("deploy-all")),gF(t.command("deploy-selected")),hF(t.command("deliver")),yF(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");wF(r.command("add")),kF(r.command("list")),bF(r.command("remove")),vF(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");PF(n.command("path")),xF(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=>{D(await _i({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)=>{D(await jl({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)=>{D(await Np({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=>{D(await sc({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=>{D(await sc({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)"),Fe.exitCode=1;return}let c=await Ci({all:a.all,root:a.root,fix:a.fix,design:a.design});D(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&(Fe.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=>{D(await Lp({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 Up({check:a.check});D(c),c.structuredContent.ok||(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");SF(i.command("check")),RF(i.command("config")),EF(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 ua({fix:!!a.fix});lr.enabled||Hl(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(Fe.exitCode=1),D(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=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,appName:a},u,lr.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{D(await Mi())}),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)=>{D(await fa({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 Ub("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Ub("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){D(await rp());return}D(await Ba({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()=>{D(await Ka())}),e.command("change-stats").description("Change-failure baseline for this git repo: agent vs human commits, revert and 72h follow-up-fix rates").option("--since <days>",`Window in days, ending now (default ${So})`,pF).action(async a=>{D(await Di({since:a.since}))}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{D(await ya())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{D(await Hf())}),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=>{Wb(await Fc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Wb(await ha())}),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.");D(await Jp({fromFile:c.fromFile,force:c.force}));return}D(await Gp({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=>{D(await va({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=>{D(await Wp({env:a}))});for(let a of e.commands)Xm(a);return mm(e),fm(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&iF(sF(Fe.cwd(),l)),h.start(vc(c)),lr.enabled=!!c.optsWithGlobals().json,lr.enabled&&(d.level="warn"),j.source=ei({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),TF.has(vc(c))||await ku()}),e.hook("postAction",(a,c)=>{let l=vc(c);if($p(l))return;let p=h.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Fb({equivalent:gc(f,!0)})}),e};import CF from"node:process";var $F={exit:CF.exit,emit:D,logger:d},Jb=(e,t=$F)=>Oe(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof O?(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 hm=(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 AF from"node:fs";import ym from"node:path";import Hn from"node:process";var qb=new Set([...ff,Yn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Yb=null,wc=new Set,vm=null,Kb=!1;var Hb=e=>{try{return AF.statSync(e)}catch{return null}},OF=()=>{if(Kb)return null;try{return Br()}catch{return Kb=!0,d.debug(`session-env: ${Yn} unset \u2014 no overlay`),null}},DF=e=>{let t=ym.join(e,Fr),r=ym.join(e,Gs),n=Hb(t),o=Hb(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Cm(ym.join(e,Js),Hn.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"}},IF=e=>e.kind==="load"?{kind:"load",vars:xm(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Tm(e.file),signature:e.signature}:e;var NF=()=>{let e=OF();if(e===null)return{kind:"no-session"};let t=DF(e);return t.signature===vm?null:IF(t)},_F=()=>{for(let e of wc){let t=Yb[e];t===void 0?delete Hn.env[e]:Hn.env[e]=t}wc.clear()},MF=(e,t,r)=>{if(qb.has(t)){e.skipped.push(t);return}Hn.env[t]=r,wc.add(t),e.set.push(t)},jF=(e,t)=>{if(qb.has(t)){e.skipped.push(t);return}delete Hn.env[t],wc.add(t),e.unset.push(t)},FF=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))MF(t,r,n);if(e.kind==="clear")for(let r of e.unset)jF(t,r);return t},LF=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,wm=(e=NF())=>{if(Yb??={...Hn.env},e===null||e.kind==="no-session"||e.signature===vm)return{set:[],unset:[],changed:!1};_F();let{set:t,unset:r,skipped:n}=FF(e);return vm=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(", ")}] (${LF(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as iL}from"chalk";import{spawn as aL}from"node:child_process";import Le from"node:process";import{Chalk as BF}from"chalk";var qn=new BF({level:1}),ot={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."},UF={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"}},zb={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Xb={unicode:"\u2500",ascii:"-"},WF=3,km=e=>e,VF={ok:e=>qn.green(e),findings:e=>qn.yellow(e),failed:e=>qn.red(e),cancelled:e=>qn.gray(e)},Rm=e=>e?{dim:t=>qn.dim(t),bold:t=>qn.bold(t)}:{dim:km,bold:km},GF=(e,t)=>e?VF[t]:km,bm=e=>[...e].length,JF=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return bm(e)<=r?e:[...e].slice(0,r).join("")},Zb=e=>{let t=Rm(e.color===!0).dim,r=UF[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(JF(n,e.width))},Qb=(e,t={})=>{let r=Rm(t.color===!0);return`${r.dim(ot.reproPrefix.trim())} ${r.bold(e)}`},KF=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,HF=(e,t)=>e==="findings"?t!=null?`${t} ${ot.findingsSuffix}`:ot.findingsPlain:{ok:ot.ok,failed:ot.failed,cancelled:ot.cancelled}[e],qF=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<WF?"":` ${n(r.repeat(o))}`},eR=e=>{let t=e.color===!0,r=Rm(t),n=GF(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?ot.reproPrefix:ot.nonReproPrefix,i=o?zb[e.outcome].ascii:zb[e.outcome].unicode,a=HF(e.outcome,e.findingsCount),c=[KF(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
472
|
+
`)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${ot.sep}${c.join(ot.sep)}`,m=bm(u)+bm(p),f=qF(m,e.width,o?Xb.ascii:Xb.unicode,r.dim),y=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&y.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&y.push(r.dim(ot.envNotice)),y.join(`
|
|
473
|
+
`)};var YF=new Set([130,143]),tR=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&YF.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import zF from"node:process";var XF={3:"quit",4:"quit",26:"suspend",27:"quit"},ZF=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":XF[t]??"continue"},QF=150,eL="\r\x1B[2K",tL=`\r
|
|
474
|
+
`,rR=(e,t)=>{nR(e),e.stdin.on("data",t),e.listener=t},nR=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},oR=(e,t)=>{Ef(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),rR(e,t)},sR=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(eL)),nR(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Pf()},rL=e=>{e.settled||(e.settled=!0,sR(e))},iR=(e,t)=>{let r=Zb({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},nL=async e=>{await new Promise(t=>{setTimeout(t,e)})},oL=(e,t,r)=>{sR(e),t(),oR(e,r),iR(e,tL)},sL=async e=>new Promise(t=>{let r=n=>{let o=ZF(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){oL(e,s,r);return}t("palette")};rR(e,r),iR(e,"")}),aR=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??zF.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return oR(n,()=>{}),e.armed(),await nL(t.drainMs??QF),await sL(n)}finally{rL(n)}};import cR from"node:process";var cr={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},lR=(e,t)=>{let r=t?.write??(s=>{cR.stderr.write(s)}),n=t?.stdin??cR.stdin,o=[cr.saveCursor,cr.scrollRegion,cr.restoreCursor,cr.column,cr.sgr,cr.cursor,cr.wrap];e.entersAltScreen===!0&&o.push(cr.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var uR=e=>`infra-kit ${e.groupPath.join(" ")}`,cL=()=>{lL();let e=Le.stderr.columns;return e!=null&&e>0?e:void 0},lL=()=>{let e=Le.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},uL=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),dL=async(e,t,r)=>{let n=Lb(),o={...t.env,[yc]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Le.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await uL(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Bb(n),c=tR(i.code,i.signal,a!=null,e.longRunning),l=uR(e),u=a?.equivalent??gc(l,!0);return eR({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)})},pL=1e3,mL=(e,t)=>e!=null&&t-e<=pL,Sm=e=>{e.resetTerminal(),e.exit(0)},fL=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&Sm(t)},s=()=>{let c=e();if(c==="palette"){Sm(t);return}if(!mL(r,t.now())){if(c==="pause"){Sm(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}},dR=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),gL=Le.platform==="win32"?void 0:()=>{xf()},hL=(e,t)=>r=>aR(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:gL}),pR=async(e,t)=>{let r={spawn:t.spawn??aL,now:t.now??(()=>Date.now()),env:t.env??Le.env,cliPath:t.cliPath,ascii:t.ascii??!(Le.stdout.isTTY&&Le.env.TERM!=="dumb"),color:t.color??iL.level>0,columns:t.columns??cL,resetTerminal:t.resetTerminal??(u=>{lR(u)})},n=t.write??(u=>Le.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Le.on(u,p)},unregister:(u,p)=>{Le.off(u,p)},exit:u=>{Le.exit(u)},raise:u=>{Le.kill(Le.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:fL(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??hL(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=Qb(uR(p),{color:r.color});n(`
|
|
474
475
|
${m}
|
|
475
|
-
`),a.childStarted();let f=await
|
|
476
|
+
`),a.childStarted();let f=await dL(p,r,()=>{o="child"});if(n(`
|
|
476
477
|
${f}
|
|
477
|
-
`),await l(c)==="quit")return}}finally{a.dispose()}}
|
|
478
|
+
`),await l(c)==="quit")return}}finally{a.dispose()}};Op();jb();var hR=gm(),fR=async(e=Be.argv)=>{wm(),Rf(e);try{await hR.parseAsync(e)}catch(t){Jb(t)}},bL=()=>{try{if(Be.env.INFRA_KIT_NO_LOCATION_WARN||Be.argv.includes("--json"))return;Dm({selfRealPath:wL(gR(import.meta.url)),cwd:Be.cwd(),env:Be.env,realpath:xe,home:kL(),exists:vL})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};bL();zm((e,t)=>{d.debug(e,t)});Ru(L.version);var yR=()=>jk(hR.commands),RL=async()=>{let e=yR(),t=null;try{if(Be.stdout.isTTY&&Be.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-ST2534PA.js");t=await r(e)}else{let r=hm(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new mR(" "),new mR(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await _(o=>yL({message:"Select a command to run",choices:n},o),{output:Be.stderr})}}catch(r){if(!Oe(r))throw r}return t},SL=async()=>{let{runCommandPalette:e}=await import("./boot-ST2534PA.js"),t=gR(import.meta.url),r=new Map(xr.map(n=>[n.groupPath.join(" "),n]));await pR(yR(),{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(Be.argv.length<=2){let e={stdoutIsTTY:!!Be.stdout.isTTY,stdinIsTTY:!!Be.stdin.isTTY,stderrIsTTY:!!Be.stderr.isTTY};if(dR(Be.env,e))await SL();else{let t=await RL();t&&await fR(["node","infra-kit",...t.split(" ")])}}else await fR();
|
|
478
479
|
//# sourceMappingURL=cli.js.map
|