infra-kit 0.40.0 → 0.42.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/{boot-ST2534PA.js → boot-26CWOALE.js} +2 -2
- package/dist/{boot-ST2534PA.js.map → boot-26CWOALE.js.map} +1 -1
- package/dist/{chunk-QS7RKE5P.js → chunk-HIGOL4H4.js} +2 -2
- package/dist/chunk-HMXEV7ZN.js +16 -0
- package/dist/chunk-HMXEV7ZN.js.map +7 -0
- package/dist/chunk-K5KNXRTF.js +6 -0
- package/dist/chunk-K5KNXRTF.js.map +7 -0
- package/dist/chunk-K5YNW3DE.js +4 -0
- package/dist/chunk-K5YNW3DE.js.map +7 -0
- package/dist/{chunk-GCOYOWGH.js → chunk-RVMKL6T4.js} +1 -1
- package/dist/{chunk-GCOYOWGH.js.map → chunk-RVMKL6T4.js.map} +1 -1
- package/dist/chunk-S23ECFH4.js +5 -0
- package/dist/chunk-S23ECFH4.js.map +7 -0
- package/dist/{chunk-PP44RGIU.js → chunk-VZAXKGEY.js} +2 -2
- package/dist/{chunk-T5WMUJID.js → chunk-YSR7UND3.js} +2 -2
- package/dist/{chunk-T5WMUJID.js.map → chunk-YSR7UND3.js.map} +2 -2
- package/dist/{chunk-TNT65LOE.js → chunk-ZY6BBGHH.js} +3 -3
- package/dist/cli.js +169 -143
- package/dist/cli.js.map +4 -4
- package/dist/dev-server.js +19 -19
- package/dist/dev-server.js.map +4 -4
- package/dist/dev-wizard-run-PF3FTXA7.js +2 -0
- package/dist/{dev-wizard-run-AAQGTUAH.js.map → dev-wizard-run-PF3FTXA7.js.map} +2 -2
- package/dist/mcp-proxy.js +1 -1
- package/dist/{persistent-ink-dev-ui-D6ALK2P3.js → persistent-ink-dev-ui-HHTHZ24S.js} +2 -2
- package/dist/secrets-download-DXRM5M6F.js +2 -0
- package/dist/update-check.js +1 -1
- package/package.json +14 -15
- package/readme.md +1 -1
- package/dist/chunk-KTWOAA5C.js +0 -12
- package/dist/chunk-KTWOAA5C.js.map +0 -7
- package/dist/chunk-LSZFL3CV.js +0 -7
- package/dist/chunk-LSZFL3CV.js.map +0 -7
- package/dist/chunk-SIEUC4SP.js +0 -15
- package/dist/chunk-SIEUC4SP.js.map +0 -7
- package/dist/dev-wizard-run-AAQGTUAH.js +0 -2
- package/dist/env-load-KX34NCPI.js +0 -2
- /package/dist/{chunk-QS7RKE5P.js.map → chunk-HIGOL4H4.js.map} +0 -0
- /package/dist/{chunk-PP44RGIU.js.map → chunk-VZAXKGEY.js.map} +0 -0
- /package/dist/{chunk-TNT65LOE.js.map → chunk-ZY6BBGHH.js.map} +0 -0
- /package/dist/{persistent-ink-dev-ui-D6ALK2P3.js.map → persistent-ink-dev-ui-HHTHZ24S.js.map} +0 -0
- /package/dist/{env-load-KX34NCPI.js.map → secrets-download-DXRM5M6F.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{a as Ig}from"./chunk-V2ZLQPLI.js";import{a as an,b as yg,c as Zt,d as Mi,e as vg,f as wg,g as kg,h as bg,i as Rg,j as Sg,k as Eg,l as Pg,o as vl,p as Og,s as Dg,u as _e}from"./chunk-ZY6BBGHH.js";import{a as Cf,b as Ge,c as $f,d as Xc,e as Af,f as Of,g as Df,h as If,i as ko,j as _f,k as Nf,l as Mf,m as jf,n as Ff,o as bo,p as Lf,q as Bf,r as Uf,s as Vf,t as Zc,u as Pi,v as Tt,w as Wf,x as xi,y as Gf}from"./chunk-VZAXKGEY.js";import{a as pe,b as X,c as zt,d as Eo,e as nl,f as Di,g as Ii,h as ol,i as Po,j as kr,k as sl,l as _i,m as fg,n as Ct,o as To,p as fl,q as gl,r as hl,s as xg,u as yl}from"./chunk-HIGOL4H4.js";import{b as rn,c as Si,d as zc,e as Sf,f as Ei,g as Ef,i as Pf,k as xf,m as be,o as Tf}from"./chunk-REDCBY4O.js";import{a as il,b as al,c as Ke,d as cl,e as Ae,f as ul,h as xo,j as dl,k as pl,n as ml}from"./chunk-K5KNXRTF.js";import{a as y,b as Ee,c as Tg,d as Cg,e as N,f as ji,g as q}from"./chunk-K5YNW3DE.js";import{a as $g,b as Ag}from"./chunk-QWVLAZ6N.js";import{b as Ni,c as Xt,d as me,e as gg,f as ll,g as hg}from"./chunk-S23ECFH4.js";import{$ as qt,A as Xf,B as Zf,C as Qf,D as $i,E as Ai,F as $e,G as Ro,H as sn,I as Oi,J as eg,K as tg,L as rg,M as el,N as tl,O as ng,P as d,Q as Je,R as ie,S as w,T as st,U as og,V as sg,W as ig,X as A,Y as cg,Z as lg,_ as ug,a as Ht,aa as dg,b as I,ba as rl,c as Jf,ca as pg,d as _,da as mg,e as ee,ea as z,f as H,fa as V,g as Ti,ga as So,h as Kf,ha as Yt,i as g,j as Hf,k as Ci,l as te,m as Re,n as Ce,o as qf,p as Qc,q as de,r as se,s as nn,t as Yf,u as pt,v as Se,w as $,x as Ie,y as on,z as zf}from"./chunk-HMXEV7ZN.js";import{a as ag}from"./chunk-MFAFQVTW.js";import{a as U}from"./chunk-YSR7UND3.js";import{a as Gt,b as ki,c as Xr,d as dt,e as wf,f as Jt,g as Zr,h as Qr,i as bi,j as en,k as Ri,l as kf,m as bf,n as xt,o as Kt,p as ot,q as ce,r as Rf,s as tn}from"./chunk-RVMKL6T4.js";import U0,{Separator as lS}from"@inquirer/select";import{existsSync as V0,realpathSync as W0}from"node:fs";import{homedir as G0}from"node:os";import We from"node:process";import{fileURLToPath as dS}from"node:url";import _h from"node:process";import{z as je}from"zod";import Ug from"node:fs";import ln from"node:path";import{packageConfigSchema as Mg}from"@slip-stream-kit/config/internal";import jg from"node:fs/promises";import Fi from"node:path";import{pathToFileURL as kS}from"node:url";import{z as Fg}from"zod";import _g from"node:path";var Co=["frontend","backend","lib","e2e","mobile"],fS={ui:"frontend",api:"backend",tests:"e2e"},gS="mobile-app",hS=[{type:"e2e",packages:["@playwright/test"]},{type:"mobile",packages:["@capacitor/core","@capacitor/cli"]},{type:"backend",packages:["serverless"]}],yS=(e,t)=>{let r=_g.relative(t,e).split(_g.sep).filter(s=>s!==""&&s!=="."),[n,,o]=r;if(r.length===3&&n==="apps"&&o!==void 0){let s=fS[o];if(s)return s}return r.at(-1)===gS?"mobile":null},vS=e=>{let t=new Set([...Object.keys(e.dependencies??{}),...Object.keys(e.devDependencies??{}),...Object.keys(e.peerDependencies??{})]);for(let n of hS)if(n.packages.some(o=>t.has(o)))return n.type;return t.has("vite")&&t.has("react")&&!!e.scripts?.dev?"frontend":null},$o=({packageDir:e,repoRoot:t,pkgJson:r,declaredType:n})=>n??yS(e,t)??vS(r)??"lib";var mt={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Ng=2e3,wl={"e2e-test":"pnpm exec playwright test","e2e-test-ui":"pnpm exec playwright test --ui","e2e-test-ui-demo":`E2E_SLOW_MO=\${E2E_SLOW_MO:-${Ng}} 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"},br={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"]},Ao=(e,t=mt)=>({requiredScripts:e.requiredScripts??[...t.requiredScripts],requiredFiles:e.requiredFiles??[...t.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...t.turboTasks]});import wS from"node:fs/promises";var Ne=async e=>{try{return await wS.access(e),!0}catch{return!1}};var fe="infra-kit.config.ts",Rr=async e=>{try{let t=await jg.readFile(Fi.join(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}},kl=async e=>{let t=await jg.stat(e),o=(await import(`${kS(e).href}?mtime=${Number(t.mtimeMs)}`)).default;if(o===void 0)throw new Error(`${fe} at ${e} has no default export`);return typeof o=="function"?await o():o},$t=async e=>{let t=Fi.join(e,fe);if(await Ne(t))try{let n=(await kl(t))?.type;return Co.find(o=>o===n)}catch{return}},Lg=e=>e,Oo=async(e,t=mt)=>{let r=Fi.join(e,fe);if(!await Ne(r))throw new Error(`${fe} not found at ${r}`);let n=await kl(r),o=Mg.safeParse(n);if(!o.success)throw new Error(`Invalid ${fe} at ${r}: ${Fg.prettifyError(o.error)}`);return Ao(Lg(o.data),t)},ft=async e=>{let t=Fi.join(e,fe);if(!await Ne(t))return;let r=Mg.safeParse(await kl(t));if(!r.success)throw new Error(`Invalid ${fe} at ${t}: ${Fg.prettifyError(r.error)}`);return Lg(r.data)};import Bg from"node:fs/promises";import Li from"node:path";import bS from"yaml";var RS="pnpm-workspace.yaml",SS=async e=>(await Bg.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(r=>r.isDirectory()).map(r=>Li.join(e,r.name)),ES=async(e,t)=>{let r=[];for(let n of e){if(t==="*"){r.push(...await SS(n));continue}let o=Li.join(n,t);await Ne(o)&&r.push(o)}return r},PS=async(e,t)=>{let r=[e];for(let n of t.split("/"))r=await ES(r,n);return r},Pe=async e=>{let t=await Bg.readFile(Li.join(e,RS),"utf-8"),n=((bS.parse(t)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),o=new Set;for(let s of n){let i=await PS(e,s);for(let a of i)await Ne(Li.join(a,"package.json"))&&o.add(a)}return[...o].sort()};import Do from"node:path";var Io=async e=>{let t=Do.resolve(e);for(;t!==Do.dirname(t);){if(await Ne(Do.join(t,"package.json")))return t;t=Do.dirname(t)}if(await Ne(Do.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 He=(e,t,r)=>{let n=e.indexOf(t),o=e.indexOf(r);return n!==-1&&o!==-1&&o>=n},Qt=(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}`:"")},Sr=(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},Bi=(e,t,r)=>`${e}
|
|
4
4
|
${t}
|
|
5
|
-
${r}`,
|
|
5
|
+
${r}`,cn=({content:e,body:t,startMarker:r,endMarker:n,placement:o="replace-in-place"})=>{let s=Bi(r,t,n),i=He(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?Qt(e,r,n)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
6
6
|
${s}
|
|
7
7
|
`:`${s}
|
|
8
|
-
`};var
|
|
8
|
+
`};var xe="<!-- infra-kit:begin -->",Me="<!-- infra-kit:end -->",Er="<!-- infra-kit:version ",qe="<!-- infra-kit:package:begin -->",it="<!-- infra-kit:package:end -->",At="<!-- infra-kit:package:version ";var xS=e=>{let t=e.indexOf(qe)+qe.length;return e.slice(t,e.indexOf(it))},TS=e=>{let t=e.indexOf(At);if(t===-1)return null;let r=e.slice(t+At.length).match(/^\S+\s+([^\s>]+)/)?.[1];return Co.find(n=>n===r)??null},Ot=e=>{if(e===null)return{state:"missing"};if(!He(e,qe,it))return e.includes(qe)||e.includes(it)?{state:"malformed"}:He(e,xe,Me)?{state:"foreign-block"}:{state:"no-block"};let t=xS(e);if(t.trim()==="")return{state:"malformed"};let r={state:"ok"},n=Sr(t,At),o=TS(t);return n!==null&&(r.version=n),o!==null&&(r.type=o),r};import CS from"node:fs";var gt=e=>{try{return CS.readFileSync(e,"utf-8")}catch{return null}};var Vg="pnpm-workspace.yaml",$S="CLAUDE.md",Rl=e=>{let t=ln.resolve(e);for(;t!==ln.dirname(t);){if(Ug.existsSync(ln.join(t,Vg)))return t;t=ln.dirname(t)}return Ug.existsSync(ln.join(t,Vg))?t:null},bl=new Map,Ui=()=>{bl.clear()},AS=async e=>{let t;try{t=await Pe(e)}catch{return{adopted:!1,workspaceRoot:e}}for(let r of t){let n=ln.join(r,$S),o=gt(n);if(o!==null&&Ot(o).state==="ok")return{adopted:!0,workspaceRoot:e,evidencePath:n}}return{adopted:!1,workspaceRoot:e}},un=async e=>{if(e===null)return{adopted:!1,workspaceRoot:null};let t=bl.get(e);if(t)return t;let r=await AS(e);return bl.set(e,r),r};import Pr from"node:fs";import er from"node:path";var Wg=`---
|
|
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 Gg=`# {{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 Jg="# {{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 Kg="# {{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 Hg=`# {{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 qg=`# {{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,33 @@ This block is generated by \`infra-kit audit --fix\` \u2014 edit text _outside_
|
|
|
138
138
|
- The native shell is Capacitor; its settings live in \`capacitor.config.*\`.
|
|
139
139
|
- The web build feeds the native shell, so a device run needs a rebuild first.
|
|
140
140
|
- Use the tokens in \`DESIGN.md\` rather than ad-hoc colors, spacing, or type scales.
|
|
141
|
-
`;var
|
|
142
|
-
`)&&n.index!==0)throw new Error(`renderTemplate: multi-line value for {{${n[1]}}} must start its line (found at column ${n.index})`)}},
|
|
143
|
-
`),t);return
|
|
144
|
-
`).replace(
|
|
145
|
-
`};var
|
|
146
|
-
`)};var
|
|
147
|
-
`)};import Zr from"node:fs";import iS from"node:path";var yi=e=>{let t;try{t=Zr.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},fo=(e,t)=>{let r=go(e,t);return r!=="unchanged"&&(Zr.mkdirSync(iS.dirname(e),{recursive:!0}),Zr.writeFileSync(e,t,"utf-8")),r},go=(e,t)=>{yi(e);let r=Zr.existsSync(e)?Zr.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Zc=(e,t,r)=>{let n=Zr.readFileSync(e,"utf-8");if(!Ve(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},hg=(e,t,r)=>Ve(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Qc=(e,t,r,n)=>{let o=hg(e,r,n),s=hg(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 wi="<!-- infra-kit:import:begin -->",ki="<!-- infra-kit:import:end -->",aS="AGENTS.md",yg="CLAUDE.md",cS="README.md",el="DESIGN.md",lS=["frontend","mobile"],uS=e=>yr.existsSync(e)?yr.readFileSync(e,"utf-8"):null,tl=(e,t)=>{try{return yr.readdirSync(e).includes(t)}catch{return!1}},vi=(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},vg=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=uS(e),a=i===null?"":o?.(i)??i,c=Hr({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return go(e,c);let l=fo(e,c);return Zc(e,r,n),i!==null&&Qc(a,c,r,n),l},dS=(e,t)=>{if(!yr.existsSync(e))return"unchanged";yi(e);let r=yr.readFileSync(e,"utf-8"),n=Jt(r,Se,Ie);return n===null?"unchanged":n.trim()===""?(t||yr.rmSync(e),"removed"):t?go(e,n):fo(e,n)},pS=(e,t,r)=>vg({filePath:e,dryRun:r,body:mo(t),startMarker:Se,endMarker:Ie,prepare:n=>Jt(n,wi,ki)??n}),ho=async(e,{version:t,dryRun:r=!1})=>{let n=Kt.join(e,yg),o=Kt.join(e,aS),s=[];try{s.push({path:n,action:pS(n,t,r)})}catch(i){s.push(vi(n,i))}try{s.push({path:o,action:dS(o,r)})}catch(i){s.push(vi(o,i))}return s},mS=(e,t,r,n)=>{if(!lS.includes(r)||tl(e,el))return null;let o=Kt.join(e,el),s=Yc(t);try{return{path:o,action:n?go(o,s):fo(o,s),type:r}}catch(i){return vi(o,i,r)}},bi=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await fr(e),s=o.name??Kt.basename(e),i=ao({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:Xc({version:r,type:i,packageName:s,relDir:Kt.relative(t,e).split(Kt.sep).join("/"),hasReadme:tl(e,cS),hasDesign:tl(e,el),hasE2eDoc:yr.existsSync(Kt.join(t,zc)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},yo=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=Kt.join(e,yg),{body:a,type:c,packageName:l}=await bi(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:vg({filePath:i,body:a,startMarker:Ge,endMarker:et,dryRun:s}),type:c})}catch(p){u.push(vi(i,p,c))}if(n){let p=mS(e,l,c,s);p&&u.push(p)}return u};import _S from"node:path";import wg from"node:path";var rl="agent-guidance",vo="CLAUDE.md",fS="\u2014 run: infra-kit audit --fix",gS={missing:`${vo} missing`,"no-block":`${vo} has no infra-kit block (expected ${Ge} \u2026 ${et})`,malformed:`${vo} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${vo} carries the ROOT infra-kit block (${Se}); a package needs the package block`},hS=e=>e.adopted?` (workspace adopted: ${wg.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",nl=(e,t)=>{let r=Tt(ut(wg.join(e,vo)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:rl,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${gS[r.state]} ${fS}`,o=r.state==="missing"?`${n}${hS(t)}`:n;return t.adopted?{name:rl,status:"fail",message:o}:{name:rl,status:"pass",message:`not yet adopted \u2014 ${o}`}};import yS from"node:path";var ol=async(e,t=ct)=>{try{let r=await lo(e,t);return{check:{name:de,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:de,status:"fail",message:r.message},rules:null}}},kg="infra-kit.json",vS=async e=>await De(yS.join(e,de))?{name:de,status:"fail",message:'retired at the repo root \u2014 root audit rules live in infra-kit.json "audit". Run `infra-kit audit --fix --root` to move them and delete the file'}:null,sl=async(e,t=mr)=>{let r=await vS(e),n=r?[r]:[];try{let{audit:o={}}=await K();return{checks:[{name:kg,status:"pass",message:"present and valid"},...n],rules:co(o,t)}}catch(o){return{checks:[{name:kg,status:"fail",message:o.message},...n],rules:null}}};import Ri from"node:fs/promises";import Qr from"node:path";import{$ as wS}from"zx";var wo="playwright.config.ts",kS=[{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')"}],bg=e=>Object.entries(Gc).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"}}),bS="infra-kit-e2e",Rg=async(e,t={})=>{let r=Qr.join(e,wo),n=await Ri.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${wo}`,status:"fail",message:`missing ${wo}`}]:kS.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===bS?{name:s,status:"pass",message:"not required \u2014 e2e.server is 'static', the suite serves its own build"}:o.pattern.test(n)?{name:s,status:"pass",message:"present"}:{name:s,status:"fail",message:`${wo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},RS=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,SS=/\.[cm]?[jt]sx?$/u,il=async(e,t)=>(await Ri.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&SS.test(n.name)).map(n=>Qr.join(n.parentPath,n.name)),ES=async e=>{let t=await il(Qr.join(e,"src"),!0);for(let r of[Qr.join(e,wo),...t]){let n=await Ri.readFile(r,"utf-8").catch(()=>"");if(RS.test(n))return!0}return!1},Sg=async e=>{let t="e2e-auth:gitignored";if(!await ES(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await wS({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}`}},al="E2E__BASIC_AUTH_USERNAME",cl="E2E__BASIC_AUTH_PASSWORD",PS=/\bE2E_\w*BASIC_AUTH_\w+/gu,xS=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,TS=/\/\*[\s\S]*?\*\//gu,CS=/(^|[^:])\/\/[^\n]*/gu,$S=e=>/USER(?:NAME)?$/u.test(e)?al:cl,AS=e=>e.replace(TS,"").replace(CS,"$1"),Eg=async e=>{let t="e2e-env:basic-auth",r=[...await il(e,!1),...await il(Qr.join(e,"src"),!0)],n=[];for(let o of r){let s=await Ri.readFile(o,"utf-8").catch(()=>""),i=new Set([...AS(s).matchAll(PS)].map(a=>a[0]).filter(a=>xS.test(a)&&a!==al&&a!==cl));for(let a of i)n.push(`${a} \u2192 ${$S(a)} (${Qr.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${al} / ${cl}`}:{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("; ")}`}},ll=async(e,t,r={})=>[...bg(t),...await Rg(e,r),await Sg(e),await Eg(e)];import OS from"node:fs/promises";import DS from"node:path";var ul=async(e,t)=>Promise.all(t.map(async r=>{let n=await OS.stat(DS.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 dl=(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 IS from"node:fs/promises";import NS from"node:path";var en="turbo.json",pl=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await IS.readFile(NS.join(e,en),"utf-8");r=JSON.parse(o)}catch(o){return[{name:en,status:"fail",message:`cannot read/parse ${en}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:en,status:"fail",message:`no "tasks" object defined in ${en}`}]:t.map(o=>{let s=o in n||`//#${o}`in n;return{name:`turbo:${o}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${o}" in ${en}`}})};var MS=async(e,t)=>{let{check:r,rules:n}=await ol(e,t);return{checks:[r],rules:n}},jS={adopted:!1,workspaceRoot:null},FS=async(e,t,r)=>ao({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await Pt(e)}),LS=async e=>(await lt(e).catch(()=>{}))?.e2e?.server==="static",ml=async(e,t=ct,r={})=>{let n=await fr(e),o=n.name??_S.basename(e),{checks:s,rules:i}=r.isRoot?await sl(e,t):await MS(e,t);r.isRoot||s.push(nl(e,r.adoption??jS)),i&&(s.push(...dl(n.scripts??{},i.requiredScripts)),s.push(...await ul(e,i.requiredFiles)),s.push(...await pl(e,i.turboTasks))),!r.isRoot&&await FS(e,n,r.repoRoot)==="e2e"&&s.push(...await ll(e,n.scripts??{},{staticServer:await LS(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var fl=["plugin","marketplace","add",Bt],gl=["plugin","install",q,"--scope","project"],Pg=(e,t)=>ur({projectPath:e,home:t}).kind==="installed",Si=e=>((e??"").split(`
|
|
148
|
-
`).find(r=>r.trim().length>0)??"").trim(),
|
|
149
|
-
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${
|
|
141
|
+
`;var Yg='# 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 the integration branch by default \u2014 `dev`, or `main` in a repo with `"gitFlow": "main"` (or 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 integration branch (`dev`, or `main` under `"gitFlow": "main"`) 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- The git flow is the root `infra-kit.json` key `gitFlow`: `"dev"` (default) cuts features and regular releases from `dev` and delivers through a `dev \u2192 main` RC PR, hotfixes from `main`; `"main"` cuts everything from `main` and delivers straight into it, with no hotfix type. Never branch from `dev` in a `"main"` repo, even if a stale `dev` exists.\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 dn={"root/body":Yg.trimEnd(),"package/frontend":Kg.trimEnd(),"package/backend":Gg.trimEnd(),"package/lib":Hg.trimEnd(),"package/e2e":Jg.trimEnd(),"package/mobile":qg.trimEnd(),"design/skeleton":Wg.trimEnd()};var Sl=/\{\{(\w+)\}\}/g,FS=/^- \{\{(\w+)\}\}$/,LS=e=>new Set([...e.matchAll(Sl)].map(t=>t[1])),BS=(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(", ")}`)},US=(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(", ")}`)},VS=(e,t)=>e.filter(r=>{let n=FS.exec(r);return n===null||t[n[1]]!==""}),WS=(e,t)=>{for(let r of e)for(let n of r.matchAll(Sl)){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})`)}},pn=(e,t)=>{let r=LS(e);US(r,t),BS(r,t);let n=VS(e.split(`
|
|
143
|
+
`),t);return WS(n,t),n.join(`
|
|
144
|
+
`).replace(Sl,(o,s)=>t[s])};var GS="name: TODO",El=e=>{let t=pn(dn["design/skeleton"],{packageName:e}),r=`name: ${e}`;return`${t.replace(GS,()=>r)}
|
|
145
|
+
`};var JS=(e,t)=>`${At}${e} ${t} -->`,KS="`README.md` \u2014 what this package is and how to run it.",Pl="docs/e2e-playwright.md",HS=`\`${Pl}\` at the repo root \u2014 env setup, run modes, \`E2E_SLOW_MO\`, traces after a failure.`,qS=["ts-check","eslint-check","test"],YS="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.",zS="Run `pnpm run build` before a dependent package can see a change.",zg=(e,t)=>e?.includes(t)??!0,XS=e=>{let t=qS.filter(r=>zg(e,r)).map(r=>`pnpm run ${r}`);return t.length===0?"":`\`${t.join(" && ")}\` \u2014 this package only.`},xl=e=>{let{version:t,type:r,packageName:n,relDir:o,hasReadme:s,hasE2eDoc:i,scripts:a,hasPublicSurface:c=!0}=e,l=pn(dn[`package/${r}`],{packageName:n,relDir:o,type:r,readmeBullet:s?KS:"",checksBullet:XS(a),...r==="e2e"?{e2eDocBullet:i?HS:""}:{},...r==="lib"?{surfaceBullet:c?YS:"",buildBullet:zg(a,"build")?zS:""}:{}});return[JS(t,r),"",l,""].join(`
|
|
146
|
+
`)};var ZS=e=>`${Er}${e} -->`,_o=e=>{let t=pn(dn["root/body"],{});return[ZS(e),"",t,""].join(`
|
|
147
|
+
`)};import mn from"node:fs";import QS from"node:path";var Vi=e=>{let t;try{t=mn.lstatSync(e)}catch{return}if(t.isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},No=(e,t)=>{let r=Mo(e,t);return r!=="unchanged"&&(mn.mkdirSync(QS.dirname(e),{recursive:!0}),mn.writeFileSync(e,t,"utf-8")),r},Mo=(e,t)=>{Vi(e);let r=mn.existsSync(e)?mn.readFileSync(e,"utf-8"):null;return r===t?"unchanged":r===null?"created":"updated"},Tl=(e,t,r)=>{let n=mn.readFileSync(e,"utf-8");if(!He(n,t,r))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Xg=(e,t,r)=>He(e,t,r)?{before:e.slice(0,e.indexOf(t)),after:e.slice(e.indexOf(r)+r.length)}:null,Cl=(e,t,r,n)=>{let o=Xg(e,r,n),s=Xg(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 Gi="<!-- infra-kit:import:begin -->",Ji="<!-- infra-kit:import:end -->",eE="AGENTS.md",Zg="CLAUDE.md",tE="README.md",$l="DESIGN.md",rE=["frontend","mobile"],nE=e=>Pr.existsSync(e)?Pr.readFileSync(e,"utf-8"):null,Al=(e,t)=>{try{return Pr.readdirSync(e).includes(t)}catch{return!1}},Wi=(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},Qg=({filePath:e,body:t,startMarker:r,endMarker:n,prepare:o,dryRun:s})=>{let i=nE(e),a=i===null?"":o?.(i)??i,c=cn({content:a,body:t,startMarker:r,endMarker:n,placement:"replace-in-place"});if(s)return Mo(e,c);let l=No(e,c);return Tl(e,r,n),i!==null&&Cl(a,c,r,n),l},oE=(e,t)=>{if(!Pr.existsSync(e))return"unchanged";Vi(e);let r=Pr.readFileSync(e,"utf-8"),n=Qt(r,xe,Me);return n===null?"unchanged":n.trim()===""?(t||Pr.rmSync(e),"removed"):t?Mo(e,n):No(e,n)},sE=(e,t,r)=>Qg({filePath:e,dryRun:r,body:_o(t),startMarker:xe,endMarker:Me,prepare:n=>Qt(n,Gi,Ji)??n}),jo=async(e,{version:t,dryRun:r=!1})=>{let n=er.join(e,Zg),o=er.join(e,eE),s=[];try{s.push({path:n,action:sE(n,t,r)})}catch(i){s.push(Wi(n,i))}try{s.push({path:o,action:oE(o,r)})}catch(i){s.push(Wi(o,i))}return s},iE=(e,t,r,n)=>{if(!rE.includes(r)||Al(e,$l))return null;let o=er.join(e,$l),s=El(t);try{return{path:o,action:n?Mo(o,s):No(o,s),type:r}}catch(i){return Wi(o,i,r)}},Ki=async(e,{repoRoot:t,version:r,declaredType:n})=>{let o=await Rr(e),s=o.name??er.basename(e),i=$o({packageDir:e,repoRoot:t,pkgJson:o,declaredType:n});return{body:xl({version:r,type:i,packageName:s,relDir:er.relative(t,e).split(er.sep).join("/"),hasReadme:Al(e,tE),hasDesign:Al(e,$l),hasE2eDoc:Pr.existsSync(er.join(t,Pl)),scripts:Object.keys(o.scripts??{}),hasPublicSurface:o.exports!==void 0||o.bin!==void 0}),type:i,packageName:s}},Fo=async(e,{repoRoot:t,version:r,design:n,declaredType:o,dryRun:s=!1})=>{let i=er.join(e,Zg),{body:a,type:c,packageName:l}=await Ki(e,{repoRoot:t,version:r,declaredType:o}),u=[];try{u.push({path:i,action:Qg({filePath:i,body:a,startMarker:qe,endMarker:it,dryRun:s}),type:c})}catch(p){u.push(Wi(i,p,c))}if(n){let p=iE(e,l,c,s);p&&u.push(p)}return u};import CE from"node:path";import eh from"node:path";var Ol="agent-guidance",Lo="CLAUDE.md",aE="\u2014 run: infra-kit audit --fix",cE={missing:`${Lo} missing`,"no-block":`${Lo} has no infra-kit block (expected ${qe} \u2026 ${it})`,malformed:`${Lo} block is malformed (end marker precedes start, or body is empty)`,"foreign-block":`${Lo} carries the ROOT infra-kit block (${xe}); a package needs the package block`},lE=e=>e.adopted?` (workspace adopted: ${eh.relative(e.workspaceRoot,e.evidencePath)} carries a package block)`:"",Dl=(e,t)=>{let r=Ot(gt(eh.join(e,Lo)));if(r.state==="ok"){let s=r.version??"unknown",i=r.type??"unknown";return{name:Ol,status:"pass",message:`present (block from infra-kit ${s}, type ${i})`}}let n=`${cE[r.state]} ${aE}`,o=r.state==="missing"?`${n}${lE(t)}`:n;return t.adopted?{name:Ol,status:"fail",message:o}:{name:Ol,status:"pass",message:`not yet adopted \u2014 ${o}`}};import uE from"node:path";var Il=async(e,t=mt)=>{try{let r=await Oo(e,t);return{check:{name:fe,status:"pass",message:"present and valid"},rules:r}}catch(r){return{check:{name:fe,status:"fail",message:r.message},rules:null}}},th="infra-kit.json",dE=async e=>await Ne(uE.join(e,fe))?{name:fe,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,_l=async(e,t=br)=>{let r=await dE(e),n=r?[r]:[];try{let{audit:o={}}=await V();return{checks:[{name:th,status:"pass",message:"present and valid"},...n],rules:Ao(o,t)}}catch(o){return{checks:[{name:th,status:"fail",message:o.message},...n],rules:null}}};import Hi from"node:fs/promises";import fn from"node:path";import{$ as pE}from"zx";var Bo="playwright.config.ts",mE=[{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')"}],rh=e=>Object.entries(wl).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"}}),fE="infra-kit-e2e",nh=async(e,t={})=>{let r=fn.join(e,Bo),n=await Hi.readFile(r,"utf-8").catch(()=>null);return n===null?[{name:`e2e-config:${Bo}`,status:"fail",message:`missing ${Bo}`}]:mE.map(o=>{let s=`e2e-config:${o.name}`;return t.staticServer&&o.name===fE?{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:`${Bo} lacks the shared e2e convention \u2014 expected: ${o.expected}`}})},gE=/['"`](?:[^'"`\n]*\/)?\.auth['"/`]/u,hE=/\.[cm]?[jt]sx?$/u,Nl=async(e,t)=>(await Hi.readdir(e,{recursive:t,withFileTypes:!0}).catch(()=>[])).filter(n=>n.isFile()&&hE.test(n.name)).map(n=>fn.join(n.parentPath,n.name)),yE=async e=>{let t=await Nl(fn.join(e,"src"),!0);for(let r of[fn.join(e,Bo),...t]){let n=await Hi.readFile(r,"utf-8").catch(()=>"");if(gE.test(n))return!0}return!1},oh=async e=>{let t="e2e-auth:gitignored";if(!await yE(e))return{name:t,status:"pass",message:"no saved auth state referenced"};let r=await pE({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}`}},Ml="E2E__BASIC_AUTH_USERNAME",jl="E2E__BASIC_AUTH_PASSWORD",vE=/\bE2E_\w*BASIC_AUTH_\w+/gu,wE=/_(?:USER(?:NAME)?|PASS(?:WORD)?)$/u,kE=/\/\*[\s\S]*?\*\//gu,bE=/(^|[^:])\/\/[^\n]*/gu,RE=e=>/USER(?:NAME)?$/u.test(e)?Ml:jl,SE=e=>e.replace(kE,"").replace(bE,"$1"),sh=async e=>{let t="e2e-env:basic-auth",r=[...await Nl(e,!1),...await Nl(fn.join(e,"src"),!0)],n=[];for(let o of r){let s=await Hi.readFile(o,"utf-8").catch(()=>""),i=new Set([...SE(s).matchAll(vE)].map(a=>a[0]).filter(a=>wE.test(a)&&a!==Ml&&a!==jl));for(let a of i)n.push(`${a} \u2192 ${RE(a)} (${fn.relative(e,o)})`)}return n.length===0?{name:t,status:"pass",message:`basic auth read only from ${Ml} / ${jl}`}:{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("; ")}`}},Fl=async(e,t,r={})=>[...rh(t),...await nh(e,r),await oh(e),await sh(e)];import EE from"node:fs/promises";import PE from"node:path";var Ll=async(e,t)=>Promise.all(t.map(async r=>{let n=await EE.stat(PE.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 Bl=(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 xE from"node:fs/promises";import TE from"node:path";var gn="turbo.json",Ul=async(e,t)=>{if(t.length===0)return[];let r;try{let o=await xE.readFile(TE.join(e,gn),"utf-8");r=JSON.parse(o)}catch(o){return[{name:gn,status:"fail",message:`cannot read/parse ${gn}: ${o.message}`}]}let n=r.tasks;return n===null||typeof n!="object"?[{name:gn,status:"fail",message:`no "tasks" object defined in ${gn}`}]: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 ${gn}`}})};var $E=async(e,t)=>{let{check:r,rules:n}=await Il(e,t);return{checks:[r],rules:n}},AE={adopted:!1,workspaceRoot:null},OE=async(e,t,r)=>$o({packageDir:e,repoRoot:r??e,pkgJson:t,declaredType:await $t(e)}),DE=async e=>(await ft(e).catch(()=>{}))?.e2e?.server==="static",Vl=async(e,t=mt,r={})=>{let n=await Rr(e),o=n.name??CE.basename(e),{checks:s,rules:i}=r.isRoot?await _l(e,t):await $E(e,t);r.isRoot||s.push(Dl(e,r.adoption??AE)),i&&(s.push(...Bl(n.scripts??{},i.requiredScripts)),s.push(...await Ll(e,i.requiredFiles)),s.push(...await Ul(e,i.turboTasks))),!r.isRoot&&await OE(e,n,r.repoRoot)==="e2e"&&s.push(...await Fl(e,n.scripts??{},{staticServer:await DE(e)}));let a=s.every(c=>c.status!=="fail");return{packageDir:e,packageName:o,checks:s,passed:a}};var Wl=["plugin","marketplace","add",zt],Gl=["plugin","install",X,"--scope","project"],ih=(e,t)=>kr({projectPath:e,home:t}).kind==="installed",qi=e=>((e??"").split(`
|
|
148
|
+
`).find(r=>r.trim().length>0)??"").trim(),IE=(e,t)=>{if(Po(t))return null;d.debug({msg:`Running: ${Eo} ${Wl.join(" ")}`});let r=e({args:Wl});return r.ok?null:{step:"marketplace",error:qi(r.output)}},_E=(e,t)=>{d.debug({msg:`Running: ${Eo} ${Ii.join(" ")}`});let r=e({args:Ii});if(!r.ok)return{status:"update-failed",error:qi(r.output)};d.debug({msg:`Running: ${Eo} ${Di.join(" ")}`});let n=e({args:Di,cwd:t});return n.ok?{status:"updated"}:{status:"update-failed",error:qi(n.output)}},Jl=e=>{let{projectRoot:t,home:r}=e,n=e.run??ol;if(!n({args:nl}).ok)return{status:"claude-missing"};if(ih(t,r))return e.cliIsStale?.()===!0?{status:"skipped-cli-stale"}:_E(n,t);let o=IE(n,r);if(o!==null)return{status:"failed",...o};d.debug({msg:`Running: ${Eo} ${Gl.join(" ")}`});let s=n({args:Gl,cwd:t});return s.ok?ih(t,r)?{status:"installed"}:{status:"unverified"}:{status:"failed",step:"install",error:qi(s.output)}};import NE from"node:fs";import ME from"node:path";var Ye=".mcp.json",ht="mcpServers",jE="infra-kit",FE=["mcp"],LE="/infra-kit/dist/mcp.js",Kl=" ",xr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ah=e=>{if(!xr(e))return!1;let{command:t,args:r}=e;return Array.isArray(r)?t===jE&&r[0]===FE[0]?!0:r.some(n=>typeof n=="string"&&n.endsWith(LE)):!1},ch=e=>/\n([ \t]+)"/.exec(e)?.[1]??Kl,Hl=e=>{try{return{kind:"raw",raw:NE.readFileSync(e,"utf-8")}}catch(t){return t.code==="ENOENT"?{kind:"absent"}:{kind:"unreadable",error:t}}},ql=e=>{try{return JSON.parse(e)}catch{return}},Yl=e=>e instanceof Error?e.message:String(e),hn=e=>{let t=Hl(ME.join(e,Ye));if(t.kind==="absent")return{kind:"missing-file"};if(t.kind==="unreadable")return{kind:"unparseable"};let r=ql(t.raw);if(!xr(r)||!xr(r[ht]))return{kind:"unparseable"};let n=r[ht];if(pe in n)return{kind:"stale"};let o=Object.keys(n).find(s=>ah(n[s]));return o===void 0?{kind:"absent"}:{kind:"wrong-key",key:o}};import Yi from"node:fs";import BE from"node:path";var Dt=`claude plugin install ${X} --scope project`,yn=`claude plugin marketplace update ${pe} && claude plugin update ${X} --scope project`,zl=`claude plugin marketplace add ${zt}`,dh=" ",ph=()=>({source:{source:"github",repo:zt}}),UE=()=>({extraKnownMarketplaces:{[pe]:ph()},enabledPlugins:{[X]:!0}}),mh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),VE=e=>/\n([ \t]+)"/.exec(e)?.[1]??dh,lh=(e,t,r,n)=>{let o=e[t];return o===void 0?(e[t]={[r]:n},`${t}.${r}`):!mh(o)||r in o?null:(o[r]=n,`${t}.${r}`)},uh=e=>[lh(e,"extraKnownMarketplaces",pe,ph()),lh(e,"enabledPlugins",X,!0)].filter(r=>r!==null),WE=e=>{try{return Yi.readFileSync(e,"utf-8")}catch{return null}},GE=e=>(Yi.mkdirSync(BE.dirname(e),{recursive:!0}),Yi.writeFileSync(e,`${JSON.stringify(UE(),null,dh)}
|
|
149
|
+
`,"utf-8"),{status:"created",path:e,added:[`extraKnownMarketplaces.${pe}`,`enabledPlugins.${X}`]}),Xl=(e,{write:t=!0}={})=>{let r=WE(e);if(r===null)return t?GE(e):{status:"withheld",path:e,added:uh({})};let n;try{n=JSON.parse(r)}catch{n=void 0}if(!mh(n))return d.warn(`Could not parse ${e} \u2014 left it untouched. Add "${X}" to enabledPlugins by hand, or fix the JSON and re-run: infra-kit setup --skip-tools`),{status:"unparseable",path:e,added:[]};let o=uh(n);if(o.length===0)return{status:"unchanged",path:e,added:[]};if(!t)return{status:"withheld",path:e,added:o};let s=VE(r),i=r.endsWith(`
|
|
150
150
|
`)?`
|
|
151
|
-
`:"";return
|
|
152
|
-
`,"utf-8")}return o},
|
|
151
|
+
`:"";return Yi.writeFileSync(e,`${JSON.stringify(n,null,s)}${i}`,"utf-8"),{status:"added",path:e,added:o}};var R=e=>[{type:"text",text:e}],T=e=>e;var JE="empty-rules",KE=["requiredScripts","requiredFiles"],fh=(e,t,r)=>KE.filter(n=>e[n]?.length===0).map(n=>({name:JE,status:"fail",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`})),gh=async(e,t)=>{try{if(t){let{audit:r={}}=await V();return fh(r,br,'infra-kit.json "audit"')}return fh(await ft(e)??{},mt,"infra-kit.config.ts")}catch{return[]}};import YE from"node:path";import zE from"node:process";import Zl from"node:fs/promises";import hh from"node:path";var HE="infra-kit.json",yh=["requiredScripts","requiredFiles","turbo"],Uo=(e,t)=>[{path:e,action:"failed",message:t}],qE=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vh=async e=>{let t=hh.join(e,fe),r=hh.join(e,HE),n;try{n=await ft(e)}catch(c){return Uo(t,c.message)}if(!n)return[];let o={...n},s=Object.keys(o).filter(c=>!yh.includes(c));if(s.length>0)return Uo(t,`declares ${s.join(", ")}, which mean nothing at the repo root \u2014 remove them, then re-run`);let i=Object.fromEntries(yh.filter(c=>o[c]!==void 0).map(c=>[c,o[c]])),a=[];if(Object.keys(i).length>0)try{let c=await Zl.stat(r),l=await Zl.readFile(r,"utf8"),u=JSON.parse(l);if(!qE(u))return Uo(r,"is not a JSON object");if("audit"in u)return Uo(r,`already has an "audit" block \u2014 merge ${fe}'s rules into it by hand, then delete ${fe}`);await sg({path:r,raw:l,migrated:{...u,audit:i},expectedMtimeMs:c.mtimeMs}),a.push({path:r,action:"updated"})}catch(c){return Uo(r,c.message)}try{await Zl.rm(t),a.push({path:t,action:"removed"})}catch(c){a.push({path:t,action:"failed",message:c.message})}return a};var XE=["unchanged","created"],ZE=["unchanged","created","updated","removed","failed"],wh=async(e,t,r)=>{let n=await $t(e);return Fo(e,{repoRoot:t,version:U.version,design:r,declaredType:n})},QE=async(e,t)=>{if(e.root)return[...await vh(t),...await jo(t,{version:U.version})];if(e.all){let n=[];for(let o of await Pe(t))n.push(...await wh(o,t,e.design));return n}let r=await Io(e.cwd??zE.cwd());return wh(r,t,e.design)},eP=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 ${ZE.filter(n=>XE.includes(n)||(t.get(n)??0)>0).map(n=>`${t.get(n)??0} ${n}`).join(", ")} (infra-kit ${U.version})`},tP=(e,t)=>{for(let r of e){if(r.action==="unchanged")continue;let n=YE.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(eP(e))},rP=e=>{let t={path:e.path,action:e.action};return e.type&&(t.type=e.type),t},kh=async(e,t)=>{let r=await $();Ui();let n=await un(t),o=await QE(e,r);tP(o,r),Ui();let s=await un(t),i=!e.all&&!e.root;return{fixed:o.map(rP),adoptionFlipped:i&&!n.adopted&&s.adopted}};import zi from"node:fs/promises";import Xi from"node:path";import nP from"yaml";var Vo="dependency-drift",Ql="@slip-stream-kit/",oP="infra-kit",sP=["dependencies","devDependencies","optionalDependencies"],Sh=e=>e.startsWith("workspace:")||e.startsWith("link:")||e.startsWith("file:"),tu=e=>e.startsWith("catalog:"),iP=(e,t,r)=>{if(!tu(e))return e;let n=e.slice(8);return n===""||n==="default"?t.default[r]:t.named[n]?.[r]},bh=e=>{let t=e.slice(Math.max(e.search(/\d/),0)).match(/^(\d+)\.(\d+)\.\d/);return t?[Number(t[1]),Number(t[2])]:null},aP=(e,t)=>{let r=bh(e),n=bh(t);return!r||!n?!1:r[0]<n[0]||r[0]===n[0]&&r[1]<n[1]},cP=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},eu=e=>e.map(t=>`${t.file} "${t.spec}"`).join(", "),lP=(e,t)=>[...cP(e)].flatMap(([r,n])=>{if(t.default[r]!==void 0){let o=n.filter(s=>!tu(s.spec));return o.length===0?[]:[{name:`${Vo}:catalog`,status:"fail",message:`${r} has a catalog entry (${t.default[r]}) but ${eu(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:`${Vo}:catalog`,status:"fail",message:`${r} is pinned at more than one range: ${eu(n)} \u2014 add one entry to the pnpm-workspace.yaml catalog, then run \`ik audit --fix --root\``}]}),uP=(e,t,r)=>{let n=new Map;for(let o of e){let s=iP(o.spec,t,o.name);s!==void 0&&aP(s,r)&&n.set(`${o.name}@${s}`,o.name)}return[...n.keys()].map(o=>({name:`${Vo}:lockstep`,status:"warn",message:`${o} is behind the infra-kit ${r} lockstep release \u2014 bump it to ^${r}`}))},dP=e=>{let t=e.filter(r=>r.name===oP);return t.length===0?[]:[{name:`${Vo}:infra-kit-pin`,status:"warn",message:`${eu(t)} \u2014 the repo runs the global infra-kit CLI; a local dependency is a second copy that can skew from it`}]},pP=(e,t,r)=>{let n=e.filter(i=>!Sh(i.spec)),o=n.filter(i=>i.name.startsWith(Ql)),s=[...lP(o,t),...uP(o,t,r),...dP(n)];return s.length>0?s:[{name:Vo,status:"pass",message:`no ${Ql}* or infra-kit dependency drift`}]},mP=async e=>{try{return JSON.parse(await zi.readFile(e,"utf-8"))}catch{return null}},fP=async e=>{try{let t=nP.parse(await zi.readFile(Xi.join(e,"pnpm-workspace.yaml"),"utf-8"))??{};return{default:t.catalog??{},named:t.catalogs??{}}}catch{return{default:{},named:{}}}},gP=async e=>{let t=await Pe(e).catch(()=>[]);return[e,...t].map(r=>Xi.join(r,"package.json"))},Rh=async e=>{let t=[];for(let r of await gP(e)){let n=await mP(r);if(!n)continue;let o=Xi.relative(e,r);for(let s of sP){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},hP=async(e,t,r)=>{let n=t.filter(s=>s.name.startsWith(Ql)&&!Sh(s.spec)&&!tu(s.spec)&&r.default[s.name]!==void 0),o=[...new Set(n.map(s=>s.file))];for(let s of o){let i=Xi.join(e,s),a=await zi.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 zi.writeFile(i,`${JSON.stringify(c,null,l)}
|
|
152
|
+
`,"utf-8")}return o},Eh=async(e,t,r=U.version)=>{let n=await fP(e),o=await Rh(e),s=t?await hP(e,o,n):[],i=s.length>0?await Rh(e):o;return{checks:pP(i,n,r),rewritten:s}};import xh from"node:path";var Zi="agent-guidance:drift",yP={root:"ik audit --fix --root",all:"ik audit --fix --all",package:"ik audit --fix"},Ph=(e,t)=>e.split(`
|
|
153
153
|
`).filter(r=>!r.startsWith(t)).join(`
|
|
154
|
-
`),
|
|
154
|
+
`),Th=({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=Bi(r,t,n);if(Ph(a,o)===Ph(c,o))return{name:Zi,status:"pass",message:`matches infra-kit ${s}`};let l=Sr(a,o),u=yP[i];return l!==null&&Ct(l,s)?{name:Zi,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&&Ct(s,l)?{name:Zi,status:"warn",message:`block from infra-kit ${l} differs from what infra-kit ${s} generates \u2014 run \`${u}\``}:{name:Zi,status:"warn",message:`block differs from what infra-kit ${s} generates (edited inside the markers?) \u2014 run \`${u}\``}},Ch=(e,t=U.version)=>{let r=gt(xh.join(e,"CLAUDE.md"));return r===null||!He(r,xe,Me)?null:Th({content:r,expectedBody:_o(t),startMarker:xe,endMarker:Me,versionPrefix:Er,current:t,scope:"root"})},$h=async(e,t,r,n=U.version)=>{let o=gt(xh.join(e,"CLAUDE.md"));if(o===null||Ot(o).state!=="ok")return null;let s;try{({body:s}=await Ki(e,{repoRoot:t,version:n,declaredType:await $t(e)}))}catch{return null}return Th({content:o,expectedBody:s,startMarker:qe,endMarker:it,versionPrefix:At,current:n,scope:r})};import Oh from"node:fs";import Dh from"node:path";var ru="ik-mcp",Ah=(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:ru,args:r}};var Qi="run `infra-kit setup` (or `infra-kit audit --root --fix`)",vP=(e,t)=>Array.isArray(e)&&e.length===t.length&&e.every((r,n)=>r===t[n]),nu=e=>xr(e)&&e.command===ru,wP=(e,t)=>({...e??{},type:t.type,command:t.command,args:t.args}),kP=(e,t,r)=>{let n=[],o={...e},s=!1;for(let[i,a]of Object.entries(t)){let c=Ah(i,a),l=e[i];if(l!==void 0&&!nu(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 ${Qi}, or drop mcp.${i} from infra-kit.json`});continue}if(nu(l)&&l.type===c.type&&vP(l.args,c.args)){n.push({name:i,status:"unchanged",message:""});continue}if(r){o[i]=wP(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: ${Qi}`:`"${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: ${Qi}`})}for(let[i,a]of Object.entries(e))Object.hasOwn(t,i)||!nu(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}},bP=(e,t,r)=>{let n=r===null?Kl:ch(r),o=r===null||r.endsWith(`
|
|
155
155
|
`)?`
|
|
156
|
-
`:"";try{return
|
|
156
|
+
`:"";try{return Oh.mkdirSync(Dh.dirname(e),{recursive:!0}),Oh.writeFileSync(e,`${JSON.stringify(t,null,n)}${o}`,"utf-8"),!0}catch(s){return d.warn(`Could not write ${e} (${Yl(s)}) \u2014 the ik-mcp entries were not updated.`),!1}},Wo=({projectRoot:e,proxies:t,write:r})=>{let n=Dh.join(e,Ye),o=Hl(n);if(o.kind==="unreadable")return d.warn(`Could not read ${n} (${Yl(o.error)}) \u2014 left it untouched.`),{status:"unreadable",path:n,entries:[],wrote:!1};let s=o.kind==="raw"?o.raw:null,i=s===null?{}:ql(s);if(!xr(i))return d.warn(`Could not parse ${n} \u2014 left it untouched. Fix the JSON, then ${Qi}.`),{status:"unparseable",path:n,entries:[],wrote:!1};let a=i[ht];if(a!==void 0&&!xr(a))return d.warn(`${n} has a "${ht}" that is not an object \u2014 left it untouched.`),{status:"unparseable",path:n,entries:[],wrote:!1};let c=kP(a??{},t,r);if(!c.changed)return{status:"ok",path:n,entries:c.entries,wrote:!1};let l=bP(n,{...i,[ht]:c.servers},s);return{status:l?"ok":"failed",path:n,entries:c.entries,wrote:l}};var Ih=async(e,t)=>{let r;try{r=(await V()).mcp}catch{return null}if(!r||Object.keys(r).length===0)return null;let n=Wo({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 RP="workspace adopted \u2014 every other package now needs a CLAUDE.md: run infra-kit audit --fix --all",SP=async e=>e.root?[{dir:await $(),baseline:br,isRoot:!0}]:e.all?(await Pe(await $())).map(r=>({dir:r})):[{dir:await Io(e.cwd??_h.cwd())}],EP=async e=>e.root||e.all?await $():e.cwd??_h.cwd(),PP=async()=>{try{return await $()}catch{return}},xP=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}},TP=async(e,t)=>{let{fixed:r,adoptionFlipped:n}=await kh(e,t);return n&&d.info(RP),r},CP=e=>{if(hn(e).kind!=="stale")return null;let t=`${Ye} still registers "${pe}" \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 "${pe}" 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}},$P=e=>e.root?"root":e.all?"all":"package",AP=async(e,t,r)=>{let n=await gh(e.dir,e.isRoot===!0);if(!e.isRoot){let a=await $h(e.dir,r??e.dir,$P(t));return a?[a,...n]:n}let o=Ch(e.dir),{checks:s,rewritten:i}=await Eh(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]},ea=async(e={})=>{let t=Rl(await EP(e)),r=e.fix?await TP(e,t):void 0,n=await SP(e),o=await un(t),s=await PP(),i=[];for(let u of n){let p=await Vl(u.dir,u.baseline,{adoption:o,isRoot:u.isRoot,repoRoot:s});p.checks.push(...await AP(u,e,s)),p.passed=p.checks.every(m=>m.status!=="fail"),i.push(p)}if(e.root){let u=await Ih(n[0].dir,e.fix===!0);u&&i.push(u);let p=CP(n[0].dir);p&&i.push(p)}let{allPassed:a,warnCount:c}=xP(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:R(JSON.stringify(l,null,2)),structuredContent:l}},OP={all:je.boolean().optional().describe("Audit every non-vendor workspace package"),root:je.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},DP={allPassed:je.boolean().describe("Whether every audited package passed all checks (warnings do not fail it)"),warnCount:je.number().int().describe("How many checks reported a warning"),packages:je.array(je.object({name:je.string(),passed:je.boolean(),checks:je.array(je.object({name:je.string(),status:je.enum(["pass","warn","fail"]),message:je.string()}))})).describe("Per-package check results")},ou=T({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:OP,outputSchema:DP,handler:e=>ea({all:e.all,root:e.root})});import{z as L}from"zod";import{$ as VP}from"zx";var su=1.959963984540054,IP=[/^co-authored-by:\s*claude\b/imu,/^claude-session:/imu],iu=/\b(?:fix(?:es|ed)?|hotfix|bugfix|regression)\b/iu,au=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lockb","CHANGELOG.md"],_P=/This reverts commit ([0-9a-f]{7,40})/u,Mh=/^Revert "(.*)"(?: \(#\d+\))?$/u,jh="",ta="",Fh=`--format=${jh}%H${ta}%ct${ta}%B${ta}`,Lh=e=>e.split(jh).filter(t=>t.trim()!=="").map(t=>{let[r="",n="0",o="",s=""]=t.split(ta),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:
|
|
161
|
-
`,420),
|
|
162
|
-
${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}}
|
|
163
|
-
`),
|
|
158
|
+
`).map(a=>a.trim()).filter(Boolean)}}),NP=e=>IP.some(t=>t.test(e.body))?"agent":"human",cu=e=>Mh.test(e.subject),MP=e=>!cu(e)&&iu.test(e.subject),jP=(e,t)=>{if(t===0)return null;let r=e/t,n=su*su,o=1+n/t,s=(r+n/(2*t))/o,i=su*Math.sqrt(r*(1-r)/t+n/(4*t*t))/o;return{low:Math.max(0,s-i),high:Math.min(1,s+i)}},ra=e=>Math.round(e*1e4)/1e4,Nh=(e,t)=>{let r=jP(e,t);return{hits:e,n:t,rate:t===0?null:ra(e/t),ci95:r&&{low:ra(r.low),high:ra(r.high)}}},FP=e=>{let t=new Set;for(let[r,n]of e.entries()){if(!cu(n))continue;let o=e.slice(0,r),s=_P.exec(n.body)?.[1],i=Mh.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},LP=(e,t)=>{let r=new Set(e.files.filter(n=>!au.includes(n.split("/").at(-1)??n)));return t.files.some(n=>r.has(n))},BP=(e,t,r)=>r.slice(t+1).some(n=>n.committedAt-e.committedAt<=259200&&MP(n)&&LP(e,n)),Bh=(e,t)=>{let r=FP(e),n=o=>{let s=e.map((u,p)=>({commit:u,position:p})).filter(({commit:u})=>o(NP(u))),i=s.filter(({commit:u})=>!cu(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})=>BP(u,p,e)).length;return{commits:s.length,reverts:s.length-i.length,changes:i.length,revertRate:Nh(c,i.length),followUpFixRate:Nh(l,a.length)}};return{agent:n(o=>o==="agent"),human:n(o=>o==="human"),total:n(()=>!0)}},lu=(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:ra(e.rate-t.rate),intervalsOverlap:e.ci95.low<=t.ci95.high&&t.ci95.low<=e.ci95.high}};var Go=90,WP=864e5,GP=async(e,t)=>{if(await $e(e,"HEAD")===null)return[];let r=`--since=${t}`,n=await VP({cwd:e,quiet:!0})`git log --no-merges --name-only ${r} ${Fh}`;return Lh(n.stdout).toReversed().sort((o,s)=>o.committedAt-s.committedAt)},Jh=async({cwd:e,sinceDays:t,nowMs:r})=>{let n=new Date(r-t*WP).toISOString(),o=await GP(e,n),s=Bh(o,Math.floor(r/1e3));return{repoRoot:e,sinceDays:t,from:n,until:new Date(r).toISOString(),classes:s,comparison:{minN:30,revertRate:lu(s.agent.revertRate,s.human.revertRate),followUpFixRate:lu(s.agent.followUpFixRate,s.human.followUpFixRate)},heuristics:{agentTrailers:["Co-Authored-By: Claude\u2026","Claude-Session:"],fixSubjectPattern:iu.source,followUpWindowHours:72,followUpIgnoredFiles:au,mergesExcluded:!0}}},na=e=>`${(e*100).toFixed(1)}%`,Uh=e=>e.rate===null||!e.ci95?"n/a (n=0)":`${na(e.rate)} (${e.hits}/${e.n}, 95% CI ${na(e.ci95.low)}\u2013${na(e.ci95.high)})`,uu=(e,t)=>[` ${e}: ${t.commits} commits (${t.reverts} reverts)`,` revert rate: ${Uh(t.revertRate)}`,` ${72}h follow-up-fix rate: ${Uh(t.followUpFixRate)}`].join(`
|
|
159
|
+
`),oa=async({since:e=Go})=>{let t=await Jh({cwd:await $(),sinceDays:e,nowMs:Date.now()}),{classes:r,comparison:n}=t;d.info(`Change stats for ${t.repoRoot} \u2014 last ${e} days (${t.from.slice(0,10)} \u2192 ${t.until.slice(0,10)}, merges excluded)`),d.info(uu("agent",r.agent)),d.info(uu("human",r.human)),d.info(uu("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 = ${na(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:R(JSON.stringify(t,null,2)),structuredContent:t}},Vh=L.object({hits:L.number().describe("Changes that hit the metric"),n:L.number().describe("Changes the rate is computed over"),rate:L.number().nullable().describe("hits / n, rounded to 4 places; null when n is 0"),ci95:L.object({low:L.number(),high:L.number()}).nullable().describe("Wilson 95% score interval; null when n is 0")}),du=L.object({commits:L.number().describe("Non-merge commits in range for this class"),reverts:L.number().describe("Of those, revert commits (excluded from both rate denominators)"),changes:L.number().describe("Non-revert commits \u2014 the revert-rate denominator"),revertRate:Vh.describe("Changes later reverted by an in-range commit"),followUpFixRate:Vh.describe("Changes at least 72h old followed within 72h by a fix-subject commit touching a shared file")}),Wh=L.object({suppressed:L.boolean().describe("True when either class has n below minN"),reason:L.string().nullable(),difference:L.number().nullable().describe("agent rate \u2212 human rate"),intervalsOverlap:L.boolean().nullable().describe("Whether the two Wilson intervals overlap")}),pu=T({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:L.number().int().positive().optional().describe(`Window in days, ending now (default ${Go})`)},outputSchema:{repoRoot:L.string().describe("git toplevel the stats were read from"),sinceDays:L.number(),from:L.string().describe("ISO start of the window"),until:L.string().describe("ISO end of the window (now)"),classes:L.object({agent:du,human:du,total:du}),comparison:L.object({minN:L.number(),revertRate:Wh,followUpFixRate:Wh}),heuristics:L.object({agentTrailers:L.array(L.string()),fixSubjectPattern:L.string(),followUpWindowHours:L.number(),followUpIgnoredFiles:L.array(L.string()),mergesExcluded:L.boolean()})},handler:oa});import{z as tr}from"zod";import mu from"node:fs/promises";import JP from"node:path";var vn=()=>Object.keys(ug.shape).filter(e=>e!=="$schema"&&e!=="configVersion"),KP=new Set(["protectedEnvs"]),wn={project:"per-project override",global:"user-global override"},Jo=(e,t)=>{if(ee()&&KP.has(e))throw new A({status:"refused",agentMode:_.source},2,{operation:t,remediation:`ask the human to run \`infra-kit ${t} ${e} \u2026\` in their own terminal`,stderrExcerpt:`"${e}" decides what an agent may reach, so an agent may not change it`});if(!vn().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: ${vn().join(", ")}.`)}},fu=e=>{try{return JSON.parse(e)}catch{return e}},HP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qP=async e=>{let t;try{t=await mu.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(!HP(r))throw new Error(`${w(e)} is not a JSON object \u2014 fix it with \`infra-kit config edit\`.`);return{raw:t,data:r}},YP=async(e,t)=>{t===null?await mu.rm(e,{force:!0}):ot(e,t,420),So()},Ko=async(e,t,r)=>{let n=await z(),o=e==="global"?n.userGlobal:n.userProject,{raw:s,data:i}=await qP(o),a=i[t],c=r({...i});if(c===null)return{file:o,previous:a,changed:!1};await mu.mkdir(JP.dirname(o),{recursive:!0}),ot(o,`${JSON.stringify(c,null,2)}
|
|
161
|
+
`,420),So();try{await V({autoMigrate:"off"})}catch(l){throw await YP(o,s),new Error(`${l.message}
|
|
162
|
+
${w(o)} was left unchanged.`)}return{file:o,previous:a,changed:!0}};var sa=async({key:e}={})=>{let[t,r]=await Promise.all([V(),z()]),n=t;if(e===void 0){let s=Object.keys(t).sort();d.info(`Merged config for ${r.projectName} \u2014 ${s.length} section(s): ${s.join(", ")}`),d.info(` source: ${r.main}`)}else{if(!vn().includes(e))throw new Error(`Unknown config key "${e}". Top-level keys: ${vn().join(", ")}.`);d.info(`${e} = ${JSON.stringify(n[e]??null,null,2)}`)}let o={config:n,configPath:r.main,projectName:r.projectName,...e===void 0?{}:{key:e,value:n[e]??null}};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},zP={config:tr.record(tr.string(),tr.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:tr.string().describe("Absolute path to the project-level infra-kit.json (the base layer / committed source of truth)."),key:tr.string().optional().describe("The top-level key asked for, when one was."),value:tr.unknown().optional().describe("The merged value of `key` (null when no layer sets it)."),projectName:tr.string().describe("Repository name the config is keyed to (the main-repo basename; shared across all worktrees of the repo).")},gu=T({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:tr.string().optional().describe("Report only this top-level key as `value` (e.g. `ide`).")},outputSchema:zP,handler:e=>sa(e)});import rx from"node:fs";import{z as ge}from"zod";import qo from"node:fs";import kn from"node:path";import XP from"node:process";var ZP=kn.join(".infra-kit","dev-context"),QP=".infra-kit",Kh=(e,t)=>{let r=kn.resolve(e);for(;;){let n=kn.join(r,t);if(qo.existsSync(n))return n;let o=kn.dirname(r);if(o===r)return;r=o}},ex=e=>{let t=Kh(e,ZP);if(t)return t;let r=Kh(e,QP);return r?kn.join(r,"dev-context"):void 0},hu=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Ho=e=>typeof e=="string"?e:"",tx=(e,t,r)=>{let n=kn.join(e,t);try{let o=qo.statSync(n),s=JSON.parse(qo.readFileSync(n,"utf-8"));if(typeof s!="object"||s===null)return null;let i=s;return{app:t.replace(/\.json$/,""),package:Ho(i.package),port:hu(i.port),alias:Ho(i.alias),origin:Ho(i.origin),release:Ho(i.release),env:Ho(i.env),pid:hu(i.pid),writtenAt:hu(i.writtenAt),mtimeMs:Math.round(o.mtimeMs),ageMs:Math.max(0,Math.round(r-o.mtimeMs))}}catch{return null}},Yo=(e=XP.cwd())=>{let t=Date.now(),r=ex(e);if(!r||!qo.existsSync(r))return{session:"none",fragmentDir:r,readAt:t,apps:[]};let n;try{n=qo.readdirSync(r).filter(s=>s.endsWith(".json"))}catch{return{session:"none",fragmentDir:r,readAt:t,apps:[]}}let o=n.map(s=>tx(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 ia=async(e={})=>{let t=e.now??Date.now,r=e.isListening??ko,n=Yo(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&&(rx.statSync(a,{throwIfNoEntry:!1})?.isDirectory()??!1),l=a===null?"nothing (no .infra-kit anchor exists up-tree)":a;if(i){d.info(`infra-kit dev: ${s.length} app(s) with a dev-context fragment in ${l}:`);for(let p of s){let m=p.live?"live":"NOT responding",f=`written ${p.ageSeconds}s ago`;d.info(` ${p.app} (${p.package}) \u2192 ${p.origin} on :${p.port} \u2014 ${m}, ${f}`)}}else{let p=c?"no readable fragment found there":"that directory does not exist";d.info(`No active infra-kit dev session \u2014 searched ${l} (${p}).`)}let u={active:i,apps:s,contextDir:a,contextDirExists:c};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}},nx={active:ge.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:ge.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:ge.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:ge.array(ge.object({app:ge.string().describe("App folder name (the fragment filename without .json)."),package:ge.string().describe("The app package name the vite helper reads to decide a local route."),port:ge.number().describe("The actual bound port the dev server is listening on."),pid:ge.number().describe("PID of the dev-server process that wrote the fragment (ownership / staleness metadata)."),alias:ge.string().describe("Registered portless hostname for the app."),origin:ge.string().describe("Authoritative local origin the vite helper proxies to for this app."),release:ge.string().describe("Release slug the runner recorded for this worktree."),env:ge.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:ge.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:ge.string().describe("ISO 8601 filesystem mtime of the fragment file \u2014 the AUTHORITATIVE freshness signal."),ageSeconds:ge.number().describe("Seconds since the fragment was last written on disk. A large value with live:false means a stale/abandoned fragment."),live:ge.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.")},yu=T({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:nx,handler:()=>ia()});import Oe from"node:fs";import i$ from"node:os";import Ze from"node:path";import ks from"node:process";import{z as Fe}from"zod";import{execFileSync as ox}from"node:child_process";var Hh=(e,t)=>{let r=e.filter(n=>!n.live).map(n=>n.name);return t?{prunable:[],withheld:r}:{prunable:r,withheld:[]}},sx=[/\binfra-kit\s+dev\b/,/cli\.js\s+dev\b/,/dev-server\.(?:js|ts)\b/],ix=e=>sx.some(t=>t.test(e)),ax="/bin/ps",cx=()=>ox(ax,["-eo","command="],{encoding:"utf8",maxBuffer:8<<20}).split(`
|
|
163
|
+
`),qh=(e=cx)=>{try{return e().some(ix)}catch{return!0}};import{Chalk as lx}from"chalk";import vu from"node:process";var wu={unicode:{ok:"\u2713",changed:"+",skipped:"-",manual:">",warn:"!",fail:"\u2717",separator:"\xB7",rule:"\u2500"},ascii:{ok:"ok",changed:"++",skipped:"--",manual:">>",warn:"!?",fail:"!!",separator:"-",rule:"-"}},ux=new Set(["warn","fail"]),dx=24,bn=" ",Yh=" ",px=(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:[""]},zh=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},mx=e=>{let t=new lx({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)}},Xh=(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),fx=(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=Xh(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}},gx=(e,t,r,n)=>{let o=fx(zh(e.rows),e.rows.length,t,r),s=Math.max(1,n-bn.length-e.label.length-o.plainWidth);return`${bn}${t.header(e.label)}${" ".repeat(s)}${o.text}`},hx=(e,t,r,n,o)=>{let s=ux.has(e.status),i=n.ok.length,a=e.name.padEnd(t),c=r[e.status],l=s?c(a):a,u=Yh.length+i+1+t+2,p=Math.max(dx,o-u),[m,...f]=px(e.message,p),h=" ".repeat(u),b=k=>s?k:r.dim(k);return[`${Yh}${c(n[e.status])} ${l} ${b(m??"")}`.trimEnd(),...f.map(k=>`${h}${b(k)}`),...(e.notes??[]).map(k=>`${h}${k}`.trimEnd())]},yx=(e,t,r,n,o)=>{let s=zh(t),i=n.rule.repeat(Math.max(12,Math.min(o-bn.length,56))),a=Xh(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[`${bn}${r.dim(i)}`,`${bn}${c}${l.join("")}`]},ku=(e,t={})=>{let r=t.width??80,n=mx(t.color??!1),o=t.unicode??!0?wu.unicode:wu.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,"",`${bn}${n.dim(e.emptyMessage??"Nothing ran.")}`];let c=Math.max(...i.map(u=>u.name.length)),l=s.flatMap(u=>[gx(u,n,o,r),...u.rows.flatMap(p=>hx(p,c,n,o,r)),""]);return[a,"",...l,...yx(e,i,n,o,r)]},vx=new Set(["","0","false","none"]),wx=["LC_ALL","LC_CTYPE","LANG"],kx=(e,t)=>e.NO_COLOR!==void 0&&e.NO_COLOR!==""?!1:e.FORCE_COLOR!==void 0?!vx.has(e.FORCE_COLOR.toLowerCase()):!!t.isTTY,bx=(e,t)=>{if(t)return!1;let r=wx.map(n=>e[n]).find(n=>n!==void 0&&n!=="");return r===void 0?!0:/UTF-?8/i.test(r)},bu=(e={})=>{let t=e.env??vu.env,r=e.stream??vu.stderr;return{color:kx(t,r),unicode:bx(t,e.ascii??!1),width:r.columns??80}},yt=(e,t={})=>{(t.write??(n=>{vu.stderr.write(n)}))(`${ku(e,bu(t)).join(`
|
|
164
164
|
`)}
|
|
165
|
-
`)};var
|
|
166
|
-
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:GP(t.slice(10))},wh=(e,t)=>{try{return e==="darwin"?VP(t):e==="linux"?JP(t):null}catch{return null}};import{Buffer as Fh}from"node:buffer";import Me from"node:fs/promises";import tt from"node:path";import Lh from"node:process";import{$ as qi}from"zx";import KP from"node:process";var Co=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var kh=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(X())throw new O({status:"argument_required",argument:e,agentMode:j.source},2,t);if(!KP.stdin.isTTY)throw new g(void 0,t)},qt=async e=>{kh("version");let{runBranchPicker:t}=await import("./boot-ST2534PA.js"),r=await t(e);if(r===null)throw new Co;return r},Yt=async(e,t)=>{kh("versions");let{runBranchMultiPicker:r}=await import("./boot-ST2534PA.js"),n=await r(e,t);if(n===null)throw new Co;return n};import{$ as Th}from"zx";import{$ as WV}from"zx";import{$ as cn}from"zx";import{$ as bh}from"zx";var zl=async e=>{let{operation:t}=e;try{await bh({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 bh({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"})}},qP=4,an=async e=>{let{operation:t}=e,r=await af();if(r.length===0)return;d.error(`working tree has uncommitted changes:
|
|
167
|
-
|
|
168
|
-
`)}`);let n=r.slice(0,qP),o=r.length-n.length,s=o>0?`${n.join(", ")} (+${o} more)`:n.join(", ");throw new g(void 0,{operation:t,remediation:"commit or stash your changes (`git stash -u`), then retry",stderrExcerpt:`working tree has uncommitted changes: ${s}`})},$o=async e=>{let{operation:t,base:r}=e;if(await Vr()===r)return;let n=(await st(await $())).find(o=>o.branch===r);if(n)throw new g(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},_e=async e=>{let{operation:t}=e;if(await lf())throw new g(void 0,{operation:t,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});await an({operation:t})};var YP=e=>e.map(t=>({pr:t,id:Q(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>sf(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),Ao=200,Rh=(e,t)=>{e.length<Ao||d.warn({source:t,limit:Ao},`\u26A0\uFE0F ${t} returned ${Ao} PRs \u2014 the page is full, so older release PRs may be missing`)},zP=async()=>{let[e,t]=await Promise.all([cn`gh pr list --limit ${Ao} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,cn`gh pr list --limit ${Ao} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),r=JSON.parse(e.stdout),n=JSON.parse(t.stdout);Rh(r,"release PR discovery (base dev)"),Rh(n,"hotfix PR discovery (base main)");let o=new Set(r.map(c=>c.headRefName)),s=new Set(n.filter(c=>o.has(c.headRefName)).map(c=>c.headRefName)),i=[...n,...r],a=new Set;return i.filter(c=>a.has(c.headRefName)?!1:(a.add(c.headRefName),!0)).map(c=>({...c,dualBase:s.has(c.headRefName)}))},Oo="find open release PRs",Sh=async()=>{try{let e=await zP();if(e.length===0)throw new g(void 0,{operation:Oo,remediation:"open a release PR first, or check you are in the right repo"});return YP(e)}catch(e){throw e instanceof g?e:(d.debug({err:e},"Error fetching release PRs"),new g(e,{operation:"fetch release PRs"}))}},Fi=async()=>(await Sh()).map(t=>t.headRefName),XP=e=>{let t=Do(e.baseRefName);if(t===null)throw new g(void 0,{operation:"classify release PRs",remediation:"discovery returned a PR outside the dev/main base set \u2014 this is an infra-kit bug, please report it",stderrExcerpt:`${e.headRefName} (#${e.number}) targets ${e.baseRefName}`});let r=Xl(e.title)!==t;return(r||e.dualBase)&&d.warn({branch:e.headRefName,title:e.title,baseRefName:e.baseRefName},e.dualBase?`\u26A0\uFE0F ${e.headRefName} has open PRs to both dev and main \u2014 treated as a hotfix (base main)`:`\u26A0\uFE0F ${e.headRefName} is titled "${e.title}" but targets ${e.baseRefName} \u2014 treated as ${t} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:t,titleMismatch:r,dualBase:e.dualBase}},G=async()=>(await Sh()).map(XP),Li=async e=>{let{branch:t,body:r}=e;try{await cn({quiet:!0})`gh pr edit ${t} --body ${r}`}catch(n){throw d.error({error:n,branch:t},`Error updating release PR body for ${t}`),n}},ZP=async(e,t)=>{let r=cn({quiet:!0,nothrow:!0}),n=await r`git ls-remote --heads origin ${e}`,o=n.exitCode!==0,s=n.stdout.trim().length>0;if(o||s){d.error({branchName:e},o?`could not reach origin to check whether ${e} was pushed \u2014 the branch is left in place; check with \`git ls-remote --heads origin ${e}\` before deleting anything`:`release branch ${e} exists on origin without a PR \u2014 left in place; delete it with \`git push origin --delete ${e}\` once you are sure`);return}await r`git switch ${t}`,(await r`git branch -D ${e}`).exitCode!==0&&d.error({branchName:e},`could not remove the local branch ${e} after a failed release \u2014 delete it with \`git branch -D ${e}\` before retrying`)},Bi=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=of(t,n),a=mt(n),c=cn({quiet:!0}),l=Te(t),u=Io(r,o);try{await an({operation:`create release branch ${l}`});let p=(await c`git rev-parse HEAD`).stdout.trim();if(p!==s)throw new g(void 0,{operation:`create release branch ${l}`,remediation:"something moved the checkout mid-run \u2014 re-run the release",stderrExcerpt:`expected to be on ${s.slice(0,8)} (${a}) but HEAD is ${p.slice(0,8)}`});await c`git checkout -b ${l}`;try{await c`git commit --allow-empty-message --allow-empty --message ''`,await c`git push -u origin ${l}`;let m=await c`gh pr create --title ${i} --body ${u} --base ${a} --head ${l}`;return{branchName:l,prUrl:m.stdout.trim()}}catch(m){throw await ZP(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await cn({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Zl}from"zx";var ln=async e=>{let t=await Zl`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Ql=async e=>{let t=await Zl`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Ui=async e=>{try{let t=await Zl`gh pr view ${e} --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)}catch(t){throw new g(t,{operation:`fetch PR #${e}`,remediation:`check it exists with \`gh pr view ${e}\``})}};import _o from"node:process";var QP="x-seraph-loginreason",ex="AUTHENTICATED_FAILED",tx=(e,t=160)=>{let r=e.split(`
|
|
169
|
-
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Ph=(e,t)=>t===ex||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Eh=(e,t)=>e==="auth"?`Jira rejected the credentials (HTTP ${t}) \u2014 check JIRA_EMAIL and JIRA_TOKEN; Atlassian API tokens expire`:e==="forbidden"?`Jira authenticated the account but refused the operation (HTTP ${t}) \u2014 the account lacks permission on this project`:e==="not-found-or-forbidden"?`Jira returned HTTP ${t}: either JIRA_PROJECT_ID does not exist, or these credentials cannot browse it, or the Authorization header was malformed and the request went out anonymous`:`Jira returned HTTP ${t}`,un=class extends Error{status;kind;body;context;constructor(t){let r=Ph(t.status,t.seraphLoginReason),n=tx(t.body);super(n===""?`${t.context}: ${Eh(r,t.status)}`:`${t.context}: ${Eh(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},No=e=>e instanceof un,xh=e=>e.headers.get(QP);var dn=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new un({status:e.status,seraphLoginReason:xh(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},wr=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,eu=async(e,t)=>{let{baseUrl:r,token:n,email:o,projectId:s}=t,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1,...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}},a=`${r}/rest/api/3/version`,c=btoa(`${o}:${n}`),l=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});return await dn(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},pn=async e=>{let{baseUrl:t,token:r,email:n,projectId:o}=e,s=`${t}/rest/api/3/project/${o}/versions`,i=btoa(`${n}:${r}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await dn(a,"Failed to get Jira project versions"),await a.json()},$t=async(e,t)=>(await pn(t)).find(o=>o.name===e)||null,mn=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.released!==void 0&&(s.released=e.released),e.archived!==void 0&&(s.archived=e.archived),e.releaseDate!==void 0&&(s.releaseDate=e.releaseDate),e.description!==void 0&&(s.description=e.description);let i=`${r}/rest/api/3/version/${e.versionId}`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await dn(c,"Failed to update Jira version");let l=await c.json();if(e.releaseDate===null&&(l.releaseDate||null)!==null)throw new Error(`Jira accepted the update (the write happened) but still reports releaseDate=${l.releaseDate}; the clear payload in updateJiraVersion needs revisiting`);return{success:!0,version:l}},tu=async(e,t)=>{let{versionName:r}=e,n=await $t(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await mn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},fn=async()=>{let e=_o.env.JIRA_BASE_URL,t=_o.env.JIRA_TOKEN||_o.env.JIRA_API_TOKEN,r=_o.env.JIRA_PROJECT_ID,n=_o.env.JIRA_EMAIL,o=[];if(e||o.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),t||o.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),r||o.push("JIRA_PROJECT_ID (numeric project ID)"),n||o.push("JIRA_EMAIL (your Jira email address)"),o.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...o.map(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
170
|
-
`);throw new Error(i)}let s=Number.parseInt(r,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${r}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:t,projectId:s,email:n}},At=async()=>{try{return await fn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Wi=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s=`${r}/rest/api/3/version/${e}/relatedIssueCounts`,i=btoa(`${o}:${n}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});await dn(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},ru=async(e,t)=>{let{baseUrl:r,token:n,email:o}=t,s={};e.moveFixIssuesTo!==void 0&&(s.moveFixIssuesTo=e.moveFixIssuesTo),e.moveAffectedIssuesTo!==void 0&&(s.moveAffectedIssuesTo=e.moveAffectedIssuesTo);let i=`${r}/rest/api/3/version/${e.versionId}/removeAndSwap`,a=btoa(`${o}:${n}`),c=await fetch(i,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});await dn(c,"Failed to remove Jira version")};var Ch="dev",$h={regular:"dev",hotfix:"main"},mt=e=>$h[e],Do=e=>{let t=Object.entries($h).find(([,r])=>r===e);return t?t[0]:null},Io=(e,t)=>(t??"").trim()!==""?`${e}
|
|
171
|
-
|
|
172
|
-
${t}`:`${e}
|
|
173
|
-
`,nu=async(e="regular")=>{let t=mt(e),r=Th({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 Th({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()},rx=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await $t(t,r);if(!s)return(await eu({name:t,projectId:r.projectId,description:n||"",released:!1,archived:!1,...o===void 0?{}:{releaseDate:o}},r)).version;if(s.released||s.archived)throw new g(void 0,{operation:`reuse Jira fix version "${t}"`,remediation:"pick a different version, or un-release it in Jira first",stderrExcerpt:`fix version "${t}" is already ${s.released?"released":"archived"}`});let i=n||"",a={...i!==""&&i!==(s.description??"")?{description:i}:{},...o!==void 0&&o!==(s.releaseDate??"")?{releaseDate:o}:{}};if(Object.keys(a).length===0)return s;let c=await mn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},ou=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=le(t),c=await rx({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=wr(r,c),u=await Bi({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:ne(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Vi=async()=>{let e=new Map,t=await At();if(!t)return e;try{let r=await pn(t);for(let n of r)e.set(n.name,{description:n.description||null,releaseDate:n.releaseDate||null})}catch(r){d.warn({err:r},"Jira descriptions unavailable \u2014 the release list will render without them. If this persists, check JIRA_EMAIL / JIRA_TOKEN.")}return e},me=async()=>{let e=await Vi();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Mo=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Xl=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Gi=e=>e.flatMap(t=>{let r=Q(t);return r?[{branch:t,id:r,label:ne(r)}]:[]}),Ot=e=>{try{return Te(ke(e))}catch(t){throw new g(t,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:t instanceof Error?t.message:String(t)})}},jo=e=>{if(e===Ch)return Ch;let t=Q(e);return t?ne(t):e},Dt=e=>e.flatMap(t=>{let r=Q(t);return r?[ne(r)]:[]}),nx=(e,t)=>t?t.get(e)||"regular":void 0,fe=e=>{let{branches:t,descriptions:r,types:n}=e;return Gi(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(le(s)),type:nx(o,n)}))};import Ah from"node:fs/promises";import ox from"node:path";import{$ as su}from"zx";var V="pnpm-lock.yaml",sx=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,Dh=async(e,t)=>{let r=ox.join(e,V),n=`${t}:${V}`;try{let o=await su({cwd:e,quiet:!0})`git show ${n}`;await Ah.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${V} to start from: ${Oh(o)}`}}try{await su({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${V}: ${Oh(o)}`}}return sx.test(await Ah.readFile(r,"utf8"))?{ok:!1,reason:`${V} still carries conflict markers after pnpm ran`}:(await su({cwd:e,quiet:!0})`git add -- ${V}`,{ok:!0})},Oh=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import{$ as kr}from"zx";var iu="Merge remote-tracking branch 'origin/dev' into ",ix=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},ax=2048,cx=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-ax)).filter(s=>s.length>0).join(`
|
|
174
|
-
`)||`the verify command exited with code ${n??"unknown"} and printed nothing`},lx=async e=>{try{return(await kr({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
|
|
175
|
-
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},ux=async(e,t)=>{let r=ix(t),n=await lx(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await mf(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},Ih=async e=>{let{cwd:t,worktreePath:r,branches:n}=e,o=[],s=await Ce(t,"origin/dev");if(!s)return n.map(i=>({branch:i,status:"error",reason:"origin/dev does not resolve"}));for(let i of n){let a=Date.now(),c=await dx({cwd:t,worktreePath:r,branch:i,devSha:s});o.push({...c,durationMs:Date.now()-a})}return o},dx=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o}=e,s=`origin/${n}`;if(!await Ce(t,s))return{branch:n,status:"error",reason:`${s} does not exist on origin`};if(await Qn(t,"origin/dev",s))return{branch:n,status:"up-to-date"};try{await Tc(r),await kr({cwd:r,quiet:!0})`git checkout --detach ${s}`;let i=`${iu}${n}`;await kr({cwd:r,quiet:!0})`git merge origin/dev --no-edit -m ${i}`;let a=(await kr({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:a===o?"fast-forward":"merged",mergeSha:a}}catch(i){return{branch:n,...await ux(r,i)}}finally{await Cc(r)}},Nh=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),_h="pnpm install --frozen-lockfile",Mh=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await Tc(t),await kr({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await kr({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,cx(a))}finally{await Cc(t)}return{kept:o,failed:s}},Fo=async(e,t,r="origin/dev")=>{await kr({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Qn(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import au from"node:process";var Ji=new Set,Ki=e=>(Ji.add(e),()=>{Ji.delete(e)}),px=async()=>{for(let e of[...Ji])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}Ji.clear()},mx=["SIGINT","SIGTERM"],jh=async(e,t={})=>{let{register:r=(i,a)=>{au.on(i,a)},unregister:n=(i,a)=>{au.off(i,a)},exit:o=i=>{au.exit(i)}}=t,s=new Map;for(let i of mx){let a=()=>{px().then(()=>{o(Of(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var fx="pnpm install --frozen-lockfile --ignore-scripts",cu="pnpm install --frozen-lockfile",Bh=64*1024,Jh=4096,Bo=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-Jh)},U=async(e,t)=>(await qi({cwd:e,quiet:!0})`git ${t}`).stdout,uu=e=>e.split(`
|
|
176
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),hn=e=>e.split("\0").filter(t=>t.length>0),br=async(e,t)=>{try{return(await U(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},Kh=async e=>tt.resolve(e,(await U(e,["rev-parse","--git-common-dir"])).trim()),du=e=>e.then(()=>!0,()=>!1),Lo=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),pu=e=>e?.length===1&&e[0]===V,Hh=async e=>tt.join(await Kh(e),"infra-kit","merge-dev-resolutions"),mu=async(e,t)=>tt.join(await Hh(e),`${df(t)}.json`),qh=async e=>{try{return JSON.parse(await Me.readFile(e,"utf8"))}catch{return null}},yn=async(e,t)=>{let r=await mu(e,t.branch);await Me.mkdir(tt.dirname(r),{recursive:!0}),await Me.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
177
|
-
`)},Yh=async e=>{let t=await Hh(e),r=await Me.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>qh(tt.join(t,o))))).filter(o=>o!==null)},zh=async e=>Promise.all((await Yh(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await du(Me.stat(t.worktreePath))}))),Uh=(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}),gx=e=>e.editablePaths??e.conflictPaths,hx=e=>tt.posix.basename(e)==="package.json",fu=e=>e.conflictPaths.includes(V)||e.lockfileBlob!==void 0,Xh=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(V);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=hn(await U(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await hu(e),...r].some(hx)},Zh=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",gu=async(e,t,r)=>{await U(e,["worktree","remove","--force",r]).catch(()=>Me.rm(r,{recursive:!0,force:!0})),await Me.rm(await mu(e,t),{force:!0}).catch(()=>{}),await U(e,["worktree","prune"]).catch(()=>{})},Qh=async e=>hn(await U(e,["diff","--name-only","-z","--diff-filter=U"])),Hi=async e=>hn(await U(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),yx=async(e,t)=>{let r=(await U(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await du(Me.stat(tt.join(await Kh(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(uu(await U(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},ey=e=>e.split("/").includes("node_modules"),Yi=async(e,t)=>{let r=new Set(gx(t));t.editablePaths&&await Xh(e,t)&&r.add(V);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=hn(await U(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await hu(e),...o].filter(a=>!r.has(a)),i=(await Hi(e)).filter(a=>!n.has(a)&&!ey(a));return[...new Set([...s,...i,...await vx(e)])].sort()},hu=async e=>{let t=hn(await U(e,["status","--porcelain","-z","--untracked-files=all"])),r=[],n=!1;for(let o of t){if(n){n=!1;continue}let[s,i]=o;i!==" "&&r.push(o.slice(3)),n=s==="R"||s==="C"}return r},vx=async e=>(await U(e,["ls-files","-v"])).split(`
|
|
178
|
-
`).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),wx=async(e,t)=>{let r=`:(exclude)${V}`;try{return await U(e,["diff","--cached","--check",t,"--",".",r]),[]}catch(n){let{stdout:o="",stderr:s="",exitCode:i}=n;if(s.trim().length>0||o.trim().length===0||i!==1&&i!==2)throw new g(n,{operation:"check the staged resolution for conflict markers"});let a=new Set;for(let c of o.split(`
|
|
179
|
-
`)){let l=/^(.*):\d+: leftover conflict marker/.exec(c);l?.[1]&&a.add(l[1])}return[...a].sort()}},kx=async(e,t)=>{let r=[];for(let n of t)(await du(Me.lstat(tt.join(e,n)))||(await U(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await U(e,["--literal-pathspecs","add","-A","--",...r])},lu=async e=>(await U(e,["write-tree"])).trim(),ty=async e=>(await U(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),bx=e=>{let t=`${cu} && `;if(e!==cu)return e?.startsWith(t)?e.slice(t.length):e},Rx=e=>e?`${cu} && ${e}`:fx,Sx=async(e,t)=>{try{return await qi({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:Bo(r)}}},ry=async(e,t)=>{let r=(await U(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await U(e,["diff","--cached","--stat",l,"--",V])).trim(),o=fu(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await U(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${V}`]),i=new Set(t.rererePreResolved),a=s.split(/^(?=diff --git )/m).map(l=>{let u=/^diff --git a\/(.*) b\//.exec(l)?.[1];return u&&i.has(u)?`# rerere (recorded resolution)
|
|
180
|
-
${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?Fh.from(a).subarray(0,Bh).toString():a,resolutionDiffTruncated:c}},ny=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 Wh(t,a,o,"conflict"));for(let a of n)i.set(a,await Wh(t,a,o,"verify-failed",s));return i},Ex=async(e,t,r)=>{let n=async(a,c)=>hn(await U(e,["diff","--name-only","-z","--no-renames",`${a}...${c}`])),o=await n(t,r),s=await n(r,t);return{editablePaths:[...new Set([...o,...s])].filter(a=>a!==V).sort(),lockfileBothSides:o.includes(V)&&s.includes(V)}},Px=async(e,t,r,n)=>{let o=await Qh(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await br(e,"HEAD"),a=await br(e,"MERGE_HEAD");return i!==r||a!==n?{reason:"the merge no longer reproduces (already up to date?) \u2014 re-run release merge-dev"}:{conflictPaths:[],...await Ex(e,r,n),autoMergeTree:await lu(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await br(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await yx(e,o),lockfileOnly:pu(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await U(e,["--version"])).trim()})`}},xx={conflict:"needs-agent","verify-failed":"verify-failed"},Wh=async(e,t,r,n,o)=>{let s=await qh(await mu(e,t));if(s)return{resolution:Uh(s,"exists"),reason:`resolution-exists: ${s.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let i=await Ce(e,`origin/${t}`);if(!i)return{reason:`origin/${t} does not exist on origin`};let a=pf(e,t),c=()=>gu(e,t,a),l=Ki(c);try{await U(e,["worktree","prune"]),await Me.mkdir(tt.dirname(a),{recursive:!0}),await U(e,["worktree","add","--detach",a,i]),await qi({cwd:a,quiet:!0})`git merge --no-commit ${r} -m ${iu+t}`.catch(()=>{});let u=await Px(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 Hi(a),cliVersion:L.version,createdAt:new Date().toISOString()};return await yn(e,p),{resolution:Uh(p,p.lockfileOnly?"lockfile-only":xx[n])}}catch(u){return await c(),{reason:Bo(u)}}finally{l()}},oy=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Yh(t),s=o.map(a=>a.branch);if(r!==void 0)return(Array.isArray(r)?r:r.split(",")).map(c=>c.trim()).filter(c=>c.length>0).map(c=>{let l=Te(ke(c)),u=o.find(p=>p.branch===l);if(!u)throw new g(void 0,{operation:`select the resolution for "${c}"`,stderrExcerpt:`${l} has no resolution in progress`,remediation:s.length>0?`pass one of: ${s.join(", ")}`:"start one with release merge-dev --keep-conflicts"});return u});if(n||o.length===0)return o;let i=await Yt(fe({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},Tx=async(e,t)=>{let r=await Me.realpath(t).catch(()=>null);if(!r)return!1;let n=await st(e);for(let o of n)if(await Me.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},gn=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),sy=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 Tx(e,n))return gn(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await br(n,"HEAD"),i=await br(n,"MERGE_HEAD"),a=r??bx(t.handOffVerify);return s===t.baseSha&&i===t.devSha?Dx(e,t,o,a):Cx(t,o,s,i)},Cx=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return gn(t,"tree-changed",`commit ${r} carries a tree a commit hook rewrote after approval \u2014 run --abort, then hand off again`);let s=n?[]:await ty(o),i=n?null:await br(o,"HEAD^{tree}");if(!(s.length===2&&s[0]===e.baseSha&&s[1]===e.devSha&&i!==null&&i===e.previewedTree)||!r||!i){let l=n?`HEAD ${r??"none"} merging ${n}`:`HEAD ${r??"none"}`;return gn(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await Yi(o,e);return c.length>0?gn(t,"out-of-scope-edit",Zh(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:fu(e),...await ry(o,e)}},Vh=async(e,t)=>{let r=uu(await U(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},$x=async(e,t)=>{let r=t.worktreePath,n=await Vh(r,V),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await br(r,`${t.autoMergeTree}:${V}`),i=await Dh(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[V]};let a=await Vh(r,V);if(a!==null&&a!==o&&(t.lockfileBlob=a,await yn(e,t)),n!==null&&n!==a&&!s)return n===o?{code:"tree-changed",detail:`rebuilding ${V} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[V]}:{code:"out-of-scope-edit",detail:`${V} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[V]};let c=await Yi(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},Ax=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await hu(r)).filter(c=>n.has(c)):t.conflictPaths;await kx(r,o.filter(c=>c!==V));let s=await Yi(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:Zh(t),paths:s};let i=(await Qh(r)).filter(c=>c!==V);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await wx(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${Bo(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await Xh(r,t)?$x(e,t):null},Ox=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 Hi(o)),i=await Sx(o,n),a=(await Hi(o)).filter(c=>!s.has(c)&&!ey(c)&&tt.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await yn(e,t),i},Dx=async(e,t,r,n)=>{let o=t.worktreePath,s=await Ax(e,t);if(s)return{...r,blocked:s};let i=fu(t),a=await lu(o),c=await Ox(e,t,a,Rx(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return gn(l,"verify-failed",c.reason??"the verify command failed");let u=await Yi(o,t),p=uu(await U(o,["diff","--name-only"]));return u.length>0||p.length>0||await lu(o)!==a?gn(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await yn(e,t)),{...l,...await ry(o,t)})},Ix=12e4,Nx=async(e,t=Ix)=>{let r=qi({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...Lh.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&Lh.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:Bo(s)};let i=(await U(e,["rev-parse","--git-path","index.lock"])).trim();return await Me.rm(tt.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},_x={"verify-failed":"verify-failed","tree-changed":"tree-changed"},Mx=e=>{let t=e.blocked;return{branch:e.branch,status:_x[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},jx=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 Nx(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await U(o,["rev-parse","HEAD"])).trim(),c=(await U(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await yn(e,r),s("tree-changed",`a commit hook rewrote the tree (${c}, approved ${t.treeSha}) \u2014 run --abort, then hand off again`,{mergeSha:a});let l=await ty(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}},Fx=async(e,t,r)=>{let n=(c,l,u)=>({branch:t.branch,status:c,mergeSha:r,conflictPaths:t.conflictPaths,pushed:!1,...l?{reason:l}:{},...u?{blocked:u}:{}}),o;try{o=(await Fo(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${Bo(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await Ce(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Qn(e,s,t.baseSha),a={code:"parents-mismatch",detail:`origin/${t.branch} ${i?"was rewound":"moved"} to ${s??"nothing"} since the hand-off at ${t.baseSha}`};return n("blocked",`parents-mismatch: ${a.detail}`,a)},Lx=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}`)},iy=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await oy({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Lo();if(i)return Gh(t,a,o,s);let c=[];for(let m of a){let f=await sy(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await yn(t,m)),c.push(f)}Lx(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new O({status:"refused",plan:l,agentMode:j.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await J(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,throwOnDecline:!0,rerun:Bx(p)})}catch(m){if(!Et(m))throw m;return{...Lo(),declined:!0}}return Gh(t,a,o,p)},ay=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},Bx=e=>{let t=[],r=!1;for(let o of Tf())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"]},Ux=async(e,t,r,n)=>{let o=await sy(e,t,r);if(o.blocked)return Mx(o);let s=await jx(e,o,t,n);if(!("sha"in s))return s;let i=await Fx(e,t,s.sha);return i==="keep"?s:i},Wx=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 si(e,r),o=[];for(let s of t){let i=n.pushed||await Gr(e,s.record.branch)===s.sha;o.push({branch:s.record.branch,status:i?"merged":"push-aborted",mergeSha:s.sha,conflictPaths:s.record.conflictPaths,pushed:i,...i?{}:{reason:n.stderr?.trim().slice(-Jh)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
|
|
183
|
-
`)[0]}}},Gh=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await Ux(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await Wx(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 gu(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}},cy=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await oy({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Lo();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await J(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i,throwOnDecline:!0})}catch(a){if(!Et(a))throw a;return{...Lo(),declined:!0}}for(let a of s)await gu(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Lo(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};import Vx from"node:fs";import Gx from"node:os";import Jx from"node:path";var Kx="infra-kit.json",Hx="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)",qx="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Uo=async()=>{let e;try{e=await $()}catch{return null}let t=e.trim();return t===""||t===Gx.homedir()?null:t},ly=async()=>{let e=await Uo();return e===null&&d.info(Hx),e},Yx=async()=>{let e=await Uo();return e===null?null:Vx.existsSync(Jx.join(e,Kx))?e:(d.info(qx),null)};var zx=async e=>{try{return await Re(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},uy=async({dryRun:e=!1}={})=>{let t=await Yx(),r=L.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await ho(t,{version:r,dryRun:e})];for(let o of await zx(t)){let s=await Pt(o);n.push(...await yo(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};import ye from"node:fs";import ra from"node:os";import ie from"node:path";import Tu from"node:process";import yu from"node:fs";import dy from"node:os";import py from"node:path";import Xx from"node:process";import{z as Xi}from"zod";var my=e=>{try{return yu.readFileSync(e,"utf-8")}catch{return null}},vn="claude in chrome",Zx="com.anthropic.claude_code_browser_extension",zi="run `/chrome` inside Claude Code to set up Claude in Chrome",Qx={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},eT=e=>{try{return yu.accessSync(e,yu.constants.X_OK),!0}catch{return!1}},fy=e=>{try{return JSON.parse(e)}catch{return null}},tT=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Wo=(e={})=>{let t=e.platform??Xx.platform,r=e.home??dy.homedir(),n=e.readText??my,o=e.isExecutable??eT,s=Qx[t];if(s===void 0)return{name:vn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=py.join(r,...s,`${Zx}.json`),a=n(i);if(a===null)return{name:vn,status:"warn",message:`Chrome native host not registered \u2014 ${zi}`};let c=Xi.object({path:Xi.string().min(1)}).safeParse(fy(a));if(!c.success)return{name:vn,status:"fail",message:`${w(i)} has no host path \u2014 ${zi} again`};let l=c.data.path;if(!o(l))return{name:vn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${zi} again`};let u=tT.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:vn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${zi} again`}:{name:vn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},vu=(e={})=>{let t=e.home??dy.homedir(),r=e.readText??my,n=Xi.object({claudeInChromeDefaultEnabled:Xi.boolean().optional()}).safeParse(fy(r(py.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import Qi from"node:fs/promises";import rT from"node:path";import nT from"node:process";var gy=` // // Editor tooling only \u2014 a JSON Schema URL for completion and validation. Ignored at runtime.
|
|
165
|
+
`)};var Rx="Tools & CLIs",Sx="Shell & integration",Ex="Project config",Px="Doppler env tokens",xx="Dev proxy (portless)",Tx="Claude Code plugin",Cx=`portless serving TLS on :${qt}`,Ru=[[Rx,["brew installed","git installed","gh installed","gh authenticated","doppler installed","aws installed","package manager installed","typescript-language-server installed","orca installed"]],[Sx,["zshrc init block","zshenv session block","pnpm enableGlobalVirtualStore","CLAUDE.md block","Guidance version"]],[Ex,["infra-kit config valid","user override path","legacy user-global config","merge-dev resolutions"]],[Px,["tokens.json present","env tokens configured","tokens.json perms"]],[xx,["portless installed","portless node","portless service target",Cx,"portless CA chain valid","portless CA trusted","portless routes"]],[Tx,["claude CLI","marketplace registered","plugin installed","plugin version","plugin MCP server","CLI version","background setup","claude in chrome","Agent mode","Agent allowlist"]]],Zh="Other",$x=Ru.map(([e])=>e),Ax=new Map(Ru.flatMap(([e,t])=>t.map(r=>[r,e]))),YG=Ru.flatMap(([,e])=>e),Su=new Set(["portless routes","tokens.json perms"]),Ox=e=>{let t=new Map;for(let n of e){let o=Ax.get(n.name)??Zh,s=t.get(o);s?s.push(n):t.set(o,[n])}return[...$x,Zh].flatMap(n=>{let o=t.get(n);return o&&o.length>0?[{label:n,checks:o}]:[]})};var Dx=e=>{switch(e){case"pass":return"ok";case"fail":return"fail";case"warn":return"warn";case"skip":return"skipped";default:return Je(e)}},Ix=e=>{let t=e.filter(r=>r.status==="fail"&&Su.has(r.name)).length;return{title:"infra-kit doctor",emptyMessage:"No checks ran.",sections:Ox(e).map(r=>({label:r.label,rows:r.checks.map(n=>({name:n.name,status:Dx(n.status),message:n.message}))})),hints:t>0?[`${t} fixable \u2014 run \`infra-kit doctor --fix\``]:[]}};var Eu=(e,t={})=>{yt(Ix(e),t)};import{spawnSync as sy}from"node:child_process";import aa from"node:fs";import Hx from"node:os";import ca from"node:path";import zo from"node:process";import{z as ry}from"zod";import _x from"node:fs";import Nx from"node:os";import Mx from"node:path";var jx="infra-kit.json",Fx="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)",Lx="Skipped agent-instruction files \u2014 no infra-kit.json at the repo root (the plugin pointer, the plugin install and .mcp.json are unaffected)",Rn=async()=>{let e;try{e=await $()}catch{return null}let t=e.trim();return t===""||t===Nx.homedir()?null:t},Qh=async()=>{let e=await Rn();return e===null&&d.info(Fx),e},Bx=async()=>{let e=await Rn();return e===null?null:_x.existsSync(Mx.join(e,jx))?e:(d.info(Lx),null)};var Ux=async e=>{try{return await Pe(e)}catch(t){return d.debug({err:t,msg:"Skipped per-package agent guidance \u2014 no workspace packages could be discovered."}),[]}},ey=async({dryRun:e=!1}={})=>{let t=await Bx(),r=U.version;if(t===null)return{skipped:!0,root:null,version:r,written:[]};let n=[...await jo(t,{version:r,dryRun:e})];for(let o of await Ux(t)){let s=await $t(o);n.push(...await Fo(o,{repoRoot:t,version:r,declaredType:s,dryRun:e}))}return{skipped:!1,root:t,version:r,written:n}};var Vx=e=>e.replace(/'/g,"'").replace(/"/g,'"').replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&"),Wx=e=>[...e.matchAll(/<string>([\s\S]*?)<\/string>/g)].map(t=>Vx(t[1])),Gx=e=>{let t=e.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/);return t===null?null:Wx(t[1])},Jx=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},Kx=e=>{let t=e.split(`
|
|
166
|
+
`).find(r=>r.startsWith("ExecStart="));return t===void 0?null:Jx(t.slice(10))},ty=(e,t)=>{try{return e==="darwin"?Gx(t):e==="linux"?Kx(t):null}catch{return null}};var It="portless service target",Zo=e=>({name:It,status:"warn",message:e}),iy=e=>e==="darwin"?Of:e==="linux"?Df:null,qx=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Af}`:`sudo systemctl restart ${If}`,Yx="/bin/ps",zx=e=>{try{let t=sy(Yx,["-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}},ny=e=>{try{return aa.readFileSync(e,"utf-8")}catch{return null}},Xx=e=>{try{return aa.statSync(e).mtime}catch{return null}},Zx=2e3,Qx=e=>{try{let t=sy(e,["-p","process.version"],{encoding:"utf-8",timeout:Zx}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},eT=(e,t)=>({platform:e.platform??zo.platform,readServiceFile:e.readServiceFile??ny,readFile:e.readFile??ny,exists:e.exists??aa.existsSync,realpath:e.realpath??be,mtime:e.mtime??Xx,execPath:e.execPath??zo.execPath,home:e.home??Hx.homedir(),cwd:e.cwd??zo.cwd(),repoRoot:e.repoRoot??Rn,stateDir:(e.stateDir??Nf)(),processStartTime:e.processStartTime??zx,version:e.version??zo.version,arch:e.arch??zo.arch,nodeVersionOf:e.nodeVersionOf??Qx,isGlobal:e.isGlobal??xi().node.isGlobal,nodeFs:e.nodeFs??aa,stableNode:null,stableNodeSidecar:null,bin:t}),Sn="portless node",Tr="~/.infra-kit/node",Xo=e=>({row:{name:Sn,status:"fail",message:e},stableNode:null,sidecar:null}),oy=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},tT=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,rT=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,nT=e=>{let t=Bf(e.home),r=oy(e.nodeFs.lstatSync,t);if(r===void 0)return Xo(`${Tr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return Xo(`${Tr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Uf(e.home,e.nodeFs);if(n===null)return Xo(`${Tr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=oy(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 Xo(`${Tr} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!rT(c,e))return Xo(`${Tr} does not run as Node ${e.version} (${tT(c)}). Re-run through the current Node: \`${Tt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:Sn,status:"pass",message:`${Tr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},oT=e=>{if(iy(e.platform)===null)return{row:{name:Sn,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=nT(e);return e.isGlobal()?t:{...t,row:{name:Sn,status:"skip",message:`not a global install; the global infra-kit keeps ${Tr} current`}}},Pu=(e,t)=>{let r=eT(e,t),n=oT(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},sT=(e,t)=>{let r=t.readFile(ca.join(e,"package.json"));try{let n=r===null?null:ry.object({version:ry.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},iT=e=>{let t=Number.parseInt(e.readFile(ca.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},aT=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},cT=(e,t,r)=>{let n=iT(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(aT(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ca.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},lT=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:rn(await t.repoRoot()??r,e,t.realpath)},Cr=e=>({state:"drifted",row:e}),uT=async(e,t,r)=>{let n=Tt(r.bin,r);if(!r.exists(e))return Cr({name:It,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=ca.join(Zc(r.home),"dist","cli.js");if(t!==o)return Cr(Zo(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Pi(r.home,r.exists)===null)return Cr({name:It,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(Zc(r.home));if(await lT(s,r))return Cr({name:It,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=dT(e,n,r);if(i!==null)return i;let a=sT(s,r),c=cT(s,a,r);return c!==null?{state:"converged",row:Zo(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${qx(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:It,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},dT=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Cr(Zo(`The service runs \`${e}\`, a path its package manager will remove. Re-run once to switch it to the stable node: \`${t}\``)):r.realpath(e)===r.realpath(r.execPath)?null:Cr(Zo(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),xu=async e=>{let t=iy(e.platform);if(t===null)return{state:"absent",row:{name:It,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:It,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=ty(e.platform,r)??[];return n===void 0||o===void 0?Cr(Zo(`could not parse ${t} \u2014 re-run \`${Tt(e.bin,e)}\` to rewrite it.`)):uT(n,o,e)},ay=async(e,t)=>{let{seams:r}=Pu(e,t);return{state:(await xu(r)).state,stableNode:r.stableNode}};import la from"node:fs";import En from"node:path";var cy="auto-setup.json",pT="auto-setup.log",mT="auto-setup.lock",ly="auto-setup.notified",fT=3,gT=3600*1e3,hT=()=>En.join(xt(),cy),Pn=()=>En.join(xt(),pT),uy=()=>En.join(xt(),mT),yT=()=>En.join(xt(),ly),vT=new Set(["ok","attention","failed"]),wT=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"&&vT.has(r)&&Array.isArray(n)&&n.every(o=>typeof o=="string")},kT=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(wT)},xn=(e=t=>la.readFileSync(t,"utf8"))=>{try{let t=JSON.parse(e(hT()));return kT(t)?t:null}catch{return null}},dy=e=>{let t=xt();la.mkdirSync(t,{recursive:!0}),ot(En.join(t,cy),JSON.stringify(e),384)},bT=e=>e.finishedMs===null||e.runs.some(t=>t.status==="failed"),py=(e=t=>la.readFileSync(t,"utf8"))=>{try{let t=Number(e(yT()).trim());return Number.isFinite(t)?t:null}catch{return null}},my=e=>{let t=xt();la.mkdirSync(t,{recursive:!0}),ot(En.join(t,ly),String(e),384)},fy=(e,t,r)=>{if(e===null)return!0;let n=r-e.startedMs;return n>=0&&n<gT?!1:e.version!==t?!0:bT(e)&&e.attempts<fT};import Tu from"node:fs";import gy from"node:os";import hy from"node:path";import RT from"node:process";import{z as da}from"zod";var yy=e=>{try{return Tu.readFileSync(e,"utf-8")}catch{return null}},Tn="claude in chrome",ST="com.anthropic.claude_code_browser_extension",ua="run `/chrome` inside Claude Code to set up Claude in Chrome",ET={darwin:["Library","Application Support","Google","Chrome","NativeMessagingHosts"],linux:[".config","google-chrome","NativeMessagingHosts"]},PT=e=>{try{return Tu.accessSync(e,Tu.constants.X_OK),!0}catch{return!1}},vy=e=>{try{return JSON.parse(e)}catch{return null}},xT=/^exec\s+(?<target>\S+)\s+--chrome-native-host\b/m,Qo=(e={})=>{let t=e.platform??RT.platform,r=e.home??gy.homedir(),n=e.readText??yy,o=e.isExecutable??PT,s=ET[t];if(s===void 0)return{name:Tn,status:"skip",message:`no Chrome native host location known for ${t}`};let i=hy.join(r,...s,`${ST}.json`),a=n(i);if(a===null)return{name:Tn,status:"warn",message:`Chrome native host not registered \u2014 ${ua}`};let c=da.object({path:da.string().min(1)}).safeParse(vy(a));if(!c.success)return{name:Tn,status:"fail",message:`${w(i)} has no host path \u2014 ${ua} again`};let l=c.data.path;if(!o(l))return{name:Tn,status:"fail",message:`Chrome native host ${w(l)} is missing or not executable \u2014 ${ua} again`};let u=xT.exec(n(l)??"")?.groups?.target;return u!==void 0&&!o(u)?{name:Tn,status:"fail",message:`Chrome native host runs ${w(u)}, which no longer exists \u2014 ${ua} again`}:{name:Tn,status:"pass",message:`Native host registered (${w(l)}); /infra-kit:doctor checks the live connection`}},Cu=(e={})=>{let t=e.home??gy.homedir(),r=e.readText??yy,n=da.object({claudeInChromeDefaultEnabled:da.boolean().optional()}).safeParse(vy(r(hy.join(t,".claude.json"))??""));return n.success&&n.data.claudeInChromeDefaultEnabled===!0};import TT from"node:fs/promises";var es=async(e,t)=>{if(!t)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let r=await TT.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}}},ts=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import $T from"node:fs";import AT from"node:os";import wy from"node:path";import OT from"node:process";import{$ as CT}from"zx";var Cn=()=>CT({quiet:!0});var DT=()=>[wy.join(AT.homedir(),".local","bin"),"/opt/homebrew/bin","/usr/local/bin"],IT=async e=>{try{return(await Cn()`command -v ${e}`).stdout.trim()||null}catch{return null}},rs=()=>({runCommand:async e=>{let t=await Cn()`${e}`;return{stdout:`${t.stdout}
|
|
167
|
+
${t.stderr}`}},resolveBinPath:async e=>{let t=await IT(e);return t!==null?t:DT().map(r=>wy.join(r,e)).find(r=>$T.existsSync(r))??null},realpath:be,platform:OT.platform});var rr=(...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"],ga=e=>t=>zc(t,e)?"homebrew":"unknown",ha=(e,t)=>r=>r===null?null:t(e(r),r),Au=e=>ha(ga(e.kegName),t=>t==="homebrew"?rr(["brew","upgrade",e.brewFormula]):null),ky=e=>Si(e,"Homebrew")||Si(e,"homebrew")?"homebrew":"unknown",_T={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:ky,updateFor:ha(ky,e=>e==="homebrew"?rr(["brew","update"]):null)},$u={brewFormula:"awscli",brewInstallSpec:"awscli",kegName:"awscli"},Sy="https://awscli.amazonaws.com/v2/install.sh",Ey={steps:[["/bin/bash","-c",`curl -fsSL ${Sy} | bash`]],needsSudo:!1,fetchesNetworkScript:!0},NT="/usr/local/aws-cli",MT=e=>rn(NT,e,be)?{steps:[["sudo","/bin/bash","-c",`curl -fsSL ${Sy} | bash -s -- --system`]],needsSudo:!0,fetchesNetworkScript:!0}:Ey,by=e=>zc(e,$u.kegName)?"homebrew":Si(e,"aws-cli")?"script":"unknown",jT={id:"aws",binName:"aws",...$u,probeArgv:["aws","--version"],versionFrom:$n,platforms:An,prerequisites:[],bootstrapInstall:Ey,identify:by,updateFor:ha(by,(e,t)=>e==="homebrew"?rr(["brew","upgrade",$u.brewFormula]):e==="script"?MT(t):null)},pa={brewFormula:"git",brewInstallSpec:"git",kegName:"git"},FT={id:"git",binName:"git",...pa,probeArgv:["git","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:rr(["brew","install",pa.brewInstallSpec]),identify:ga(pa.kegName),updateFor:Au(pa)},ma={brewFormula:"gh",brewInstallSpec:"gh",kegName:"gh"},LT={id:"gh",binName:"gh",...ma,probeArgv:["gh","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:rr(["brew","install",ma.brewInstallSpec]),identify:ga(ma.kegName),updateFor:Au(ma)},fa={brewFormula:"doppler",brewInstallSpec:"dopplerhq/cli/doppler",kegName:"doppler"},BT={id:"doppler",binName:"doppler",...fa,probeArgv:["doppler","--version"],versionFrom:$n,platforms:An,prerequisites:["brew"],bootstrapInstall:rr(["brew","install","gnupg"],["brew","install",fa.brewInstallSpec]),identify:ga(fa.kegName),updateFor:Au(fa)},ns="portless",Ry=e=>Sf(e,ns)===null?"unknown":"npm",UT={id:"portless",binName:ns,npmPackage:ns,probeArgv:["portless","--version"],versionFrom:$n,platforms:[...An,"win32"],prerequisites:[],bootstrapInstall:rr(["npm","install","-g",ns]),identify:Ry,updateFor:ha(Ry,e=>e==="npm"?rr(["npm","install","-g",`${ns}@latest`]):null)},Ou={brew:_T,git:FT,aws:jT,gh:LT,doppler:BT,portless:UT},$r=Object.keys(Ou),ze=e=>Ou[e],Du=(e,t)=>e.platforms.includes(t),Iu=e=>{let t=[],r=new Set,n=(o,s)=>{if(s.includes(o))throw new Error(`dependency cycle: ${[...s,o].join(" -> ")}`);if(!r.has(o)){r.add(o);for(let i of ze(o).prerequisites)n(i,[...s,o]);t.push(o)}};for(let o of e)n(o,[]);return t};var Py=e=>({id:e,present:!1,onPath:!1,binRealPath:null,version:null,manager:"unknown"}),xy=async(e,t)=>{try{return await e(t)}catch{return null}},VT=async(e,t)=>{try{let r=await e.resolveBinPath(t);return r==null?null:e.realpath(r)}catch{return null}},Ty=async(e,t)=>{if(!Du(e,t.platform))return Py(e.id);let r=await xy(t.runCommand,e.probeArgv),n=await VT(t,e.binName);if(r==null&&n==null)return Py(e.id);let o=r??(n==null?null:await xy(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)}},os=async(e,t)=>Promise.all(e.map(r=>Ty(ze(r),t)));import ve from"node:fs";import ka from"node:os";import le from"node:path";import Vu from"node:process";import va from"node:fs/promises";import WT from"node:path";import GT from"node:process";var Cy=` // // Editor tooling only \u2014 a JSON Schema URL for completion and validation. Ignored at runtime.
|
|
184
168
|
// "$schema": "https://\u2026/infra-kit.schema.json",
|
|
185
169
|
//
|
|
186
170
|
// // The committed file's shape version. A CLI that reads an older version refuses the file and
|
|
@@ -227,6 +211,15 @@ ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
227
211
|
// // grants yourself production access with no trace in the repo.
|
|
228
212
|
// "protectedEnvs": "disallow"
|
|
229
213
|
//
|
|
214
|
+
// // Which branch releases and features are cut from. "dev" (the default): an integration branch \u2014
|
|
215
|
+
// // regular releases branch off dev and merge back, \`release deliver\` promotes dev to main and
|
|
216
|
+
// // syncs main back, hotfixes branch off main. "main": no integration branch \u2014 features and
|
|
217
|
+
// // releases branch off main and merge straight into it, and there is no separate hotfix type.
|
|
218
|
+
// //
|
|
219
|
+
// // PROJECT LAYER ONLY. REFUSED here and in the per-project override: every teammate's releases
|
|
220
|
+
// // must travel the same branches.
|
|
221
|
+
// "gitFlow": "dev"
|
|
222
|
+
//
|
|
230
223
|
// // MCP servers fronted by \`ik-mcp\`, the credential-agnostic stdio proxy: one entry per server,
|
|
231
224
|
// // naming the command to spawn and the env-var NAMES it reads from the \`ik env-load\` session
|
|
232
225
|
// // file. \`ik setup\` derives a committed \`.mcp.json\` entry from each; \`ik audit\` guards drift.
|
|
@@ -293,7 +286,7 @@ ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
293
286
|
// // also fixes its modes), or by hand: both are supported, which is why the store carries no
|
|
294
287
|
// // repo-identity field and no mandatory version. Pasting a token into an
|
|
295
288
|
// // 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.`,
|
|
289
|
+
// // the token first, because a config file can be committed, backed up by your editor, or shared.`,_u=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
|
|
297
290
|
//
|
|
298
291
|
// Merge chain (later layers override earlier ones at top-level keys):
|
|
299
292
|
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
@@ -302,8 +295,8 @@ ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
302
295
|
//
|
|
303
296
|
// Merge is shallow: setting a top-level key replaces that whole section from
|
|
304
297
|
// layer 1. Arrays do not concatenate. Top-level keys recognized:
|
|
305
|
-
// $schema, configVersion, envManagement, defaultEnv, worktrees, protectedEnvs, mcp,
|
|
306
|
-
// vendorSource, vendorTarget, audit, aliasRepo (configVersion and the last five project layer
|
|
298
|
+
// $schema, configVersion, envManagement, defaultEnv, worktrees, protectedEnvs, gitFlow, mcp,
|
|
299
|
+
// vendorSource, vendorTarget, audit, aliasRepo (configVersion, gitFlow and the last five project layer
|
|
307
300
|
// only). The schema is strict \u2014 an
|
|
308
301
|
// unrecognized top-level key is a parse error, not a silently ignored one.
|
|
309
302
|
//
|
|
@@ -315,15 +308,15 @@ ${l}`:l}).join(""),c=Fh.byteLength(a)>Bh;return{diffStat:r,...o?{lockfileDiffSta
|
|
|
315
308
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
316
309
|
// user-global layer \u2014 it is shown here only to document the full, valid config shape.
|
|
317
310
|
{
|
|
318
|
-
${
|
|
311
|
+
${Cy}
|
|
319
312
|
}
|
|
320
|
-
`,
|
|
313
|
+
`,Nu=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
321
314
|
//
|
|
322
315
|
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
|
|
323
316
|
// <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
|
|
324
317
|
// top-level key set here replaces that whole section wholesale; arrays do not
|
|
325
318
|
// concatenate. Top-level keys recognized: $schema, configVersion, envManagement, defaultEnv, worktrees,
|
|
326
|
-
// protectedEnvs, mcp, vendorSource, vendorTarget, audit, aliasRepo (configVersion and the last five project layer only \u2014 refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
|
|
319
|
+
// protectedEnvs, gitFlow, mcp, vendorSource, vendorTarget, audit, aliasRepo (configVersion, gitFlow and the last five project layer only \u2014 refused here). The schema is strict \u2014 an unrecognized top-level key is a parse
|
|
327
320
|
// error, not a silently ignored one.
|
|
328
321
|
//
|
|
329
322
|
// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
|
|
@@ -333,9 +326,9 @@ ${gy}
|
|
|
333
326
|
// the committed project infra-kit.json (layer 1) and is usually NOT set in this
|
|
334
327
|
// override layer \u2014 it is shown here only to document the full, valid config shape.
|
|
335
328
|
{
|
|
336
|
-
${
|
|
329
|
+
${Cy}
|
|
337
330
|
}
|
|
338
|
-
`,
|
|
331
|
+
`,Mu=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
|
|
339
332
|
//
|
|
340
333
|
// Machine-local registry the vendor commands (sync/manifest/diff) read to know
|
|
341
334
|
// where your project repos live, which one is the source and which ones to stamp. This .example.jsonc is
|
|
@@ -347,110 +340,143 @@ ${gy}
|
|
|
347
340
|
// "source": "starter-workspace", // string \u2014 the one repo \`vendor sync\` copies from (its infra-kit.json holds vendorSource)
|
|
348
341
|
// "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
|
|
349
342
|
}
|
|
350
|
-
`;var
|
|
351
|
-
`,"utf-8");let o=
|
|
343
|
+
`;var $y=!1,JT=e=>e.replace(/\.json$/,".example.jsonc"),KT=async e=>{try{return await va.readFile(e,"utf-8")}catch{return null}},On=async e=>{let t=e.userProject,r=JT(t);await va.mkdir(WT.dirname(t),{recursive:!0});let n=!await ie(t);n&&await va.writeFile(t,`{}
|
|
344
|
+
`,"utf-8");let o=Nu(e.projectName),s=await KT(r)!==o;return s&&await va.writeFile(r,o,"utf-8"),n&&So(),{configPath:t,examplePath:r,createdConfig:n,refreshedExample:s}},Dn=e=>`Created ${w(e.configPath)} \u2014 see ${w(e.examplePath)} for the annotated reference.`,ju=async()=>{if(GT.env.INFRA_KIT_NO_SEED||$y)return;$y=!0;let e;try{e=await z()}catch{return}if(await ie(e.main))try{let t=await On(e);t.createdConfig?d.info(Dn(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 HT}from"node:child_process";import Oy from"node:fs";import In from"node:process";import{fileURLToPath as Dy}from"node:url";var Ay=["INFRA_KIT_NO_AUTO_UPDATE","NO_UPDATE_NOTIFIER","CI"],Fu=e=>{let{argv:t,env:r,isTty:n,selfRealPath:o,cwd:s,realpath:i}=e;return Ay.some(c=>{let l=r[c];return l!=null&&l!==""})?"opt-out":t.includes("--json")?"json":n?Pf(o,s,i)?"local-install":null:"not-a-tty"};var qT=e=>{HT(In.execPath,[e,"--parent-pid",String(In.pid)],{detached:!0,stdio:"ignore",windowsHide:!0}).unref()},YT=()=>Dy(new URL("./update-check.js",import.meta.url)),zT=()=>Oy.realpathSync(Dy(new URL("./cli.js",import.meta.url))),XT=/^[\w@./+ -]+$/,ZT=e=>XT.test(e),QT=(e,t,r)=>{!e?.latestVersion||!e.updateCommand||Ct(e.latestVersion,t)&&e.updateCommand.every(ZT)&&r(`infra-kit ${e.latestVersion} is available (you have ${t}). Run: ${Ei(e.updateCommand)}`)},eC=(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(Pn())}, or run: infra-kit setup`),o(e.finishedMs)},Lu=(e,t={})=>{try{let r=t.argv??In.argv,n=t.env??In.env,o=t.isTty??!!In.stdout.isTTY,s=t.cwd??In.cwd(),i=t.nowMs??Date.now(),a=t.selfRealPath??zT(),c=t.readCache??To,l=t.spawnChild??qT,u=t.fileExists??(h=>Oy.existsSync(h)),p=t.notify??(h=>{d.info(h)});if(Fu({argv:r,env:n,isTty:o,selfRealPath:a,cwd:s,realpath:be})!==null)return;let m=c();QT(m,e,p);try{eC((t.readAutoSetup??xn)(),e,(t.readNotified??py)(),p,t.writeNotified??my)}catch{}if(!fl(m,i))return;let f=t.childPath??YT();if(!u(f))return;l(f)}catch{}};import wt from"node:fs/promises";import vt from"node:path";import{pathToFileURL as nC}from"node:url";import oC from"yaml";import{z as Mn}from"zod";import tC from"node:fs/promises";import Bu from"node:os";import Uu from"node:path";import{z as rC}from"zod";import{z as ss}from"zod";var Iy="vendor.json",_y=ss.object({workspaceDir:ss.string().min(1),source:ss.string().min(1),targets:ss.array(ss.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 _n=()=>Uu.join(Bu.homedir(),wf,Iy),Nn=e=>{if(e==="~")return Bu.homedir();if(e.startsWith("~/"))return Uu.join(Bu.homedir(),e.slice(2));if(Uu.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},wa=async()=>{let e=_n(),t;try{t=await tC.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
345
|
|
|
353
346
|
{
|
|
354
347
|
"workspaceDir": "~/projects",
|
|
355
348
|
"source": "my-starter",
|
|
356
349
|
"targets": ["my-repo"]
|
|
357
350
|
}
|
|
358
|
-
`)}let r;try{r=t.trim()===""?{}:JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in vendor.json at ${e}: ${o.message}`)}let n=
|
|
359
|
-
`,"utf-8"),await
|
|
360
|
-
`,"utf-8"),await
|
|
361
|
-
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},
|
|
362
|
-
`)[0]??n;return
|
|
363
|
-
`),s=0;for(;s<o.length&&
|
|
351
|
+
`)}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=_y.safeParse(r);if(!n.success)throw new Error(`Invalid factory config at ${e}: ${rC.prettifyError(n.error)}`);return n.data};var Ny=e=>e.replace(/\.json$/,".yml"),My=async()=>{let e;try{e=await z()}catch{return}let t={label:"infra-kit.json",yml:Ny(e.main),json:e.main,schema:dg},r=[...st.withheld?[]:[t],{label:"~/.infra-kit/infra-kit.json",yml:vt.join(vt.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:rl},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Ny(e.userProject),json:e.userProject,schema:rl}],n=0;for(let o of r){let[s,i]=await Promise.all([ie(o.yml),ie(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 wt.readFile(o.yml,"utf-8"),c=oC.parse(a)??{},l=o.schema.safeParse(c);if(!l.success){d.info(`\u26A0 Skipped ${w(o.yml)} \u2014 invalid config: ${Mn.prettifyError(l.error)}`);continue}await wt.mkdir(vt.dirname(o.json),{recursive:!0}),await wt.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
|
|
352
|
+
`,"utf-8"),await wt.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&&Yt()},jy=async()=>{let e;try{e=await z()}catch{return}let t=vt.dirname(e.userGlobal),r=[{from:vt.join(t,"config.json"),to:e.userGlobal},{from:vt.join(t,"config.example.jsonc"),to:vt.join(t,"infra-kit.example.jsonc")}],n=0;for(let{from:o,to:s}of r){let[i,a]=await Promise.all([ie(o),ie(s)]);if(i){if(a){d.info(`\u26A0 Skipped ${w(o)} \u2014 ${w(s)} already exists (remove the stale file manually)`);continue}try{await wt.mkdir(vt.dirname(s),{recursive:!0}),await wt.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&&Yt()},sC=Mn.object({workspaceDir:Mn.string().min(1),targets:Mn.array(Mn.string()).min(1)}).strict(),Fy=async()=>{let e=_n(),t=vt.dirname(e),r=vt.join(t,"vendor.config.ts"),[n,o]=await Promise.all([ie(r),ie(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 wt.stat(r),c=(await import(`${nC(r).href}?mtime=${Number(s.mtimeMs)}`)).default,l=typeof c=="function",u=l?await c():c,p=sC.safeParse(u);if(!p.success){d.info(`\u26A0 Skipped ${w(r)} \u2014 invalid factory config: ${Mn.prettifyError(p.error)}`);return}await wt.mkdir(t,{recursive:!0}),await wt.writeFile(e,`${JSON.stringify(p.data,null,2)}
|
|
353
|
+
`,"utf-8"),await wt.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}`)}}},Ly=async()=>{let e=await iC(),t=0;for(let r of e)if(await ie(r))try{let n=await ig(r);if(!n.changed)continue;d.info(`\u2713 Migrated ${w(r)} (removed ${n.notes.join(" and ")})`),t++}catch(n){let o=n instanceof og?"changed while migrating":n.message;d.info(`\u26A0 Skipped ${w(r)} \u2014 ${o}`)}t>0&&Yt()},iC=async()=>{try{let e=await z();return st.withheld?[e.userGlobal,e.userProject]:[e.main,e.userGlobal,e.userProject]}catch{return[mg()]}};var Ar="# -- infra-kit:begin --",nr="# -- infra-kit:end --",aC=[["# region infra-kit","# endregion infra-kit"]],cC="# infra-kit shell functions",jn=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},Fn="Run `source ~/.zshrc` or open a new terminal to activate.",lC={step:"migrations",outcome:"unchanged",message:"Config migrations checked (legacy yml layers, user-global filename, ide structure, factory config, retired project cache)",level:"silent"},Xe=async(e,t)=>{try{return await t()}catch(r){throw new jn(e,r)}},Wu=async e=>{let t=[],r=(...s)=>{for(let i of s)t.push(i),e?.(i)};await Xe("zshrc",()=>{r(pC())}),await Xe("zshenv",()=>{r(mC())}),await Xe("migrations",async()=>{await gC(),fC(),r(lC)}),await Xe("user-config",()=>{r(yC())});let n=await Xe("guidance",async()=>{let{entries:s,root:i}=await bC();return r(...s),i}),o=await Xe("plugin-pointer",async()=>Qh());return r(...SC(o,n)),await Xe("worktrees",async()=>{r(...await CC(o))}),await Xe("plugin-pointer",async()=>{await AC(o,r)}),await Xe("mcp-proxies",async()=>{r(...await DC(o))}),await Xe("project-config",async()=>{r(...await vC(o))}),await Xe("token-perms",async()=>{r(await dC())}),await Xe("chrome",()=>{r(uC())}),r(...hC()),t},uC=()=>{let e=Qo();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"}:Cu()?{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"}},dC=async()=>{let e=await gg();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 Uy=e=>{let t=le.dirname(e);return ve.existsSync(le.join(e,".git"))?e:t===e?null:Uy(t)},Vy=(e,t,r,n)=>{if(!st.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=ve.realpathSync(t)}catch{}return Uy(le.dirname(o))===null?null:as(e,ka.homedir(),o,["the infra-kit block updated"])},Wy=e=>ve.existsSync(e)?ve.readFileSync(e,"utf-8"):null,pC=()=>{let e=le.join(ka.homedir(),".zshrc"),t=Wy(e),r=t===null?"":_C(t),n=cn({content:r,body:Ky(),startMarker:Ar,endMarker:nr,placement:"append-end"}),o=Vy("zshrc",e,t,n);return o!==null?o:(ve.writeFileSync(e,n),{step:"zshrc",outcome:"written",message:`Added infra-kit shell functions to ${e}`,level:"info"})},mC=()=>{let e=le.join(ka.homedir(),".zshenv"),t=Wy(e),r=cn({content:t??"",body:Gu(),startMarker:Ar,endMarker:nr}),n=Vy("zshenv",e,t,r);return n!==null?n:(ve.writeFileSync(e,r),{step:"zshenv",outcome:"written",message:`Added infra-kit session-env block to ${e}`,level:"info"})},fC=()=>{ve.rmSync(le.join(xt(),"projects"),{recursive:!0,force:!0})},gC=async()=>{await My(),await jy(),await Ly(),await Fy()},hC=()=>{let e=Vu.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:Fn,level:"info"}),t},yC=()=>{let e=le.join(ka.homedir(),".infra-kit"),t=le.join(e,"infra-kit.json");return ve.mkdirSync(e,{recursive:!0}),ve.writeFileSync(le.join(e,"infra-kit.example.jsonc"),_u(),"utf-8"),ve.writeFileSync(le.join(e,"vendor.example.jsonc"),Mu(),"utf-8"),ve.existsSync(t)?{step:"user-config",outcome:"unchanged",message:`User-global config already present at ${t} (refreshed reference examples)`,level:"info"}:(ve.writeFileSync(t,`{}
|
|
354
|
+
`,"utf-8"),{step:"user-config",outcome:"written",message:`Wrote user-global config to ${t} (see the sibling .example.jsonc files for reference)`,level:"info"})},vC=async e=>{if(Vu.env.INFRA_KIT_NO_SEED)return[is("skipped","INFRA_KIT_NO_SEED is set")];if(e===null)return[is("skipped","not inside a git repository")];try{let t=await z();if(!ve.existsSync(t.main))return[is("skipped",`no project config at ${t.main}`)];let r=await On(t);return r.createdConfig?[{step:"project-config",outcome:"written",message:Dn(r),level:"info"}]:[is("unchanged","the user-project config was already present")]}catch(t){return d.debug({err:t,msg:"Skipped seeding the user-project config (init)."}),[is("warned",t instanceof Error?t.message:String(t))]}},is=(e,t)=>({step:"project-config",outcome:e,message:`Skipped seeding the user-project config \u2014 ${t}`,level:"silent"}),wC=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},kC=(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"},...wC(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},bC=async()=>{let{skipped:e,root:t,version:r,written:n}=await ey({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:kC(r,n)}},ba=e=>`cd ${Cf(e)} && infra-kit setup --skip-tools`,as=(e,t,r,n)=>({step:e,outcome:"manual",message:`${r} needs ${n.join(", ")} \u2014 left for a human to commit; run: ${ba(t)}`,level:"info"}),RC=(e,t)=>{let r=le.relative(e,t.path);return t.status==="withheld"?as("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"}},By=(e,t)=>{let r=Ye;if(t.kind==="stale"||t.kind==="wrong-key"){let o=t.kind==="stale"?pe: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 ${ht} from ${le.join(e,Ye)} \u2014 fix the JSON and re-run: infra-kit setup --skip-tools`,level:"warn"}:{step:"mcp-server",outcome:"unchanged",message:` infra-kit MCP server: none wanted \u2014 the plugin is skills-only (${t.kind==="absent"?`${r} carries no "${pe}" key`:`no ${r}`})`,level:"info"}},SC=(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 ${X} plugin for that project. If that is not the repo you meant to set up, revert that file and uninstall the plugin.`,level:"warn"}],EC=()=>[zl,Dt].map(e=>({step:"plugin-pointer",outcome:"manual",message:e,level:"info"})),PC=e=>{let r={step:"plugin-pointer",outcome:"warned",message:`Claude Code plugin not updated \u2014 ${e.stale?`CLI ${U.version} is behind ${e.latestVersion}, update it first with the command below`:`CLI ${U.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:Ei(e.updateCommand),level:"info"}]:[r]},xC=(e,t)=>e.status==="skipped-cli-stale"?PC(t):e.status==="updated"?[{step:"plugin-pointer",outcome:"unchanged",message:`Claude Code plugin ${X} 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: ${yn}`,level:"warn"}]:e.status==="installed"?[{step:"plugin-pointer",outcome:"written",message:`installed Claude Code plugin ${X} (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"},...EC()]:[{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: ${Dt}`,level:"warn"}],Gy={stale:!1},TC=async()=>{let e=To(),t=e===null?await hl(Vu.env):e.latestVersion;return t===null||!yl(t,U.version)?Gy:{stale:!0,latestVersion:t,updateCommand:e?.updateCommand??Ef(t)}},CC=async e=>{if(e===null)return[];let r=`${await Ie(e)}${ce}`,n=Object.values(tn).filter(o=>!ve.existsSync(le.join(r,o)));for(let o of Object.values(tn))ve.mkdirSync(le.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"}]},$C=(e,t)=>t?[{step:"plugin-pointer",outcome:"skipped",message:`Claude Code plugin ${X} is installed; the update worker keeps it current`,level:"debug"}]:[as("plugin-pointer",e,".claude/settings.json",[`the ${X} plugin installed`])],AC=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(RC(e,Xl(le.join(e,".claude","settings.json"),{write:!st.withheld})));let r=kr({projectPath:e}).kind==="installed";if(st.withheld){t(...$C(e,r),By(e,hn(e)));return}let n=r?await TC():Gy;t(...xC(Jl({projectRoot:e,cliIsStale:()=>n.stale}),n)),t(By(e,hn(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: ${Dt}`,level:"warn"})}},Jy=(e,t)=>{let r=le.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},OC=(e,t)=>{let r=t.entries.filter(i=>i.status==="drifted"),n=t.entries.filter(i=>i.status!=="drifted"),o=Jy(e,{...t,entries:n});if(t.status!=="ok"||r.length===0)return o;let s=r.map(i=>`ik-mcp "${i.name}"`);return[...o,as("mcp-proxies",e,le.relative(e,t.path),s)]},DC=async e=>{if(e===null)return[];if(!ve.existsSync(le.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 V()).mcp}catch(r){let n=r instanceof Error?r.message:String(r),o=n.split(`
|
|
355
|
+
`)[0]??n;return st.withheld?[as("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?[]:st.withheld?OC(e,Wo({projectRoot:e,proxies:t,write:!1})):Jy(e,Wo({projectRoot:e,proxies:t,write:!0}))},IC=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"),_C=e=>{let t=Qt(e,Ar,nr);if(t!==null)return t;for(let[a,c]of aC){let l=Qt(e,a,c);if(l!==null)return l}let r=e.indexOf(cC);if(r===-1)return e;let n=e.slice(0,r).replace(/\n+$/,""),o=e.slice(r).split(`
|
|
356
|
+
`),s=0;for(;s<o.length&&IC(o[s]);)s++;let i=o.slice(s).join(`
|
|
364
357
|
`);return n+(i?`
|
|
365
|
-
${i}`:"")},
|
|
366
|
-
`)},
|
|
367
|
-
${
|
|
368
|
-
${
|
|
369
|
-
`),
|
|
370
|
-
${
|
|
371
|
-
${
|
|
372
|
-
|
|
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),TC=async()=>{let e=await PC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return xC(e.stdout)},CC=async()=>{let e=await At();return e?(await pn(e)).map(r=>r.name):[]},Qo=async()=>{let[e,t]=await Promise.allSettled([TC(),CC()]);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"),Lu({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import $C from"node:fs";import AC from"node:path";var Ku=[".claude/settings.json",".claude/settings.local.json"],OC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],DC=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),IC=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},NC=(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(DC).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},_C=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},MC=()=>xr.filter(e=>e.mutating),jC=e=>{let t=IC(e);return t===null?[]:MC().filter(r=>OC.some(n=>_C(r).some(o=>NC(t,`${n} ${o}`)))).map(r=>r.groupPath.join(" "))},FC=(e,t)=>{let r;try{r=$C.readFileSync(AC.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}},nv=e=>{let t={present:[],unreadable:[],hits:[]};for(let r of Ku){let n=FC(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=jC(o);s.length>0&&t.hits.push({file:r,pattern:o,commands:s})}}}return t};var LC=e=>e.every(t=>t.status!=="fail"),BC=["brew","git","gh","doppler","aws"],UC=async e=>{let t=await zo(BC,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},It=async(e,t,r,n)=>{try{return await An()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},WC=async()=>{let e="orca installed",t=await Wt();return t==="absent"?{name:e,status:"fail",message:"orca is not on PATH. Install with: brew install --cask stablyai/orca/orca, then register the CLI in Orca \u2192 Settings \u2192 Experimental \u2192 CLI"}:t==="unreachable"?{name:e,status:"warn",message:"orca is installed but the app is not running \u2014 start it with: orca open"}:{name:e,status:"pass",message:"Installed: orca (app running, runtime reachable)"}},yv=(e,t,r,n)=>{let o=ve.join(hv.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!ae.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=ae.readFileSync(o,"utf-8"),a=i.indexOf(Rr),c=i.indexOf(zt);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+zt.length).trim()!==n.trim()?{name:e,status:"fail",message:`infra-kit ${r} block in ~/${t} is out of date. ${s}`}:{name:e,status:"pass",message:`infra-kit ${r} block in ~/${t} is up to date`}},VC=()=>yv("zshrc init block",".zshrc","shell",Uy()),GC=()=>yv("zshenv session block",".zshenv","session-env",Au()),JC=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await $(),r=ve.join(t,"pnpm-workspace.yaml");if(!ae.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=ae.readFileSync(r,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(n)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(t){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${t.message}`}}},KC=async()=>{try{return Lt(),{config:await K(),error:null}}catch(e){return{config:null,error:e}}},HC=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)"}},qC=384,Hu=448,YC=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(", "),zC=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}}})),XC=async(e,t={})=>{let r="env tokens configured",n=t.readStore??Qe,o=t.resolveToken??Ff;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 zC(await pi(),o);return{name:r,status:"pass",message:YC(s)}},ZC=()=>ht.env[pr]||void 0,QC=async(e={})=>{let t="tokens.json present",r=e.readStore??Qe,n=e.storePath??Ut;if((e.readEnvToken??ZC)())return{name:t,status:"skip",message:`${pr} is set; that channel takes precedence over the store`};let s;try{s=w(await n())}catch{return{name:t,status:"skip",message:"the token store path could not be resolved"}}let i;try{i=await r()}catch{return{name:t,status:"skip",message:`The store at ${s} is unreadable (see env tokens configured)`}}let a=i===null?[]:Object.keys(i.envs);if(a.length===0){let c=i===null?`No token store at ${s}`:`${s} holds no tokens`;return{name:t,status:"fail",message:`${c} \u2014 every project needs one to authenticate. Fix: run \`infra-kit env-token-set <env>\`. CI / agents: set ${pr} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},es=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},e$=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Ut,o=t.statPath??t$,s=t.chmodPath??ae.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(es(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=ve.dirname(i),c=ve.dirname(a),l=ve.dirname(c),p=[{target:l,expected:Hu,actual:es(l,o)},{target:c,expected:Hu,actual:es(c,o)},{target:a,expected:Hu,actual:es(a,o)},{target:i,expected:qC,actual:es(i,o)}].filter(f=>f.actual!==null&&f.actual!==f.expected);if(p.length===0)return{name:r,status:"pass",message:`${w(i)} is 0600 (0700 dirs)`};let m=p.map(f=>`${w(f.target)} is ${ov(f.actual)}, expected ${ov(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}`}},ov=e=>`0${e.toString(8).padStart(3,"0")}`,t$=e=>{try{return ae.statSync(e)}catch{return null}},r$=async()=>{let e="user override path";try{let t=await ee(),r=ae.existsSync(t.userProject),n=await Ko(t.userProject,r),o=r?Ho(n):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${w(t.userProject)} ${o} \u2014 project: ${t.projectName}`}}catch(t){return{name:e,status:"fail",message:t.message}}},n$=async()=>{let e="legacy user-global config",t;try{t=await ee()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=ve.join(ve.dirname(t.userGlobal),"config.json");return ae.existsSync(r)?ae.existsSync(t.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${w(r)} \u2014 ${w(t.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${w(r)} \u2014 run \`infra-kit setup --skip-tools\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},sv=/^\d+\.\d+\.\d+$/,iv=(e,t)=>e===t||!sv.test(e)||!sv.test(t)?!1:Nn([`v${e}`,`v${t}`])[0]===`v${e}`,o$=async e=>{let t;try{t=await Re(e)}catch{return[]}return t.flatMap(r=>{let n=Tt(ut(ve.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},av=e=>Nn(e.map(t=>`v${t}`)).map(t=>t.slice(1)),s$=async(e,t,r)=>{let n="Guidance version",o=gr(t,hr),s=await o$(e),a=(o===null?s:[o,...s]).filter(p=>St(p,r));if(a.length>0){let p=av(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&&iv(o,r),l=s.filter(p=>iv(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 ${av(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},i$=async()=>{let e=[{name:"CLAUDE.md block",status:"skip",message:"no infra-kit config in this repo"},{name:"Guidance version",status:"skip",message:"no infra-kit config in this repo"}],t;try{t=(await ee()).main}catch{return e}if(!ae.existsSync(t))return e;let r=ve.dirname(t),n=ve.join(r,"CLAUDE.md"),o=ae.existsSync(n)?ae.readFileSync(n,"utf-8"):"",s=Ve(o,Se,Ie);return[{name:"CLAUDE.md block",status:s?"pass":"fail",message:s?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit setup --skip-tools"},await s$(r,o,L.version)]},a$=async()=>{try{let e=(await ee()).main;return ae.existsSync(e)?ve.dirname(e):null}catch{return null}},c$=e=>{let t=Pf();return t===null||!St(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${rn}`},l$=e=>{let t=e.kind==="installed"?ci(e.installation):null;return{name:"plugin version",status:t===null?"fail":"pass",message:t===null?"No infra-kit plugin installed for this project to read a version from":`Plugin ${q} version ${t}${c$(t)}`}},cv=3,lv=(e,t)=>xe(e)===xe(t),u$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(lv(e.projectDir,e.gitRoot))return"";let r=zn(e.gitRoot,xe(e.projectDir),xe)?"below the repo root":"not this checkout";return` \u2014 this session was launched from ${w(e.projectDir)}, ${r}: the plugin and this repo's .claude/settings.json hooks load only from ${t} (measured); restart Claude Code there`}return lv(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}`},d$=(e,t)=>{let r="plugin installed",n=u$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${q} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${q} is not installed. Run: ${Ct}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-cv,i=s>0?` and ${s} more`:"",a=`${o.slice(0,cv).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${q} is installed for ${a} only, not this project. Run: ${Ct}${n}`}},p$=()=>It("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var m$=(e,...t)=>{try{return JSON.parse(ae.readFileSync(ve.join(e,...t),"utf-8"))}catch{return null}},f$=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=ci(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=m$(r,Je),o=n!==null&&typeof n=="object"?n[dt]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},uv=e=>`Plugin ${q} ${e===null?"(version unreadable)":e}`,g$=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${Ct}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${uv(e.version)} still carries an MCP server in its ${Je}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${rn}), then restart Claude Code`}}return{name:t,status:"pass",message:`${uv(e.version)} is skills-only \u2014 no ${Je}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},h$=(e,t)=>{let r=ur(e===null?{}:{projectPath:e}),n=ro();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${ue} is known to Claude Code`:`Marketplace ${ue} is not registered. Run: claude plugin marketplace add ${Bt}`},d$(r,t),l$(r),g$(f$(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${L.version}`}]},y$=(e,t)=>{let r="background setup";if(e===null)return{name:r,status:"skip",message:"not run yet \u2014 it runs after the next background update check"};if(e.version!==t)return{name:r,status:"skip",message:`last ran for ${e.version}; runs for ${t} after the next background update check`};if(e.finishedMs===null)return{name:r,status:"skip",message:`a pass for ${t} is running, or was interrupted and will be retried`};let n=e.runs.filter(o=>o.status!=="ok");return n.length===0?{name:r,status:"pass",message:`ran for ${t} on the machine and ${e.runs.length-1} project(s)`}:{name:r,status:"warn",message:`${n.length} run(s) left work for you (${n.map(o=>`${o.root??"machine"}: ${o.status}`).join(", ")}) \u2014 see ${w(Rn())}, or run: infra-kit setup`}},v$=({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(", ")},w$=e=>{let t="Agent mode",r=ti(e),n=v$(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})`}},dv=4,k$=e=>{let t=e.slice(0,dv).join(", "),r=e.length-dv;return r>0?`${t} +${r} more`:t},b$=e=>{let t="Agent allowlist",{present:r,unreadable:n,hits:o}=nv(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"} (${k$(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 ${Ku.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`}},R$=(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`},S$=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 zh(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} (${R$(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`}},vv=e=>Ec(["trust"],{bin:e}),E$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),pv="ERR_TLS_CERT_ALTNAME_INVALID",wv=()=>`portless serving TLS on :${Ft}`,P$=async(e,t,r)=>{let n=wv();return await e(Ft,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${Ft}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${Ft}. Install it once (needs root): \`${jt(t,r)}\`.`}},x$=async(e,t,r,n,o)=>{let s="portless CA chain valid",i=["localhost",...t.slice(0,1).map(u=>u.name)],c=(await Promise.all(i.map(async u=>({servername:u,result:await e(Ft,u)})))).filter(u=>!u.result.ok);if(c.length===0)return{name:s,status:"pass",message:`Served certificate chains to ${w(r)} (${i.join(", ")})`};let l=c.map(u=>u.result.ok?"":u.result.code);return l.includes(pv)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${pv} 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=>E$.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 \`${vv(n)}\`, or reinstall: \`${jt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},T$=(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: \`${vv(r)}\` (no sudo needed).`}},C$=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 \`${Ec(["alias","--remove","<name>"],{bin:r})}\`.`}},Qt="portless service target",rs=e=>({name:Qt,status:"warn",message:e}),kv=e=>e==="darwin"?Um:e==="linux"?Wm:null,$$=e=>e==="darwin"?`sudo launchctl kickstart -k system/${Bm}`:`sudo systemctl restart ${Vm}`,A$="/bin/ps",O$=e=>{try{let t=gv(A$,["-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}},mv=e=>{try{return ae.readFileSync(e,"utf-8")}catch{return null}},D$=e=>{try{return ae.statSync(e).mtime}catch{return null}},I$=2e3,N$=e=>{try{let t=gv(e,["-p","process.version"],{encoding:"utf-8",timeout:I$}),r=t.stdout?.trim()??"";return{version:r===""?null:r,status:t.status,signal:t.signal}}catch{return{version:null,status:null,signal:null}}},_$=(e,t)=>({platform:e.platform??ht.platform,readServiceFile:e.readServiceFile??mv,readFile:e.readFile??mv,exists:e.exists??ae.existsSync,realpath:e.realpath??xe,mtime:e.mtime??D$,execPath:e.execPath??ht.execPath,home:e.home??hv.homedir(),cwd:e.cwd??ht.cwd(),repoRoot:e.repoRoot??Uo,stateDir:(e.stateDir??Jm)(),processStartTime:e.processStartTime??O$,version:e.version??ht.version,arch:e.arch??ht.arch,nodeVersionOf:e.nodeVersionOf??N$,isGlobal:e.isGlobal??ei().node.isGlobal,nodeFs:e.nodeFs??ae,stableNode:null,stableNodeSidecar:null,bin:t}),ns="portless node",Tr="~/.infra-kit/node",ts=e=>({row:{name:ns,status:"fail",message:e},stableNode:null,sidecar:null}),fv=(e,t)=>{try{return e(t,{throwIfNoEntry:!1})}catch{return}},M$=e=>e.signal!==null?`killed by ${e.signal}`:e.status===null?"did not start":e.status!==0?`exit ${e.status}`:`printed ${e.version??"nothing"}`,j$=(e,t)=>e.status===0&&e.signal===null&&e.version===t.version,F$=e=>{let t=zm(e.home),r=fv(e.nodeFs.lstatSync,t);if(r===void 0)return ts(`${Tr} is missing and could not be written \u2014 run \`infra-kit setup\` and see the debug log`);if(!r.isFile())return ts(`${Tr} is not a regular file; infra-kit will not replace it \u2014 move it away and run \`infra-kit setup\``);let n=Xm(e.home,e.nodeFs);if(n===null)return ts(`${Tr} has no readable node.source.json and it could not be rewritten \u2014 run \`infra-kit setup\``);let o=fv(e.nodeFs.statSync,e.execPath),s=n.version===e.version&&n.arch===e.arch&&n.platform===e.platform,i=o!==void 0&&r.ino===o.ino&&r.dev===o.dev,a=n.method==="copy"&&o!==void 0&&n.sourceSize===o.size;if(!s||!(i||a))return ts(`${Tr} is Node ${n.version} (${n.method} of ${w(n.source)}); infra-kit runs ${e.version} at ${w(e.execPath)}, a different file, and could not relink it \u2014 run \`infra-kit setup\``);if(!i){let c=e.nodeVersionOf(t);if(!j$(c,e))return ts(`${Tr} does not run as Node ${e.version} (${M$(c)}). Re-run through the current Node: \`${jt(e.bin,{...e,stableNode:null})}\`, then \`infra-kit setup\``)}return{row:{name:ns,status:"pass",message:`${Tr} is Node ${n.version} (${n.arch}, ${n.method} of ${w(n.source)})`},stableNode:t,sidecar:n}},L$=e=>{if(kv(e.platform)===null)return{row:{name:ns,status:"skip",message:"no portless OS service on this platform"},stableNode:null,sidecar:null};let t=F$(e);return e.isGlobal()?t:{...t,row:{name:ns,status:"skip",message:`not a global install; the global infra-kit keeps ${Tr} current`}}},bv=(e,t)=>{let r=_$(e,t),n=L$(r);return{seams:{...r,stableNode:n.stableNode,stableNodeSidecar:n.sidecar},node:n.row}},B$=(e,t)=>{let r=t.readFile(ve.join(e,"package.json"));try{let n=r===null?null:Ee.object({version:Ee.string()}).safeParse(JSON.parse(r));return n?.success===!0?n.data.version:"?"}catch{return"?"}},U$=e=>{let t=Number.parseInt(e.readFile(ve.join(e.stateDir,"proxy.pid"))?.trim()??"",10);return!Number.isInteger(t)||t<=0?null:e.processStartTime(t)},W$=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?null:t},V$=(e,t,r)=>{let n=U$(r),o=a=>n!==null&&a!==null&&n.getTime()<a.getTime(),s=r.stableNodeSidecar,i=[...s!==null&&o(W$(s.versionChangedAt))?[`Node ${s.version}`]:[],...o(r.mtime(ve.join(e,"package.json")))?[`portless ${t}`]:[]];return i.length===0?null:i.join(" and ")},G$=async(e,t)=>{let r=t.realpath(t.cwd);return r===t.realpath(t.home)?!1:zn(await t.repoRoot()??r,e,t.realpath)},Cr=e=>({state:"drifted",row:e}),J$=async(e,t,r)=>{let n=jt(r.bin,r);if(!r.exists(e))return Cr({name:Qt,status:"fail",message:`The service runs \`${e}\`, which no longer exists (Node was upgraded, or its package dir was re-created). Re-run: \`${n}\``});let o=ve.join(Pc(r.home),"dist","cli.js");if(t!==o)return Cr(rs(`The service points at \`${t}\`, a version-specific location. Re-run once to switch it to the stable link: \`${n}\``));if(Qs(r.home,r.exists)===null)return Cr({name:Qt,status:"fail",message:"~/.infra-kit/portless is broken. Run any infra-kit command from the global install (e.g. `infra-kit setup`) to repair it."});let s=r.realpath(Pc(r.home));if(await G$(s,r))return Cr({name:Qt,status:"fail",message:`The service runs portless from a project checkout (${s}). Re-run \`service install\` from the global install: \`${n}\``});let i=K$(e,n,r);if(i!==null)return i;let a=B$(s,r),c=V$(s,a,r);return c!==null?{state:"converged",row:rs(`The running daemon predates ${c} that \`dev\` will talk to. Restart it: \`${$$(r.platform)}\` (or reboot).`)}:{state:"converged",row:{name:Qt,status:"pass",message:`service runs \`${e}\` (Node ${r.version}) + stable link \u2192 portless ${a}`}}},K$=(e,t,r)=>r.stableNode!==null?r.realpath(e)===r.realpath(r.stableNode)?null:Cr(rs(`The service runs \`${e}\`, a path its package manager will remove. Re-run once to switch it to the stable node: \`${t}\``)):r.realpath(e)===r.realpath(r.execPath)?null:Cr(rs(`The service runs \`${e}\`; infra-kit runs \`${r.execPath}\`. Works until the old Node is removed. Re-run when convenient: \`${t}\``)),Rv=async e=>{let t=kv(e.platform);if(t===null)return{state:"absent",row:{name:Qt,status:"skip",message:"no portless OS service file on this platform"}};let r=e.readServiceFile(t);if(r===null)return{state:"absent",row:{name:Qt,status:"skip",message:`the OS service is not installed (no ${t})`}};let[n,o]=wh(e.platform,r)??[];return n===void 0||o===void 0?Cr(rs(`could not parse ${t} \u2014 re-run \`${jt(e.bin,e)}\` to rewrite it.`)):J$(n,o,e)},Sv=async(e,t)=>{let{seams:r}=bv(e,t);return{state:(await Rv(r)).state,stableNode:r.stableNode}},H$=()=>[ns,Qt,wv(),"portless CA chain valid","portless CA trusted","portless routes"],q$=async(e={})=>{let t=e.resolveBin??Lm,r=e.isProxyServing??Gm,n=e.handshake??qm,o=e.caTrusted??Hm,s=e.routes??Zn,i=e.isListening??Xn,a=(e.caPath??Km)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...H$().map(S=>({name:S,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=bv(e,c),m=s(),f=await P$(r,c,u),h=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await x$(n,m,a,c,u);return[l,p,(await Rv(u)).row,f,h,T$(o(),a,c),await C$(m,i,c)]},Y$=async(e={})=>{let t="portless routes",r=e.routes??Zn,n=e.isListening??Xn,o=e.devSessionRunning??fh,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}=mh(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??Ym().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},da=async(e={})=>{let t=await KC(),r=UC(e.probeDeps??qo()),n=async(m,f)=>{let[h,S]=await Promise.all([f,r]),k=S.get(m);return k===void 0?h:{...h,detail:k}},o=await Promise.all([n("brew",It("brew installed",He("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",It("git installed",He("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",It("gh installed",He("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),It("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",It("doppler installed",He("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",It("aws installed",He("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),It("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),It("typescript-language-server installed",["typescript-language-server","--version"],"typescript-language-server is installed","typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing"),WC(),Promise.resolve(VC()),Promise.resolve(GC()),JC(),Promise.resolve(HC(t)),QC(),XC(t),e$(e.fix??!1),r$(),n$()]),s=await q$(e.portlessDeps);if(e.fix){let m=await Y$(),f=s.findIndex(h=>h.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await a$(),a=await Uo(),c={projectDir:ht.env.CLAUDE_PROJECT_DIR||null,cwd:ht.cwd(),gitRoot:a},l=[await p$(),...h$(i,c),Wo(),w$({env:ht.env,stdinIsTTY:ht.stdin.isTTY===!0,flag:j.source==="flag"}),a===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:b$(a)],u=[...o,await S$(a),...s,...await i$(),...l,y$(Sn(),L.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:ql.has(m.name),detail:m.detail})),allPassed:LC(u),cliVersion:L.version};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}},qu=C({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:Ee.array(Ee.object({name:Ee.string().describe("Name of the check"),status:Ee.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:Ee.string().describe("Details about the check result"),fixable:Ee.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Ee.object({manager:Ee.string().describe("Which package manager owns this install, read from its resolved path"),version:Ee.string().nullable().describe("The version the tool reported, or null"),present:Ee.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Ee.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:Ee.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Ee.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>da()});import{E2E_MODE_ENV as RA}from"@slip-stream-kit/config/internal";import rd from"node:fs";import SA from"node:os";import ss from"node:path";import fa from"node:process";import{z as P}from"zod";var yt=(e,t,r)=>new O({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as z$,loadDev as X$,readAppAliasName as Z$,readCloudOrigin as Q$,readLocalContext as Pv}from"@slip-stream-kit/config/internal";import Ev from"node:fs";import $r from"node:path";import pa from"node:process";import{z as Yu}from"zod";var eA=async e=>{let t=$r.join(e,"apps"),r=Ev.existsSync(t)?Ev.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=$r.join(t,o,"tests"),a=(await lt(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},tA=(e,t)=>{let[r,n]=$r.relative(e,t).split($r.sep);return r==="apps"&&n?n:void 0},rA=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(tA(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:Yu.toJSONSchema(Yu.object({app:Yu.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(", ")}`})},nA=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}})),oA=e=>To(e).apps.find(t=>t.env!=="")?.env??null,zu=async(e,t={})=>{let r=t.cwd??pa.cwd(),n=t.projectRoot??await $(),o=(t.env??pa.env)[Lr]||null,s=t.healthProbe??Lc,i=rA(await eA(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=$r.join(n,"apps",c,l),p=(await fr(u)).name,m=(await lt(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${$r.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=zf(u),h=Z$(p,u),S=`${h}.localhost`,k=`https://${S}`,A=0;if(l==="ui")A=(t.listRoutes??Zn)().find(R=>R.name===S||R.name===h)?.port??0;else{let R=Pv(u).info.get(p);A=R?.port??0,k=R?.origin??k}let M=A>0&&await s({tag:a,port:A,kind:l})==="ok",v=M?oA(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:v,localUrl:k,served:M}},xv=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}},Xu=async(e,t={})=>{let r=t.healthProbe??Lc,n=Pv(e.targetDir),o=e.kind==="ui"?await X$(e.targetDir):void 0,s=o?.proxy?z$({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:Q$(e.deployedUrlEnv??void 0,t.env??pa.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...xv(e),mode:"local",baseUrl:e.localUrl,routes:await nA(s,i,r)}},Zu=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw yt("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${$r.join(e.targetDir,"infra-kit.config.ts")} and keep the URL per environment in Doppler`,stderrExcerpt:`${o} names no variable holding its deployed URL`});let s=(t.env??pa.env)[n];if(!r||!s){let i=s?Lr:n;throw yt("env_not_loaded",{missing:i},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:"load an environment (`infra-kit env-load -c <env>`), or drop --cloud to run against this worktree",stderrExcerpt:`a cloud run of ${o} needs ${n} and ${Lr}, and ${i} is not set`})}return{...xv(e),mode:"cloud",baseUrl:s,routes:[]}};import sA from"node:fs";import iA from"node:path";import{stripVTControlCharacters as aA}from"node:util";import{z as I}from"zod";var Tv=2e3,Cv="--reporter=line,json",$v=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Av=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),Qu=I.object({message:I.string().optional()}),Ov=I.object({type:I.string()}),cA=I.object({status:I.string(),retry:I.number(),error:Qu.optional(),errors:I.array(Qu).optional(),annotations:I.array(Ov).optional(),attachments:I.array(I.object({name:I.string(),path:I.string().optional()})).optional()}),lA=I.object({projectName:I.string(),status:I.string(),expectedStatus:I.string().optional(),annotations:I.array(Ov).optional(),results:I.array(cA)}),uA=I.object({title:I.string(),file:I.string(),line:I.number().optional(),tests:I.array(lA)}),Dv=I.lazy(()=>I.object({title:I.string(),specs:I.array(uA).optional(),suites:I.array(Dv).optional()})),dA=I.object({config:I.object({rootDir:I.string().optional()}).optional(),suites:I.array(Dv),errors:I.array(Qu).optional(),stats:I.object({expected:I.number(),unexpected:I.number(),flaky:I.number(),skipped:I.number()})}),Iv=e=>{let t=aA(e);return t.length>Tv?`${t.slice(0,Tv)}\u2026`:t},pA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Iv(t)},mA=e=>e.status==="unexpected"||e.status==="flaky",fA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},gA=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),hA=(e,t)=>{let r=e.filter(mA),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?pA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},yA=e=>{let t=dA.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=>[...gA(k)])),h=m.some(k=>k.expectedStatus==="failed");if(!h&&!f.has("fixme")&&!f.has("skip"))return;let S=a.get(p)??{file:p,fail:0,fixme:0,skip:0};h&&(S.fail+=1),f.has("fixme")?S.fixme+=1:f.has("skip")&&(S.skip+=1),a.set(p,S)},u=(p,m)=>{for(let f of p.specs??[]){let h=r?.rootDir?iA.resolve(r.rootDir,f.file):f.file,S=[...m,f.title].join(" \u203A ");l(h,f.tests);for(let[k,A]of fA(f.tests)){let M=hA(A,{title:S,file:h,line:f.line??null,project:k});M&&(M.runs>1&&M.failedRuns<M.runs&&(c+=1),i.push(M))}}for(let f of p.suites??[])u(f,[...m,f.title])};for(let p of n)u(p,[]);return{summary:{expected:s.expected,unexpected:s.unexpected,flaky:s.flaky,skipped:s.skipped,repeatFlaky:c},failures:i,annotated:[...a.values()],errors:(o??[]).flatMap(p=>p.message===void 0?[]:[Iv(p.message)])}},Nv=e=>{try{return yA(JSON.parse(sA.readFileSync(e,"utf8")))}catch{return null}};import os from"node:fs";import Mv from"node:path";import ma from"node:process";var vA=e=>Mv.join(e,"node_modules",".cache","infra-kit-e2e.lock"),wA=e=>{try{return ma.kill(e,0),!0}catch(t){return t.code==="EPERM"}},_v=e=>{try{return os.writeFileSync(e,String(ma.pid),{flag:"wx"}),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}},ed=e=>{try{let t=Number.parseInt(os.readFileSync(e,"utf8"),10);return Number.isInteger(t)&&t>0?t:null}catch{return null}},jv=e=>{let t=vA(e);if(os.mkdirSync(Mv.dirname(t),{recursive:!0}),!_v(t)){let r=ed(t);if(r!==null&&r!==ma.pid&&wA(r))return{holder:r};if(os.rmSync(t,{force:!0}),!_v(t))return{holder:ed(t)??0}}return{release:()=>{ed(t)===ma.pid&&os.rmSync(t,{force:!0})}}};import{spawn as kA}from"node:child_process";import bA from"node:os";import td from"node:process";var Fv=(e,t,r)=>new Promise((n,o)=>{let s=kA(e,t,r),i=td.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)td.off(l,a)};for(let l of i)td.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+bA.constants.signals[u]:1))})});var EA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],PA=e=>EA.some(t=>{try{return rd.readFileSync(ss.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),nd=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,xA=(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
|
-
|
|
358
|
+
${i}`:"")},Ky=()=>{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(`
|
|
359
|
+
`)},Hy=()=>`${Ar}
|
|
360
|
+
${Ky()}
|
|
361
|
+
${nr}`,Gu=()=>["# 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(`
|
|
362
|
+
`),Ju=()=>`${Ar}
|
|
363
|
+
${Gu()}
|
|
364
|
+
${nr}`;import cs from"node:fs/promises";import ls from"node:path";import{$ as NC}from"zx";var MC=async e=>ls.resolve(e,(await NC({cwd:e,quiet:!0})`git rev-parse --git-common-dir`).stdout.trim()),Ku=async e=>ls.join(await MC(e),"infra-kit","merge-dev-resolutions"),us=async(e,t)=>ls.join(await Ku(e),`${eg(t)}.json`),Ra=async e=>{try{return JSON.parse(await cs.readFile(e,"utf8"))}catch{return null}},or=async(e,t)=>{let r=await us(e,t.branch);await cs.mkdir(ls.dirname(r),{recursive:!0}),await cs.writeFile(r,`${JSON.stringify(t,null,2)}
|
|
365
|
+
`)},Sa=async e=>{let t=await Ku(e),r=await cs.readdir(t).catch(()=>[]);return(await Promise.all(r.filter(o=>o.endsWith(".json")).sort().map(o=>Ra(ls.join(t,o))))).filter(o=>o!==null)},Hu=async e=>Promise.all((await Sa(e)).map(async t=>({branch:t.branch,worktreePath:t.worktreePath,createdAt:t.createdAt,worktreeExists:await cs.stat(t.worktreePath).then(()=>!0,()=>!1)})));var ds=async()=>{try{return(await V()).defaultEnv??null}catch{return null}};var ps=["prod"],Ln={allowed:!1,reason:"disallow"},sr=e=>ps.includes(e),jC=["dev","stage"],Bn=e=>jC.includes(e)||sr(e),_t=(e,t=Ln)=>t.allowed?e:e.filter(r=>!sr(r)),Or=(e,t,r=Ln)=>{if(!r.allowed&&sr(e))throw r.reason==="agent-blocked"?new A({status:"refused",env:e,agentMode:_.source},2,{operation:t,remediation:'a human runs it from their own terminal \u2014 this project sets `protectedEnvs: "cli-only"`',stderrExcerpt:`"${e}" is withheld from agents in this project (protectedEnvs: "cli-only")`}):new g(void 0,{operation:t,remediation:`use \`infra-kit release deliver\` \u2014 it merges the release to main, opens the RC PR, deploys from main, and releases the Jira version. To allow ad-hoc deploys to "${e}" in this project, set \`protectedEnvs\` to "allow" or "cli-only" in infra-kit.json`,stderrExcerpt:`"${e}" is delivered, not deployed ad-hoc`})};var at=async()=>{let e;try{e=(await V()).protectedEnvs??"disallow"}catch{return Ln}return e==="disallow"?Ln:e==="cli-only"&&ee()?{allowed:!1,reason:"agent-blocked"}:{allowed:!0,reason:"allowed"}};var ms=e=>{let{env:t,branch:r}=e;sr(t)&&d.warn([`\u26A0\uFE0F "${t}" is a delivery target \u2014 this project allows dispatching to it directly, but this is NOT the delivery flow.`,`Dispatching from "${r}" ships ${t} from a ref that is not merged to main, and skips:`," \u2022 the squash-merge of the release branch into main"," \u2022 the RC pull request"," \u2022 the Jira fix-version release","Run `infra-kit release deliver` instead if you want those."].join(`
|
|
366
|
+
`))};import qy from"node:fs/promises";import qu from"node:path";import FC from"yaml";var Yy=".github/workflows",Nt=async e=>{let t=await $();return zy(qu.resolve(t,Yy,e))},Yu=async()=>{let e=await $(),t=qu.resolve(e,Yy),r;try{r=await qy.readdir(t)}catch{return[]}let n=r.filter(s=>s.endsWith(".yml")||s.endsWith(".yaml")).sort(),o=await Promise.all(n.map(s=>zy(qu.resolve(t,s))));return[...new Set(o.flat())]},zy=async e=>{let t;try{t=FC.parse(await qy.readFile(e,"utf-8"))}catch{return[]}let r=Un(t,"on")??Un(t,"true"),n=Un(Un(Un(Un(r,"workflow_dispatch"),"inputs"),"environment"),"options");return Array.isArray(n)?n.filter(o=>typeof o=="string"&&o.length>0):[]},Un=(e,t)=>{if(!(typeof e!="object"||e===null||Array.isArray(e)))return e[t]};var ir=async()=>{let e=await Yu(),t=await me(),r=e.map(s=>({env:s,source:"gh-workflow"})),n=new Set(e),o=Object.keys(t?.envs??{}).filter(s=>!n.has(s)).sort().map(s=>({env:s,source:"token-only"}));return[...r,...o]},Dr=async()=>(await ir()).map(t=>t.env);import{$ as HC}from"zx";import gs from"node:process";var LC="x-seraph-loginreason",BC="AUTHENTICATED_FAILED",UC=(e,t=160)=>{let r=e.split(`
|
|
367
|
+
`,1)[0].trim();return r.length>t?`${r.slice(0,t)}\u2026`:r},Zy=(e,t)=>t===BC||e===401?"auth":e===403?"forbidden":e===404?"not-found-or-forbidden":"other",Xy=(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}`,Vn=class extends Error{status;kind;body;context;constructor(t){let r=Zy(t.status,t.seraphLoginReason),n=UC(t.body);super(n===""?`${t.context}: ${Xy(r,t.status)}`:`${t.context}: ${Xy(r,t.status)}. Jira said: ${n}`),this.name="JiraApiError",this.status=t.status,this.kind=r,this.body=t.body,this.context=t.context}},fs=e=>e instanceof Vn,Qy=e=>e.headers.get(LC);var Wn=async(e,t)=>{if(e.ok)return;let r=await e.text(),n=new Vn({status:e.status,seraphLoginReason:Qy(e),body:r,context:t});throw d.debug({status:e.status,kind:n.kind,body:r},t),n},Ir=(e,t)=>`${e.baseUrl}/projects/${t.projectId}/versions/${t.id}/tab/release-report-all-issues`,zu=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 Wn(l,"Failed to create Jira version"),{success:!0,version:await l.json()}},Gn=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 Wn(a,"Failed to get Jira project versions"),await a.json()},Mt=async(e,t)=>(await Gn(t)).find(o=>o.name===e)||null,Jn=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 Wn(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}},Xu=async(e,t)=>{let{versionName:r}=e,n=await Mt(r,t);if(!n)throw new Error(`Version "${r}" not found in Jira project`);return await Jn({versionId:n.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},t)},Kn=async()=>{let e=gs.env.JIRA_BASE_URL,t=gs.env.JIRA_TOKEN||gs.env.JIRA_API_TOKEN,r=gs.env.JIRA_PROJECT_ID,n=gs.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(`
|
|
368
|
+
`);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}},jt=async()=>{try{return await Kn()}catch(e){return d.warn({err:e},"Jira configuration not available, skipping Jira integration"),null}};var Ea=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 Wn(a,"Failed to get Jira version issue counts");let c=await a.json();return{issuesFixedCount:c.issuesFixedCount,issuesAffectedCount:c.issuesAffectedCount}},Zu=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 Wn(c,"Failed to remove Jira version")};import{z as ev}from"zod";var tv=/^\d{4}-\d{2}-\d{2}$/,hs=e=>{if(!tv.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},rv=e=>`Release date "${e}" is not a calendar date in yyyy-mm-dd form.`,Hn=class extends Error{constructor(t){super(rv(t)),this.name="InvalidReleaseDateError"}},_r=e=>{let t=e.trim();if(!hs(t))throw new Hn(t);return t},ys=e=>{let t=e.trim();return t===""||hs(t)?!0:rv(t)},Qu=ev.string().refine(hs,{message:"Expected a calendar date in yyyy-mm-dd form."}),ed=ev.string().refine(e=>e===""||hs(e),{message:'Expected a calendar date in yyyy-mm-dd form, or "" to clear.'});var ar=e=>e.slice(1).split(".").map(Number),qn=e=>[...e].sort((t,r)=>{let[n,o,s]=ar(t),[i,a,c]=ar(r);return n!==i?(n??0)-(i??0):o!==a?(o??0)-(a??0):(s??0)-(c??0)});var ov="next",VC=/^v?(\d+)\.(\d+)\.(\d+)$/,WC=e=>e.replace(/^.*release\//,""),td=e=>{let t=WC(e.trim()),r=VC.exec(t);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null},nv=e=>`${e[0]}.${e[1]}.${e[2]}`,rd=e=>{let t=[...e.remoteBranches??[],...e.jiraVersions??[]],r=[],n=new Set;for(let o of t){let s=td(o);if(!s)continue;let i=nv(s);n.has(i)||(n.add(i),r.push(s))}return qn(r.map(o=>nv(o))).map(o=>ar(`v${o}`))},Nr=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},nd=(e,t)=>{if(e.length===0)throw new Nr;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`},Yn=(e,t)=>{try{return nd(e,t)}catch(r){if(r instanceof Nr)return null;throw r}},od=e=>e.trim().toLowerCase()===ov,xa=e=>od(e)||td(e)!==null?{version:e}:{name:e},GC=e=>e==="regular"||e==="hotfix",sv=e=>"name"in e,JC=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:_r(n)}},sd=e=>{let t=e.trim();if(t==="")throw new Error("Release spec is empty");let r=t.indexOf(":"),{token:n,releaseDate:o}=JC(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 Pa({...xa(n),type:s},{description:i,releaseDate:o})},id=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},Pa=(e,t)=>{let{description:r,releaseDate:n}=t;return{...e,...r!==void 0&&r!==""?{description:r}:{},...n===void 0?{}:{releaseDate:n}}},KC=e=>{let t=e.name.trim();return Ci(t),Pa({id:{kind:"name",name:t,raw:t},type:e.type},e)},ad=(e,t)=>{let r=[...t];return e.map(n=>{if(sv(n))return KC(n);let o=n.version.trim();if(o==="")throw new Error("Release entry has an empty version");if(od(o)){let a=nd(r,n.type);return r.push(ar(`v${a}`)),Pa({id:Re(a),type:n.type},n)}let s=td(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),Pa({id:Re(i),type:n.type},n)})},cd=e=>e.some(t=>!sv(t)&&od(t.version));var qC=e=>e.split(`
|
|
369
|
+
`).map(t=>{let r=t.indexOf(" ");return r===-1?null:te(t.slice(r+1))}).filter(t=>t!==null&&t.kind==="version").map(t=>t.raw),YC=async()=>{let e=await HC({quiet:!0})`git ls-remote --heads origin 'release/v*'`;return qC(e.stdout)},zC=async()=>{let e=await jt();return e?(await Gn(e)).map(r=>r.name):[]},vs=async()=>{let[e,t]=await Promise.allSettled([YC(),zC()]);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"),rd({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:t.status==="fulfilled"?t.value:[]})};import XC from"node:fs";import ZC from"node:path";var ld=[".claude/settings.json",".claude/settings.local.json"],QC=["infra-kit","ik","pnpm exec infra-kit","pnpm exec ik","pnpm infra-kit"],e$=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t$=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},r$=(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(e$).join(".*")}$`,"s").test(t)||n===t||n.startsWith(`${t} `)},n$=e=>{let t=e.groupPath.join(" ");return t===e.cliName?[t]:[t,e.cliName]},o$=(e,t)=>{let r=t$(e);return r===null?[]:t.filter(n=>n.mutating).filter(n=>QC.some(o=>n$(n).some(s=>r$(r,`${o} ${s}`)))).map(n=>n.groupPath.join(" "))},s$=(e,t)=>{let r;try{r=XC.readFileSync(ZC.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}},iv=(e,t)=>{let r={present:[],unreadable:[],hits:[]};for(let n of ld){let o=s$(e,n);if(o.kind!=="absent"){if(r.present.push(n),o.kind==="unreadable"){r.unreadable.push(n);continue}for(let s of o.patterns){let i=o$(s,t);i.length>0&&r.hits.push({file:n,pattern:s,commands:i})}}}return r};var a$=e=>e.every(t=>t.status!=="fail"),c$=["brew","git","gh","doppler","aws"],l$=async e=>{let t=await os(c$,e);return new Map(t.map(r=>[r.id,{manager:r.manager,version:r.version,present:r.present,onPath:r.onPath}]))},Ft=async(e,t,r,n)=>{try{return await Cn()`${t}`,{name:e,status:"pass",message:r}}catch{return{name:e,status:"fail",message:n}}},u$=async()=>{let e="orca installed",t=await Zt();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)"}},hv=(e,t,r,n)=>{let o=Ze.join(i$.homedir(),t),s="Run: infra-kit setup --skip-tools";if(!Oe.existsSync(o))return{name:e,status:"fail",message:`~/${t} not found. ${s}`};let i=Oe.readFileSync(o,"utf-8"),a=i.indexOf(Ar),c=i.indexOf(nr);return a===-1||c===-1||c<a?{name:e,status:"fail",message:`infra-kit ${r} block missing from ~/${t}. ${s}`}:i.slice(a,c+nr.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`}},d$=()=>hv("zshrc init block",".zshrc","shell",Hy()),p$=()=>hv("zshenv session block",".zshenv","session-env",Ju()),m$=async()=>{let e="pnpm enableGlobalVirtualStore";try{let t=await $(),r=Ze.join(t,"pnpm-workspace.yaml");if(!Oe.existsSync(r))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${r}`};let n=Oe.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}`}}},f$=async()=>{try{return Yt(),{config:await V(),error:null}}catch(e){return{config:null,error:e}}},g$=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)"}},h$=384,ud=448,y$=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(", "),v$=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}}})),w$=async(e,t={})=>{let r="env tokens configured",n=t.readStore??me,o=t.resolveToken??ul;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 v$(await Dr(),o);return{name:r,status:"pass",message:y$(s)}},k$=()=>ks.env[Ae]||void 0,b$=async(e={})=>{let t="tokens.json present",r=e.readStore??me,n=e.storePath??Xt;if((e.readEnvToken??k$)())return{name:t,status:"skip",message:`${Ae} 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 ${Ae} instead.`}}return{name:t,status:"pass",message:`${s} holds ${a.length} token(s): ${a.join(", ")}`}},ws=(e,t)=>{let r=t(e);return r===null?null:r.mode&511},R$=async(e,t={})=>{let r="tokens.json perms",n=t.storePath??Xt,o=t.statPath??S$,s=t.chmodPath??Oe.chmodSync,i;try{i=await n()}catch{return{name:r,status:"skip",message:"the token store path could not be resolved"}}if(ws(i,o)===null)return{name:r,status:"skip",message:`No store to protect at ${w(i)} (see tokens.json present)`};let a=Ze.dirname(i),c=Ze.dirname(a),l=Ze.dirname(c),p=[{target:l,expected:ud,actual:ws(l,o)},{target:c,expected:ud,actual:ws(c,o)},{target:a,expected:ud,actual:ws(a,o)},{target:i,expected:h$,actual:ws(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 ${av(f.actual)}, expected ${av(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}`}},av=e=>`0${e.toString(8).padStart(3,"0")}`,S$=e=>{try{return Oe.statSync(e)}catch{return null}},E$=async()=>{let e="user override path";try{let t=await z(),r=Oe.existsSync(t.userProject),n=await es(t.userProject,r),o=r?ts(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}}},P$=async()=>{let e="legacy user-global config",t;try{t=await z()}catch{return{name:e,status:"skip",message:"infra-kit config paths could not be resolved"}}let r=Ze.join(Ze.dirname(t.userGlobal),"config.json");return Oe.existsSync(r)?Oe.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"}},cv=/^\d+\.\d+\.\d+$/,lv=(e,t)=>e===t||!cv.test(e)||!cv.test(t)?!1:qn([`v${e}`,`v${t}`])[0]===`v${e}`,x$=async e=>{let t;try{t=await Pe(e)}catch{return[]}return t.flatMap(r=>{let n=Ot(gt(Ze.join(r,"CLAUDE.md")));return n.state==="ok"&&n.version!==void 0?[n.version]:[]})},uv=e=>qn(e.map(t=>`v${t}`)).map(t=>t.slice(1)),T$=async(e,t,r)=>{let n="Guidance version",o=Sr(t,Er),s=await x$(e),a=(o===null?s:[o,...s]).filter(p=>Ct(p,r));if(a.length>0){let p=uv(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&&lv(o,r),l=s.filter(p=>lv(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 ${uv(l)[0]}, current ${r}) \u2014 run: infra-kit audit --fix --all`]:[]];return{name:n,status:"warn",message:u.join("; ")}},C$=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 z()).main}catch{return e}if(!Oe.existsSync(t))return e;let r=Ze.dirname(t),n=Ze.join(r,"CLAUDE.md"),o=Oe.existsSync(n)?Oe.readFileSync(n,"utf-8"):"",s=He(o,xe,Me);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 T$(r,o,U.version)]},$$=async()=>{try{let e=(await z()).main;return Oe.existsSync(e)?Ze.dirname(e):null}catch{return null}},A$=e=>{let t=fg();return t===null||!Ct(t,e)?"":` \u2014 plugin ${t} is fetched but not applied. Run: ${yn}`},O$=e=>{let t=e.kind==="installed"?_i(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 ${X} version ${t}${A$(t)}`}},dv=3,pv=(e,t)=>be(e)===be(t),D$=e=>{if(e===void 0||e.gitRoot===null)return"";let t=w(e.gitRoot);if(e.projectDir!==null){if(pv(e.projectDir,e.gitRoot))return"";let r=rn(e.gitRoot,be(e.projectDir),be)?"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 pv(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}`},I$=(e,t)=>{let r="plugin installed",n=D$(t);if(e.kind==="installed"){let{scope:c,projectPath:l}=e.installation,u=l===null?"":`, ${w(l)}`;return{name:r,status:"pass",message:`Plugin ${X} installed (${c??"unknown"} scope${u})${n}`}}if(e.kind==="absent")return{name:r,status:"fail",message:`Plugin ${X} is not installed. Run: ${Dt}${n}`};let o=e.installations.map(c=>c.projectPath===null?"(unnamed project)":w(c.projectPath)),s=o.length-dv,i=s>0?` and ${s} more`:"",a=`${o.slice(0,dv).join(", ")}${i}`;return{name:r,status:"fail",message:`Plugin ${X} is installed for ${a} only, not this project. Run: ${Dt}${n}`}},_$=()=>Ft("claude CLI",["claude","--version"],"Installed: claude","claude CLI not found on PATH \u2014 `infra-kit setup` cannot install the plugin; install Claude Code first");var N$=(e,...t)=>{try{return JSON.parse(Oe.readFileSync(Ze.join(e,...t),"utf-8"))}catch{return null}},M$=e=>{if(e.kind!=="installed")return{kind:"not-installed"};let t=_i(e.installation),{installPath:r}=e.installation;if(r===null)return{kind:"skills-only",version:t};let n=N$(r,Ye),o=n!==null&&typeof n=="object"?n[ht]:void 0;return o==null||typeof o!="object"?{kind:"skills-only",version:t}:{kind:"stale-server",version:t,keys:Object.keys(o)}},mv=e=>`Plugin ${X} ${e===null?"(version unreadable)":e}`,j$=e=>{let t="plugin MCP server";if(e.kind==="not-installed")return{name:t,status:"fail",message:`No infra-kit plugin installed for this project \u2014 no skills to drive the CLI. Run: ${Dt}`};if(e.kind==="stale-server"){let r=e.keys.length===0?"":` (under "${e.keys.join('", "')}")`;return{name:t,status:"pass",message:`${mv(e.version)} still carries an MCP server in its ${Ye}${r} \u2014 a copy from before the plugin went skills-only. Update it: infra-kit setup (or ${yn}), then restart Claude Code`}}return{name:t,status:"pass",message:`${mv(e.version)} is skills-only \u2014 no ${Ye}, as shipped; the /infra-kit:* skills drive the infra-kit CLI`}},F$=(e,t)=>{let r=kr(e===null?{}:{projectPath:e}),n=Po();return[{name:"marketplace registered",status:n?"pass":"fail",message:n?`Marketplace ${pe} is known to Claude Code`:`Marketplace ${pe} is not registered. Run: claude plugin marketplace add ${zt}`},I$(r,t),O$(r),j$(M$(r)),{name:"CLI version",status:"pass",message:`infra-kit CLI ${U.version}`}]},L$=(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(Pn())}, or run: infra-kit setup`}},B$=({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(", ")},U$=e=>{let t="Agent mode",r=Ti(e),n=B$(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})`}},fv=4,V$=e=>{let t=e.slice(0,fv).join(", "),r=e.length-fv;return r>0?`${t} +${r} more`:t},W$=(e,t)=>{let r="Agent allowlist",{present:n,unreadable:o,hits:s}=iv(e,t);if(s.length>0){let i=s.map(a=>`${a.file} allows "${a.pattern}", which reaches ${a.commands.length} mutating infra-kit command${a.commands.length===1?"":"s"} (${V$(a.commands)})`);return{name:r,status:"warn",message:`${i.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 o.length>0?{name:r,status:"warn",message:`Could not read permissions.allow from ${o.join(" and ")} \u2014 fix the JSON and re-run; until then the allowlist is unchecked`}:n.length===0?{name:r,status:"pass",message:`no ${ld.join(" or ")} at the repo root \u2014 no Bash allow pattern to reach a mutating infra-kit command`}:{name:r,status:"pass",message:`no permissions.allow pattern in ${n.join(" or ")} reaches a mutating infra-kit command`}},G$=(e,t)=>e===null?{name:"Agent allowlist",status:"skip",message:"no git root"}:t===void 0?{name:"Agent allowlist",status:"skip",message:"no command catalog supplied"}:W$(e,t),J$=(e,t)=>{let r=Math.floor((t-Date.parse(e))/36e5);return Number.isNaN(r)?"age unknown":r>=24?`${Math.floor(r/24)}d old`:`${Math.max(r,0)}h old`},K$=async(e,t=Date.now())=>{let r="merge-dev resolutions";if(e===null)return{name:r,status:"skip",message:"no git root"};let n;try{n=await Hu(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} (${J$(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`}},yv=e=>Xc(["trust"],{bin:e}),H$=new Set(["SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"]),gv="ERR_TLS_CERT_ALTNAME_INVALID",vv=()=>`portless serving TLS on :${qt}`,q$=async(e,t,r)=>{let n=vv();return await e(qt,!0)?{name:n,status:"pass",message:`portless is serving HTTPS on :${qt}`}:{name:n,status:"fail",message:`No portless daemon is serving HTTPS on :${qt}. Install it once (needs root): \`${Tt(t,r)}\`.`}},Y$=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(qt,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(gv)?{name:s,status:"fail",message:`Internal check error: the TLS probe got ${gv} 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=>H$.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 \`${yv(n)}\`, or reinstall: \`${Tt(n,o)}\`.`}:{name:s,status:"fail",message:`TLS handshake failed (${l.join(", ")})`}},z$=(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: \`${yv(r)}\` (no sudo needed).`}},X$=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 \`${Xc(["alias","--remove","<name>"],{bin:r})}\`.`}},Z$=()=>[Sn,It,vv(),"portless CA chain valid","portless CA trusted","portless routes"],Q$=async(e={})=>{let t=e.resolveBin??$f,r=e.isProxyServing??_f,n=e.handshake??Ff,o=e.caTrusted??jf,s=e.routes??bo,i=e.isListening??ko,a=(e.caPath??Mf)(),c=t();if(c===null)return[{name:"portless installed",status:"fail",message:"portless is not resolvable from node_modules \u2014 run `pnpm install`."},...Z$().map(b=>({name:b,status:"skip",message:"portless not resolvable"}))];let l={name:"portless installed",status:"pass",message:"portless is resolvable from node_modules"},{seams:u,node:p}=Pu(e,c),m=s(),f=await q$(r,c,u),h=f.status==="fail"?{name:"portless CA chain valid",status:"skip",message:"no daemon to handshake with"}:await Y$(n,m,a,c,u);return[l,p,(await xu(u)).row,f,h,z$(o(),a,c),await X$(m,i,c)]},eA=async(e={})=>{let t="portless routes",r=e.routes??bo,n=e.isListening??ko,o=e.devSessionRunning??qh,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}=Hh(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??Lf().removeAlias;for(let u of a)await l(u);return{name:t,status:"pass",message:`Removed ${a.length} stale portless route(s): ${a.join(", ")}`}},Ta=async(e={})=>{let t=await f$(),r=l$(e.probeDeps??rs()),n=async(m,f)=>{let[h,b]=await Promise.all([f,r]),C=b.get(m);return C===void 0?h:{...h,detail:C}},o=await Promise.all([n("brew",Ft("brew installed",ze("brew").probeArgv,"Homebrew is installed","Homebrew is not installed. Install from: https://brew.sh/")),n("git",Ft("git installed",ze("git").probeArgv,"git is installed","git is not installed. Install with: brew install git")),n("gh",Ft("gh installed",ze("gh").probeArgv,"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/")),Ft("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),n("doppler",Ft("doppler installed",ze("doppler").probeArgv,"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli")),n("aws",Ft("aws installed",ze("aws").probeArgv,"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html")),Ft("package manager installed",["pnpm","--version"],"Installed: pnpm","pnpm is not installed. Install from: https://pnpm.io/installation"),Ft("typescript-language-server installed",["typescript-language-server","--version"],"typescript-language-server is installed","typescript-language-server is not installed. Install from: https://github.com/typescript-language-server/typescript-language-server#installing"),u$(),Promise.resolve(d$()),Promise.resolve(p$()),m$(),Promise.resolve(g$(t)),b$(),w$(t),R$(e.fix??!1),E$(),P$()]),s=await Q$(e.portlessDeps);if(e.fix){let m=await eA(),f=s.findIndex(h=>h.name===m.name);f>=0?s[f]=m:s.push(m)}let i=await $$(),a=await Rn(),c={projectDir:ks.env.CLAUDE_PROJECT_DIR||null,cwd:ks.cwd(),gitRoot:a},l=[await _$(),...F$(i,c),Qo(),U$({env:ks.env,stdinIsTTY:ks.stdin.isTTY===!0,flag:_.source==="flag"}),G$(a,e.catalog)],u=[...o,await K$(a),...s,...await C$(),...l,L$(xn(),U.version)],p={checks:u.map(m=>({name:m.name,status:m.status,message:m.message,fixable:Su.has(m.name),detail:m.detail})),allPassed:a$(u),cliVersion:U.version};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}},dd=T({name:"doctor",description:"Check installation and authentication status of gh, doppler, and aws CLIs. Read-only: a row marked fixable is one `infra-kit doctor --fix` repairs, and that flag is not reachable from this boundary \u2014 report such a row to the human instead.",inputSchema:{},outputSchema:{checks:Fe.array(Fe.object({name:Fe.string().describe("Name of the check"),status:Fe.enum(["pass","fail","warn","skip"]).describe("Check result; warn is advisory and never fails the run; skip is not evaluated; the message says why; never a failure"),message:Fe.string().describe("Details about the check result"),fixable:Fe.boolean().describe("Whether `infra-kit doctor --fix` repairs this row"),detail:Fe.object({manager:Fe.string().describe("Which package manager owns this install, read from its resolved path"),version:Fe.string().nullable().describe("The version the tool reported, or null"),present:Fe.boolean().describe("The tool is installed somewhere findable \u2014 on PATH or not"),onPath:Fe.boolean().describe("The binary resolves on PATH")}).optional().describe("Probe facts about an external dependency. Never a fix: no action, no commands")})).describe("List of all check results"),allPassed:Fe.boolean().describe("Whether no check failed (warnings and skips do not count)"),cliVersion:Fe.string().describe("Version of the infra-kit CLI that produced this report")},handler:()=>Ta()});import{E2E_MODE_ENV as CA}from"@slip-stream-kit/config/internal";import wd from"node:fs";import $A from"node:os";import Rs from"node:path";import Aa from"node:process";import{z as E}from"zod";var kt=(e,t,r)=>new A({status:"refused",reason:e,...t},2,r);import{describeProxyRoutes as tA,loadDev as rA,readAppAliasName as nA,readCloudOrigin as oA,readLocalContext as kv}from"@slip-stream-kit/config/internal";import wv from"node:fs";import Mr from"node:path";import Ca from"node:process";import{z as pd}from"zod";var sA=async e=>{let t=Mr.join(e,"apps"),r=wv.existsSync(t)?wv.readdirSync(t).toSorted():[],n=[];for(let o of r){let s=Mr.join(t,o,"tests"),a=(await ft(s))?.e2e;a?.target!==void 0&&n.push({app:o,testsDir:s,e2e:{target:a.target}})}return n},iA=(e,t)=>{let[r,n]=Mr.relative(e,t).split(Mr.sep);return r==="apps"&&n?n:void 0},aA=(e,t,r,n)=>{let o=c=>e.find(l=>l.app===c),s=o(t)??(t===void 0?o(iA(n,r)):void 0);if(s)return s;if(t===void 0&&e.length===1)return e[0];let i=e.map(c=>c.app);if(i.length===0)throw new g(void 0,{operation:"find an e2e package",remediation:"declare `e2e: { target }` in `apps/<app>/tests/infra-kit.config.ts` (see the `InfraKitE2e` type)",stderrExcerpt:`no apps/*/tests package under ${n} declares an e2e block`});let a="app";throw new A({status:"argument_required",argument:a,choices:pd.toJSONSchema(pd.object({app:pd.enum(i)})),agentMode:_.source},2,{operation:"pick the e2e package to run",remediation:`pass --app ${i.join("|")}`,stderrExcerpt:t===void 0?"more than one app has e2e tests":`"${t}" has no e2e block; e2e apps: ${i.join(", ")}`})},cA=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}})),lA=e=>Yo(e).apps.find(t=>t.env!=="")?.env??null,md=async(e,t={})=>{let r=t.cwd??Ca.cwd(),n=t.projectRoot??await $(),o=(t.env??Ca.env)[Jt]||null,s=t.healthProbe??vl,i=aA(await sA(n),e,r,n),{target:a}=i.e2e,[c,l]=a.split("/"),u=Mr.join(n,"apps",c,l),p=(await Rr(u)).name,m=(await ft(u))?.deployedUrlEnv??null;if(!p)throw new g(void 0,{operation:`resolve e2e target ${a}`,remediation:`check \`e2e.target\` in ${Mr.join(i.testsDir,"infra-kit.config.ts")}`,stderrExcerpt:`${u} has no package.json name`});let f=Og(u),h=nA(p,u),b=`${h}.localhost`,C=`https://${b}`,k=0;if(l==="ui")k=(t.listRoutes??bo)().find(S=>S.name===b||S.name===h)?.port??0;else{let S=kv(u).info.get(p);k=S?.port??0,C=S?.origin??C}let F=k>0&&await s({tag:a,port:k,kind:l})==="ok",v=F?lA(u):null;return{app:i.app,testsDir:i.testsDir,target:a,kind:l,targetDir:u,packageName:p,deployedUrlEnv:m,release:f,env:o,servedEnv:v,localUrl:C,served:F}},bv=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}},fd=async(e,t={})=>{let r=t.healthProbe??vl,n=kv(e.targetDir),o=e.kind==="ui"?await rA(e.targetDir):void 0,s=o?.proxy?tA({proxy:o.proxy,localContext:n,env:e.env??void 0,cloud:oA(e.deployedUrlEnv??void 0,t.env??Ca.env),getRelease:()=>e.release}):[],i=new Map([...n.info].map(([a,c])=>[a,c.port]));return{...bv(e),mode:"local",baseUrl:e.localUrl,routes:await cA(s,i,r)}},gd=(e,t={})=>{let{env:r,deployedUrlEnv:n,target:o}=e;if(!n)throw kt("no_deployed_url_env",{target:o},{operation:`resolve the deployed app ${e.app}'s cloud e2e run targets`,remediation:`declare \`deployedUrlEnv: '<APP>_URL'\` in ${Mr.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??Ca.env)[n];if(!r||!s){let i=s?Jt:n;throw kt("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 ${Jt}, and ${i} is not set`})}return{...bv(e),mode:"cloud",baseUrl:s,routes:[]}};import uA from"node:fs";import dA from"node:path";import{stripVTControlCharacters as pA}from"node:util";import{z as M}from"zod";var Rv=2e3,Sv="--reporter=line,json",Ev=e=>({PLAYWRIGHT_JSON_OUTPUT_FILE:e,PLAYWRIGHT_JSON_OUTPUT_NAME:e}),Pv=e=>e.some(t=>t==="--reporter"||t.startsWith("--reporter=")),hd=M.object({message:M.string().optional()}),xv=M.object({type:M.string()}),mA=M.object({status:M.string(),retry:M.number(),error:hd.optional(),errors:M.array(hd).optional(),annotations:M.array(xv).optional(),attachments:M.array(M.object({name:M.string(),path:M.string().optional()})).optional()}),fA=M.object({projectName:M.string(),status:M.string(),expectedStatus:M.string().optional(),annotations:M.array(xv).optional(),results:M.array(mA)}),gA=M.object({title:M.string(),file:M.string(),line:M.number().optional(),tests:M.array(fA)}),Tv=M.lazy(()=>M.object({title:M.string(),specs:M.array(gA).optional(),suites:M.array(Tv).optional()})),hA=M.object({config:M.object({rootDir:M.string().optional()}).optional(),suites:M.array(Tv),errors:M.array(hd).optional(),stats:M.object({expected:M.number(),unexpected:M.number(),flaky:M.number(),skipped:M.number()})}),Cv=e=>{let t=pA(e);return t.length>Rv?`${t.slice(0,Rv)}\u2026`:t},yA=e=>{let t=e.error?.message??e.errors?.[0]?.message;return t===void 0?null:Cv(t)},vA=e=>e.status==="unexpected"||e.status==="flaky",wA=e=>{let t=new Map;for(let r of e)t.set(r.projectName,[...t.get(r.projectName)??[],r]);return t},kA=e=>new Set([...e.annotations??[],...e.results.flatMap(t=>t.annotations??[])].map(t=>t.type)),bA=(e,t)=>{let r=e.filter(vA),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?yA(o):"Expected to fail, but passed.",tracePath:o?.attachments?.find(i=>i.name==="trace")?.path??null}},RA=e=>{let t=hA.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(C=>[...kA(C)])),h=m.some(C=>C.expectedStatus==="failed");if(!h&&!f.has("fixme")&&!f.has("skip"))return;let b=a.get(p)??{file:p,fail:0,fixme:0,skip:0};h&&(b.fail+=1),f.has("fixme")?b.fixme+=1:f.has("skip")&&(b.skip+=1),a.set(p,b)},u=(p,m)=>{for(let f of p.specs??[]){let h=r?.rootDir?dA.resolve(r.rootDir,f.file):f.file,b=[...m,f.title].join(" \u203A ");l(h,f.tests);for(let[C,k]of wA(f.tests)){let F=bA(k,{title:b,file:h,line:f.line??null,project:C});F&&(F.runs>1&&F.failedRuns<F.runs&&(c+=1),i.push(F))}}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?[]:[Cv(p.message)])}},$v=e=>{try{return RA(JSON.parse(uA.readFileSync(e,"utf8")))}catch{return null}};import bs from"node:fs";import Ov from"node:path";import $a from"node:process";var SA=e=>Ov.join(e,"node_modules",".cache","infra-kit-e2e.lock"),EA=e=>{try{return $a.kill(e,0),!0}catch(t){return t.code==="EPERM"}},Av=(e,t)=>{try{return bs.writeFileSync(e,`${$a.pid}
|
|
370
|
+
${JSON.stringify({startedAt:Date.now(),command:t})}`,{flag:"wx"}),!0}catch(r){if(r.code==="EEXIST")return!1;throw r}},PA=e=>{try{let t=JSON.parse(e??"");return{...typeof t?.startedAt=="number"&&{startedAt:t.startedAt},...typeof t?.command=="string"&&{command:t.command}}}catch{return{}}},yd=e=>{try{let[t,r]=bs.readFileSync(e,"utf8").split(`
|
|
371
|
+
`),n=Number.parseInt(t,10);return Number.isInteger(n)&&n>0?{pid:n,...PA(r)}:null}catch{return null}},Dv=(e,t)=>{let r=SA(e);if(bs.mkdirSync(Ov.dirname(r),{recursive:!0}),!Av(r,t)){let n=yd(r);if(n!==null&&n.pid!==$a.pid&&EA(n.pid))return{holder:n};if(bs.rmSync(r,{force:!0}),!Av(r,t))return{holder:yd(r)??{pid:0}}}return{release:()=>{yd(r)?.pid===$a.pid&&bs.rmSync(r,{force:!0})}}};import{spawn as xA}from"node:child_process";import TA from"node:os";import vd from"node:process";var Iv=(e,t,r)=>new Promise((n,o)=>{let s=xA(e,t,r),i=vd.stdin.isTTY?["SIGTERM","SIGHUP"]:["SIGINT","SIGTERM","SIGHUP"],a=l=>{s.kill(l)},c=()=>{for(let l of i)vd.off(l,a)};for(let l of i)vd.on(l,a);s.once("error",l=>{c(),o(l)}),s.once("close",(l,u)=>{c(),n(l??(u?128+TA.constants.signals[u]:1))})});var AA=["playwright.config.ts","playwright.config.mts","playwright.config.js","playwright.config.mjs"],OA=e=>AA.some(t=>{try{return wd.readFileSync(Rs.join(e,t),"utf8").includes("infraKitE2e")}catch{return!1}}),kd=e=>`infra-kit dev ${e.target.split("/")[0]} --no-watch --reuse`,DA=(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(`
|
|
372
|
+
`)},IA=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 kt("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(", ")}`})},_A=async(e,t)=>{if(e.env===null||!sr(e.env))return;let r=await(t.protectedEnvAccess??at)();if(r.allowed)return;let n=`run ${e.app} e2e against "${e.env}"`;throw r.reason==="agent-blocked"?kt("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`}):kt("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`})},NA=e=>{if(!(e.servedEnv===null||e.servedEnv===e.env))throw kt("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"}"`})},MA=async(e,t)=>{if(e.served){NA(e);let p=await fd(e,t);return IA(p),p}if(!OA(e.testsDir))throw kt("no_dev_server",{devCommand:kd(e)},{operation:`run ${e.app} e2e locally`,remediation:`start it (\`${kd(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:[]}},jA=(e,t,r)=>Iv("pnpm",["exec","playwright","test",...t],{cwd:e.testsDir,env:{...Aa.env,...r,[CA]:e.mode},stdio:["inherit",Ht.enabled||H()?2:"inherit","inherit"]}),FA=(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:Rs.resolve(e.testsDir,s)}}let n=new Date().toISOString().replace(/[:.]/g,"-"),o=Rs.join(e.testsDir,"test-results",`ik-e2e-${n}-${Aa.pid}`);return{args:[...t,`--output=${o}`],outputDir:o}},LA=e=>{if(e.mode==="cloud")return()=>{};let t=Dv(e.testsDir,`ik e2e --app ${e.app}`);if("holder"in t){let{pid:r,startedAt:n,command:o}=t.holder,s=n===void 0?void 0:`${Math.floor((Date.now()-n)/1e3)}s`,i=[`pid ${r}`,s,o].filter(Boolean).join(", ");throw kt("run_in_progress",{pid:r,startedAt:n,command:o},{operation:`run ${e.app} e2e locally`,remediation:`wait for it to finish (or stop process ${r}), then re-run`,stderrExcerpt:`another local e2e run of ${e.app} (${i}) is using its dev server`})}return t.release},Oa=async(e,t={})=>{let r=await md(e.app,t),n=e.cloud?gd(r,t):await MA(r,t);d.info(DA(n,r.served)),n.mode==="cloud"&&await _A(n,t);let o={...n,served:r.served,devCommand:n.mode==="local"&&!r.served?kd(r):null,playwrightArgs:e.playwrightArgs??[]};if(e.dryRun)return Rd({...o,ran:!1,exitCode:null,...bd});n.mode==="cloud"&&await q(e.yes,`Run ${n.app} e2e against ${n.baseUrl} ("${n.env}", shared)?`,{plan:o});let s=LA(n);try{return await BA(o,t.runPlaywright??jA)}finally{s()}},BA=async(e,t)=>{if(!H()||Pv(e.playwrightArgs)){let i=await t(e,e.playwrightArgs,{});return i!==0&&(Aa.exitCode=i),Rd({...e,ran:!0,exitCode:i,...bd,report:H()?"caller-reporter":"off"})}let{args:r,outputDir:n}=FA(e,e.playwrightArgs),o=wd.mkdtempSync(Rs.join($A.tmpdir(),"ik-e2e-report-")),s=Rs.join(o,"report.json");try{let i=await t(e,[Sv,...r],Ev(s));i!==0&&(Aa.exitCode=i);let a=$v(s);return Rd({...e,ran:!0,exitCode:i,...a?{report:"collected",...a}:{...bd,report:"unavailable"},outputDir:n})}finally{wd.rmSync(o,{recursive:!0,force:!0})}},bd={report:"off",outputDir:null,summary:null,failures:[],annotated:[],errors:[]},Rd=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),UA={app:E.string(),testsDir:E.string(),target:E.string().describe("The package under test, `<app>/ui` or `<app>/api`."),packageName:E.string(),mode:E.enum(["local","cloud"]).describe("local (default): this worktree\u2019s dev server. cloud (--cloud): the deployed app at env."),baseUrl:E.string().describe("The URL the run was pointed at: the local alias, or the deployed URL."),deployedUrlEnv:E.string().nullable().describe("The target\u2019s variable holding its deployed URL; a cloud run reads it. Null when it declares none."),release:E.string().describe("This worktree\u2019s release slug \u2014 the first label of every local alias."),env:E.string().nullable().describe("INFRA_KIT_ENV of this process; the env a cloud run targets."),servedEnv:E.string().nullable().describe("Served local runs: the INFRA_KIT_ENV the running dev session recorded \u2014 where its cloud routes go. Null when nothing served the target or the session recorded none. A local run refuses when it differs from env."),localUrl:E.string().describe("This worktree\u2019s address for the target, whether or not anything serves it."),served:E.boolean().describe("Whether this worktree\u2019s dev server already served the target when the run began."),devCommand:E.string().nullable().describe("Local runs with nothing served: the dev command the Playwright config starts, and stops after."),routes:E.array(E.object({path:E.string(),packageName:E.string(),source:E.enum(["local","cloud"]),target:E.string().nullable(),live:E.boolean().nullable()})).describe("Served local UI runs only: the dev proxy\u2019s route-by-route local/cloud split, local backends probed."),playwrightArgs:E.array(E.string()),ran:E.boolean().describe("False for --dry-run."),exitCode:E.number().nullable().describe("Playwright\u2019s exit code; null when it did not run."),report:E.enum(["off","caller-reporter","unavailable","collected"]).describe("Per-test results: collected from Playwright\u2019s JSON reporter under --json/agent mode; caller-reporter when playwrightArgs carried its own --reporter; unavailable when the run wrote no readable report; off otherwise."),outputDir:E.string().nullable().describe("Where this run\u2019s traces and attachments live \u2014 its own directory, so a later run cannot delete them. Null unless report is collected or unavailable."),summary:E.object({expected:E.number(),unexpected:E.number(),flaky:E.number(),skipped:E.number(),repeatFlaky:E.number()}).nullable().describe("Playwright\u2019s counts by outcome, one per run (each --repeat-each repeat counts), plus repeatFlaky: tests that passed in some repeats and failed in others. Null unless report is collected."),failures:E.array(E.object({title:E.string().describe("Describe path and test title, joined with \u203A."),file:E.string(),line:E.number().nullable(),project:E.string(),status:E.enum(["unexpected","flaky"]).describe("flaky: failed, then passed on a retry or in another --repeat-each repeat."),retry:E.number().describe("The retry index of the failed attempt reported here."),runs:E.number().describe("How many times the test ran in this project \u2014 its --repeat-each repeats."),failedRuns:E.number().describe("How many of those runs failed."),error:E.string().nullable().describe("The failure message, ANSI stripped, truncated to 2000 characters."),tracePath:E.string().nullable().describe("The failed attempt\u2019s trace.zip; open with `playwright show-trace`.")})).describe("One entry per test and project that failed, needed a retry, or failed in some repeat; empty unless report is collected."),annotated:E.array(E.object({file:E.string(),fail:E.number().describe("test.fail \u2014 green only while the bug it registers exists."),fixme:E.number().describe("test.fixme \u2014 skipped as unfinished."),skip:E.number().describe("test.skip, declared or called at runtime, conditional ones included.")})).describe("Per spec file, the tests that passed or skipped while asserting little, as Playwright ran them; empty unless report is collected."),errors:E.array(E.string()).describe("Run-level errors with no test to blame (config, global setup, a spec that fails to import), ANSI stripped and truncated; empty unless report is collected.")},Sd=T({name:"e2e",description:"Run an app\u2019s Playwright e2e suite against this worktree: the running dev server, or one the package\u2019s infraKitE2e() Playwright config starts and stops. cloud runs against the deployed app at INFRA_KIT_ENV instead, confirm-gated; a protected env (prod) follows protectedEnvs. dryRun reports the target without running.",requiresHumanConfirm:!0,inputSchema:{app:E.string().optional().describe("App folder with an apps/<app>/tests e2e package; inferred from cwd when omitted."),dryRun:E.boolean().optional(),yes:E.boolean().optional(),cloud:E.boolean().optional().describe("Run against the deployed app at INFRA_KIT_ENV instead of this worktree."),playwrightArgs:E.array(E.string()).optional().describe("Passed to `playwright test` verbatim \u2014 a spec path, `--grep <title>`, `--project=chromium`.")},outputSchema:UA,handler:e=>Oa(e)});import Da from"node:fs";import Ed from"node:path";import{z as Ss}from"zod";var VA=e=>[...e.map(t=>`unset ${t}`),`unset ${Jt}`,`unset ${Zr}`,`unset ${Qr}`,`unset ${bi}`,`unset ${en}`],Ia=async()=>{let e=Kt(),t=Ed.join(e,Gt);if(!Da.existsSync(t))throw new Error("No loaded environment found. Run `env-load` first.");let r=Ri(t),n=VA(r),o=Ed.resolve(e,ki);Da.mkdirSync(e,{recursive:!0,mode:448}),ot(o,`${n.join(`
|
|
375
373
|
`)}
|
|
376
|
-
`,384),
|
|
374
|
+
`,384),Da.rmSync(t,{force:!0}),Da.rmSync(Ed.join(e,Xr),{force:!0});let s={filePath:o,variableCount:r.length,unsetStatements:n};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}},Pd=T({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:Ss.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{filePath:Ss.string().describe("Path to the file that must be sourced to apply"),variableCount:Ss.number().describe("Number of variables cleared"),unsetStatements:Ss.array(Ss.string()).describe("Unset statements generated")},handler:()=>Ia()});import WA from"node:process";import{z as Lt}from"zod";var _v=["Environment","Source","Token"],GA=e=>{let t=e.map(s=>[s.env,s.source,s.hasToken?"set":"not set"]),r=_v.map((s,i)=>Math.max(s.length,...t.map(a=>(a[i]??"").length))),n=s=>s.map((i,a)=>i.padEnd(r[a]??0)).join(" | ").trimEnd(),o=r.map(s=>"\u2500".repeat(s)).join("\u2500\u253C\u2500");return["Environments:","",n(_v),o,...t.map(n)]},_a=async()=>{let e=await Ke(),t=await ir(),r=await me(),n=WA.env[Ae],o=await ds(),s=Ni(t,r?.envs??{},n);if(d.info(`Doppler project: ${e}`),d.info(`Default env: ${o??"none \u2014 set one with `infra-kit config-set defaultEnv <env>`"}
|
|
375
|
+
`),s.length===0)return d.info("No environments found."),d.info(" Declare them in a workflow's `workflow_dispatch` `environment.options`,"),d.info(" or add a token for one manually."),Nv({project:e,defaultEnv:o,envs:s});for(let i of GA(s))d.info(i);return Nv({project:e,defaultEnv:o,envs:s})},Nv=({project:e,defaultEnv:t,envs:r})=>{let n={project:e,defaultEnv:t,configs:r.map(o=>o.env),tokens:r};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},xd=T({name:"env-list",description:"List the environments this project has. The list is the union of two local sources: every environment declared in a GitHub workflow's `workflow_dispatch` `environment.options` (source `gh-workflow`), and every environment the local token store holds a token for (source `token-only`). Not a live fetch from Doppler \u2014 a Doppler service token is config-scoped and cannot enumerate sibling configs. Also returns the Doppler project name, and reports per environment whether a service token resolves locally (from the token store or INFRA_KIT_ENV_TOKEN) \u2014 presence only, never the token value, and never a live Doppler probe. Read-only.",inputSchema:{},outputSchema:{project:Lt.string().describe("Detected Doppler project name"),defaultEnv:Lt.string().nullable().describe('The configured "defaultEnv" \u2014 what env-load takes when no config is named; null when unset'),configs:Lt.array(Lt.string()).describe("Every environment name known to this project"),tokens:Lt.array(Lt.object({env:Lt.string().describe("Environment / Doppler config name"),source:Lt.enum(["gh-workflow","token-only"]).describe("Where we learned this environment exists \u2014 a workflow declaration, or a token we hold"),hasToken:Lt.boolean().describe("Whether a service token resolves locally for this environment")})).describe("Per-environment token presence \u2014 never the token value")},handler:_a});import YA from"@inquirer/select";import{readRepoIdentity as zA}from"@slip-stream-kit/config/internal";import XA from"node:fs";import $d from"node:path";import Ad from"node:process";import{z as jr}from"zod";import Fv from"node:process";import{z as Mv}from"zod";var jv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),JA=async e=>{try{return await e}catch{return[]}},KA=async e=>{let t=await me().catch(()=>null);return Ni(e,t?.envs??{},Fv.env[Ae]).filter(r=>!r.hasToken).map(r=>r.env)},Td=()=>({get message(){return`Choose the environment to load into terminal session ${Fv.env[dt]??`UNKNOWN \u2014 ${dt} is not set, the load will fail`}. Picking one LOADS it; there is no further prompt.`},isFormable:e=>jv(e)&&(e.config===void 0||e.config===""),buildRequestedSchema:async()=>{let e=await JA(ir());if(e.length===0)return d.info({msg:"Tool execution form options empty: env-load"}),null;let t=e.map(n=>n.env),r=await KA(e);return Mv.object({config:Mv.enum(t).describe(`The environment to load. ${r.length===0?"A service token is stored for every one of them.":`NO stored token for: ${r.join(", ")} \u2014 choosing one of those fails until you run \`infra-kit env-token-set <env>\`.`} The list is what env-list knows: workflow-declared environments first, then token-only ones.`)})},toArgs:(e,t)=>{let{config:r}=e;return typeof r!="string"||r.length===0?null:{...jv(t)?t:{},config:r}}});import{z as HA}from"zod";var qA=async e=>{try{return await e.provider.buildRequestedSchema(e.params)}catch(t){return d.debug({err:t,operation:e.operation},"argument form builder threw; refusing without choices"),null}},Qe=async e=>{if(!H()||!e.provider.isFormable(e.params))return;let t=await qA(e),r=typeof e.params=="object"&&e.params!==null?e.params:{},n=(t===null?[]:Object.keys(t.shape)).filter(i=>r[i]===void 0||r[i]===""),o=typeof e.argument=="string"?e.argument:e.argument(n),s=t===null?void 0:HA.toJSONSchema(t);throw new A({status:"argument_required",argument:o,...s===void 0?{}:{choices:s},agentMode:_.source},2,{operation:e.operation,remediation:s===void 0?`pass --${o} on the re-run \u2014 nothing could be listed to choose from`:`ask the human to pick from "choices", then pass --${o} on the re-run`,stderrExcerpt:`--${o} was not given and there is no human to ask`})};var Lv=new Set(["DOPPLER_TOKEN",Ae]),Bv=!1,ZA=e=>{e.length===0||Bv||(Bv=!0,d.warn(`infra-kit: not exporting ${e.join(", ")} from Doppler into your shell \u2014 a service token must not be sourced into every process.`))},Uv=({pairs:e,config:t,project:r,projectRoot:n,loadedAt:o})=>{let s=e.filter(([i])=>!Lv.has(i));return ZA(e.filter(([i])=>Lv.has(i)).map(([i])=>i)),["set -a",...s.map(([i,a])=>`${i}=${zn(a)}`),`${Jt}=${zn(t)}`,`${Zr}=${zn(t)}`,`${Qr}=${zn(r)}`,`${bi}=${zn(n)}`,`${en}=${zn(o)}`,"set +a"]},QA=async()=>{try{return await $()}catch{return""}},eO=(e,t=Ad.cwd())=>{if(e==="")return[$d.resolve(t)];let r=zA(e).root??e;return[...new Set([r,`${r}${ce}`,e])]},Vv=async({config:e})=>{let t=await Ke(),r=await QA(),n=await dl(t,e),o=new Date().toISOString(),i=`${Uv({pairs:n,config:e,project:t,projectRoot:r,loadedAt:o}).join(`
|
|
376
|
+
`)}
|
|
377
|
+
`,a=Kt(),c=$d.resolve(a,Gt);XA.mkdirSync(a,{recursive:!0,mode:448});let l=eO(r);return ot($d.resolve(a,Xr),`${l.join(`
|
|
378
|
+
`)}
|
|
379
|
+
`,384),ot(c,i,384),{filePath:c,variableCount:n.length,project:t,config:e}},Wv=Td(),Na=async e=>{let{config:t}=e,r=t?null:await ds();if(!t&&r&&H())return Cd(r,"default");if(await Qe({provider:Wv,params:e,operation:"env-load",argument:"config"}),t)return Cd(t,"argument");if(ee())throw new A({status:"argument_required",argument:"config",agentMode:_.source},2,{operation:"env-load",remediation:'call env-list, ask the human which environment, and re-call env-load with "config"'});let n=await Dr();y.setInteractive();let o=await N(s=>YA({message:"Select environment config",choices:tO(n,r),...r?{default:r}:{}},s),{output:Ad.stderr,whenHeadless:"refuse"});return Cd(o,"picker")},tO=(e,t)=>(t&&!e.includes(t)?[t,...e]:e).map(n=>({name:n===t?`${n} (default)`:n,value:n})),Cd=async(e,t)=>{y.addOption("--config",e);let r=await Vv({config:e});y.print();let n={filePath:r.filePath,variableCount:r.variableCount,project:r.project,config:r.config,configSource:t,sessionId:Ad.env[dt]??null};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},zn=e=>`'${e.replaceAll("'","'\\''")}'`,Od=T({name:"env-load",description:'Download the env vars for a Doppler config and write them to a temporary shell script. Does NOT mutate the calling process \u2014 returns the path to a script that must be sourced ("source <filePath>") for the vars to take effect. The infra-kit shell wrapper auto-sources; direct MCP callers must handle sourcing themselves or surface filePath to the user. This server picks the file up on its next tool call, so a tool that needs the variables can be called right after. Omit "config" and this server offers the human a form listing every environment env-list knows, token-less ones marked; a client that cannot render one gets a refusal naming the missing field \u2014 call env-list and ask the human, never guess. When the project config sets "defaultEnv", omitting "config" headless loads that environment instead of refusing, and "configSource" reports "default".',inputSchema:{config:jr.string().optional().describe('Doppler config / environment name to load (e.g. "dev", "arthur"). Omit it to load the configured "defaultEnv", or, with none set, to have the human choose from a form.')},formProvider:Wv,outputSchema:{filePath:jr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:jr.number().describe("Number of variables loaded"),project:jr.string().describe("Doppler project name"),config:jr.string().describe("Doppler config name"),configSource:jr.enum(["argument","default","picker"]).describe('How the config was chosen: passed as "config", the configured "defaultEnv", or the terminal picker'),sessionId:jr.string().nullable().describe("The INFRA_KIT_SESSION the file was written for; null when the process had no session")},handler:Na});import rO from"node:path";import Es from"node:process";import{z as Xn}from"zod";var Ma=async()=>{d.info("Environment session status:");let e=Kt(),t=Es.env[dt],r=rO.join(e,Gt),n=0,o=0,s=Es.env[Zr]??null,i=Es.env[Qr]??null,a=Es.env[en]??null;if(s){let l=Ri(r);l.length>0&&(o=l.length,n=l.filter(p=>p in Es.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
380
|
`),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:
|
|
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:
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
`)[0],
|
|
385
|
-
`)
|
|
386
|
-
|
|
381
|
+
`);let c={sessionId:t,sessionLoadedCount:n,sessionTotalCount:o,sessionConfig:s,sessionProject:i,sessionLoadedAt:a};return{content:R(JSON.stringify(c,null,2)),structuredContent:c}},Dd=T({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:Xn.string().describe("Current terminal session ID"),sessionLoadedCount:Xn.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Xn.number().describe("Total number of cached var names"),sessionConfig:Xn.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Xn.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Xn.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Ma});import nO from"node:process";import{z as cr}from"zod";var Gv="****",De=e=>typeof e!="string"||e.length<8?Gv:`${Gv}${e.slice(-4)}`;var Jv=(e,t,r)=>e.map(n=>{let o=r||t[n];return o?{env:n,source:r?`env:${Ae}`:"store",redactedToken:De(o),present:!0}:{env:n,source:"-",redactedToken:"-",present:!1}}),oO=["ENV","SOURCE","TOKEN","PRESENT"],Kv=(e,t)=>{let r=[...oO,...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())},ja=async({check:e}={})=>{let t=await Dr(),r=await me(),n=nO.env[Ae],o=Jv(t,r?.envs??{},n);if(e){let a=await Ke();for(let c of o){if(!c.present)continue;let l=n||r.envs[c.env],u=await cl({childEnv:xo(l),project:a,config:c.env});c.status=u.outcome}}for(let a of Kv(o,!!e))d.info(a);let s=o.filter(a=>!a.present);s.length>0&&d.info(`
|
|
382
|
+
No token for: ${s.map(a=>a.env).join(", ")}. Add one with \`infra-kit env-token-set <env>\`.`);let i={tokens:o};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}},Id=T({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:cr.boolean().optional().describe("Probe Doppler for each token\u2019s validity and scope (one cheap call per environment).")},outputSchema:{tokens:cr.array(cr.object({env:cr.string().describe("Environment / Doppler config name"),source:cr.string().describe('"store", "env:INFRA_KIT_ENV_TOKEN", or "-" when absent'),redactedToken:cr.string().describe("Redacted token \u2014 last 4 chars at most, never the raw value"),present:cr.boolean().describe("Whether a token is configured for this environment"),status:cr.string().optional().describe("Only with check=true: valid | revoked | mis-scoped | unreachable")})).describe("One row per declared environment")},handler:ja});import{z as x}from"zod";import{$ as sD}from"zx";import{$ as Wz}from"zx";import{$ as Lr}from"zx";import iO from"node:fs/promises";import aO from"node:path";import{$ as cO}from"zx";var lO="infra-kit.json",_d="dev",we="main",Hv=e=>e==="dev"?"dev":we,re=async()=>{let{main:e}=await z();try{await iO.access(e)}catch{return _d}let t=(await V()).gitFlow??_d;return t==="dev"&&await uO(e),t},uO=async e=>{let t=`origin/${we}:${lO}`,r=await cO({quiet:!0,nothrow:!0})`git -C ${aO.dirname(e)} show ${t}`;if(r.exitCode!==0)return;let n;try{n=JSON.parse(r.stdout)}catch{return}if(n?.gitFlow==="main")throw new g(void 0,{operation:"resolve the git flow",remediation:`origin/${we} sets "gitFlow": "main" but this checkout's infra-kit.json does not \u2014 switch to ${we} and pull, or rebase this branch onto it, then re-run`})},Fr=async()=>Hv(await re());import{$ as qv}from"zx";var Nd=async e=>{let{operation:t}=e;try{await qv({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 qv({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"})}},dO=4,Zn=async e=>{let{operation:t}=e,r=await zf();if(r.length===0)return;d.error(`working tree has uncommitted changes:
|
|
383
|
+
${r.join(`
|
|
384
|
+
`)}`);let n=r.slice(0,dO),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}`})},Ps=async e=>{let{operation:t,base:r}=e;if(await on()===r)return;let n=(await pt(await $())).find(o=>o.branch===r);if(n)throw new g(void 0,{operation:t,remediation:"close or remove that worktree, or run the release from it",stderrExcerpt:`base branch "${r}" is checked out in the worktree at ${n.path}`})},Le=async e=>{let{operation:t}=e;if(await Zf())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 Zn({operation:t})};import{$ as Yv}from"zx";var Md={dev:{regular:"dev",hotfix:we},main:{regular:we}},Qn=e=>Object.keys(Md[e]),bt=(e,t)=>{let r=Md[t][e];if(r===void 0)throw new g(void 0,{operation:`use a ${e} release`,remediation:`this repo sets "gitFlow": "${t}" in infra-kit.json, which has only ${Qn(t).join(" and ")} releases \u2014 create it as a regular release`});return r},xs=(e,t)=>{let r=Object.entries(Md[t]).find(([,n])=>n===e);return r?r[0]:null},Ts=(e,t)=>(t??"").trim()!==""?`${e}
|
|
385
|
+
|
|
386
|
+
${t}`:`${e}
|
|
387
|
+
`,jd=async(e="regular")=>{let t=bt(e,await re()),r=Yv({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 Yv({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()},pO=async e=>{let{versionName:t,jiraConfig:r,description:n,releaseDate:o}=e,s=await Mt(t,r);if(!s)return(await zu({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 Jn({versionId:s.id,...a},r);return{...s,...a,...a.releaseDate===void 0?{}:{releaseDate:c.version.releaseDate}}},Fd=async e=>{let{id:t,jiraConfig:r,description:n,releaseDate:o,type:s="regular",baseSha:i}=e,a=de(t),c=await pO({versionName:a,jiraConfig:r,description:n,...o===void 0?{}:{releaseDate:o}}),l=Ir(r,c),u=await Ba({id:t,jiraVersionUrl:l,type:s,description:n,baseSha:i});return{version:se(t),type:s,branchName:u.branchName,prUrl:u.prUrl,jiraVersionUrl:l,releaseDate:c.releaseDate||null}},Fa=async()=>{let e=new Map,t=await jt();if(!t)return e;try{let r=await Gn(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},he=async()=>{let e=await Fa();return new Map([...e].flatMap(([t,{description:r}])=>r?[[t,r]]:[]))},Cs=(e,t,r)=>{let n=r?" ".repeat(r-e.length+3):" ",o=`[${t}]`.padEnd(11);return`${e}${n}${o}`},Ld=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",La=e=>e.flatMap(t=>{let r=te(t);return r?[{branch:t,id:r,label:se(r)}]:[]}),Bt=e=>{try{return Ce(Re(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)})}},$s=e=>{let t=te(e);return t?se(t):e},Ut=e=>e.flatMap(t=>{let r=te(t);return r?[se(r)]:[]}),mO=(e,t)=>t?t.get(e)||"regular":void 0,ye=e=>{let{branches:t,descriptions:r,types:n}=e;return La(t).map(({branch:o,id:s,label:i})=>({value:o,label:i,description:r.get(de(s)),type:mO(o,n)}))};var fO=e=>e.map(t=>({pr:t,id:te(t.headRefName)})).filter(t=>t.id!==null).sort((t,r)=>Yf(t.id,r.id,{a:t.pr.createdAt,b:r.pr.createdAt})).map(t=>t.pr),eo=200,Bd=(e,t)=>{e.length<eo||d.warn({source:t,limit:eo},`\u26A0\uFE0F ${t} returned ${eo} PRs \u2014 the page is full, so older release PRs may be missing`)},gO=async e=>{if(e==="main"){let l=await Lr`gh pr list --limit ${eo} --base ${we} --json number,title,headRefName,state,baseRefName,createdAt`,u=JSON.parse(l.stdout);return Bd(u,`release PR discovery (base ${we})`),u.map(p=>({...p,dualBase:!1}))}let[t,r]=await Promise.all([Lr`gh pr list --limit ${eo} --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,Lr`gh pr list --limit ${eo} --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`]),n=JSON.parse(t.stdout),o=JSON.parse(r.stdout);Bd(n,"release PR discovery (base dev)"),Bd(o,"hotfix PR discovery (base main)");let s=new Set(n.map(l=>l.headRefName)),i=new Set(o.filter(l=>s.has(l.headRefName)).map(l=>l.headRefName)),a=[...o,...n],c=new Set;return a.filter(l=>c.has(l.headRefName)?!1:(c.add(l.headRefName),!0)).map(l=>({...l,dualBase:i.has(l.headRefName)}))},As="find open release PRs",zv=async e=>{try{let t=await gO(e);if(t.length===0)throw new g(void 0,{operation:As,remediation:"open a release PR first, or check you are in the right repo"});return fO(t)}catch(t){throw t instanceof g?t:(d.debug({err:t},"Error fetching release PRs"),new g(t,{operation:"fetch release PRs"}))}},Ua=async()=>(await zv(await re())).map(t=>t.headRefName),hO=(e,t)=>{let r=xs(e.baseRefName,t);if(r===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 n=Ld(e.title)!==r;return(n||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 ${r} by its base`),{branch:e.headRefName,number:e.number,title:e.title,createdAt:e.createdAt,baseRefName:e.baseRefName,type:r,titleMismatch:n,dualBase:e.dualBase}},K=async()=>{let e=await re();return(await zv(e)).map(r=>hO(r,e))},Va=async e=>{let{branch:t,body:r}=e;try{await Lr({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}},yO=async(e,t)=>{let r=Lr({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`)},Ba=async e=>{let{id:t,jiraVersionUrl:r,type:n,description:o,baseSha:s}=e,i=qf(t,n),a=bt(n,await re()),c=Lr({quiet:!0}),l=Ce(t),u=Ts(r,o);try{await Zn({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 yO(l,a),m}}catch(p){throw d.error({error:p,branchName:l},`Error creating release branch ${l}`),p}finally{await Lr({quiet:!0,nothrow:!0})`git switch ${a}`}};import{$ as Ud}from"zx";var to=async e=>{let t=await Ud`gh pr list --head ${e} --state all --json number,state,title,baseRefName,headRefName --limit 1`;return JSON.parse(t.stdout)[0]??null},Vd=async e=>{let t=await Ud`gh pr list --head ${e} --state open --limit 5 --json number,state,title,baseRefName,headRefName`;return JSON.parse(t.stdout)},Wa=async e=>{try{let t=await Ud`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 vO from"node:process";var Os=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Wd=null,Xv=e=>{Wd=e},Zv=()=>{if(Wd===null)throw new Error("no branch picker registered: entry/cli.ts registers the Ink pickers at startup");return Wd()},Qv=e=>{let t={operation:"interactive branch selection",remediation:"pass the branch selection explicitly (`--version`/`--versions`/`--all`) for non-interactive, --json, or --agent runs"};if(H())throw new A({status:"argument_required",argument:e,agentMode:_.source},2,t);if(!vO.stdin.isTTY)throw new g(void 0,t)},lr=async e=>{Qv("version");let{runBranchPicker:t}=await Zv(),r=await t(e);if(r===null)throw new Os;return r},ur=async(e,t)=>{Qv("versions");let{runBranchMultiPicker:r}=await Zv(),n=await r(e,t);if(n===null)throw new Os;return n};import{$ as Br}from"zx";var Gd=(e,t)=>`Merge remote-tracking branch '${e}' into ${t}`,wO=e=>{let{stderr:t,message:r}=e;return String(t?.trim()||r||e).trim()},kO=2048,bO=e=>{let{stderr:t,stdout:r,exitCode:n}=e;return[t,r].map(s=>(s??"").trim().slice(-kO)).filter(s=>s.length>0).join(`
|
|
388
|
+
`)||`the verify command exited with code ${n??"unknown"} and printed nothing`},RO=async e=>{try{return(await Br({cwd:e,quiet:!0})`git diff --name-only --diff-filter=U`).stdout.split(`
|
|
389
|
+
`).map(r=>r.trim()).filter(r=>r.length>0)}catch{return[]}},SO=async(e,t)=>{let r=wO(t),n=await RO(e);return n.length>0?{status:"conflict",conflictPaths:n,reason:r}:await rg(e)?{status:"hook-failed",reason:r}:{status:"error",reason:r}},ew=async e=>{let{cwd:t,worktreePath:r,branches:n,integrationRef:o}=e,s=[],i=await $e(t,o);if(!i)return n.map(a=>({branch:a,status:"error",reason:`${o} does not resolve`}));for(let a of n){let c=Date.now(),l=await EO({cwd:t,worktreePath:r,branch:a,devSha:i,integrationRef:o});s.push({...l,durationMs:Date.now()-c})}return s},EO=async e=>{let{cwd:t,worktreePath:r,branch:n,devSha:o,integrationRef:s}=e,i=`origin/${n}`;if(!await $e(t,i))return{branch:n,status:"error",reason:`${i} does not exist on origin`};if(await Ro(t,s,i))return{branch:n,status:"up-to-date"};try{await el(r),await Br({cwd:r,quiet:!0})`git checkout --detach ${i}`;let a=Gd(s,n);await Br({cwd:r,quiet:!0})`git merge ${s} --no-edit -m ${a}`;let c=(await Br({cwd:r,quiet:!0})`git rev-parse HEAD`).stdout.trim();return{branch:n,status:c===o?"fast-forward":"merged",mergeSha:c}}catch(a){return{branch:n,...await SO(r,a)}}finally{await tl(r)}},tw=e=>e.flatMap(t=>t.mergeSha?[{branch:t.branch,sha:t.mergeSha}]:[]),rw="pnpm install --frozen-lockfile",nw=async e=>{let{worktreePath:t,refs:r,command:n}=e,o=[],s=new Map;for(let i of r)try{await el(t),await Br({cwd:t,quiet:!0})`git checkout --detach ${i.sha}`,await Br({cwd:t,quiet:!0})`sh -c ${n}`,o.push(i)}catch(a){s.set(i.branch,bO(a))}finally{await tl(t)}return{kept:o,failed:s}},Ds=async(e,t,r)=>{await Br({cwd:e,quiet:!0})`git fetch origin --prune`;let n=[],o=[];for(let s of t)await Ro(e,r,`origin/${s.branch}`)?o.push(s.branch):n.push(s);return{kept:n,nowUpToDate:o}};import{Buffer as cw}from"node:buffer";import dr from"node:fs/promises";import Vr from"node:path";import lw from"node:process";import{$ as Ha}from"zx";import ow from"node:fs/promises";import PO from"node:path";import{$ as Jd}from"zx";var J="pnpm-lock.yaml",xO=/^(?:<{7}|={7}|>{7})(?:\s|$)/m,iw=async(e,t)=>{let r=PO.join(e,J),n=`${t}:${J}`;try{let o=await Jd({cwd:e,quiet:!0})`git show ${n}`;await ow.writeFile(r,o.stdout)}catch(o){return{ok:!1,reason:`dev has no ${J} to start from: ${sw(o)}`}}try{await Jd({cwd:e,quiet:!0})`pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile`}catch(o){return{ok:!1,reason:`pnpm could not merge ${J}: ${sw(o)}`}}return xO.test(await ow.readFile(r,"utf8"))?{ok:!1,reason:`${J} still carries conflict markers after pnpm ran`}:(await Jd({cwd:e,quiet:!0})`git add -- ${J}`,{ok:!0})},sw=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim()};import Kd from"node:process";var Ga=new Set,Ja=e=>(Ga.add(e),()=>{Ga.delete(e)}),TO=async()=>{for(let e of[...Ga])try{await e()}catch(t){d.warn({error:t,msg:"cleanup failed during shutdown"})}Ga.clear()},CO=["SIGINT","SIGTERM"],aw=async(e,t={})=>{let{register:r=(i,a)=>{Kd.on(i,a)},unregister:n=(i,a)=>{Kd.off(i,a)},exit:o=i=>{Kd.exit(i)}}=t,s=new Map;for(let i of CO){let a=()=>{TO().then(()=>{o(Dg(i))})};s.set(i,a),r(i,a)}try{return await e()}finally{for(let[i,a]of s)n(i,a)}};var $O="pnpm install --frozen-lockfile --ignore-scripts",Hd="pnpm install --frozen-lockfile",uw=64*1024,gw=4096,_s=e=>{let{stderr:t,message:r}=e;return String(t||r||e).trim().slice(-gw)},W=async(e,t)=>(await Ha({cwd:e,quiet:!0})`git ${t}`).stdout,Yd=e=>e.split(`
|
|
390
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),no=e=>e.split("\0").filter(t=>t.length>0),Ur=async(e,t)=>{try{return(await W(e,["rev-parse","-q","--verify",t])).trim()||null}catch{return null}},AO=async e=>Vr.resolve(e,(await W(e,["rev-parse","--git-common-dir"])).trim()),hw=e=>e.then(()=>!0,()=>!1),Is=()=>({results:[],atomicPush:{attempted:!1,aborted:!1},declined:!1}),zd=e=>e?.length===1&&e[0]===J,dw=(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}),OO=e=>e.editablePaths??e.conflictPaths,DO=e=>Vr.posix.basename(e)==="package.json",Xd=e=>e.conflictPaths.includes(J)||e.lockfileBlob!==void 0,yw=async(e,t)=>{if(!t.editablePaths)return t.conflictPaths.includes(J);if(t.lockfileBothSides||t.lockfileBlob!==void 0)return!0;let r=no(await W(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree]));return[...await Qd(e),...r].some(DO)},vw=e=>e.editablePaths?"only the editable paths may change":"only the conflicted paths may change",Zd=async(e,t,r)=>{await W(e,["worktree","remove","--force",r]).catch(()=>dr.rm(r,{recursive:!0,force:!0})),await dr.rm(await us(e,t),{force:!0}).catch(()=>{}),await W(e,["worktree","prune"]).catch(()=>{})},ww=async e=>no(await W(e,["diff","--name-only","-z","--diff-filter=U"])),Ka=async e=>no(await W(e,["status","--porcelain","-z","--untracked-files=all","--ignored=matching"])).filter(r=>r.startsWith("!! ")).map(r=>r.slice(3)),IO=async(e,t)=>{let r=(await W(e,["config","--type=bool","--get","rerere.enabled"]).catch(()=>"")).trim(),n=await hw(dr.stat(Vr.join(await AO(e),"rr-cache")));if(r==="false"||r===""&&!n)return[];let o=new Set(Yd(await W(e,["rerere","remaining"])));return t.filter(s=>!o.has(s))},kw=e=>e.split("/").includes("node_modules"),qa=async(e,t)=>{let r=new Set(OO(t));t.editablePaths&&await yw(e,t)&&r.add(J);let n=new Set([...t.ignoredAtHandoff,...t.ignoredByVerify??[]]),o=no(await W(e,["diff","--cached","--name-only","-z","--no-renames",t.autoMergeTree])),s=[...await Qd(e),...o].filter(a=>!r.has(a)),i=(await Ka(e)).filter(a=>!n.has(a)&&!kw(a));return[...new Set([...s,...i,...await _O(e)])].sort()},Qd=async e=>{let t=no(await W(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},_O=async e=>(await W(e,["ls-files","-v"])).split(`
|
|
391
|
+
`).filter(t=>{let r=t.charAt(0);return r==="S"||r!==""&&r!==r.toUpperCase()}).map(t=>t.slice(2)),NO=async(e,t)=>{let r=`:(exclude)${J}`;try{return await W(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(`
|
|
392
|
+
`)){let l=/^(.*):\d+: leftover conflict marker/.exec(c);l?.[1]&&a.add(l[1])}return[...a].sort()}},MO=async(e,t)=>{let r=[];for(let n of t)(await hw(dr.lstat(Vr.join(e,n)))||(await W(e,["--literal-pathspecs","ls-files","--",n])).length>0)&&r.push(n);r.length>0&&await W(e,["--literal-pathspecs","add","-A","--",...r])},qd=async e=>(await W(e,["write-tree"])).trim(),bw=async e=>(await W(e,["rev-list","--parents","-n","1","HEAD"])).trim().split(" ").slice(1),jO=e=>{let t=`${Hd} && `;if(e!==Hd)return e?.startsWith(t)?e.slice(t.length):e},FO=e=>e?`${Hd} && ${e}`:$O,LO=async(e,t)=>{try{return await Ha({cwd:e,quiet:!0})`sh -c ${t}`,{command:t,ok:!0}}catch(r){return{command:t,ok:!1,reason:_s(r)}}},Rw=async(e,t)=>{let r=(await W(e,["diff","--cached","--stat",t.autoMergeTree])).trim(),n=async l=>(await W(e,["diff","--cached","--stat",l,"--",J])).trim(),o=Xd(t)?{vsDev:await n(t.devSha),vsBase:await n(t.baseSha)}:void 0,s=await W(e,["diff","--cached",t.autoMergeTree,"--",".",`:(exclude)${J}`]),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)
|
|
393
|
+
${l}`:l}).join(""),c=cw.byteLength(a)>uw;return{diffStat:r,...o?{lockfileDiffStat:o}:{},resolutionDiff:c?cw.from(a).subarray(0,uw).toString():a,resolutionDiffTruncated:c}},Sw=async e=>{let{cwd:t,conflicted:r,verifyFailed:n,devSha:o,integrationRef:s,verify:i}=e,a=new Map;for(let c of r)a.set(c,await pw(t,c,o,s,"conflict"));for(let c of n)a.set(c,await pw(t,c,o,s,"verify-failed",i));return a},BO=async(e,t,r)=>{let n=async(a,c)=>no(await W(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!==J).sort(),lockfileBothSides:o.includes(J)&&s.includes(J)}},UO=async(e,t,r,n)=>{let o=await ww(e);if(t==="verify-failed"){if(o.length>0)return{reason:"the merge now conflicts \u2014 re-run release merge-dev"};let i=await Ur(e,"HEAD"),a=await Ur(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 BO(e,r,n),autoMergeTree:await qd(e),rererePreResolved:[],lockfileOnly:!1}}if(o.length===0)return{reason:"the merge no longer conflicts \u2014 re-run release merge-dev"};let s=await Ur(e,"AUTO_MERGE");return s?{conflictPaths:o,autoMergeTree:s,rererePreResolved:await IO(e,o),lockfileOnly:zd(o)}:{reason:`git-too-old: the scope check needs AUTO_MERGE, written by git \u2265 2.42 (found ${(await W(e,["--version"])).trim()})`}},VO={conflict:"needs-agent","verify-failed":"verify-failed"},pw=async(e,t,r,n,o,s)=>{let i=await Ra(await us(e,t));if(i)return{resolution:dw(i,"exists"),reason:`resolution-exists: ${i.worktreePath} \u2014 finish it with --continue or drop it with --abort`};let a=await $e(e,`origin/${t}`);if(!a)return{reason:`origin/${t} does not exist on origin`};let c=tg(e,t),l=()=>Zd(e,t,c),u=Ja(l);try{await W(e,["worktree","prune"]),await dr.mkdir(Vr.dirname(c),{recursive:!0}),await W(e,["worktree","add","--detach",c,a]);let p=Gd(n,t);await Ha({cwd:c,quiet:!0})`git merge --no-commit ${r} -m ${p}`.catch(()=>{});let m=await UO(c,o,a,r);if("reason"in m)return await l(),m;let f={branch:t,worktreePath:c,baseSha:a,devSha:r,...m,...o==="verify-failed"&&s?{handOffVerify:s}:{},ignoredAtHandoff:await Ka(c),cliVersion:U.version,createdAt:new Date().toISOString()};return await or(e,f),{resolution:dw(f,f.lockfileOnly?"lockfile-only":VO[o])}}catch(p){return await l(),{reason:_s(p)}}finally{u()}},Ew=async e=>{let{cwd:t,versions:r,all:n}=e,o=await Sa(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=Ce(Re(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 ur(ye({branches:s,descriptions:new Map}),{required:!0});return o.filter(a=>i.includes(a.branch))},WO=async(e,t)=>{let r=await dr.realpath(t).catch(()=>null);if(!r)return!1;let n=await pt(e);for(let o of n)if(await dr.realpath(o.path).catch(()=>o.path)===r)return!0;return!1},ro=(e,t,r,n)=>({...e,blocked:{code:t,detail:r,...n&&n.length>0?{paths:n}:{}}}),Pw=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 WO(e,n))return ro(o,"parents-mismatch",`the resolution worktree ${n} is gone \u2014 run --abort, then start again`);let s=await Ur(n,"HEAD"),i=await Ur(n,"MERGE_HEAD"),a=r??jO(t.handOffVerify);return s===t.baseSha&&i===t.devSha?qO(e,t,o,a):GO(t,o,s,i)},GO=async(e,t,r,n)=>{let o=e.worktreePath;if(r!==null&&r===e.unapprovedCommit)return ro(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 bw(o),i=n?null:await Ur(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 ro(t,"parents-mismatch",`expected HEAD ${e.baseSha} merging ${e.devSha}, or an approved merge commit of the two; found ${l}`)}let c=await qa(o,e);return c.length>0?ro(t,"out-of-scope-edit",vw(e),c):{...t,committed:!0,mergeSha:r,treeSha:i,lockfileMerged:Xd(e),...await Rw(o,e)}},mw=async(e,t)=>{let r=Yd(await W(e,["--literal-pathspecs","ls-files","-s","--",t])),[n,o,s]=r.length===1?(r[0]??"").split(/\s+/):[];return n&&s==="0"?o??null:null},JO=async(e,t)=>{let r=t.worktreePath,n=await mw(r,J),o=t.lockfileBlob,s=o===void 0&&t.editablePaths!==void 0&&n===await Ur(r,`${t.autoMergeTree}:${J}`),i=await iw(r,t.devSha);if(!i.ok)return{code:"verify-failed",detail:i.reason,paths:[J]};let a=await mw(r,J);if(a!==null&&a!==o&&(t.lockfileBlob=a,await or(e,t)),n!==null&&n!==a&&!s)return n===o?{code:"tree-changed",detail:`rebuilding ${J} from dev resolved differently than the last preview (the registry moved) \u2014 preview again`,paths:[J]}:{code:"out-of-scope-edit",detail:`${J} was staged by something other than the CLI; it has been rebuilt from dev \u2014 preview again`,paths:[J]};let c=await qa(r,t);return c.length>0?{code:"out-of-scope-edit",detail:"merging the lockfile changed other paths",paths:c}:null},KO=async(e,t)=>{let r=t.worktreePath,n=new Set(t.editablePaths),o=t.editablePaths?(await Qd(r)).filter(c=>n.has(c)):t.conflictPaths;await MO(r,o.filter(c=>c!==J));let s=await qa(r,t);if(s.length>0)return{code:"out-of-scope-edit",detail:vw(t),paths:s};let i=(await ww(r)).filter(c=>c!==J);if(i.length>0)return{code:"unmerged-paths",detail:"these paths are still unmerged",paths:i};let a;try{a=await NO(r,t.editablePaths?t.autoMergeTree:"HEAD")}catch(c){return{code:"markers-remaining",detail:`the marker check could not run: ${_s(c)}`}}return a.length>0?{code:"markers-remaining",detail:"conflict markers are still staged",paths:a}:await yw(r,t)?JO(e,t):null},HO=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 Ka(o)),i=await LO(o,n),a=(await Ka(o)).filter(c=>!s.has(c)&&!kw(c)&&Vr.posix.basename(c)!==".gitignore");return t.ignoredByVerify=[...new Set([...t.ignoredByVerify??[],...a])],await or(e,t),i},qO=async(e,t,r,n)=>{let o=t.worktreePath,s=await KO(e,t);if(s)return{...r,blocked:s};let i=Xd(t),a=await qd(o),c=await HO(e,t,a,FO(n)),l={...r,treeSha:a,lockfileMerged:i,verify:c};if(!c.ok)return ro(l,"verify-failed",c.reason??"the verify command failed");let u=await qa(o,t),p=Yd(await W(o,["diff","--name-only"]));return u.length>0||p.length>0||await qd(o)!==a?ro(l,"verify-mutated-tree","the verify step changed the tree",[...new Set([...u,...p])]):(c.reused||(t.verified={treeSha:a,command:c.command},await or(e,t)),{...l,...await Rw(o,t)})},YO=12e4,zO=async(e,t=YO)=>{let r=Ha({cwd:e,quiet:!0,detached:!0,stdio:["ignore","pipe","pipe"],env:{...lw.env,GIT_TERMINAL_PROMPT:"0"}})`git commit --no-edit --cleanup=strip`,n=!1,o=setTimeout(()=>{n=!0;let s=r.child?.pid;try{s&&lw.kill(-s,"SIGKILL")}catch{}},t);try{return await r,{ok:!0}}catch(s){if(!n)return{ok:!1,reason:_s(s)};let i=(await W(e,["rev-parse","--git-path","index.lock"])).trim();return await dr.rm(Vr.resolve(e,i),{force:!0}),{ok:!1,reason:`git commit timed out after ${t}ms`}}finally{clearTimeout(o)}},XO={"verify-failed":"verify-failed","tree-changed":"tree-changed"},ZO=e=>{let t=e.blocked;return{branch:e.branch,status:XO[t.code]??"blocked",conflictPaths:e.conflictPaths,pushed:!1,reason:[`${t.code}: ${t.detail}`,...t.paths?[`(${t.paths.join(", ")})`]:[]].join(" "),blocked:t}},QO=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 zO(o);if(!i.ok)return s("hook-failed",i.reason);let a=(await W(o,["rev-parse","HEAD"])).trim(),c=(await W(o,["rev-parse","HEAD^{tree}"])).trim();if(c!==t.treeSha)return r.unapprovedCommit=a,await or(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 bw(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}},eD=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 Ds(e,[{branch:t.branch,sha:r}],t.devSha)).nowUpToDate}catch(c){let l={code:"parents-mismatch",detail:`origin/${t.branch}: ${_s(c)}`};return n("blocked",`parents-mismatch: ${l.detail}`,l)}if(o.includes(t.branch))return n("up-to-date",`origin/${t.branch} already carries ${t.devSha}`);let s=await $e(e,`origin/${t.branch}`);if(s===t.baseSha)return"keep";let i=s!==null&&await Ro(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)},tD=e=>{d.info(`
|
|
394
|
+
\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}`)},xw=async e=>{let{cwd:t,versions:r,all:n,verify:o,trees:s=new Map,confirmedCommand:i}=e,a=await Ew({cwd:t,versions:r,all:n});if(a.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Is();if(i)return fw(t,a,o,s);let c=[];for(let m of a){let f=await Pw(t,m,o);!f.blocked&&!f.committed&&f.treeSha&&(m.previewedTree=f.treeSha,await or(t,m)),c.push(f)}tD(c);let l={branches:c},u=c.filter(m=>!m.blocked&&m.treeSha!==void 0);if(u.length===0)throw new A({status:"refused",plan:l,agentMode:_.source},2,{operation:"continue the merge-dev resolutions",stderrExcerpt:"every selected resolution is blocked",remediation:"fix the paths each row names, then preview again \u2014 or drop it with --abort"});let p=new Map(u.map(m=>[m.branch,m.treeSha]));try{await q(i,`Commit and push the resolved merges for: ${[...p.keys()].join(", ")}?`,{plan:l,rerun:rD(p)})}catch(m){if(!Ee(m))throw m;return{...Is(),declined:!0}}return fw(t,a,o,p)},Tw=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},rD=e=>{let t=[],r=!1;for(let o of Cg())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"]},nD=async(e,t,r,n)=>{let o=await Pw(e,t,r);if(o.blocked)return ZO(o);let s=await QO(e,o,t,n);if(!("sha"in s))return s;let i=await eD(e,t,s.sha);return i==="keep"?s:i},oD=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(`
|
|
395
|
+
\u2B06\uFE0F Pushing atomically: ${r.map(s=>s.branch).join(", ")}`);let n=await Oi(e,r),o=[];for(let s of t){let i=n.pushed||await sn(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(-gw)}})}return{results:o,atomicPush:{attempted:!0,aborted:!n.pushed,abortedBy:n.stderr?.split(`
|
|
396
|
+
`)[0]}}},fw=async(e,t,r,n)=>{let o=[],s=[];for(let u of t){let p=await nD(e,u,r,n.get(u.branch));"sha"in p?s.push({record:u,sha:p.sha}):o.push(p)}let i=await oD(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 Zd(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}},Cw=async e=>{let{cwd:t,versions:r,all:n,confirmedCommand:o}=e,s=await Ew({cwd:t,versions:r,all:n});if(s.length===0)return d.info("\u2139\uFE0F No merge-dev resolutions in progress"),Is();let i={branches:s.map(a=>({branch:a.branch,worktreePath:a.worktreePath}))};try{await q(o,`Discard the resolution worktrees for: ${s.map(a=>a.branch).join(", ")}?`,{plan:i})}catch(a){if(!Ee(a))throw a;return{...Is(),declined:!0}}for(let a of s)await Zd(t,a.branch,a.worktreePath),d.info(`\u{1F5D1}\uFE0F Discarded the resolution for ${a.branch}`);return{...Is(),results:s.map(a=>({branch:a.branch,status:"aborted",conflictPaths:a.conflictPaths,pushed:!1}))}};var iD=(e,t)=>({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0,dryRun:e,atomicPush:{attempted:!1,aborted:!1},results:[],skipped:t}),aD=e=>e.dualBase?"open PRs to both dev and main":e.titleMismatch?"title/base mismatch":e.type==="hotfix"?"hotfix (targets main)":null,cD=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(", ")},tp=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),ep=new Set(["up-to-date","fast-forward","merged"]),lD=(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=Ce(Re(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))},uD={"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"},Aw=e=>{let t=uD[e.status];if(e.status==="conflict"){let r=e.conflictPaths?.length??0;return`${t}: ${r} file(s)`}return e.reason?`${t}: ${e.reason}`:t},dD=(e,t)=>{d.info(`
|
|
397
|
+
\u{1F4CB} Merge plan:`);for(let r of e)d.info(` ${r.branch} \u2014 ${Aw(r)}`);for(let r of t)d.info(` ${r.branch} \u2014 skipped: ${r.reason}`)},pD=(e,t,r)=>{let n=t.find(o=>o.branch===e);return n?`git -C ${n.path} merge ${r}`:`git switch ${e} && git merge ${r}`},mD=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=te(i.branch);return a?[[de(a),Aw(i)]]:[]}));return ur(ye({branches:r,descriptions:s}),{required:!0})},fD=async e=>{let{cwd:t,worktreePath:r,entries:n,selected:o,verify:s,integrationRef:i}=e,a=n.filter(b=>o.includes(b.branch)),c=b=>{for(let C of b)d.info(`\u2139\uFE0F ${C} was merged by someone else while we planned \u2014 dropping it from the push`)},l=await Ds(t,tw(a),i);c(l.nowUpToDate);let u=l.kept,p=new Map;if(s&&u.length>0){d.info(`
|
|
398
|
+
\u{1F50E} Verifying ${u.length} merge(s) with: ${s}`);let b=await nw({worktreePath:r,refs:u,command:s});p=b.failed;for(let[k,F]of b.failed)d.info(`\u2717 ${k} failed verification \u2014 not pushing it. ${F.split(`
|
|
399
|
+
`)[0]??""}`);let C=await Ds(t,b.kept,i);c(C.nowUpToDate),u=C.kept}if(u.length===0)return{pushed:!1,pushAborted:!1,verifyFailed:p};d.info(`
|
|
400
|
+
\u2B06\uFE0F Pushing atomically: ${u.map(b=>b.branch).join(", ")}`);let m=await Oi(t,u);if(m.pushed)return{pushed:!0,pushAborted:!1,verifyFailed:p};let h=(await Promise.all(u.map(async b=>({branch:b.branch,landed:await sn(t,b.branch)===b.sha})))).filter(b=>b.landed);return h.length>0&&d.warn(`\u26A0\uFE0F The push reported failure, but origin already carries ${h.map(b=>b.branch).join(", ")} \u2014 re-run to reconcile.`),{pushed:!1,pushAborted:!0,verifyFailed:p,abortedBy:m.stderr?.split(`
|
|
401
|
+
`)[0],observedLanded:h.map(b=>b.branch)}},gD=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"})},$w=e=>{let{results:t,atomicPush:r,declined:n}=e;for(let i of t){let a=i.reason?.split(`
|
|
402
|
+
`)[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=>!ep.has(i.status));return tp({successfulMerges:o.length-s.length,failedMerges:s.length,failedBranches:s.map(i=>i.branch),totalBranches:t.length,dryRun:!1,atomicPush:r,results:t,skipped:[]})},hD=async e=>{let{all:t,versions:r,verify:n,confirmedCommand:o}=e,s=await Ie();if(e.abort)return $w(await Cw({cwd:s,versions:r,all:t,confirmedCommand:o}));let i=typeof n=="string"&&n.length>0?n:void 0;return $w(await xw({cwd:s,versions:r,all:t,verify:i,trees:Tw(e.tree),confirmedCommand:o}))},Ya=async e=>{let{all:t,versions:r,dryRun:n=!1,verify:o,keepConflicts:s=!1,confirmedCommand:i}=e;gD(e);let a=o===!0?rw:o||void 0;if(await Nd({operation:"merge dev into release branches"}),e.continue||e.abort)return hD(e);let c=[],l=[];for(let D of await K()){let B=aD(D);B?l.push({branch:D.branch,reason:B}):c.push(D.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 (${cD(l)})`),y.print(),tp(iD(n,l));let u=await Ie();try{await sD({cwd:u,quiet:!0})`git fetch origin --prune`}catch(D){throw new g(D,{operation:"fetch origin before planning the merges",remediation:"check network access and that `origin` is reachable"})}let p=r===void 0?c:lD(r,c,l),m=`origin/${await Fr()}`,f=await ng({cwd:u,anchor:m},async D=>{let B=Ja(D.remove);try{return await yD({cwd:u,worktree:D,toPlan:p,candidates:c,skipped:l,all:t,versions:r,dryRun:n,verify:a,keepConflicts:s,confirmedCommand:i,integrationRef:m})}finally{B()}}),{entries:h,selected:b,pushed:C,pushAborted:k,abortedBy:F,declined:v,verifyFailed:S,handOffs:P}=f,O=await pt(u).catch(()=>[]);return bD({entries:h,selected:b,pushed:C,pushAborted:k,abortedBy:F,declined:v,verifyFailed:S,handOffs:P,dryRun:n,worktrees:O,skipped:l,integrationRef:m})},yD=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,integrationRef:m}=e,f=u?await $e(t,m):null,h=await ew({cwd:t,worktreePath:r.path,branches:n,integrationRef:m}),b={entries:h,pushed:!1,pushAborted:!1,declined:!1};if(dD(h,s),c)return{...b,selected:n};let C=await mD({entries:h,toPlan:n,all:i,explicit:a!==void 0});C.length===o.length?y.addOption("--all",!0):y.addOption("--versions",C);let k=h.filter(D=>C.includes(D.branch)&&D.mergeSha).length;k>0&&d.info(`
|
|
403
|
+
\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 q(p,`Are you sure you want to merge ${m} into these branches: ${C.join(", ")}?`,{plan:vD(h,C,s)})}catch(D){if(!Ee(D))throw D;return{...b,selected:C,declined:!0}}p||y.addOption("--yes",!0);let F=await fD({cwd:t,worktreePath:r.path,entries:h,selected:C,verify:l,integrationRef:m}),v=D=>h.filter(B=>C.includes(B.branch)&&D(B)).map(B=>B.branch),S=v(D=>D.status==="conflict"),P=v(D=>D.status==="merged"&&(F.verifyFailed?.has(D.branch)??!1)),O=u&&f&&S.length+P.length>0?await Sw({cwd:t,conflicted:S,verifyFailed:P,devSha:f,integrationRef:m,verify:l}):void 0;return{entries:h,selected:C,declined:!1,...F,handOffs:O}},vD=(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:zd(n.conflictPaths)}:{},...n.reason?{reason:n.reason}:{}})),skipped:r}),wD=(e,t,r)=>e.resolution?`# ${e.branch} \u2014 ${e.status}, left to resolve in ${e.resolution.worktreePath} (then --continue)
|
|
387
404
|
`:`# ${e.branch} \u2014 ${e.status}
|
|
388
|
-
${
|
|
389
|
-
`,
|
|
390
|
-
hand-off: ${t}`:e??t,
|
|
405
|
+
${pD(e.branch,t,r)}
|
|
406
|
+
`,kD=(e,t)=>e!==void 0&&t?`${e}
|
|
407
|
+
hand-off: ${t}`:e??t,bD=e=>{let{entries:t,selected:r,pushed:n,pushAborted:o,abortedBy:s,declined:i,dryRun:a,worktrees:c,verifyFailed:l,handOffs:u,skipped:p,integrationRef:m}=e,f=new Set(n?t.filter(k=>r.includes(k.branch)&&k.mergeSha&&!l?.has(k.branch)).map(k=>k.branch):[]),h=t.filter(k=>r.includes(k.branch)).map(k=>{let F=!!k.mergeSha,v=l?.has(k.branch)??!1,S=l?.get(k.branch),P=o&&F?"push-aborted":k.status,O=v?"verify-failed":P,D=u?.get(k.branch);return{branch:k.branch,status:O,mergeSha:k.mergeSha,conflictPaths:k.conflictPaths,pushed:f.has(k.branch),reason:kD(S,D?.reason)??k.reason,...D?.resolution?{resolution:D.resolution}:{}}}),b=h.filter(k=>!ep.has(k.status));for(let k of h){let F=t.find(v=>v.branch===k.branch);d.info({branch:k.branch,status:k.status,mergeSha:k.mergeSha,conflictCount:k.conflictPaths?.length??0,durationMs:F?.durationMs,pushed:k.pushed,msg:"merge-dev branch result"})}if(i||a)d.info(i?`
|
|
391
408
|
Operation cancelled \u2014 nothing was pushed.
|
|
392
409
|
`:`
|
|
393
410
|
\u{1F50D} Dry run \u2014 nothing was pushed.
|
|
394
|
-
`);else if(
|
|
395
|
-
\u26A0\uFE0F ${
|
|
396
|
-
`);for(let k of
|
|
397
|
-
`);y.print();let
|
|
398
|
-
`).filter(r=>r.trim().length>0)}catch{return[]}},
|
|
399
|
-
`);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},
|
|
400
|
-
|
|
411
|
+
`);else if(b.length>0){d.info(`
|
|
412
|
+
\u26A0\uFE0F ${b.length} branch(es) did not merge.
|
|
413
|
+
`);for(let k of b)d.info(wD(k,c,m))}else d.info(`\u2705 All merges completed successfully!
|
|
414
|
+
`);y.print();let C=a||i;return tp({successfulMerges:C?0:h.filter(k=>ep.has(k.status)).length,failedMerges:C?0:b.length,failedBranches:C?[]:b.map(k=>k.branch),totalBranches:h.length,dryRun:a,atomicPush:{attempted:!a&&!i,aborted:o,abortedBy:s},results:h.map(k=>C?{...k,pushed:!1}:k),skipped:p})},rp=T({name:"gh-merge-dev",description:'Merge origin/dev (origin/main in a repo with "gitFlow": "main") into open regular release branches and push them in one atomic push. A release PR is classified by its base branch, not its title: a PR to main is a hotfix and is skipped, as is any row whose title disagrees with its base or whose head has open PRs to both dev and main \u2014 every skipped row is reported in `skipped` with its reason. Merges happen in a disposable scratch worktree, so no existing checkout is touched and the branches may be checked out elsewhere. When invoked via MCP, pass all=true or an explicit versions list \u2014 the branch picker is unreachable without a TTY, and the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. Irreversible once pushed.',requiresHumanConfirm:!0,inputSchema:{all:x.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls unless `versions` is supplied (the interactive picker is unavailable without a TTY)."),versions:x.union([x.string(),x.array(x.string())]).optional().describe('Target a subset of the open regular release branches. Each entry may be a version label ("1.2.5") or a raw branch name ("release/v1.2.5"). A selector that is not an open regular release is an error; one that names a skipped row (hotfix, title/base mismatch, dual-base) quotes that reason. Takes precedence over `all`.'),dryRun:x.boolean().optional().describe("Compute and print the merge plan without pushing anything."),verify:x.union([x.boolean(),x.string()]).optional().describe("Check each merge before pushing it. `true` runs `pnpm install --frozen-lockfile` \u2014 which catches the characteristic dev\u2192release failure, a pnpm-lock.yaml whose text merge is clean but whose result is broken. A string runs that command instead. A branch that fails verification is dropped from the push; nothing is ever rolled back, because verification runs pre-push. Under `continue`, a string runs after the mandatory `pnpm install --frozen-lockfile --ignore-scripts`."),keepConflicts:x.boolean().optional().describe("On the confirmed run, after the clean branches are pushed, leave each conflicted branch \u2014 and each clean merge that failed `verify` \u2014 mid-merge in a detached worktree under `<root>-worktrees/merge-dev/` for resolution. Excludes `continue`, `abort` and `dryRun`."),continue:x.boolean().optional().describe("Check the selected resolutions (only conflicted paths edited, no markers, install passes), preview them, and on confirmation commit exactly the previewed tree and push atomically. Excludes `keepConflicts`, `abort` and `dryRun`."),abort:x.boolean().optional().describe("Discard the selected resolution worktrees and their state. Excludes `keepConflicts`, `continue` and `dryRun`."),tree:x.union([x.string(),x.array(x.string())]).optional().describe("With `continue` and confirmation: `<branch>=<treeSha>`, comma-separated or repeated \u2014 the trees the human approved in the `continue` preview. Pass the preview `rerun` unchanged; a branch whose resolved tree differs is reported `tree-changed` and not committed."),confirm:x.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{successfulMerges:x.number().describe("Number of branches that reached their desired state"),failedMerges:x.number().describe("Number of branches that did not"),failedBranches:x.array(x.string()).describe("List of branches that did not merge"),totalBranches:x.number().describe("Total number of branches processed"),dryRun:x.boolean().describe("True when nothing was pushed because this was a plan-only run"),atomicPush:x.object({attempted:x.boolean(),aborted:x.boolean(),abortedBy:x.string().optional()}).describe("Outcome of the single all-or-nothing push"),results:x.array(x.object({branch:x.string(),status:x.string(),mergeSha:x.string().optional(),conflictPaths:x.array(x.string()).optional(),pushed:x.boolean(),reason:x.string().optional(),resolution:x.object({worktreePath:x.string(),baseSha:x.string(),devSha:x.string(),conflictPaths:x.array(x.string()),editablePaths:x.array(x.string()).optional(),lockfileOnly:x.boolean(),rererePreResolved:x.array(x.string()),state:x.enum(["needs-agent","lockfile-only","verify-failed","exists"])}).optional().describe("The `keepConflicts` hand-off for a conflicted branch, or for a clean merge that failed verify (`verify-failed`: edit only `editablePaths`)"),blocked:x.object({code:x.enum(["unmerged-paths","markers-remaining","out-of-scope-edit","verify-failed","verify-mutated-tree","parents-mismatch","git-too-old","tree-changed"]),paths:x.array(x.string()).optional(),detail:x.string()}).optional().describe("Why a `continue` run did not commit this resolution")})).describe("Per-branch terminal state"),skipped:x.array(x.object({branch:x.string(),reason:x.enum(["hotfix (targets main)","title/base mismatch","open PRs to both dev and main"])})).describe("Every discovered release PR that was not a merge candidate, with why. Empty only when nothing was discovered.")},handler:Ya});import{z as Vs}from"zod";import{$ as et}from"zx";var Ow=(e,t)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-t).trim()},Wr=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=Ow(t.stderr,500);o&&(r.stderr=o);let s=Ow(t.stdout,200);return s&&(r.stdout=s),r};var Ns="feature/",oo=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${Ns}${t}`};var Ms=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 js=e=>{let{result:t,operation:r}=e,n={removedWorktrees:t.removed,failedWorktrees:t.failed.map(i=>i.branch),count:t.removed.length},o=R(JSON.stringify(n,null,2));if(t.failed.length===0)return{content:o,structuredContent:n};let s={operation:r,remediation:`not removed: ${n.failedWorktrees.join(", ")} \u2014 fix the cause above and re-run`,stderrExcerpt:t.failed.map(i=>`${i.branch}: ${i.reason}`).join("; ")};throw ee()?new A({status:"partial_failure",...n},1,s):new g(void 0,s)};import za from"node:fs/promises";import{$ as op}from"zx";var RD=new Set([".omc",".DS_Store"]),SD=new Set(["state","sessions"]),ED=2e3,Nw="check 'git worktree list' for the path; uncommitted changes block removal",PD=e=>new Promise(t=>{setTimeout(t,e)}),np=e=>typeof e=="object"&&e!==null?e.code:void 0,Dw=e=>{let t=e.length;for(;t>1&&e[t-1]==="/";)t-=1;return e.slice(0,t)},Iw=async e=>{try{return Dw(await za.realpath(e))}catch{return Dw(e)}},xD=async e=>{let{projectRoot:t,worktreePath:r}=e;try{let n=await pt(t),o=await Iw(r);for(let s of n)if(await Iw(s.path)===o)return!0;return!1}catch{return!0}},TD=async e=>{let t;try{t=await za.readdir(e)}catch(n){return{kind:np(n)==="ENOENT"?"gone":"not-sweepable",entries:[]}}if(!t.every(n=>RD.has(n)))return{kind:"not-sweepable",entries:t};if(!t.includes(".omc"))return{kind:"sweepable",entries:t};try{return{kind:(await za.readdir(`${e}/.omc`)).every(s=>SD.has(s))?"sweepable":"not-sweepable",entries:t}}catch(n){return{kind:np(n)==="ENOENT"?"sweepable":"not-sweepable",entries:t}}},_w=async e=>{try{return await za.rm(e,{recursive:!0,force:!0}),"removed"}catch(t){return np(t)==="ENOTEMPTY"?"busy":"failed"}},CD=async e=>{let{worktreePath:t,sleep:r}=e,n=await _w(t);return n!=="busy"?n==="removed":(await r(ED),await _w(t)==="removed")},Fs=(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}},$D=async e=>{let{branch:t,worktreePath:r,projectRoot:n,error:o,sleep:s}=e;if(await xD({projectRoot:n,worktreePath:r}))return Fs(t,o,Nw);let i=await TD(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 CD({worktreePath:r,sleep:s})?Fs(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"})},AD=async e=>{try{return(await op`git -C ${e} status --porcelain`).stdout.split(`
|
|
415
|
+
`).filter(r=>r.trim().length>0)}catch{return[]}},OD=async e=>{let{branch:t,worktreeDir:r,projectRoot:n,orcaProbe:o,sleep:s}=e,i=`${r}/${t}`,a=await AD(i);if(a.length>0)return Fs(t,new Error(`uncommitted changes in ${i}: ${a.slice(0,5).join(", ")}`),Nw);let c=await wg(i,o);if(!c.closed&&"error"in c)return Fs(t,c.error,"close the Orca terminals of this worktree manually (orca terminal close --terminal <handle>) and re-run");try{return await op`git worktree remove ${i}`,{branch:t,status:"removed"}}catch(l){return $D({branch:t,worktreePath:i,projectRoot:n,error:l,sleep:s})}},Gr=async e=>{let{branches:t,worktreeDir:r,projectRoot:n,pruneFolder:o=!1,sleep:s=PD}=e,i=t.length>0?await Zt():"unreachable",a=await Promise.all(t.map(l=>OD({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 op`git worktree prune`,c};var Ls=async(e,t)=>{if(!(await Se("release")).includes(e))return[];let n=await $(),o=`${n}${ce}`,{removed:s,failed:i}=await Gr({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 sp}from"zx";var Bs=async(e,t)=>{let r=await sp({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(`
|
|
416
|
+
`);return{tree:n,conflicts:r.exitCode===1?[...new Set(o.filter(Boolean))]:[]}},Mw=async(e,t)=>(await sp({quiet:!0})`git commit-tree ${e} -p ${t} -m ${"infra-kit deliver preflight"}`).stdout.trim(),Us=(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`})},jw=async e=>{let{releaseBranch:t,viaIntegration:r,syncsDev:n,releaseMerged:o,rcMerged:s}=e,i=`origin/${t}`;if(await sp({quiet:!0})`git fetch origin main ${n?["dev"]:[]} ${o?[]:[t]}`,!r){let c="origin/main";if(!o){let l=await Bs("origin/main",i);Us(`merging ${t} into main`,l),c=await Mw(l.tree,"origin/main")}n&&Us("syncing main back into dev",await Bs("origin/dev",c));return}let a="origin/dev";if(!o){let c=await Bs("origin/dev",i);Us(`merging ${t} into dev`,c),a=await Mw(c.tree,"origin/dev")}s?Us("syncing main back into dev",await Bs(a,"origin/main")):Us("merging dev into main (RC PR)",await Bs("origin/main",a))};var so=async(e,t,r)=>{try{return await r()}catch(n){throw d.debug({err:Wr(n)},`Failed to ${e}`),new g(n,{operation:e,remediation:t})}},Lw=async e=>{let t=Qc(e),r=await et`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},Fw=async()=>{let e=await et`gh pr list --head dev --base main --state open --json number,state,title,baseRefName,headRefName --limit 5`;return JSON.parse(e.stdout)[0]??null},DD=async(e,t)=>{let r=Bt(e),n=await Vd(r);if(n.length>1){let i=n.map(a=>`#${a.number} \u2192 ${a.baseRefName}`).join(", ");throw new g(void 0,{operation:`deliver release ${r}`,remediation:`the branch has open PRs to both dev and main (${i}); close the one that should not be delivered`})}let o=n[0]??await to(r);if(!o)throw d.error(`\u274C No PR found for branch ${r}.`),new g(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});let s=xs(o.baseRefName,t);if(!s){let i=t==="dev"?"dev nor main":`${we} (this repo's "gitFlow": "main")`,a=t==="dev"?"<dev|main>":we;throw new g(void 0,{operation:`deliver release ${r}`,remediation:`PR #${o.number} targets '${o.baseRefName}', which is ${t==="dev"?"neither":"not"} ${i}; retarget it ('gh pr edit ${o.number} --base ${a}')`})}return{selectedReleaseBranch:r,releaseType:s,prNumber:o.number}},ID=async()=>{let e=await K(),t=e.map(i=>i.branch),r=new Map(e.map(i=>[i.branch,i.type]));y.setInteractive();let n=await he(),o=await lr(ye({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}},_D=async e=>{let{selectedReleaseBranch:t,releaseType:r,prNumber:n,flow:o}=e,s=bt(r,o),i=await Wa(n);if(i.state==="MERGED"){d.info(`\u2713 Release PR ${t} already merged \u2014 skipping`);return}if(i.state==="CLOSED")throw new g(void 0,{operation:`merge release PR ${t} into ${s}`,remediation:"the PR is closed without merge; reopen it or create a new release"});if(i.baseRefName!==s||i.headRefName!==t)throw new g(void 0,{operation:`merge release PR #${n} ${t} into ${s}`,remediation:`PR #${n} now reads ${i.headRefName} \u2192 ${i.baseRefName}; it changed since it was resolved \u2014 re-run the command`});await so(`merge release PR #${n} ${t} into ${s}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await et`gh pr merge ${n} --squash --admin --delete-branch`})},ND=async e=>{let t=se(e),r=Qc(e),n=await Fw();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 so(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await et`gh pr edit ${s} --title ${r}`})),s}await so(`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 et`gh pr create --base main --head dev --title ${r} --body ""`});let o=await Fw();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},MD=async e=>{let t=se(e);if(await Lw(e)){d.info(`\u2713 RC PR for ${t} already merged into main \u2014 skipping`);return}let n=await ND(e);await so(`merge RC PR #${n} (dev \u2192 main) for ${t}`,`check 'gh pr view ${n}' for mergeability and required reviews`,async()=>{await et`gh pr merge ${n} --squash --admin`})},jD=async()=>{et.quiet=!1,await so("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await et`gh workflow run deploy-all.yml --ref main -f environment=prod`}),et.quiet=!0},FD=async()=>{await so("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 et`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},LD=async e=>{try{await $i(e)}catch(t){d.warn({err:Wr(t)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Ai(e)}catch(t){d.warn({err:Wr(t)},`Failed to delete remote branch ${e} (non-blocking)`)}},BD=async e=>{let t=await jt();if(!t){d.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let r=de(e);await Xu({versionName:r},t)}catch(r){let n=fs(r)&&r.kind==="auth"?" \u2014 reissue the Atlassian API token and update JIRA_TOKEN":"";d.error({err:Wr(r)},`Failed to deliver Jira release (non-blocking)${n}`)}},Xa=async e=>{let{version:t,confirmedCommand:r}=e;await Le({operation:"deliver release"});let n=await re(),{selectedReleaseBranch:o,releaseType:s,prNumber:i}=t?await DD(t,n):await ID(),a=n==="dev"&&s!=="hotfix",c=te(o);if(!c)throw new g(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=se(c);if(y.addOption("--version",l),d.info(`Delivering ${c.kind==="name"?"named release":"version"} ${o}`),ee())throw new A({status:"refused",agentMode:_.source},2,{operation:`deliver release ${o}`,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 jw({releaseBranch:o,viaIntegration:a,syncsDev:n==="dev",releaseMerged:(await Wa(i)).state==="MERGED",rcMerged:a&&await Lw(c)!==null}),await q(r,`Are you sure you want to deliver version ${o} to production?`),y.addOption("--yes",!0),et.quiet=!0;let p=`${await $()}${ce}`;await Ls(o,{operation:`remove worktree for ${o} before merge`,remediation:`run manually: git worktree remove ${p}/${o} (use --force if uncommitted changes)`}),await _D({selectedReleaseBranch:o,releaseType:s,prNumber:i,flow:n}),a&&await MD(c),await jD(),n==="dev"&&await FD(),await LD(o),et.quiet=!1,await BD(c),d.info(`Successfully delivered ${o} to production!`),y.print();let m={releaseBranch:o,version:l,type:s,success:!0};return{content:R(JSON.stringify(m,null,2)),structuredContent:m}},ip=T({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes, and for every release in a repo with "gitFlow": "main" (no dev branch, no RC PR, no back-sync): 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:Vs.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:Vs.string().describe("The release branch that was delivered"),version:Vs.string().describe("The version that was delivered"),type:Vs.enum(["regular","hotfix"]).describe("Release type"),success:Vs.boolean().describe("Whether the delivery was successful")},handler:Xa});import{z as pr}from"zod";var Za=async()=>{let t=(await K()).flatMap(i=>{let a=te(i.branch);return a?[{version:se(a),jiraKey:de(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Fa(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Cs(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:
|
|
417
|
+
`),d.info(`
|
|
418
|
+
${o.join(`
|
|
419
|
+
`)}
|
|
420
|
+
`);let s={releases:t.map(i=>({version:i.version,type:i.type,description:r.get(i.jiraKey)?.description??null,releaseDate:r.get(i.jiraKey)?.releaseDate??null,titleMismatch:i.titleMismatch})),count:t.length};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}},ap=T({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:pr.array(pr.object({version:pr.string().describe("Release version"),type:pr.enum(["regular","hotfix"]).describe("Release type"),description:pr.string().nullable().describe("Jira version description"),releaseDate:pr.string().nullable().describe("Planned release date of the Jira version (yyyy-mm-dd)"),titleMismatch:pr.boolean().describe("The PR title names a different release type than its base branch")})).describe("List of all release branches"),count:pr.number().describe("Number of release branches")},handler:Za});import UD from"node:process";var Ws="local-deploy";var cp=e=>({...e}),lp=e=>{let{env:t,branch:r,sha:n,isClean:o,ambient:s=UD.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:Ws},contract:i,stripped:c}},Qa=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(`
|
|
421
|
+
`)};import BI from"@inquirer/checkbox";import UI from"@inquirer/confirm";import VI from"@inquirer/select";import{spawn as WI}from"node:child_process";import xp from"node:process";import{z as ne}from"zod";import{$ as Zs}from"zx";import{z as qs}from"zod";import Yw from"node:fs/promises";import yp from"node:path";import{DEPLOY_CONFIG_FILE as ec,deployConfigSchema as VD}from"@slip-stream-kit/config/internal";import WD from"node:fs/promises";import GD from"node:path";import{pathToFileURL as JD}from"node:url";import{z as KD}from"zod";var Rt=async e=>{let t=GD.join(e,ec);try{await WD.access(t)}catch{return}let r=await import(JD(t).href);if(r.default===void 0)throw new Error(`${ec} at ${t} has no default export`);let n=VD.safeParse(r.default);if(!n.success)throw new Error(`Invalid ${ec} at ${t}:
|
|
422
|
+
${KD.prettifyError(n.error)}`);let o=[...qD(n.data),...HD(n.data)];if(o.length>0)throw new Error(`Invalid ${ec} at ${t}:
|
|
401
423
|
${o.join(`
|
|
402
|
-
`)}`);return n.data},
|
|
424
|
+
`)}`);return n.data},HD=e=>e.replaceV1!==!0?[]:ps.filter(t=>!e.environments.includes(t)).map(t=>`\u2716 replaceV1: environments must include '${t}', which delivery dispatches deploy-all.yml with`),qD=e=>{let t=new Set([...e.environments,...ps]);return Object.entries(e.services).flatMap(([r,n])=>["envs","skipEnvs"].flatMap(o=>(n[o]??[]).filter(s=>!t.has(s)).map(s=>`\u2716 services.${r}.${o}: unknown environment '${s}' (known: ${[...t].join(", ")})`)))};var Gs=e=>{let t=new Map;for(let[r,n]of Object.entries(e.services)){if(n.envs!==void 0){t.set(r,[...n.envs]);continue}let o=n.skipEnvs??[],s=e.environments.filter(i=>!o.includes(i));s.length<e.environments.length&&t.set(r,s)}return t};import{serviceDependencies as YD}from"@slip-stream-kit/config/internal";var Ww="28aac6de980c6073d37a872c78309134bf62c47c",Gw=`ArthurSaenz/infra-kit/.github/workflows/ik-deploy-service.yml@${Ww}`,zD=`ArthurSaenz/infra-kit/.github/workflows/ik-install-deps.yml@${Ww}`,oc="install-deps",Bw=25,io="# Generated by `infra-kit deploy-sync` from infra-kit.deploy.ts",sc="skip_terraform_deploy",Jw={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"}}},Kw=(e,t)=>Jw[e.replaceV1===!0?"v1":"pilot"][t],Hw=e=>Object.values(Jw[e]).map(({file:t})=>`.github/workflows/${t}`),up=Hw("pilot"),dp=Hw("v1"),rc=e=>e.replace(/^_/,"").replace(/(?:-jobs)?\.ya?ml$/,""),XD=(e,t)=>{let r=Object.entries(e.services).flatMap(([o,s])=>{if(t==="all"&&s.deployAll===!1)return[];let i=t==="all"&&Array.isArray(s.deployAll)?s.deployAll:void 0,a=e.environments.filter(c=>(s.envs?.includes(c)??!0)&&!(s.skipEnvs?.includes(c)??!1)&&(i?.includes(c)??!0));return a.length===0?[]:[{name:o,service:s,gate:a.length===e.environments.length?void 0:a,triggers:void 0}]}),n=new Set(r.map(o=>o.name));return r.flatMap(o=>{if(o.service.runsBefore===void 0)return[o];let s=o.service.runsBefore.filter(i=>n.has(i));return s.length===0?[]:[{...o,triggers:s}]})},pp=e=>e.filter(t=>t.triggers===void 0),Z=e=>`\${{ ${e} }}`,tc=e=>Z(`secrets[format('{0}_${e}', inputs.environment)]`),ZD=e=>[oc,...e.terraform,...e.preDeploy],mp=e=>e.map(t=>`(needs.${t}.result == 'success' || needs.${t}.result == 'skipped')`),QD=e=>[`needs.${oc}.result == 'success'`,...mp(e.terraform),...e.preDeploy.map(t=>`needs.${t}.result == 'success'`)],eI=(e,t,r,n)=>{let o=[];return t==="selected"&&o.push(e.triggers===void 0?`inputs.${e.name}`:`(${e.triggers.map(s=>`inputs.${s}`).join(" || ")})`),e.gate!==void 0&&o.push(`contains(fromJSON('${JSON.stringify(e.gate)}'), inputs.environment)`),o.push("!cancelled()",...QD(r),...mp(n.map(nc))),Z(o.join(" && "))},nc=e=>`deploy-${e}`,fp=e=>e.length===0?[]:[` needs: [ ${e.join(", ")} ]`],qw=e=>e===void 0?[]:[` if: ${e}`],gp=e=>[` uses: ./.github/workflows/${e}`," with:",` branch: ${Z("github.ref")}`,` environment: ${Z("inputs.environment")}`," secrets: inherit"],tI=(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: ${Gw}`," with:",` environment: ${Z("inputs.environment")}`,` ref: ${Z("github.ref")}`,` sha: ${Z("github.sha")}`,` service: ${e.name}`,` infra-kit-version: ${U.version}`,...n,...o,...t.doppler===void 0?[]:[` doppler-project: ${t.doppler.project}`]," secrets:",...t.doppler===void 0?[` aws-access-key-id: ${tc("AWS_ACCESS_KEY_ID")}`,` aws-secret-access-key: ${tc("AWS_SECRET_ACCESS_KEY")}`,` aws-region: ${tc("AWS_REGION")}`]:[` doppler-token: ${tc("DOPPLER_TOKEN")}`],` serverless-access-key: ${Z("secrets.SERVERLESS_ACCESS_KEY")}`,` slack-token: ${Z("secrets.SLACK_TOKEN")}`,` slack-channel: ${Z("secrets.SLACK_CHANNEL")}`,...s]},rI=(e,t,r,n,o)=>{let s=e.service.workflow===void 0?tI(e,n):gp(e.service.workflow);return["",` ${nc(e.name)}:`,...fp([...ZD(r),...o.map(nc)]),...qw(eI(e,t,r,o)),...s]},Uw=(e,t)=>["",` ${e}:`," type: boolean",` description: '${t}'`," required: false"," default: false"],nI=(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?Uw(sc,"Skip terraform deployment"):[],s=t==="all"?[]:pp(r).flatMap(i=>{let a=i.gate===void 0?"":` (${i.gate.join(", ")} only)`;return Uw(i.name,`Deploy ${i.name}${a}`)});return["on:"," workflow_dispatch:"," inputs:",...n,...o,...s]},oI=e=>pp(e).map(t=>Z(`inputs.${t.name} && ''${t.name} '' || ''''`)).join(""),sI=(e,t,r)=>{let{title:n,concurrency:o}=Kw(e,t),s=(e.terraform??[]).length>0?Z(`inputs.${sc} && '' \u2014 skip TF'' || ''''`):"",i=t==="selected"?` \u2014 ${oI(r)}`:"";return[`${io}: 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",""]},iI=e=>{let t=Z(`!inputs.${sc}`);return["",` ${rc(e)}:`,` if: ${t}`,...gp(e)]},aI=(e,t)=>{let r=t.length===0?void 0:Z(["!cancelled()",...mp(t)].join(" && "));return["",` ${rc(e)}:`,...fp(t),...qw(r),...gp(e)]},cI=()=>["",` ${oc}:`,` uses: ${zD}`," with:",` ref: ${Z("github.ref")}`,` sha: ${Z("github.sha")}`," secrets:",` slack-token: ${Z("secrets.SLACK_TOKEN")}`,` slack-channel: ${Z("secrets.SLACK_CHANNEL")}`],lI=(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)}},uI=(e,t)=>[""," notify-success:",...fp(t),` if: ${Z("!cancelled() && contains(needs.*.result, 'success') && !contains(needs.*.result, 'failure')")}`,` uses: ./.github/workflows/${e}`," secrets: inherit"],Vw=(e,t)=>{let r=XD(e,t),n=e.terraform??[],o=e.preDeploy??[],s={terraform:n.map(rc),preDeploy:o.map(rc)},{file:i}=Kw(e,t),a=1+(n.length>0?1:0)+(t==="selected"?pp(r).length:0);if(a>Bw){let h=n.length>0?`environment, ${sc}`:"environment";throw new Error(`${i} would need ${a} dispatch inputs (${h} and one checkbox per service); GitHub allows ${Bw}. Fold services that always deploy together into one deploy script.`)}let c=r.map(h=>nc(h.name)),l=new Set(r.map(h=>h.name)),u=YD(e.services),p=h=>(u.get(h)??[]).filter(b=>l.has(b));lI([oc,...s.terraform,...s.preDeploy,...c,...e.notifySuccess===void 0?[]:["notify-success"]],i);let f=`${[...sI(e,t,r),...nI(e,t,r),"","permissions:"," contents: read","","jobs:",...cI(),...n.flatMap(iI),...o.flatMap(h=>aI(h,s.terraform)),...r.flatMap(h=>rI(h,t,s,e,p(h.name))),...e.notifySuccess===void 0?[]:uI(e.notifySuccess,c)].join(`
|
|
403
425
|
`).replace(`jobs:
|
|
404
426
|
|
|
405
427
|
`,`jobs:
|
|
406
428
|
`)}
|
|
407
|
-
`;return{path:`.github/workflows/${i}`,content:f}},Ed=e=>[tw(e,"all"),tw(e,"selected")];var lw=".github/workflows",JO=/script_name:\s*(?<service>[a-z0-9-]+)/,KO=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,HO=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,xd=async e=>{let t=Pd.resolve(e,lw),r;try{r=await cw.readdir(t)}catch{return new Map}return uw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},hs=async(e,t)=>uw(e,[t]),uw=async(e,t)=>{let r=Pd.resolve(e,lw),n=new Map,o=!1;for(let s of t){let i;try{i=await cw.readFile(Pd.resolve(r,s),"utf-8")}catch{continue}i.startsWith(Fn)?o=!0:YO(i,n)}return o&&dw(n,await qO(e)),n},qO=async e=>{try{let t=await vt(e);return t?.replaceV1===!0?gs(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},dw=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},YO=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=JO.exec(r)?.groups?.service??KO.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(HO)].map(s=>s.groups?.env??"");o.length!==0&&dw(t,new Map([[n,o]]))}},ys=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import zO from"node:fs/promises";import XO from"node:path";import ZO from"yaml";var QO=".github/workflows",eD="skip_terraform_deploy",vs=async(e,t)=>{let r=XO.resolve(e,QO,t),n;try{n=ZO.parse(await zO.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!==eD).map(([i])=>i)};var pw="dev",Td=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mw=(e,t)=>e[t]===void 0,fw=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},Cd=async e=>{try{return await e}catch{return[]}},tD=async()=>{let e=await G();return Dt(e.map(t=>t.branch))},rD=(e,t)=>{let r=e.filter(o=>t.get(o)!==void 0);if(r.length===0)return"none declared.";let n=r.map(o=>`${o}: ${(t.get(o)??[]).join(", ")} only.`).join(" ");return r.length<e.length?`${n} Others: any environment.`:n},Dr=e=>{let{workflowFile:t,fields:r,toolName:n}=e,o=c=>(d.info({msg:`Tool execution form options empty (${t}): ${n}`,emptyList:c}),null),s=async c=>{let l=await Cd(tD());if(l.length===0)return null;let u=fw(c,"version");return ws.enum([...new Set([...l,pw])]).optional().describe(`Which release to deploy from. "${pw}" deploys from the dev branch instead of a release branch. ${u===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${u}".`}`)},i=async c=>{let l=Vt(await Cd(Gt(t)),await it());if(l.length===0)return null;let u=l.filter(oo),p=l.filter(f=>!oo(f)),m=fw(c,"env");return ws.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await $(),l=await Cd(vs(c,t));if(l.length===0)return null;let u=await hs(c,t);return ws.array(ws.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${rD(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=>Td(c)?r.some(l=>mw(c,l)):!1,buildRequestedSchema:async c=>{let l=Td(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")&&mw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):ws.object(u)},toArgs:(c,l)=>{let u={...Td(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 nD from"@inquirer/select";var Ln=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return _(r=>nD({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import oD from"@inquirer/confirm";var ks=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;X()&&li(o,{branch:r,env:n}),y.setInteractive();let s=await _(i=>oD({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import sD from"@inquirer/select";import iD from"node:process";var $d=()=>!X()&&iD.stdin.isTTY===!0,aD={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Ad=async()=>_(e=>sD({message:"\u{1F680} Where should this deploy run?",choices:tr.filter(t=>t!=="local").map(t=>({name:t,value:t,description:aD[t]}))},e),{whenHeadless:"refuse"});var tr=["ci","local"],cD={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},gw=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${tr.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw X()?new O({status:"argument_required",argument:"from",agentMode:j.source},2,r):new g(void 0,r)}let t=tr.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${tr.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},Od=(e,t)=>{let n=cD[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}`})},Dd=async e=>e||!$d()?gw(e):Ad();var bs=async e=>{if(e)return e==="dev"?"dev":Ot(e);y.setInteractive();let t=await G(),r=t.map(s=>s.branch),n=new Map(t.map(s=>[s.branch,s.type])),o=await me();return qt([{value:"dev",label:"dev"},...fe({branches:r,descriptions:o,types:n})])};var hw="deploy-all.yml",yw=Dr({workflowFile:hw,fields:["version","env"],toolName:"gh-release-deploy-all"}),$a=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await at({provider:yw,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await bs(t),i=jo(s);y.addOption("--version",i);let a=await it(),c=Vt(await Gt(hw),a),l="";r?l=r:(y.setInteractive(),l=await Ln(c,"launch deploy-all workflow")),y.addOption("--env",l),Kr(l,"launch deploy-all workflow",a),di({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await ks({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:b(JSON.stringify(p,null,2)),structuredContent:p}}try{Id.quiet=!0,await Id`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Id.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"})}},Nd=C({name:"gh-release-deploy-all",formProvider:yw,description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Omit "version" or "env" and this server offers the human a form listing the real releases and the environments this workflow declares; a client that cannot render one gets a refusal naming the missing field, never a guess.',requiresHumanConfirm:!0,inputSchema:{version:Nt.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:Nt.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-all.yml declares.'),skipTerraform:Nt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Nt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Nt.string().describe("The release branch that was deployed"),version:Nt.string().describe("The version that was deployed"),environment:Nt.string().describe("The environment deployed to"),skipTerraformDeploy:Nt.boolean().describe("Whether terraform deployment was skipped"),success:Nt.boolean().describe("Whether the deployment was successful")},handler:$a});import lD from"@inquirer/checkbox";import{z as je}from"zod";import{$ as _d}from"zx";var Ir="deploy-selected-services.yml",vw=Dr({workflowFile:Ir,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),Aa=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await at({provider:vw,params:e,operation:"launch deploy-selected workflow",argument:v=>v[0]??"version"});let i=await bs(t),a=jo(i);y.addOption("--version",a);let c=await it(),l=Vt(await Gt(Ir),c),u="";r?u=r:(y.setInteractive(),u=await Ln(l,"launch deploy-selected workflow")),y.addOption("--env",u),Kr(u,"launch deploy-selected workflow",c),di({env:u,branch:i});let p=await $(),m=await vs(p,Ir);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Ir}`,stderrExcerpt:`no services found in .github/workflows/${Ir}`});let f=[];if(n&&n.length>0?f=n:(y.setInteractive(),f=await _(v=>lD({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(R=>({name:R,value:R}))},v),{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 h=f.filter(v=>!m.includes(v));if(h.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let S=await hs(p,Ir),k=f.filter(v=>{let R=S.get(v);return R!==void 0&&!R.includes(u)});if(k.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:k.map(v=>`${v} deploys only to: ${(S.get(v)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Ir} gates these services out of ${u}: ${k.join(", ")}`});let A=o??!1;A&&y.addOption("--skip-terraform",!0);let M=v=>{let R={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:A,success:v};return{content:b(JSON.stringify(R,null,2)),structuredContent:R}};if(!await ks({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),M(!1);try{_d.quiet=!0;let v=f.flatMap(T=>["-f",`${T}=true`]);return await _d`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${v} ${A?["-f","skip_terraform_deploy=true"]:[]}`,_d.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),y.print(),M(!0)}catch(v){throw d.error({error:v},"\u274C Error launching workflow"),new g(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Md=C({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:vw,description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow, and a service the target environment gates out is refused BEFORE dispatch rather than dispatched and silently skipped. Use gh-release-deploy-all for every service. Omit any of "version", "env" or "services" and this server offers the human a form built from the real releases, environments and services; a client that cannot render one gets a refusal naming the missing field, never a guess.',inputSchema:{version:je.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Omit it to be offered the open releases.'),env:je.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-selected-services.yml declares.'),services:je.array(je.string()).optional().describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Some services are gated to particular environments by that workflow and are refused here rather than skipped by CI. Omit it to be offered the declared services.'),skipTerraform:je.boolean().optional().describe("Skip the terraform deployment stage."),confirm:je.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:je.string().describe("The release branch that was deployed"),version:je.string().describe("The version that was deployed"),environment:je.string().describe("The environment deployed to"),services:je.array(je.string()).describe("The services that were deployed"),skipTerraformDeploy:je.boolean().describe("Whether terraform deployment was skipped"),success:je.boolean().describe("Whether the deployment was successful")},handler:Aa});import{z as rr}from"zod";var Oa=async()=>{let t=(await G()).flatMap(i=>{let a=Q(i.branch);return a?[{version:ne(a),jiraKey:le(a),type:i.type,titleMismatch:i.titleMismatch}]:[]}),r=await Vi(),n=Math.max(...t.map(i=>i.version.length)),o=t.map(i=>{let a=Mo(i.version,i.type,n),c=r.get(i.jiraKey),l=c?.description?` ${c.description}`:"",u=c?.releaseDate?` \xB7 ships ${c.releaseDate}`:"",p=i.titleMismatch?" \u26A0 title/base mismatch":"";return`${a}${l}${u}${p}`});d.info(`All release branches:
|
|
408
|
-
`),d.info(`
|
|
409
|
-
${
|
|
410
|
-
`)}
|
|
411
|
-
`);
|
|
412
|
-
`)};import TD from"@inquirer/checkbox";import CD from"@inquirer/confirm";import $D from"@inquirer/select";import{spawn as AD}from"node:child_process";import Jd from"node:process";import{z as te}from"zod";import{$ as xs}from"zx";import{$ as Ss}from"zx";var dD=async e=>{let t=Ss.quiet;Ss.quiet=!0;try{let r=`/${e}/environment`,n=await Ss`aws sts get-caller-identity --query Account --output text`,o=await Ss`aws ssm get-parameter --name ${r} --query Parameter.Value --output text`;return{accountId:n.stdout.trim(),stage:o.stdout.trim()}}catch(r){throw new g(r,{operation:"resolve the AWS account for this deploy",remediation:`check that credentials are loaded and that \`/${e}/environment\` exists in the account they point at \u2014 run \`aws sts get-caller-identity\` to see which account that is`})}finally{Ss.quiet=t}},ww=(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`})},kw=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"})},bw=(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`})},Bd=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Kr(t,`deploy to "${t}"`,i),bw(t,s),kw({env:t,isShared:n,isClean:o});let a=await dD(r);return ww(t,a),{identity:a}};import{serviceDependencies as pD}from"@slip-stream-kit/config/internal";import Ud from"node:fs/promises";import Es from"node:path";var Ew="devops/scripts",mD=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,fD=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,gD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,hD=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,yD=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,vD=/`[^`]*\$\{[^`]*\/environment[^`]*`/,Rw={commentPrefixes:["#"],literalPrefix:e=>hD.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=gD.exec(e)?.groups?.arg;return t!==void 0&&SD(t)}},Sw={commentPrefixes:["//","/*","*"],literalPrefix:e=>yD.exec(e)?.groups?.prefix,isUnparseable:e=>vD.test(e)},Wd=async e=>{let t=await vt(e),r=await xd(e);return(t===void 0?await wD(e,r):await kD(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},wD=async(e,t)=>{let r=Es.resolve(e,Ew),n;try{n=await Ud.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=mD.exec(o)?.groups?.service;return s===void 0?[]:[Pw(s,Es.resolve(r,o),t)]}))},Pw=async(e,t,r)=>{let n=Tw(await xw(t),Rw);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:ys(RD(n),r.get(e)),ssmPrefix:Cw(n,Rw)}},kD=async(e,t,r)=>{let n=gs(t),o=pD(t.services),s=(a,c)=>({...(o.get(a)??[]).length===0?{}:{dependsOn:o.get(a)},...c.runsBefore===void 0?{}:{runsBefore:[...c.runsBefore]}});return(await Promise.all(Object.entries(t.services).map(async([a,c])=>{if(c.deploy===void 0){let p=Es.resolve(e,Ew,`deploy-${a}.sh`);if(!await bD(p))return null;let m=await Pw(a,p,r);return{...m,allowedEnvs:ys(m.allowedEnvs,n.get(a)),...s(a,c)}}let l=Es.resolve(e,c.deploy),u=Tw(await xw(l),Sw);return{name:a,scriptPath:l,runner:"deploy-run",allowedEnvs:ys(n.get(a)??null,r.get(a)),ssmPrefix:Cw(u,Sw),...s(a,c)}}))).filter(a=>a!==null)},bD=async e=>{try{return await Ud.access(e),!0}catch{return!1}},xw=async e=>{try{return await Ud.readFile(e,"utf-8")}catch{return""}},Tw=(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))}),RD=e=>{let t=e.reduce((n,{text:o})=>n??fD.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},SD=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},Cw=(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},$w=e=>{let t=Es.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},ED=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],$w(r)]);return t},PD=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${$w(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("; ")})},xD=e=>{PD(e);let t=ED(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},Aw=async(e,t)=>(await vt(e))?.project??xD(t),Ps=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Vd=(e,t)=>e.filter(r=>r.runsBefore===void 0&&Ps(r,t)),Ow=(e,t,r)=>{let n=new Set(e.map(l=>l.name)),o=t.filter(l=>!n.has(l.name)&&Ps(l,r)&&(l.runsBefore??[]).some(u=>n.has(u))),s=new Map([...o,...e].map(l=>[l.name,l])),i=[],a=new Set,c=l=>{if(!a.has(l.name)){a.add(l.name);for(let u of l.dependsOn??[]){let p=s.get(u);p!==void 0&&c(p)}i.push(l)}};for(let l of e)c(l);return i};var Kd="deploy-all.yml",OD="/bin/sh",DD=async()=>{let e=xs.quiet;xs.quiet=!0;try{let t=await xs`gh run list --workflow=${Kd} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{xs.quiet=e}},ID=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await _(o=>TD({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},ND=async e=>{let{env:t,isShared:r,names:n,accountId:o}=e,s=n.length,i=r?`"${t}" is a SHARED environment \u2014 deploying ${s} service(s) from this machine. Continue?`:`Deploy ${s} service(s) to ${t} from this machine?`;return X()&&li(i,{env:t,services:n,accountId:o,shared:r}),r?_(a=>$D({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):_(a=>CD({message:i,default:!1},a),{whenHeadless:"refuse"})},Iw=e=>e.runner==="sh"?[OD,[e.scriptPath]]:[Jd.execPath,[Jd.argv[1]??"","deploy-run",e.name]],_D=(e,t,r)=>new Promise((n,o)=>{let[s,i]=Iw(e),a=AD(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),MD=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 _D(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}},jD=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&&!Ps(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))},Gd=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:Fd(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},FD=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(),ID(r,o))},Nw=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await $(),c=await Wd(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has infra-kit.deploy.ts or devops/scripts/deploy-*.sh",stderrExcerpt:`no deployable services found under ${a}`});let l=await Aw(a,c);await at({provider:Hd[t],params:e,operation:"deploy locally",argument:"env"});let u=await it(),p=Vt(await Gt(Kd),u),m=r??"";m||(y.setInteractive(),m=await Ln(p,"deploy locally")),y.addOption("--env",m);let f=Vd(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 h=await FD({selection:t,eligible:f,service:n,env:m}),S=Ow(jD({names:h,services:c,env:m}),c,m);if(t==="selected")for(let we of h)y.addOption("--service",we);let k=oo(m),A=await Vr(),M=(await xs`git rev-parse HEAD`.quiet()).stdout.trim(),v=await cf(),R=Ld({env:m,branch:A,sha:M,isClean:v});i&&d.info(`Deploy contract for ${m}:
|
|
414
|
-
${Da(R)}`);let E=(await Bd({env:m,project:l,isShared:k,isClean:v,runningEnvs:await DD(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${E}) from this machine`,`Preflight parameter: /${l}/environment`,Da(R),"Commands:",...S.map(we=>` ${Iw(we).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
|
|
415
|
-
`)),Gd({env:m,accountId:E,names:h,built:R,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await ND({env:m,isShared:k,names:h,accountId:E}))return d.info("Deployment cancelled"),Gd({env:m,accountId:E,names:h,built:R,deployed:[],failed:[],dryRun:!1,success:!1});R.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${R.stripped.join(", ")}`);let{deployed:B,failed:Z}=await MD({chosen:S,childEnv:R.childEnv,cwd:a,env:m});return Z.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${B.join(", ")||"none"}], failed [${Z.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),Jd.exitCode=1),y.print(),Gd({env:m,accountId:E,names:h,built:R,deployed:B,failed:Z,dryRun:!1,success:Z.length===0})},_w=async e=>Nw(e,"all"),Mw=async e=>Nw(e,"selected"),jw='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.',Fw={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.")},Lw={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")},Dw=e=>Dr({workflowFile:Kd,fields:["env"],toolName:e}),Hd={all:Dw("local-deploy-all"),selected:Dw("local-deploy-selected")},qd=C({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${jw}`,requiresHumanConfirm:!0,formProvider:Hd.all,inputSchema:Fw,outputSchema:Lw,handler:_w}),Yd=C({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${jw}`,requiresHumanConfirm:!0,formProvider:Hd.selected,inputSchema:{...Fw,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:Lw,handler:Mw});import UD from"@inquirer/confirm";import Ia from"@inquirer/input";import Vw from"@inquirer/select";import Xd from"node:process";import{z as H}from"zod";import{z as Ts}from"zod";var Bn=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Ww=2500,Bw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Uw=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,LD=async()=>{let e=await Qo();return{regular:_n(e,"regular"),hotfix:_n(e,"hotfix")}},BD=(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).`,zd=(e={})=>{let t=e.hintBudgetMs??Ww;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=>Bw(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await Bn(LD(),t);return Ts.object({type:Ts.enum(["regular","hotfix"]).describe('Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Ts.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. ${BD(r,t)}`),description:Ts.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Ts.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=Uw(r.description),a=Uw(r.releaseDate),c=ua(o);return{...Bw(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var WD='"1.2.5" or "next"',Zd=(e,t)=>{try{return Gu(e,t)}catch(r){throw r instanceof Pr?new g(r,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):r instanceof nf?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}},VD=async(e,t)=>{let r=_n(e,t),n=r?` [${r}]`:"",o=(await _(i=>Ia({message:` Version (e.g. ${WD})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Xd.exit(1)),s},GD=async()=>{let e=(await _(t=>Ia({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Xd.exit(1));try{ri(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Xd.exit(1)}return e},JD=async()=>(await _(e=>Ia({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:Zo},e),{whenHeadless:"refuse"})).trim(),KD=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=>Vw({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=>Vw({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 GD();l=Zd([{name:m,type:c}],[])[0]}else{let m=await VD(await n(),c);l=Zd([{version:m,type:c}],r)[0],l.id.kind==="version"&&r.push(Zt(`v${l.id.raw}`))}let u=(await _(m=>Ia({message:" Description (optional, press Enter to skip): "},m),{whenHeadless:"refuse"})).trim(),p=await JD();o.push({...l,...u!==""?{description:u}:{},...p!==""?{releaseDate:p}:{}}),s=await _(m=>UD({message:"Add another release?",default:!1},m),{whenHeadless:"refuse"})}return o},HD=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 ")},Gw=e=>{for(let t of e)y.addOption("--release",Vu(t))},qD=async(e,t)=>{if(e&&e.length>0){let n=Ju(e)?await t():[],o=Zd(e,n);return Gw(o),o}if(he())throw new O({status:"argument_required",argument:"release",agentMode:j.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await KD(t);return Gw(r),r},YD=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"})},zD=async(e,t)=>{let r=e.map(HD).join(`
|
|
416
|
-
- `);await J(t,`Create the following ${e.length} release(s)?
|
|
429
|
+
`;return{path:`.github/workflows/${i}`,content:f}},hp=e=>[Vw(e,"all"),Vw(e,"selected")];var zw=".github/workflows",dI=/script_name:\s*(?<service>[a-z0-9-]+)/,pI=/uses:\s*\.\/\.github\/workflows\/_deploy-(?<service>[a-z0-9-]+)-jobs\.ya?ml/,mI=/inputs\.environment\s*==\s*'(?<env>[a-z0-9-]+)'/g,vp=async e=>{let t=yp.resolve(e,zw),r;try{r=await Yw.readdir(t)}catch{return new Map}return Xw(e,r.filter(n=>n.endsWith(".yml")||n.endsWith(".yaml")))},Js=async(e,t)=>Xw(e,[t]),Xw=async(e,t)=>{let r=yp.resolve(e,zw),n=new Map,o=!1;for(let s of t){let i;try{i=await Yw.readFile(yp.resolve(r,s),"utf-8")}catch{continue}i.startsWith(io)?o=!0:gI(i,n)}return o&&Zw(n,await fI(e)),n},fI=async e=>{try{let t=await Rt(e);return t?.replaceV1===!0?Gs(t):new Map}catch(t){return d.warn(`Deploy gates unavailable, nothing is refused before dispatch: ${t.message}`),new Map}},Zw=(e,t)=>{for(let[r,n]of t)e.set(r,[...new Set([...e.get(r)??[],...n])])},gI=(e,t)=>{for(let r of e.split(/\n(?= {2}[\w-]+:)/i)){let n=dI.exec(r)?.groups?.service??pI.exec(r)?.groups?.service;if(n===void 0||r.trimStart().startsWith("#"))continue;let o=[...r.matchAll(mI)].map(s=>s.groups?.env??"");o.length!==0&&Zw(t,new Map([[n,o]]))}},Ks=(e,t)=>e===null?t??null:t===void 0?e:e.filter(r=>t.includes(r));import hI from"node:fs/promises";import yI from"node:path";import vI from"yaml";var wI=".github/workflows",kI="skip_terraform_deploy",Hs=async(e,t)=>{let r=yI.resolve(e,wI,t),n;try{n=vI.parse(await hI.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!==kI).map(([i])=>i)};var wp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qw=(e,t)=>e[t]===void 0,ek=(e,t)=>{let r=e[t];return typeof r=="string"&&r.length>0?r:void 0},kp=async e=>{try{return await e}catch{return[]}},bI=async()=>{let e=await K();return Ut(e.map(t=>t.branch))},RI=(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},Jr=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 kp(bI());if(l.length===0)return null;let u=ek(c,"version"),p=await Fr();return qs.enum([...new Set([...l,p])]).optional().describe(`Which release to deploy from. "${p}" deploys from the ${p} branch instead of a release branch. ${u===void 0?"Leaving it blank sends no version, and the tool will refuse rather than guess one.":`Leave it blank to keep the caller's "${u}".`}`)},i=async c=>{let l=_t(await kp(Nt(t)),await at());if(l.length===0)return null;let u=l.filter(Bn),p=l.filter(f=>!Bn(f)),m=ek(c,"env");return qs.enum(l).optional().describe(`Target environment. Shared with the whole team: ${u.length>0?u.join(", "):"none"}. Personal accounts: ${p.length>0?p.join(", "):"none"}. This list is read from .github/workflows/${t} in the WORKING TREE, not from the branch being deployed or from GitHub. ${m===void 0?"Leaving it blank sends no environment at all.":`Leave it blank to keep the caller's "${m}" \u2014 including when this tree does not declare it.`}`)},a=async()=>{let c=await $(),l=await kp(Hs(c,t));if(l.length===0)return null;let u=await Js(c,t);return qs.array(qs.enum(l)).optional().describe(`Services to deploy. Environment gates declared by ${t} \u2014 ${RI(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=>wp(c)?r.some(l=>Qw(c,l)):!1,buildRequestedSchema:async c=>{let l=wp(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")&&Qw(l,"services")){let p=await a();if(p===null)return o("services");u.services=p}return Object.keys(u).length===0?o("fields"):qs.object(u)},toArgs:(c,l)=>{let u={...wp(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 SI from"@inquirer/select";var ao=async(e,t)=>{if(e.length===0)throw new g(void 0,{operation:t,remediation:"pass --env <name> explicitly",stderrExcerpt:"the workflow declares no `environment` choices to pick from"});return N(r=>SI({message:"\u{1F9EA} Select environment",choices:e.map(n=>({name:n,value:n}))},r),{whenHeadless:"refuse"})};import{$ as Ys}from"zx";var EI=async e=>{let t=Ys.quiet;Ys.quiet=!0;try{let r=`/${e}/environment`,n=await Ys`aws sts get-caller-identity --query Account --output text`,o=await Ys`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{Ys.quiet=t}},tk=(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`})},rk=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"})},nk=(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`})},bp=async e=>{let{env:t,project:r,isShared:n,isClean:o,runningEnvs:s,protectedEnvAccess:i}=e;Or(t,`deploy to "${t}"`,i),nk(t,s),rk({env:t,isShared:n,isClean:o});let a=await EI(r);return tk(t,a),{identity:a}};import{serviceDependencies as PI}from"@slip-stream-kit/config/internal";import Rp from"node:fs/promises";import zs from"node:path";var ik="devops/scripts",xI=/^deploy-(?<service>[a-z0-9-]+)\.sh$/,TI=/skip_unless_env_enabled\s+"[^"]*"\s+"[^"]*"\s+"(?<envs>[^"]*)"/,CI=/aws\s+ssm\s+get-parameter\s+--name[=\s]+(?<arg>[^\s)]+)/,$I=/aws\s+ssm\s+get-parameter\s+--name[=\s]+["']?\/(?<prefix>[\w.-]+)\/environment["']?(?![\w./-])/,AI=/(["'`])\/(?<prefix>[\w.-]+)\/environment\1/,OI=/`[^`]*\$\{[^`]*\/environment[^`]*`/,ok={commentPrefixes:["#"],literalPrefix:e=>$I.exec(e)?.groups?.prefix,isUnparseable:e=>{let t=CI.exec(e)?.groups?.arg;return t!==void 0&&MI(t)}},sk={commentPrefixes:["//","/*","*"],literalPrefix:e=>AI.exec(e)?.groups?.prefix,isUnparseable:e=>OI.test(e)},Sp=async e=>{let t=await Rt(e),r=await vp(e);return(t===void 0?await DI(e,r):await II(e,t,r)).sort((o,s)=>o.name.localeCompare(s.name))},DI=async(e,t)=>{let r=zs.resolve(e,ik),n;try{n=await Rp.readdir(r)}catch{return[]}return Promise.all(n.flatMap(o=>{let s=xI.exec(o)?.groups?.service;return s===void 0?[]:[ak(s,zs.resolve(r,o),t)]}))},ak=async(e,t,r)=>{let n=lk(await ck(t),ok);return{name:e,scriptPath:t,runner:"sh",allowedEnvs:Ks(NI(n),r.get(e)),ssmPrefix:uk(n,ok)}},II=async(e,t,r)=>{let n=Gs(t),o=PI(t.services),s=(a,c)=>({...(o.get(a)??[]).length===0?{}:{dependsOn:o.get(a)},...c.runsBefore===void 0?{}:{runsBefore:[...c.runsBefore]}});return(await Promise.all(Object.entries(t.services).map(async([a,c])=>{if(c.deploy===void 0){let p=zs.resolve(e,ik,`deploy-${a}.sh`);if(!await _I(p))return null;let m=await ak(a,p,r);return{...m,allowedEnvs:Ks(m.allowedEnvs,n.get(a)),...s(a,c)}}let l=zs.resolve(e,c.deploy),u=lk(await ck(l),sk);return{name:a,scriptPath:l,runner:"deploy-run",allowedEnvs:Ks(n.get(a)??null,r.get(a)),ssmPrefix:uk(u,sk),...s(a,c)}}))).filter(a=>a!==null)},_I=async e=>{try{return await Rp.access(e),!0}catch{return!1}},ck=async e=>{try{return await Rp.readFile(e,"utf-8")}catch{return""}},lk=(e,t)=>e.split(`
|
|
430
|
+
`).map((r,n)=>({line:n+1,text:r})).filter(({text:r})=>{let n=r.trimStart();return!t.commentPrefixes.some(o=>n.startsWith(o))}),NI=e=>{let t=e.reduce((n,{text:o})=>n??TI.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},MI=e=>{let t=e.replaceAll(/["']/g,"");return t.includes("$")&&(t.includes("/environment")||t.startsWith("$"))},uk=(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},dk=e=>{let t=zs.basename(e.scriptPath);return e.runner==="sh"?t:`${e.name} (${t})`},jI=e=>{let t=new Map;for(let r of e)typeof r.ssmPrefix=="string"&&t.set(r.ssmPrefix,[...t.get(r.ssmPrefix)??[],dk(r)]);return t},FI=e=>{let t=e.flatMap(r=>{if(r.ssmPrefix===null||typeof r.ssmPrefix=="string")return[];let{line:n,text:o}=r.ssmPrefix.unparseable;return[`${dk(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("; ")})},LI=e=>{FI(e);let t=jI(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},pk=async(e,t)=>(await Rt(e))?.project??LI(t),Xs=(e,t)=>e.allowedEnvs===null||e.allowedEnvs.includes(t),Ep=(e,t)=>e.filter(r=>r.runsBefore===void 0&&Xs(r,t)),mk=(e,t,r)=>{let n=new Set(e.map(l=>l.name)),o=t.filter(l=>!n.has(l.name)&&Xs(l,r)&&(l.runsBefore??[]).some(u=>n.has(u))),s=new Map([...o,...e].map(l=>[l.name,l])),i=[],a=new Set,c=l=>{if(!a.has(l.name)){a.add(l.name);for(let u of l.dependsOn??[]){let p=s.get(u);p!==void 0&&c(p)}i.push(l)}};for(let l of e)c(l);return i};var Tp="deploy-all.yml",GI="/bin/sh",JI=async()=>{let e=Zs.quiet;Zs.quiet=!0;try{let t=await Zs`gh run list --workflow=${Tp} --status=in_progress --json displayTitle`;return JSON.parse(t.stdout).flatMap(n=>/\[(?<env>[a-z0-9-]+)\]/.exec(n.displayTitle??"")?.groups?.env??[])}catch{return[]}finally{Zs.quiet=e}},KI=async(e,t)=>{let r=e.map(o=>({name:o.name,value:o.name})),n=await N(o=>BI({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},HI=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 H()&&ji(i,{env:t,services:n,accountId:o,shared:r}),r?N(a=>VI({message:i,choices:[{name:"No, cancel",value:!1},{name:`Yes, deploy to ${t}`,value:!0}]},a),{whenHeadless:"refuse"}):N(a=>UI({message:i,default:!1},a),{whenHeadless:"refuse"})},gk=e=>e.runner==="sh"?[GI,[e.scriptPath]]:[xp.execPath,[xp.argv[1]??"","deploy-run",e.name]],qI=(e,t,r)=>new Promise((n,o)=>{let[s,i]=gk(e),a=WI(s,i,{cwd:r,env:t,stdio:"inherit"});a.on("error",o),a.on("close",c=>{n(c??1)})}),YI=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 qI(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}},zI=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&&!Xs(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))},Pp=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:cp(o.contract),strippedVars:o.stripped,dryRun:a,success:c};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},XI=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(),KI(r,o))},hk=async(e,t)=>{let{env:r,service:n,confirmedCommand:o,dryRun:s,printEnv:i}=e,a=await $(),c=await Sp(a);if(c.length===0)throw new g(void 0,{operation:"discover deployable services",remediation:"run this from a repo that has infra-kit.deploy.ts or devops/scripts/deploy-*.sh",stderrExcerpt:`no deployable services found under ${a}`});let l=await pk(a,c);await Qe({provider:Cp[t],params:e,operation:"deploy locally",argument:"env"});let u=await at(),p=_t(await Nt(Tp),u),m=r??"";m||(y.setInteractive(),m=await ao(p,"deploy locally")),y.addOption("--env",m);let f=Ep(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 h=await XI({selection:t,eligible:f,service:n,env:m}),b=mk(zI({names:h,services:c,env:m}),c,m);if(t==="selected")for(let ke of h)y.addOption("--service",ke);let C=Bn(m),k=await on(),F=(await Zs`git rev-parse HEAD`.quiet()).stdout.trim(),v=await Xf(),S=lp({env:m,branch:k,sha:F,isClean:v});i&&d.info(`Deploy contract for ${m}:
|
|
431
|
+
${Qa(S)}`);let O=(await bp({env:m,project:l,isShared:C,isClean:v,runningEnvs:await JI(),protectedEnvAccess:u})).identity.accountId;if(s)return d.info([`Would deploy to "${m}" (AWS account ${O}) from this machine`,`Preflight parameter: /${l}/environment`,Qa(S),"Commands:",...b.map(ke=>` ${gk(ke).flat().join(" ")}`),"","Dry run: preflight and contract only \u2014 says nothing about whether the deploy would succeed."].join(`
|
|
432
|
+
`)),Pp({env:m,accountId:O,names:h,built:S,deployed:[],failed:[],dryRun:!0,success:!0});if(!o&&!await HI({env:m,isShared:C,names:h,accountId:O}))return d.info("Deployment cancelled"),Pp({env:m,accountId:O,names:h,built:S,deployed:[],failed:[],dryRun:!1,success:!1});S.stripped.length>0&&d.info(`Stripped ambient VITE_* from the build env: ${S.stripped.join(", ")}`);let{deployed:D,failed:B}=await YI({chosen:b,childEnv:S.childEnv,cwd:a,env:m});return B.length>0&&(d.error(`Partial deploy to "${m}": succeeded [${D.join(", ")||"none"}], failed [${B.join(", ")}]. There is no rollback \u2014 redeploy the previous commit to restore it.`),xp.exitCode=1),y.print(),Pp({env:m,accountId:O,names:h,built:S,deployed:D,failed:B,dryRun:!1,success:B.length===0})},yk=async e=>hk(e,"all"),vk=async e=>hk(e,"selected"),wk='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.',kk={env:ne.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:ne.boolean().optional().describe("Resolve target, contract and commands without deploying."),confirm:ne.boolean().optional().describe("Set true to execute; omit for a dry-run gate.")},bk={environment:ne.string().describe("Environment deployed to"),accountId:ne.string().describe("AWS account the deploy targeted"),services:ne.array(ne.string()).describe("Services requested"),deployed:ne.array(ne.string()).describe("Services that completed successfully"),failed:ne.array(ne.string()).describe("Services that failed"),contract:ne.record(ne.string(),ne.string()).describe("Build contract passed to the scripts"),strippedVars:ne.array(ne.string()).describe("Ambient VITE_* names removed from the build env"),dryRun:ne.boolean().describe("Whether this was a dry run"),success:ne.boolean().describe("Whether every requested service deployed")},fk=e=>Jr({workflowFile:Tp,fields:["env"],toolName:e}),Cp={all:fk("local-deploy-all"),selected:fk("local-deploy-selected")},$p=T({name:"local-deploy-all",description:`Deploy EVERY service enabled for an environment, from this machine. ${wk}`,requiresHumanConfirm:!0,formProvider:Cp.all,inputSchema:kk,outputSchema:bk,handler:yk}),Ap=T({name:"local-deploy-selected",description:`Deploy a NAMED SUBSET of services from this machine. ${wk}`,requiresHumanConfirm:!0,formProvider:Cp.selected,inputSchema:{...kk,service:ne.array(ne.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:bk,handler:vk});import e_ from"@inquirer/confirm";import ic from"@inquirer/input";import Pk from"@inquirer/select";import Dp from"node:process";import{z as Y}from"zod";import{z as Qs}from"zod";var co=async(e,t)=>new Promise(r=>{let n=setTimeout(()=>{r(null)},t);e.then(o=>{clearTimeout(n),r(o)},()=>{clearTimeout(n),r(null)})});var Ek=2500,Rk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Sk=e=>typeof e=="string"&&e.trim()!==""?e.trim():void 0,ZI=async()=>{let e=await vs();return{regular:Yn(e,"regular"),hotfix:Yn(e,"hotfix")}},QI=(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).`,Op=(e={})=>{let t=e.hintBudgetMs??Ek;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=>Rk(r)&&(r.releases===void 0||Array.isArray(r.releases)&&r.releases.length===0),buildRequestedSchema:async()=>{let r=await co(ZI(),t),n=await re(),[o,...s]=Qn(n);return Qs.object({type:Qs.enum([o,...s]).describe(n==="main"?'Release type. This repo sets "gitFlow": "main", so every release is "regular": it branches off main and bumps the minor.':'Release type. "regular" branches off dev and bumps the minor; "hotfix" branches off main and bumps the patch.'),release:Qs.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. ${QI(r,t)}`),description:Qs.string().optional().describe("Optional. Becomes the Jira fix version description and feeds the PR body. Blank means none."),releaseDate:Qs.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=Sk(r.description),a=Sk(r.releaseDate),c=xa(o);return{...Rk(n)?n:{},releases:[{...c,type:s,...i===void 0?{}:{description:i},...a===void 0?{}:{releaseDate:a}}]}}}};var t_='"1.2.5" or "next"',Ip=(e,t)=>{try{return ad(e,t)}catch(r){throw r instanceof Nr?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 Hf?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}},r_=async(e,t)=>{let r=Yn(e,t),n=r?` [${r}]`:"",o=(await N(i=>ic({message:` Version (e.g. ${t_})${n}: `},i),{whenHeadless:"refuse"})).trim(),s=o===""?r??"":o;return s===""&&(d.error("No version provided. Exiting..."),Dp.exit(1)),s},n_=async()=>{let e=(await N(t=>ic({message:' Name (kebab-case, e.g. "checkout-redesign"): '},t),{whenHeadless:"refuse"})).trim();e===""&&(d.error("No name provided. Exiting..."),Dp.exit(1));try{Ci(e)}catch(t){let r=t instanceof Error?t.message:String(t);d.error(`${r} Exiting...`),Dp.exit(1)}return e},o_=async()=>(await N(e=>ic({message:" Release date (yyyy-mm-dd, optional, press Enter to skip): ",validate:ys},e),{whenHeadless:"refuse"})).trim(),s_=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 N(f=>Pk({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"},f),{whenHeadless:"refuse"}),c=Qn(await re()),l=c.length===1?c[0]:await N(f=>Pk({message:`Release #${i} \u2014 select type:`,choices:c.map(h=>({name:h,value:h})),default:"regular"},f),{whenHeadless:"refuse"}),u;if(a==="name"){let f=await n_();u=Ip([{name:f,type:l}],[])[0]}else{let f=await r_(await n(),l);u=Ip([{version:f,type:l}],r)[0],u.id.kind==="version"&&r.push(ar(`v${u.id.raw}`))}let p=(await N(f=>ic({message:" Description (optional, press Enter to skip): "},f),{whenHeadless:"refuse"})).trim(),m=await o_();o.push({...u,...p!==""?{description:p}:{},...m!==""?{releaseDate:m}:{}}),s=await N(f=>e_({message:"Add another release?",default:!1},f),{whenHeadless:"refuse"})}return o},i_=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 ")},xk=e=>{for(let t of e)y.addOption("--release",id(t))},a_=async(e,t)=>{if(e&&e.length>0){let n=cd(e)?await t():[],o=Ip(e,n);return xk(o),o}if(ee())throw new A({status:"argument_required",argument:"release",agentMode:_.source},2,{operation:"create release",remediation:'pass "releases" explicitly, or call from a client that can render the argument form (omit "releases" and the human is asked)',stderrExcerpt:"no releases provided and no human to ask"});let r=await s_(t);return xk(r),r},c_=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"})},l_=async(e,t)=>{let r=e.map(i_).join(`
|
|
433
|
+
- `);await q(t,`Create the following ${e.length} release(s)?
|
|
417
434
|
- ${r}
|
|
418
|
-
`),y.addOption("--yes",!0)},
|
|
419
|
-
`),{result:i}}catch(s){let i=
|
|
420
|
-
`),{failure:{version:n,error:a.message}}}},ZD=(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.`)},Jw=zd(),Na=async e=>{let{releases:t,confirmedCommand:r}=e;await _e({operation:"create release"}),await at({provider:Jw,params:e,operation:"create release",argument:"release"});let n=await fn(),o=null,i=await qD(t,async()=>(o===null&&(o=await Qo()),o));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});YD(i),await $o({operation:"create release",base:mt(i[0].type)}),await zD(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await XD({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}ZD(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:Jw,description:'Create one or more releases in a single call. Each entry in "releases" carries EITHER a "version" (semver or the literal token "next") OR a "name" (free-form kebab-case identifier) \u2014 exactly one is required and they are mutually exclusive. Each entry also has its own type (regular|hotfix, default regular) and optional description; all entries in one call must share the same type \u2014 mixed regular+hotfix batches are rejected (create them in separate invocations). For each release this tool switches to the appropriate base branch (dev for regular, main for hotfix), cuts the release branch (release/v<semver> for versions, release/<name> for names), opens a GitHub release PR, and creates the matching Jira fix version (v<semver> for versions, <name> for names). The literal token "next" auto-increments from the union of remote release branches and Jira fix versions (regular bumps minor + resets patch; hotfix bumps patch on the highest minor); multiple "next" tokens advance sequentially. Named releases never auto-bump and "next" is version-only. Must be run from the main repository checkout (not a linked worktree) on the matching base branch with a clean working tree. Omit "releases" and this server offers the human a form for ONE release (type, version/next/name, description); the accepted form feeds the confirm gate. A client that cannot render a form gets a gate with no releases \u2014 confirming it is refused, never guessed. Pass "releases" explicitly for a batch or when the human already named the release. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:H.array(H.object({version:H.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:H.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:H.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:H.string().optional().describe("Optional description for the Jira version."),releaseDate:Mu.optional().describe('Optional planned production date, yyyy-mm-dd. Written to the Jira fix version as its release date; "release deliver" overwrites it with the actual date. Rides in the CLI spec as "<token>@yyyy-mm-dd".')}).refine(e=>e.version===void 0!=(e.name===void 0),{message:'Each release entry must have exactly one of "version" or "name" (they are mutually exclusive).'}).transform(e=>{let t={...e.description?{description:e.description}:{},...e.releaseDate===void 0?{}:{releaseDate:e.releaseDate}};return e.name!==void 0?{name:e.name,type:e.type,...t}:{version:e.version,type:e.type,...t}})).min(1).describe('One or more releases to create. Each entry has exactly one of "version" or "name", plus its own type and optional description. Optional over MCP: omit it to have the human fill one release from a form.').optional(),confirm:H.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:H.array(H.string()).describe("List of created release branch names"),successCount:H.number().describe("Number of releases created successfully"),failureCount:H.number().describe("Number of releases that failed"),releases:H.array(H.object({version:H.string().describe("Version number"),type:H.enum(["regular","hotfix"]).describe("Release type"),branchName:H.string().describe("Release branch name"),prUrl:H.string().describe("GitHub PR URL"),jiraVersionUrl:H.string().describe("Jira version URL"),releaseDate:H.string().nullable().describe("The release date the Jira fix version now carries (yyyy-mm-dd), or null when it has none")})).describe("Detailed information for each created release with URLs"),failedReleases:H.array(H.object({version:H.string().describe("Version number that failed"),error:H.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:Na});import Kw from"@inquirer/input";import{z as Ye}from"zod";var Hw=["description","releaseDate"],QD=async()=>{let e=await G(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await me(),o=await qt(fe({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},eI=async e=>{let r=(await G()).find(n=>n.branch===e);if(!r)throw new g(void 0,{operation:`edit release ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return r.type},tI=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await _(o=>Kw({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},rI=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await _(o=>Kw({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:Zo},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:Er(n)},nI=e=>{if(e!==void 0)return e===""?null:e},oI=async e=>(y.setInteractive(),{description:await tI(e.description),releaseDate:await rI(e.releaseDate)}),ep=e=>e??"(none)",sI=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${ep(t.releaseDate)} \u2192 ${ep(r.releaseDate)}`,_a=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=nI(n),i=await fn(),a;t?(a=Ot(t),await eI(a)):(y.setInteractive(),a=(await QD()).branch);let c=Q(a);if(!c)throw new g(void 0,{operation:`edit release ${a}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let l=ne(c);y.addOption("--version",l);let u=le(c),p=await $t(u,i);if(!p)throw new g(void 0,{operation:`edit release ${u}`,remediation:`create the Jira fix version "${u}" first or pick a different release`});let m={description:p.description??"",releaseDate:p.releaseDate||null},f=r!==void 0||s!==void 0;if(!f&&X())throw new O({status:"argument_required",argument:"description",agentMode:j.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let h=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await oI(m),S=Hw.filter(T=>h[T]!==m[T]),k=S.includes("description"),A=S.includes("releaseDate"),M=wr(i,p),v=T=>{let E={version:l,branch:a,jiraVersionUrl:M,previousDescription:m.description,newDescription:h.description,previousReleaseDate:m.releaseDate,newReleaseDate:h.releaseDate,changedFields:S,changed:T};return{content:b(JSON.stringify(E,null,2)),structuredContent:E}};if(S.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${ep(m.releaseDate)}`),y.print(),v(!1);k&&y.addOption("--description",h.description),A&&y.addOption("--release-date",h.releaseDate??"");let R=S.map(T=>sI(T,m,h));return await J(o,`Update ${u}?
|
|
421
|
-
${
|
|
435
|
+
`),y.addOption("--yes",!0)},u_=async e=>{let{entry:t,jiraConfig:r}=e,n=se(t.id),o=t.id.kind==="version"?`v${t.id.raw}`:t.id.name;try{await Zn({operation:`create release ${o}`});let s=await jd(t.type),i=await Fd({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}
|
|
436
|
+
`),{result:i}}catch(s){let i=fs(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}
|
|
437
|
+
`),{failure:{version:n,error:a.message}}}},d_=(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.`)},Tk=Op(),ac=async e=>{let{releases:t,confirmedCommand:r}=e;await Le({operation:"create release"}),await Qe({provider:Tk,params:e,operation:"create release",argument:"release"});let n=await Kn(),o=null,i=await a_(t,async()=>(o===null&&(o=await vs()),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"});c_(i),await Ps({operation:"create release",base:bt(i[0].type,await re())}),await l_(i,!!r);let a=[],c=[];for(let u of i){let{result:p,failure:m}=await u_({entry:u,jiraConfig:n});p&&a.push(p),m&&c.push(m)}d_(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:R(JSON.stringify(l,null,2)),structuredContent:l}},_p=T({name:"release-create",requiresHumanConfirm:!0,formProvider:Tk,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; main for every release in a repo with "gitFlow": "main", which has no hotfix type), 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:Y.array(Y.object({version:Y.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:Y.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:Y.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:Y.string().optional().describe("Optional description for the Jira version."),releaseDate:Qu.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:Y.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{createdBranches:Y.array(Y.string()).describe("List of created release branch names"),successCount:Y.number().describe("Number of releases created successfully"),failureCount:Y.number().describe("Number of releases that failed"),releases:Y.array(Y.object({version:Y.string().describe("Version number"),type:Y.enum(["regular","hotfix"]).describe("Release type"),branchName:Y.string().describe("Release branch name"),prUrl:Y.string().describe("GitHub PR URL"),jiraVersionUrl:Y.string().describe("Jira version URL"),releaseDate:Y.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:Y.array(Y.object({version:Y.string().describe("Version number that failed"),error:Y.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:ac});import{z as Vt}from"zod";import{$ as Lp}from"zx";import p_ from"@inquirer/confirm";var ei=async e=>{let{confirmedCommand:t,branch:r,env:n}=e;if(t)return!0;let o=`Deploy ${r} \u2192 ${n} via GitHub Actions?`;H()&&ji(o,{branch:r,env:n}),y.setInteractive();let s=await N(i=>p_({message:o,default:!1},i),{whenHeadless:"refuse"});return s&&y.addOption("--yes",!0),s};import m_ from"@inquirer/select";import f_ from"node:process";var Np=()=>!H()&&f_.stdin.isTTY===!0,g_={ci:"Dispatch the GitHub workflow for a release ref",local:"Run devops/scripts/deploy-*.sh here, against your current checkout"},Mp=async()=>N(e=>m_({message:"\u{1F680} Where should this deploy run?",choices:mr.filter(t=>t!=="local").map(t=>({name:t,value:t,description:g_[t]}))},e),{whenHeadless:"refuse"});var mr=["ci","local"],h_={ci:["--version","--skip-terraform"],local:["--dry-run","--print-env"]},Ck=e=>{if(!e){let r={operation:"resolve the deploy source",remediation:`pass --from with one of: ${mr.join(", ")}`,stderrExcerpt:"--from is required \u2014 it decides whether this deploy runs in CI or on this machine"};throw H()?new A({status:"argument_required",argument:"from",agentMode:_.source},2,r):new g(void 0,r)}let t=mr.find(r=>r===e);if(!t)throw new g(void 0,{operation:"resolve the deploy source",remediation:`use one of: ${mr.join(", ")}`,stderrExcerpt:`unknown --from value "${e}"`});return t},jp=(e,t)=>{let n=h_[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}`})},Fp=async e=>e||!Np()?Ck(e):Mp();var ti=async e=>{let t=await Fr();if(e==="dev"&&t!=="dev")throw new g(void 0,{operation:"resolve the deploy branch",remediation:`this repo sets "gitFlow": "${t}" in infra-kit.json and has no dev branch to deploy \u2014 pass --version ${t}, or a release`});if(e)return e===t?t:Bt(e);y.setInteractive();let r=await K(),n=r.map(i=>i.branch),o=new Map(r.map(i=>[i.branch,i.type])),s=await he();return lr([{value:t,label:t},...ye({branches:n,descriptions:s,types:o})])};var $k="deploy-all.yml",Ak=Jr({workflowFile:$k,fields:["version","env"],toolName:"gh-release-deploy-all"}),cc=async e=>{let{version:t,env:r,skipTerraform:n,confirmedCommand:o}=e;await Qe({provider:Ak,params:e,operation:"launch deploy-all workflow",argument:p=>p[0]??"version"});let s=await ti(t),i=$s(s);y.addOption("--version",i);let a=await at(),c=_t(await Nt($k),a),l="";r?l=r:(y.setInteractive(),l=await ao(c,"launch deploy-all workflow")),y.addOption("--env",l),Or(l,"launch deploy-all workflow",a),ms({env:l,branch:s});let u=n??!1;if(u&&y.addOption("--skip-terraform",!0),!await ei({confirmedCommand:o,branch:s,env:l})){d.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:u,success:!1};return{content:R(JSON.stringify(p,null,2)),structuredContent:p}}try{Lp.quiet=!0,await Lp`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Lp.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:R(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw d.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Bp=T({name:"gh-release-deploy-all",formProvider:Ak,description:'Dispatch the deploy-all.yml GitHub Actions workflow to deploy every service from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Use gh-release-deploy-selected for a subset of services. Pass version="dev" to deploy from the dev branch instead of a release branch. Omit "version" or "env" and this server offers the human a form listing the real releases and the environments this workflow declares; a client that cannot render one gets a refusal naming the missing field, never a guess.',requiresHumanConfirm:!0,inputSchema:{version:Vt.string().optional().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead ("main" in a repo with "gitFlow": "main"). Omit it to be offered the open releases.'),env:Vt.string().optional().describe('Target environment name \u2014 must match an env this project may reach (e.g. "dev", "renana", "oriana"). Omit it to be offered the environments deploy-all.yml declares.'),skipTerraform:Vt.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Vt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Vt.string().describe("The release branch that was deployed"),version:Vt.string().describe("The version that was deployed"),environment:Vt.string().describe("The environment deployed to"),skipTerraformDeploy:Vt.boolean().describe("Whether terraform deployment was skipped"),success:Vt.boolean().describe("Whether the deployment was successful")},handler:cc});import y_ from"@inquirer/checkbox";import{z as Be}from"zod";import{$ as Up}from"zx";var Kr="deploy-selected-services.yml",Ok=Jr({workflowFile:Kr,fields:["version","env","services"],toolName:"gh-release-deploy-selected"}),lc=async e=>{let{version:t,env:r,services:n,skipTerraform:o,confirmedCommand:s}=e;await Qe({provider:Ok,params:e,operation:"launch deploy-selected workflow",argument:v=>v[0]??"version"});let i=await ti(t),a=$s(i);y.addOption("--version",a);let c=await at(),l=_t(await Nt(Kr),c),u="";r?u=r:(y.setInteractive(),u=await ao(l,"launch deploy-selected workflow")),y.addOption("--env",u),Or(u,"launch deploy-selected workflow",c),ms({env:u,branch:i});let p=await $(),m=await Hs(p,Kr);if(m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`declare boolean service inputs in .github/workflows/${Kr}`,stderrExcerpt:`no services found in .github/workflows/${Kr}`});let f=[];if(n&&n.length>0?f=n:(y.setInteractive(),f=await N(v=>y_({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:m.map(S=>({name:S,value:S}))},v),{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 h=f.filter(v=>!m.includes(v));if(h.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${m.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let b=await Js(p,Kr),C=f.filter(v=>{let S=b.get(v);return S!==void 0&&!S.includes(u)});if(C.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:C.map(v=>`${v} deploys only to: ${(b.get(v)??[]).join(", ")}`).join("; "),stderrExcerpt:`${Kr} gates these services out of ${u}: ${C.join(", ")}`});let k=o??!1;k&&y.addOption("--skip-terraform",!0);let F=v=>{let S={releaseBranch:i,version:a,environment:u,services:f,skipTerraformDeploy:k,success:v};return{content:R(JSON.stringify(S,null,2)),structuredContent:S}};if(!await ei({confirmedCommand:s,branch:i,env:u}))return d.info("Deployment cancelled"),F(!1);try{Up.quiet=!0;let v=f.flatMap(P=>["-f",`${P}=true`]);return await Up`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${u} ${v} ${k?["-f","skip_terraform_deploy=true"]:[]}`,Up.quiet=!1,d.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${u}, services: ${f.join(", ")}`),y.print(),F(!0)}catch(v){throw d.error({error:v},"\u274C Error launching workflow"),new g(v,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Vp=T({name:"gh-release-deploy-selected",requiresHumanConfirm:!0,formProvider:Ok,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:Be.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 ("main" in a repo with "gitFlow": "main"). Omit it to be offered the open releases.'),env:Be.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:Be.array(Be.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:Be.boolean().optional().describe("Skip the terraform deployment stage."),confirm:Be.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{releaseBranch:Be.string().describe("The release branch that was deployed"),version:Be.string().describe("The version that was deployed"),environment:Be.string().describe("The environment deployed to"),services:Be.array(Be.string()).describe("The services that were deployed"),skipTerraformDeploy:Be.boolean().describe("Whether terraform deployment was skipped"),success:Be.boolean().describe("Whether the deployment was successful")},handler:lc});import Dk from"@inquirer/input";import{z as tt}from"zod";var Ik=["description","releaseDate"],v_=async()=>{let e=await K(),t=e.map(s=>s.branch),r=new Map(e.map(s=>[s.branch,s.type])),n=await he(),o=await lr(ye({branches:t,descriptions:n,types:r}));return{branch:o,type:r.get(o)||"regular"}},w_=async e=>{let r=(await K()).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},k_=async e=>{let t=e===""?"(no current description)":`current: "${e}"`,n=(await N(o=>Dk({message:` New description ${t} (press Enter to keep current): `},o),{whenHeadless:{refuse:"description"}})).trim();return n===""?e:n},b_=async e=>{let t=e===null?"(no current date)":`current: ${e}`,n=(await N(o=>Dk({message:` Release date yyyy-mm-dd ${t} (press Enter to keep current): `,validate:ys},o),{whenHeadless:{refuse:"releaseDate"}})).trim();return n===""?e:_r(n)},R_=e=>{if(e!==void 0)return e===""?null:e},S_=async e=>(y.setInteractive(),{description:await k_(e.description),releaseDate:await b_(e.releaseDate)}),Wp=e=>e??"(none)",E_=(e,t,r)=>e==="description"?` description: "${t.description}" \u2192 "${r.description}"`:` release date: ${Wp(t.releaseDate)} \u2192 ${Wp(r.releaseDate)}`,uc=async e=>{let{version:t,description:r,releaseDate:n,confirmedCommand:o}=e,s=R_(n),i=await Kn(),a;t?(a=Bt(t),await w_(a)):(y.setInteractive(),a=(await v_()).branch);let c=te(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=se(c);y.addOption("--version",l);let u=de(c),p=await Mt(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&&H())throw new A({status:"argument_required",argument:"description",agentMode:_.source},2,{operation:"edit release",remediation:"pass --description and/or --release-date on the re-run",stderrExcerpt:"no field to edit and no human to ask"});let h=f?{description:r??m.description,releaseDate:s===void 0?m.releaseDate:s}:await S_(m),b=Ik.filter(P=>h[P]!==m[P]),C=b.includes("description"),k=b.includes("releaseDate"),F=Ir(i,p),v=P=>{let O={version:l,branch:a,jiraVersionUrl:F,previousDescription:m.description,newDescription:h.description,previousReleaseDate:m.releaseDate,newReleaseDate:h.releaseDate,changedFields:b,changed:P};return{content:R(JSON.stringify(O,null,2)),structuredContent:O}};if(b.length===0)return d.info(`No change \u2014 ${u} already has description "${m.description}" and release date ${Wp(m.releaseDate)}`),y.print(),v(!1);C&&y.addOption("--description",h.description),k&&y.addOption("--release-date",h.releaseDate??"");let S=b.map(P=>E_(P,m,h));return await q(o,`Update ${u}?
|
|
438
|
+
${S.join(`
|
|
422
439
|
`)}
|
|
423
|
-
`),y.addOption("--yes",!0),await
|
|
424
|
-
`),y.print(),v(!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=
|
|
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},
|
|
440
|
+
`),y.addOption("--yes",!0),await Jn({versionId:p.id,...C?{description:h.description}:{},...k?{releaseDate:h.releaseDate}:{}},i),C&&await Va({branch:a,body:Ts(F,h.description)}),d.info(`\u2705 Updated ${b.join(" and ")} for ${u}`),d.info(`\u{1F517} Jira Version: ${F}`),d.info(`\u{1F517} PR branch: ${a}
|
|
441
|
+
`),y.print(),v(!0)},Gp=T({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:tt.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:tt.string().optional().describe("New description. Empty string clears the description."),releaseDate:ed.optional().describe("New planned release date (yyyy-mm-dd). Empty string clears the date.")},outputSchema:{version:tt.string().describe("Release version"),branch:tt.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:tt.string().describe("Jira fix version URL"),previousDescription:tt.string().describe("The description before the update"),newDescription:tt.string().describe("The description after the update"),previousReleaseDate:tt.string().nullable().describe("The planned release date before the update, or null"),newReleaseDate:tt.string().nullable().describe("The planned release date after the update, or null"),changedFields:tt.array(tt.enum(Ik)).describe("The fields whose value actually changed"),changed:tt.boolean().describe("Whether anything actually changed")},handler:uc});import{z as ue}from"zod";import{$ as Kp}from"zx";import{z as _k}from"zod";var jk=2500,dc="release-remove",Nk=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),P_=e=>e.version===void 0||e.version==="",x_=async()=>{try{return{outcome:"listed",prs:await K()}}catch(e){return e instanceof g&&e.operation===As?{outcome:"empty"}:{outcome:"failed"}}},Mk=(e,t)=>(e===null?d.info({msg:`Tool execution form enumeration timed out (gh pr list, ${t/1e3} s): ${dc}`}):e.outcome==="failed"?d.info({msg:`Tool execution form enumeration failed (gh pr list): ${dc}`}):d.info({msg:`Tool execution form options empty (open release PRs): ${dc}`}),null),T_=(e,t)=>{let r=new Map(e.map(n=>[n.branch,n.type]));return La(e.map(n=>n.branch)).map(({branch:n,id:o,label:s})=>{let i=t?.get(de(o)),a=i===void 0?"":` \u2014 ${i}`;return{label:s,prose:`${s} [${r.get(n)??"regular"}]${a}`}})},C_=(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): ${dc}`}),`Open release PRs right now: ${n}. Jira descriptions could not be fetched within ${r/1e3} s. `)},Jp=(e={})=>{let t=e.fetchBudgetMs??jk;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=>Nk(r)&&P_(r),buildRequestedSchema:async()=>{let[r,n]=await Promise.all([co(x_(),t),co(he(),t)]);if(r===null||r.outcome!=="listed")return Mk(r,t);let o=T_(r.prs,n);return o.length===0?Mk({outcome:"empty"},t):_k.object({version:_k.enum(o.map(s=>s.label)).describe(`The ONE release to tear down. ${C_(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:{...Nk(n)?n:{},version:r.version}}};var Fk=["worktree","pr","local-branch","remote-branch","jira"],Uk={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"},Hr="remove a release",ct=e=>{throw d.warn({operation:e.operation},`\u26D4 ${e.stderrExcerpt??e.operation}`),new g(void 0,e)},Lk=(e,t)=>{throw d.warn({operation:t.operation},`\u26D4 ${t.stderrExcerpt??t.operation}`),new A({...e,agentMode:_.source},2,t)},$_=e=>{ee()&&(e.version||Lk({status:"argument_required",argument:"version"},{operation:Hr,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&&Lk({status:"refused"},{operation:Hr,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"}))},Vk=e=>{e.pr?.state==="MERGED"&&ct({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`})},A_=(e,t)=>{if(t.skipJira||(e.jiraConfig||ct({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)&&ct({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||ct({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)`}))},O_=e=>{if(e.worktreePresent||e.pr!==null||e.localTipSha!==null||e.remoteTipSha!==null||e.jira)return;ct({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"})},D_=e=>{!e.worktreeDirty||e.worktreeDirty.length===0||ct({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(", ")}`})},I_=async e=>(await Kp`git -C ${e} status --porcelain`).stdout.split(`
|
|
442
|
+
`).map(r=>r.trimEnd()).filter(r=>r.length>0),__=async e=>{try{let{terminals:t}=await vg(e);return t.filter(r=>r.connected).length}catch(t){return d.debug({error:t,worktreePath:e},"release remove: orca terminal probe failed"),0}},N_=async e=>{let t=await Mi([e]);if(t!==null)throw d.warn({operation:Hr},`\u26D4 this command runs inside an Orca terminal of ${t}`),new A({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:Hr,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`})},M_=async(e,t)=>{let r={jiraConfig:null,jira:null,moveIssuesTo:null};if(t.skipJira)return r;let n=await jt();if(!n)return r;let o=await Mt(de(e),n),s=t.moveIssuesTo?await j_(t.moveIssuesTo,n):null;if(!o)return{jiraConfig:n,jira:null,moveIssuesTo:s};let i=await Ea(o.id,n);return{jiraConfig:n,moveIssuesTo:s,jira:{version:o,fixCount:i.issuesFixedCount,affectsCount:i.issuesAffectedCount,url:Ir(n,o)}}},j_=async(e,t)=>{let r=await Mt(e,t);return r||ct({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}"`})},F_=async(e,t)=>{let r=te(e);r||ct({operation:`remove release ${e}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")',stderrExcerpt:`"${e}" is not a release branch`});let n=await $(),s=`${`${n}${ce}`}/${e}`,[i,a,c,l]=await Promise.all([Se("release"),to(e),$e(n,`refs/heads/${e}`),sn(n,e)]),u=i.includes(e);return u&&await N_(s),{...await M_(r,t),branch:e,id:r,label:se(r),baseBranch:a?.baseRefName??bt("regular",await re()),worktreePath:s,worktreePresent:u,orcaTerminalCount:u?await __(s):0,worktreeDirty:u?await I_(s):null,localTipSha:c,remoteTipSha:l,pr:a}},Bk=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}),L_=(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}`},B_=(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: ${L_(e,t)}`];return e.orcaTerminalCount>0&&n.push(` \u2022 ${e.orcaTerminalCount} Orca terminal(s) in ${e.worktreePath} will be closed`),n.join(`
|
|
443
|
+
`)},pc=class extends Error{constructor(r,n){super(`step ${r} failed`,{cause:n});this.step=r;this.reason=n;this.name="StepFailure"}step;reason},U_=e=>typeof e=="string"?e:e.outcome;async function ri(e,t,r){try{let n=await r(),o=U_(n);return t.push({step:e}),d.info({step:e,outcome:o},`\u2705 ${Uk[e]} \u2014 ${o}`),n}catch(n){throw new pc(e,n)}}var V_=(e,t)=>t.step==="local-branch"&&e.localTipSha?`local-branch (was ${e.localTipSha.slice(0,7)})`:t.step,W_=e=>{let{plan:t,step:r,done:n,cause:o}=e,s=n.map(p=>V_(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 ${Fk.indexOf(r)+1} of ${Fk.length} (${Uk[r]})`,remediation:u?`${u} \u2014 ${l}`:l})},G_=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",J_=async e=>{let t=await to(e.branch);if(Vk({...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 Kp`gh pr close ${String(t.number)} --comment ${r}`,{outcome:"closed",number:t.number}},K_=async e=>(await on()===e.branch&&await Kp`git switch ${e.baseBranch}`,await $i(e.branch),await Qf(e.branch)?ct({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"),H_=async e=>(await Ai(e.branch),e.remoteTipSha?"deleted":"absent"),q_=async(e,t,r)=>{let n=await Ea(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}\``;ct({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}`})},Y_=async(e,t)=>t.skipJira?"skipped":!e.jira||!e.jiraConfig?"absent":(await q_(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 Zu({versionId:e.jira.version.id,moveFixIssuesTo:e.moveIssuesTo?.id,moveAffectedIssuesTo:e.moveIssuesTo?.id},e.jiraConfig),"removed"),z_=(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}),X_=async(e,t,r)=>{let n=await ri("worktree",r,()=>G_(e)),o=await ri("pr",r,()=>J_(e));d.info({branch:e.branch,localTipSha:e.localTipSha,remoteTipSha:e.remoteTipSha},"\u{1F516} branch tips before deletion");let s=await ri("local-branch",r,()=>K_(e)),i=await ri("remote-branch",r,()=>H_(e)),a=await ri("jira",r,()=>Y_(e,t));return{worktree:n,pr:o,localBranch:s,remoteBranch:i,jira:a}},Z_=async(e,t)=>{let r=[];try{return z_(e,await X_(e,t,r))}catch(n){throw n instanceof pc?W_({plan:e,step:n.step,done:r,cause:n.reason}):n}},Q_=async e=>{if(e)return Bt(e);y.setInteractive();let[t,r]=await Promise.all([he(),K()]),n=r.map(s=>s.branch);n.length===0&&ct({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 lr(ye({branches:n,descriptions:t,types:o}))}catch(s){throw _e(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"})}},Wk=Jp(),mc=async e=>{let{confirmedCommand:t,version:r,moveIssuesTo:n,skipJira:o}=e;await Le({operation:Hr}),await V(),await Qe({provider:Wk,params:e,operation:Hr,argument:"version"}),$_(e);try{let s=await F_(await Q_(r),e);d.debug({plan:Bk(s)},"release remove: resolved plan"),Vk(s),A_(s,e),O_(s),await Ps({operation:`remove release ${s.label}`,base:s.baseBranch}),D_(s),y.addOption("--version",s.label),n&&y.addOption("--move-issues-to",n),o&&y.addOption("--skip-jira",!0),await q(t,B_(s,!!o),{plan:{...Bk(s),skipJira:!!o}}),t||y.addOption("--yes",!0);let i=await Z_(s,e);return y.print(),{content:R(JSON.stringify(i,null,2)),structuredContent:i}}catch(s){throw _e(s)||Ee(s)||s instanceof g?s:(d.error({err:Wr(s)},"\u274C Error removing release"),new g(s,{operation:Hr,remediation:"check `gh auth status`, `git worktree list` and the Jira credentials, then re-run"}))}},Hp=T({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:Wk,inputSchema:{version:ue.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:ue.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:ue.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{branch:ue.string().describe("The release branch that was targeted"),version:ue.string().describe('The release label (e.g. "1.2.5")'),baseBranch:ue.string().describe("The branch HEAD was moved to before the local delete"),worktree:ue.enum(["removed","absent"]).describe("Whether a git worktree was removed or none existed"),pr:ue.enum(["closed","already-closed","absent"]).describe("What happened to the release pull request"),prNumber:ue.number().nullable().describe("The pull request number, or null when none exists"),localBranch:ue.enum(["deleted","absent"]).describe("Whether a local branch was deleted or none existed"),localTipSha:ue.string().nullable().describe("The local tip before deletion \u2014 the handle that restores the branch"),remoteBranch:ue.enum(["deleted","absent"]).describe("Whether the origin branch was deleted or none existed"),remoteTipSha:ue.string().nullable().describe("The origin tip before deletion"),jira:ue.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:ue.object({id:ue.string(),name:ue.string(),url:ue.string()}).nullable().describe("The fix version this release owned, captured before removal \u2014 the id is the only handle that survives it")},handler:mc});import{spawn as nN}from"node:child_process";import oN from"node:fs";import{homedir as sN}from"node:os";import gc from"node:process";import fc from"node:fs";import lo from"node:path";var eN=e=>{try{return fc.statSync(e).isFile()?fc.readFileSync(e,"utf8"):null}catch{return null}},tN=e=>{try{return fc.realpathSync(e)}catch{return e}},rN=(e,t)=>{let o=t(lo.join(e,".git"))?.split(`
|
|
444
|
+
`).map(c=>c.trim()).find(c=>c.startsWith("gitdir:"))?.slice(7).trim();if(!o)return e;let s=lo.resolve(e,o),i=`${lo.sep}.git${lo.sep}worktrees${lo.sep}`,a=s.lastIndexOf(i);return a===-1?e:s.slice(0,a)},Gk=(e={})=>{let t=e.listInstallations??sl,r=e.exists??fc.existsSync,n=e.readGitFile??eN,o=e.realpath??tN,s=new Map;for(let i of t()){if(i.projectPath===null)continue;let a=rN(i.projectPath,n);if(!r(lo.join(a,"infra-kit.json")))continue;let c=o(a);s.has(c)||s.set(c,a)}return[...s.values()].sort()};var iN=180*1e3,aN=900*1e3,cN=4*1024*1024,lN=2e3,uN=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=nN(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&&gc.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<cN&&(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)},lN).unref()})}),dN=({cwd:e,timeoutMs:t})=>uN({command:gc.execPath,args:[gc.argv[1]??"","setup","--unattended","--json"],cwd:e,env:xg(gc.env),timeoutMs:t}),pN=e=>{oN.writeFileSync(Pn(),e,{mode:384})},mN=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}},fN=new RegExp("\x1B\\[[0-9;]*m","g"),gN=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(fN,"").split(`
|
|
445
|
+
`).map(n=>n.trim()).filter(Boolean).at(-1),r=`no setup report (exit ${String(e.status)})`;return t?`${r}: ${t.slice(0,300)}`:r},hN=(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}},Jk=async(e,t,r,n)=>{let o=n-r.clock(),s=e===null?"infra-kit setup":ba(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(iN,o)}),a=i.error===null?mN(i.stdout):null;return a===null?{root:e,status:"failed",notes:[`${gN(i)} \u2014 run: ${s}`]}:{root:e,...hN(a,i.status)}}catch(i){return{root:e,status:"failed",notes:[`${i instanceof Error?i.message:String(i)} \u2014 run: ${s}`]}}},yN=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}})},vN=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
446
|
`)}
|
|
430
|
-
`},
|
|
431
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),hN=e=>{let t=ak(e.stderr),r=ak(e.stdout),n=[...t,...r].filter(s=>gN.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-fN).join(" / ")},yN="ENOBUFS",vN=e=>e.error?.code===yN,wN=e=>{if(vN(e))return`terminated after exceeding the ${ck} 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=hN(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var kN=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},bN=e=>{let t=He(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},RN=(e,t)=>{let r=bN(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=$s(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:As(r),context:n}},Ua=async(e=Sr,t=qo())=>{let r=await zo(Sr,t),n={owner:null,present:kN(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 ap=(e,t)=>({...Os(e),action:"skipped",commands:e.commands,detail:t}),Os=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),lk=(e,t)=>e.action==="none"?ap(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?ap(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...Os(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},SN=(e,t)=>t.ran?t.ok?{...Os(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...Os(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...Os(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},cp=async e=>{let t=e.run??ip,{plans:r}=await Ua(e.ids,e.probeDeps),n=[];for(let o of r){let s=lk(o,e.mode);if(s!==null){n.push(s);continue}n.push(SN(o,t(o.recipe,o.context)))}return n},lp=async(e,t)=>{let{plans:r}=await Ua(e,t);return r.map(n=>lk(n,"converge")??ap(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import LN from"node:process";import{z as N}from"zod";var up={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},EN=Object.keys(up).sort((e,t)=>up[e]-up[t]),uk={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},dk=new Set(["manual","warn","fail"]),dp=e=>{switch(e){case"written":return"changed";case"unchanged":return"ok";case"skipped":return"skipped";case"manual":return"manual";case"warned":return"warn";case"failed":return"fail";default:return We(e)}},PN=e=>e.reduce((t,r)=>uk[r]>uk[t]?r:t,"skipped"),mk=e=>e.message.trim(),xN=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 "),pk=e=>e.message===$n,TN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?mk(r):e.length>1?xN(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=>dp(i.outcome)),n=t.filter(i=>dk.has(dp(i.outcome))).map(mk),o=t.filter(i=>!dk.has(dp(i.outcome))&&!pk(i)),s={name:e,status:PN(r),message:TN(o,t.some(pk))};return n.length>0?{...s,notes:n}:s},$N=e=>({label:"Local setup",rows:EN.map(t=>CN(t,e.filter(r=>r.step===t)))}),AN=(e,t)=>{switch(e.action){case"installed":case"updated":return"changed";case"skipped":return t.skipTools&&e.commands.length>0?"manual":"skipped";case"refused":return"manual";case"failed":return"fail";default:return We(e.action)}},ON=(e,t)=>{let r=AN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},DN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>ON(r,t))}),IN=e=>{switch(e){case"created":case"repointed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-unresolved":return"skipped";case"failed":return"fail";default:return We(e)}},NN=e=>{switch(e){case"created":case"refreshed":return"changed";case"unchanged":return"ok";case"skipped-local":case"skipped-platform":return"skipped";case"failed":return"fail";default:return We(e)}},_N=e=>{switch(e){case"created":return"linked ~/.infra-kit/portless to the running portless";case"repointed":return"re-pointed ~/.infra-kit/portless to the running portless";case"unchanged":return"already linked to the running portless";case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-unresolved":return"skipped \u2014 portless is not installed";case"failed":return"could not update the link \u2014 see the debug log";default:return We(e)}},MN=e=>{let t=e.method==="copy"?"copied":"linked";switch(e.outcome){case"created":return`${t} Node ${e.version} to ~/.infra-kit/node`;case"refreshed":return`re-${t} Node ${e.version} to ~/.infra-kit/node`;case"unchanged":return`~/.infra-kit/node is already Node ${e.version}`;case"skipped-local":return"skipped \u2014 this install is not global";case"skipped-platform":return"skipped \u2014 no portless OS service on this platform";case"failed":return"could not write ~/.infra-kit/node \u2014 see the debug log";default:return We(e.outcome)}},jN=(e,t)=>{let r="service";switch(e){case"converged":return{name:r,status:"ok",message:"installed service runs through the link and the node"};case"absent":return{name:r,status:"manual",message:"no service installed",notes:t===null?[]:[t]};case"drifted":return{name:r,status:"manual",message:"installed service is out of date",notes:t===null?[]:[t]};case"skipped":return{name:r,status:"skipped",message:"not judged \u2014 portless is not installed"};default:return We(e)}},FN=e=>({label:"Portless service",rows:[{name:"link",status:IN(e.link),message:_N(e.link)},{name:"node",status:NN(e.node.outcome),message:MN(e.node)},jN(e.service,e.command)]}),fk=(e,t)=>[$N(e.init),DN(e.tools,t),FN(e.portless)],gk=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var BN=()=>{let{link:e,node:t}=ei();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},UN=async e=>{let t=Qm(e.link).outcome,r=Zm(e.node),n=Qs(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 Sv(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=jt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},yk="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",vk="--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.",WN=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(yk);if(o&&(e.tools!==void 0||r))throw new Error(vk);return{ids:e.tools??t??Sr,mode:r?"update":"converge",skipTools:o}},hk=(e,t)=>e instanceof Cn?e.step:t.at(-1)?.step??"zshrc",VN=async()=>{let e=[];try{await Cu(t=>{e.push(t)})}catch(t){e.push({step:hk(t,e),outcome:"failed",message:`The ${hk(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},GN=(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}`}))},JN=async(e,t)=>{try{return e.skipTools?await lp(e.ids,t.probeDeps):await cp({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return GN(e.ids,r)}},KN=e=>({step:e.step,outcome:e.outcome,message:e.message}),Wa=async(e={})=>{let t=WN(e);Ze.withheld=e.unattended===!0;let r=await VN(),n=await JN(t,e),o=await UN(e.portlessDeps??BN()),s=fk({init:r,tools:n,portless:o},{skipTools:t.skipTools});pt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info($n),gk(s)&&(LN.exitCode=1);let i={init:r.map(KN),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}},HN=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")}),qN=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")}),YN=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")}),zN={init:N.array(HN).describe("One entry per init step, in the order they ran"),tools:N.array(qN).describe("One result per requested dependency"),portlessService:YN.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)")},XN={tools:N.array(N.enum(Sr)).optional().describe("Which tools to act on. Omit for all six."),mode:N.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:N.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},pp=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:XN,outputSchema:zN,requiresHumanConfirm:!0,handler:e=>Wa({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as kk}from"node:fs";import bk from"node:path";import c_ from"node:process";import{z as _t}from"zod";import{createHash as ZN}from"node:crypto";import{readFileSync as QN}from"node:fs";var _r=e=>ZN("sha256").update(QN(e)).digest("hex");import{readFileSync as s_,writeFileSync as i_}from"node:fs";import Ka from"node:path";import{z as wt}from"zod";var se="vendor",e_=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),t_=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),r_=[".tsbuildinfo"],mp=e=>e_.has(e),fp=e=>t_.has(e)?!0:r_.some(t=>e.endsWith(t)),Va=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>mp(o))||fp(r)};import{readdirSync as n_}from"node:fs";import gp from"node:path";var o_=e=>e.split(gp.sep).join("/"),Ga=e=>{let t=[],r=n=>{for(let o of n_(n,{withFileTypes:!0})){let s=gp.join(n,o.name);if(o.isDirectory()){if(mp(o.name))continue;r(s);continue}fp(o.name)||t.push(o_(gp.relative(e,s)))}};return r(e),t.sort()};var ze=".sync-manifest.json",Ja=1,a_=wt.object({schemaVersion:wt.number().optional(),source:wt.string(),commit:wt.string(),syncedAt:wt.string(),fileCount:wt.number(),files:wt.record(wt.string(),wt.string())}),hp=e=>(e.schemaVersion??Ja)>Ja,wk=(e,t)=>{let r={},n=t?[...new Set(t)].sort():Ga(e);for(let o of n)try{r[o]=_r(Ka.join(e,o))}catch(s){let i=s instanceof Error?s.message:String(s);throw new Error(`Cannot hash vendor file "${o}" (broken symlink or unreadable file): ${i}`)}return r},Ds=e=>{let t=Ka.join(e,ze),r;try{r=s_(t,"utf8")}catch{throw new Error(`Missing ${ze} at ${t}`)}let n=a_.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${ze} at ${t}: ${wt.prettifyError(n.error)}`);return n.data},yp=(e,t,r)=>{let n=wk(e,r),o={schemaVersion:Ja,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return i_(Ka.join(e,ze),`${JSON.stringify(o,null,2)}
|
|
432
|
-
`),
|
|
433
|
-
${e} (${t.length}):`);for(let r of t.slice(0,wp))d.info(` ${r}`);t.length>wp&&d.info(` \u2026and ${t.length-wp} more`)}},Ha=async(e={})=>{let t=e.cwd??await $(),r=bk.join(t,se),n={modified:[],added:[],removed:[],fileCount:0};if(!kk(r)){d.info(`\u2139\uFE0F No ${se}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}if(!kk(bk.join(r,ze))){d.error(`\u274C Missing ${se}/${ze}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}let o=Ds(r);if(hp(o)){d.error(`\u274C ${se}/${ze} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:b(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=vp(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${se}/ has drifted from ${se}/${ze}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),kp("Modified",s),kp("Added (not in manifest)",i),kp("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${se}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:b(JSON.stringify(l,null,2)),structuredContent:l}},l_={status:_t.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:_t.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:_t.number(),modified:_t.array(_t.string()),added:_t.array(_t.string()),removed:_t.array(_t.string())},bp=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:l_,handler:()=>Ha({cwd:c_.cwd()})});import Rk from"node:process";import{z as Is}from"zod";var Sk=async e=>{try{return await e()}catch{return null}},qa=async()=>{let e=L.version;d.info(e);let t=await Sk($),r=t===null?null:await Sk(()=>Ae(t)),n={version:e,cwd:Rk.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:Rk.env.CLAUDE_PROJECT_DIR||null};return{content:b(JSON.stringify(n,null,2)),structuredContent:n}},Rp=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:Is.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:Is.string().describe("The working directory of this process"),repoRoot:Is.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:Is.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:Is.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:qa});import Mk from"@inquirer/confirm";import g_ from"node:path";import{z as W}from"zod";import{$ as _s}from"zx";import u_ from"@inquirer/input";import Pk from"@inquirer/select";import{$ as nr}from"zx";var Ns="dev",d_="main",Sp="feature/",xk=["new","local","remote"],Ya=e=>{let t=e.trim().replace(/^feature\//,"").toLowerCase().replaceAll(/\s+/g,"-");return`${Sp}${t}`},Tk=async()=>{let e=await nr({nothrow:!0,quiet:!0})`git symbolic-ref --quiet --short refs/remotes/origin/HEAD`,t=e.exitCode===0?e.stdout.trim().replace(/^origin\//,""):"";return t===""?null:t},p_=2,Ep=async()=>{let e=await nr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${Ns}`;if(e.exitCode===0)return Ns;if(e.exitCode!==p_)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 ${Ns} exists`});return await Tk()??Ns},Ck=async e=>{let t=e?.trim();return t?t===Ns||t===d_||t===await Tk()?t:Te(ke(t)):Ep()},$k=async()=>_(e=>Pk({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"}}),Ak=async()=>_(e=>u_({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>Ya(t)===Sp?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Ok=async(e,t)=>e.length===0?t:_(r=>Pk({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),m_=async e=>{let t=await nr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===Sp||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`})},Ek=async e=>(await nr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,f_=async e=>(await nr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Dk=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(Ya))];for(let s of n)await m_(s);if(!await Ek(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 f_(s)?o.push({branch:s,base:r,source:"local"}):await Ek(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Ik=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await nr`git worktree add ${t} ${r}`:o==="remote"?await nr`git worktree add --track -b ${r} ${t} origin/${r}`:await nr`git worktree add --no-track -b ${r} ${t} origin/${n}`},Nk=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 Ms="create worktrees",h_=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],Pp=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),za=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await _e({operation:Ms}),y_(e);try{let o=await $(),s=`${o}${ge}`;await _k(`${s}/${Ur.release}`),await _k(`${s}/${Ur.feature}`);let i=await v_(e),a=i==="feature"?await k_(e):await w_(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let M={kind:i,createdWorktrees:[],count:0,features:[],...Pp()};return{content:b(JSON.stringify(M,null,2)),structuredContent:M}}let c=await K(),l=await b_(r,c),u=await R_(n,c),p=await Ae(o),m=g_.basename(p),f=u?await S_({explicit:n!==void 0,mainRepoRoot:p}):null;await J(t,E_(f,m,a.previewLines)),t||y.addOption("--yes",!0);let h=f?await P_(f,p):null,S=await A_(a.targets,s);if(O_(S),l)for(let M of S)await _s`github ${s}/${M}`,await _s`sleep 5`;let k=h?await T_({registration:h,createdWorktrees:S,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):Pp();C_(k),y.print();let A={kind:i,createdWorktrees:S,count:S.length,features:a.features.filter(M=>S.includes(M.branch)),...k};return{content:b(JSON.stringify(A,null,2)),structuredContent:A}}catch(o){throw Oe(o)||o instanceof O?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:Ms,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},y_=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:Ms,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},v_=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),$k()),w_=async e=>{let{all:t,versions:r}=e,n=await be("release"),o=[];if(r)o=r.split(",").map(a=>Te(ke(a.trim())));else{let a=await G(),c=a.map(l=>l.branch);if(c.length===0)return null;if(t)o=c;else{y.setInteractive();let l=new Map(a.map(p=>[p.branch,p.type])),u=await me();o=await Yt(fe({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",Dt(o));let{branchesToCreate:s}=$_({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>_s`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},k_=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await Ak()],n===void 0)){let l=(await G()).map(u=>u.branch);n=await Ok(l,await Ep())}let o=await Ck(n),s=await Dk({names:r,base:o});y.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),y.addOption("--base",o);let i=await be("feature"),a=s.filter(l=>i.includes(l.branch)?(d.info(`\u2139\uFE0F ${l.branch} is already checked out in a worktree`),!1):!0);return{targets:a.map(l=>({branch:l.branch,add:u=>Ik(l,u)})),features:a,previewLines:a.map(Nk)}},b_=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await _(o=>Mk({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=>Mk({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},jk=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"},S_=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Wt();if(n!=="ready"){let{reason:s,text:i}=jk(n);if(t)throw d.warn({operation:Ms},`\u26D4 --orca was passed but ${i}`),new O({status:"refused",reason:s,agentMode:j.source},2,{operation:Ms,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 Wf(r);return{probe:n,registered:o.registered,visibility:o.visibility}},E_=(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
|
-
`)
|
|
435
|
-
|
|
436
|
-
|
|
447
|
+
`},wN=e=>({version:e.version??U.version,home:e.home??sN(),clock:e.clock??Date.now,acquireLock:e.acquireLock??(()=>gl({lockPath:uy()})),readRecord:e.readRecord??xn,writeRecord:e.writeRecord??dy,discoverProjects:e.discoverProjects??(()=>Gk()),runSetupChild:e.runSetupChild??dN,writeLog:e.writeLog??pN}),kN=e=>{try{return{projects:e.discoverProjects(),error:null}}catch(t){return{projects:[],error:t instanceof Error?t.message:String(t)}}},bN=async e=>{let t=e.readRecord(),r=e.clock();if(!fy(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+aN,s=await Jk(null,e.home,e,o),i=kN(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 Jk(l,l,e,o));let c={version:e.version,attempts:n,startedMs:r,finishedMs:e.clock(),runs:yN(a)};e.writeRecord(c);try{e.writeLog(vN(c))}catch{}return"ran"},Kk=async(e={})=>{try{let t=wN(e),r=t.acquireLock();if(r===null)return"already-running";try{return await bN(t)}finally{r()}}catch{return"not-due"}},qp=async(e={})=>{let t=await Kk(e);return{content:R(JSON.stringify({outcome:t})),structuredContent:{outcome:t}}};import{spawnSync as PN}from"node:child_process";import{homedir as xN}from"node:os";import TN from"node:process";var RN=e=>{let t=new Set(e.steps.map(r=>r[0]));return t.has("brew")?"homebrew":t.has("npm")?"npm":null},SN=e=>{let t=[];return e.needsSudo&&t.push("needs-sudo"),e.fetchesNetworkScript&&t.push("fetches-network-script"),t},EN=(e,t)=>{let r=RN(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},ni=(e,t)=>{let r=[...SN(e),...EN(e,t)];return r.length===0?{executable:!0}:{executable:!1,reasons:r}},oi=e=>e.steps.map(Ge);var CN=["NONINTERACTIVE","CI","INTERACTIVE","HAVE_SUDO_ACCESS","SUDO_ASKPASS"],$N=e=>{let t={...Tf(e)};for(let r of CN)delete t[r];return t},Yp=(e,t,r={})=>{let n=r.spawnSync??PN,o=r.env??TN.env,s=(r.agentMode??ee)(),i=oi(e),a=ni(e,t);return a.executable?s?{ran:!1,commands:i,refusedBecause:["agent-mode"]}:DN({recipe:e,spawn:n,env:o,commands:i,notify:r.notify??AN}):{ran:!1,commands:i,refusedBecause:a.reasons}},AN=e=>{d.info(e)},qk=64,ON=qk*1024*1024,DN=({recipe:e,spawn:t,env:r,commands:n,notify:o})=>{let s=$N(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:ON,cwd:xN(),env:s}),l=FN(c);if(l!==null)return{ran:!0,ok:!1,commands:n,failedStep:n[i],detail:l}}return{ran:!0,ok:!0,commands:n}},IN=5,_N=/^(?:error|fatal|warning: failed|[a-z-]{0,20} ERR!)[:\s]/i,Hk=e=>e==null?[]:String(e).split(`
|
|
448
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),NN=e=>{let t=Hk(e.stderr),r=Hk(e.stdout),n=[...t,...r].filter(s=>_N.test(s)),o=t.length>0?t:r;return(n.length>0?n:o).slice(-IN).join(" / ")},MN="ENOBUFS",jN=e=>e.error?.code===MN,FN=e=>{if(jN(e))return`terminated after exceeding the ${qk} 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=NN(e),r=t===""?"":`: ${t}`;return`exited ${e.status??"unknown"}${r}`};var LN=e=>{let t=[];return e.some(n=>n.id==="brew"&&n.present)&&t.push("homebrew"),t.push("npm"),t},BN=e=>{let t=ze(e.id);return e.present?t.updateFor(e.binRealPath):t.bootstrapInstall},UN=(e,t)=>{let r=BN(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=ni(r,n);return{state:e,action:e.present?"update":"install",recipe:r,executable:o.executable,refusedBecause:o.executable?[]:o.reasons,commands:oi(r),context:n}},hc=async(e=$r,t=rs())=>{let r=await os($r,t),n={owner:null,present:LN(r)},o=Iu(e),s=new Map(r.map(a=>[a.id,a]));return{plans:o.filter(a=>e.includes(a)).map(a=>UN(s.get(a),n)),context:n}};var zp=(e,t)=>({...si(e),action:"skipped",commands:e.commands,detail:t}),si=e=>({id:e.state.id,before:{present:e.state.present,onPath:e.state.onPath,version:e.state.version,manager:e.state.manager}}),Yk=(e,t)=>e.action==="none"?zp(e,`nothing to do: ${e.state.manager} installs are not managed from here`):t==="update"&&e.action==="install"?zp(e,"not installed, and --update only updates \u2014 drop the flag to install it"):e.executable?null:{...si(e),action:"refused",commands:e.commands,detail:`refused (${e.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},VN=(e,t)=>t.ran?t.ok?{...si(e),action:e.action==="install"?"installed":"updated",commands:t.commands,detail:e.action==="install"?"installed":"updated"}:{...si(e),action:"failed",commands:t.commands,detail:`${t.failedStep??"a step"} ${t.detail??"failed"}`}:{...si(e),action:"refused",commands:t.commands,detail:`refused (${t.refusedBecause.join(", ")}) \u2014 run the commands printed below yourself`},Xp=async e=>{let t=e.run??Yp,{plans:r}=await hc(e.ids,e.probeDeps),n=[];for(let o of r){let s=Yk(o,e.mode);if(s!==null){n.push(s);continue}n.push(VN(o,t(o.recipe,o.context)))}return n},Zp=async(e,t)=>{let{plans:r}=await hc(e,t);return r.map(n=>Yk(n,"converge")??zp(n,`would ${n.action} \u2014 nothing was run (--skip-tools)`))};import oM from"node:process";import{z as j}from"zod";var Qp={zshrc:0,zshenv:1,migrations:2,"user-config":3,guidance:4,worktrees:5,"plugin-pointer":6,"mcp-server":7,"mcp-proxies":8,"project-config":9,"token-perms":10,chrome:11,shell:12},WN=Object.keys(Qp).sort((e,t)=>Qp[e]-Qp[t]),zk={skipped:0,ok:1,changed:2,manual:3,warn:4,fail:5},Xk=new Set(["manual","warn","fail"]),em=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 Je(e)}},GN=e=>e.reduce((t,r)=>zk[r]>zk[t]?r:t,"skipped"),Qk=e=>e.message.trim(),JN=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 "),Zk=e=>e.message===Fn,KN=(e,t)=>{let[r]=e;return e.length===1&&r!==void 0?Qk(r):e.length>1?JN(e):t?"activate with the last line below":"see below"},HN=(e,t)=>{if(t.length===0)return{name:e,status:"skipped",message:"did not run"};let r=t.map(i=>em(i.outcome)),n=t.filter(i=>Xk.has(em(i.outcome))).map(Qk),o=t.filter(i=>!Xk.has(em(i.outcome))&&!Zk(i)),s={name:e,status:GN(r),message:KN(o,t.some(Zk))};return n.length>0?{...s,notes:n}:s},qN=e=>({label:"Local setup",rows:WN.map(t=>HN(t,e.filter(r=>r.step===t)))}),YN=(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 Je(e.action)}},zN=(e,t)=>{let r=YN(e,t),n={name:e.id,status:r,message:e.detail};return r==="manual"&&e.commands.length>0?{...n,notes:[...e.commands]}:n},XN=(e,t)=>({label:t.skipTools?"Tools (probe: nothing installed)":"Tools",rows:e.map(r=>zN(r,t))}),ZN=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 Je(e)}},QN=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 Je(e)}},eM=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 Je(e)}},tM=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 Je(e.outcome)}},rM=(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 Je(e)}},nM=e=>({label:"Portless service",rows:[{name:"link",status:ZN(e.link),message:eM(e.link)},{name:"node",status:QN(e.node.outcome),message:tM(e.node)},rM(e.service,e.command)]}),eb=(e,t)=>[qN(e.init),XN(e.tools,t),nM(e.portless)],tb=e=>e.some(t=>t.rows.some(r=>r.status==="fail"));var sM=()=>{let{link:e,node:t}=xi();return{link:e,node:t,target:{home:e.home,isGlobal:e.isGlobal,processStartTime:()=>null}}},iM=async e=>{let t=Wf(e.link).outcome,r=Vf(e.node),n=Pi(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 ay(e.target,n);if(o==="converged")return{link:t,node:r,service:o,command:null};let i=Tt(n,{home:e.link.home,exists:e.target.exists,execPath:e.target.execPath,stableNode:s});return{link:t,node:r,service:o,command:i}},nb="--unattended cannot be combined with --tools or --update: an unattended run installs and updates nothing (it implies --skip-tools).",ob="--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.",aM=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(nb);if(o&&(e.tools!==void 0||r))throw new Error(ob);return{ids:e.tools??t??$r,mode:r?"update":"converge",skipTools:o}},rb=(e,t)=>e instanceof jn?e.step:t.at(-1)?.step??"zshrc",cM=async()=>{let e=[];try{await Wu(t=>{e.push(t)})}catch(t){e.push({step:rb(t,e),outcome:"failed",message:`The ${rb(t,e)} step failed: ${t instanceof Error?t.message:String(t)}`,level:"warn"})}return e},lM=(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}`}))},uM=async(e,t)=>{try{return e.skipTools?await Zp(e.ids,t.probeDeps):await Xp({ids:e.ids,mode:e.mode,probeDeps:t.probeDeps,run:t.run})}catch(r){return lM(e.ids,r)}},dM=e=>({step:e.step,outcome:e.outcome,message:e.message}),yc=async(e={})=>{let t=aM(e);st.withheld=e.unattended===!0;let r=await cM(),n=await uM(t,e),o=await iM(e.portlessDeps??sM()),s=eb({init:r,tools:n,portless:o},{skipTools:t.skipTools});yt({title:"infra-kit setup",sections:s},{ascii:e.ascii}),d.info(Fn),tb(s)&&(oM.exitCode=1);let i={init:r.map(dM),tools:n,portlessService:{link:o.link,node:o.node.outcome,service:o.service,command:o.command},report:s,converged:!t.skipTools,changed:n.some(a=>a.action==="installed"||a.action==="updated"),allSucceeded:n.every(a=>a.action!=="failed")};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}},pM=j.object({step:j.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:j.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:j.string().describe("The same line a human running this would have read")}),mM=j.object({id:j.string().describe("Dependency id"),action:j.enum(["installed","updated","skipped","refused","failed"]).describe("What happened"),before:j.object({present:j.boolean(),onPath:j.boolean(),version:j.string().nullable(),manager:j.string()}).describe("The tool\u2019s state before this run"),commands:j.array(j.string()).describe("The exact commands, one per step \u2014 printed even when refused"),detail:j.string().describe("Why, in one line")}),fM=j.object({link:j.enum(["created","repointed","unchanged","skipped-local","skipped-unresolved","failed"]).describe("What the ~/.infra-kit/portless link step did"),node:j.enum(["created","refreshed","unchanged","skipped-local","skipped-platform","failed"]).describe("What the ~/.infra-kit/node step did"),service:j.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:j.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")}),gM={init:j.array(pM).describe("One entry per init step, in the order they ran"),tools:j.array(mM).describe("One result per requested dependency"),portlessService:fM.describe("The portless link, node, and system-service step \u2014 run on every setup, never gated on the tool options"),converged:j.boolean().describe("Whether the dependency step could act at all (false under skipTools)"),changed:j.boolean().describe("Whether anything was installed or updated"),report:j.array(j.object({label:j.string().describe("Section heading"),rows:j.array(j.object({name:j.string().describe("Init step, tool id, or portless part"),status:j.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:j.string().describe("The row message, as printed"),notes:j.array(j.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:j.boolean().describe("Whether no tool failed (a refusal is not a failure)")},hM={tools:j.array(j.enum($r)).optional().describe("Which tools to act on. Omit for all six."),mode:j.enum(["converge","update"]).optional().describe("converge (default): install what is missing and update the rest. update: never install."),skipTools:j.boolean().optional().describe("Read-only: run the init half, then REPORT what each tool needs without installing anything.")},tm=T({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:hM,outputSchema:gM,requiresHumanConfirm:!0,handler:e=>yc({tools:e.tools,update:e.mode==="update",skipTools:e.skipTools})});import{existsSync as db}from"node:fs";import pb from"node:path";import CM from"node:process";import{z as Wt}from"zod";import{createHash as vM}from"node:crypto";import{readFileSync as wM}from"node:fs";import{Buffer as vc}from"node:buffer";var sb=/^\s*(?:#|\/\/|;|--|<!--)\s*infra-kit:local-(start|end)\s*(?:-->\s*)?$/,yM=vc.from("infra-kit:local-"),rm=e=>{let t=e.findIndex(n=>sb.exec(n)?.[1]==="start");if(t===-1)return null;let r=e.slice(t+1).findIndex(n=>sb.exec(n)?.[1]==="end");return r===-1?null:{start:t,end:t+1+r}},ib=e=>e.includes(yM)?e.toString("utf8").split(`
|
|
449
|
+
`):null,ab=e=>{let t=ib(e),r=t&&rm(t);return t&&r?t.slice(r.start,r.end+1).join(`
|
|
450
|
+
`):null},cb=e=>{let t=ib(e),r=t&&rm(t);return!t||!r?e:vc.from([...t.slice(0,r.start),...t.slice(r.end+1)].join(`
|
|
451
|
+
`))},lb=(e,t)=>{let r=e.toString("utf8").split(`
|
|
452
|
+
`),n=rm(r);if(n)return vc.from([...r.slice(0,n.start),t,...r.slice(n.end+1)].join(`
|
|
453
|
+
`));let o=r.join(`
|
|
454
|
+
`);return vc.from(`${o}${o===""||o.endsWith(`
|
|
455
|
+
`)?"":`
|
|
456
|
+
`}${t}
|
|
457
|
+
`)};var uo=e=>vM("sha256").update(cb(wM(e))).digest("hex");import{readFileSync as PM,writeFileSync as xM}from"node:fs";import Rc from"node:path";import{z as St}from"zod";var ae="vendor",kM=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".vitest",".output",".source",".nitro",".tanstack"]),bM=new Set([".sync-manifest.json",".eslintcache","log.txt","routeTree.gen.ts"]),RM=[".tsbuildinfo"],nm=e=>kM.has(e),om=e=>bM.has(e)?!0:RM.some(t=>e.endsWith(t)),wc=e=>{let t=e.split("/"),r=t.pop()??"";return t.some(o=>nm(o))||om(r)};import{readdirSync as SM}from"node:fs";import sm from"node:path";var EM=e=>e.split(sm.sep).join("/"),kc=e=>{let t=[],r=n=>{for(let o of SM(n,{withFileTypes:!0})){let s=sm.join(n,o.name);if(o.isDirectory()){if(nm(o.name))continue;r(s);continue}om(o.name)||t.push(EM(sm.relative(e,s)))}};return r(e),t.sort()};var rt=".sync-manifest.json",bc=1,TM=St.object({schemaVersion:St.number().optional(),source:St.string(),commit:St.string(),syncedAt:St.string(),fileCount:St.number(),files:St.record(St.string(),St.string())}),im=e=>(e.schemaVersion??bc)>bc,ub=(e,t)=>{let r={},n=t?[...new Set(t)].sort():kc(e);for(let o of n)try{r[o]=uo(Rc.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},ii=e=>{let t=Rc.join(e,rt),r;try{r=PM(t,"utf8")}catch{throw new Error(`Missing ${rt} at ${t}`)}let n=TM.safeParse(JSON.parse(r));if(!n.success)throw new Error(`Invalid ${rt} at ${t}: ${St.prettifyError(n.error)}`);return n.data},am=(e,t,r)=>{let n=ub(e,r),o={schemaVersion:bc,source:t.source,commit:t.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(n).length,files:n};return xM(Rc.join(e,rt),`${JSON.stringify(o,null,2)}
|
|
458
|
+
`),o},cm=(e,t)=>{let r=Object.fromEntries(Object.entries(t.files).filter(([c])=>!wc(c))),n=kc(e),o=[],s=[];for(let c of n){if(!(c in r)){s.push(c);continue}uo(Rc.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 lm=30,um=(e,t)=>{if(t.length!==0){d.info(`
|
|
459
|
+
${e} (${t.length}):`);for(let r of t.slice(0,lm))d.info(` ${r}`);t.length>lm&&d.info(` \u2026and ${t.length-lm} more`)}},Sc=async(e={})=>{let t=e.cwd??await $(),r=pb.join(t,ae),n={modified:[],added:[],removed:[],fileCount:0};if(!db(r)){d.info(`\u2139\uFE0F No ${ae}/ folder found \u2014 nothing to check.`);let u={status:"skipped",ok:!0,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}if(!db(pb.join(r,rt))){d.error(`\u274C Missing ${ae}/${rt}. Re-run the vendor sync to generate it.`);let u={status:"missing-manifest",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let o=ii(r);if(im(o)){d.error(`\u274C ${ae}/${rt} has a newer schemaVersion (${String(o.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let u={status:"unknown-schema",ok:!1,...n};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}}let{modified:s,added:i,removed:a}=cm(r,o),c=s.length>0||i.length>0||a.length>0;c?(d.error(`\u274C ${ae}/ has drifted from ${ae}/${rt}.`),d.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),um("Modified",s),um("Added (not in manifest)",i),um("Removed (in manifest, now missing)",a)):d.info(`\u2705 ${ae}/ matches manifest (${o.fileCount} files).`);let l={status:c?"drift":"clean",ok:!c,fileCount:o.fileCount,modified:s,added:i,removed:a};return{content:R(JSON.stringify(l,null,2)),structuredContent:l}},$M={status:Wt.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:Wt.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:Wt.number(),modified:Wt.array(Wt.string()),added:Wt.array(Wt.string()),removed:Wt.array(Wt.string())},dm=T({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:$M,handler:()=>Sc({cwd:CM.cwd()})});import mb from"node:process";import{z as ai}from"zod";var fb=async e=>{try{return await e()}catch{return null}},Ec=async()=>{let e=U.version;d.info(e);let t=await fb($),r=t===null?null:await fb(()=>Ie(t)),n={version:e,cwd:mb.cwd(),repoRoot:t,mainRepoRoot:r,projectDir:mb.env.CLAUDE_PROJECT_DIR||null};return{content:R(JSON.stringify(n,null,2)),structuredContent:n}},pm=T({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:ai.string().describe("Installed infra-kit CLI version (from package.json)"),cwd:ai.string().describe("The working directory of this process"),repoRoot:ai.string().nullable().describe("git toplevel of cwd \u2014 the worktree itself in a linked worktree; null when git cannot answer"),mainRepoRoot:ai.string().nullable().describe("The main checkout a linked worktree belongs to (equals repoRoot outside worktrees); null with repoRoot"),projectDir:ai.string().nullable().describe("CLAUDE_PROJECT_DIR as Claude Code set it for this process, or null")},handler:Ec});import Tb from"@inquirer/confirm";import NM from"node:path";import{z as G}from"zod";import{$ as ci}from"zx";import AM from"@inquirer/input";import hb from"@inquirer/select";import{$ as fr}from"zx";var po="dev",OM="main",yb=["new","local","remote"],vb=async()=>{let e=await fr({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},DM=2,mm=async()=>{if(await re()==="main")return we;let e=await fr({nothrow:!0,quiet:!0})`git ls-remote --exit-code origin refs/heads/${po}`;if(e.exitCode===0)return po;if(e.exitCode!==DM)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 ${po} exists`});return await vb()??po},wb=async e=>{let t=e?.trim();if(!t)return mm();if(t===po&&await re()==="main")throw new g(void 0,{operation:"create feature worktree",remediation:'this repo sets "gitFlow": "main" in infra-kit.json, so features branch off main \u2014 drop --base or pass --base main'});return t===po||t===OM||t===await vb()?t:Ce(Re(t))},kb=async()=>N(e=>hb({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"}}),bb=async()=>N(e=>AM({message:"Feature name (becomes feature/<name>):",required:!0,validate:t=>oo(t)===Ns?"Enter a name":!0},e),{whenHeadless:{refuse:"feature"}}),Rb=async(e,t)=>e.length===0?t:N(r=>hb({message:"Base branch:",default:t,choices:[t,...e].map(n=>({name:n,value:n}))},r),{whenHeadless:{value:t}}),IM=async e=>{let t=await fr({nothrow:!0,quiet:!0})`git check-ref-format --branch ${e}`;if(e===Ns||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`})},gb=async e=>(await fr({nothrow:!0,quiet:!0})`git fetch origin ${e}`).exitCode===0,_M=async e=>(await fr({nothrow:!0,quiet:!0})`git show-ref --verify --quiet refs/heads/${e}`).exitCode===0,Sb=async e=>{let{names:t,base:r}=e,n=[...new Set(t.map(oo))];for(let s of n)await IM(s);if(!await gb(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 _M(s)?o.push({branch:s,base:r,source:"local"}):await gb(s)?o.push({branch:s,base:r,source:"remote"}):o.push({branch:s,base:r,source:"new"});return o},Eb=async(e,t)=>{let{branch:r,base:n,source:o}=e;o==="local"?await fr`git worktree add ${t} ${r}`:o==="remote"?await fr`git worktree add --track -b ${r} ${t} origin/${r}`:await fr`git worktree add --no-track -b ${r} ${t} origin/${n}`},Pb=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 li="create worktrees",MM=["already_open","orca_unreachable","orca_absent","orca_worktree_not_selectable","orca_error"],fm=()=>({orcaOpened:[],orcaSkipped:[],orcaHidden:[]}),Pc=async e=>{let{confirmedCommand:t,githubDesktop:r,orca:n}=e;await Le({operation:li}),jM(e);try{let o=await $(),s=`${o}${ce}`;await xb(`${s}/${tn.release}`),await xb(`${s}/${tn.feature}`);let i=await FM(e),a=i==="feature"?await BM(e):await LM(e);if(a===null){d.info("\u2139\uFE0F No open release branches found"),y.print();let F={kind:i,createdWorktrees:[],count:0,features:[],...fm()};return{content:R(JSON.stringify(F,null,2)),structuredContent:F}}let c=await V(),l=await UM(r,c),u=await VM(n,c),p=await Ie(o),m=NM.basename(p),f=u?await WM({explicit:n!==void 0,mainRepoRoot:p}):null;await q(t,GM(f,m,a.previewLines)),t||y.addOption("--yes",!0);let h=f?await JM(f,p):null,b=await zM(a.targets,s);if(XM(b),l)for(let F of b)await ci`github ${s}/${F}`,await ci`sleep 5`;let C=h?await HM({registration:h,createdWorktrees:b,worktreeDir:s,mainRepoRoot:p,repoName:m,config:c}):fm();qM(C),y.print();let k={kind:i,createdWorktrees:b,count:b.length,features:a.features.filter(F=>b.includes(F.branch)),...C};return{content:R(JSON.stringify(k,null,2)),structuredContent:k}}catch(o){throw _e(o)||Ee(o)||o instanceof A?o:(d.debug({err:o},"Error managing worktrees"),new g(o,{operation:li,remediation:o instanceof g&&o.remediation||"verify branches don't already exist as worktrees: 'git worktree list'"}))}},jM=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:li,remediation:"pass either --versions/--all (release worktrees) or --feature [--base] (feature worktrees)",stderrExcerpt:"--feature/--base cannot be combined with --versions/--all"})},FM=async e=>e.feature!==void 0||e.base!==void 0?"feature":e.all||e.versions!==void 0?"release":(y.setInteractive(),kb()),LM=async e=>{let{all:t,versions:r}=e,n=await Se("release"),o=[];if(r)o=r.split(",").map(a=>Ce(Re(a.trim())));else{let a=await K(),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 he();o=await ur(ye({branches:c,descriptions:u,types:l}),{required:!0})}}t?y.addOption("--all",!0):y.addOption("--versions",Ut(o));let{branchesToCreate:s}=YM({selectedReleaseBranches:o,currentWorktrees:n});return{targets:s.map(a=>({branch:a,add:c=>ci`git worktree add ${c} ${a}`})),features:[],previewLines:[]}},BM=async e=>{let r=e.feature?.split(",").filter(l=>l.trim()!=="")??[],n=e.base;if(r.length===0&&(y.setInteractive(),r=[await bb()],n===void 0)){let l=(await K()).map(u=>u.branch);n=await Rb(l,await mm())}let o=await wb(n),s=await Sb({names:r,base:o});y.addOption("--feature",s.map(l=>l.branch.replace(/^feature\//,"")).join(",")),y.addOption("--base",o);let i=await Se("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=>Eb(l,u)})),features:a,previewLines:a.map(Pb)}},UM=async(e,t)=>{let r=t.worktrees?.openInGithubDesktop,n=e??r??await N(o=>Tb({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},VM=async(e,t)=>{let r=t.worktrees?.openInOrca,n=e??r??await N(o=>Tb({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},Cb=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"},WM=async e=>{let{explicit:t,mainRepoRoot:r}=e,n=await Zt();if(n!=="ready"){let{reason:s,text:i}=Cb(n);if(t)throw d.warn({operation:li},`\u26D4 --orca was passed but ${i}`),new A({status:"refused",reason:s,agentMode:_.source},2,{operation:li,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 kg(r);return{probe:n,registered:o.registered,visibility:o.visibility}},GM=(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(`
|
|
460
|
+
`)},JM=async(e,t)=>{if(e.probe!=="ready")return{kind:"skip",reason:Cb(e.probe).reason};if(e.registered)return{kind:"ready",visibility:e.visibility};try{let{visibility:r}=await bg(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 an?r.code:void 0}}},KM=e=>`Orca \u2192 ${e} \u2192 "hidden worktrees" card \u2192 Show, or Settings \u2192 General \u2192 Workspace \u2192 external-worktree sources`,HM=async e=>{let{registration:t,createdWorktrees:r,worktreeDir:n,mainRepoRoot:o,repoName:s,config:i}=e,a=fm();if(t.kind==="skip"){for(let p of r)a.orcaSkipped.push({branch:p,reason:t.reason,code:t.code});return a}let c=pg(i),l=r.length===1&&t.visibility!=="hide",u=Sg();for(let p of r){let m=`${n}/${p}`;try{let{layout:f}=await Eg({cwd:m,title:Pg({branch:p}),focus:l,layout:"full",panes:c,poll:u});await Rg(o,m)?a.orcaOpened.push({branch:p,layout:f}):a.orcaHidden.push({branch:p,path:m,fix:KM(s)})}catch(f){d.warn({error:f,branch:p},`\u26A0\uFE0F Failed to open Orca terminals for ${p}`),f instanceof an&&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 an?f.code:void 0})}}return a},qM=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}`)}},xb=async e=>{await ci`mkdir -p ${e}`},YM=e=>{let{selectedReleaseBranches:t,currentWorktrees:r}=e,n=r.filter(s=>nn(s));return{branchesToCreate:t.filter(s=>!n.includes(s))}},zM=async(e,t)=>{let r=await Promise.allSettled(e.map(async o=>{let s=`${t}/${o.branch}`;return await o.add(s),await ci({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},XM=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")},gm=T({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:G.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:G.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:G.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:G.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:G.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:G.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:G.enum(["release","feature"]).describe("Which kind of worktree the run created"),features:G.array(G.object({branch:G.string(),base:G.string(),source:G.enum(yb)})).describe('Created feature worktrees: source "new" = cut from origin/<base>; "local" / "remote" = an existing branch checked out as-is (base not applied)'),createdWorktrees:G.array(G.string()).describe("List of created git worktree branches"),count:G.number().describe("Number of git worktrees created"),orcaOpened:G.array(G.object({branch:G.string(),layout:G.enum(["full","single-pane"])})).describe("Created worktrees that got an Orca terminal tab on a row the sidebar shows, with the layout applied"),orcaSkipped:G.array(G.object({branch:G.string(),reason:G.enum(MM),code:G.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:G.array(G.object({branch:G.string(),path:G.string(),fix:G.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:Pc});import{z as gr}from"zod";var xc=async()=>{await V();let[e,t]=await Promise.all([Se("release"),Se("feature")]);if(e.length===0&&t.length===0){d.info("\u2139\uFE0F No active worktrees found");let s={worktrees:[],count:0,features:[]};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}}let r=e.length>0?await ZM(e):[],n=[];r.length>0&&n.push(`\u{1F33F} Active worktrees:
|
|
461
|
+
|
|
462
|
+
${QM(r).join(`
|
|
437
463
|
`)}`),t.length>0&&n.push(`\u{1F9EA} Feature worktrees:
|
|
438
464
|
|
|
439
465
|
${t.join(`
|
|
440
466
|
`)}`),d.info(n.join(`
|
|
441
467
|
|
|
442
|
-
`));let o={worktrees:r,count:r.length,features:t};return{content:
|
|
443
|
-
`).filter(r=>r.trim().length>0),B_=async e=>{let[t,r]=await Promise.all([Fk(e.worktreePath),Fk(e.mainRoot)]);t.length>0&&Mr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&Mr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Wt();n!=="ready"&&Mr(`run \`infra-kit worktrees remove ${Ue(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},U_=async e=>{let t=Ue(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${M_}; ${t} && { sleep ${j_}; exit; }`;try{return(await Lf(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof Jr?new g(n,{operation:Lk,remediation:`run \`infra-kit worktrees remove ${Ue(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Bk=async e=>{let t=await L_();await B_(t),y.addOption("--self",!0),await J(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 U_(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 W_=e=>{if(he()){if(e.all)throw new O({status:"refused",agentMode:j.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions&&!e.feature)throw new O({status:"argument_required",argument:"versions",agentMode:j.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},V_=(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(", ")}`})},G_=async(e,t)=>{let r=await ui(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`})},J_=e=>e?e.split(",").map(t=>Te(ke(t.trim()))):[],K_=e=>e?e.split(",").filter(t=>t.trim()!=="").map(Ya):[],H_=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&y.addOption("--versions",Dt(r)),t.length>0&&y.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Qa=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 Bk(t)}await _e({operation:"remove worktrees"}),await K(),W_({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([be("release"),be("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),y.print();let h={removedWorktrees:[],failedWorktrees:[],count:0};return{content:b(JSON.stringify(h,null,2)),structuredContent:h}}let l=await $(),u=`${l}${ge}`,p=[];if(r)p=c;else if(n||o)p=[...J_(n),...K_(o)];else{y.setInteractive();let[h,S]=await Promise.all([me(),G()]),k=new Map(S.map(A=>[A.branch,A.type]));p=await Yt([...fe({branches:i,descriptions:h,types:k}),...a.map(A=>({value:A,label:A,type:"feature"}))],{required:!0})}V_(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):H_(p),await G_(u,p),await J(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await Or({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return cs(f),y.print(),ls({result:f,operation:"remove worktrees"})}catch(i){throw Oe(i)||i instanceof g?i:(d.error({error:i},"\u274C Error managing worktrees"),new g(i,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"}))}},Cp=C({name:"worktrees-remove",description:'Remove local git worktrees for the named release branches ("versions") and/or feature branches ("feature"). Over MCP you MUST pass "versions" or "feature" (comma-separated); bulk all=true removal is disabled here (it is a one-shot, unconfirmed wipe of every worktree) \u2014 the branch picker and confirmation are unavailable without a TTY. Every named target must be an active worktree, or the call errors without removing anything. What survives: the release and feature branches/commits themselves are never deleted, and the worktrees directory plus its release/feature subfolders are left in place (recreate a worktree with worktrees-add). What is lost: git refuses to remove a worktree with modified tracked files or untracked files, BUT it DOES delete the worktree directory including gitignored contents \u2014 a hydrated .env of Doppler secrets (re-fetch with env-load) and build output such as node_modules/dist (needs reinstall/rebuild). When every worktree is removed it also runs "git worktree prune". A branch git refuses to remove is listed in failedWorktrees and the result carries isError; a leftover that git already unregistered and that holds only tool state (.omc/state, .omc/sessions, .DS_Store) is swept automatically. Every Orca terminal open in a removed worktree is closed first; a call made from an Orca terminal INSIDE one of the targets is refused (orca_caller_inside_target) before anything is removed \u2014 re-run it from a terminal that is not an Orca pane of that worktree.',requiresHumanConfirm:!0,inputSchema:{versions:Xe.string().optional().describe('Comma-separated release versions or names to remove (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). This or "feature" is required: each must name an active worktree, or the call errors before removing anything.'),feature:Xe.string().optional().describe('Comma-separated feature names to remove (e.g. "checkout-v2" or "feature/checkout-v2"). This or "versions" is required; each must name an active feature worktree.'),confirm:Xe.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:Xe.array(Xe.string()).describe("List of removed git worktree branches"),failedWorktrees:Xe.array(Xe.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:Xe.number().describe("Number of git worktrees removed"),handedOff:Xe.object({branch:Xe.string(),worktreePath:Xe.string(),terminal:Xe.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Qa});import{z as js}from"zod";var ec=async e=>{let{confirmedCommand:t}=e;await _e({operation:"sync worktrees"}),await K();try{let r=await be("release"),n=await $(),o=`${n}${ge}`,s=await Fi();await J(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=q_({releasePRsList:s,currentWorktrees:r}),a=await Or({branches:i,worktreeDir:o,projectRoot:n});return cs(a),y.print(),ls({result:a,operation:"sync worktrees"})}catch(r){throw Oe(r)||r instanceof g?r:(d.error({error:r},"\u274C Error managing worktrees"),new g(r,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"}))}},q_=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>Wr(s)).filter(s=>!t.includes(s))}},$p=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:js.array(js.string()).describe("List of removed worktree branches"),failedWorktrees:js.array(js.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:js.number().describe("Number of worktrees removed during sync")},handler:ec});var Ap=[{key:"develop",label:"Develop"},{key:"release",label:"Release Management"},{key:"worktrees",label:"Worktrees"},{key:"environment",label:"Environment"},{key:"configuration",label:"Configuration"},{key:"vendor",label:"Vendor"},{key:"setup",label:"Setup & Diagnostics"}],xr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:Wl,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:id,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:md,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:jd,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:tp,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Nd,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Md,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:yd,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:op,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:qd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Yd,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:xp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:Tp,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:Cp,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:$p,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:ld,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:Zf,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Vc,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:cd,mcpExposed:!0,mutating:!0,groupPath:["env-clear"],sessionEnvNotice:!0},{cliName:"env-token-list",menuGroup:"environment",mcpTool:ud,mcpExposed:!0,mutating:!1,groupPath:["env-token-list"]},{cliName:"config-get",menuGroup:"configuration",mcpTool:Bl,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:bp,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:pp,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:qu,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:$l,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:Rp,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:jl,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 Op=e=>xr.filter(t=>t.menuGroup===e),Dp=e=>xr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var Y_=(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},Uk=e=>Ap.flatMap(({key:t,label:r})=>Op(t).flatMap(n=>{let o=Y_(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import Ip from"node:process";var z_="MODULE_TYPELESS_PACKAGE_JSON",X_=(e,t)=>typeof e=="object"&&e!==null?e.code:t,Wk=!1,Np=()=>{if(Wk)return;Wk=!0;let e=Ip.emitWarning.bind(Ip);Ip.emitWarning=((t,...r)=>{X_(r[0],r[1])!==z_&&e(t,...r)})};import{Command as lF,InvalidArgumentError as Kb,Option as Gb}from"commander";import{resolve as uF}from"node:path";import Fe from"node:process";import{cd as dF}from"zx";import Vk from"node:process";import{$ as Z_}from"zx";var _p=async()=>{let e=await ee(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await oe(i.path)}))),r=t.at(-1)?.exists===!0,n=await Ko(e.userProject,r),o=r?Ho(n):"";d.info(`Project name: ${e.projectName}
|
|
468
|
+
`));let o={worktrees:r,count:r.length,features:t};return{content:R(JSON.stringify(o,null,2)),structuredContent:o}},ZM=async e=>{let[t,r]=await Promise.all([K(),he()]),n=new Map(t.map(o=>[o.branch,o.type]));return e.flatMap(o=>{let s=te(o);if(!s)return[];let i=se(s),a=n.get(o)||"regular",c=r.get(de(s))||null;return[{version:i,type:a,description:c}]})},QM=e=>{let t=Math.max(...e.map(r=>r.version.length));return e.map(r=>{let n=Cs(r.version,r.type,t);return r.description?`${n} ${r.description}`:n})},hm=T({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:gr.array(gr.object({version:gr.string().describe("Release version"),type:gr.enum(["regular","hotfix"]).describe("Release type"),description:gr.string().nullable().describe("Jira version description")})).describe("Release worktrees with details"),count:gr.number().describe("Number of release worktrees"),features:gr.array(gr.string()).describe("Branches of feature worktrees (feature/<name>)")},handler:xc});import{z as nt}from"zod";import ej from"node:fs/promises";import{$ as tj}from"zx";var Ab="remove this worktree",rj=2,nj=3,Tc=async e=>{try{return await ej.realpath(e)}catch{return e}},qr=(e,t)=>{throw new g(void 0,{operation:Ab,remediation:e,stderrExcerpt:t})},oj=e=>{if(e.startsWith("feature/"))return["--feature",e.slice(8)];let[t]=Ut([e]);return nn(e)&&t?["--versions",t]:qr("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`)},sj=async()=>{let e=await Tc(await $()),t=await Tc(await Ie(e));e===t&&qr("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 pt(t))await Tc(o.path)===e&&(r=o.branch);if(!r)return qr("check out a branch in this worktree first",`no branch is checked out at ${e}`);let n=await Tc(`${t}${ce}/${r}`);return n!==e&&qr("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:oj(r)}},$b=async e=>(await tj({quiet:!0})`git -C ${e} status --porcelain`).stdout.split(`
|
|
469
|
+
`).filter(r=>r.trim().length>0),ij=async e=>{let[t,r]=await Promise.all([$b(e.worktreePath),$b(e.mainRoot)]);t.length>0&&qr("commit or stash your changes (`git stash -u`), then retry",`uncommitted changes: ${t.join(", ")}`),r.length>0&&qr(`commit or stash the changes in the main checkout ${e.mainRoot}, then retry`,`the main checkout has uncommitted changes: ${r.join(", ")}`);let n=await Zt();n!=="ready"&&qr(`run \`infra-kit worktrees remove ${Ge(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,`--self hands the removal to an Orca terminal, and Orca is ${n}`)},aj=async e=>{let t=Ge(["infra-kit","worktrees","remove",...e.targetArgs,"--yes"]),r=`sleep ${rj}; ${t} && { sleep ${nj}; exit; }`;try{return(await yg(["terminal","create","--worktree",`path:${e.mainRoot}`,"--title",`ik: remove ${e.branch}`,"--command",r])).terminal.handle}catch(n){throw n instanceof an?new g(n,{operation:Ab,remediation:`run \`infra-kit worktrees remove ${Ge(e.targetArgs)}\` from the main checkout ${e.mainRoot}`,stderrExcerpt:n.message}):n}},Ob=async e=>{let t=await sj();await ij(t),y.addOption("--self",!0),await q(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 aj(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:R(JSON.stringify({status:"handed_off",...n},null,2)),structuredContent:{removedWorktrees:[],failedWorktrees:[],count:0,handedOff:n}}};var cj=e=>{if(ee()){if(e.all)throw new A({status:"refused",agentMode:_.source},2,{operation:"remove worktrees",remediation:"name targets explicitly via --versions <refs>; bulk --all removal is disabled under agent mode",stderrExcerpt:"--all is not permitted for worktrees remove under agent mode"});if(!e.versions&&!e.feature)throw new A({status:"argument_required",argument:"versions",agentMode:_.source},2,{operation:"remove worktrees",remediation:"pass --versions <refs> (comma-separated release versions/names) or --feature <names> on the re-run \u2014 `infra-kit worktrees list --json` lists them",stderrExcerpt:"worktrees remove under agent mode requires --versions or --feature"})}},lj=(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(", ")}`})},uj=async(e,t)=>{let r=await Mi(t.map(n=>`${e}/${n}`));if(r!==null)throw new A({status:"refused",reason:"orca_caller_inside_target",agentMode:_.source},2,{operation:"remove worktrees",remediation:`re-run from a terminal that is not an Orca pane of ${r} (a non-Orca terminal, or another worktree's row)`,stderrExcerpt:`this command runs inside an Orca terminal of ${r}, which the removal would close`})},dj=e=>e?e.split(",").map(t=>Ce(Re(t.trim()))):[],pj=e=>e?e.split(",").filter(t=>t.trim()!=="").map(oo):[],mj=e=>{let t=e.filter(n=>n.startsWith("feature/")),r=e.filter(n=>!t.includes(n));r.length>0&&y.addOption("--versions",Ut(r)),t.length>0&&y.addOption("--feature",t.map(n=>n.replace(/^feature\//,"")).join(","))},Cc=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 Ob(t)}await Le({operation:"remove worktrees"}),await V(),cj({all:r,versions:n,feature:o});try{let[i,a]=await Promise.all([Se("release"),Se("feature")]),c=[...i,...a];if(c.length===0){d.info("\u2139\uFE0F No active worktrees to remove"),y.print();let h={removedWorktrees:[],failedWorktrees:[],count:0};return{content:R(JSON.stringify(h,null,2)),structuredContent:h}}let l=await $(),u=`${l}${ce}`,p=[];if(r)p=c;else if(n||o)p=[...dj(n),...pj(o)];else{y.setInteractive();let[h,b]=await Promise.all([he(),K()]),C=new Map(b.map(k=>[k.branch,k.type]));p=await ur([...ye({branches:i,descriptions:h,types:C}),...a.map(k=>({value:k,label:k,type:"feature"}))],{required:!0})}lj(p,c);let m=p.length===c.length;m?y.addOption("--all",!0):mj(p),await uj(u,p),await q(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let f=await Gr({branches:p,worktreeDir:u,projectRoot:l,pruneFolder:m});return Ms(f),y.print(),js({result:f,operation:"remove worktrees"})}catch(i){throw _e(i)||Ee(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"}))}},ym=T({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:nt.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:nt.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:nt.boolean().optional().describe("Set true to execute; omit for a dry-run gate that echoes the resolved action.")},outputSchema:{removedWorktrees:nt.array(nt.string()).describe("List of removed git worktree branches"),failedWorktrees:nt.array(nt.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:nt.number().describe("Number of git worktrees removed"),handedOff:nt.object({branch:nt.string(),worktreePath:nt.string(),terminal:nt.string()}).optional().describe("--self only: the worktree whose removal now runs in an Orca tab of the main checkout")},handler:Cc});import{z as ui}from"zod";var $c=async e=>{let{confirmedCommand:t}=e;await Le({operation:"sync worktrees"}),await V();try{let r=await Se("release"),n=await $(),o=`${n}${ce}`,s=await Ua();await q(t,"Are you sure you want to proceed with these worktree changes?"),t||y.addOption("--yes",!0);let{branchesToRemove:i}=fj({releasePRsList:s,currentWorktrees:r}),a=await Gr({branches:i,worktreeDir:o,projectRoot:n});return Ms(a),y.print(),js({result:a,operation:"sync worktrees"})}catch(r){throw _e(r)||Ee(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"}))}},fj=e=>{let{releasePRsList:t,currentWorktrees:r}=e;return{branchesToRemove:r.filter(s=>nn(s)).filter(s=>!t.includes(s))}},vm=T({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:ui.array(ui.string()).describe("List of removed worktree branches"),failedWorktrees:ui.array(ui.string()).describe("Branches whose worktree could NOT be removed (git refused, or an unsweepable leftover remained)"),count:ui.number().describe("Number of worktrees removed during sync")},handler:$c});var wm=[{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"}],Yr=[{cliName:"dev",menuGroup:"develop",mcpTool:null,mcpExposed:!1,mutating:!0,groupPath:["dev"],longRunning:!0},{cliName:"dev-status",menuGroup:"develop",mcpTool:yu,mcpExposed:!0,mutating:!1,groupPath:["dev-status"]},{cliName:"e2e",menuGroup:"develop",mcpTool:Sd,mcpExposed:!1,mutating:!0,groupPath:["e2e"]},{cliName:"merge-dev",menuGroup:"release",mcpTool:rp,mcpExposed:!0,mutating:!0,groupPath:["release","merge-dev"]},{cliName:"release-list",menuGroup:"release",mcpTool:ap,mcpExposed:!0,mutating:!1,groupPath:["release","list"]},{cliName:"release-create",menuGroup:"release",mcpTool:_p,mcpExposed:!0,mutating:!0,groupPath:["release","create"]},{cliName:"release-edit",menuGroup:"release",mcpTool:Gp,mcpExposed:!0,mutating:!0,groupPath:["release","edit"]},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:Bp,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-all"]},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Vp,mcpExposed:!0,mutating:!0,groupPath:["release","deploy-selected"]},{cliName:"release-deliver",menuGroup:"release",mcpTool:ip,mcpExposed:!1,mutating:!0,humanOnly:!0,groupPath:["release","deliver"]},{cliName:"release-remove",menuGroup:"release",mcpTool:Hp,mcpExposed:!0,mutating:!0,groupPath:["release","remove"]},{cliName:"local-deploy-all",menuGroup:null,mcpTool:$p,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-all"]},{cliName:"local-deploy-selected",menuGroup:null,mcpTool:Ap,mcpExposed:!0,mutating:!0,groupPath:["local","deploy-selected"]},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:gm,mcpExposed:!0,mutating:!0,groupPath:["worktrees","add"]},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:hm,mcpExposed:!0,mutating:!1,groupPath:["worktrees","list"]},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:ym,mcpExposed:!0,mutating:!0,groupPath:["worktrees","remove"]},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:vm,mcpExposed:!0,mutating:!0,groupPath:["worktrees","sync"]},{cliName:"env-status",menuGroup:"environment",mcpTool:Dd,mcpExposed:!0,mutating:!1,groupPath:["env-status"]},{cliName:"env-list",menuGroup:"environment",mcpTool:xd,mcpExposed:!0,mutating:!1,groupPath:["env-list"]},{cliName:"env-load",menuGroup:"environment",mcpTool:Od,mcpExposed:!0,mutating:!0,groupPath:["env-load"],sessionEnvNotice:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:Pd,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:gu,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:dm,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:tm,mcpExposed:!0,mutating:!0,groupPath:["setup"]},{cliName:"doctor",menuGroup:"setup",mcpTool:dd,mcpExposed:!0,mutating:!1,groupPath:["doctor"]},{cliName:"audit",menuGroup:"setup",mcpTool:ou,mcpExposed:!0,mutating:!1,groupPath:["audit"]},{cliName:"version",menuGroup:"setup",mcpTool:pm,mcpExposed:!0,mutating:!1,groupPath:["version"]},{cliName:"change-stats",menuGroup:null,mcpTool:pu,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 km=e=>Yr.filter(t=>t.menuGroup===e),bm=e=>Yr.some(t=>t.longRunning===!0&&t.groupPath.join(" ")===e);var gj=(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},Db=e=>wm.flatMap(({key:t,label:r})=>km(t).flatMap(n=>{let o=gj(e,n.groupPath);return o?[{name:n.groupPath.join(" "),description:o.description(),group:r}]:[]}));import{Command as xL,InvalidArgumentError as FR,Option as MR}from"commander";import{resolve as TL}from"node:path";import Ue from"node:process";import{cd as CL}from"zx";import Ib from"node:process";import{$ as hj}from"zx";var Rm=async()=>{let e=await z(),t=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async i=>({...i,exists:await ie(i.path)}))),r=t.at(-1)?.exists===!0,n=await es(e.userProject,r),o=r?ts(n):"";d.info(`Project name: ${e.projectName}
|
|
444
470
|
`),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
|
-
`);try{let{resolveHere:n}=await import(
|
|
447
|
-
`)}},
|
|
448
|
-
`,"%0A")}`,
|
|
449
|
-
`).filter(n=>n.trim()!=="").map(n=>{let o=n.indexOf("="),s=n.slice(0,Math.max(o,0));if(!/^[A-Z_][A-Z0-9_]*$/.test(s))throw new g(void 0,{operation:"deploy-run",remediation:"write each extra-env line as KEY=VALUE with an upper-case KEY",stderrExcerpt:"an extra-env line is not KEY=VALUE"});return[s,n.slice(o+1)]});for(let[,n]of r)n!==""&&t(
|
|
450
|
-
`))},
|
|
451
|
-
`),
|
|
452
|
-
`)[0]??"",
|
|
453
|
-
`;import{existsSync as
|
|
471
|
+
`);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}},Sm=async()=>{let e=await z(),t=Ib.env.EDITOR||Ib.env.VISUAL||"vi",r=await On(e);r.createdConfig&&d.info(Dn(r)),d.info(`Opening ${w(e.userProject)} in ${t} (per-machine override \u2014 every key except "mcp")`),await hj({stdio:"inherit"})`${t} ${e.userProject}`,Yt();let n={path:e.userProject,editor:t};return{content:[{type:"text",text:JSON.stringify(n,null,2)}],structuredContent:n}};var Em=async({key:e,value:t,global:r})=>{Jo(e,"config-set");let n=r?"global":"project",o=fu(t),{file:s,previous:i}=await Ko(n,e,c=>({...c,[e]:o}));d.info(`Set ${e} = ${JSON.stringify(o)} in the ${wn[n]} (${w(s)})`);let a={key:e,value:o,previous:i??null,scope:n,path:s};return{content:R(JSON.stringify(a,null,2)),structuredContent:a}};var Pm=async({key:e,global:t})=>{Jo(e,"config-unset");let r=t?"global":"project",{file:n,previous:o,changed:s}=await Ko(r,e,a=>e in a?Object.fromEntries(Object.entries(a).filter(([c])=>c!==e)):null);d.info(s?`Removed ${e} from the ${wn[r]} (${w(n)})`:`${e} is not set in the ${wn[r]} (${w(n)}) \u2014 nothing to remove`);let i={key:e,removed:s,previous:o??null,scope:r,path:n};return{content:R(JSON.stringify(i,null,2)),structuredContent:i}};import Lb from"node:fs/promises";import di from"node:path";import Aj from"node:process";import{pathToFileURL as Oj}from"node:url";import{execFile as kj,spawn as bj}from"node:child_process";import yr from"node:fs/promises";import Rj from"node:os";import hr from"node:path";import Nb from"node:process";import{promisify as Sj}from"node:util";import _b from"node:fs/promises";import yj from"node:path";import{pathToFileURL as vj}from"node:url";var wj=".infra-kit-import-from-app.mjs",xm=async(e,t)=>{let r=yj.join(e,wj);await _b.writeFile(r,`export const resolveHere = (specifier) => import.meta.resolve(specifier)
|
|
472
|
+
`);try{let{resolveHere:n}=await import(vj(r).href);return await import(n(t))}finally{await _b.rm(r,{force:!0})}};var Ej=Sj(kj),Mb="3.39.0",Pj=10*1024*1024,xj=960,Tj=60,Tm=(e,t=500)=>e.length>t?`${e.slice(0,t)}\u2026`:e,Cj=e=>{try{let{FunctionError:t}=JSON.parse(e);return t===void 0?void 0:`FunctionError=${t}`}catch{return`unparseable invoke metadata: ${Tm(e)}`}},mo=class extends Error{constructor(t){super(t),this.name="DeploySkipped"}},$j=(e,t,r)=>new Promise((n,o)=>{let s=bj(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}`))})}),Oc={run:$j,capture:async(e,t,r)=>{let{stdout:n}=await Ej(e,t,{...r,maxBuffer:Pj});return n},sleep:e=>new Promise(t=>{setTimeout(t,e)}),random:Math.random,log:e=>{Nb.stdout.write(`${e}
|
|
473
|
+
`)}},Ac=e=>({AWS_RETRY_MODE:"adaptive",AWS_MAX_ATTEMPTS:"10",...e,AWS_PAGER:""}),jb=async e=>{let t=JSON.parse(await yr.readFile(hr.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},$m=async e=>{let t=await yr.readdir(e,{withFileTypes:!0});await Promise.all(t.filter(r=>r.isDirectory()).map(r=>{let n=hr.join(e,r.name);return r.name==="node_modules"?yr.rm(n,{recursive:!0,force:!0}):$m(n)}))},Cm=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 yr.readFile(hr.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`)},Am=({root:e,service:t,project:r,scriptDir:n,env:o=Nb.env,deps:s=Oc})=>{let i=async(v,S,P,O={})=>{s.log(`COMMAND: ${[S,...P].join(" ")}`);try{await s.run(S,P,{cwd:O.cwd??e,env:O.env??o})}catch(D){throw new Error(`${v} failed: ${D.message}`)}},a=async(v,S,P={})=>{let{attempts:O=8,initialDelaySeconds:D=3,maxDelaySeconds:B=60}=P,ke=async oe=>{try{return await S()}catch(Pt){if(oe>=O)throw new Error(`${v} failed after ${O} attempts: ${Pt.message}`);let vi=Math.min(B,D*2**(oe-1)),wi=Math.round((vi/2+s.random()*vi/2)*10)/10;return s.log(`Attempt ${oe}/${O} failed. Retrying in ${wi}s...`),await s.sleep(wi*1e3),ke(oe+1)}};return ke(1)},c=async(v,S,P=o)=>{s.log(`COMMAND: aws ${S.join(" ")}`),await a(v,()=>s.run("aws",S,{cwd:e,env:Ac(P)}))},l=async(v,S={})=>{await i(`aws ${v.slice(0,2).join(" ")}`,"aws",v,{cwd:S.cwd,env:Ac(S.env??o)})},u=async v=>{let S=await Promise.all(v.map(async P=>{try{let O=await s.capture("aws",["ssm","get-parameter","--name",P,"--query","Parameter.Value","--output","text"],{cwd:e,env:Ac(o)});return[P,O.trim()]}catch(O){throw new Error(`SSM parameter ${P}: ${O instanceof Error?O.message:String(O)}`)}}));return Object.fromEntries(S)},p=async v=>{let S=[`turbo@${await jb(e)}`,...v?[`serverless@${Mb}`]:[]];await i("Install tools","pnpm",["add","-g",...S])},m=async(v,S)=>{let P=hr.join(e,"out"),O={...o,...S.buildEnv},D=S.buildTask??O.TURBO_BUILD_TASK??"build";return await yr.rm(P,{recursive:!0,force:!0}),await i(`Prune to ${v}`,"turbo",["prune",v],{env:O}),await i("Install dependencies","pnpm",["install"],{cwd:P,env:O}),await i(`Build ${v}`,"pnpm",["exec","turbo",D,`--filter=${v}`,"--env-mode=loose"],{cwd:P,env:O}),S.installProd&&(s.log("COMMAND: remove every node_modules under ./out"),await $m(P),await i("Install production dependencies","pnpm",["install","--frozen-lockfile","--node-linker=hoisted","--prod"],{cwd:P,env:O}),await i("Show node_modules size","du",["-sm","./node_modules/"],{cwd:P})),P},f=(v,S,P)=>({stage:v,outDir:S,appDir:P,importFromApp:O=>xm(P,O)}),h=async(v,S,P)=>{if(S!==void 0){s.log(`Running ${v} hooks...`);try{await S(P)}catch(O){throw new Error(`${v} hooks failed: ${O.message}`)}s.log(`${v} hooks completed successfully`)}},b=async v=>{let{app:S,appPath:P}=await Cm(e,n,v);await p(!0);let O={...o,...v.buildEnv},D=await m(S,{installProd:!0,buildTask:v.buildTask,buildEnv:v.buildEnv}),B=f(v.stage,D,hr.join(D,P));await h("Pre-deployment",v.preDeploy,B),await i("Deploy with Serverless","serverless",["deploy","--stage",v.stage,"--force"],{cwd:B.appDir,env:O}),v.restApiId===void 0?s.log(`Skipping API Gateway deployment for ${S}: no restApiId.`):await c("Create API Gateway deployment",["apigateway","create-deployment","--rest-api-id",v.restApiId,"--stage-name","api"],O),await h("Post-deployment",v.postDeploy,B)},C=async v=>{let{app:S,appPath:P}=await Cm(e,n,v);await p(!1);let O={...o,...v.buildEnv},D=await m(S,{installProd:!1,buildTask:v.buildTask,buildEnv:v.buildEnv}),B=f(v.stage,D,hr.join(D,P)),ke=`s3://${v.bucket}${v.destPath??""}`,oe=v.sourcePath??"./dist";await i("Sync to S3","aws",["s3","sync",oe,ke,...v.syncFlags??[],"--only-show-errors"],{cwd:B.appDir,env:Ac(O)}),await c("Invalidate CloudFront",["cloudfront","create-invalidation","--distribution-id",v.cloudfrontId,"--paths",v.invalidationPath??"/*"],O),await h("Post-deployment",v.postDeploy,B)},k=async(v,S,P)=>{let O=await yr.mkdtemp(hr.join(Rj.tmpdir(),"infra-kit-lambda-")),D=hr.join(O,"response.json"),B=["lambda","invoke","--function-name",v.functionName,...P===void 0?[]:["--region",P],"--cli-binary-format","raw-in-base64-out","--payload",v.payload??S,"--cli-read-timeout",String(xj),"--cli-connect-timeout",String(Tj),D],ke=Date.now();s.log(`COMMAND: aws ${B.join(" ")}`);try{let oe=await s.capture("aws",B,{cwd:e,env:{...o,AWS_PAGER:""}}).then(Cj,Yc=>`aws CLI failed: ${Tm(Yc instanceof Error?Yc.message:String(Yc))}`),Pt=await yr.readFile(D,"utf-8").catch(()=>""),vi=((Date.now()-ke)/1e3).toFixed(1),wi=oe!==void 0&&Pt?`; response: ${Tm(Pt)}`:"";return{outcome:`${v.functionName} (${vi}s)`,failure:oe===void 0?void 0:oe+wi}}finally{await yr.rm(O,{recursive:!0,force:!0})}};return{root:e,service:t,project:r,ssm:u,aws:l,run:(v,S,P={})=>s.run(v,S,{cwd:P.cwd??e,env:P.env??o}),capture:(v,S,P={})=>s.capture(v,S,{cwd:P.cwd??e,env:P.env??o}),retry:a,skip:v=>{throw new mo(v)},pruneAndBuild:m,deployBackendApi:b,deployFrontendUi:C,invokeLambdas:async v=>{let{region:S,payload:P="{}",blocking:O=[],steps:D=[]}=v;for(let B of O){let{outcome:ke,failure:oe}=await k(B,P,S);if(oe!==void 0)throw new Error(`Lambda ${ke} failed: ${oe}`);s.log(`Lambda ${ke} OK`)}for(let B of D){let ke=await Promise.all(B.map(oe=>k(oe,P,S).catch(Pt=>({outcome:oe.functionName,failure:String(Pt)}))));for(let{outcome:oe,failure:Pt}of ke)s.log(Pt===void 0?`Lambda ${oe} OK`:`Warning: Lambda ${oe} failed, continuing: ${Pt}`)}},importFromApp:xm}};var Fb=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),Dj=async(e,t)=>{let r=di.join(e,"devops","scripts",`deploy-${t}.sh`);try{await Lb.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},Ij=e=>`::add-mask::${e.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
|
|
474
|
+
`,"%0A")}`,_j=(e,t)=>{let r=(e??"").split(`
|
|
475
|
+
`).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(Ij(n));return Object.fromEntries(r)},Nj=async e=>{try{await Lb.access(e)}catch{throw new g(void 0,{operation:`run ${di.basename(e)}`,remediation:"create it, or fix the deploy path in infra-kit.deploy.ts",stderrExcerpt:`${e} does not exist`})}let t=await import(Oj(e).href);if(typeof t.default!="function")throw new g(void 0,{operation:`run ${di.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},Om=async e=>{let{service:t,env:r=Aj.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(ee()&&r.INFRA_KIT_DEPLOY_VIA!==Ws)throw new A({status:"refused",agentMode:_.source},2,{operation:`deploy ${t}`,remediation:"ask a human to run `infra-kit deploy-run` from their own shell, or deploy through `infra-kit release deploy-selected` (CI) or `infra-kit local deploy-selected`, which check the environment first",stderrExcerpt:"deploy-run deploys with whatever AWS credentials are loaded: refused in agent mode"});let n=e.cwd??await $(),o=e.deps??Oc,{INFRA_KIT_EXTRA_ENV:s,...i}=r,a={...i,..._j(s,o.log)},c=await Rt(n),l=c?.services[t]?.deploy;if(l===void 0)await o.run("sh",[await Dj(n,t)],{cwd:n,env:a});else{let u=await Nj(di.join(n,l)),p=Am({root:n,service:t,project:c?.project,scriptDir:di.dirname(l),env:a,deps:o});try{await u(p)}catch(m){if(!(m instanceof mo))throw m;return d.info(`\u23ED\uFE0F ${t} skipped: ${m.message}`),Fb({status:"skipped",service:t,reason:m.message})}}return d.info(`\u2705 ${t} deployed`),Fb({status:"deployed",service:t})};import{DEPLOY_CONFIG_FILE as pi}from"@slip-stream-kit/config/internal";import Ic from"node:fs/promises";import _c from"node:path";var Dm=async e=>{try{return await Ic.readFile(e,"utf-8")}catch{return}},Dc=e=>({content:R(JSON.stringify(e,null,2)),structuredContent:e}),Mj={created:"missing",updated:"differs",unchanged:"matches",removed:"no longer generated"},Bb=async(e,t)=>(await Promise.all(t.map(async n=>{let o=_c.join(e,n);return(await Dm(o))?.startsWith(io)?[{path:n,absolute:o}]:[]}))).flat(),jj=async(e,t)=>t.replaceV1!==!0?[]:(await Bb(e,up)).map(r=>({...r,status:"removed"})),Fj=async(e,t)=>{let n=(await Promise.all(Object.entries(t.services).map(async([o,s])=>s.deploy===void 0?[]:await Dm(_c.join(e,s.deploy))===void 0?[`${o}: ${s.deploy}`]:[]))).flat();if(n.length>0)throw new Error(`Deploy scripts named in ${pi} do not exist: ${n.join(", ")}`)},Lj=async(e,t)=>{if(t.replaceV1===!0)return;let r=await Bb(e,dp);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 ${pi} no longer sets. Restore the hand-written v1 workflows from git history (or set replaceV1 again) before syncing.`)},Im=async(e={})=>{let t=e.cwd??await $(),r=await Rt(t);if(r===void 0)return(e.check?d.info.bind(d):d.error.bind(d))(`No ${pi} at ${t}, nothing to generate.`),Dc({status:"missing-config",ok:!!e.check,files:[]});await Lj(t,r),await Fj(t,r);let n=await Promise.all(hp(r).map(async a=>{let c=_c.join(t,a.path),l=await Dm(c),u="unchanged";return l===void 0?u="created":l!==a.content&&(u="updated"),{...a,absolute:c,status:u}})),o=await jj(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 ${pi}.`),Dc({status:"unchanged",ok:!0,files:i});if(e.check){d.error(`\u274C Deploy workflows differ from ${pi}; run \`infra-kit deploy-sync\` and commit:`);for(let a of s)d.error(` ${a.path} (${Mj[a.status]})`);return Dc({status:"drift",ok:!1,files:i})}for(let a of s){if(a.status==="removed"){await Ic.rm(a.absolute),d.info(`\u{1F5D1}\uFE0F Removed ${a.path}`);continue}await Ic.mkdir(_c.dirname(a.absolute),{recursive:!0}),await Ic.writeFile(a.absolute,a.content),d.info(`\u270F\uFE0F ${a.status==="created"?"Created":"Updated"} ${a.path}`)}return Dc({status:"written",ok:!0,files:i})};var Ub="https://dashboard.doppler.com/workplace/projects",Bj=(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}"): ${Ub}/${e}`],_m=async({env:e})=>{let r=!!(await me())?.envs[e];await hg(e);let n=await Ke(),o=await Xt();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 Bj(n,e))d.warn(i);let s={env:e,removed:r,storePath:o,revokeUrl:`${Ub}/${n}`};return{content:R(JSON.stringify(s,null,2)),structuredContent:s}};import Uj from"@inquirer/confirm";import Vj from"@inquirer/input";import Wj from"@inquirer/password";import Gj from"@inquirer/select";import Jj from"node:fs/promises";import Et from"node:process";import{$ as Nc}from"zx";var Kj=async({stdin:e,fromEnv:t})=>{if(e)return{token:await Vb(),source:"stdin"};if(t){let n=Et.env[t];if(!n)throw new Error(`${t} is not set (or is empty) \u2014 nothing to store.`);return{token:n,source:"env"}}if(!Et.stdin.isTTY){let n=await Vb();if(n)return{token:n,source:"stdin"};if(!H())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(n=>Wj({message:"Paste the Doppler service token (input is hidden)",mask:!0},n),{output:Et.stderr,whenHeadless:{refuse:"stdin"}})).trim(),source:"prompt"}},Vb=async()=>{let e=[];Et.stdin.setEncoding("utf8");for await(let t of Et.stdin)e.push(t);return e.join("").trim()},Nm="DOPPLER_CONFIG",Hj=3e4,qj=async(e,t,r)=>{let n=Nc.quiet;Nc.quiet=!0;let o;try{o=(await Nc({env:xo(e)})`doppler secrets download --no-file --format json --project ${t} --config ${r}`.timeout(Hj)).stdout}catch(s){throw Yj(s,r)}finally{Nc.quiet=n}return ml(o)},Yj=(e,t)=>{let r=Kf(e)??(e instanceof Error?e.message:String(e));if(il(r)!=="auth")return e instanceof Error?e:new Error(String(e));let n=al(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(`
|
|
476
|
+
`))},zj=e=>[`Could not verify this token's scope: the Doppler payload for "${e}" carries no ${Nm}.`,"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(`
|
|
477
|
+
`),Gb=async(e,t,r,n)=>{let o=await qj(e,t,r);pl(o,r);let s=o.some(([i])=>i===Nm);if(!s&&!n)throw new Error(zj(r));return s},Wb="\0new-env",Xj=async()=>{if(H()||!Et.stdin.isTTY)throw new A({status:"argument_required",argument:"env",agentMode:_.source},2,{operation:"env-token-set",remediation:"pass the environment as the positional argument on the re-run: `infra-kit env-token-set <env>`",stderrExcerpt:"<env> was not given and there is no terminal to pick it in"});let[e,t]=await Promise.all([ir(),me()]),r=Math.max(0,...e.map(({env:s})=>s.length));y.setInteractive();let n=await N(s=>Gj({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:Wb}]},s),{output:Et.stderr,whenHeadless:"refuse"});return n!==Wb?n:(await N(s=>Vj({message:"Doppler config name",validate:i=>/^\S+$/.test(i.trim())||"Enter a config name without spaces"},s),{output:Et.stderr,whenHeadless:"refuse"})).trim()},Zj=async(e,t,r)=>N(n=>Uj({message:`Replace the "${e}" token ${De(t)} with ${De(r)}?`,default:!0},n),{output:Et.stderr,whenHeadless:"refuse"}),Qj=(e,t,r,n)=>{switch(t){case"stored":return`Stored the "${e}" service token (${De(r)})`;case"replaced":return`Replaced the "${e}" service token ${De(n??"")} \u2192 ${De(r)}`;case"unchanged":return`The "${e}" service token is already ${De(r)} \u2014 nothing to write`;case"kept":return`Kept the existing "${e}" service token ${De(n??"")} \u2014 nothing was written`;default:return Je(t)}},Mm=async({env:e,stdin:t,fromEnv:r,force:n})=>{let o=await Ke(),s=e??await Xj(),{token:i,source:a}=await Kj({stdin:t,fromEnv:r});if(!i)throw new Error("No token provided \u2014 nothing was written.");let c=await Gb(i,o,s,n),l=(await me())?.envs[s],u;l===i?u="unchanged":l!==void 0&&a==="prompt"&&!await Zj(s,l,i)?u="kept":(await ll({[s]:i}),u=l===void 0?"stored":"replaced");let p=await Xt();d.info(`${Qj(s,u,i,l)} in ${w(p)} (mode 0600).`),c||d.warn(`Scope was NOT verified (no ${Nm} in the payload) \u2014 accepted because --force was given.`);let m={env:s,status:u,source:a,redactedToken:De(i),previousRedactedToken:l===void 0?null:De(l),storePath:p,scopeVerified:c};return y.print(),{content:R(JSON.stringify(m,null,2)),structuredContent:m}},eF=e=>/^(["']).*\1$/.test(e)?e.slice(1,-1):e,Jb=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?eF(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},tF=e=>(e instanceof Error?e.message:String(e)).split(`
|
|
478
|
+
`)[0]??"",rF=(e,t)=>e===void 0?"stored":e===t?"unchanged":"replaced",nF=async(e,t,r,n)=>{let o=De(e.token);try{let s=await Gb(e.token,t,e.env,n);return{env:e.env,status:rF(r,e.token),redactedToken:o,scopeVerified:s}}catch(s){return{env:e.env,status:"failed",redactedToken:o,scopeVerified:!1,error:tF(s)}}},jm=async({fromFile:e,force:t})=>{let r=await Ke(),n=Jb(await Jj.readFile(e,"utf8")),o=await me(),s=await Promise.all(n.map(p=>nF(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 ll(i);let a=await Xt(),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&&(Et.exitCode=1);let u={storePath:a,rows:s,failedCount:l};return{content:R(JSON.stringify(u,null,2)),structuredContent:u}};var Fm=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 Fp(n);if(r&&y.addOption("--from",p),jp(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"?cc({version:o,env:s,skipTerraform:a,confirmedCommand:c}):lc({version:o,env:s,services:i,skipTerraform:a,confirmedCommand:c})},Lm=async e=>Fm(e,"all"),Bm=async e=>Fm(e,"selected"),Mc=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.`),Fm({...e,from:"local"},t,!1)};import{VENDOR_CONFIG_FILE as Hb}from"@slip-stream-kit/config/internal";import Um from"node:fs/promises";import fo from"node:path";import Kb from"node:process";import{pathToFileURL as oF}from"node:url";var qb="~/projects",Vm=async(e={})=>{if(e.init){await iF(e.cwd);return}await sF()},sF=async()=>{let e=_n(),t=await ie(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."),Kb.exitCode=1;return}let{workspaceDir:r,source:n,targets:o}=await wa(),s=Nn(r),i=await ie(s),a=fo.join(s,n),c=await ie(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=fo.join(s,u),m=await ie(p);m||(l=!1);let f=m?"[\u2713]":"[ ]",h=m?"":" (not found \u2014 clone or remove)";d.info(` ${f} ${u} ${w(p)}${h}`)}l||(Kb.exitCode=1)},iF=async e=>{let t=_n();if(await ie(t)){d.info(`Factory config already exists at ${w(t)} \u2014 leaving it untouched.`);return}let r=e??await $(),n=await aF(r);await Um.mkdir(fo.dirname(t),{recursive:!0}),await Um.writeFile(t,cF(fo.basename(r),n),"utf-8"),d.info(`\u2713 Created ${w(t)}`),n.length>0&&d.info(` Seeded ${n.length} target(s) from the source ${Hb}.`),d.info(` Edit \`workspaceDir\` (placeholder: ${qb}) to point at where your repos live.`),d.info(` \`source\` is seeded with ${fo.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.")},aF=async e=>{try{let t=fo.join(e,Hb),r=await Um.stat(t),s=(await import(`${oF(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[]},cF=(e,t)=>`${JSON.stringify({workspaceDir:qb,source:e,targets:t},null,2)}
|
|
479
|
+
`;import{existsSync as gL}from"node:fs";import hL from"node:fs/promises";import ER from"node:path";import PR from"node:process";import{z as yL}from"zod";import{chmodSync as hF,copyFileSync as yF,lstatSync as vF,mkdirSync as sR,readFileSync as oR,readdirSync as wF,readlinkSync as kF,rmSync as bF,rmdirSync as iR,symlinkSync as RF,unlinkSync as SF,writeFileSync as aR}from"node:fs";import Te from"node:path";import{lstatSync as lF,readlinkSync as Yb}from"node:fs";import uF from"node:path";var dF=new Set(["ENOENT","ENOTDIR"]),mi=e=>{let t;try{t=lF(e)}catch(r){if(dF.has(r.code??""))return null;throw r}return t.isSymbolicLink()?{kind:"link",text:Yb(e)}:t.isFile()?{kind:"file",executable:(t.mode&64)!==0,sha:uo(e)}:{kind:"other"}},zb=(e,t)=>{let r=uF.join(e,t.path),n=t.mode==="120000"?{kind:"link",text:Yb(r)}:{kind:"file",executable:t.mode==="100755",sha:uo(r)};return{...t,fingerprint:n}},Xb=(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 pF}from"zx";var Q=async(e,t,r={})=>{let{input:n,allowFailure:o=!1}=r,s=await pF({cwd:e,quiet:!0,input:n,nothrow:o})`git ${t}`;return s.exitCode===0?s.stdout:""},jc=e=>e.slice(0,7),lt=e=>e.split("\0").filter(t=>t.length>0);import mF from"node:path";var Wm=`${ae}/`,vr=`${ae}/README.md`,fi=`${ae}/${rt}`,Qb=e=>e.startsWith(Wm),Zb=e=>{let t=mF.posix.normalize(e);return t.endsWith("/")?t.slice(0,-1):t},eR=e=>{let t=Zb(e.path),r=e.target===void 0?t:Zb(e.target);return{path:t,target:r,vendored:Qb(r),module:e.module??null}},tR=e=>e.copy.map(eR),gi=(e,t)=>t.length===0?!1:e.split("/").some(r=>t.includes(r)),hi=(e,t)=>e.filter(r=>!gi(r.path,t)),Fc=(e,t)=>e===t.path?t.target:`${t.target}${e.slice(t.path.length)}`,go=e=>[...new Set(e)].sort(),rR=e=>e.startsWith(Wm)?e.slice(Wm.length):null;var Lc=e=>`# vendor/ \u2014 mirrored from ${e}
|
|
454
480
|
|
|
455
481
|
**DO NOT EDIT files in this folder here.**
|
|
456
482
|
|
|
@@ -461,19 +487,19 @@ fail \`ik vendor check\` in CI.
|
|
|
461
487
|
To change a vendored package, edit it in \`${e}\` and re-run the sync there.
|
|
462
488
|
|
|
463
489
|
See \`.sync-manifest.json\` for the source commit and per-file checksums.
|
|
464
|
-
`;var
|
|
465
|
-
`).trim()||String(e)},
|
|
466
|
-
`).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},
|
|
467
|
-
`)[0]??"git rev-parse failed"}}},
|
|
468
|
-
`).slice(0,
|
|
469
|
-
${
|
|
470
|
-
`)},
|
|
471
|
-
`),D(e)),fF=e=>e.description("List all release branches").action(async()=>{D(await Oa())}),gF=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".',pF,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(Wu),o=n.length>0?n:void 0;D(await Na({releases:o,confirmedCommand:t.yes}))}),hF=e=>{if(e==="")return e;try{return Er(e)}catch(t){throw t instanceof In?new Kb(t.message):t}},yF=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new Kb("Expected a positive whole number of days.");return t},vF=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)',hF).option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await _a({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),Hb=e=>e.option("-f, --from <where>",`Where the deploy runs: ${tr.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" deploys from the dev branch. Prompts when omitted').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-y, --yes","Skip confirmation prompt").option("--skip-terraform","With --from ci: skip the terraform deployment step").option("--dry-run","With --from local: resolve target, contract and commands without deploying").option("--print-env","With --from local: print the resolved build contract"),wF=e=>Hb(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{D(await Xp({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),kF=e=>Hb(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 Zp({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),bF=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 Ra({version:t.version,confirmedCommand:t.yes}))}),RF=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 Fa({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),SF=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{D(await ec({confirmedCommand:t.yes}))}),EF=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 za({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 Xa())}),xF=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 Qa({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),TF=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 em({init:t.init}))}),CF=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Ha();D(t),t.structuredContent.ok||(Fe.exitCode=1)}),$F=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 gm({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly})}catch(a){if(!Et(a))throw a;d.info("Operation cancelled.");return}D(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Fe.exitCode=1)}),AF=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{D(await _p())}),OF=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{D(await Mp())}),DF=new Set(["version"]),kc=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},wm=()=>{let e=new lF().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");mF(t.command("merge-dev")),fF(t.command("list")),gF(t.command("create")),vF(t.command("edit")),wF(t.command("deploy-all")),kF(t.command("deploy-selected")),bF(t.command("deliver")),RF(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");EF(r.command("add")),PF(r.command("list")),xF(r.command("remove")),SF(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");AF(n.command("path")),OF(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 Mi({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 Ll({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 jp({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 ac({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 ac({env:a.env,services:a.service,yes:a.yes,dryRun:a.dryRun,printEnv:a.printEnv},"selected"))}),e.command("audit").description("Audit against infra-kit.config.ts rules (--all for every package, --root for the monorepo root)").option("-a, --all","Audit every non-vendor workspace package").option("-r, --root","Audit the monorepo root (turbo pipeline + root commands)").option("--fix","Write the infra-kit guidance block into CLAUDE.md for the audited scope before checking (CLI-only)").option("--design","With --fix: scaffold DESIGN.md for frontend/mobile packages that lack one").action(async a=>{if(a.design&&!a.fix){d.error("--design requires --fix (it scaffolds DESIGN.md; there is nothing to scaffold without a fix run)"),Fe.exitCode=1;return}let c=await $i({all:a.all,root:a.root,fix:a.fix,design:a.design});D(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&(Fe.exitCode=1)}),e.command("deploy-run").description("Deploy a service: its deploy.ts from infra-kit.deploy.ts, else its devops/scripts .sh (what the CI deploy job runs)").argument("<service>","The service as infra-kit.deploy.ts names it, e.g. client-be").action(async a=>{D(await Vp({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||(Fe.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");CF(i.command("check")),TF(i.command("config")),$F(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 da({fix:!!a.fix});lr.enabled||Yl(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(Fe.exitCode=1),D(c)}),e.command("dev").description("Run local dev servers for an app (or every app); api + ui").argument("[app]","An app \u2014 its api/ui plus the backends its routes can run locally (omit to run every app)").option("-w, --watch","Rebuild and restart on file save (the default)").option("--no-watch","Build once and never restart on save").option("--app <names>","Further narrow to these app folder names (comma-separated)").option("--target <keys>","Run exactly these <app>/api|<app>/ui packages (comma-separated); part-level, unlike --app").option("--orca","Run each app in its own Orca pane (one tab, N panes; falls back to single terminal when Orca is not running)").option("--self","Run only the app of the current directory (infer from cwd; use inside apps/<app>/\u2026)").option("-V, --verbose","Print full boot narration (default: quiet; full detail always in the session log)").option("--routes","Print each app\u2019s registered METHOD /path routes at startup (default: off)").option("--reuse","For test runners: start nothing when this worktree already serves one of these apps, exit on a boot failure").option("--no-ui-health","Do not probe the frontends\u2019 liveness (vite\u2019s HMR ping); their rows carry no health dot (also: INFRA_KIT_NO_UI_HEALTH=1)").action(async(a,c)=>{let{runDevServerCli:l}=await import("./dev-server.js"),u=!!(Fe.stdout.isTTY&&Fe.stdin.isTTY);await l({...c,appName:a},u,lr.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{D(await ji())}),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 ga({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 Gb("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new Gb("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){D(await sp());return}D(await Wa({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 qa())}),e.command("change-stats").description("Change-failure baseline for this git repo: agent vs human commits, revert and 72h follow-up-fix rates").option("--since <days>",`Window in days, ending now (default ${So})`,yF).action(async a=>{D(await Ii({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 va())}),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 Xf())}),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=>{Jb(await Bc({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{Jb(await ya())}),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 Yp({fromFile:c.fromFile,force:c.force}));return}D(await qp({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 wa({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 Kp({env:a}))});for(let a of e.commands)tf(a);return ym(e),vm(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&dF(uF(Fe.cwd(),l)),y.start(kc(c)),lr.enabled=!!c.optsWithGlobals().json,lr.enabled&&(d.level="warn"),j.source=ti({env:Fe.env,stdinIsTTY:Fe.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),DF.has(kc(c))||await Ru()}),e.hook("postAction",(a,c)=>{let l=kc(c);if(Dp(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;Ub({equivalent:yc(f,!0)})}),e};import IF from"node:process";var NF={exit:IF.exit,emit:D,logger:d},qb=(e,t=NF)=>Oe(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof O?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));var km=(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 _F from"node:fs";import bm from"node:path";import Hn from"node:process";var Xb=new Set([...vf,Yn,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),Zb=null,bc=new Set,Rm=null,Yb=!1;var zb=e=>{try{return _F.statSync(e)}catch{return null}},MF=()=>{if(Yb)return null;try{return Br()}catch{return Yb=!0,d.debug(`session-env: ${Yn} unset \u2014 no overlay`),null}},jF=e=>{let t=bm.join(e,Fr),r=bm.join(e,Js),n=zb(t),o=zb(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Dm(bm.join(e,Ks),Hn.cwd())?{kind:"load",file:t,signature:`load:${n.ino}:${n.mtimeMs}:${n.size}`}:{kind:"none",signature:"none"}:o?{kind:"clear",file:r,signature:`clear:${o.ino}:${o.mtimeMs}`}:{kind:"none",signature:"none"}},FF=e=>e.kind==="load"?{kind:"load",vars:Am(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:Om(e.file),signature:e.signature}:e;var LF=()=>{let e=MF();if(e===null)return{kind:"no-session"};let t=jF(e);return t.signature===Rm?null:FF(t)},BF=()=>{for(let e of bc){let t=Zb[e];t===void 0?delete Hn.env[e]:Hn.env[e]=t}bc.clear()},UF=(e,t,r)=>{if(Xb.has(t)){e.skipped.push(t);return}Hn.env[t]=r,bc.add(t),e.set.push(t)},WF=(e,t)=>{if(Xb.has(t)){e.skipped.push(t);return}delete Hn.env[t],bc.add(t),e.unset.push(t)},VF=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))UF(t,r,n);if(e.kind==="clear")for(let r of e.unset)WF(t,r);return t},GF=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,Sm=(e=LF())=>{if(Zb??={...Hn.env},e===null||e.kind==="no-session"||e.signature===Rm)return{set:[],unset:[],changed:!1};BF();let{set:t,unset:r,skipped:n}=VF(e);return Rm=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(", ")}] (${GF(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as dL}from"chalk";import{spawn as pL}from"node:child_process";import Le from"node:process";import{Chalk as JF}from"chalk";var qn=new JF({level:1}),ot={ok:"ok",findingsPlain:"completed with findings",failed:"failed",cancelled:"cancelled",findingsSuffix:"findings",sep:" \xB7 ",reproPrefix:"$ ",nonReproPrefix:"\u2248 ",envNotice:"Applies to infra-kit commands in this terminal and to new shells; this zsh prompt itself needs the env-load function."},KF={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"}},Qb={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},eR={unicode:"\u2500",ascii:"-"},HF=3,Em=e=>e,qF={ok:e=>qn.green(e),findings:e=>qn.yellow(e),failed:e=>qn.red(e),cancelled:e=>qn.gray(e)},xm=e=>e?{dim:t=>qn.dim(t),bold:t=>qn.bold(t)}:{dim:Em,bold:Em},YF=(e,t)=>e?qF[t]:Em,Pm=e=>[...e].length,zF=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return Pm(e)<=r?e:[...e].slice(0,r).join("")},tR=e=>{let t=xm(e.color===!0).dim,r=KF[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(zF(n,e.width))},rR=(e,t={})=>{let r=xm(t.color===!0);return`${r.dim(ot.reproPrefix.trim())} ${r.bold(e)}`},XF=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,ZF=(e,t)=>e==="findings"?t!=null?`${t} ${ot.findingsSuffix}`:ot.findingsPlain:{ok:ot.ok,failed:ot.failed,cancelled:ot.cancelled}[e],QF=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<HF?"":` ${n(r.repeat(o))}`},nR=e=>{let t=e.color===!0,r=xm(t),n=YF(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?ot.reproPrefix:ot.nonReproPrefix,i=o?Qb[e.outcome].ascii:Qb[e.outcome].unicode,a=ZF(e.outcome,e.findingsCount),c=[XF(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
472
|
-
`)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${
|
|
473
|
-
`)};var
|
|
474
|
-
`,
|
|
490
|
+
`;var fF=new Set(["100644","100755","120000"]),gF=(e,t)=>{let r=new Map;for(let n of lt(e)){let o=n.indexOf(" "),s=n.slice(0,n.indexOf(" ")),i=n.slice(o+1);o<0||!fF.has(s)||gi(i,t)||r.set(i,{path:i,mode:s})}return[...r.values()]},Gm=async(e,t,r)=>{let n=await Q(e,["--literal-pathspecs","ls-files","-z","-s","--",t]);return gF(n,r)},nR=async e=>lt(await Q(e,["--literal-pathspecs","ls-files","-z","--",ae]));var ho=e=>["git","-C",e.root,"--literal-pathspecs","checkout","HEAD","--",...e.recoveryPaths],cR=e=>{let t=mi(e);t!==null&&(t.kind==="other"?iR(e):SF(e))},EF=(e,t,r)=>{let n=Te.join(e,r.source),o=Te.join(t,r.target);sR(Te.dirname(o),{recursive:!0});let s=mi(o)?.kind==="file"?ab(oR(o)):null;if(cR(o),r.mode==="120000"){RF(kF(n),o);return}s===null?yF(n,o):aR(o,lb(oR(n),s)),hF(o,r.mode==="100755"?493:420)},PF=async(e,t)=>{let r=new Set;for(let n of lt(await Q(e,["ls-files","-z"]))){if(t.has(n))continue;let o=Te.posix.dirname(n);for(;o!==".";)r.add(o),o=Te.posix.dirname(o)}return r},xF=async(e,t)=>{if(t.length===0)return;let r=await PF(e,new Set(t)),n=[...new Set(t.map(o=>Te.dirname(Te.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)&&!(!vF(s,{throwIfNoEntry:!1})?.isDirectory()||wF(s).length>0||r.has(Te.relative(e,s).split(Te.sep).join("/")));)iR(s),s=Te.dirname(s)}},lR=(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,vr,...s].map(rR).filter(a=>a!==null&&!wc(a));return go(i)},uR=async(e,t,r,n)=>{let o=Te.join(e,ae);sR(o,{recursive:!0}),aR(Te.join(e,vr),Lc(t.name));let s=lR(r,await nR(e),n);am(o,{source:t.name,commit:t.headSha},s)},Jm=async({source:e,plan:t,onBeforeFirstWrite:r})=>{if(t.status!=="changed")return{touched:[],manifestWritten:!1};r?.(ho(t));let n=Te.resolve(t.root),o=t.entries.flatMap(a=>a.deletes);for(let a of o)cR(Te.join(n,a));await xF(n,o);for(let a of t.entries)a.pruned&&a.deletes.length>0&&bF(Te.join(n,a.target),{recursive:!0,force:!0});let s=t.entries.flatMap(a=>a.writes);for(let a of s)EF(e.root,n,a);let i=s.map(a=>a.target);return t.writeVendorMeta?(await uR(n,e,t.entries,o),{touched:go([...o,...i,vr,fi]),manifestWritten:!0}):{touched:go([...o,...i]),manifestWritten:!1}},Km=async(e,t)=>(await uR(e,t,[],[]),[vr,fi]);var Hm=(e,t)=>`[ROOT] vendor: sync from ${e}@${jc(t)}`,TF=e=>{let{stdout:t,stderr:r}=e;return[t,r].filter(o=>typeof o=="string"&&o.trim().length>0).join(`
|
|
491
|
+
`).trim()||String(e)},qm=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 Q(e,["--literal-pathspecs","add","-A",...o],{input:n}),await Q(e,["--literal-pathspecs","commit","--only","-m",r,...o],{input:n}),{ok:!0}}catch(s){return{ok:!1,output:TF(s)}}};var dR=20,CF=20,zm=(e,t)=>e.length<=t?[...e]:[...e.slice(0,t),`\u2026and ${e.length-t} more`],Ym=(e,t,r)=>{let{entry:n}=e,o=new Set(t.tracked),s=[],i=[];for(let u of hi(e.files,r)){let p=Fc(u.path,n);if(s.push(p),Xb(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=hi(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}},zr=(e,t,r,n=[])=>({name:e.name,root:e.root,status:t,message:r,notes:n,warnings:[],entries:[],writeVendorMeta:!1,recoveryPaths:[]}),Xm=(e,t)=>e.entries.filter((r,n)=>t[n]!=="release").map(r=>r.entry.target),$F=(e,t,r,n)=>{let o=["git","-C",t.root,"--literal-pathspecs","status","--",...Xm(e,r)];return zr(t,"fail",`blocked: ${n.length} uncommitted path(s) under synced paths`,[...zm(n,dR),Ge(o)])},AF=(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=jc(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}`,...zm(e.lines,CF)],warnings:[]}},OF=e=>{let{added:t,modified:r,removed:n}=e.counts;return t+r+n===0?null:`${e.target}: ${t} added, ${r} modified, ${n} removed`},DF=e=>{let t=r=>e.reduce((n,o)=>n+o.counts[r],0);return`${t("added")} added, ${t("modified")} modified, ${t("removed")} removed`},IF=(e,t,r)=>{let n=e.flatMap(o=>[...o.writes.filter(i=>i.change==="modified").map(i=>i.target),...o.deletes]);return go([...n,...r?t.headVendorMeta:[]])},_F=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`),NF=(e,t)=>{let r=t.entries.map(f=>f.scope);if(t.dirty.length>0)return $F(e,t,r,t.dirty);if(t.pruneConflicts.length>0)return zr(t,"fail","blocked: a module this repo dropped is still a dependency",[...zm(t.pruneConflicts,dR)]);let n=e.entries.flatMap((f,h)=>{let b=t.entries[h]??{target:f.entry.target,scope:"sync",tracked:[],onDisk:{}};return b.scope==="release"?[]:b.scope==="sync"?[Ym(f,b,e.exclude)]:[{...Ym({...f,files:[]},b,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={...zr(t,"ok","up to date"),branch:t.branch,entries:n,writeVendorMeta:o};if(!s&&!i)return a;let c=AF(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(OF).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:`${DF(n)} on ${t.branch}`,notes:[...u,...m,..._F(t),...i?["vendor/README.md and manifest rewritten"]:[],...c.notes],warnings:[...l,...c.warnings],recoveryPaths:IF(n,t,o)}},Bc=(e,t)=>{switch(t.kind){case"missing":return zr(t,"skipped",`not checked out at ${t.root}`);case"source":return zr(t,"skipped","this is the source repo");case"not-git":return zr(t,"fail",`not a git repo: ${t.reason}`);case"bad-selection":return zr(t,"fail",`vendorTarget: ${t.reason}`);case"repo":return NF(e,t)}};import{existsSync as WF,readFileSync as GF,realpathSync as Uc}from"node:fs";import Vc from"node:path";import{readFileSync as pR}from"node:fs";import yo from"node:path";var MF=["dependencies","devDependencies","peerDependencies","optionalDependencies"],jF=e=>{let t=e.flatMap(({entry:r})=>r.module===null?[]:[r.module]);return[...new Set(t)].sort()},mR=(e,t)=>{if(t.kind==="invalid")return{reason:t.reason};let r=jF(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")},fR=e=>{try{return JSON.parse(pR(e,"utf8"))}catch{return null}},FF=(e,t)=>t.files.flatMap(r=>{let n=yo.posix.relative(t.entry.path,r.path);if(yo.posix.basename(n)!=="package.json"||n.split("/").length>2)return[];let o=fR(yo.join(e,r.path))?.name;return typeof o=="string"?[o]:[]}),LF=e=>MF.flatMap(t=>{let r=e[t];return r!==null&&typeof r=="object"?Object.keys(r):[]}),gR=(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},BF=["*.sh","*.yml","*.yaml"],UF=(e,t,r)=>{let n=LF(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"&&gR(i,r)&&n.push(`${e} script "${s}" runs ${r}`);return n},VF=async(e,t,r)=>{let n=["grep","-z","-l","-F","-e",t,"--",...BF];return lt(await Q(e,n,{allowFailure:!0})).filter(s=>r(s)&&gR(pR(yo.join(e,s),"utf8"),t)).map(s=>`${s} uses ${t}`)},hR=async(e,t,r)=>{let n=new Map;for(let{facts:c}of r)for(let l of FF(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=lt(await Q(t,["ls-files","-z","--","*package.json"])).filter(c=>yo.posix.basename(c)==="package.json"&&s(c)),a=[];for(let[c,l]of n){let u=i.flatMap(p=>{let m=fR(yo.join(t,p));return m===null?[]:UF(p,m,c)});u.push(...await VF(t,c,s));for(let p of u)a.push(`${p}: add "${l}" to vendorTarget.modules or stop using it`)}return a.sort()};var Zm=async(e,t)=>{let r=t.exclude??[],n=(await Q(e,["rev-parse","HEAD"])).trim(),o=await Ie(e),s=await Promise.all(tR(t).map(async i=>{let a=await Gm(e,i.path,r);return{entry:i,files:a.map(c=>zb(e,c))}}));return{root:e,selfRoots:[...new Set([Uc(e),Uc(o)])],name:Vc.basename(o),headSha:n,entries:s,exclude:r}},Wc=e=>{let t=lt(e)[Symbol.iterator](),r=[];for(let n of t)r.push(n.slice(3)),/^[RC]|^.[RC]/u.test(n)&&t.next();return r},JF=async(e,t,r)=>{let n=Xm(e,t);if(n.length===0)return[];let o=await Q(r,["--literal-pathspecs","status","--porcelain","-z","--untracked-files=all","--",...n]);return Wc(o).filter(s=>!gi(s,e.exclude))},KF=async(e,t,r)=>Promise.all(e.entries.map(async({entry:n,files:o},s)=>{let i=t[s],a=await Gm(r,n.target,e.exclude),c={},l=i==="sync"?o:[];for(let u of hi(l,e.exclude)){let p=Fc(u.path,n);c[p]=mi(Vc.join(r,p))}return{target:n.target,scope:i,tracked:a.map(u=>u.path),onDisk:c}})),HF=async e=>{try{return lt(await Q(e,["--literal-pathspecs","ls-tree","-z","--name-only","HEAD","--",vr,fi]))}catch{return[]}},qF=e=>{try{let{commit:t,source:r}=ii(Vc.join(e,ae));return{commit:t,source:r}}catch{return null}},YF=async(e,t,r)=>{if(r===null)return{kind:"unknown-sha"};if(await $e(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 Q(e.root,["--literal-pathspecs","log","--oneline",`${r}..HEAD`,"--",...n])).split(`
|
|
492
|
+
`).filter(i=>i.length>0);return{kind:"log",sha:r,lines:s}},zF=(e,t)=>{try{return GF(Vc.join(e,vr),"utf8")===Lc(t)}catch{return!1}},XF=async e=>{try{return{toplevel:(await Q(e,["rev-parse","--show-toplevel"])).trim()}}catch(t){return{reason:String(t.stderr??t).trim().split(`
|
|
493
|
+
`)[0]??"git rev-parse failed"}}},ZF=async e=>{try{return(await Q(e,["rev-parse","--abbrev-ref","HEAD"])).trim()}catch{return"HEAD"}},Gc=async(e,t)=>{if(!WF(t.root))return{...t,kind:"missing"};let r=Uc(t.root);if(e.selfRoots.includes(r))return{...t,kind:"source"};let n=await XF(t.root);if("reason"in n)return{...t,kind:"not-git",reason:n.reason};if(Uc(n.toplevel)!==r)return{...t,kind:"not-git",reason:`it sits inside the repo at ${n.toplevel}`};let o=mR(e.entries,t.selection??{kind:"all"});if("reason"in o)return{...t,kind:"bad-selection",reason:o.reason};let s=qF(t.root),i=s?.commit??null,[a,c,l,u,p]=await Promise.all([ZF(t.root),JF(e,o,t.root),KF(e,o,t.root),HF(t.root),YF(e,o,i)]),m=l.flatMap((f,h)=>f.scope==="prune"&&f.tracked.length>0?[{facts:e.entries[h],target:f.target}]:[]);return{...t,kind:"repo",branch:a,dirty:c,entries:l,headVendorMeta:u,readmeCurrent:zF(t.root,e.name),manifestPresent:s!==null,manifestSource:s?.source??null,changelog:p,pruneConflicts:await hR(e.root,t.root,m)}};var QF=20,eL=(e,t)=>!t.commit||e.status!=="changed"||e.branch===void 0?e.notes:[...e.notes,`--commit lands on ${e.branch}`],tL=(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:",Ge(ho(r))]};let o=e.applied?`wrote ${r.message}`:r.message;return{name:n,status:r.status,message:o,notes:t.mode==="applied"?r.notes:eL(r,t)}},rL=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(`
|
|
494
|
+
`).slice(0,QF)},nL=(e,t)=>{let r=e.plan.warnings.map(n=>({name:"changelog",status:"warn",message:n}));return{label:e.plan.name,rows:[tL(e,t),...r,...e.commit?[rL(e.commit)]:[]]}},oL={preview:"infra-kit vendor sync (preview)",check:"infra-kit vendor sync --check",applied:"infra-kit vendor sync"},Qm=(e,t,r)=>{let n=r.mode==="preview"?["re-run with --yes from a real terminal to apply"]:[];return{title:oL[r.mode],sections:[{label:"source",rows:[...e]},...t.map(o=>nL(o,r))],hints:n}},yR=e=>e.sections.some(t=>t.rows.some(r=>r.status==="fail")),vR=(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 sL=20,ef=async(e,t)=>(await Q(e,t,{allowFailure:!0})).trim(),iL=async e=>Wc(await Q(e,["status","--porcelain","-z","--untracked-files=normal"])),aL=async e=>(await ef(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"]},cL=async e=>{let[t,r]=await Promise.all([ef(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]),ef(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}`}},wR=async e=>{let t=await iL(e);if(t.length>0){let n=t.slice(0,sL),o=t.length>n.length?`, and ${t.length-n.length} more`:"";throw new A({status:"refused",reason:"source-dirty",paths:t},1,{operation:`sync vendored files from ${e}`,stderrExcerpt:`the source has ${t.length} uncommitted path(s)`,remediation:`commit or stash them first, so every target records a commit holding exactly the files it got: ${n.join(", ")}${o}`})}let r=await Promise.all([aL(e),cL(e)]);return[{name:"working tree",status:"ok",message:"clean"},...r.filter(n=>n!==null)]};import pL from"node:path";import{readFileSync as lL}from"node:fs";import uL from"node:path";import{z as dL}from"zod";var kR=e=>{let t;try{t=lL(uL.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=lg.safeParse(r);return n.success?{kind:"modules",modules:n.data.modules}:{kind:"invalid",reason:dL.prettifyError(n.error)}};var bR=(e,t)=>{let r=t.filter(s=>!e.targets.includes(s));if(r.length>0)throw new A({status:"refused",reason:"unknown-target",unknown:r,valid:e.targets},2,{operation:`sync vendored files to ${r.join(", ")}`,stderrExcerpt:`not a target in ~/.infra-kit/vendor.json: ${r.join(", ")}`,remediation:`name one of: ${e.targets.join(", ")}`});let n=Nn(e.workspaceDir);return(t.length>0?e.targets.filter(s=>t.includes(s)):e.targets).map(s=>{let i=pL.join(n,s);return{name:s,root:i,selection:kR(i)}})},mL="rewrite vendor/README.md and vendor/.sync-manifest.json from the tracked vendor/ files",fL=async(e,t)=>{let r=await Gc(e,t),n=Bc(e,r);return r.kind!=="repo"||n.status==="fail"?n:{...n,status:"changed",message:`${mL} on ${r.branch}`,notes:[],warnings:[],branch:r.branch,entries:[],writeVendorMeta:!0,recoveryPaths:r.headVendorMeta}},RR=async(e,t,r)=>Promise.all(t.map(async n=>r?fL(e,n):Bc(e,await Gc(e,n))));var xR="sync vendored files",vL=e=>{let t=ER.join(Nn(e.workspaceDir),e.source);if(gL(t))return t;throw new A({status:"refused",reason:"source-missing",source:t},1,{operation:xR,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'})},tf=(e,t)=>new A({status:"refused",reason:"not-a-vendor-source"},1,{operation:xR,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`}),wL=async e=>{let t=ER.join(e,"infra-kit.json"),r;try{r=JSON.parse(await hL.readFile(t,"utf8"))}catch(s){throw tf(t,`is unreadable: ${s instanceof Error?s.message:String(s)}`)}let n=r?.vendorSource;if(n==null)throw tf(t,"has no vendorSource block");let o=cg.safeParse(n);if(!o.success)throw tf(t,`has an invalid vendorSource: ${yL.prettifyError(o.error)}`);return o.data},SR=(e,t)=>{PR.stderr.write(`${e.name}: if this run dies, restore the tracked paths with:
|
|
495
|
+
${Ge(t)}
|
|
496
|
+
`)},kL=async(e,t,r)=>r?(SR(t,ho(t)),Km(t.root,e)):(await Jm({source:e,plan:t,onBeforeFirstWrite:o=>{SR(t,o)}})).touched,bL=async(e,t,r)=>{if(t.status!=="changed")return{plan:t,applied:!1};let n;try{n=await kL(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 qm(t.root,n,Hm(e.name,e.headSha));return{plan:t,applied:!0,commit:o}},RL=async(e,t,r)=>{let n=[];for(let o of t)n.push(await bL(e,o,r));return n},TR=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})),rf=({mode:e,report:t,outcomes:r,source:n,print:o})=>{o&&yt(t);let s=r.map(a=>a.plan);return{structuredContent:{mode:e,source:{root:n.root,name:n.name,headSha:n.headSha},targets:TR(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:yR(t),report:t.sections}}},SL=async e=>{let t=await wa(),r=vL(t),n=await wR(r),o=await wL(r),s=bR(t,e.targets??[]),i=await Zm(r,o),a=await RR(i,s,!!e.manifestOnly);return{source:i,sourceRows:n,plans:a}},nf=async(e={})=>{let{source:t,sourceRows:r,plans:n}=await SL(e),o=n.map(m=>({plan:m,applied:!1})),s={commit:e.commit,manifestOnly:e.manifestOnly},i=e.check?"check":"preview",a=Qm(r,o,{...s,mode:i}),c=!n.some(m=>m.status==="changed");if(e.check||c)return rf({mode:i,report:a,outcomes:o,source:t,print:!0});let l=!e.confirmedCommand&&!H();if(l&&!PR.stdin.isTTY)return yt(a),rf({mode:"preview",report:a,outcomes:o,source:t,print:!1});l&&yt({...a,hints:[]}),await q(e.confirmedCommand,`Sync vendored files from ${t.name} into these targets?`,{plan:TR(n)});let u=await RL(t,n,e),p=Qm(r,u,{...s,mode:"applied"});if(l){let m=u.filter(f=>f.applied).map(f=>f.plan.name);yt(vR(a,p,m))}return rf({mode:"applied",report:p,outcomes:u,source:t,print:!l})};var Jc=(e,t=!0)=>({line:e,reproducible:t});import Kc from"node:fs";import EL from"node:os";import PL from"node:path";import OR from"node:process";var Hc="INFRA_KIT_SESSION_REPORT",of=null,CR=!1,$R=[],DR=(e=OR.env)=>{CR||(of=e[Hc]??null,CR=!0,delete e[Hc])};var IR=(e,t)=>{if(!of)return;let r=e.summary??($R.length>0?[...$R]:void 0),n={...e,...r?{summary:r}:{}},o=t?.write??((s,i)=>{Kc.writeFileSync(s,i)});try{o(of,JSON.stringify(n))}catch{}},AR=0,_R=e=>{let t=e?.tmpdir?.()??EL.tmpdir(),r=e?.pid??OR.pid;return AR+=1,PL.join(t,`infra-kit-session-${r}-${AR}.json`)},NR=(e,t)=>{if(!(t?.exists??(i=>Kc.existsSync(i)))(e))return null;let n=t?.read??(i=>Kc.readFileSync(i,"utf-8")),o=t?.unlink??(i=>Kc.unlinkSync(i)),s;try{s=n(e)}catch{return null}finally{try{o(e)}catch{}}try{return JSON.parse(s)}catch{return null}};var sf=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)sf(r)};var af=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)af(r)};var $L=(e,t)=>[...t,e],AL=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 aw(()=>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}));I(r),r.structuredContent.failedMerges>0&&(Ue.exitCode=1)}),jR=e=>(Ue.stdout.write(`${e.structuredContent.filePath}
|
|
497
|
+
`),I(e)),OL=e=>e.description("List all release branches").action(async()=>{I(await Za())}),DL=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".',$L,[]).option("-y, --yes","Skip confirmation prompt").action(async t=>{let n=t.release.map(sd),o=n.length>0?n:void 0;I(await ac({releases:o,confirmedCommand:t.yes}))}),IL=e=>{if(e==="")return e;try{return _r(e)}catch(t){throw t instanceof Hn?new FR(t.message):t}},_L=e=>{let t=Number(e);if(!Number.isInteger(t)||t<=0)throw new FR("Expected a positive whole number of days.");return t},NL=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)',IL).option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await uc({version:t.version,description:t.description,releaseDate:t.releaseDate,confirmedCommand:t.yes}))}),LR=e=>e.option("-f, --from <where>",`Where the deploy runs: ${mr.join(" | ")} (required)`).option("-v, --version <version>",'With --from ci: version (e.g. 1.2.5) or release name to deploy; "dev" ("main" with gitFlow main) deploys from that 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"),ML=e=>LR(e).description("Deploy every service to any environment, in CI or from this machine").action(async t=>{I(await Lm({from:t.from,version:t.version,env:t.env,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),jL=e=>LR(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=>{I(await Bm({from:t.from,version:t.version,env:t.env,services:t.services,skipTerraform:t.skipTerraform,yes:t.yes,dryRun:t.dryRun,printEnv:t.printEnv}))}),FL=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=>{I(await Xa({version:t.version,confirmedCommand:t.yes}))}),LL=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=>{I(await mc({version:t.version,moveIssuesTo:t.moveIssuesTo,skipJira:t.skipJira,confirmedCommand:t.yes}))}),BL=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async t=>{I(await $c({confirmedCommand:t.yes}))}),UL=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=>{I(await Pc({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,base:t.base,githubDesktop:t.githubDesktop,orca:t.orca}))}),VL=e=>e.description("List all git worktrees with detailed information").action(async()=>{I(await xc())}),WL=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=>{I(await Cc({confirmedCommand:t.yes,all:t.all,versions:t.versions,feature:t.feature,self:t.self}))}),GL=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=>{I(await Vm({init:t.init}))}),JL=e=>e.description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let t=await Sc();I(t),t.structuredContent.ok||(Ue.exitCode=1)}),KL=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=await nf({targets:t,confirmedCommand:r.yes,check:r.check,commit:r.commit,manifestOnly:r.manifestOnly});I(n);let{failed:o,changed:s,mode:i}=n.structuredContent;(o||i==="check"&&s)&&(Ue.exitCode=1)}),HL=e=>e.description("Show the resolved config merge chain and file paths").action(async()=>{I(await Rm())}),qL=e=>e.description("Open the user-scope per-project override file in $EDITOR").action(async()=>{I(await Sm())}),YL=new Set(["version"]),yi=e=>{let t=[];for(let r=e;r&&r.parent;r=r.parent)t.unshift(r.name());return t.join(" ")},cf=()=>{let e=new xL().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");AL(t.command("merge-dev")),OL(t.command("list")),DL(t.command("create")),NL(t.command("edit")),ML(t.command("deploy-all")),jL(t.command("deploy-selected")),FL(t.command("deliver")),LL(t.command("remove"));let r=e.command("worktrees").description("Git worktree management commands");UL(r.command("add")),VL(r.command("list")),WL(r.command("remove")),BL(r.command("sync"));let n=e.command("config").description("Manage infra-kit configuration files");HL(n.command("path")),qL(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=>{I(await sa({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)=>{I(await Em({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)=>{I(await Pm({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=>{I(await Mc({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=>{I(await Mc({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)"),Ue.exitCode=1;return}let c=await ea({all:a.all,root:a.root,fix:a.fix,design:a.design});I(c);let{allPassed:l,fixed:u}=c.structuredContent,p=(u??[]).some(m=>m.action==="failed");(!l||p)&&(Ue.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=>{I(await Om({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 Im({check:a.check});I(c),c.structuredContent.ok||(Ue.exitCode=1)});let i=e.command("vendor").description("Mirror and verify the vendored starter files");JL(i.command("check")),GL(i.command("config")),KL(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 Ta({fix:!!a.fix,catalog:Yr});Ht.enabled||Eu(c.structuredContent.checks,{ascii:!!a.ascii}),c.structuredContent.checks.some(u=>u.name==="plugin installed"&&u.status==="fail")&&(Ue.exitCode=1),I(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=!!(Ue.stdout.isTTY&&Ue.stdin.isTTY);await l({...c,appName:a},u,Ht.enabled)}),e.command("dev-status").description("Show what `infra-kit dev` currently has running (reads dev-context fragments; starts nothing)").action(async()=>{I(await ia())}),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)=>{I(await Oa({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 MR("--unattended","Background run: no tool installs, no writes to git-tracked files").hideHelp()).addOption(new MR("--auto","Unattended setup for the machine and every infra-kit project, once per version").hideHelp()).action(async a=>{if(a.auto){I(await qp());return}I(await yc({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()=>{I(await Ec())}),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 ${Go})`,_L).action(async a=>{I(await oa({since:a.since}))}),e.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{I(await Ma())}),e.command("env-list").description("List available Doppler configs for the detected project, and whether a service token resolves for each").action(async()=>{I(await _a())}),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=>{jR(await Na({config:a.config}))}),e.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{jR(await Ia())}),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.");I(await jm({fromFile:c.fromFile,force:c.force}));return}I(await Mm({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=>{I(await ja({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=>{I(await _m({env:a}))});for(let a of e.commands)Jf(a);return sf(e),af(e),e.hook("preAction",async(a,c)=>{let{C:l}=e.opts();l!==void 0&&CL(TL(Ue.cwd(),l)),y.start(yi(c)),Ht.enabled=!!c.optsWithGlobals().json,Ht.command=yi(c),Ht.enabled&&(d.level="warn"),_.source=Ti({env:Ue.env,stdinIsTTY:Ue.stdin.isTTY===!0,flag:!!c.optsWithGlobals().agent}),YL.has(yi(c))||await ju()}),e.hook("postAction",(a,c)=>{let l=yi(c);if(bm(l))return;let p=y.snapshot()?.formattedOptions??"",m=p?` ${p}`:"",f=`infra-kit ${l}${m}`;IR({equivalent:Jc(f,!0)})}),e};import zL from"node:process";var XL={exit:zL.exit,emit:I,logger:d},BR=(e,t=XL)=>_e(e)||Ee(e)?(t.logger.info("Operation cancelled."),t.exit(0)):e instanceof A?(t.emit({structuredContent:e.structuredContent}),t.logger.error(e.message),t.exit(e.exitCode)):(t.logger.error(e instanceof Error?e.message:String(e)),t.exit(1));import lf from"node:process";var ZL="MODULE_TYPELESS_PACKAGE_JSON",QL=(e,t)=>typeof e=="object"&&e!==null?e.code:t,UR=!1,uf=()=>{if(UR)return;UR=!0;let e=lf.emitWarning.bind(lf);lf.emitWarning=((t,...r)=>{QL(r[0],r[1])!==ZL&&e(t,...r)})};var df=(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 e0 from"node:fs";import pf from"node:path";import vo from"node:process";var GR=new Set([...ag,dt,"XDG_CACHE_HOME","CLAUDE_PROJECT_DIR","CLAUDE_PLUGIN_ROOT"]),JR=null,qc=new Set,mf=null,VR=!1;var WR=e=>{try{return e0.statSync(e)}catch{return null}},t0=()=>{if(VR)return null;try{return Kt()}catch{return VR=!0,d.debug(`session-env: ${dt} unset \u2014 no overlay`),null}},r0=e=>{let t=pf.join(e,Gt),r=pf.join(e,ki),n=WR(t),o=WR(r);return n&&!(o&&o.mtimeMs>n.mtimeMs)?Rf(pf.join(e,Xr),vo.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"}},n0=e=>e.kind==="load"?{kind:"load",vars:kf(e.file),signature:e.signature}:e.kind==="clear"?{kind:"clear",unset:bf(e.file),signature:e.signature}:e;var o0=()=>{let e=t0();if(e===null)return{kind:"no-session"};let t=r0(e);return t.signature===mf?null:n0(t)},s0=()=>{for(let e of qc){let t=JR[e];t===void 0?delete vo.env[e]:vo.env[e]=t}qc.clear()},i0=(e,t,r)=>{if(GR.has(t)){e.skipped.push(t);return}vo.env[t]=r,qc.add(t),e.set.push(t)},a0=(e,t)=>{if(GR.has(t)){e.skipped.push(t);return}delete vo.env[t],qc.add(t),e.unset.push(t)},c0=e=>{let t={set:[],unset:[],skipped:[]};if(e.kind==="load")for(let[r,n]of Object.entries(e.vars))i0(t,r,n);if(e.kind==="clear")for(let r of e.unset)a0(t,r);return t},l0=e=>e.kind==="load"?`load, ${Object.keys(e.vars).length} vars`:e.kind,ff=(e=o0())=>{if(JR??={...vo.env},e===null||e.kind==="no-session"||e.signature===mf)return{set:[],unset:[],changed:!1};s0();let{set:t,unset:r,skipped:n}=c0(e);return mf=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(", ")}] (${l0(e)})`),{set:t,unset:r,changed:!0}};import{chalkStderr as A0}from"chalk";import{spawn as O0}from"node:child_process";import Ve from"node:process";import{Chalk as u0}from"chalk";var wo=new u0({level:1}),ut={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."},d0={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"}},KR={ok:{unicode:"\u2713",ascii:"[ok]"},findings:{unicode:"\u26A0",ascii:"[!]"},failed:{unicode:"\u2717",ascii:"[x]"},cancelled:{unicode:"\u2298",ascii:"[-]"}},HR={unicode:"\u2500",ascii:"-"},p0=3,gf=e=>e,m0={ok:e=>wo.green(e),findings:e=>wo.yellow(e),failed:e=>wo.red(e),cancelled:e=>wo.gray(e)},yf=e=>e?{dim:t=>wo.dim(t),bold:t=>wo.bold(t)}:{dim:gf,bold:gf},f0=(e,t)=>e?m0[t]:gf,hf=e=>[...e].length,g0=(e,t)=>{if(t==null)return e;let r=Math.max(0,t-1);return hf(e)<=r?e:[...e].slice(0,r).join("")},qR=e=>{let t=yf(e.color===!0).dim,r=d0[e.canSuspend?"suspend":"plain"],n=e.ascii===!0?r.ascii:r.unicode;return t(g0(n,e.width))},YR=(e,t={})=>{let r=yf(t.color===!0);return`${r.dim(ut.reproPrefix.trim())} ${r.bold(e)}`},h0=e=>e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`,y0=(e,t)=>e==="findings"?t!=null?`${t} ${ut.findingsSuffix}`:ut.findingsPlain:{ok:ut.ok,failed:ut.failed,cancelled:ut.cancelled}[e],v0=(e,t,r,n)=>{if(t==null)return"";let o=t-2-e;return o<p0?"":` ${n(r.repeat(o))}`},zR=e=>{let t=e.color===!0,r=yf(t),n=f0(t,e.outcome),o=e.ascii===!0,s=e.equivalent.reproducible?ut.reproPrefix:ut.nonReproPrefix,i=o?KR[e.outcome].ascii:KR[e.outcome].unicode,a=y0(e.outcome,e.findingsCount),c=[h0(e.durationMs)],l=e.summary?.[0]?.split(`
|
|
498
|
+
`)[0];l!=null&&l.length>0&&c.push(l);let u=`${i} ${a}`,p=`${ut.sep}${c.join(ut.sep)}`,m=hf(u)+hf(p),f=v0(m,e.width,o?HR.ascii:HR.unicode,r.dim),h=[`${n(u)}${r.dim(p)}${f}`];return e.showEquivalent!==!1&&h.unshift(`${r.dim(s.trim())} ${r.bold(e.equivalent.line)}`),e.envNotice===!0&&h.push(r.dim(ut.envNotice)),h.join(`
|
|
499
|
+
`)};var w0=new Set([130,143]),XR=(e,t,r,n=!1)=>r?t!=null||e===0?"ok":"findings":n&&e!=null&&w0.has(e)||t==="SIGINT"||e===0?"cancelled":"failed";import k0 from"node:process";var b0={3:"quit",4:"quit",26:"suspend",27:"quit"},R0=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":b0[t]??"continue"},S0=150,E0="\r\x1B[2K",P0=`\r
|
|
500
|
+
`,ZR=(e,t)=>{QR(e),e.stdin.on("data",t),e.listener=t},QR=e=>{e.listener!==null&&(e.stdin.off("data",e.listener),e.listener=null)},eS=(e,t)=>{$g(),e.stdin.setRawMode(!0),e.stdin.isPaused()&&e.stdin.resume(),ZR(e,t)},tS=e=>{e.hintOnScreen&&(e.hintOnScreen=!1,e.deps.write(E0)),QR(e),e.stdin.isTTY===!0&&e.stdin.isRaw===!0&&e.stdin.setRawMode(!1),Ag()},x0=e=>{e.settled||(e.settled=!0,tS(e))},rS=(e,t)=>{let r=qR({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},T0=async e=>{await new Promise(t=>{setTimeout(t,e)})},C0=(e,t,r)=>{tS(e),t(),eS(e,r),rS(e,P0)},$0=async e=>new Promise(t=>{let r=n=>{let o=R0(n),s=e.deps.suspend;if(o==="quit"){t("quit");return}if(o==="suspend"&&s!==void 0){C0(e,s,r);return}t("palette")};ZR(e,r),rS(e,"")}),nS=async(e,t)=>{if(e.quitRequested())return"quit";let r=t.stdin??k0.stdin;if(r.isTTY!==!0)return"palette";let n={deps:t,stdin:r,listener:null,hintOnScreen:!1,settled:!1};try{return eS(n,()=>{}),e.armed(),await T0(t.drainMs??S0),await $0(n)}finally{x0(n)}};import oS from"node:process";var wr={column:"\r",sgr:"\x1B[0m",cursor:"\x1B[?25h",wrap:"\x1B[?7h",saveCursor:"\x1B7",restoreCursor:"\x1B8",scrollRegion:"\x1B[r",primaryBuffer:"\x1B[?1049l"},sS=(e,t)=>{let r=t?.write??(s=>{oS.stderr.write(s)}),n=t?.stdin??oS.stdin,o=[wr.saveCursor,wr.scrollRegion,wr.restoreCursor,wr.column,wr.sgr,wr.cursor,wr.wrap];e.entersAltScreen===!0&&o.push(wr.primaryBuffer),r(o.join("")),n.isTTY===!0&&n.isRaw===!0&&n.setRawMode?.(!1)};var iS=e=>`infra-kit ${e.groupPath.join(" ")}`,D0=()=>{I0();let e=Ve.stderr.columns;return e!=null&&e>0?e:void 0},I0=()=>{let e=Ve.stderr;typeof e._refreshSize=="function"&&e._refreshSize()},_0=e=>new Promise(t=>{e.on("exit",(r,n)=>{t({code:r,signal:n})}),e.on("error",()=>{t({code:1,signal:null})})}),N0=async(e,t,r)=>{let n=_R(),o={...t.env,[Hc]:n,INFRA_KIT_NO_AUTO_UPDATE:"1"},s=t.now(),i={code:1,signal:null};r();try{let p=t.spawn(Ve.execPath,[t.cliPath,...e.groupPath],{stdio:"inherit",env:o});i=await _0(p)}catch{i={code:1,signal:null}}finally{t.resetTerminal({entersAltScreen:e.entersAltScreen})}let a=NR(n),c=XR(i.code,i.signal,a!=null,e.longRunning),l=iS(e),u=a?.equivalent??Jc(l,!0);return zR({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)})},M0=1e3,j0=(e,t)=>e!=null&&t-e<=M0,vf=e=>{e.resetTerminal(),e.exit(0)},F0=(e,t)=>{let r=null,n=!1,o=()=>{let c=e();if(c==="child"){r=t.now();return}c!=="pause"&&vf(t)},s=()=>{let c=e();if(c==="palette"){vf(t);return}if(!j0(r,t.now())){if(c==="pause"){vf(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}},aS=(e,t)=>!!(t.stdoutIsTTY&&t.stdinIsTTY&&t.stderrIsTTY&&e.TERM!=="dumb"&&!e.INFRA_KIT_NO_SESSION&&!e.INFRA_KIT_SESSION_REPORT),L0=Ve.platform==="win32"?void 0:()=>{Ig()},B0=(e,t)=>r=>nS(r,{write:e,columns:t.columns,ascii:t.ascii,color:t.color,suspend:L0}),cS=async(e,t)=>{let r={spawn:t.spawn??O0,now:t.now??(()=>Date.now()),env:t.env??Ve.env,cliPath:t.cliPath,ascii:t.ascii??!(Ve.stdout.isTTY&&Ve.env.TERM!=="dumb"),color:t.color??A0.level>0,columns:t.columns??D0,resetTerminal:t.resetTerminal??(u=>{sS(u)})},n=t.write??(u=>Ve.stderr.write(u)),o="palette",s=t.signals??{register:(u,p)=>{Ve.on(u,p)},unregister:(u,p)=>{Ve.off(u,p)},exit:u=>{Ve.exit(u)},raise:u=>{Ve.kill(Ve.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:F0(()=>o,s),c={armed:()=>{o="pause"},quitRequested:()=>a.quitRequested()},l=t.afterRun??B0(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=YR(iS(p),{color:r.color});n(`
|
|
475
501
|
${m}
|
|
476
|
-
`),a.childStarted();let f=await
|
|
502
|
+
`),a.childStarted();let f=await N0(p,r,()=>{o="child"});if(n(`
|
|
477
503
|
${f}
|
|
478
|
-
`),await l(c)==="quit")return}}finally{a.dispose()}};
|
|
504
|
+
`),await l(c)==="quit")return}}finally{a.dispose()}};uf();DR();Xv(()=>import("./boot-26CWOALE.js"));var pS=cf(),uS=async(e=We.argv)=>{ff(),Tg(e);try{await pS.parseAsync(e)}catch(t){BR(t)}},J0=()=>{try{if(We.env.INFRA_KIT_NO_LOCATION_WARN||We.argv.includes("--json"))return;xf({selfRealPath:W0(dS(import.meta.url)),cwd:We.cwd(),env:We.env,realpath:be,home:G0(),exists:V0})&&d.info("Running from a project-local node_modules. Install globally for faster startup: npm i -g infra-kit")}catch{}};J0();Gf((e,t)=>{d.debug(e,t)});Lu(U.version);var mS=()=>Db(pS.commands),K0=async()=>{let e=mS(),t=null;try{if(We.stdout.isTTY&&We.stdin.isTTY){let{runCommandPalette:r}=await import("./boot-26CWOALE.js");t=await r(e)}else{let r=df(e.map(o=>[o.name,o.description])),n=e.flatMap((o,s)=>[...e[s-1]?.group===o.group?[]:[new lS(" "),new lS(`\u2014 ${o.group} \u2014`)],{name:r[s]??o.name,value:o.name}]);t=await N(o=>U0({message:"Select a command to run",choices:n},o),{output:We.stderr})}}catch(r){if(!_e(r))throw r}return t},H0=async()=>{let{runCommandPalette:e}=await import("./boot-26CWOALE.js"),t=dS(import.meta.url),r=new Map(Yr.map(n=>[n.groupPath.join(" "),n]));await cS(mS(),{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(We.argv.length<=2){let e={stdoutIsTTY:!!We.stdout.isTTY,stdinIsTTY:!!We.stdin.isTTY,stderrIsTTY:!!We.stderr.isTTY};if(aS(We.env,e))await H0();else{let t=await K0();t&&await uS(["node","infra-kit",...t.split(" ")])}}else await uS();
|
|
479
505
|
//# sourceMappingURL=cli.js.map
|