infra-kit 0.35.0 → 0.36.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-5SGMD57Z.js → chunk-3JFITLZG.js} +2 -2
- package/dist/{chunk-GDOQUC23.js → chunk-BPOPODWW.js} +2 -2
- package/dist/{chunk-YVIJUGOB.js → chunk-SBG3HRSC.js} +2 -2
- package/dist/{chunk-TFOXJRVH.js → chunk-TCQXTDVZ.js} +2 -2
- package/dist/{chunk-TFOXJRVH.js.map → chunk-TCQXTDVZ.js.map} +1 -1
- package/dist/{chunk-BYCCXWPB.js → chunk-TGEAIKD6.js} +2 -2
- package/dist/cli.js +125 -125
- package/dist/cli.js.map +3 -3
- package/dist/dev-server.js +2 -2
- package/dist/{dev-wizard-run-5JKULZ4J.js → dev-wizard-run-PAHX7EMH.js} +2 -2
- package/dist/{env-load-HRJPWQ5X.js → env-load-XBKASGXP.js} +2 -2
- package/dist/update-check.js +1 -1
- package/package.json +3 -3
- /package/dist/{chunk-5SGMD57Z.js.map → chunk-3JFITLZG.js.map} +0 -0
- /package/dist/{chunk-GDOQUC23.js.map → chunk-BPOPODWW.js.map} +0 -0
- /package/dist/{chunk-YVIJUGOB.js.map → chunk-SBG3HRSC.js.map} +0 -0
- /package/dist/{chunk-BYCCXWPB.js.map → chunk-TGEAIKD6.js.map} +0 -0
- /package/dist/{dev-wizard-run-5JKULZ4J.js.map → dev-wizard-run-PAHX7EMH.js.map} +0 -0
- /package/dist/{env-load-HRJPWQ5X.js.map → env-load-XBKASGXP.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 Pf,e as Vr,f as If,g as Bt,h as ai,i as Nf,j as _f,k as Mf,l as jf,m as Ff,n as Lf,o as Bf,p as Uf,s as _c,t as Gf,u as Ae}from"./chunk-3JFITLZG.js";import{a as Dm,b as Be,c as Im,d as kc,e as Nm,f as _m,g as Mm,h as jm,i as Yn,j as Fm,k as Lm,l as Bm,m as Um,n as Wm,o as zn,p as Vm,q as Gm,r as Jm,s as Km,t as bc,u as zs,v as _t,w as Hm,x as Xs,y as qm}from"./chunk-PP44RGIU.js";import{a as le,b as Y,c as Ft,d as Qn,e as xc,f as ni,g as oi,h as Tc,i as eo,j as cr,k as Cc,l as si,m as wf,n as kt,o as to,p as Ac,q as Oc,r as Dc,s as Cf,u as Ic}from"./chunk-QS7RKE5P.js";import{b as qn,c as qs,d as wc,e as Tm,f as Ys,g as Cm,i as $m,k as Am,m as Ee,o as Om}from"./chunk-REDCBY4O.js";import{a as Ef}from"./chunk-V2ZLQPLI.js";import{B as no,D as jc,H as Fc,I as Lc,a as b,b as C,c as $f,d as Af,e as lr,f as Of,g as ur,h as Df,i as Nc,j as Wf,k as ro,l as Ut,m as Gr,n as st,o as ci,p as Wt,q as Vf,r as li,s as Jf,t as Kf,u as it,y as Mc}from"./chunk-SBG3HRSC.js";import{a as y,b as bt,c as kf,d as bf,e as _,f as ii,g as G,i as Lt,j as Ze,k as xf,l as $c,m as Tf}from"./chunk-TGEAIKD6.js";import{$ as Mt,A as tf,B as rf,C as nf,D as ei,E as ti,F as xe,G as Xn,H as Wr,I as ri,J as of,K as sf,L as af,M as Sc,N as Ec,O as cf,P as d,Q as Ue,R as ne,S as w,T as Xe,U as lf,V as uf,W as df,X as O,Y as mf,Z as ff,_ as gf,a as ar,aa as hf,b as D,ba as Pc,c as Ym,ca as yf,d as j,da as vf,e as ge,ea as ee,f as Z,fa as H,g as Zs,ga as Zn,h as zm,ha as jt,i as g,j as Xm,k as Qs,l as Q,m as ve,n as Pe,o as Zm,p as Rc,q as ce,r as re,s as Br,t as Qm,u as ot,v as we,w as A,x as $e,y as Ur,z as ef}from"./chunk-BPOPODWW.js";import{a as pf}from"./chunk-MFAFQVTW.js";import{a as L}from"./chunk-TCQXTDVZ.js";import{a as Mr,b as Ws,c as Vs,d as Hn,e as Rm,f as jr,g as Gs,h as Js,i as Sm,j as Ks,k as Hs,l as Em,m as Pm,n as wt,o as Fr,p as Nt,q as fe,r as xm,s as Lr}from"./chunk-GCOYOWGH.js";import{a as Rf,b as Sf}from"./chunk-QWVLAZ6N.js";import lL,{Separator as lR}from"@inquirer/select";import{existsSync as uL,realpathSync as dL}from"node:fs";import{homedir as pL}from"node:os";import Le from"node:process";import{fileURLToPath as dR}from"node:url";import Hg from"node:process";import{z as Ie}from"zod";import eg from"node:fs";import Kr from"node:path";import{packageConfigSchema as Yf}from"@slip-stream-kit/config/internal";import zf from"node:fs/promises";import ui from"node:path";import{pathToFileURL as kR}from"node:url";import{z as Xf}from"zod";import Hf from"node:path";var oo=["frontend","backend","lib","e2e","mobile"],fR={ui:"frontend",api:"backend",tests:"e2e"},gR="mobile-app",hR=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],yR=(e,t)=>{let r=Hf.relative(t,e).split(Hf.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=fR[o];if(s)return s}return r.at(-1)===gR?"mobile":null},vR=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of hR)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},so=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??yR(e,t)??vR(r)??"lib";var at={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},qf=2e3,Bc={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${qf}} 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"},dr={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"]},io=(e,t=at)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import wR from"node:fs/promises";var Oe=async e=>{try{return await wR.access(e),!0}catch{return!1}};var ue="infra-kit.config.ts",pr=async e=>{try{let t=await zf.readFile(ui.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},Uc=async e=>{let t=await zf.stat(e),o=(await import(`${kR(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${ue} at ${e} has no default export`);return typeof o=="function"?await o():o},Rt=async e=>{let t=ui.join(e,ue);if(await Oe(t))try{let n=(await Uc(t))?.type;return oo.find(o=>o===n)}catch{return}},Zf=e=>e,ao=async(e,t=at)=>{let r=ui.join(e,ue);if(!await Oe(r))throw new Error(`${ue} not found at ${r}`);let n=await Uc(r),o=Yf.safeParse(n);if(!o.success)throw new Error(`Invalid ${ue} at ${r}: ${Xf.prettifyError(o.error)}`);return io(Zf(o.data),t)},ct=async e=>{let t=ui.join(e,ue);if(!await Oe(t))return;let r=Yf.safeParse(await Uc(t));if(!r.success)throw new Error(`Invalid ${ue} at ${t}: ${Xf.prettifyError(r.error)}`);return Zf(r.data)};import Qf from"node:fs/promises";import di from"node:path";import bR from"yaml";var RR="pnpm-workspace.yaml",SR=async e=>(await Qf.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>di.join(e,r.name)),ER=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await SR(n));continue}let o=di.join(n,t);await Oe(o)&&r.push(o)}return r},PR=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await ER(r,n);return r},ke=async e=>{let t=await Qf.readFile(di.join(e,RR),"utf-8"),n=((bR.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await PR(e,s);for(let a of i)await Oe(di.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import co from"node:path";var lo=async e=>{let t=co.resolve(e);for(;t!==co.dirname(t);){if(await Oe(co.join(t,"package.json")))return t;t=co.dirname(t)}if(await Oe(co.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 We=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Vt=(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}`:"")},mr=(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},pi=(e,t,r)=>`${e}
|
|
4
4
|
${t}
|
|
5
|
-
${r}`,Jr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=
|
|
5
|
+
${r}`,Jr=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=pi(r,t,n),i=We(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?Vt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
6
6
|
${s}
|
|
7
7
|
`:`${s}
|
|
8
|
-
`};var be="<!-- infra-kit:begin -->",De="<!-- infra-kit:end -->",
|
|
8
|
+
`};var be="<!-- infra-kit:begin -->",De="<!-- infra-kit:end -->",fr="<!-- infra-kit:version ",Ve="<!-- infra-kit:package:begin -->",Qe="<!-- infra-kit:package:end -->",St="<!-- infra-kit:package:version ";var xR=e=>{let t=e.indexOf(Ve)+Ve.length;return e.slice(t,e.indexOf(Qe))},TR=e=>{let t=e.indexOf(St);if(t===-1)return null;let r=e.slice(t+St.length).match(/^\S+\s+([^\s>]+)/)?.[1];return oo.find(n=>n===r)??null},Et=e=>{if(e===null)return{state:"missing"};if(!We(e,Ve,Qe))return e.includes(Ve)||e.includes(Qe)?{state:"malformed"}:We(e,be,De)?{state:"foreign-block"}:{state:"no-block"};let t=xR(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=mr(t,St),o=TR(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import CR from"node:fs";var lt=e=>{try{return CR.readFileSync(e,"utf-8")}catch{return null}};var tg="pnpm-workspace.yaml",$R="CLAUDE.md",Vc=e=>{let t=Kr.resolve(e);for(;t!==Kr.dirname(t);){if(eg.existsSync(Kr.join(t,tg)))return t;t=Kr.dirname(t)}return eg.existsSync(Kr.join(t,tg))?t:null},Wc=new Map,mi=()=>{Wc.clear()},AR=async e=>{let t;try{t=await ke(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=Kr.join(r,$R),o=lt(n);if(o!==null&&Et(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},Hr=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=Wc.get(e);if(t)return t;let r=await AR(e);return Wc.set(e,r),r};import gr from"node:fs";import Gt from"node:path";var rg=`---
|
|
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 ng=`# {{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 og="# {{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 sg="# {{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 ig=`# {{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 ag=`# {{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})`)}},Yr=(e,t)=>{let r=
|
|
143
|
-
`),t);return
|
|
144
|
-
`).replace(
|
|
145
|
-
`};var
|
|
146
|
-
`)};var
|
|
147
|
-
`)};import zr from"node:fs";import GR from"node:path";var di=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(GR.dirname(e),{recursive:!0}),zr.writeFileSync(e,t,"utf-8")),r},mo=(e,t)=>{di(e);let r=zr.existsSync(e)?zr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Kc=(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}`)},cg=(e,t,r)=>We(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Hc=(e,t,r,n)=>{let o=cg(e,r,n),s=cg(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 mi="<!-- infra-kit:import:begin -->",fi="<!-- infra-kit:import:end -->",JR="AGENTS.md",lg="CLAUDE.md",KR="README.md",qc="DESIGN.md",HR=["frontend","mobile"],qR=e=>fr.existsSync(e)?fr.readFileSync(e,"utf-8"):null,Yc=(e,t)=>{try{return fr.readdirSync(e).includes(t)}catch{return!1}},pi=(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},ug=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=qR(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 Kc(e,r,n),i!==null&&Hc(a,c,r,n),l},YR=(e,t)=>{if(!fr.existsSync(e))return"unchanged";di(e);let r=fr.readFileSync(e,"utf-8"),n=Wt(r,be,De);return n===null?"unchanged":n.trim()===""?(t||fr.rmSync(e),"removed"):t?mo(e,n):po(e,n)},zR=(e,t,r)=>ug({filePath:e,dryRun:r,body:uo(t),startMarker:be,endMarker:De,prepare:n=>Wt(n,mi,fi)??n}),fo=async(e,{version:t,dryRun:r=!1})=>{let n=Vt.join(e,lg),o=Vt.join(e,JR),s=[];try{s.push({path:n,action:zR(n,t,r)})}catch(i){s.push(pi(n,i))}try{s.push({path:o,action:YR(o,r)})}catch(i){s.push(pi(o,i))}return s},XR=(e,t,r,n)=>{if(!HR.includes(r)||Yc(e,qc))return null;let o=Vt.join(e,qc),s=Vc(t);try{return{path:o,action:n?mo(o,s):po(o,s),type:r}}catch(i){return pi(o,i,r)}},gi=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await dr(e),s=o.name??Vt.basename(e),i=so({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:Jc({version:r,type:i,packageName:s,relDir:Vt.relative(t,e).split(Vt.sep).join("/"),hasReadme:Yc(e,KR),hasDesign:Yc(e,qc),hasE2eDoc:fr.existsSync(Vt.join(t,Gc)),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=Vt.join(e,lg),{body:a,type:c,packageName:l}=await gi(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:ug({filePath:i,body:a,startMarker:Ve,endMarker:Qe,dryRun:s}),type:c})}catch(p){u.push(pi(i,p,c))}if(n){let p=XR(e,l,c,s);p&&u.push(p)}return u};import wS from"node:path";import dg from"node:path";var zc="agent-guidance",ho="CLAUDE.md",ZR="\u2014 run: infra-kit audit --fix",QR={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`},eS=e=>e.adopted?` (workspace adopted: ${dg.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Xc=(e,t)=>{let r=Et(lt(dg.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=`${QR[r.state]} ${ZR}`,o=r.state==="missing"?`${n}${eS(t)}`:n;return t.adopted?{name:zc,status:"fail",message:o}:{name:zc,status:"pass",message:`not yet adopted \u2014 ${o}`}};import tS from"node:path";var Zc=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}}},pg="infra-kit.json",rS=async e=>await Oe(tS.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,Qc=async(e,t=ur)=>{let r=await rS(e),n=r?[r]:[];try{let{audit:o={}}=await H();return{checks:[{name:pg,status:"pass",message:"present and valid"},...n],rules:io(o,t)}}catch(o){return{checks:[{name:pg,status:"fail",message:o.message},...n],rules:null}}};import hi from"node:fs/promises";import Xr from"node:path";import{$ as nS}from"zx";var yo="playwright.config.ts",oS=[{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')"}],mg=e=>Object.entries(Fc).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"}}),sS="infra-kit-e2e",fg=async(e,t={})=>{let r=Xr.join(e,yo),n=await hi.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${yo}`,status:"fail",message:`missing ${yo}`}]:oS.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===sS?{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}`}})},iS=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,aS=/\.[cm]?[jt]sx?$/u,el=async(e,t)=>(await hi.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&aS.test(n.name)).map(n=>Xr.join(n.parentPath,n.name)),cS=async e=>{let t=await el(Xr.join(e,"src"),!0);for(let r of[Xr.join(e,yo),...t]){let n=await hi.readFile(r,"utf-8").catch(()=>"");if(iS.test(n))return!0}return!1},gg=async e=>{let t="e2e-auth:gitignored";if(!await cS(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await nS({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}`}},tl="E2E__BASIC_AUTH_USERNAME",rl="E2E__BASIC_AUTH_PASSWORD",lS=/\bE2E_\w*BASIC_AUTH_\w+/gu,uS=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,dS=/\/\*[\s\S]*?\*\//gu,pS=/(^|[^:])\/\/[^\n]*/gu,mS=e=>/USER(?:NAME)?$/u.test(e)?tl:rl,fS=e=>e.replace(dS,"").replace(pS,"$1"),hg=async e=>{let t="e2e-env:basic-auth",r=[...await el(e,!1),...await el(Xr.join(e,"src"),!0)],n=[];for(let o of r){let s=await hi.readFile(o,"utf-8").catch(()=>""),i=new Set([...fS(s).matchAll(lS)].map(a=>a[0]).filter(a=>uS.test(a)&&a!==tl&&a!==rl));for(let a of i)n.push(`${a} \u2192 ${mS(a)} (${Xr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${tl} / ${rl}`}:{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("; ")}`}},nl=async(e,t,r={})=>[...mg(t),...await fg(e,r),await gg(e),await hg(e)];import gS from"node:fs/promises";import hS from"node:path";var ol=async(e,t)=>Promise.all(t.map(async r=>{let n=await gS.stat(hS.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 sl=(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 yS from"node:fs/promises";import vS from"node:path";var Zr="turbo.json",il=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await yS.readFile(vS.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 kS=async(e,t)=>{let{check:r,rules:n}=await Zc(e,t);return{checks:[r],rules:n}},bS={adopted:!1,workspaceRoot:null},RS=async(e,t,r)=>so({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Rt(e)}),SS=async e=>(await ct(e).catch(()=>{}))?.e2e?.server==="static",al=async(e,t=at,r={})=>{let n=await dr(e),o=n.name??wS.basename(e),{checks:s,rules:i}=r.isRoot?await Qc(e,t):await kS(e,t);r.isRoot||s.push(Xc(e,r.adoption??bS)),i&&(s.push(...sl(n.scripts??{},i.requiredScripts)),s.push(...await ol(e,i.requiredFiles)),s.push(...await il(e,i.turboTasks))),!r.isRoot&&await RS(e,n,r.repoRoot)==="e2e"&&s.push(...await nl(e,n.scripts??{},{staticServer:await SS(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var cl=["plugin","marketplace","add",jt],ll=["plugin","install",Y,"--scope","project"],yg=(e,t)=>ar({projectPath:e,home:t}).kind==="installed",yi=e=>((e??"").split(`
|
|
148
|
-
`).find(r=>r.trim().length>0)??"").trim(),
|
|
149
|
-
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${le}`,`enabledPlugins.${Y}`]}),
|
|
141
|
+
`;var cg="# 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 qr={"root/body":cg.trimEnd(),"package/frontend":sg.trimEnd(),"package/backend":ng.trimEnd(),"package/lib":ig.trimEnd(),"package/e2e":og.trimEnd(),"package/mobile":ag.trimEnd(),"design/skeleton":rg.trimEnd()};var Gc=/\{\{(\w+)\}\}/g,FR=/^- \{\{(\w+)\}\}$/,LR=e=>new Set([...e.matchAll(Gc)].map(t=>t[1])),BR=(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(", ")}`)},UR=(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(", ")}`)},WR=(e,t)=>e.filter(r=>{let n=FR.exec(r);return n===null||t[n[1]]!==""}),VR=(e,t)=>{for(let r of e)for(let n of r.matchAll(Gc)){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})`)}},Yr=(e,t)=>{let r=LR(e);UR(r,t),BR(r,t);let n=WR(e.split(`
|
|
143
|
+
`),t);return VR(n,t),n.join(`
|
|
144
|
+
`).replace(Gc,(o,s)=>t[s])};var GR="name: TODO",Jc=e=>{let t=Yr(qr["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(GR,()=>r)}
|
|
145
|
+
`};var JR=(e,t)=>`${St}${e} ${t} -->`,KR="`README.md` \u2014 what this package is and how to run it.",Kc="docs/e2e-playwright.md",HR=`\`${Kc}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,qR=["ts-check","eslint-check","test"],YR="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.",zR="Run `pnpm run build` before a dependent package can see a change.",lg=(e,t)=>e?.includes(t)??!0,XR=e=>{let t=qR.filter(r=>lg(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},Hc=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=Yr(qr[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?KR:"",checksBullet:XR(a),...r==="e2e"?{e2eDocBullet:i?HR:""}:{},...r==="lib"?{surfaceBullet:c?YR:"",buildBullet:lg(a,"build")?zR:""}:{}});return[JR(t,r),"",l,""].join(`
|
|
146
|
+
`)};var ZR=e=>`${fr}${e} -->`,uo=e=>{let t=Yr(qr["root/body"],{});return[ZR(e),"",t,""].join(`
|
|
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(),IS=(e,t)=>{if(eo(t))return null;d.debug({msg:`Running: ${Qn} ${ul.join(" ")}`});let r=e({args:ul});return r.ok?null:{step:"marketplace",error:ki(r.output)}},NS=(e,t)=>{d.debug({msg:`Running: ${Qn} ${oi.join(" ")}`});let r=e({args:oi});if(!r.ok)return{status:"update-failed",error:ki(r.output)};d.debug({msg:`Running: ${Qn} ${ni.join(" ")}`});let n=e({args:ni,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:ki(n.output)}},pl=e=>{let{projectRoot:t,home:r}=e,n=e.run??Tc;if(!n({args:xc}).ok)return{status:"claude-missing"};if(wg(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:NS(n,t);let o=IS(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${Qn} ${dl.join(" ")}`});let s=n({args:dl,cwd:t});return s.ok?wg(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:ki(s.output)}};import _S from"node:fs";import MS from"node:path";var Ge=".mcp.json",ut="mcpServers",jS="infra-kit",FS=["mcp"],LS="/infra-kit/dist/mcp.js",ml=" ",hr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),kg=e=>{if(!hr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===jS&&r[0]===FS[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(LS)):!1},bg=e=>/\n([ \t]+)"/.exec(e)?.[1]??ml,fl=e=>{try{return{kind:"raw",raw:_S.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},gl=e=>{try{return JSON.parse(e)}catch{return}},hl=e=>e instanceof Error?e.message:String(e),Qr=e=>{let t=fl(MS.join(e,Ge));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=gl(t.raw);if(!hr(r)||!hr(r[ut]))return{kind:"unparseable"};let n=r[ut];if(le in n)return{kind:"stale"};let o=Object.keys(n).find(s=>kg(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import bi from"node:fs";import BS from"node:path";var Pt=`claude plugin install ${Y} --scope project`,en=`claude plugin marketplace update ${le} && claude plugin update ${Y} --scope project`,yl=`claude plugin marketplace add ${Ft}`,Eg=" ",Pg=()=>({source:{source:"github",repo:Ft}}),US=()=>({extraKnownMarketplaces:{[le]:Pg()},enabledPlugins:{[Y]:!0}}),xg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),WS=e=>/\n([ \t]+)"/.exec(e)?.[1]??Eg,Rg=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!xg(o)||r in o?null:(o[r]=n,`${t}.${r}`)},Sg=e=>[Rg(e,"extraKnownMarketplaces",le,Pg()),Rg(e,"enabledPlugins",Y,!0)].filter(r=>r!==null),VS=e=>{try{return bi.readFileSync(e,"utf-8")}catch{return null}},GS=e=>(bi.mkdirSync(BS.dirname(e),{recursive:!0}),bi.writeFileSync(e,`${JSON.stringify(US(),null,Eg)}
|
|
149
|
+
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${le}`,`enabledPlugins.${Y}`]}),vl=(e,{write:t=!0}={})=>{let r=VS(e);if(r===null)return t?GS(e):{status:"withheld",path:e,added:Sg({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!xg(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${Y}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=Sg(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=WS(r),i=r.endsWith(`
|
|
150
150
|
`)?`
|
|
151
|
-
`:"";return
|
|
152
|
-
`,"utf-8")}return o},
|
|
151
|
+
`:"";return bi.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var JS="empty-rules",KS=["requiredScripts","requiredFiles"],Tg=(e,t,r)=>KS.filter(n=>e[n]?.length===0).map(n=>({name:JS,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`})),Cg=async(e,t)=>{try{if(t){let{audit:r={}}=await H();return Tg(r,dr,'infra-kit.json "audit"')}return Tg(await ct(e)??{},at,"infra-kit.config.ts")}catch{return[]}};import YS from"node:path";import zS from"node:process";import wl from"node:fs/promises";import $g from"node:path";var HS="infra-kit.json",Ag=["requiredScripts","requiredFiles","turbo"],vo=(e,t)=>[{path:e,action:"failed",message:t}],qS=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Og=async e=>{let t=$g.join(e,ue),r=$g.join(e,HS),n;try{n=await ct(e)}catch(c){return vo(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!Ag.includes(c));if(s.length>0)return vo(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(Ag.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await wl.stat(r),l=await wl.readFile(r,"utf8"),u=JSON.parse(l);if(!qS(u))return vo(r,"is not a JSON object");if("audit"in u)return vo(r,`already has an "audit" block \u2014 merge ${ue}'s rules into it by hand, then delete ${ue}`);await uf({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return vo(r,c.message)}try{await wl.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var XS=["unchanged","created"],ZS=["unchanged","created","updated","removed","failed"],Dg=async(e,t,r)=>{let n=await Rt(e);return go(e,{repoRoot:t,version:L.version,design:r,declaredType:n})},QS=async(e,t)=>{if(e.root)return[...await Og(t),...await fo(t,{version:L.version})];if(e.all){let n=[];for(let o of await ke(t))n.push(...await Dg(o,t,e.design));return n}let r=await lo(e.cwd??zS.cwd());return Dg(r,t,e.design)},eE=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 ${ZS.filter(n=>XS.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${L.version})`},tE=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=YS.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(eE(e))},rE=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},Ig=async(e,t)=>{let r=await A();mi();let n=await Hr(t),o=await QS(e,r);tE(o,r),mi();let s=await Hr(t),i=!e.all&&!e.root;return{fixed:o.map(rE),adoptionFlipped:i&&!n.adopted&&s.adopted}};import Ri from"node:fs/promises";import Si from"node:path";import nE from"yaml";var wo="dependency-drift",kl="@slip-stream-kit/",oE="infra-kit",sE=["dependencies","devDependencies","optionalDependencies"],Mg=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),Rl=e=>e.startsWith("catalog:"),iE=(e,t,r)=>{if(!Rl(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},Ng=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},aE=(e,t)=>{let r=Ng(e),n=Ng(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},cE=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},bl=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),lE=(e,t)=>[...cE(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!Rl(s.spec));return o.length===0?[]:[{name:`${wo}:catalog`,status:"warn",message:`${r} has a catalog entry (${t.default[r]}) but ${bl(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:`${wo}:catalog`,status:"warn",message:`${r} is pinned at more than one range: ${bl(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),uE=(e,t,r)=>{let n=new Map;for(let o of e){let s=iE(o.spec,t,o.name);s!==void 0&&aE(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${wo}:lockstep`,status:"warn",message:`${o} is behind the infra-kit ${r} lockstep release \u2014 bump it to ^${r}`}))},dE=e=>{let t=e.filter(r=>r.name===oE);return t.length===0?[]:[{name:`${wo}:infra-kit-pin`,status:"warn",message:`${bl(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},pE=(e,t,r)=>{let n=e.filter(i=>!Mg(i.spec)),o=n.filter(i=>i.name.startsWith(kl)),s=[...lE(o,t),...uE(o,t,r),...dE(n)];return s.length>0?s:[{name:wo,status:"pass",message:`no ${kl}* or infra-kit dependency drift`}]},mE=async e=>{try{return JSON.parse(await Ri.readFile(e,"utf-8"))}catch{return null}},fE=async e=>{try{let t=nE.parse(await Ri.readFile(Si.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},gE=async e=>{let t=await ke(e).catch(()=>[]);return[e,...t].map(r=>Si.join(r,"package.json"))},_g=async e=>{let t=[];for(let r of await gE(e)){let n=await mE(r);if(!n)continue;let o=Si.relative(e,r);for(let s of sE){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},hE=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(kl)&&!Mg(s.spec)&&!Rl(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=Si.join(e,s),a=await Ri.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 Ri.writeFile(i,`${JSON.stringify(c,null,l)}
|
|
152
|
+
`,"utf-8")}return o},jg=async(e,t,r=L.version)=>{let n=await fE(e),o=await _g(e),s=t?await hE(e,o,n):[],i=s.length>0?await _g(e):o;return{checks:pE(i,n,r),rewritten:s}};import Lg from"node:path";var Ei="agent-guidance:drift",yE={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Fg=(e,t)=>e.split(`
|
|
153
153
|
`).filter(r=>!r.startsWith(t)).join(`
|
|
154
|
-
`),
|
|
154
|
+
`),Bg=({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=pi(r,t,n);if(Fg(a,o)===Fg(c,o))return{name:Ei,status:"pass",message:`matches infra-kit ${s}`};let l=mr(a,o),u=yE[i];return l!==null&&kt(l,s)?{name:Ei,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&&kt(s,l)?{name:Ei,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:Ei,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},Ug=(e,t=L.version)=>{let r=lt(Lg.join(e,"CLAUDE.md"));return r===null||!We(r,be,De)?null:Bg({content:r,expectedBody:uo(t),startMarker:be,endMarker:De,versionPrefix:fr,current:t,scope:"root"})},Wg=async(e,t,r,n=L.version)=>{let o=lt(Lg.join(e,"CLAUDE.md"));if(o===null||Et(o).state!=="ok")return null;let s;try{({body:s}=await vi(e,{repoRoot:t,version:n,declaredType:await Rt(e)}))}catch{return null}return Bg({content:o,expectedBody:s,startMarker:Ve,endMarker:Qe,versionPrefix:St,current:n,scope:r})};import Gg from"node:fs";import Jg from"node:path";var Sl="ik-mcp",Vg=(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:Sl,args:r}};var Pi="run `infra-kit setup` (or `infra-kit audit --root --fix`)",vE=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),El=e=>hr(e)&&e.command===Sl,wE=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),kE=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Vg(i,a),l=e[i];if(l!==void 0&&!El(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 ${Pi}, or drop mcp.${i} from infra-kit.json`});continue}if(El(l)&&l.type===c.type&&vE(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=wE(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: ${Pi}`:`"${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: ${Pi}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!El(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}},bE=(e,t,r)=>{let n=r===null?ml:bg(r),o=r===null||r.endsWith(`
|
|
155
155
|
`)?`
|
|
156
|
-
`:"";try{return
|
|
156
|
+
`:"";try{return Gg.mkdirSync(Jg.dirname(e),{recursive:!0}),Gg.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${hl(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},ko=({projectRoot:e,proxies:t,write:r})=>{let n=Jg.join(e,Ge),o=fl(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${hl(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:gl(s);if(!hr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Pi}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[ut];if(a!==void 0&&!hr(a))return d.warn(`${n} has a "${ut}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=kE(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=bE(n,{...i,[ut]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Kg=async(e,t)=>{let r;try{r=(await H()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=ko({projectRoot:e,proxies:r,write:t});if(n.status!=="ok"&&n.status!=="failed")return{packageDir:e,packageName:"mcp",checks:[{name:"mcp:.mcp.json",status:"fail",message:`${n.path} could not be read as JSON \u2014 fix it and re-run`}],passed:!1};let o=n.entries.filter(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 RE="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",SE=async e=>e.root?[{dir:await A(),baseline:dr,isRoot:!0}]:e.all?(await ke(await A())).map(r=>({dir:r})):[{dir:await lo(e.cwd??Hg.cwd())}],EE=async e=>e.root||e.all?await A():e.cwd??Hg.cwd(),PE=async()=>{try{return await A()}catch{return}},xE=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}},TE=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await Ig(e,t);return n&&d.info(RE),r},CE=e=>{if(Qr(e).kind!=="stale")return null;let t=`${Ge} still registers "${le}" \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 "${le}" 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}},$E=e=>e.root?"root":e.all?"all":"package",AE=async(e,t,r)=>{let n=await Cg(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await Wg(e.dir,r??e.dir,$E(t));return a?[a,...n]:n}let o=Ug(e.dir),{checks:s,rewritten:i}=await jg(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]},xi=async(e={})=>{let t=Vc(await EE(e)),r=e.fix?await TE(e,t):void 0,n=await SE(e),o=await Hr(t),s=await PE(),i=[];for(let u of n){let p=await ll(u.dir,u.baseline,{adoption:o,isRoot:u.isRoot,repoRoot:s});p.checks.push(...await AE(u,e,s)),p.passed=p.checks.every(m=>m.status!=="fail"),i.push(p)}if(e.root){let u=await Kg(n[0].dir,e.fix===!0);u&&i.push(u);let p=CE(n[0].dir);p&&i.push(p)}let{allPassed:a,warnCount:c}=xE(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}},OE={all:Ie.boolean().optional().describe("Audit every non-vendor workspace package"),root:Ie.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},DE={allPassed:Ie.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:Ie.number().int().describe("How many checks reported a warning"),packages:Ie.array(Ie.object({name:Ie.string(),passed:Ie.boolean(),checks:Ie.array(Ie.object({name:Ie.string(),status:Ie.enum(["pass","warn","fail"]),message:Ie.string()}))})).describe("Per-package check results")},Pl=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:OE,outputSchema:DE,handler:e=>xi({all:e.all,root:e.root})});import{z as F}from"zod";import{$ as WE}from"zx";var xl=1.959963984540054,IE=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],Tl=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,Cl=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],NE=/This reverts commit ([0-9a-f]{7,40})/u,Yg=/^Revert "(.*)"(?: \(#\d+\))?$/u,zg="",Ti="",Xg=`--format=${zg}%H${Ti}%ct${Ti}%B${Ti}`,Zg=e=>e.split(zg).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split(Ti),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),Zn();try{await H({autoMigrate:"off"})}catch(l){throw await
|
|
162
|
-
${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},
|
|
163
|
-
`),
|
|
158
|
+
`).map(a=>a.trim()).filter(Boolean)}}),_E=e=>IE.some(t=>t.test(e.body))?"agent":"human",$l=e=>Yg.test(e.subject),ME=e=>!$l(e)&&Tl.test(e.subject),jE=(e,t)=>{if(t===0)return null;let r=e/t,n=xl*xl,o=1+n/t,s=(r+n/(2*t))/o,i=xl*Math.sqrt(r*(1-r)/t+n/(4*t*t))/o;return{low:Math.max(0,s-i),high:Math.min(1,s+i)}},Ci=e=>Math.round(e*1e4)/1e4,qg=(e,t)=>{let r=jE(e,t);return{hits:e,n:t,rate:t===0?null:Ci(e/t),ci95:r&&{low:Ci(r.low),high:Ci(r.high)}}},FE=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!$l(n))continue;let o=e.slice(0,r),s=NE.exec(n.body)?.[1],i=Yg.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},LE=(e,t)=>{let r=new Set(e.files.filter(n=>!Cl.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},BE=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&ME(n)&&LE(e,n)),Qg=(e,t)=>{let r=FE(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(_E(u))),i=s.filter(({commit:u})=>!$l(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})=>BE(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:qg(c,i.length),followUpFixRate:qg(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},Al=(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:Ci(e.rate-t.rate),intervalsOverlap:e.ci95.low<=t.ci95.high&&t.ci95.low<=e.ci95.high}};var bo=90,VE=864e5,GE=async(e,t)=>{if(await xe(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await WE({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${Xg}`;return Zg(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},oh=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*VE).toISOString(),o=await GE(e,n),s=Qg(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:Al(s.agent.revertRate,s.human.revertRate),followUpFixRate:Al(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:Tl.source,followUpWindowHours:72,followUpIgnoredFiles:Cl,mergesExcluded:!0}}},$i=e=>`${(e*100).toFixed(1)}%`,eh=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${$i(e.rate)} (${e.hits}/${e.n}, 95% CI ${$i(e.ci95.low)}\u2013${$i(e.ci95.high)})`,Ol=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${eh(t.revertRate)}`,` ${72}h follow-up-fix rate: ${eh(t.followUpFixRate)}`].join(`
|
|
159
|
+
`),Ai=async({since:e=bo})=>{let t=await oh({cwd:await A(),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(Ol("agent",r.agent)),d.info(Ol("human",r.human)),d.info(Ol("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 = ${$i(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}},th=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")}),Dl=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:th.describe("Changes later reverted by an in-range commit"),followUpFixRate:th.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),rh=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")}),Il=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 ${bo})`)},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:Dl,human:Dl,total:Dl}),comparison:F.object({minN:F.number(),revertRate:rh,followUpFixRate:rh}),heuristics:F.object({agentTrailers:F.array(F.string()),fixSubjectPattern:F.string(),followUpWindowHours:F.number(),followUpIgnoredFiles:F.array(F.string()),mergesExcluded:F.boolean()})},handler:Ai});import{z as Jt}from"zod";import Nl from"node:fs/promises";import JE from"node:path";var tn=()=>Object.keys(gf.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),KE=new Set(["protectedEnvs"]),Ro={project:"per-project override",global:"user-global override"},Oi=(e,t)=>{if(ge()&&KE.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(!tn().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: ${tn().join(", ")}.`)}},sh=e=>{try{return JSON.parse(e)}catch{return e}},HE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qE=async e=>{let t;try{t=await Nl.readFile(e,"utf-8")}catch{return{raw:null,data:{}}}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(n){throw new Error(`Invalid JSON in ${w(e)}: ${n.message} \u2014 fix it with \`infra-kit config edit\`.`)}if(!HE(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},YE=async(e,t)=>{t===null?await Nl.rm(e,{force:!0}):Nt(e,t,420),Zn()},Di=async(e,t,r)=>{let n=await ee(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await qE(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await Nl.mkdir(JE.dirname(o),{recursive:!0}),Nt(o,`${JSON.stringify(c,null,2)}
|
|
161
|
+
`,420),Zn();try{await H({autoMigrate:"off"})}catch(l){throw await YE(o,s),new Error(`${l.message}
|
|
162
|
+
${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}},_l=async({key:e,value:t,global:r})=>{Oi(e,"config-set");let n=r?"global":"project",o=sh(t),{file:s,previous:i}=await Di(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${Ro[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 Ii=async({key:e}={})=>{let[t,r]=await Promise.all([H(),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(!tn().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${tn().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}},zE={config:Jt.record(Jt.string(),Jt.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:Jt.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:Jt.string().optional().describe("The top-level key asked for, when one was."),value:Jt.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:Jt.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},Ml=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:Jt.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:zE,handler:e=>Ii(e)});import rP from"node:fs";import{z as de}from"zod";import Eo from"node:fs";import rn from"node:path";import XE from"node:process";var ZE=rn.join(".infra-kit","dev-context"),QE=".infra-kit",ih=(e,t)=>{let r=rn.resolve(e);for(;;){let n=rn.join(r,t);if(Eo.existsSync(n))return n;let o=rn.dirname(r);if(o===r)return;r=o}},eP=e=>{let t=ih(e,ZE);if(t)return t;let r=ih(e,QE);return r?rn.join(r,"dev-context"):void 0},jl=e=>typeof e=="number"&&Number.isFinite(e)?e:0,So=e=>typeof e=="string"?e:"",tP=(e,t,r)=>{let n=rn.join(e,t);try{let o=Eo.statSync(n),s=JSON.parse(Eo.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:So(i.package),port:jl(i.port),alias:So(i.alias),origin:So(i.origin),release:So(i.release),env:So(i.env),pid:jl(i.pid),writtenAt:jl(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},Po=(e=XE.cwd())=>{let t=Date.now(),r=eP(e);if(!r||!Eo.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=Eo.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>tP(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 Ni=async(e={})=>{let t=e.now??Date.now,r=e.isListening??Yn,n=Po(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&&(rP.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}},nP={active:de.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:de.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:de.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:de.array(de.object({app:de.string().describe("App folder name (the fragment filename without .json)."),package:de.string().describe("The app package name the vite helper reads to decide a local route."),port:de.number().describe("The actual bound port the dev server is listening on."),pid:de.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:de.string().describe("Registered portless hostname for the app."),origin:de.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:de.string().describe("Release slug the runner recorded for this worktree."),env:de.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:de.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:de.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:de.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:de.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.")},Fl=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:nP,handler:()=>Ni()});import{spawnSync as lv}from"node:child_process";import ie from"node:fs";import uv from"node:os";import ye from"node:path";import gt from"node:process";import{z as Re}from"zod";import{execFileSync as oP}from"node:child_process";var ah=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},sP=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],iP=e=>sP.some(t=>t.test(e)),aP="/bin/ps",cP=()=>oP(aP,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
163
|
+
`),ch=(e=cP)=>{try{return e().some(iP)}catch{return!0}};import{Chalk as lP}from"chalk";import Ll from"node:process";var Bl={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},uP=new Set(["warn","fail"]),dP=24,nn=" ",lh=" ",pP=(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:[""]},uh=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},mP=e=>{let t=new lP({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)}},dh=(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),fP=(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=dh(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}},gP=(e,t,r,n)=>{let o=fP(uh(e.rows),e.rows.length,t,r),s=Math.max(1,n-nn.length-e.label.length-o.plainWidth);return`${nn}${t.header(e.label)}${" ".repeat(s)}${o.text}`},hP=(e,t,r,n,o)=>{let s=uP.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=lh.length+i+1+t+2,p=Math.max(dP,o-u),[m,...f]=pP(e.message,p),v=" ".repeat(u),E=h=>s?h:r.dim(h);return[`${lh}${c(n[e.status])} ${l} ${E(m??"")}`.trimEnd(),...f.map(h=>`${v}${E(h)}`),...(e.notes??[]).map(h=>`${v}${h}`.trimEnd())]},yP=(e,t,r,n,o)=>{let s=uh(t),i=n.rule.repeat(Math.max(12,Math.min(o-nn.length,56))),a=dh(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[`${nn}${r.dim(i)}`,`${nn}${c}${l.join("")}`]},Ul=(e,t={})=>{let r=t.width??80,n=mP(t.color??!1),o=t.unicode??!0?Bl.unicode:Bl.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,"",`${nn}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[gP(u,n,o,r),...u.rows.flatMap(p=>hP(p,c,n,o,r)),""]);return[a,"",...l,...yP(e,i,n,o,r)]},vP=new Set(["","0","false","none"]),wP=["LC_ALL","LC_CTYPE","LANG"],kP=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!vP.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,bP=(e,t)=>{if(t)return!1;let r=wP.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},Wl=(e={})=>{let t=e.env??Ll.env,r=e.stream??Ll.stderr;return{color:kP(t,r),unicode:bP(t,e.ascii??!1),width:r.columns??80}},dt=(e,t={})=>{(t.write??(n=>{Ll.stderr.write(n)}))(`${Ul(e,Wl(t)).join(`
|
|
164
164
|
`)}
|
|
165
|
-
`)};var
|
|
166
|
-
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:
|
|
165
|
+
`)};var RP="Tools & CLIs",SP="Shell & integration",EP="Project config",PP="Doppler env tokens",xP="Dev proxy (portless)",TP="Claude Code plugin",CP=`portless serving TLS on :${Mt}`,Vl=[[RP,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[SP,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[EP,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[PP,["tokens.json present","env tokens configured","tokens.json perms"]],[xP,["portless installed","portless node","portless service target",CP,"portless CA chain valid","portless CA trusted","portless routes"]],[TP,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],ph="Other",$P=Vl.map(([e])=>e),AP=new Map(Vl.flatMap(([e,t])=>t.map(r=>[r,e]))),vV=Vl.flatMap(([,e])=>e),Gl=new Set(["portless routes","tokens.json perms"]),OP=e=>{let t=new Map;for(let n of e){let o=AP.get(n.name)??ph,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...$P,ph].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var DP=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Ue(e)}},IP=e=>{let t=e.filter(r=>r.status==="fail"&&Gl.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:OP(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:DP(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Jl=(e,t={})=>{dt(IP(e),t)};var NP=e=>e.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"),_P=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>NP(t[1])),MP=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:_P(t[1])},jP=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},FP=e=>{let t=e.split(`
|
|
166
|
+
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:jP(t.slice(10))},mh=(e,t)=>{try{return e==="darwin"?MP(t):e==="linux"?FP(t):null}catch{return null}};import{Buffer as Dh}from"node:buffer";import _e from"node:fs/promises";import et from"node:path";import Ih from"node:process";import{$ as Ji}from"zx";import LP from"node:process";var xo=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var fh=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(Z())throw new O({status:"argument_required",argument:e,agentMode:j.source},2,t);if(!LP.stdin.isTTY)throw new g(void 0,t)},Kt=async e=>{fh("version");let{runBranchPicker:t}=await import("./boot-ST2534PA.js"),r=await t(e);if(r===null)throw new xo;return r},Ht=async(e,t)=>{fh("versions");let{runBranchMultiPicker:r}=await import("./boot-ST2534PA.js"),n=await r(e,t);if(n===null)throw new xo;return n};import{$ as bh}from"zx";import{$ as $V}from"zx";import{$ as sn}from"zx";import{$ as gh}from"zx";var Kl=async e=>{let{operation:t}=e;try{await gh({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 gh({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"})}},UP=4,on=async e=>{let{operation:t}=e,r=await ef();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}},Tt=async()=>{try{return await pn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var
|
|
168
|
+
`)}`);let n=r.slice(0,UP),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}`})},To=async e=>{let{operation:t,base:r}=e;if(await Ur()===r)return;let n=(await ot(await A())).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}`})},Ne=async e=>{let{operation:t}=e;if(await rf())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 on({operation:t})};var WP=e=>e.map(t=>({pr:t,id:Q(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Qm(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Co=200,hh=(e,t)=>{e.length<Co||d.warn({source:t,limit:Co},`\u26A0\uFE0F ${t} returned ${Co} PRs \u2014 the page is full, so older release PRs may be missing`)},VP=async()=>{let[e,t]=await Promise.all([sn`gh pr list --limit ${Co} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,sn`gh pr list --limit ${Co} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);hh(r,"release PR discovery (base dev)"),hh(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)}))},$o="find open release PRs",yh=async()=>{try{let e=await VP();if(e.length===0)throw new g(void 0,{operation:$o,remediation:"open a release PR first, or check you are in the right repo"});return WP(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},_i=async()=>(await yh()).map(t=>t.headRefName),GP=e=>{let t=Ao(e.baseRefName);if(t===null)throw new g(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Hl(e.title)!==t;return(r||e.dualBase)&&d.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},V=async()=>(await yh()).map(GP),Mi=async e=>{let{branch:t,body:r}=e;try{await sn({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}},JP=async(e,t)=>{let r=sn({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`)},ji=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=Zm(t,n),a=pt(n),c=sn({quiet:!0}),l=Pe(t),u=Oo(r,o);try{await on({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 JP(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await sn({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as ql}from"zx";var an=async e=>{let t=await ql`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Yl=async e=>{let t=await ql`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Fi=async e=>{try{let t=await ql`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 Io from"node:process";var KP="x-seraph-loginreason",HP="AUTHENTICATED_FAILED",qP=(e,t=160)=>{let r=e.split(`
|
|
169
|
+
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},wh=(e,t)=>t===HP||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",vh=(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}`,cn=class extends Error{status;kind;body;context;constructor(t){let r=wh(t.status,t.seraphLoginReason),n=qP(t.body);super(n===""?`${t.context}: ${vh(r,t.status)}`:`${t.context}: ${vh(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},Do=e=>e instanceof cn,kh=e=>e.headers.get(KP);var ln=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new cn({status:e.status,seraphLoginReason:kh(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},yr=(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 ln(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},un=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 ln(a,"Failed to get Jira project versions"),await a.json()},xt=async(e,t)=>(await un(t)).find(o=>o.name===e)||null,dn=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 ln(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}},Xl=async(e,t)=>{let{versionName:r}=e,n=await xt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await dn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},pn=async()=>{let e=Io.env.JIRA_BASE_URL,t=Io.env.JIRA_TOKEN||Io.env.JIRA_API_TOKEN,r=Io.env.JIRA_PROJECT_ID,n=Io.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}},Tt=async()=>{try{return await pn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Li=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 ln(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Zl=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 ln(c,"Failed to remove Jira version")};var Rh="dev",Sh={regular:"dev",hotfix:"main"},pt=e=>Sh[e],Ao=e=>{let t=Object.entries(Sh).find(([,r])=>r===e);return t?t[0]:null},Oo=(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),fn=e=>e.split("\0").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
|
+
`,Ql=async(e="regular")=>{let t=pt(e),r=bh({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 bh({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()},YP=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await xt(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 dn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},eu=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=ce(t),c=await YP({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=yr(r,c),u=await ji({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:re(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Bi=async()=>{let e=new Map,t=await Tt();if(!t)return e;try{let r=await un(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},pe=async()=>{let e=await Bi();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},No=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Hl=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Ui=e=>e.flatMap(t=>{let r=Q(t);return r?[{branch:t,id:r,label:re(r)}]:[]}),Ct=e=>{try{return Pe(ve(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)})}},_o=e=>{if(e===Rh)return Rh;let t=Q(e);return t?re(t):e},$t=e=>e.flatMap(t=>{let r=Q(t);return r?[re(r)]:[]}),zP=(e,t)=>t?t.get(e)||"regular":void 0,me=e=>{let{branches:t,descriptions:r,types:n}=e;return Ui(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(ce(s)),type:zP(o,n)}))};import Eh from"node:fs/promises";import XP from"node:path";import{$ as tu}from"zx";var W="pnpm-lock.yaml",ZP=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,xh=async(e,t)=>{let r=XP.join(e,W),n=`${t}:${W}`;try{let o=await tu({cwd:e,quiet:!0})`git show ${n}`;await Eh.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${W} to start from: ${Ph(o)}`}}try{await tu({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${W}: ${Ph(o)}`}}return ZP.test(await Eh.readFile(r,"utf8"))?{ok:!1,reason:`${W} still carries conflict markers after pnpm ran`}:(await tu({cwd:e,quiet:!0})`git add -- ${W}`,{ok:!0})},Ph=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as vr}from"zx";var ru="Merge remote-tracking branch 'origin/dev' into ",QP=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},ex=2048,tx=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-ex)).filter(s=>s.length>0).join(`
|
|
174
|
+
`)||`the verify command exited with code ${n??"unknown"} and printed nothing`},rx=async e=>{try{return(await vr({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[]}},nx=async(e,t)=>{let r=QP(t),n=await rx(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await af(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Th=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await xe(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 ox({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},ox=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await xe(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Xn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await Sc(r),await vr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${ru}${n}`;await vr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await vr({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 nx(r,i)}}finally{await Ec(r)}},Ch=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),$h="pnpm install --frozen-lockfile",Ah=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await Sc(t),await vr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await vr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,tx(a))}finally{await Ec(t)}return{kept:o,failed:s}},Mo=async(e,t,r="origin/dev")=>{await vr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Xn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import nu from"node:process";var Wi=new Set,Vi=e=>(Wi.add(e),()=>{Wi.delete(e)}),sx=async()=>{for(let e of[...Wi])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}Wi.clear()},ix=["SIGINT","SIGTERM"],Oh=async(e,t={})=>{let{register:r=(i,a)=>{nu.on(i,a)},unregister:n=(i,a)=>{nu.off(i,a)},exit:o=i=>{nu.exit(i)}}=t,s=new Map;for(let i of ix){let a=()=>{sx().then(()=>{o(Pf(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var ax="pnpm install --frozen-lockfile --ignore-scripts",ou="pnpm install --frozen-lockfile",Nh=64*1024,Lh=4096,Fo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Lh)},B=async(e,t)=>(await Ji({cwd:e,quiet:!0})`git ${t}`).stdout,iu=e=>e.split(`
|
|
176
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),fn=e=>e.split("\0").filter(t=>t.length>0),wr=async(e,t)=>{try{return(await B(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Bh=async e=>et.resolve(e,(await B(e,["rev-parse","--git-common-dir"])).trim()),au=e=>e.then(()=>!0,()=>!1),jo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),cu=e=>e?.length===1&&e[0]===W,Uh=async e=>et.join(await Bh(e),"infra-kit","merge-dev-resolutions"),lu=async(e,t)=>et.join(await Uh(e),`${of(t)}.json`),Wh=async e=>{try{return JSON.parse(await _e.readFile(e,"utf8"))}catch{return null}},gn=async(e,t)=>{let r=await lu(e,t.branch);await _e.mkdir(et.dirname(r),{recursive:!0}),await _e.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
177
|
+
`)},Vh=async e=>{let t=await Uh(e),r=await _e.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Wh(et.join(t,o))))).filter(o=>o!==null)},Gh=async e=>Promise.all((await Vh(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await au(_e.stat(t.worktreePath))}))),_h=(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}),cx=e=>e.editablePaths??e.conflictPaths,lx=e=>et.posix.basename(e)==="package.json",uu=e=>e.conflictPaths.includes(W)||e.lockfileBlob!==void 0,Jh=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(W);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=fn(await B(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await pu(e),...r].some(lx)},Kh=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",du=async(e,t,r)=>{await B(e,["worktree","remove","--force",r]).catch(()=>_e.rm(r,{recursive:!0,force:!0})),await _e.rm(await lu(e,t),{force:!0}).catch(()=>{}),await B(e,["worktree","prune"]).catch(()=>{})},Hh=async e=>fn(await B(e,["diff","--name-only","-z","--diff-filter=U"])),Gi=async e=>fn(await B(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),ux=async(e,t)=>{let r=(await B(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await au(_e.stat(et.join(await Bh(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(iu(await B(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},qh=e=>e.split("/").includes("node_modules"),Ki=async(e,t)=>{let r=new Set(cx(t));t.editablePaths&&await Jh(e,t)&&r.add(W);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=fn(await B(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await pu(e),...o].filter(a=>!r.has(a)),i=(await Gi(e)).filter(a=>!n.has(a)&&!qh(a));return[...new Set([...s,...i,...await dx(e)])].sort()},pu=async e=>{let t=fn(await B(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},dx=async e=>(await B(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)),px=async(e,t)=>{let r=`:(exclude)${W}`;try{return await B(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()}},mx=async(e,t)=>{let r=[];for(let n of t)(await au(_e.lstat(et.join(e,n)))||(await B(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await B(e,["--literal-pathspecs","add","-A","--",...r])},su=async e=>(await B(e,["write-tree"])).trim(),Yh=async e=>(await B(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),fx=e=>{let t=`${ou} && `;if(e!==ou)return e?.startsWith(t)?e.slice(t.length):e},gx=e=>e?`${ou} && ${e}`:ax,hx=async(e,t)=>{try{return await Ji({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Fo(r)}}},zh=async(e,t)=>{let r=(await B(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await B(e,["diff","--cached","--stat",l,"--",W])).trim(),o=uu(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await B(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${W}`]),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=Dh.byteLength(a)>Nh;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Dh.from(a).subarray(0,Nh).toString():a,resolutionDiffTruncated:c}},Xh=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 Mh(t,a,o,"conflict"));for(let a of n)i.set(a,await Mh(t,a,o,"verify-failed",s));return i},yx=async(e,t,r)=>{let n=async(a,c)=>fn(await B(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!==W).sort(),lockfileBothSides:o.includes(W)&&s.includes(W)}},vx=async(e,t,r,n)=>{let o=await Hh(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await wr(e,"HEAD"),a=await wr(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 yx(e,r,n),autoMergeTree:await su(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await wr(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await ux(e,o),lockfileOnly:cu(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await B(e,["--version"])).trim()})`}},wx={conflict:"needs-agent","verify-failed":"verify-failed"},Mh=async(e,t,r,n,o)=>{let s=await Wh(await lu(e,t));if(s)return{resolution:_h(s,"exists"),reason:`resolution-exists: ${s.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let i=await xe(e,`origin/${t}`);if(!i)return{reason:`origin/${t} does not exist on origin`};let a=sf(e,t),c=()=>du(e,t,a),l=Vi(c);try{await B(e,["worktree","prune"]),await _e.mkdir(et.dirname(a),{recursive:!0}),await B(e,["worktree","add","--detach",a,i]),await Ji({cwd:a,quiet:!0})`git merge --no-commit ${r} -m ${ru+t}`.catch(()=>{});let u=await vx(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 Gi(a),cliVersion:L.version,createdAt:new Date().toISOString()};return await gn(e,p),{resolution:_h(p,p.lockfileOnly?"lockfile-only":wx[n])}}catch(u){return await c(),{reason:Fo(u)}}finally{l()}},Zh=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Vh(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=Pe(ve(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 Ht(me({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},kx=async(e,t)=>{let r=await _e.realpath(t).catch(()=>null);if(!r)return!1;let n=await ot(e);for(let o of n)if(await _e.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},mn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Qh=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 kx(e,n))return mn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await wr(n,"HEAD"),i=await wr(n,"MERGE_HEAD"),a=r??fx(t.handOffVerify);return s===t.baseSha&&i===t.devSha?Px(e,t,o,a):bx(t,o,s,i)},bx=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return mn(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 Yh(o),i=n?null:await wr(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 mn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Ki(o,e);return c.length>0?mn(t,"out-of-scope-edit",Kh(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:uu(e),...await zh(o,e)}},jh=async(e,t)=>{let r=iu(await B(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},Rx=async(e,t)=>{let r=t.worktreePath,n=await jh(r,W),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await wr(r,`${t.autoMergeTree}:${W}`),i=await xh(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[W]};let a=await jh(r,W);if(a!==null&&a!==o&&(t.lockfileBlob=a,await gn(e,t)),n!==null&&n!==a&&!s)return n===o?{code:"tree-changed",detail:`rebuilding ${W} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[W]}:{code:"out-of-scope-edit",detail:`${W} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[W]};let c=await Ki(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},Sx=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await pu(r)).filter(c=>n.has(c)):t.conflictPaths;await mx(r,o.filter(c=>c!==W));let s=await Ki(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:Kh(t),paths:s};let i=(await Hh(r)).filter(c=>c!==W);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await px(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Fo(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await Jh(r,t)?Rx(e,t):null},Ex=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 Gi(o)),i=await hx(o,n),a=(await Gi(o)).filter(c=>!s.has(c)&&!qh(c)&&et.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await gn(e,t),i},Px=async(e,t,r,n)=>{let o=t.worktreePath,s=await Sx(e,t);if(s)return{...r,blocked:s};let i=uu(t),a=await su(o),c=await Ex(e,t,a,gx(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return mn(l,"verify-failed",c.reason??"the verify command failed");let u=await Ki(o,t),p=iu(await B(o,["diff","--name-only"]));return u.length>0||p.length>0||await su(o)!==a?mn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await gn(e,t)),{...l,...await zh(o,t)})},xx=12e4,Tx=async(e,t=xx)=>{let r=Ji({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Ih.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Ih.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Fo(s)};let i=(await B(e,["rev-parse","--git-path","index.lock"])).trim();return await _e.rm(et.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},Cx={"verify-failed":"verify-failed","tree-changed":"tree-changed"},$x=e=>{let t=e.blocked;return{branch:e.branch,status:Cx[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},Ax=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 Tx(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await B(o,["rev-parse","HEAD"])).trim(),c=(await B(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await gn(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 Yh(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}},Ox=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 Mo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Fo(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 xe(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Xn(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)},Dx=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}`)},ey=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Zh({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),jo();if(i)return Fh(t,a,o,s);let c=[];for(let m of a){let f=await Qh(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await gn(t,m)),c.push(f)}Dx(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 G(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Ix(p)})}catch(m){if(!bt(m))throw m;return{...jo(),declined:!0}}return Fh(t,a,o,p)},ty=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},Ix=e=>{let t=[],r=!1;for(let o of bf())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"]},Nx=async(e,t,r,n)=>{let o=await Qh(e,t,r);if(o.blocked)return $x(o);let s=await Ax(e,o,t,n);if(!("sha"in s))return s;let i=await Ox(e,t,s.sha);return i==="keep"?s:i},_x=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 ri(e,r),o=[];for(let s of t){let i=n.pushed||await Wr(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(-Lh)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
|
|
183
|
+
`)[0]}}},Fh=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await Nx(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await _x(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 du(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}},ry=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Zh({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),jo();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await G(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!bt(a))throw a;return{...jo(),declined:!0}}for(let a of s)await du(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...jo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Mx from"node:fs";import jx from"node:os";import Fx from"node:path";var Lx="infra-kit.json",Bx="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)",Ux="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Lo=async()=>{let e;try{e=await A()}catch{return null}let t=e.trim();return t===""||t===jx.homedir()?null:t},ny=async()=>{let e=await Lo();return e===null&&d.info(Bx),e},Wx=async()=>{let e=await Lo();return e===null?null:Mx.existsSync(Fx.join(e,Lx))?e:(d.info(Ux),null)};var Vx=async e=>{try{return await ke(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},oy=async({dryRun:e=!1}={})=>{let t=await Wx(),r=L.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await fo(t,{version:r,dryRun:e})];for(let o of await Vx(t)){let s=await Rt(o);n.push(...await go(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import he from"node:fs";import Qi from"node:os";import se from"node:path";import Su from"node:process";import mu from"node:fs";import sy from"node:os";import iy from"node:path";import Gx from"node:process";import{z as qi}from"zod";var ay=e=>{try{return mu.readFileSync(e,"utf-8")}catch{return null}},hn="claude in chrome",Jx="com.anthropic.claude_code_browser_extension",Hi="run `/chrome` inside Claude Code to set up Claude in Chrome",Kx={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},Hx=e=>{try{return mu.accessSync(e,mu.constants.X_OK),!0}catch{return!1}},cy=e=>{try{return JSON.parse(e)}catch{return null}},qx=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Bo=(e={})=>{let t=e.platform??Gx.platform,r=e.home??sy.homedir(),n=e.readText??ay,o=e.isExecutable??Hx,s=Kx[t];if(s===void 0)return{name:hn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=iy.join(r,...s,`${Jx}.json`),a=n(i);if(a===null)return{name:hn,status:"warn",message:`Chrome native host not registered \u2014 ${Hi}`};let c=qi.object({path:qi.string().min(1)}).safeParse(cy(a));if(!c.success)return{name:hn,status:"fail",message:`${w(i)} has no host path \u2014 ${Hi} again`};let l=c.data.path;if(!o(l))return{name:hn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${Hi} again`};let u=qx.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:hn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${Hi} again`}:{name:hn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},fu=(e={})=>{let t=e.home??sy.homedir(),r=e.readText??ay,n=qi.object({claudeInChromeDefaultEnabled:qi.boolean().optional()}).safeParse(cy(r(iy.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import zi from"node:fs/promises";import Yx from"node:path";import zx from"node:process";var ly=` // // 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=Ah.byteLength(a)>Dh;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.`,gu=()=>`// 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=Ah.byteLength(a)>Dh;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
|
+
${ly}
|
|
319
319
|
}
|
|
320
|
-
`,
|
|
320
|
+
`,hu=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 @@ ${ay}
|
|
|
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
|
+
${ly}
|
|
337
337
|
}
|
|
338
|
-
`,
|
|
338
|
+
`,yu=()=>`// 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,109 @@ ${ay}
|
|
|
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 uy=!1,Xx=e=>e.replace(/\.json$/,".example.jsonc"),Zx=async e=>{try{return await zi.readFile(e,"utf-8")}catch{return null}},yn=async e=>{let t=e.userProject,r=Xx(t);await zi.mkdir(Yx.dirname(t),{recursive:!0});let n=!await ne(t);n&&await zi.writeFile(t,`{}
|
|
351
|
+
`,"utf-8");let o=hu(e.projectName),s=await Zx(r)!==o;return s&&await zi.writeFile(r,o,"utf-8"),n&&Zn(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},vn=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,vu=async()=>{if(zx.env.INFRA_KIT_NO_SEED||uy)return;uy=!0;let e;try{e=await ee()}catch{return}if(await ne(e.main))try{let t=await yn(e);t.createdConfig?d.info(vn(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 lT}from"node:child_process";import wy from"node:fs";import Rn from"node:process";import{fileURLToPath as ky}from"node:url";import Xi from"node:fs";import wn from"node:path";var dy="auto-setup.json",Qx="auto-setup.log",eT="auto-setup.lock",py="auto-setup.notified",tT=3,rT=3600*1e3,nT=()=>wn.join(wt(),dy),kn=()=>wn.join(wt(),Qx),my=()=>wn.join(wt(),eT),oT=()=>wn.join(wt(),py),sT=new Set(["ok","attention","failed"]),iT=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"&&sT.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},aT=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(iT)},bn=(e=t=>Xi.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(nT()));return aT(t)?t:null}catch{return null}},fy=e=>{let t=wt();Xi.mkdirSync(t,{recursive:!0}),Nt(wn.join(t,dy),JSON.stringify(e),384)},cT=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),gy=(e=t=>Xi.readFileSync(t,"utf8"))=>{try{let t=Number(e(oT()).trim());return Number.isFinite(t)?t:null}catch{return null}},hy=e=>{let t=wt();Xi.mkdirSync(t,{recursive:!0}),Nt(wn.join(t,py),String(e),384)},yy=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<rT?!1:e.version!==t?!0:cT(e)&&e.attempts<tT};var vy=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],wu=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return vy.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?$m(o,s,i)?"local-install":null:"not-a-tty"};var uT=e=>{lT(Rn.execPath,[e,"--parent-pid",String(Rn.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},dT=()=>ky(new URL("./update-check.js",import.meta.url)),pT=()=>wy.realpathSync(ky(new URL("./cli.js",import.meta.url))),mT=/^[\w@./+ -]+$/,fT=e=>mT.test(e),gT=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||kt(e.latestVersion,t)&&e.updateCommand.every(fT)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ys(e.updateCommand)}`)},hT=(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(kn())}, or run: infra-kit setup`),o(e.finishedMs)},ku=(e,t={})=>{try{let r=t.argv??Rn.argv,n=t.env??Rn.env,o=t.isTty??!!Rn.stdout.isTTY,s=t.cwd??Rn.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??pT(),c=t.readCache??to,l=t.spawnChild??uT,u=t.fileExists??(v=>wy.existsSync(v)),p=t.notify??(v=>{d.info(v)});if(wu({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:Ee})!==null)return;let m=c();gT(m,e,p);try{hT((t.readAutoSetup??bn)(),e,(t.readNotified??gy)(),p,t.writeNotified??hy)}catch{}if(!Ac(m,i))return;let f=t.childPath??dT();if(!u(f))return;l(f)}catch{}};import ft from"node:fs/promises";import mt from"node:path";import{pathToFileURL as wT}from"node:url";import kT from"yaml";import{z as Pn}from"zod";import yT from"node:fs/promises";import bu from"node:os";import Ru from"node:path";import{z as vT}from"zod";import{z as Uo}from"zod";var by="vendor.json",Ry=Uo.object({workspaceDir:Uo.string().min(1),source:Uo.string().min(1),targets:Uo.array(Uo.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 Sn=()=>Ru.join(bu.homedir(),Rm,by),En=e=>{if(e==="~")return bu.homedir();if(e.startsWith("~/"))return Ru.join(bu.homedir(),e.slice(2));if(Ru.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Zi=async()=>{let e=Sn(),t;try{t=await yT.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 ft.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&&
|
|
360
|
-
`,"utf-8"),await ft.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}`)}}},
|
|
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 Xe.withheld?[Vo("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?[]:Xe.withheld?
|
|
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=Ry.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${vT.prettifyError(n.error)}`);return n.data};var Sy=e=>e.replace(/\.json$/,".yml"),Ey=async()=>{let e;try{e=await ee()}catch{return}let t={label:"infra-kit.json",yml:Sy(e.main),json:e.main,schema:hf},r=[...Xe.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:mt.join(mt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:Pc},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Sy(e.userProject),json:e.userProject,schema:Pc}],n=0;for(let o of r){let[s,i]=await Promise.all([ne(o.yml),ne(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 ft.readFile(o.yml,"utf-8"),c=kT.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${Pn.prettifyError(l.error)}`);continue}await ft.mkdir(mt.dirname(o.json),{recursive:!0}),await ft.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
|
|
359
|
+
`,"utf-8"),await ft.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&&jt()},Py=async()=>{let e;try{e=await ee()}catch{return}let t=mt.dirname(e.userGlobal),r=[{from:mt.join(t,"config.json"),to:e.userGlobal},{from:mt.join(t,"config.example.jsonc"),to:mt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([ne(o),ne(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await ft.mkdir(mt.dirname(s),{recursive:!0}),await ft.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&&jt()},bT=Pn.object({workspaceDir:Pn.string().min(1),targets:Pn.array(Pn.string()).min(1)}).strict(),xy=async()=>{let e=Sn(),t=mt.dirname(e),r=mt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ne(r),ne(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 ft.stat(r),c=(await import(`${wT(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=bT.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${Pn.prettifyError(p.error)}`);return}await ft.mkdir(t,{recursive:!0}),await ft.writeFile(e,`${JSON.stringify(p.data,null,2)}
|
|
360
|
+
`,"utf-8"),await ft.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}`)}}},Ty=async()=>{let e=await RT(),t=0;for(let r of e)if(await ne(r))try{let n=await df(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof lf?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&jt()},RT=async()=>{try{let e=await ee();return Xe.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[vf()]}};var kr="# -- infra-kit:begin --",qt="# -- infra-kit:end --",ST=[["# region infra-kit","# endregion infra-kit"]],ET="# infra-kit shell functions",xn=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},Tn="Run `source ~/.zshrc` or open a new terminal to activate.",PT={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Je=async(e,t)=>{try{return await t()}catch(r){throw new xn(e,r)}},Eu=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Je("zshrc",()=>{r(CT())}),await Je("zshenv",()=>{r($T())}),await Je("migrations",async()=>{await OT(),AT(),r(PT)}),await Je("user-config",()=>{r(IT())});let n=await Je("guidance",async()=>{let{entries:s,root:i}=await jT();return r(...s),i}),o=await Je("plugin-pointer",async()=>ny());return r(...LT(o,n)),await Je("worktrees",async()=>{r(...await GT(o))}),await Je("plugin-pointer",async()=>{await KT(o,r)}),await Je("mcp-proxies",async()=>{r(...await qT(o))}),await Je("project-config",async()=>{r(...await NT(o))}),await Je("token-perms",async()=>{r(await TT())}),await Je("chrome",()=>{r(xT())}),r(...DT()),t},xT=()=>{let e=Bo();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"}:fu()?{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"}},TT=async()=>{let e=await xf();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 $y=e=>{let t=se.dirname(e);return he.existsSync(se.join(e,".git"))?e:t===e?null:$y(t)},Ay=(e,t,r,n)=>{if(!Xe.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=he.realpathSync(t)}catch{}return $y(se.dirname(o))===null?null:Vo(e,Qi.homedir(),o,["the infra-kit block updated"])},Oy=e=>he.existsSync(e)?he.readFileSync(e,"utf-8"):null,CT=()=>{let e=se.join(Qi.homedir(),".zshrc"),t=Oy(e),r=t===null?"":zT(t),n=Jr({content:r,body:Ny(),startMarker:kr,endMarker:qt,placement:"append-end"}),o=Ay("zshrc",e,t,n);return o!==null?o:(he.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},$T=()=>{let e=se.join(Qi.homedir(),".zshenv"),t=Oy(e),r=Jr({content:t??"",body:Pu(),startMarker:kr,endMarker:qt}),n=Ay("zshenv",e,t,r);return n!==null?n:(he.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},AT=()=>{he.rmSync(se.join(wt(),"projects"),{recursive:!0,force:!0})},OT=async()=>{await Ey(),await Py(),await Ty(),await xy()},DT=()=>{let e=Su.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:Tn,level:"info"}),t},IT=()=>{let e=se.join(Qi.homedir(),".infra-kit"),t=se.join(e,"infra-kit.json");return he.mkdirSync(e,{recursive:!0}),he.writeFileSync(se.join(e,"infra-kit.example.jsonc"),gu(),"utf-8"),he.writeFileSync(se.join(e,"vendor.example.jsonc"),yu(),"utf-8"),he.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(he.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"})},NT=async e=>{if(Su.env.INFRA_KIT_NO_SEED)return[Wo("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[Wo("skipped","not inside a git repository")];try{let t=await ee();if(!he.existsSync(t.main))return[Wo("skipped",`no project config at ${t.main}`)];let r=await yn(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:vn(r),level:"info"}]:[Wo("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[Wo("warned",t instanceof Error?t.message:String(t))]}},Wo=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),_T=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},MT=(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"},..._T(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},jT=async()=>{let{skipped:e,root:t,version:r,written:n}=await oy({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:MT(r,n)}},ea=e=>`cd ${Dm(e)} && infra-kit setup --skip-tools`,Vo=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${ea(t)}`,level:"info"}),FT=(e,t)=>{let r=se.relative(e,t.path);return t.status==="withheld"?Vo("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"}},Cy=(e,t)=>{let r=Ge;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?le: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 ${ut} from ${se.join(e,Ge)} \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 "${le}" key`:`no ${r}`})`,level:"info"}},LT=(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 ${Y} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],BT=()=>[yl,Pt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),UT=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:Ys(e.updateCommand),level:"info"}]:[r]},WT=(e,t)=>e.status==="skipped-cli-stale"?UT(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${Y} 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: ${en}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${Y} (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"},...BT()]:[{step:"plugin-pointer",outcome:"warned",message:`Could not install the Claude Code plugin \u2014 ${e.status==="unverified"?"the install reported success but Claude Code recorded no installation":`the ${e.step} step failed: ${e.error}`}. Run by hand: ${Pt}`,level:"warn"}],Dy={stale:!1},VT=async()=>{let e=to(),t=e===null?await Dc(Su.env):e.latestVersion;return t===null||!Ic(t,L.version)?Dy:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Cm(t)}},GT=async e=>{if(e===null)return[];let r=`${await $e(e)}${fe}`,n=Object.values(Lr).filter(o=>!he.existsSync(se.join(r,o)));for(let o of Object.values(Lr))he.mkdirSync(se.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"}]},JT=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${Y} is installed; the update worker keeps it current`,level:"debug"}]:[Vo("plugin-pointer",e,".claude/settings.json",[`the ${Y} plugin installed`])],KT=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(FT(e,vl(se.join(e,".claude","settings.json"),{write:!Xe.withheld})));let r=cr({projectPath:e}).kind==="installed";if(Xe.withheld){t(...JT(e,r),Cy(e,Qr(e)));return}let n=r?await VT():Dy;t(...WT(pl({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(Cy(e,Qr(e)))}catch(r){let n=r instanceof Error?r.message:String(r);t({step:"plugin-pointer",outcome:"warned",message:`Could not finish the Claude Code plugin step for ${e} (${n}). Run by hand: ${Pt}`,level:"warn"})}},Iy=(e,t)=>{let r=se.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},HT=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=Iy(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,Vo("mcp-proxies",e,se.relative(e,t.path),s)]},qT=async e=>{if(e===null)return[];if(!he.existsSync(se.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 H()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
|
|
362
|
+
`)[0]??n;return Xe.withheld?[Vo("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?[]:Xe.withheld?HT(e,ko({projectRoot:e,proxies:t,write:!1})):Iy(e,ko({projectRoot:e,proxies:t,write:!0}))},YT=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"),zT=e=>{let t=Vt(e,kr,qt);if(t!==null)return t;for(let[a,c]of ST){let l=Vt(e,a,c);if(l!==null)return l}let r=e.indexOf(ET);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&&YT(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),dC=async()=>{let e=await lC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return uC(e.stdout)},pC=async()=>{let e=await Tt();return e?(await un(e)).map(r=>r.name):[]},Xo=async()=>{let[e,t]=await Promise.allSettled([dC(),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"),Iu({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import mC from"node:fs";import fC from"node:path";var Bu=[".claude/settings.json",".claude/settings.local.json"],gC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],hC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),yC=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},vC=(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(hC).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},wC=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},kC=()=>Sr.filter(e=>e.mutating),bC=e=>{let t=yC(e);return t===null?[]:kC().filter(r=>gC.some(n=>wC(r).some(o=>vC(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},RC=(e,t)=>{let r;try{r=mC.readFileSync(fC.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}},Yy=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Bu){let n=RC(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=bC(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var SC=e=>e.every(t=>t.status!=="fail"),EC=["brew","git","gh","doppler","aws"],PC=async e=>{let t=await qo(EC,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}}},xC=async()=>{let e="orca installed",t=await Lt();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)"}},lv=(e,t,r,n)=>{let o=ye.join(cv.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(wr),c=i.indexOf(Ht);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+Ht.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`}},TC=()=>lv("zshrc init block",".zshrc","shell",Iy()),CC=()=>lv("zshenv session block",".zshenv","session-env",Eu()),$C=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}`}}},AC=async()=>{try{return Mt(),{config:await H(),error:null}}catch(e){return{config:null,error:e}}},OC=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)"}},DC=384,Uu=448,IC=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(", "),NC=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}}})),_C=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Ze,o=t.resolveToken??Af;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 NC(await ii(),o);return{name:r,status:"pass",message:IC(s)}},MC=()=>gt.env[lr]||void 0,jC=async(e={})=>{let t="tokens.json present",r=e.readStore??Ze,n=e.storePath??Ft;if((e.readEnvToken??MC)())return{name:t,status:"skip",message:`${lr} 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 ${lr} 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},FC=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Ft,o=t.statPath??LC,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:Uu,actual:Zo(l,o)},{target:c,expected:Uu,actual:Zo(c,o)},{target:a,expected:Uu,actual:Zo(a,o)},{target:i,expected:DC,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")}`,LC=e=>{try{return ie.statSync(e)}catch{return null}},BC=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}}},UC=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"}},Xy=/^\d+\.\d+\.\d+$/,Zy=(e,t)=>e===t||!Xy.test(e)||!Xy.test(t)?!1:Dn([`v${e}`,`v${t}`])[0]===`v${e}`,WC=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]:[]})},Qy=e=>Dn(e.map(t=>`v${t}`)).map(t=>t.slice(1)),VC=async(e,t,r)=>{let n="Guidance version",o=pr(t,mr),s=await WC(e),a=(o===null?s:[o,...s]).filter(p=>kt(p,r));if(a.length>0){let p=Qy(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&&Zy(o,r),l=s.filter(p=>Zy(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 ${Qy(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},GC=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 VC(r,o,L.version)]},JC=async()=>{try{let e=(await ee()).main;return ie.existsSync(e)?ye.dirname(e):null}catch{return null}},KC=e=>{let t=yf();return t===null||!kt(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${en}`},HC=e=>{let t=e.kind==="installed"?ri(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}${KC(t)}`}},ev=3,tv=(e,t)=>Ee(e)===Ee(t),qC=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(tv(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 tv(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}`},YC=(e,t)=>{let r="plugin installed",n=qC(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-ev,i=s>0?` and ${s} more`:"",a=`${o.slice(0,ev).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${Y} is installed for ${a} only, not this project. Run: ${Pt}${n}`}},zC=()=>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 XC=(e,...t)=>{try{return JSON.parse(ie.readFileSync(ye.join(e,...t),"utf-8"))}catch{return null}},ZC=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ri(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=XC(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)}},rv=e=>`Plugin ${Y} ${e===null?"(version unreadable)":e}`,QC=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:`${rv(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:`${rv(e.version)} is skills-only \u2014 no ${Ge}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},e$=(e,t)=>{let r=ar(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 ${jt}`},YC(r,t),HC(r),QC(ZC(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${L.version}`}]},t$=(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`}},r$=({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(", ")},n$=e=>{let t="Agent mode",r=Ys(e),n=r$(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})`}},nv=4,o$=e=>{let t=e.slice(0,nv).join(", "),r=e.length-nv;return r>0?`${t} +${r} more`:t},s$=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=Yy(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"} (${o$(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 ${Bu.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`}},i$=(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`},a$=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 Wh(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} (${i$(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`}},uv=e=>vc(["trust"],{bin:e}),c$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),ov="ERR_TLS_CERT_ALTNAME_INVALID",dv=()=>`portless serving TLS on :${_t}`,l$=async(e,t,r)=>{let n=dv();return await e(_t,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${_t}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${_t}. Install it once (needs root): \`${Nt(t,r)}\`.`}},u$=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(_t,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(ov)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${ov} 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=>c$.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 \`${uv(n)}\`, or reinstall: \`${Nt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},d$=(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: \`${uv(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 \`${vc(["alias","--remove","<name>"],{bin:r})}\`.`}},zt="portless service target",es=e=>({name:zt,status:"warn",message:e}),pv=e=>e==="darwin"?Im:e==="linux"?Nm:null,m$=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Dm}`:`sudo systemctl restart ${_m}`,f$="/bin/ps",g$=e=>{try{let t=av(f$,["-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}},sv=e=>{try{return ie.readFileSync(e,"utf-8")}catch{return null}},h$=e=>{try{return ie.statSync(e).mtime}catch{return null}},y$=2e3,v$=e=>{try{let t=av(e,["-p","process.version"],{encoding:"utf-8",timeout:y$}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},w$=(e,t)=>({platform:e.platform??gt.platform,readServiceFile:e.readServiceFile??sv,readFile:e.readFile??sv,exists:e.exists??ie.existsSync,realpath:e.realpath??Ee,mtime:e.mtime??h$,execPath:e.execPath??gt.execPath,home:e.home??cv.homedir(),cwd:e.cwd??gt.cwd(),repoRoot:e.repoRoot??Lo,stateDir:(e.stateDir??jm)(),processStartTime:e.processStartTime??g$,version:e.version??gt.version,arch:e.arch??gt.arch,nodeVersionOf:e.nodeVersionOf??v$,isGlobal:e.isGlobal??qs().node.isGlobal,nodeFs:e.nodeFs??ie,stableNode:null,stableNodeSidecar:null,bin:t}),ts="portless node",Er="~/.infra-kit/node",Qo=e=>({row:{name:ts,status:"fail",message:e},stableNode:null,sidecar:null}),iv=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},k$=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,b$=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,R$=e=>{let t=Wm(e.home),r=iv(e.nodeFs.lstatSync,t);if(r===void 0)return Qo(`${Er} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Qo(`${Er} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Vm(e.home,e.nodeFs);if(n===null)return Qo(`${Er} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=iv(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(`${Er} 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(!b$(c,e))return Qo(`${Er} does not run as Node ${e.version} (${k$(c)}). Re-run through the current Node: \`${Nt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:ts,status:"pass",message:`${Er} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},S$=e=>{if(pv(e.platform)===null)return{row:{name:ts,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=R$(e);return e.isGlobal()?t:{...t,row:{name:ts,status:"skip",message:`not a global install; the global infra-kit keeps ${Er} current`}}},mv=(e,t)=>{let r=w$(e,t),n=S$(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},E$=(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"?"}},P$=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)},x$=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},T$=(e,t,r)=>{let n=P$(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(x$(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ye.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},C$=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:qn(await t.repoRoot()??r,e,t.realpath)},Pr=e=>({state:"drifted",row:e}),$$=async(e,t,r)=>{let n=Nt(r.bin,r);if(!r.exists(e))return Pr({name:zt,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(wc(r.home),"dist","cli.js");if(t!==o)return Pr(es(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Hs(r.home,r.exists)===null)return Pr({name:zt,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(wc(r.home));if(await C$(s,r))return Pr({name:zt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=A$(e,n,r);if(i!==null)return i;let a=E$(s,r),c=T$(s,a,r);return c!==null?{state:"converged",row:es(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${m$(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:zt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},A$=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Pr(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:Pr(es(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),fv=async e=>{let t=pv(e.platform);if(t===null)return{state:"absent",row:{name:zt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:zt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=dh(e.platform,r)??[];return n===void 0||o===void 0?Pr(es(`could not parse ${t} \u2014 re-run \`${Nt(e.bin,e)}\` to rewrite it.`)):$$(n,o,e)},gv=async(e,t)=>{let{seams:r}=mv(e,t);return{state:(await fv(r)).state,stableNode:r.stableNode}},O$=()=>[ts,zt,dv(),"portless CA chain valid","portless CA trusted","portless routes"],D$=async(e={})=>{let t=e.resolveBin??Om,r=e.isProxyServing??Mm,n=e.handshake??Bm,o=e.caTrusted??Lm,s=e.routes??zn,i=e.isListening??Yn,a=(e.caPath??Fm)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...O$().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}=mv(e,c),m=s(),f=await l$(r,c,u),v=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await u$(n,m,a,c,u);return[l,p,(await fv(u)).row,f,v,d$(o(),a,c),await p$(m,i,c)]},I$=async(e={})=>{let t="portless routes",r=e.routes??zn,n=e.isListening??Yn,o=e.devSessionRunning??ih,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}=sh(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??Um().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},sa=async(e={})=>{let t=await AC(),r=PC(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"),xC(),Promise.resolve(TC()),Promise.resolve(CC()),$C(),Promise.resolve(OC(t)),jC(),_C(t),FC(e.fix??!1),BC(),UC()]),s=await D$(e.portlessDeps);if(e.fix){let m=await I$(),f=s.findIndex(v=>v.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await JC(),a=await Lo(),c={projectDir:gt.env.CLAUDE_PROJECT_DIR||null,cwd:gt.cwd(),gitRoot:a},l=[await zC(),...e$(i,c),Bo(),n$({env:gt.env,stdinIsTTY:gt.stdin.isTTY===!0,flag:j.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:s$(a)],u=[...o,await a$(a),...s,...await GC(),...l,t$(bn(),L.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Wl.has(m.name),detail:m.detail})),allPassed:SC(u),cliVersion:L.version};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}},Wu=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:()=>sa()});import{E2E_MODE_ENV as iA}from"@slip-stream-kit/config/internal";import zu from"node:fs";import aA from"node:os";import ns from"node:path";import ca 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 N$,loadDev as _$,readAppAliasName as M$,readCloudOrigin as j$,readLocalContext as yv}from"@slip-stream-kit/config/internal";import hv from"node:fs";import xr from"node:path";import ia from"node:process";import{z as Vu}from"zod";var F$=async e=>{let t=xr.join(e,"apps"),r=hv.existsSync(t)?hv.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=xr.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},L$=(e,t)=>{let[r,n]=xr.relative(e,t).split(xr.sep);return r==="apps"&&n?n:void 0},B$=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(L$(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:Vu.toJSONSchema(Vu.object({app:Vu.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(", ")}`})},U$=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}})),W$=e=>Po(e).apps.find(t=>t.env!=="")?.env??null,Gu=async(e,t={})=>{let r=t.cwd??ia.cwd(),n=t.projectRoot??await A(),o=(t.env??ia.env)[jr]||null,s=t.healthProbe??Ic,i=B$(await F$(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=xr.join(n,"apps",c,l),p=(await dr(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 ${xr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Wf(u),v=M$(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=yv(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?W$(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}},vv=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}},Ju=async(e,t={})=>{let r=t.healthProbe??Ic,n=yv(e.targetDir),o=e.kind==="ui"?await _$(e.targetDir):void 0,s=o?.proxy?N$({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:j$(e.deployedUrlEnv??void 0,t.env??ia.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...vv(e),mode:"local",baseUrl:e.localUrl,routes:await U$(s,i,r)}},Ku=(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 ${xr.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??ia.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{...vv(e),mode:"cloud",baseUrl:s,routes:[]}};import V$ from"node:fs";import G$ from"node:path";import{stripVTControlCharacters as J$}from"node:util";import{z as I}from"zod";var wv=2e3,kv="--reporter=line,json",bv=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Rv=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Hu=I.object({message:I.string().optional()}),Sv=I.object({type:I.string()}),K$=I.object({status:I.string(),retry:I.number(),error:Hu.optional(),errors:I.array(Hu).optional(),annotations:I.array(Sv).optional(),attachments:I.array(I.object({name:I.string(),path:I.string().optional()})).optional()}),H$=I.object({projectName:I.string(),status:I.string(),expectedStatus:I.string().optional(),annotations:I.array(Sv).optional(),results:I.array(K$)}),q$=I.object({title:I.string(),file:I.string(),line:I.number().optional(),tests:I.array(H$)}),Ev=I.lazy(()=>I.object({title:I.string(),specs:I.array(q$).optional(),suites:I.array(Ev).optional()})),Y$=I.object({config:I.object({rootDir:I.string().optional()}).optional(),suites:I.array(Ev),errors:I.array(Hu).optional(),stats:I.object({expected:I.number(),unexpected:I.number(),flaky:I.number(),skipped:I.number()})}),Pv=e=>{let t=J$(e);return t.length>wv?`${t.slice(0,wv)}\u2026`:t},z$=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Pv(t)},X$=e=>e.status==="unexpected"||e.status==="flaky",Z$=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},Q$=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),eA=(e,t)=>{let r=e.filter(X$),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?z$(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},tA=e=>{let t=Y$.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=>[...Q$(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?G$.resolve(r.rootDir,f.file):f.file,E=[...m,f.title].join(" \u203A ");l(v,f.tests);for(let[k,h]of Z$(f.tests)){let R=eA(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?[]:[Pv(p.message)])}},xv=e=>{try{return tA(JSON.parse(V$.readFileSync(e,"utf8")))}catch{return null}};import rs from"node:fs";import Cv from"node:path";import aa from"node:process";var rA=e=>Cv.join(e,"node_modules",".cache","infra-kit-e2e.lock"),nA=e=>{try{return aa.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Tv=e=>{try{return rs.writeFileSync(e,String(aa.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},qu=e=>{try{let t=Number.parseInt(rs.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},$v=e=>{let t=rA(e);if(rs.mkdirSync(Cv.dirname(t),{recursive:!0}),!Tv(t)){let r=qu(t);if(r!==null&&r!==aa.pid&&nA(r))return{holder:r};if(rs.rmSync(t,{force:!0}),!Tv(t))return{holder:qu(t)??0}}return{release:()=>{qu(t)===aa.pid&&rs.rmSync(t,{force:!0})}}};import{spawn as oA}from"node:child_process";import sA from"node:os";import Yu from"node:process";var Av=(e,t,r)=>new Promise((n,o)=>{let s=oA(e,t,r),i=Yu.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)Yu.off(l,a)};for(let l of i)Yu.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+sA.constants.signals[u]:1))})});var cA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],lA=e=>cA.some(t=>{try{return zu.readFileSync(ns.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),Xu=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,uA=(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}`:"")},Ny=()=>{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
|
+
`)},_y=()=>`${kr}
|
|
367
|
+
${Ny()}
|
|
368
|
+
${qt}`,Pu=()=>["# 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
|
+
`),xu=()=>`${kr}
|
|
370
|
+
${Pu()}
|
|
371
|
+
${qt}`;import XT from"node:fs/promises";var Go=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await XT.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}}},Jo=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import QT from"node:fs";import eC from"node:os";import My from"node:path";import tC from"node:process";import{$ as ZT}from"zx";var Cn=()=>ZT({quiet:!0});var rC=()=>[My.join(eC.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],nC=async e=>{try{return(await Cn()`command -v ${e}`).stdout.trim()||null}catch{return null}},Ko=()=>({runCommand:async e=>{let t=await Cn()`${e}`;return{stdout:`${t.stdout}
|
|
372
|
+
${t.stderr}`}},resolveBinPath:async e=>{let t=await nC(e);return t!==null?t:rC().map(r=>My.join(r,e)).find(r=>QT.existsSync(r))??null},realpath:Ee,platform:tC.platform});var Yt=(...e)=>({steps:e,needsSudo:!1,fetchesNetworkScript:!1}),$n=e=>/\d{1,10}\.\d{1,10}\.\d{1,10}/.exec(e)?.[0]??null,An=["darwin","linux"],oa=e=>t=>wc(t,e)?"homebrew":"unknown",sa=(e,t)=>r=>r===null?null:t(e(r),r),Cu=e=>sa(oa(e.kegName),t=>t==="homebrew"?Yt(["brew","upgrade",e.brewFormula]):null),jy=e=>qs(e,"Homebrew")||qs(e,"homebrew")?"homebrew":"unknown",oC={id:"brew",binName:"brew",probeArgv:["brew","--version"],versionFrom:$n,platforms:An,prerequisites:[],bootstrapInstall:{steps:[["/bin/bash","-c","$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"]],needsSudo:!0,fetchesNetworkScript:!0},identify:jy,updateFor:sa(jy,e=>e==="homebrew"?Yt(["brew","update"]):null)},Tu={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},By="https://awscli.amazonaws.com/v2/install.sh",Uy={steps:[["/bin/bash","-c",`curl -fsSL ${By} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},sC="/usr/local/aws-cli",iC=e=>qn(sC,e,Ee)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${By} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Uy,Fy=e=>wc(e,Tu.kegName)?"homebrew":qs(e,"aws-cli")?"script":"unknown",aC={id:"aws",binName:"aws",...Tu,probeArgv:["aws","--version"],versionFrom:$n,platforms:An,prerequisites:[],bootstrapInstall:Uy,identify:Fy,updateFor:sa(Fy,(e,t)=>e==="homebrew"?Yt(["brew","upgrade",Tu.brewFormula]):e==="script"?iC(t):null)},ta={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},cC={id:"git",binName:"git",...ta,probeArgv:["git","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:Yt(["brew","install",ta.brewInstallSpec]),identify:oa(ta.kegName),updateFor:Cu(ta)},ra={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},lC={id:"gh",binName:"gh",...ra,probeArgv:["gh","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:Yt(["brew","install",ra.brewInstallSpec]),identify:oa(ra.kegName),updateFor:Cu(ra)},na={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},uC={id:"doppler",binName:"doppler",...na,probeArgv:["doppler","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:Yt(["brew","install","gnupg"],["brew","install",na.brewInstallSpec]),identify:oa(na.kegName),updateFor:Cu(na)},Ho="portless",Ly=e=>Tm(e,Ho)===null?"unknown":"npm",dC={id:"portless",binName:Ho,npmPackage:Ho,probeArgv:["portless","--version"],versionFrom:$n,platforms:[...An,"win32"],prerequisites:[],bootstrapInstall:Yt(["npm","install","-g",Ho]),identify:Ly,updateFor:sa(Ly,e=>e==="npm"?Yt(["npm","install","-g",`${Ho}@latest`]):null)},$u={brew:oC,git:cC,aws:aC,gh:lC,doppler:uC,portless:dC},br=Object.keys($u),Ke=e=>$u[e],Au=(e,t)=>e.platforms.includes(t),Ou=e=>{let t=[],r=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!r.has(o)){r.add(o);for(let i of Ke(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Wy=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),Vy=async(e,t)=>{try{return await e(t)}catch{return null}},pC=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Gy=async(e,t)=>{if(!Au(e,t.platform))return Wy(e.id);let r=await Vy(t.runCommand,e.probeArgv),n=await pC(t,e.binName);if(r==null&&n==null)return Wy(e.id);let o=r??(n==null?null:await Vy(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)}},qo=async(e,t)=>Promise.all(e.map(r=>Gy(Ke(r),t)));import{$ as vC}from"zx";import{z as Jy}from"zod";var Ky=/^\d{4}-\d{2}-\d{2}$/,Yo=e=>{if(!Ky.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},Hy=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,On=class extends Error{constructor(t){super(Hy(t)),this.name="InvalidReleaseDateError"}},Rr=e=>{let t=e.trim();if(!Yo(t))throw new On(t);return t},zo=e=>{let t=e.trim();return t===""||Yo(t)?!0:Hy(t)},Du=Jy.string().refine(Yo,{message:"Expected a calendar date in yyyy-mm-dd form."}),Iu=Jy.string().refine(e=>e===""||Yo(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var zt=e=>e.slice(1).split(".").map(Number),Dn=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 Yy="next",mC=/^v?(\d+)\.(\d+)\.(\d+)$/,fC=e=>e.replace(/^.*release\//,""),Nu=e=>{let t=fC(e.trim()),r=mC.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},qy=e=>`${e[0]}.${e[1]}.${e[2]}`,_u=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=Nu(o);if(!s)continue;let i=qy(s);n.has(i)||(n.add(i),r.push(s))}return Dn(r.map(o=>qy(o))).map(o=>zt(`v${o}`))},Sr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Mu=(e,t)=>{if(e.length===0)throw new Sr;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`},In=(e,t)=>{try{return Mu(e,t)}catch(r){if(r instanceof Sr)return null;throw r}},ju=e=>e.trim().toLowerCase()===Yy,aa=e=>ju(e)||Nu(e)!==null?{version:e}:{name:e},gC=e=>e==="regular"||e==="hotfix",zy=e=>"name"in e,hC=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:Rr(n)}},Fu=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=hC(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(!gC(u))throw new Error(`Invalid release type "${l}". Expected "regular" or "hotfix".`);s=u}return ia({...aa(n),type:s},{description:i,releaseDate:o})},Lu=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},ia=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},yC=e=>{let t=e.name.trim();return Qs(t),ia({id:{kind:"name",name:t,raw:t},type:e.type},e)},Bu=(e,t)=>{let r=[...t];return e.map(n=>{if(zy(n))return yC(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(ju(o)){let a=Mu(r,n.type);return r.push(zt(`v${a}`)),ia({id:ve(a),type:n.type},n)}let s=Nu(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),ia({id:ve(i),type:n.type},n)})},Uu=e=>e.some(t=>!zy(t)&&ju(t.version));var wC=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),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
|
+
`)},kA=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 ht("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(", ")}`})},bA=async(e,t)=>{if(e.env===null||!Wf(e.env))return;let r=await(t.protectedEnvAccess??st)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?ht("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`}):ht("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`})},RA=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw ht("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"}"`})},SA=async(e,t)=>{if(e.served){RA(e);let p=await Hu(e,t);return kA(p),p}if(!vA(e.testsDir))throw ht("no_dev_server",{devCommand:Qu(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${Qu(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:[]}},EA=(e,t,r)=>Dv("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...da.env,...r,[gA]:e.mode},stdio:["inherit",ar.enabled||Z()?2:"inherit","inherit"]}),PA=(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:ns.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=ns.join(e.testsDir,"test-results",`ik-e2e-${n}-${da.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},xA=e=>{if(e.mode==="cloud")return()=>{};let t=Ov(e.testsDir);if("holder"in t)throw ht("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},pa=async(e,t={})=>{let r=await Ku(e.app,t),n=e.cloud?qu(r,t):await SA(r,t);d.info(wA(n,r.served)),n.mode==="cloud"&&await bA(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?Qu(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return td({...o,ran:!1,exitCode:null,...ed});n.mode==="cloud"&&await G(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=xA(n);try{return await TA(o,t.runPlaywright??EA)}finally{s()}},TA=async(e,t)=>{if(!Z()||Ev(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(da.exitCode=i),td({...e,ran:!0,exitCode:i,...ed,report:Z()?"caller-reporter":"off"})}let{args:r,outputDir:n}=PA(e,e.playwrightArgs),o=Zu.mkdtempSync(ns.join(hA.tmpdir(),"ik-e2e-report-")),s=ns.join(o,"report.json");try{let i=await t(e,[Rv,...r],Sv(s));i!==0&&(da.exitCode=i);let a=Cv(s);return td({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...ed,report:"unavailable"},outputDir:n})}finally{Zu.rmSync(o,{recursive:!0,force:!0})}},ed={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},td=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),CA={app:x.string(),testsDir:x.string(),target:x.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:x.string(),mode:x.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:x.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:x.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:x.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:x.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:x.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:x.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:x.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:x.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:x.array(x.object({path:x.string(),packageName:x.string(),source:x.enum(["local","cloud"]),target:x.string().nullable(),live:x.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:x.array(x.string()),ran:x.boolean().describe("False for --dry-run."),exitCode:x.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:x.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:x.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:x.object({expected:x.number(),unexpected:x.number(),flaky:x.number(),skipped:x.number(),repeatFlaky:x.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:x.array(x.object({title:x.string().describe("Describe path and test title, joined with \u203A."),file:x.string(),line:x.number().nullable(),project:x.string(),status:x.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:x.number().describe("The retry index of the failed attempt reported here."),runs:x.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:x.number().describe("How many of those runs failed."),error:x.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:x.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:x.array(x.object({file:x.string(),fail:x.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:x.number().describe("test.fixme \u2014 skipped as unfinished."),skip:x.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:x.array(x.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.")},rd=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:x.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:x.boolean().optional(),yes:x.boolean().optional(),cloud:x.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:x.array(x.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:CA,handler:e=>pa(e)});import ma from"node:fs";import nd from"node:path";import{z as os}from"zod";var $A=e=>[...e.map(t=>`unset ${t}`),`unset ${jr}`,`unset ${Gs}`,`unset ${Js}`,`unset ${Sm}`,`unset ${Ks}`],fa=async()=>{let e=Fr(),t=nd.join(e,Mr);if(!ma.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Hs(t),n=$A(r),o=nd.resolve(e,Ws);ma.mkdirSync(e,{recursive:!0,mode:448}),Nt(o,`${n.join(`
|
|
375
375
|
`)}
|
|
376
|
-
`,384),
|
|
376
|
+
`,384),ma.rmSync(t,{force:!0}),ma.rmSync(nd.join(e,Vs),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}},od=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:os.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:os.string().describe("Path to the file that must be sourced to apply"),variableCount:os.number().describe("Number of variables cleared"),unsetStatements:os.array(os.string()).describe("Unset statements generated")},handler:()=>fa()});import AA from"node:path";import ss from"node:process";import{z as Nn}from"zod";var ga=async()=>{d.info("Environment session status:");let e=Fr(),t=ss.env[Hn],r=AA.join(e,Mr),n=0,o=0,s=ss.env[Gs]??null,i=ss.env[Js]??null,a=ss.env[Ks]??null;if(s){let l=Hs(r);l.length>0&&(o=l.length,n=l.filter(p=>p in ss.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 v=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}},sd=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:Nn.string().describe("Current terminal session ID"),sessionLoadedCount:Nn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Nn.number().describe("Total number of cached var names"),sessionConfig:Nn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Nn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Nn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:ga});import OA from"node:process";import{z as Zt}from"zod";var Iv="****",Te=e=>typeof e!="string"||e.length<8?Iv:`${Iv}${e.slice(-4)}`;var Nv=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${ur}`:"store",redactedToken:Te(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),DA=["ENV","SOURCE","TOKEN","PRESENT"],_v=(e,t)=>{let r=[...DA,...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())},ha=async({check:e}={})=>{let t=await li(),r=await Ze(),n=OA.env[ur],o=Nv(t,r?.envs??{},n);if(e){let a=await lr();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await Of({childEnv:no(l),project:a,config:c.env});c.status=u.outcome}}for(let a of _v(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}},id=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:Zt.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:Zt.array(Zt.object({env:Zt.string().describe("Environment / Doppler config name"),source:Zt.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:Zt.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:Zt.boolean().describe("Whether a token is configured for this environment"),status:Zt.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ha});import{z as T}from"zod";import{$ as IA}from"zx";var NA=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),_A=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,MA=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(", ")},cd=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),ad=new Set(["up-to-date","fast-forward","merged"]),jA=(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=Pe(ve(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))},FA={"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"},jv=e=>{let t=FA[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},LA=(e,t)=>{d.info(`
|
|
380
|
+
\u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${jv(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},BA=(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`},UA=async e=>{let{entries:t,toPlan:r,all:n,explicit:o}=e;if(o||n)return r;y.setInteractive();let s=new Map(t.flatMap(i=>{let a=Q(i.branch);return a?[[ce(a),jv(i)]]:[]}));return Ht(me({branches:r,descriptions:s}),{required:!0})},WA=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s}=e,i=n.filter(v=>o.includes(v.branch)),a=v=>{for(let E of v)d.info(`\u2139\uFE0F ${E} was merged by someone else while we planned \u2014 dropping it from the push`)},c=await Mo(t,Ch(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 v=await Ah({worktreePath:r,refs:l,command:s});u=v.failed;for(let[k,h]of v.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${h.split(`
|
|
382
382
|
`)[0]??""}`);let E=await Mo(t,v.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(v=>v.branch).join(", ")}`);let p=await
|
|
384
|
-
`)[0],observedLanded:f.map(v=>v.branch)}},
|
|
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 G(p,`Are you sure you want to merge dev into these branches: ${E.join(", ")}?`,{throwOnDecline:!0,plan:
|
|
383
|
+
\u2B06\uFE0F Pushing atomically: ${l.map(v=>v.branch).join(", ")}`);let p=await ri(t,l);if(p.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:u};let f=(await Promise.all(l.map(async v=>({branch:v.branch,landed:await Wr(t,v.branch)===v.sha})))).filter(v=>v.landed);return f.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${f.map(v=>v.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:u,abortedBy:p.stderr?.split(`
|
|
384
|
+
`)[0],observedLanded:f.map(v=>v.branch)}},VA=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"})},Mv=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=>!ad.has(i.status));return cd({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},GA=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await $e();if(e.abort)return Mv(await ry({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return Mv(await ey({cwd:s,versions:r,all:t,verify:i,trees:ty(e.tree),confirmedCommand:o}))},ya=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;VA(e);let a=o===!0?$h:o||void 0;if(await Kl({operation:"merge dev into release branches"}),e.continue||e.abort)return GA(e);let c=[],l=[];for(let $ of await V()){let J=_A($);J?l.push({branch:$.branch,reason:J}):c.push($.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 (${MA(l)})`),y.print(),cd(NA(n,l));let u=await $e();try{await IA({cwd:u,quiet:!0})`git fetch origin --prune`}catch($){throw new g($,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:jA(r,c,l),m=await cf({cwd:u},async $=>{let J=Vi($.remove);try{return await JA({cwd:u,worktree:$,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i})}finally{J()}}),{entries:f,selected:v,pushed:E,pushAborted:k,abortedBy:h,declined:R,verifyFailed:S,handOffs:P}=m,M=await ot(u).catch(()=>[]);return YA({entries:f,selected:v,pushed:E,pushAborted:k,abortedBy:h,declined:R,verifyFailed:S,handOffs:P,dryRun:n,worktrees:M,skipped:l})},JA=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 xe(t,"origin/dev"):null,f=await Th({cwd:t,worktreePath:r.path,branches:n}),v={entries:f,pushed:!1,pushAborted:!1,declined:!1};if(LA(f,s),c)return{...v,selected:n};let E=await UA({entries:f,toPlan:n,all:i,explicit:a!==void 0});E.length===o.length?y.addOption("--all",!0):y.addOption("--versions",E);let k=f.filter($=>E.includes($.branch)&&$.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 G(p,`Are you sure you want to merge dev into these branches: ${E.join(", ")}?`,{throwOnDecline:!0,plan:KA(f,E,s)})}catch($){if(!bt($))throw $;return{...v,selected:E,declined:!0}}p||y.addOption("--yes",!0);let h=await WA({cwd:t,worktreePath:r.path,entries:f,selected:E,verify:l}),R=$=>f.filter(J=>E.includes(J.branch)&&$(J)).map(J=>J.branch),S=R($=>$.status==="conflict"),P=R($=>$.status==="merged"&&(h.verifyFailed?.has($.branch)??!1)),M=u&&m&&S.length+P.length>0?await Xh({cwd:t,conflicted:S,verifyFailed:P,devSha:m,verify:l}):void 0;return{entries:f,selected:E,declined:!1,...h,handOffs:M}},KA=(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:cu(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),HA=(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
|
+
${BA(e.branch,t)}
|
|
389
|
+
`,qA=(e,t)=>e!==void 0&&t?`${e}
|
|
390
|
+
hand-off: ${t}`:e??t,YA=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 h=!!k.mergeSha,R=l?.has(k.branch)??!1,S=l?.get(k.branch),P=o&&h?"push-aborted":k.status,M=R?"verify-failed":P,$=u?.get(k.branch);return{branch:k.branch,status:M,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:m.has(k.branch),reason:qA(S,$?.reason)??k.reason,...$?.resolution?{resolution:$.resolution}:{}}}),v=f.filter(k=>!ad.has(k.status));for(let k of f){let h=t.find(R=>R.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:h?.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
394
|
`);else if(v.length>0){d.info(`
|
|
395
395
|
\u26A0\uFE0F ${v.length} branch(es) did not merge.
|
|
396
|
-
`);for(let k of v)d.info(
|
|
397
|
-
`);y.print();let E=a||i;return
|
|
398
|
-
`).filter(r=>r.trim().length>0)}catch{return[]}},
|
|
399
|
-
`);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},
|
|
400
|
-
${
|
|
396
|
+
`);for(let k of v)d.info(HA(k,c))}else d.info(`\u2705 All merges completed successfully!
|
|
397
|
+
`);y.print();let E=a||i;return cd({successfulMerges:E?0:f.filter(k=>ad.has(k.status)).length,failedMerges:E?0:v.length,failedBranches:E?[]:v.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})},ld=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:T.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:T.union([T.string(),T.array(T.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:T.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:T.union([T.boolean(),T.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:T.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:T.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:T.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:T.union([T.string(),T.array(T.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:T.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:T.number().describe("Number of branches that reached their desired state"),failedMerges:T.number().describe("Number of branches that did not"),failedBranches:T.array(T.string()).describe("List of branches that did not merge"),totalBranches:T.number().describe("Total number of branches processed"),dryRun:T.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:T.object({attempted:T.boolean(),aborted:T.boolean(),abortedBy:T.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:T.array(T.object({branch:T.string(),status:T.string(),mergeSha:T.string().optional(),conflictPaths:T.array(T.string()).optional(),pushed:T.boolean(),reason:T.string().optional(),resolution:T.object({worktreePath:T.string(),baseSha:T.string(),devSha:T.string(),conflictPaths:T.array(T.string()),editablePaths:T.array(T.string()).optional(),lockfileOnly:T.boolean(),rererePreResolved:T.array(T.string()),state:T.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:T.object({code:T.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:T.array(T.string()).optional(),detail:T.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:T.array(T.object({branch:T.string(),reason:T.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:ya});import{z as ps}from"zod";import{$ as He}from"zx";var Fv=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Cr=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=Fv(t.stderr,500);o&&(r.stderr=o);let s=Fv(t.stdout,200);return s&&(r.stdout=s),r};var is=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 as=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 ge()?new O({status:"partial_failure",...n},1,s):new g(void 0,s)};import va from"node:fs/promises";import{$ as dd}from"zx";var zA=new Set([".omc",".DS_Store"]),XA=new Set(["state","sessions"]),ZA=2e3,Wv="check 'git worktree list' for the path; uncommitted changes block removal",QA=e=>new Promise(t=>{setTimeout(t,e)}),ud=e=>typeof e=="object"&&e!==null?e.code:void 0,Lv=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Bv=async e=>{try{return Lv(await va.realpath(e))}catch{return Lv(e)}},eO=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await ot(t),o=await Bv(r);for(let s of n)if(await Bv(s.path)===o)return!0;return!1}catch{return!0}},tO=async e=>{let t;try{t=await va.readdir(e)}catch(n){return{kind:ud(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>zA.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await va.readdir(`${e}/.omc`)).every(s=>XA.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:ud(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},Uv=async e=>{try{return await va.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return ud(t)==="ENOTEMPTY"?"busy":"failed"}},rO=async e=>{let{worktreePath:t,sleep:r}=e,n=await Uv(t);return n!=="busy"?n==="removed":(await r(ZA),await Uv(t)==="removed")},cs=(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}},nO=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await eO({projectRoot:n,worktreePath:r}))return cs(t,o,Wv);let i=await tO(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 rO({worktreePath:r,sleep:s})?cs(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"})},oO=async e=>{try{return(await dd`git -C ${e} status --porcelain`).stdout.split(`
|
|
398
|
+
`).filter(r=>r.trim().length>0)}catch{return[]}},sO=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await oO(i);if(a.length>0)return cs(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),Wv);let c=await _f(i,o);if(!c.closed&&"error"in c)return cs(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await dd`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return nO({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},$r=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=QA}=e,i=t.length>0?await Bt():"unreachable",a=await Promise.all(t.map(l=>sO({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 dd`git worktree prune`,c};var ls=async(e,t)=>{if(!(await we("release")).includes(e))return[];let n=await A(),o=`${n}${fe}`,{removed:s,failed:i}=await $r({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 pd}from"zx";var us=async(e,t)=>{let r=await pd({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))]:[]}},Vv=async(e,t)=>(await pd({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),ds=(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`})},Gv=async e=>{let{releaseBranch:t,releaseType:r,releaseMerged:n,rcMerged:o}=e,s=`origin/${t}`;if(await pd({quiet:!0})`git fetch origin main dev ${n?[]:[t]}`,r==="hotfix"){let a="origin/main";if(!n){let c=await us("origin/main",s);ds(`merging ${t} into main`,c),a=await Vv(c.tree,"origin/main")}ds("syncing main back into dev",await us("origin/dev",a));return}let i="origin/dev";if(!n){let a=await us("origin/dev",s);ds(`merging ${t} into dev`,a),i=await Vv(a.tree,"origin/dev")}o?ds("syncing main back into dev",await us(i,"origin/main")):ds("merging dev into main (RC PR)",await us("origin/main",i))};var _n=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:Cr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},Kv=async e=>{let t=Rc(e),r=await He`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},Jv=async()=>{let e=await He`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},iO=async e=>{let t=Ct(e),r=await Yl(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 an(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=Ao(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}},aO=async()=>{let e=await V(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));y.setInteractive();let n=await pe(),o=await Kt(me({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}},cO=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n}=e,o=pt(r),s=await Fi(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 _n(`merge release PR #${n} ${t} into ${o}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await He`gh pr merge ${n} --squash --admin --delete-branch`})},lO=async e=>{let t=re(e),r=Rc(e),n=await Jv();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 _n(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await He`gh pr edit ${s} --title ${r}`})),s}await _n(`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 He`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Jv();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},uO=async e=>{let t=re(e);if(await Kv(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await lO(e);await _n(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await He`gh pr merge ${n} --squash --admin`})},dO=async()=>{He.quiet=!1,await _n("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await He`gh workflow run deploy-all.yml --ref main -f environment=prod`}),He.quiet=!0},pO=async()=>{await _n("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 He`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},mO=async e=>{try{await ei(e)}catch(t){d.warn({err:Cr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await ti(e)}catch(t){d.warn({err:Cr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},fO=async e=>{let t=await Tt();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=ce(e);await Xl({versionName:r},t)}catch(r){let n=Do(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:Cr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},wa=async e=>{let{version:t,confirmedCommand:r}=e;await Ne({operation:"deliver release"});let{selectedReleaseBranch:n,releaseType:o,prNumber:s}=t?await iO(t):await aO(),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=re(i);if(y.addOption("--version",a),d.info(`Delivering ${i.kind==="name"?"named release":"version"} ${n}`),ge())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 Gv({releaseBranch:n,releaseType:o,releaseMerged:(await Fi(s)).state==="MERGED",rcMerged:o!=="hotfix"&&await Kv(i)!==null}),await G(r,`Are you sure you want to deliver version ${n} to production?`),y.addOption("--yes",!0),He.quiet=!0;let l=`${await A()}${fe}`;await ls(n,{operation:`remove worktree for ${n} before merge`,remediation:`run manually: git worktree remove ${l}/${n} (use --force if uncommitted changes)`}),await cO({selectedReleaseBranch:n,releaseType:o,prNumber:s}),o!=="hotfix"&&await uO(i),await dO(),await pO(),await mO(n),He.quiet=!1,await fO(i),d.info(`Successfully delivered ${n} to production!`),y.print();let u={releaseBranch:n,version:a,type:o,success:!0};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}},md=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:ps.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:ps.string().describe("The release branch that was delivered"),version:ps.string().describe("The version that was delivered"),type:ps.enum(["regular","hotfix"]).describe("Release type"),success:ps.boolean().describe("Whether the delivery was successful")},handler:wa});import{z as Dt}from"zod";import{$ as Cd}from"zx";import{z as ys}from"zod";import nw from"node:fs/promises";import kd from"node:path";import{DEPLOY_CONFIG_FILE as ka,deployConfigSchema as gO}from"@slip-stream-kit/config/internal";import hO from"node:fs/promises";import yO from"node:path";import{pathToFileURL as vO}from"node:url";import{z as wO}from"zod";var Ot=async e=>{let t=yO.join(e,ka);try{await hO.access(t)}catch{return}let r=await import(vO(t).href);if(r.default===void 0)throw new Error(`${ka} at ${t} has no default export`);let n=gO.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${ka} at ${t}:
|
|
400
|
+
${wO.prettifyError(n.error)}`);let o=[...bO(n.data),...kO(n.data)];if(o.length>0)throw new Error(`Invalid ${ka} at ${t}:
|
|
401
401
|
${o.join(`
|
|
402
|
-
`)}`);return n.data},
|
|
402
|
+
`)}`);return n.data},kO=e=>e.replaceV1!==!0?[]:Nc.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),bO=e=>{let t=new Set([...e.environments,...Nc]);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 ms=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",Xv=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${zv}`,RO=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${zv}`,Ra="install-deps",Hv=25,Mn="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",Sa="skip_terraform_deploy",Zv={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"}}},Qv=(e,t)=>Zv[e.replaceV1===!0?"v1":"pilot"][t],ew=e=>Object.values(Zv[e]).map(({file:t})=>`.github/workflows/${t}`),gd=ew("pilot"),hd=ew("v1"),ba=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),SO=(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}]}),z=e=>`\${{ ${e} }}`,fd=e=>z(`secrets[format('{0}_${e}', inputs.environment)]`),EO=e=>[Ra,...e.terraform,...e.preDeploy],tw=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),PO=e=>[`needs.${Ra}.result == 'success'`,...tw(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],xO=(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()",...PO(r)),z(n.join(" && "))},yd=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],rw=e=>e===void 0?[]:[` if: ${e}`],vd=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${z("github.ref")}`,` environment: ${z("inputs.environment")}`," secrets: inherit"],TO=(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=z(`secrets.${i}`);return` ${i}=${a}`})];return[` uses: ${Xv}`," with:",` environment: ${z("inputs.environment")}`,` ref: ${z("github.ref")}`,` sha: ${z("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${L.version}`,...n,...o," secrets:",` aws-access-key-id: ${fd("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${fd("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${fd("AWS_REGION")}`,` serverless-access-key: ${z("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${z("secrets.SLACK_TOKEN")}`,` slack-channel: ${z("secrets.SLACK_CHANNEL")}`,...s]},CO=(e,t,r,n)=>{let o=e.service.workflow===void 0?TO(e,n):vd(e.service.workflow);return["",` deploy-${e.name}:`,...yd(EO(r)),...rw(xO(e,t,r)),...o]},qv=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],$O=(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?qv(Sa,"Skip terraform deployment"):[],s=t==="all"?[]:r.flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return qv(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},AO=e=>e.map(t=>z(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),OO=(e,t,r)=>{let{title:n,concurrency:o}=Qv(e,t),s=(e.terraform??[]).length>0?z(`inputs.${Sa} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${AO(r)}`:"";return[`${Mn}: edit that file and re-run the command,`,"# a hand edit here is overwritten.",`name: '${n}'`,`run-name: '${n} [${z("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}-${z("inputs.environment")}`," # false: a cancelled run would also kill an in-flight terraform apply."," cancel-in-progress: false",""]},DO=e=>{let t=z(`!inputs.${Sa}`);return["",` ${ba(e)}:`,` if: ${t}`,...vd(e)]},IO=(e,t)=>{let r=t.length===0?void 0:z(["!cancelled()",...tw(t)].join(" && "));return["",` ${ba(e)}:`,...yd(t),...rw(r),...vd(e)]},NO=()=>["",` ${Ra}:`,` uses: ${RO}`," with:",` ref: ${z("github.ref")}`,` sha: ${z("github.sha")}`," secrets:",` slack-token: ${z("secrets.SLACK_TOKEN")}`,` slack-channel: ${z("secrets.SLACK_CHANNEL")}`],_O=(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)}},MO=(e,t)=>[""," notify-success:",...yd(t),` if: ${z("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],Yv=(e,t)=>{let r=SO(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(ba),preDeploy:o.map(ba)},{file:i}=Qv(e,t),a=1+(n.length>0?1:0)+(t==="selected"?r.length:0);if(a>Hv){let p=n.length>0?`environment, ${Sa}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${p} and one checkbox per service); GitHub allows ${Hv}. Fold services that always deploy together into one deploy script.`)}let c=r.map(p=>`deploy-${p.name}`);_O([Ra,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let u=`${[...OO(e,t,r),...$O(e,t,r),"","permissions:"," contents: read","","jobs:",...NO(),...n.flatMap(DO),...o.flatMap(p=>IO(p,s.terraform)),...r.flatMap(p=>CO(p,t,s,e)),...e.notifySuccess===void 0?[]:MO(e.notifySuccess,c)].join(`
|
|
403
403
|
`).replace(`jobs:
|
|
404
404
|
|
|
405
405
|
`,`jobs:
|
|
406
406
|
`)}
|
|
407
|
-
`;return{path:`.github/workflows/${i}`,content:u}},vd=e=>[Hv(e,"all"),Hv(e,"selected")];var rw=".github/workflows",CO=/script_name:\s*(?<service>[a-z0-9-]+)/,$O=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,AO=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,kd=async e=>{let t=wd.resolve(e,rw),r;try{r=await tw.readdir(t)}catch{return new Map}return nw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},ms=async(e,t)=>nw(e,[t]),nw=async(e,t)=>{let r=wd.resolve(e,rw),n=new Map,o=!1;for(let s of t){let i;try{i=await tw.readFile(wd.resolve(r,s),"utf-8")}catch{continue}i.startsWith(Mn)?o=!0:DO(i,n)}return o&&ow(n,await OO(e)),n},OO=async e=>{try{let t=await $r(e);return t?.replaceV1===!0?pd(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},ow=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},DO=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=CO.exec(r)?.groups?.service??$O.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(AO)].map(s=>s.groups?.env??"");o.length!==0&&ow(t,new Map([[n,o]]))}},bd=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import IO from"node:fs/promises";import NO from"node:path";import _O from"yaml";var MO=".github/workflows",jO="skip_terraform_deploy",fs=async(e,t)=>{let r=NO.resolve(e,MO,t),n;try{n=_O.parse(await IO.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!==jO).map(([i])=>i)};var sw="dev",Rd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iw=(e,t)=>e[t]===void 0,aw=(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[]}},FO=async()=>{let e=await V();return $t(e.map(t=>t.branch))},LO=(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(FO());if(l.length===0)return null;let u=aw(c,"version");return gs.enum([...new Set([...l,sw])]).optional().describe(`Which release to deploy from. "${sw}" 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=Bt(await Sd(Ut(t)),await st());if(l.length===0)return null;let u=l.filter(ro),p=l.filter(f=>!ro(f)),m=aw(c,"env");return gs.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(fs(c,t));if(l.length===0)return null;let u=await ms(c,t);return gs.array(gs.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${LO(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=>iw(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")&&iw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):gs.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 BO 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=>BO({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import UO from"@inquirer/confirm";var hs=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;Z()&&ni(o,{branch:r,env:n}),y.setInteractive();let s=await _(i=>UO({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import WO from"@inquirer/select";import VO from"node:process";var Ed=()=>!Z()&&VO.stdin.isTTY===!0,GO={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Pd=async()=>_(e=>WO({message:"\u{1F680} Where should this deploy run?",choices:Zt.filter(t=>t!=="local").map(t=>({name:t,value:t,description:GO[t]}))},e),{whenHeadless:"refuse"});var Zt=["ci","local"],JO={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},cw=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${Zt.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=Zt.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${Zt.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},xd=(e,t)=>{let n=JO[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()?cw(e):Pd();var ys=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 Jt([{value:"dev",label:"dev"},...me({branches:r,descriptions:o,types:n})])};var lw="deploy-all.yml",uw=Ar({workflowFile:lw,fields:["version","env"],toolName:"gh-release-deploy-all"}),ba=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await it({provider:uw,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await ys(t),i=_o(s);y.addOption("--version",i);let a=await st(),c=Bt(await Ut(lw),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),si({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await hs({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:uw,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:Ot.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:Ot.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:Ot.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Ot.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Ot.string().describe("The release branch that was deployed"),version:Ot.string().describe("The version that was deployed"),environment:Ot.string().describe("The environment deployed to"),skipTerraformDeploy:Ot.boolean().describe("Whether terraform deployment was skipped"),success:Ot.boolean().describe("Whether the deployment was successful")},handler:ba});import KO from"@inquirer/checkbox";import{z as Me}from"zod";import{$ as Ad}from"zx";var Or="deploy-selected-services.yml",dw=Ar({workflowFile:Or,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Ra=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await it({provider:dw,params:e,operation:"launch deploy-selected workflow",argument:S=>S[0]??"version"});let i=await ys(t),a=_o(i);y.addOption("--version",a);let c=await st(),l=Bt(await Ut(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),si({env:u,branch:i});let p=await A(),m=await fs(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=>KO({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 ms(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 hs({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:dw,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:Ra});import{z as Qt}from"zod";var Sa=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 ji(),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}},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:
|
|
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}},Dd=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:
|
|
412
|
-
`)};import
|
|
413
|
-
`).map((
|
|
414
|
-
${
|
|
415
|
-
`)),
|
|
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}},Dd=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:er.array(er.object({version:er.string().describe("Release version"),type:er.enum(["regular","hotfix"]).describe("Release type"),description:er.string().nullable().describe("Jira version description"),releaseDate:er.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:er.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:er.number().describe("Number of release branches")},handler:xa});import rD from"node:process";var ks="local-deploy";var Id=e=>({...e}),Nd=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=rD.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:ks},contract:i,stripped:c}},Ta=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 yD from"@inquirer/checkbox";import vD from"@inquirer/confirm";import wD from"@inquirer/select";import{spawn as kD}from"node:child_process";import Bd from"node:process";import{z as te}from"zod";import{$ as Ss}from"zx";import{$ as bs}from"zx";var nD=async e=>{let t=bs.quiet;bs.quiet=!0;try{let r=`/${e}/environment`,n=await bs`aws sts get-caller-identity --query Account --output text`,o=await bs`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{bs.quiet=t}},fw=(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`})},gw=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"})},hw=(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`})},_d=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Gr(t,`deploy to "${t}"`,i),hw(t,s),gw({env:t,isShared:n,isClean:o});let a=await nD(r);return fw(t,a),{identity:a}};import Md from"node:fs/promises";import Rs from"node:path";var ww="devops/scripts",oD=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,sD=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,iD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,aD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,cD=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,lD=/`[^`]*\$\{[^`]*\/environment[^`]*`/,yw={commentPrefixes:["#"],literalPrefix:e=>aD.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=iD.exec(e)?.groups?.arg;return t!==void 0&&fD(t)}},vw={commentPrefixes:["//","/*","*"],literalPrefix:e=>cD.exec(e)?.groups?.prefix,isUnparseable:e=>lD.test(e)},jd=async e=>{let t=await Ot(e),r=await bd(e);return(t===void 0?await uD(e,r):await dD(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},uD=async(e,t)=>{let r=Rs.resolve(e,ww),n;try{n=await Md.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=oD.exec(o)?.groups?.service;return s===void 0?[]:[kw(s,Rs.resolve(r,o),t)]}))},kw=async(e,t,r)=>{let n=Rw(await bw(t),yw);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:gs(mD(n),r.get(e)),ssmPrefix:Sw(n,yw)}},dD=async(e,t,r)=>{let n=ms(t);return(await Promise.all(Object.entries(t.services).map(async([s,i])=>{if(i.deploy===void 0){let l=Rs.resolve(e,ww,`deploy-${s}.sh`);if(!await pD(l))return null;let u=await kw(s,l,r);return{...u,allowedEnvs:gs(u.allowedEnvs,n.get(s))}}let a=Rs.resolve(e,i.deploy),c=Rw(await bw(a),vw);return{name:s,scriptPath:a,runner:"deploy-run",allowedEnvs:gs(n.get(s)??null,r.get(s)),ssmPrefix:Sw(c,vw)}}))).filter(s=>s!==null)},pD=async e=>{try{return await Md.access(e),!0}catch{return!1}},bw=async e=>{try{return await Md.readFile(e,"utf-8")}catch{return""}},Rw=(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))}),mD=e=>{let t=e.reduce((n,{text:o})=>n??sD.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},fD=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Sw=(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},Ew=e=>{let t=Rs.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},gD=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],Ew(r)]);return t},hD=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${Ew(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("; ")})},Pw=e=>{hD(e);let t=gD(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},Ca=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Fd=(e,t)=>e.filter(r=>Ca(r,t));var Ud="deploy-all.yml",bD="/bin/sh",RD=async()=>{let e=Ss.quiet;Ss.quiet=!0;try{let t=await Ss`gh run list --workflow=${Ud} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Ss.quiet=e}},SD=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await _(o=>yD({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},ED=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 Z()&&ii(i,{env:t,services:n,accountId:o,shared:r}),r?_(a=>wD({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):_(a=>vD({message:i,default:!1},a),{whenHeadless:"refuse"})},Tw=e=>e.runner==="sh"?[bD,[e.scriptPath]]:[Bd.execPath,[Bd.argv[1]??"","deploy-run",e.name]],PD=(e,t,r)=>new Promise((n,o)=>{let[s,i]=Tw(e),a=kD(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),xD=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 PD(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}},TD=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&&!Ca(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))},Ld=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:Id(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},CD=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:(y.setInteractive(),SD(r,o))},Cw=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await A(),c=await jd(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=Pw(c);await it({provider:Wd[t],params:e,operation:"deploy locally",argument:"env"});let u=await st(),p=Ut(await Wt(Ud),u),m=r??"";m||(y.setInteractive(),m=await jn(p,"deploy locally")),y.addOption("--env",m);let f=Fd(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 v=await CD({selection:t,eligible:f,service:n,env:m}),E=TD({names:v,services:c,env:m});if(t==="selected")for(let Ce of v)y.addOption("--service",Ce);let k=ro(m),h=await Ur(),R=(await Ss`git rev-parse HEAD`.quiet()).stdout.trim(),S=await tf(),P=Nd({env:m,branch:h,sha:R,isClean:S});i&&d.info(`Deploy contract for ${m}:
|
|
414
|
+
${Ta(P)}`);let $=(await _d({env:m,project:l,isShared:k,isClean:S,runningEnvs:await RD(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${$}) from this machine`,`Preflight parameter: /${l}/environment`,Ta(P),"Commands:",...E.map(Ce=>` ${Tw(Ce).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
|
|
415
|
+
`)),Ld({env:m,accountId:$,names:v,built:P,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await ED({env:m,isShared:k,names:v,accountId:$}))return d.info("Deployment cancelled"),Ld({env:m,accountId:$,names:v,built:P,deployed:[],failed:[],dryRun:!1,success:!1});P.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${P.stripped.join(", ")}`);let{deployed:J,failed:K}=await xD({chosen:E,childEnv:P.childEnv,cwd:a,env:m});return K.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${J.join(", ")||"none"}], failed [${K.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Bd.exitCode=1),y.print(),Ld({env:m,accountId:$,names:v,built:P,deployed:J,failed:K,dryRun:!1,success:K.length===0})},$w=async e=>Cw(e,"all"),Aw=async e=>Cw(e,"selected"),Ow='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.',Dw={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.")},Iw={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")},xw=e=>Ar({workflowFile:Ud,fields:["env"],toolName:e}),Wd={all:xw("local-deploy-all"),selected:xw("local-deploy-selected")},Vd=C({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${Ow}`,requiresHumanConfirm:!0,formProvider:Wd.all,inputSchema:Dw,outputSchema:Iw,handler:$w}),Gd=C({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${Ow}`,requiresHumanConfirm:!0,formProvider:Wd.selected,inputSchema:{...Dw,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:Iw,handler:Aw});import OD from"@inquirer/confirm";import $a from"@inquirer/input";import jw from"@inquirer/select";import Kd from"node:process";import{z as q}from"zod";import{z as Es}from"zod";var Fn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Mw=2500,Nw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),_w=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,$D=async()=>{let e=await Xo();return{regular:In(e,"regular"),hotfix:In(e,"hotfix")}},AD=(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).`,Jd=(e={})=>{let t=e.hintBudgetMs??Mw;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=>Nw(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Fn($D(),t);return Es.object({type:Es.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Es.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. ${AD(r,t)}`),description:Es.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Es.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=_w(r.description),a=_w(r.releaseDate),c=aa(o);return{...Nw(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var DD='"1.2.5" or "next"',Hd=(e,t)=>{try{return Bu(e,t)}catch(r){throw r instanceof Sr?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 Xm?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}},ID=async(e,t)=>{let r=In(e,t),n=r?` [${r}]`:"",o=(await _(i=>$a({message:` Version (e.g. ${DD})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Kd.exit(1)),s},ND=async()=>{let e=(await _(t=>$a({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Kd.exit(1));try{Qs(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Kd.exit(1)}return e},_D=async()=>(await _(e=>$a({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:zo},e),{whenHeadless:"refuse"})).trim(),MD=async e=>{y.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=>jw({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=>jw({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 ND();l=Hd([{name:m,type:c}],[])[0]}else{let m=await ID(await n(),c);l=Hd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(zt(`v${l.id.raw}`))}let u=(await _(m=>$a({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await _D();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await _(m=>OD({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},jD=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 ")},Fw=e=>{for(let t of e)y.addOption("--release",Lu(t))},FD=async(e,t)=>{if(e&&e.length>0){let n=Uu(e)?await t():[],o=Hd(e,n);return Fw(o),o}if(ge())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 MD(t);return Fw(r),r},LD=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"})},BD=async(e,t)=>{let r=e.map(jD).join(`
|
|
416
416
|
- `);await G(t,`Create the following ${e.length} release(s)?
|
|
417
417
|
- ${r}
|
|
418
|
-
`),y.addOption("--yes",!0)},
|
|
418
|
+
`),y.addOption("--yes",!0)},UD=async e=>{let{entry:t,jiraConfig:r}=e,n=re(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await on({operation:`create release ${o}`});let s=await Ql(t.type),i=await eu({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
419
|
`),{result:i}}catch(s){let i=Do(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}}}},
|
|
420
|
+
`),{failure:{version:n,error:a.message}}}},WD=(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.`)},Lw=Jd(),Aa=async e=>{let{releases:t,confirmedCommand:r}=e;await Ne({operation:"create release"}),await it({provider:Lw,params:e,operation:"create release",argument:"release"});let n=await pn(),o=null,i=await FD(t,async()=>(o===null&&(o=await Xo()),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"});LD(i),await To({operation:"create release",base:pt(i[0].type)}),await BD(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await UD({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}WD(i.length,a.length,c.length),y.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}},qd=C({name:"release-create",requiresHumanConfirm:!0,formProvider:Lw,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:q.array(q.object({version:q.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:q.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:q.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:q.string().optional().describe("Optional description for the Jira version."),releaseDate:Du.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:q.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:q.array(q.string()).describe("List of created release branch names"),successCount:q.number().describe("Number of releases created successfully"),failureCount:q.number().describe("Number of releases that failed"),releases:q.array(q.object({version:q.string().describe("Version number"),type:q.enum(["regular","hotfix"]).describe("Release type"),branchName:q.string().describe("Release branch name"),prUrl:q.string().describe("GitHub PR URL"),jiraVersionUrl:q.string().describe("Jira version URL"),releaseDate:q.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:q.array(q.object({version:q.string().describe("Version number that failed"),error:q.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Aa});import Bw from"@inquirer/input";import{z as qe}from"zod";var Uw=["description","releaseDate"],VD=async()=>{let e=await V(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await pe(),o=await Kt(me({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},GD=async e=>{let r=(await V()).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},JD=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await _(o=>Bw({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},KD=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await _(o=>Bw({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:zo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Rr(n)},HD=e=>{if(e!==void 0)return e===""?null:e},qD=async e=>(y.setInteractive(),{description:await JD(e.description),releaseDate:await KD(e.releaseDate)}),Yd=e=>e??"(none)",YD=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Yd(t.releaseDate)} \u2192 ${Yd(r.releaseDate)}`,Oa=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=HD(n),i=await pn(),a;t?(a=Ct(t),await GD(a)):(y.setInteractive(),a=(await VD()).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=re(c);y.addOption("--version",l);let u=ce(c),p=await xt(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&&Z())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 v=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await qD(m),E=Uw.filter(M=>v[M]!==m[M]),k=E.includes("description"),h=E.includes("releaseDate"),R=yr(i,p),S=M=>{let $={version:l,branch:a,jiraVersionUrl:R,previousDescription:m.description,newDescription:v.description,previousReleaseDate:m.releaseDate,newReleaseDate:v.releaseDate,changedFields:E,changed:M};return{content:b(JSON.stringify($,null,2)),structuredContent:$}};if(E.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${Yd(m.releaseDate)}`),y.print(),S(!1);k&&y.addOption("--description",v.description),h&&y.addOption("--release-date",v.releaseDate??"");let P=E.map(M=>YD(M,m,v));return await G(o,`Update ${u}?
|
|
421
421
|
${P.join(`
|
|
422
422
|
`)}
|
|
423
|
-
`),y.addOption("--yes",!0),await dn({versionId:p.id,...k?{description:v.description}:{},...h?{releaseDate:v.releaseDate}:{}},i),k&&await
|
|
424
|
-
`),y.print(),S(!0)},
|
|
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=Ln.resolve(e,o),i=`${Ln.sep}.git${Ln.sep}worktrees${Ln.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},
|
|
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
|
+
`),y.addOption("--yes",!0),await dn({versionId:p.id,...k?{description:v.description}:{},...h?{releaseDate:v.releaseDate}:{}},i),k&&await Mi({branch:a,body:Oo(R,v.description)}),d.info(`\u2705 Updated ${E.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${R}`),d.info(`\u{1F517} PR branch: ${a}
|
|
424
|
+
`),y.print(),S(!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:qe.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:qe.string().optional().describe("New description. Empty string clears the description."),releaseDate:Iu.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:qe.string().describe("Release version"),branch:qe.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:qe.string().describe("Jira fix version URL"),previousDescription:qe.string().describe("The description before the update"),newDescription:qe.string().describe("The description after the update"),previousReleaseDate:qe.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:qe.string().nullable().describe("The planned release date after the update, or null"),changedFields:qe.array(qe.enum(Uw)).describe("The fields whose value actually changed"),changed:qe.boolean().describe("Whether anything actually changed")},handler:Oa});import{z as ae}from"zod";import{$ as Zd}from"zx";import{z as Ww}from"zod";var Jw=2500,Da="release-remove",Vw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zD=e=>e.version===void 0||e.version==="",XD=async()=>{try{return{outcome:"listed",prs:await V()}}catch(e){return e instanceof g&&e.operation===$o?{outcome:"empty"}:{outcome:"failed"}}},Gw=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${Da}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${Da}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${Da}`}),null),ZD=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return Ui(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(ce(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},QD=(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): ${Da}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Xd=(e={})=>{let t=e.fetchBudgetMs??Jw;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=>Vw(r)&&zD(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([Fn(XD(),t),Fn(pe(),t)]);if(r===null||r.outcome!=="listed")return Gw(r,t);let o=ZD(r.prs,n);return o.length===0?Gw({outcome:"empty"},t):Ww.object({version:Ww.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${QD(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:{...Vw(n)?n:{},version:r.version}}};var Kw=["worktree","pr","local-branch","remote-branch","jira"],Yw={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"},Dr="remove a release",tt=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Hw=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new O({...e,agentMode:j.source},2,t)},eI=e=>{ge()&&(e.version||Hw({status:"argument_required",argument:"version"},{operation:Dr,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&&Hw({status:"refused"},{operation:Dr,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"&&tt({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`})},tI=(e,t)=>{if(t.skipJira||(e.jiraConfig||tt({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)&&tt({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||tt({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)`}))},rI=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;tt({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"})},nI=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||tt({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(", ")}`})},oI=async e=>(await Zd`git -C ${e} status --porcelain`).stdout.split(`
|
|
425
|
+
`).map(r=>r.trimEnd()).filter(r=>r.length>0),sI=async e=>{try{let{terminals:t}=await Nf(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},iI=async e=>{let t=await ai([e]);if(t!==null)throw d.warn({operation:Dr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new O({status:"refused",reason:"orca_caller_inside_target",agentMode:j.source},2,{operation:Dr,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`})},aI=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await Tt();if(!n)return r;let o=await xt(ce(e),n),s=t.moveIssuesTo?await cI(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Li(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:yr(n,o)}}},cI=async(e,t)=>{let r=await xt(e,t);return r||tt({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}"`})},lI=async(e,t)=>{let r=Q(e);r||tt({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 A(),s=`${`${n}${fe}`}/${e}`,[i,a,c,l]=await Promise.all([we("release"),an(e),xe(n,`refs/heads/${e}`),Wr(n,e)]),u=i.includes(e);return u&&await iI(s),{...await aI(r,t),branch:e,id:r,label:re(r),baseBranch:a?.baseRefName??pt("regular"),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await sI(s):0,worktreeDirty:u?await oI(s):null,localTipSha:c,remoteTipSha:l,pr:a}},qw=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}),uI=(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}`},dI=(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: ${uI(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
|
|
426
|
+
`)},Ia=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},pI=e=>typeof e=="string"?e:e.outcome;async function Ps(e,t,r){try{let n=await r(),o=pI(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${Yw[e]} \u2014 ${o}`),n}catch(n){throw new Ia(e,n)}}var mI=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,fI=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>mI(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 ${Kw.indexOf(r)+1} of ${Kw.length} (${Yw[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},gI=async e=>(await ls(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",hI=async e=>{let t=await an(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 Zd`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},yI=async e=>(await Ur()===e.branch&&await Zd`git switch ${e.baseBranch}`,await ei(e.branch),await nf(e.branch)?tt({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"),vI=async e=>(await ti(e.branch),e.remoteTipSha?"deleted":"absent"),wI=async(e,t,r)=>{let n=await Li(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}\``;tt({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}`})},kI=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await wI(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 Zl({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),bI=(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}),RI=async(e,t,r)=>{let n=await Ps("worktree",r,()=>gI(e)),o=await Ps("pr",r,()=>hI(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await Ps("local-branch",r,()=>yI(e)),i=await Ps("remote-branch",r,()=>vI(e)),a=await Ps("jira",r,()=>kI(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},SI=async(e,t)=>{let r=[];try{return bI(e,await RI(e,t,r))}catch(n){throw n instanceof Ia?fI({plan:e,step:n.step,done:r,cause:n.reason}):n}},EI=async e=>{if(e)return Ct(e);y.setInteractive();let[t,r]=await Promise.all([pe(),V()]),n=r.map(s=>s.branch);n.length===0&&tt({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 Kt(me({branches:n,descriptions:t,types:o}))}catch(s){throw Ae(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"})}},Xw=Xd(),Na=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Ne({operation:Dr}),await H(),await it({provider:Xw,params:e,operation:Dr,argument:"version"}),eI(e);try{let s=await lI(await EI(r),e);d.debug({plan:qw(s)},"release remove: resolved plan"),zw(s),tI(s,e),rI(s),await To({operation:`remove release ${s.label}`,base:s.baseBranch}),nI(s),y.addOption("--version",s.label),n&&y.addOption("--move-issues-to",n),o&&y.addOption("--skip-jira",!0),await G(t,dI(s,!!o),{throwOnDecline:!0,plan:{...qw(s),skipJira:!!o}}),t||y.addOption("--yes",!0);let i=await SI(s,e);return y.print(),{content:b(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw Ae(s)||bt(s)||s instanceof g?s:(d.error({err:Cr(s)},"\u274C Error removing release"),new g(s,{operation:Dr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Qd=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:Xw,inputSchema:{version:ae.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:ae.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:ae.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:ae.string().describe("The release branch that was targeted"),version:ae.string().describe('The release label (e.g. "1.2.5")'),baseBranch:ae.string().describe("The branch HEAD was moved to before the local delete"),worktree:ae.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:ae.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:ae.number().nullable().describe("The pull request number, or null when none exists"),localBranch:ae.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:ae.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:ae.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:ae.string().nullable().describe("The origin tip before deletion"),jira:ae.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:ae.object({id:ae.string(),name:ae.string(),url:ae.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:Na});import{spawn as CI}from"node:child_process";import $I from"node:fs";import{homedir as AI}from"node:os";import Ma from"node:process";import _a from"node:fs";import Ln from"node:path";var PI=e=>{try{return _a.statSync(e).isFile()?_a.readFileSync(e,"utf8"):null}catch{return null}},xI=e=>{try{return _a.realpathSync(e)}catch{return e}},TI=(e,t)=>{let o=t(Ln.join(e,".git"))?.split(`
|
|
427
|
+
`).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=Ln.resolve(e,o),i=`${Ln.sep}.git${Ln.sep}worktrees${Ln.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},Zw=(e={})=>{let t=e.listInstallations??Cc,r=e.exists??_a.existsSync,n=e.readGitFile??PI,o=e.realpath??xI,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=TI(i.projectPath,n);if(!r(Ln.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var OI=180*1e3,DI=900*1e3,II=4*1024*1024,NI=2e3,_I=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=CI(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&&Ma.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<II&&(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)},NI).unref()})}),MI=({cwd:e,timeoutMs:t})=>_I({command:Ma.execPath,args:[Ma.argv[1]??"","setup","--unattended","--json"],cwd:e,env:Cf(Ma.env),timeoutMs:t}),jI=e=>{$I.writeFileSync(kn(),e,{mode:384})},FI=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}},LI=new RegExp("\x1B\\[[0-9;]*m","g"),BI=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(LI,"").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},UI=(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}},Qw=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":ea(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(OI,o)}),a=i.error===null?FI(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${BI(i)} \u2014 run: ${s}`]}:{root:e,...UI(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},WI=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}})},VI=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),zI=e=>{let t=Kw(e.stderr),r=Kw(e.stdout),n=[...t,...r].filter(s=>YI.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-qI).join(" / ")},XI="ENOBUFS",ZI=e=>e.error?.code===XI,QI=e=>{if(ZI(e))return`terminated after exceeding the ${Hw} 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=zI(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var eN=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},tN=e=>{let t=Ke(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},rN=(e,t)=>{let r=tN(e),n={...t,owner:e.present?e.manager:null};if(r===null)return{state:e,action:"none",recipe:null,executable:!1,refusedBecause:[],commands:[],context:n};let o=Ss(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:Es(r),context:n}},_a=async(e=kr,t=Ko())=>{let r=await qo(kr,t),n={owner:null,present:eN(r)},o=$u(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>rN(s.get(a),n)),context:n}};var ep=(e,t)=>({...Ps(e),action:"skipped",commands:e.commands,detail:t}),Ps=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),qw=(e,t)=>e.action==="none"?ep(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?ep(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Ps(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},nN=(e,t)=>t.ran?t.ok?{...Ps(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Ps(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Ps(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},tp=async e=>{let t=e.run??Qd,{plans:r}=await _a(e.ids,e.probeDeps),n=[];for(let o of r){let s=qw(o,e.mode);if(s!==null){n.push(s);continue}n.push(nN(o,t(o.recipe,o.context)))}return n},rp=async(e,t)=>{let{plans:r}=await _a(e,t);return r.map(n=>qw(n,"converge")??ep(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import wN from"node:process";import{z as N}from"zod";var np={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},oN=Object.keys(np).sort((e,t)=>np[e]-np[t]),Yw={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},zw=new Set(["manual","warn","fail"]),op=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)}},sN=e=>e.reduce((t,r)=>Yw[r]>Yw[t]?r:t,"skipped"),Zw=e=>e.message.trim(),iN=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 "),Xw=e=>e.message===Tn,aN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Zw(r):e.length>1?iN(e):t?"activate with the last line below":"see below"},cN=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>op(i.outcome)),n=t.filter(i=>zw.has(op(i.outcome))).map(Zw),o=t.filter(i=>!zw.has(op(i.outcome))&&!Xw(i)),s={name:e,status:sN(r),message:aN(o,t.some(Xw))};return n.length>0?{...s,notes:n}:s},lN=e=>({label:"Local setup",rows:oN.map(t=>cN(t,e.filter(r=>r.step===t)))}),uN=(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)}},dN=(e,t)=>{let r=uN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},pN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>dN(r,t))}),mN=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)}},fN=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)}},gN=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)}},hN=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)}},yN=(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)}},vN=e=>({label:"Portless service",rows:[{name:"link",status:mN(e.link),message:gN(e.link)},{name:"node",status:fN(e.node.outcome),message:hN(e.node)},yN(e.service,e.command)]}),Qw=(e,t)=>[lN(e.init),pN(e.tools,t),vN(e.portless)],ek=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var kN=()=>{let{link:e,node:t}=qs();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},bN=async e=>{let t=Jm(e.link).outcome,r=Gm(e.node),n=Hs(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 gv(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Nt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},rk="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",nk="--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.",RN=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(rk);if(o&&(e.tools!==void 0||r))throw new Error(nk);return{ids:e.tools??t??kr,mode:r?"update":"converge",skipTools:o}},tk=(e,t)=>e instanceof xn?e.step:t.at(-1)?.step??"zshrc",SN=async()=>{let e=[];try{await Ru(t=>{e.push(t)})}catch(t){e.push({step:tk(t,e),outcome:"failed",message:`The ${tk(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},EN=(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}`}))},PN=async(e,t)=>{try{return e.skipTools?await rp(e.ids,t.probeDeps):await tp({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return EN(e.ids,r)}},xN=e=>({step:e.step,outcome:e.outcome,message:e.message}),Ma=async(e={})=>{let t=RN(e);Xe.withheld=e.unattended===!0;let r=await SN(),n=await PN(t,e),o=await bN(e.portlessDeps??kN()),s=Qw({init:r,tools:n,portless:o},{skipTools:t.skipTools});dt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(Tn),ek(s)&&(wN.exitCode=1);let i={init:r.map(xN),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}},TN=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")}),CN=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")}),$N=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")}),AN={init:N.array(TN).describe("One entry per init step, in the order they ran"),tools:N.array(CN).describe("One result per requested dependency"),portlessService:$N.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)")},ON={tools:N.array(N.enum(kr)).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.")},sp=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:ON,outputSchema:AN,requiresHumanConfirm:!0,handler:e=>Ma({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as sk}from"node:fs";import ik from"node:path";import WN from"node:process";import{z as Dt}from"zod";import{createHash as DN}from"node:crypto";import{readFileSync as IN}from"node:fs";var Ir=e=>DN("sha256").update(IN(e)).digest("hex");import{readFileSync as LN,writeFileSync as BN}from"node:fs";import Ba from"node:path";import{z as yt}from"zod";var oe="vendor",NN=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),_N=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),MN=[".tsbuildinfo"],ip=e=>NN.has(e),ap=e=>_N.has(e)?!0:MN.some(t=>e.endsWith(t)),ja=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>ip(o))||ap(r)};import{readdirSync as jN}from"node:fs";import cp from"node:path";var FN=e=>e.split(cp.sep).join("/"),Fa=e=>{let t=[],r=n=>{for(let o of jN(n,{withFileTypes:!0})){let s=cp.join(n,o.name);if(o.isDirectory()){if(ip(o.name))continue;r(s);continue}ap(o.name)||t.push(FN(cp.relative(e,s)))}};return r(e),t.sort()};var Ye=".sync-manifest.json",La=1,UN=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())}),lp=e=>(e.schemaVersion??La)>La,ok=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Fa(e);for(let o of n)try{r[o]=Ir(Ba.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},xs=e=>{let t=Ba.join(e,Ye),r;try{r=LN(t,"utf8")}catch{throw new Error(`Missing ${Ye} at ${t}`)}let n=UN.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${Ye} at ${t}: ${yt.prettifyError(n.error)}`);return n.data},up=(e,t,r)=>{let n=ok(e,r),o={schemaVersion:La,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return BN(Ba.join(e,Ye),`${JSON.stringify(o,null,2)}
|
|
432
|
-
`),o},
|
|
433
|
-
${e} (${t.length}):`);for(let r of t.slice(0,pp))d.info(` ${r}`);t.length>pp&&d.info(` \u2026and ${t.length-pp} more`)}},Ua=async(e={})=>{let t=e.cwd??await A(),r=ik.join(t,oe),n={modified:[],added:[],removed:[],fileCount:0};if(!sk(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(!sk(ik.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=xs(r);if(lp(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}=dp(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."),mp("Modified",s),mp("Added (not in manifest)",i),mp("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}},VN={status:Dt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:Dt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:Dt.number(),modified:Dt.array(Dt.string()),added:Dt.array(Dt.string()),removed:Dt.array(Dt.string())},fp=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:VN,handler:()=>Ua({cwd:WN.cwd()})});import ak from"node:process";import{z as Ts}from"zod";var ck=async e=>{try{return await e()}catch{return null}},Wa=async()=>{let e=L.version;d.info(e);let t=await ck(A),r=t===null?null:await ck(()=>$e(t)),n={version:e,cwd:ak.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:ak.env.CLAUDE_PROJECT_DIR||null};return{content:b(JSON.stringify(n,null,2)),structuredContent:n}},gp=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:Ts.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Ts.string().describe("The working directory of this process"),repoRoot:Ts.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Ts.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Ts.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Wa});import bk from"@inquirer/confirm";import YN from"node:path";import{z as U}from"zod";import{$ as $s}from"zx";import GN from"@inquirer/input";import uk from"@inquirer/select";import{$ as er}from"zx";var Cs="dev",JN="main",hp="feature/",dk=["new","local","remote"],Va=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${hp}${t}`},pk=async()=>{let e=await er({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},KN=2,yp=async()=>{let e=await er({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Cs}`;if(e.exitCode===0)return Cs;if(e.exitCode!==KN)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 ${Cs} exists`});return await pk()??Cs},mk=async e=>{let t=e?.trim();return t?t===Cs||t===JN||t===await pk()?t:Pe(ve(t)):yp()},fk=async()=>_(e=>uk({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"}}),gk=async()=>_(e=>GN({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Va(t)===hp?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),hk=async(e,t)=>e.length===0?t:_(r=>uk({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),HN=async e=>{let t=await er({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===hp||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`})},lk=async e=>(await er({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,qN=async e=>(await er({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,yk=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Va))];for(let s of n)await HN(s);if(!await lk(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 qN(s)?o.push({branch:s,base:r,source:"local"}):await lk(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},vk=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await er`git worktree add ${t} ${r}`:o==="remote"?await er`git worktree add --track -b ${r} ${t} origin/${r}`:await er`git worktree add --no-track -b ${r} ${t} origin/${n}`},wk=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 As="create worktrees",zN=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],vp=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Ga=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await Ne({operation:As}),XN(e);try{let o=await A(),s=`${o}${fe}`;await kk(`${s}/${Lr.release}`),await kk(`${s}/${Lr.feature}`);let i=await ZN(e),a=i==="feature"?await e_(e):await QN(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let R={kind:i,createdWorktrees:[],count:0,features:[],...vp()};return{content:b(JSON.stringify(R,null,2)),structuredContent:R}}let c=await H(),l=await t_(r,c),u=await r_(n,c),p=await $e(o),m=YN.basename(p),f=u?await n_({explicit:n!==void 0,mainRepoRoot:p}):null;await G(t,o_(f,m,a.previewLines)),t||y.addOption("--yes",!0);let v=f?await s_(f,p):null,E=await u_(a.targets,s);if(d_(E),l)for(let R of E)await $s`github ${s}/${R}`,await $s`sleep 5`;let k=v?await a_({registration:v,createdWorktrees:E,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):vp();c_(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:As,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},XN=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:As,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},ZN=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),fk()),QN=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 Kt(me({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",$t(o));let{branchesToCreate:s}=l_({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>$s`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},e_=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await gk()],n===void 0)){let l=(await V()).map(u=>u.branch);n=await hk(l,await yp())}let o=await mk(n),s=await yk({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=>vk(l,u)})),features:a,previewLines:a.map(wk)}},t_=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await _(o=>bk({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},r_=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await _(o=>bk({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},Rk=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"},n_=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Lt();if(n!=="ready"){let{reason:s,text:i}=Rk(n);if(t)throw d.warn({operation:As},`\u26D4 --orca was passed but ${i}`),new O({status:"refused",reason:s,agentMode:j.source},2,{operation:As,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 Nf(r);return{probe:n,registered:o.registered,visibility:o.visibility}},o_=(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
|
+
`},GI=e=>({version:e.version??L.version,home:e.home??AI(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>Oc({lockPath:my()})),readRecord:e.readRecord??bn,writeRecord:e.writeRecord??fy,discoverProjects:e.discoverProjects??(()=>Zw()),runSetupChild:e.runSetupChild??MI,writeLog:e.writeLog??jI}),JI=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},KI=async e=>{let t=e.readRecord(),r=e.clock();if(!yy(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+DI,s=await Qw(null,e.home,e,o),i=JI(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 Qw(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:WI(a)};e.writeRecord(c);try{e.writeLog(VI(c))}catch{}return"ran"},ek=async(e={})=>{try{let t=GI(e),r=t.acquireLock();if(r===null)return"already-running";try{return await KI(t)}finally{r()}}catch{return"not-due"}},ep=async(e={})=>{let t=await ek(e);return{content:b(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as zI}from"node:child_process";import{homedir as XI}from"node:os";import ZI from"node:process";var HI=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},YI=(e,t)=>{let r=HI(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},xs=(e,t)=>{let r=[...qI(e),...YI(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},Ts=e=>e.steps.map(Be);var QI=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],eN=e=>{let t={...Om(e)};for(let r of QI)delete t[r];return t},tp=(e,t,r={})=>{let n=r.spawnSync??zI,o=r.env??ZI.env,s=(r.agentMode??ge)(),i=Ts(e),a=xs(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:nN({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??tN}):{ran:!1,commands:i,refusedBecause:a.reasons}},tN=e=>{d.info(e)},rk=64,rN=rk*1024*1024,nN=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=eN(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:rN,cwd:XI(),env:s}),l=lN(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},oN=5,sN=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,tk=e=>e==null?[]:String(e).split(`
|
|
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},mp=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!La(c))),n=Ba(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}Ir(Wa.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 fp=30,gp=(e,t)=>{if(t.length!==0){d.info(`
|
|
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
|
+
`)},g_=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Ok(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await jf(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 Vr?r.code:void 0}}},h_=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,y_=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=kp();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=yf(i),l=r.length===1&&t.visibility!=="hide",u=Lf();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Bf({cwd:m,title:Uf({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Ff(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:h_(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof Vr&&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 Vr?f.code:void 0})}}return a},v_=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}`)}},$k=async e=>{await Ds`mkdir -p ${e}`},w_=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>Br(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},k_=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await Ds({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},b_=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")},bp=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:U.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:U.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:U.boolean().optional().describe('Add worktrees for every open release branch. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:U.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),githubDesktop:U.boolean().optional().describe('Open each created worktree in GitHub Desktop. Resolution order: this flag \u2192 "worktrees.openInGithubDesktop" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).'),orca:U.boolean().optional().describe('Open each created worktree in Orca: one terminal tab per worktree, laid out per "worktrees.orca.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInOrca" from infra-kit config \u2192 interactive prompt (CLI, default yes) / false (MCP, no TTY). Passed explicitly, an Orca that is absent or not running is refused before any worktree is created (orca_absent / orca_unreachable); resolved from config it degrades to orcaSkipped with that reason.')},outputSchema:{kind:U.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:U.array(U.object({branch:U.string(),base:U.string(),source:U.enum(kk)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:U.array(U.string()).describe("List of created git worktree branches"),count:U.number().describe("Number of git worktrees created"),orcaOpened:U.array(U.object({branch:U.string(),layout:U.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:U.array(U.object({branch:U.string(),reason:U.enum(i_),code:U.string().optional()})).describe("Created worktrees NOT opened in Orca and why: orca_absent / orca_unreachable (config-derived ask, Orca down), orca_worktree_not_selectable (Orca had not scanned the fresh worktree yet), orca_error (code carries the Orca error code)"),orcaHidden:U.array(U.object({branch:U.string(),path:U.string(),fix:U.string()})).describe("Created worktrees whose Orca terminals opened on a row the sidebar HIDES (the repo hides external worktrees); fix names the in-app steps to reveal it")},handler:Ka});import{z as rr}from"zod";var Ha=async()=>{await H();let[e,t]=await Promise.all([we("release"),we("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 R_(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
|
|
435
435
|
|
|
436
|
-
${
|
|
436
|
+
${S_(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),k_=async e=>{let[t,r]=await Promise.all([Sk(e.worktreePath),Sk(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 Lt();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}`)},b_=async e=>{let t=Be(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${h_}; ${t} && { sleep ${y_}; exit; }`;try{return(await Of(["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:Ek,remediation:`run \`infra-kit worktrees remove ${Be(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Pk=async e=>{let t=await w_();await k_(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 b_(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 R_=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"})}},S_=(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(", ")}`})},E_=async(e,t)=>{let r=await oi(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`})},P_=e=>e?e.split(",").map(t=>Pe(ve(t.trim()))):[],x_=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Va):[],T_=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(","))},Ha=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 Pk(t)}await Ne({operation:"remove worktrees"}),await H(),R_({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=[...P_(n),...x_(o)];else{y.setInteractive();let[v,E]=await Promise.all([pe(),V()]),k=new Map(E.map(h=>[h.branch,h.type]));p=await Kt([...me({branches:i,descriptions:v,types:k}),...a.map(h=>({value:h,label:h,type:"feature"}))],{required:!0})}S_(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):T_(p),await E_(u,p),await G(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await Cr({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"}))}},bp=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:Ha});import{z as Os}from"zod";var qa=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 Di();await G(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=C_({releasePRsList:s,currentWorktrees:r}),a=await Cr({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"}))}},C_=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Br(s)).filter(s=>!t.includes(s))}},Rp=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:Os.array(Os.string()).describe("List of removed worktree branches"),failedWorktrees:Os.array(Os.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Os.number().describe("Number of worktrees removed during sync")},handler:qa});var Sp=[{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"}],Sr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Ml,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:ed,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:ad,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:Kd,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:qd,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:dd,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Xd,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:Ud,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Wd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:wp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:kp,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:bp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:Rp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:nd,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Gf,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:jc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:rd,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:od,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Nl,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:fp,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:sp,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:Wu,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:Sl,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:gp,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:Ol,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 Ep=e=>Sr.filter(t=>t.menuGroup===e),Pp=e=>Sr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var $_=(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},xk=e=>Sp.flatMap(({key:t,label:r})=>Ep(t).flatMap(n=>{let o=$_(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import xp from"node:process";var A_="MODULE_TYPELESS_PACKAGE_JSON",O_=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Tk=!1,Tp=()=>{if(Tk)return;Tk=!0;let e=xp.emitWarning.bind(xp);xp.emitWarning=((t,...r)=>{O_(r[0],r[1])!==A_&&e(t,...r)})};import{Command as Bj,InvalidArgumentError as Ab,Option as Cb}from"commander";import{resolve as Uj}from"node:path";import je from"node:process";import{cd as Wj}from"zx";import Ck from"node:process";import{$ as D_}from"zx";var Cp=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}},R_=async e=>{let[t,r]=await Promise.all([V(),pe()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=Q(o);if(!s)return[];let i=re(s),a=n.get(o)||"regular",c=r.get(ce(s))||null;return[{version:i,type:a,description:c}]})},S_=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=No(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},Rp=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: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")})).describe("Release worktrees with details"),count:rr.number().describe("Number of release worktrees"),features:rr.array(rr.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:Ha});import{z as ze}from"zod";import E_ from"node:fs/promises";import{$ as P_}from"zx";var Ik="remove this worktree",x_=2,T_=3,qa=async e=>{try{return await E_.realpath(e)}catch{return e}},Nr=(e,t)=>{throw new g(void 0,{operation:Ik,remediation:e,stderrExcerpt:t})},C_=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=$t([e]);return Br(e)&&t?["--versions",t]:Nr("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`)},$_=async()=>{let e=await qa(await A()),t=await qa(await $e(e));e===t&&Nr("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 ot(t))await qa(o.path)===e&&(r=o.branch);if(!r)return Nr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await qa(`${t}${fe}/${r}`);return n!==e&&Nr("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:C_(r)}},Dk=async e=>(await P_({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
|
|
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}
|
|
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
|
-
`,"%0A")}`,
|
|
448
|
-
`).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(
|
|
449
|
-
`))},
|
|
450
|
-
`),
|
|
451
|
-
`)[0]??"",
|
|
452
|
-
`;import{existsSync as
|
|
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}},Op=async()=>{let e=await ee(),t=jk.env.EDITOR||jk.env.VISUAL||"vi",r=await yn(e);r.createdConfig&&d.info(vn(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await W_({stdio:"inherit"})`${t} ${e.userProject}`,jt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Dp=async({key:e,global:t})=>{Oi(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Di(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${Ro[r]} (${w(n)})`:`${e} is not set in the ${Ro[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 Wk from"node:fs/promises";import _s from"node:path";import Q_ from"node:process";import{pathToFileURL as eM}from"node:url";import{execFile as V_,spawn as G_}from"node:child_process";import or from"node:fs/promises";import J_ from"node:os";import nr from"node:path";import Fk from"node:process";import{promisify as K_}from"node:util";var H_=K_(V_),Lk="3.39.0",q_=10*1024*1024,Y_=960,z_=60,Ip=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,X_=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${Ip(e)}`}},Bn=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},Z_=(e,t,r)=>new Promise((n,o)=>{let s=G_(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}`))})}),Za={run:Z_,capture:async(e,t,r)=>{let{stdout:n}=await H_(e,t,{...r,maxBuffer:q_});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{Fk.stdout.write(`${e}
|
|
446
|
+
`)}},Xa=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),Bk=async e=>{let t=JSON.parse(await or.readFile(nr.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},_p=async e=>{let t=await or.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=nr.join(e,r.name);return r.name==="node_modules"?or.rm(n,{recursive:!0,force:!0}):_p(n)}))},Np=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 or.readFile(nr.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`)},Mp=({root:e,service:t,scriptDir:r,env:n=Fk.env,deps:o=Za})=>{let s=async(h,R,S,P={})=>{o.log(`COMMAND: ${[R,...S].join(" ")}`);try{await o.run(R,S,{cwd:P.cwd??e,env:P.env??n})}catch(M){throw new Error(`${h} failed: ${M.message}`)}},i=async(h,R,S={})=>{let{attempts:P=8,initialDelaySeconds:M=3,maxDelaySeconds:$=60}=S,J=async K=>{try{return await R()}catch(Ce){if(K>=P)throw new Error(`${h} failed after ${P} attempts: ${Ce.message}`);let Bs=Math.min($,M*2**(K-1)),Us=Math.round((Bs/2+o.random()*Bs/2)*10)/10;return o.log(`Attempt ${K}/${P} failed. Retrying in ${Us}s...`),await o.sleep(Us*1e3),J(K+1)}};return J(1)},a=async(h,R,S=n)=>{o.log(`COMMAND: aws ${R.join(" ")}`),await i(h,()=>o.run("aws",R,{cwd:e,env:Xa(S)}))},c=async(h,R={})=>{await s(`aws ${h.slice(0,2).join(" ")}`,"aws",h,{cwd:R.cwd,env:Xa(R.env??n)})},l=async h=>{let R=await Promise.all(h.map(async S=>{try{let P=await o.capture("aws",["ssm","get-parameter","--name",S,"--query","Parameter.Value","--output","text"],{cwd:e,env:Xa(n)});return[S,P.trim()]}catch(P){throw new Error(`SSM parameter ${S}: ${P instanceof Error?P.message:String(P)}`)}}));return Object.fromEntries(R)},u=async h=>{let R=[`turbo@${await Bk(e)}`,...h?[`serverless@${Lk}`]:[]];await s("Install tools","pnpm",["add","-g",...R])},p=async(h,R)=>{let S=nr.join(e,"out"),P={...n,...R.buildEnv},M=R.buildTask??P.TURBO_BUILD_TASK??"build";return await or.rm(S,{recursive:!0,force:!0}),await s(`Prune to ${h}`,"turbo",["prune",h],{env:P}),await s("Install dependencies","pnpm",["install"],{cwd:S,env:P}),await s(`Build ${h}`,"pnpm",["exec","turbo",M,`--filter=${h}`,"--env-mode=loose"],{cwd:S,env:P}),R.installProd&&(o.log("COMMAND: remove every node_modules under ./out"),await _p(S),await s("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:S,env:P}),await s("Show node_modules size","du",["-sm","./node_modules/"],{cwd:S})),S},m=async(h,R,S)=>{if(R!==void 0){o.log(`Running ${h} hooks...`);try{await R(S)}catch(P){throw new Error(`${h} hooks failed: ${P.message}`)}o.log(`${h} hooks completed successfully`)}},f=async h=>{let{app:R,appPath:S}=await Np(e,r,h);await u(!0);let P={...n,...h.buildEnv},M=await p(R,{installProd:!0,buildTask:h.buildTask,buildEnv:h.buildEnv}),$={stage:h.stage,outDir:M,appDir:nr.join(M,S)};await m("Pre-deployment",h.preDeploy,$),await s("Deploy with Serverless","serverless",["deploy","--stage",h.stage,"--force"],{cwd:$.appDir,env:P}),h.restApiId===void 0?o.log(`Skipping API Gateway deployment for ${R}: no restApiId.`):await a("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",h.restApiId,"--stage-name","api"],P),await m("Post-deployment",h.postDeploy,$)},v=async h=>{let{app:R,appPath:S}=await Np(e,r,h);await u(!1);let P={...n,...h.buildEnv},M=await p(R,{installProd:!1,buildTask:h.buildTask,buildEnv:h.buildEnv}),$={stage:h.stage,outDir:M,appDir:nr.join(M,S)},J=`s3://${h.bucket}${h.destPath??""}`,K=h.sourcePath??"./dist";await s("Sync to S3","aws",["s3","sync",K,J,...h.syncFlags??[],"--only-show-errors"],{cwd:$.appDir,env:Xa(P)}),await a("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",h.cloudfrontId,"--paths",h.invalidationPath??"/*"],P),await m("Post-deployment",h.postDeploy,$)},E=async(h,R,S)=>{let P=await or.mkdtemp(nr.join(J_.tmpdir(),"infra-kit-lambda-")),M=nr.join(P,"response.json"),$=["lambda","invoke","--function-name",h.functionName,...S===void 0?[]:["--region",S],"--cli-binary-format","raw-in-base64-out","--payload",h.payload??R,"--cli-read-timeout",String(Y_),"--cli-connect-timeout",String(z_),M],J=Date.now();o.log(`COMMAND: aws ${$.join(" ")}`);try{let K=await o.capture("aws",$,{cwd:e,env:{...n,AWS_PAGER:""}}).then(X_,vc=>`aws CLI failed: ${Ip(vc instanceof Error?vc.message:String(vc))}`),Ce=await or.readFile(M,"utf-8").catch(()=>""),Bs=((Date.now()-J)/1e3).toFixed(1),Us=K!==void 0&&Ce?`; response: ${Ip(Ce)}`:"";return{outcome:`${h.functionName} (${Bs}s)`,failure:K===void 0?void 0:K+Us}}finally{await or.rm(P,{recursive:!0,force:!0})}};return{root:e,service:t,ssm:l,aws:c,run:(h,R,S={})=>o.run(h,R,{cwd:S.cwd??e,env:S.env??n}),capture:(h,R,S={})=>o.capture(h,R,{cwd:S.cwd??e,env:S.env??n}),retry:i,skip:h=>{throw new Bn(h)},pruneAndBuild:p,deployBackendApi:f,deployFrontendUi:v,invokeLambdas:async h=>{let{region:R,payload:S="{}",blocking:P=[],steps:M=[]}=h;for(let $ of P){let{outcome:J,failure:K}=await E($,S,R);if(K!==void 0)throw new Error(`Lambda ${J} failed: ${K}`);o.log(`Lambda ${J} OK`)}for(let $ of M){let J=await Promise.all($.map(K=>E(K,S,R).catch(Ce=>({outcome:K.functionName,failure:String(Ce)}))));for(let{outcome:K,failure:Ce}of J)o.log(Ce===void 0?`Lambda ${K} OK`:`Warning: Lambda ${K} failed, continuing: ${Ce}`)}}}};var Uk=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),tM=async(e,t)=>{let r=_s.join(e,"devops","scripts",`deploy-${t}.sh`);try{await Wk.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},rM=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
|
|
447
|
+
`,"%0A")}`,nM=(e,t)=>{let r=(e??"").split(`
|
|
448
|
+
`).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(rM(n));return Object.fromEntries(r)},oM=async e=>{try{await Wk.access(e)}catch{throw new g(void 0,{operation:`run ${_s.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(eM(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${_s.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},jp=async e=>{let{service:t,env:r=Q_.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(ge()&&r.INFRA_KIT_DEPLOY_VIA!==ks)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 A(),o=e.deps??Za,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,...nM(s,o.log)},c=(await Ot(n))?.services[t]?.deploy;if(c===void 0)await o.run("sh",[await tM(n,t)],{cwd:n,env:a});else{let l=await oM(_s.join(n,c)),u=Mp({root:n,service:t,scriptDir:_s.dirname(c),env:a,deps:o});try{await l(u)}catch(p){if(!(p instanceof Bn))throw p;return d.info(`\u23ED\uFE0F ${t} skipped: ${p.message}`),Uk({status:"skipped",service:t,reason:p.message})}}return d.info(`\u2705 ${t} deployed`),Uk({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as Ms}from"@slip-stream-kit/config/internal";import ec from"node:fs/promises";import tc from"node:path";var Fp=async e=>{try{return await ec.readFile(e,"utf-8")}catch{return}},Qa=e=>({content:b(JSON.stringify(e,null,2)),structuredContent:e}),sM={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},Vk=async(e,t)=>(await Promise.all(t.map(async n=>{let o=tc.join(e,n);return(await Fp(o))?.startsWith(Mn)?[{path:n,absolute:o}]:[]}))).flat(),iM=async(e,t)=>t.replaceV1!==!0?[]:(await Vk(e,gd)).map(r=>({...r,status:"removed"})),aM=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Fp(tc.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${Ms} do not exist: ${n.join(", ")}`)},cM=async(e,t)=>{if(t.replaceV1===!0)return;let r=await Vk(e,hd);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 ${Ms} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},Lp=async(e={})=>{let t=e.cwd??await A(),r=await Ot(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${Ms} at ${t}, nothing to generate.`),Qa({status:"missing-config",ok:!!e.check,files:[]});await cM(t,r),await aM(t,r);let n=await Promise.all(wd(r).map(async a=>{let c=tc.join(t,a.path),l=await Fp(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await iM(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 ${Ms}.`),Qa({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${Ms}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${sM[a.status]})`);return Qa({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await ec.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await ec.mkdir(tc.dirname(a.absolute),{recursive:!0}),await ec.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return Qa({status:"written",ok:!0,files:i})};var Gk="https://dashboard.doppler.com/workplace/projects",lM=(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}"): ${Gk}/${e}`],Bp=async({env:e})=>{let r=!!(await Ze())?.envs[e];await Tf(e);let n=await lr(),o=await Lt();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 lM(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Gk}/${n}`};return{content:b(JSON.stringify(s,null,2)),structuredContent:s}};import uM from"@inquirer/confirm";import dM from"@inquirer/input";import pM from"@inquirer/password";import mM from"@inquirer/select";import fM from"node:fs/promises";import vt from"node:process";import{$ as rc}from"zx";var gM=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Jk(),source:"stdin"};if(t){let n=vt.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!vt.stdin.isTTY){let n=await Jk();if(n)return{token:n,source:"stdin"};if(!Z())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 y.setInteractive(),{token:(await _(n=>pM({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:vt.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Jk=async()=>{let e=[];vt.stdin.setEncoding("utf8");for await(let t of vt.stdin)e.push(t);return e.join("").trim()},Up="DOPPLER_CONFIG",hM=3e4,yM=async(e,t,r)=>{let n=rc.quiet;rc.quiet=!0;let o;try{o=(await rc({env:no(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(hM)).stdout}catch(s){throw vM(s,r)}finally{rc.quiet=n}return Fc(o)},vM=(e,t)=>{let r=zm(e)??(e instanceof Error?e.message:String(e));if($f(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=Af(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(`
|
|
449
|
+
`))},wM=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Up}.`,"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(`
|
|
450
|
+
`),Hk=async(e,t,r,n)=>{let o=await yM(e,t,r);jc(o,r);let s=o.some(([i])=>i===Up);if(!s&&!n)throw new Error(wM(r));return s},Kk="\0new-env",kM=async()=>{if(Z()||!vt.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([Vf(),Ze()]),r=Math.max(0,...e.map(({env:s})=>s.length));y.setInteractive();let n=await _(s=>mM({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:Kk}]},s),{output:vt.stderr,whenHeadless:"refuse"});return n!==Kk?n:(await _(s=>dM({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:vt.stderr,whenHeadless:"refuse"})).trim()},bM=async(e,t,r)=>_(n=>uM({message:`Replace the "${e}" token ${Te(t)} with ${Te(r)}?`,default:!0},n),{output:vt.stderr,whenHeadless:"refuse"}),RM=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${Te(r)})`;case"replaced":return`Replaced the "${e}" service token ${Te(n??"")} \u2192 ${Te(r)}`;case"unchanged":return`The "${e}" service token is already ${Te(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${Te(n??"")} \u2014 nothing was written`;default:return Ue(t)}},Wp=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await lr(),s=e??await kM(),{token:i,source:a}=await gM({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Hk(i,o,s,n),l=(await Ze())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await bM(s,l,i)?u="kept":(await $c({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Lt();d.info(`${RM(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Up} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:Te(i),previousRedactedToken:l===void 0?null:Te(l),storePath:p,scopeVerified:c};return y.print(),{content:b(JSON.stringify(m,null,2)),structuredContent:m}},SM=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,qk=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?SM(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},EM=e=>(e instanceof Error?e.message:String(e)).split(`
|
|
451
|
+
`)[0]??"",PM=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",xM=async(e,t,r,n)=>{let o=Te(e.token);try{let s=await Hk(e.token,t,e.env,n);return{env:e.env,status:PM(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:EM(s)}}},Vp=async({fromFile:e,force:t})=>{let r=await lr(),n=qk(await fM.readFile(e,"utf8")),o=await Ze(),s=await Promise.all(n.map(p=>xM(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 $c(i);let a=await Lt(),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&&(vt.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}};var Gp=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 Td(n);if(r&&y.addOption("--from",p),xd(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"?Ea({version:o,env:s,skipTerraform:a,confirmedCommand:c}):Pa({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Jp=async e=>Gp(e,"all"),Kp=async e=>Gp(e,"selected"),nc=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.`),Gp({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as zk}from"@slip-stream-kit/config/internal";import Hp from"node:fs/promises";import Un from"node:path";import Yk from"node:process";import{pathToFileURL as TM}from"node:url";var Xk="~/projects",qp=async(e={})=>{if(e.init){await $M(e.cwd);return}await CM()},CM=async()=>{let e=Sn(),t=await ne(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."),Yk.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await Zi(),s=En(r),i=await ne(s),a=Un.join(s,n),c=await ne(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=Un.join(s,u),m=await ne(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",v=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${v}`)}l||(Yk.exitCode=1)},$M=async e=>{let t=Sn();if(await ne(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await A(),n=await AM(r);await Hp.mkdir(Un.dirname(t),{recursive:!0}),await Hp.writeFile(t,OM(Un.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${zk}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${Xk}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${Un.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.")},AM=async e=>{try{let t=Un.join(e,zk),r=await Hp.stat(t),s=(await import(`${TM(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[]},OM=(e,t)=>`${JSON.stringify({workspaceDir:Xk,source:e,targets:t},null,2)}
|
|
452
|
+
`;import{existsSync as Lj}from"node:fs";import Bj from"node:fs/promises";import Pb from"node:path";import xb from"node:process";import{z as Uj}from"zod";import{chmodSync as LM,copyFileSync as BM,lstatSync as UM,mkdirSync as ab,readdirSync as WM,readlinkSync as VM,rmSync as GM,rmdirSync as cb,symlinkSync as JM,unlinkSync as KM,writeFileSync as HM}from"node:fs";import Se from"node:path";import{lstatSync as DM,readlinkSync as Zk}from"node:fs";import IM from"node:path";var NM=new Set(["ENOENT","ENOTDIR"]),oc=e=>{let t;try{t=DM(e)}catch(r){if(NM.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:Zk(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:Ir(e)}:{kind:"other"}},Qk=(e,t)=>{let r=IM.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:Zk(r)}:{kind:"file",executable:t.mode==="100755",sha:Ir(r)};return{...t,fingerprint:n}},eb=(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 _M}from"zx";var X=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await _M({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},sc=e=>e.slice(0,7),rt=e=>e.split("\0").filter(t=>t.length>0);import MM from"node:path";var Yp=`${oe}/`,sr=`${oe}/README.md`,js=`${oe}/${Ye}`,rb=e=>e.startsWith(Yp),tb=e=>{let t=MM.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},nb=e=>{let t=tb(e.path),r=e.target===void 0?t:tb(e.target);return{path:t,target:r,vendored:rb(r),module:e.module??null}},ob=e=>e.copy.map(nb),Fs=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),Ls=(e,t)=>e.filter(r=>!Fs(r.path,t)),ic=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,Wn=e=>[...new Set(e)].sort(),sb=e=>e.startsWith(Yp)?e.slice(Yp.length):null;var ac=e=>`# vendor/ \u2014 mirrored from ${e}
|
|
453
453
|
|
|
454
454
|
**DO NOT EDIT files in this folder here.**
|
|
455
455
|
|
|
@@ -460,19 +460,19 @@ fail \`ik vendor check\` in CI.
|
|
|
460
460
|
To change a vendored package, edit it in \`${e}\` and re-run the sync there.
|
|
461
461
|
|
|
462
462
|
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,
|
|
463
|
+
`;var jM=new Set(["100644","100755","120000"]),FM=(e,t)=>{let r=new Map;for(let n of rt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!jM.has(s)||Fs(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},zp=async(e,t,r)=>{let n=await X(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return FM(n,r)},ib=async e=>rt(await X(e,["--literal-pathspecs","ls-files","-z","--",oe]));var Vn=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],lb=e=>{let t=oc(e);t!==null&&(t.kind==="other"?cb(e):KM(e))},qM=(e,t,r)=>{let n=Se.join(e,r.source),o=Se.join(t,r.target);if(ab(Se.dirname(o),{recursive:!0}),lb(o),r.mode==="120000"){JM(VM(n),o);return}BM(n,o),LM(o,r.mode==="100755"?493:420)},YM=async(e,t)=>{let r=new Set;for(let n of rt(await X(e,["ls-files","-z"]))){if(t.has(n))continue;let o=Se.posix.dirname(n);for(;o!==".";)r.add(o),o=Se.posix.dirname(o)}return r},zM=async(e,t)=>{if(t.length===0)return;let r=await YM(e,new Set(t)),n=[...new Set(t.map(o=>Se.dirname(Se.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)&&!(!UM(s,{throwIfNoEntry:!1})?.isDirectory()||WM(s).length>0||r.has(Se.relative(e,s).split(Se.sep).join("/")));)cb(s),s=Se.dirname(s)}},ub=(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,sr,...s].map(sb).filter(a=>a!==null&&!La(a));return Wn(i)},db=async(e,t,r,n)=>{let o=Se.join(e,oe);ab(o,{recursive:!0}),HM(Se.join(e,sr),ac(t.name));let s=ub(r,await ib(e),n);pp(o,{source:t.name,commit:t.headSha},s)},Xp=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(Vn(t));let n=Se.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)lb(Se.join(n,a));await zM(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&GM(Se.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)qM(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await db(n,e,t.entries,o),{touched:Wn([...o,...i,sr,js]),manifestWritten:!0}):{touched:Wn([...o,...i]),manifestWritten:!1}},Zp=async(e,t)=>(await db(e,t,[],[]),[sr,js]);var Qp=(e,t)=>`[ROOT] vendor: sync from ${e}@${sc(t)}`,XM=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
|
|
464
|
+
`).trim()||String(e)},em=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 X(e,["--literal-pathspecs","add","-A",...o],{input:n}),await X(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:XM(s)}}};var pb=20,ZM=20,rm=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],tm=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of Ls(e.files,r)){let p=ic(u.path,n);if(s.push(p),eb(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=Ls(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}},_r=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),nm=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),QM=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...nm(e,r)];return _r(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...rm(n,pb),Be(o)])},ej=(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=sc(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}`,...rm(e.lines,ZM)],warnings:[]}},tj=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},rj=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},nj=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return Wn([...n,...r?t.headVendorMeta:[]])},oj=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`),sj=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return QM(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return _r(t,"fail","blocked: a module this repo dropped is still a dependency",[...rm(t.pruneConflicts,pb)]);let n=e.entries.flatMap((f,v)=>{let E=t.entries[v]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return E.scope==="release"?[]:E.scope==="sync"?[tm(f,E,e.exclude)]:[{...tm({...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={..._r(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=ej(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(tj).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:`${rj(n)} on ${t.branch}`,notes:[...u,...m,...oj(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:nj(n,t,o)}},cc=(e,t)=>{switch(t.kind){case"missing":return _r(t,"skipped",`not checked out at ${t.root}`);case"source":return _r(t,"skipped","this is the source repo");case"not-git":return _r(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return _r(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return sj(e,t)}};import{existsSync as mj,readFileSync as fj,realpathSync as lc}from"node:fs";import uc from"node:path";import{readFileSync as mb}from"node:fs";import Gn from"node:path";var ij=["dependencies","devDependencies","peerDependencies","optionalDependencies"],aj=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},fb=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=aj(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")},gb=e=>{try{return JSON.parse(mb(e,"utf8"))}catch{return null}},cj=(e,t)=>t.files.flatMap(r=>{let n=Gn.posix.relative(t.entry.path,r.path);if(Gn.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=gb(Gn.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),lj=e=>ij.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),hb=(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},uj=["*.sh","*.yml","*.yaml"],dj=(e,t,r)=>{let n=lj(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"&&hb(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},pj=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...uj];return rt(await X(e,n,{allowFailure:!0})).filter(s=>r(s)&&hb(mb(Gn.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},yb=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of cj(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=rt(await X(t,["ls-files","-z","--","*package.json"])).filter(c=>Gn.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=gb(Gn.join(t,p));return m===null?[]:dj(p,m,c)});u.push(...await pj(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var om=async(e,t)=>{let r=t.exclude??[],n=(await X(e,["rev-parse","HEAD"])).trim(),o=await $e(e),s=await Promise.all(ob(t).map(async i=>{let a=await zp(e,i.path,r);return{entry:i,files:a.map(c=>Qk(e,c))}}));return{root:e,selfRoots:[...new Set([lc(e),lc(o)])],name:uc.basename(o),headSha:n,entries:s,exclude:r}},dc=e=>{let t=rt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},gj=async(e,t,r)=>{let n=nm(e,t);if(n.length===0)return[];let o=await X(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return dc(o).filter(s=>!Fs(s,e.exclude))},hj=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 Ls(l,e.exclude)){let p=ic(u.path,n);c[p]=oc(uc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),yj=async e=>{try{return rt(await X(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",sr,js]))}catch{return[]}},vj=e=>{try{let{commit:t,source:r}=$s(uc.join(e,oe));return{commit:t,source:r}}catch{return null}},wj=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await xe(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 X(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
|
|
465
|
+
`).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},kj=(e,t)=>{try{return fj(uc.join(e,sr),"utf8")===ac(t)}catch{return!1}},bj=async e=>{try{return{toplevel:(await X(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
|
|
466
|
+
`)[0]??"git rev-parse failed"}}},Rj=async e=>{try{return(await X(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},pc=async(e,t)=>{if(!mj(t.root))return{...t,kind:"missing"};let r=lc(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await bj(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(lc(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=fb(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=vj(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([Rj(t.root),gj(e,o,t.root),hj(e,o,t.root),yj(t.root),wj(e,o,i)]),m=l.flatMap((f,v)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[v],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:kj(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await yb(e.root,t.root,m)}};var Sj=20,Ej=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],Pj=(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:",Be(Vn(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:Ej(r,t)}},xj=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(`
|
|
467
|
+
`).slice(0,Sj)},Tj=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[Pj(e,t),...r,...e.commit?[xj(e.commit)]:[]]}},Cj={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},sm=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:Cj[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>Tj(o,r))],hints:n}},vb=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),wb=(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 $j=20,im=async(e,t)=>(await X(e,t,{allowFailure:!0})).trim(),Aj=async e=>dc(await X(e,["status","--porcelain","-z","--untracked-files=normal"])),Oj=async e=>(await im(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"]},Dj=async e=>{let[t,r]=await Promise.all([im(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),im(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}`}},kb=async e=>{let t=await Aj(e);if(t.length>0){let n=t.slice(0,$j),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([Oj(e),Dj(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import Mj from"node:path";import{readFileSync as Ij}from"node:fs";import Nj from"node:path";import{z as _j}from"zod";var bb=e=>{let t;try{t=Ij(Nj.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=ff.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:_j.prettifyError(n.error)}};var Rb=(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=En(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=Mj.join(n,s);return{name:s,root:i,selection:bb(i)}})},jj="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",Fj=async(e,t)=>{let r=await pc(e,t),n=cc(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}},Sb=async(e,t,r)=>Promise.all(t.map(async n=>r?Fj(e,n):cc(e,await pc(e,n))));var Tb="sync vendored files",Wj=e=>{let t=Pb.join(En(e.workspaceDir),e.source);if(Lj(t))return t;throw new O({status:"refused",reason:"source-missing",source:t},1,{operation:Tb,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'})},am=(e,t)=>new O({status:"refused",reason:"not-a-vendor-source"},1,{operation:Tb,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`}),Vj=async e=>{let t=Pb.join(e,"infra-kit.json"),r;try{r=JSON.parse(await Bj.readFile(t,"utf8"))}catch(s){throw am(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw am(t,"has no vendorSource block");let o=mf.safeParse(n);if(!o.success)throw am(t,`has an invalid vendorSource: ${Uj.prettifyError(o.error)}`);return o.data},Eb=(e,t)=>{xb.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
|
|
468
468
|
${Be(t)}
|
|
469
|
-
`)},
|
|
470
|
-
`),D(e)),Jj=e=>e.description("List all release branches").action(async()=>{D(await Sa())}),Kj=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".',Vj,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Mu),o=n.length>0?n:void 0;D(await Ca({releases:o,confirmedCommand:t.yes}))}),Hj=e=>{if(e==="")return e;try{return br(e)}catch(t){throw t instanceof On?new Ab(t.message):t}},qj=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Ab("Expected a positive whole number of days.");return t},Yj=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)',Hj).option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await $a({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Ob=e=>e.option("-f, --from <where>",`Where the deploy runs: ${Zt.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"),zj=e=>Ob(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{D(await Vp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Xj=e=>Ob(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 Gp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),Zj=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 ha({version:t.version,confirmedCommand:t.yes}))}),Qj=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 Da({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),eF=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await qa({confirmedCommand:t.yes}))}),tF=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 Ga({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),rF=e=>e.description("List all git worktrees with detailed information").action(async()=>{D(await Ja())}),nF=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 Ha({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),oF=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 Kp({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 Ua();D(t),t.structuredContent.ok||(je.exitCode=1)}),iF=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 am({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)}),aF=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{D(await Cp())}),cF=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{D(await $p())}),lF=new Set(["version"]),fc=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},dm=()=>{let e=new Bj().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");Gj(t.command("merge-dev")),Jj(t.command("list")),Kj(t.command("create")),Yj(t.command("edit")),zj(t.command("deploy-all")),Xj(t.command("deploy-selected")),Zj(t.command("deliver")),Qj(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");tF(r.command("add")),rF(r.command("list")),nF(r.command("remove")),eF(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");aF(n.command("path")),cF(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 Ai({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 Il({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 Ap({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 tc({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 tc({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 Si({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 _p({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 jp({check:a.check});D(c),c.structuredContent.ok||(je.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");sF(i.command("check")),oF(i.command("config")),iF(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 sa({fix:!!a.fix});ir.enabled||Vl(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,ir.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{D(await Oi())}),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 la({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 Cb("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Cb("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){D(await Zd());return}D(await Ma({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 Wa())}),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})`,qj).action(async a=>{D(await Ti({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 pa())}),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 Vf())}),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=>{$b(await Nc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{$b(await da())}),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 Up({fromFile:c.fromFile,force:c.force}));return}D(await Bp({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 ma({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 Fp({env:a}))});for(let a of e.commands)Hm(a);return lm(e),um(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&Wj(Uj(je.cwd(),l)),y.start(fc(c)),ir.enabled=!!c.optsWithGlobals().json,ir.enabled&&(d.level="warn"),j.source=Ys({env:je.env,stdinIsTTY:je.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),lF.has(fc(c))||await hu()}),e.hook("postAction",(a,c)=>{let l=fc(c);if(Pp(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Pb({equivalent:dc(f,!0)})}),e};import uF from"node:process";var dF={exit:uF.exit,emit:D,logger:d},Db=(e,t=dF)=>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 pm=(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 pF from"node:fs";import mm from"node:path";import Jn from"node:process";var _b=new Set([...uf,Hn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Mb=null,gc=new Set,fm=null,Ib=!1;var Nb=e=>{try{return pF.statSync(e)}catch{return null}},mF=()=>{if(Ib)return null;try{return Fr()}catch{return Ib=!0,d.debug(`session-env: ${Hn} unset \u2014 no overlay`),null}},fF=e=>{let t=mm.join(e,Mr),r=mm.join(e,Ls),n=Nb(t),o=Nb(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Em(mm.join(e,Bs),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"}},gF=e=>e.kind==="load"?{kind:"load",vars:Rm(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Sm(e.file),signature:e.signature}:e;var hF=()=>{let e=mF();if(e===null)return{kind:"no-session"};let t=fF(e);return t.signature===fm?null:gF(t)},yF=()=>{for(let e of gc){let t=Mb[e];t===void 0?delete Jn.env[e]:Jn.env[e]=t}gc.clear()},vF=(e,t,r)=>{if(_b.has(t)){e.skipped.push(t);return}Jn.env[t]=r,gc.add(t),e.set.push(t)},wF=(e,t)=>{if(_b.has(t)){e.skipped.push(t);return}delete Jn.env[t],gc.add(t),e.unset.push(t)},kF=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))vF(t,r,n);if(e.kind==="clear")for(let r of e.unset)wF(t,r);return t},bF=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,gm=(e=hF())=>{if(Mb??={...Jn.env},e===null||e.kind==="no-session"||e.signature===fm)return{set:[],unset:[],changed:!1};yF();let{set:t,unset:r,skipped:n}=kF(e);return fm=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(", ")}] (${bF(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as WF}from"chalk";import{spawn as VF}from"node:child_process";import Fe from"node:process";import{Chalk as RF}from"chalk";var Kn=new RF({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."},SF={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"}},jb={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},Fb={unicode:"\u2500",ascii:"-"},EF=3,hm=e=>e,PF={ok:e=>Kn.green(e),findings:e=>Kn.yellow(e),failed:e=>Kn.red(e),cancelled:e=>Kn.gray(e)},vm=e=>e?{dim:t=>Kn.dim(t),bold:t=>Kn.bold(t)}:{dim:hm,bold:hm},xF=(e,t)=>e?PF[t]:hm,ym=e=>[...e].length,TF=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return ym(e)<=r?e:[...e].slice(0,r).join("")},Lb=e=>{let t=vm(e.color===!0).dim,r=SF[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(TF(n,e.width))},Bb=(e,t={})=>{let r=vm(t.color===!0);return`${r.dim(nt.reproPrefix.trim())} ${r.bold(e)}`},CF=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,$F=(e,t)=>e==="findings"?t!=null?`${t} ${nt.findingsSuffix}`:nt.findingsPlain:{ok:nt.ok,failed:nt.failed,cancelled:nt.cancelled}[e],AF=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<EF?"":` ${n(r.repeat(o))}`},Ub=e=>{let t=e.color===!0,r=vm(t),n=xF(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?nt.reproPrefix:nt.nonReproPrefix,i=o?jb[e.outcome].ascii:jb[e.outcome].unicode,a=$F(e.outcome,e.findingsCount),c=[CF(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
471
|
-
`)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${nt.sep}${c.join(nt.sep)}`,m=
|
|
472
|
-
`)};var
|
|
473
|
-
`,
|
|
469
|
+
`)},Gj=async(e,t,r)=>r?(Eb(t,Vn(t)),Zp(t.root,e)):(await Xp({source:e,plan:t,onBeforeFirstWrite:o=>{Eb(t,o)}})).touched,Jj=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await Gj(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 em(t.root,n,Qp(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},Kj=async(e,t,r)=>{let n=[];for(let o of t)n.push(await Jj(e,o,r));return n},Cb=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})),cm=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&dt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:Cb(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:vb(t),report:t.sections}}},Hj=async e=>{let t=await Zi(),r=Wj(t),n=await kb(r),o=await Vj(r),s=Rb(t,e.targets??[]),i=await om(r,o),a=await Sb(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},lm=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await Hj(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=sm(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return cm({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!Z();if(l&&!xb.stdin.isTTY)return dt(a),cm({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&dt({...a,hints:[]}),await G(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:Cb(n),throwOnDecline:!0});let u=await Kj(t,n,e),p=sm(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);dt(wb(a,p,m))}return cm({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var mc=(e,t=!0)=>({line:e,reproducible:t});import fc from"node:fs";import qj from"node:os";import Yj from"node:path";import Db from"node:process";var gc="INFRA_KIT_SESSION_REPORT",um=null,$b=!1,Ab=[],Ib=(e=Db.env)=>{$b||(um=e[gc]??null,$b=!0,delete e[gc])};var Nb=(e,t)=>{if(!um)return;let r=e.summary??(Ab.length>0?[...Ab]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{fc.writeFileSync(s,i)});try{o(um,JSON.stringify(n))}catch{}},Ob=0,_b=e=>{let t=e?.tmpdir?.()??qj.tmpdir(),r=e?.pid??Db.pid;return Ob+=1,Yj.join(t,`infra-kit-session-${r}-${Ob}.json`)},Mb=(e,t)=>{if(!(t?.exists??(i=>fc.existsSync(i)))(e))return null;let n=t?.read??(i=>fc.readFileSync(i,"utf-8")),o=t?.unlink??(i=>fc.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var dm=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)dm(r)};var pm=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)pm(r)};var Qj=(e,t)=>[...t,e],eF=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 Oh(()=>ya({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&&(je.exitCode=1)}),Fb=e=>(je.stdout.write(`${e.structuredContent.filePath}
|
|
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=`${nt.sep}${c.join(nt.sep)}`,m=wm(u)+wm(p),f=BF(m,e.width,o?Hb.ascii:Hb.unicode,r.dim),v=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&v.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&v.push(r.dim(nt.envNotice)),v.join(`
|
|
472
|
+
`)};var UF=new Set([130,143]),Xb=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&UF.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import WF from"node:process";var VF={3:"quit",4:"quit",26:"suspend",27:"quit"},GF=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":VF[t]??"continue"},JF=150,KF="\r\x1B[2K",HF=`\r
|
|
473
|
+
`,Zb=(e,t)=>{Qb(e),e.stdin.on("data",t),e.listener=t},Qb=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},eR=(e,t)=>{Rf(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),Zb(e,t)},tR=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(KF)),Qb(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Sf()},qF=e=>{e.settled||(e.settled=!0,tR(e))},rR=(e,t)=>{let r=qb({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},YF=async e=>{await new Promise(t=>{setTimeout(t,e)})},zF=(e,t,r)=>{tR(e),t(),eR(e,r),rR(e,HF)},XF=async e=>new Promise(t=>{let r=n=>{let o=GF(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){zF(e,s,r);return}t("palette")};Zb(e,r),rR(e,"")}),nR=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??WF.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return eR(n,()=>{}),e.armed(),await YF(t.drainMs??JF),await XF(n)}finally{qF(n)}};import oR from"node:process";var ir={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},sR=(e,t)=>{let r=t?.write??(s=>{oR.stderr.write(s)}),n=t?.stdin??oR.stdin,o=[ir.saveCursor,ir.scrollRegion,ir.restoreCursor,ir.column,ir.sgr,ir.cursor,ir.wrap];e.entersAltScreen===!0&&o.push(ir.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var iR=e=>`infra-kit ${e.groupPath.join(" ")}`,eL=()=>{tL();let e=Fe.stderr.columns;return e!=null&&e>0?e:void 0},tL=()=>{let e=Fe.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},rL=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),nL=async(e,t,r)=>{let n=_b(),o={...t.env,[gc]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Fe.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await rL(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=Mb(n),c=Xb(i.code,i.signal,a!=null,e.longRunning),l=iR(e),u=a?.equivalent??mc(l,!0);return zb({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)})},oL=1e3,sL=(e,t)=>e!=null&&t-e<=oL,bm=e=>{e.resetTerminal(),e.exit(0)},iL=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&bm(t)},s=()=>{let c=e();if(c==="palette"){bm(t);return}if(!sL(r,t.now())){if(c==="pause"){bm(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}},aR=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),aL=Fe.platform==="win32"?void 0:()=>{Ef()},cL=(e,t)=>r=>nR(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:aL}),cR=async(e,t)=>{let r={spawn:t.spawn??QF,now:t.now??(()=>Date.now()),env:t.env??Fe.env,cliPath:t.cliPath,ascii:t.ascii??!(Fe.stdout.isTTY&&Fe.env.TERM!=="dumb"),color:t.color??ZF.level>0,columns:t.columns??eL,resetTerminal:t.resetTerminal??(u=>{sR(u)})},n=t.write??(u=>Fe.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Fe.on(u,p)},unregister:(u,p)=>{Fe.off(u,p)},exit:u=>{Fe.exit(u)},raise:u=>{Fe.kill(Fe.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:iL(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??cL(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=Yb(iR(p),{color:r.color});n(`
|
|
474
474
|
${m}
|
|
475
|
-
`),a.childStarted();let f=await
|
|
475
|
+
`),a.childStarted();let f=await nL(p,r,()=>{o="child"});if(n(`
|
|
476
476
|
${f}
|
|
477
|
-
`),await l(c)==="quit")return}}finally{a.dispose()}}
|
|
477
|
+
`),await l(c)==="quit")return}}finally{a.dispose()}};$p();Ib();var pR=mm(),uR=async(e=Le.argv)=>{ym(),kf(e);try{await pR.parseAsync(e)}catch(t){Ub(t)}},mL=()=>{try{if(Le.env.INFRA_KIT_NO_LOCATION_WARN||Le.argv.includes("--json"))return;Am({selfRealPath:dL(dR(import.meta.url)),cwd:Le.cwd(),env:Le.env,realpath:Ee,home:pL(),exists:uL})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};mL();qm((e,t)=>{d.debug(e,t)});ku(L.version);var mR=()=>_k(pR.commands),fL=async()=>{let e=mR(),t=null;try{if(Le.stdout.isTTY&&Le.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-ST2534PA.js");t=await r(e)}else{let r=fm(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new lR(" "),new lR(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await _(o=>lL({message:"Select a command to run",choices:n},o),{output:Le.stderr})}}catch(r){if(!Ae(r))throw r}return t},gL=async()=>{let{runCommandPalette:e}=await import("./boot-ST2534PA.js"),t=dR(import.meta.url),r=new Map(Er.map(n=>[n.groupPath.join(" "),n]));await cR(mR(),{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(Le.argv.length<=2){let e={stdoutIsTTY:!!Le.stdout.isTTY,stdinIsTTY:!!Le.stdin.isTTY,stderrIsTTY:!!Le.stderr.isTTY};if(aR(Le.env,e))await gL();else{let t=await fL();t&&await uR(["node","infra-kit",...t.split(" ")])}}else await uR();
|
|
478
478
|
//# sourceMappingURL=cli.js.map
|