infra-kit 0.1.113 → 0.1.115
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/.eslintcache +1 -1
- package/.omc/state/agent-replay-0d1515ce-4ebe-4ce8-a865-2897f68de168.jsonl +1 -0
- package/.omc/state/agent-replay-1fcfe0ec-7567-41c3-9bfd-501e99e86819.jsonl +19 -0
- package/.omc/state/agent-replay-38382db5-3088-4b5a-aff7-2561a60827c7.jsonl +17 -0
- package/.omc/state/agent-replay-50c36be9-a3a2-42b9-9c85-5a06d3e22f6a.jsonl +5 -0
- package/.omc/state/agent-replay-8198b3e5-fad6-4ee0-9c59-ef773ad89af4.jsonl +1 -0
- package/.omc/state/agent-replay-8cd7652a-b8b5-49cf-9b1f-bee8e5972458.jsonl +3 -0
- package/.omc/state/agent-replay-9bea518f-a9ee-4d14-bb53-a936ebaf647c.jsonl +7 -0
- package/.omc/state/agent-replay-b52d89fb-0e24-4901-bc66-27e3c1697126.jsonl +2 -0
- package/.omc/state/agent-replay-f581a1ae-0ee4-48a3-96f3-ce31a0633bb0.jsonl +1 -0
- package/.omc/state/agent-replay-f99d8dad-81d1-4987-8183-62edf0843d0c.jsonl +2 -0
- package/.omc/state/agent-replay-fe1057b4-9a25-4e8e-8c3f-3e11652ee697.jsonl +5 -0
- package/.omc/state/idle-notif-cooldown.json +1 -1
- package/.omc/state/sessions/0d1515ce-4ebe-4ce8-a865-2897f68de168/pre-tool-advisory-throttle.json +10 -0
- package/.omc/state/sessions/1fcfe0ec-7567-41c3-9bfd-501e99e86819/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/1fcfe0ec-7567-41c3-9bfd-501e99e86819/mission-state.json +109 -0
- package/.omc/state/sessions/1fcfe0ec-7567-41c3-9bfd-501e99e86819/pre-tool-advisory-throttle.json +42 -0
- package/.omc/state/sessions/1fcfe0ec-7567-41c3-9bfd-501e99e86819/ralph-state.json +13 -0
- package/.omc/state/sessions/1fcfe0ec-7567-41c3-9bfd-501e99e86819/skill-active-state.json +15 -0
- package/.omc/state/sessions/1fcfe0ec-7567-41c3-9bfd-501e99e86819/subagent-tracking-state.json +62 -0
- package/.omc/state/sessions/1fcfe0ec-7567-41c3-9bfd-501e99e86819/ultrawork-state.json +11 -0
- package/.omc/state/sessions/23d0ff82-17e5-428b-8743-38f7979bb6f3/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/23d0ff82-17e5-428b-8743-38f7979bb6f3/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/38382db5-3088-4b5a-aff7-2561a60827c7/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/38382db5-3088-4b5a-aff7-2561a60827c7/mission-state.json +145 -0
- package/.omc/state/sessions/38382db5-3088-4b5a-aff7-2561a60827c7/pre-tool-advisory-throttle.json +38 -0
- package/.omc/state/sessions/38382db5-3088-4b5a-aff7-2561a60827c7/ralplan-state.json +11 -0
- package/.omc/state/sessions/38382db5-3088-4b5a-aff7-2561a60827c7/subagent-tracking-state.json +98 -0
- package/.omc/state/sessions/41336850-028c-476b-be1a-2164e1e46cac/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/41336850-028c-476b-be1a-2164e1e46cac/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/50c36be9-a3a2-42b9-9c85-5a06d3e22f6a/mission-state.json +61 -0
- package/.omc/state/sessions/50c36be9-a3a2-42b9-9c85-5a06d3e22f6a/pre-tool-advisory-throttle.json +22 -0
- package/.omc/state/sessions/50c36be9-a3a2-42b9-9c85-5a06d3e22f6a/skill-active-state.json +15 -0
- package/.omc/state/sessions/50c36be9-a3a2-42b9-9c85-5a06d3e22f6a/subagent-tracking-state.json +26 -0
- package/.omc/state/sessions/560ea519-574a-4713-b134-5bf6cfaf3c33/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/8198b3e5-fad6-4ee0-9c59-ef773ad89af4/pre-tool-advisory-throttle.json +14 -0
- package/.omc/state/sessions/8198b3e5-fad6-4ee0-9c59-ef773ad89af4/subagent-tracking-state.json +17 -0
- package/.omc/state/sessions/8cd7652a-b8b5-49cf-9b1f-bee8e5972458/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/8cd7652a-b8b5-49cf-9b1f-bee8e5972458/ralplan-state.json +11 -0
- package/.omc/state/sessions/8cd7652a-b8b5-49cf-9b1f-bee8e5972458/subagent-tracking-state.json +35 -0
- package/.omc/state/sessions/9bea518f-a9ee-4d14-bb53-a936ebaf647c/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/9bea518f-a9ee-4d14-bb53-a936ebaf647c/mission-state.json +79 -0
- package/.omc/state/sessions/9bea518f-a9ee-4d14-bb53-a936ebaf647c/pre-tool-advisory-throttle.json +22 -0
- package/.omc/state/sessions/9bea518f-a9ee-4d14-bb53-a936ebaf647c/progress.txt +7 -0
- package/.omc/state/sessions/9bea518f-a9ee-4d14-bb53-a936ebaf647c/skill-active-state.json +15 -0
- package/.omc/state/sessions/9bea518f-a9ee-4d14-bb53-a936ebaf647c/subagent-tracking-state.json +26 -0
- package/.omc/state/sessions/b52d89fb-0e24-4901-bc66-27e3c1697126/pre-tool-advisory-throttle.json +14 -0
- package/.omc/state/sessions/b52d89fb-0e24-4901-bc66-27e3c1697126/subagent-tracking-state.json +17 -0
- package/.omc/state/sessions/c513ef38-cc3e-4a29-9c4c-1e0137245dd5/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/ed3e2cfb-a666-4bb1-bcc1-569d5d0b837a/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/f581a1ae-0ee4-48a3-96f3-ce31a0633bb0/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/f581a1ae-0ee4-48a3-96f3-ce31a0633bb0/subagent-tracking-state.json +17 -0
- package/.omc/state/sessions/f99d8dad-81d1-4987-8183-62edf0843d0c/pre-tool-advisory-throttle.json +14 -0
- package/.omc/state/sessions/f99d8dad-81d1-4987-8183-62edf0843d0c/ralph-state.json +13 -0
- package/.omc/state/sessions/f99d8dad-81d1-4987-8183-62edf0843d0c/ultrawork-state.json +11 -0
- package/.omc/state/sessions/fe1057b4-9a25-4e8e-8c3f-3e11652ee697/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/fe1057b4-9a25-4e8e-8c3f-3e11652ee697/mission-state.json +61 -0
- package/.omc/state/sessions/fe1057b4-9a25-4e8e-8c3f-3e11652ee697/prd.json +22 -0
- package/.omc/state/sessions/fe1057b4-9a25-4e8e-8c3f-3e11652ee697/pre-tool-advisory-throttle.json +22 -0
- package/.omc/state/sessions/fe1057b4-9a25-4e8e-8c3f-3e11652ee697/progress.txt +22 -0
- package/.omc/state/sessions/fe1057b4-9a25-4e8e-8c3f-3e11652ee697/skill-active-state.json +15 -0
- package/.omc/state/sessions/fe1057b4-9a25-4e8e-8c3f-3e11652ee697/subagent-tracking-state.json +26 -0
- package/.turbo/turbo-build.log +3 -3
- package/.turbo/turbo-test.log +92 -44
- package/dist/boot-K4QUAFSP.js +2 -0
- package/dist/boot-K4QUAFSP.js.map +7 -0
- package/dist/chunk-RTSP2FCA.js +2 -0
- package/dist/chunk-RTSP2FCA.js.map +7 -0
- package/dist/chunk-VPBZR2PY.js +166 -0
- package/dist/chunk-VPBZR2PY.js.map +7 -0
- package/dist/cli.js +11 -107
- package/dist/cli.js.map +4 -4
- package/dist/entry/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/lib/vendor/config-schema.d.ts +58 -0
- package/dist/mcp.js +1 -54
- package/dist/mcp.js.map +4 -4
- package/eslint.config.js +33 -1
- package/package.json +5 -1
- package/scripts/build.js +11 -1
- package/src/.omc/state/agent-replay-c513ef38-cc3e-4a29-9c4c-1e0137245dd5.jsonl +4 -0
- package/src/.omc/state/agent-replay-ed3e2cfb-a666-4bb1-bcc1-569d5d0b837a.jsonl +2 -0
- package/src/.omc/state/idle-notif-cooldown.json +1 -1
- package/src/.omc/state/sessions/c513ef38-cc3e-4a29-9c4c-1e0137245dd5/mission-state.json +79 -0
- package/src/.omc/state/sessions/c513ef38-cc3e-4a29-9c4c-1e0137245dd5/pre-tool-advisory-throttle.json +22 -0
- package/src/.omc/state/sessions/c513ef38-cc3e-4a29-9c4c-1e0137245dd5/subagent-tracking-state.json +26 -0
- package/src/.omc/state/sessions/ed3e2cfb-a666-4bb1-bcc1-569d5d0b837a/pre-tool-advisory-throttle.json +18 -0
- package/src/.omc/state/sessions/ed3e2cfb-a666-4bb1-bcc1-569d5d0b837a/ralph-state.json +13 -0
- package/src/.omc/state/sessions/ed3e2cfb-a666-4bb1-bcc1-569d5d0b837a/ultrawork-state.json +11 -0
- package/src/.omc/state/sessions/f99d8dad-81d1-4987-8183-62edf0843d0c/pre-tool-advisory-throttle.json +14 -0
- package/src/commands/config/.omc/state/sessions/41336850-028c-476b-be1a-2164e1e46cac/last-tool-error-state.json +7 -0
- package/src/commands/config/.omc/state/sessions/41336850-028c-476b-be1a-2164e1e46cac/pre-tool-advisory-throttle.json +18 -0
- package/src/commands/config/config.ts +7 -37
- package/src/commands/doctor/__tests__/agent-files.test.ts +8 -30
- package/src/commands/doctor/__tests__/check-legacy-user-global-config.test.ts +110 -0
- package/src/commands/doctor/doctor.ts +110 -44
- package/src/commands/env-autoload/env-autoload.ts +12 -0
- package/src/commands/env-autoload/index.ts +1 -0
- package/src/commands/env-clear/__tests__/env-clear.test.ts +27 -0
- package/src/commands/env-clear/env-clear.ts +22 -8
- package/src/commands/env-load/__tests__/env-load.test.ts +36 -1
- package/src/commands/env-load/env-load.ts +152 -35
- package/src/commands/env-load/index.ts +2 -1
- package/src/commands/env-status/__tests__/env-status.test.ts +78 -0
- package/src/commands/env-status/env-status.ts +19 -7
- package/src/commands/gh-release-deploy-all/gh-release-deploy-all.ts +45 -1
- package/src/commands/gh-release-deploy-selected/gh-release-deploy-selected.ts +46 -1
- package/src/commands/init/__tests__/agent-files.test.ts +145 -27
- package/src/commands/init/__tests__/migrate-config.test.ts +136 -5
- package/src/commands/init/__tests__/migrate-factory-config.test.ts +93 -0
- package/src/commands/init/__tests__/seed-user-global-config.test.ts +64 -0
- package/src/commands/init/__tests__/shell-body.test.ts +30 -0
- package/src/commands/init/agent-files.ts +65 -45
- package/src/commands/init/init.ts +140 -31
- package/src/commands/init/migrate-config.ts +160 -32
- package/src/commands/vendor-check/__tests__/runtime-isolation.test.ts +71 -0
- package/src/commands/vendor-check/__tests__/vendor-check.test.ts +87 -0
- package/src/commands/vendor-check/index.ts +1 -0
- package/src/commands/vendor-check/vendor-check.ts +127 -0
- package/src/commands/vendor-config/__tests__/vendor-config.test.ts +103 -0
- package/src/commands/vendor-config/index.ts +1 -0
- package/src/commands/vendor-config/vendor-config.ts +162 -0
- package/src/commands/vendor-diff/__tests__/vendor-diff.test.ts +74 -0
- package/src/commands/vendor-diff/index.ts +1 -0
- package/src/commands/vendor-diff/vendor-diff.ts +77 -0
- package/src/commands/vendor-manifest/index.ts +1 -0
- package/src/commands/vendor-manifest/vendor-manifest.ts +60 -0
- package/src/commands/vendor-sync/__tests__/vendor-write.test.ts +86 -0
- package/src/commands/vendor-sync/index.ts +1 -0
- package/src/commands/vendor-sync/vendor-sync.ts +90 -0
- package/src/commands/worktrees-add/worktrees-add.ts +1 -1
- package/src/commands/worktrees-reload/worktrees-reload.ts +6 -5
- package/src/commands/worktrees-remove/worktrees-remove.ts +10 -1
- package/src/commands/worktrees-sync/worktrees-sync.ts +9 -1
- package/src/entry/cli.ts +417 -210
- package/src/entry/index.ts +7 -1
- package/src/integrations/cmux/__tests__/open-workspace-with-layout.test.ts +127 -0
- package/src/integrations/cmux/close-workspace-by-title.ts +2 -2
- package/src/integrations/cmux/list-workspace-titles.ts +1 -1
- package/src/integrations/cmux/open-workspace-with-layout.ts +15 -4
- package/src/integrations/cursor/.omc/state/agent-replay-f99d8dad-81d1-4987-8183-62edf0843d0c.jsonl +2 -0
- package/src/integrations/cursor/.omc/state/idle-notif-cooldown.json +3 -0
- package/src/integrations/cursor/.omc/state/sessions/f99d8dad-81d1-4987-8183-62edf0843d0c/pre-tool-advisory-throttle.json +18 -0
- package/src/integrations/cursor/.omc/state/sessions/f99d8dad-81d1-4987-8183-62edf0843d0c/subagent-tracking-state.json +17 -0
- package/src/integrations/cursor/index.ts +1 -0
- package/src/integrations/cursor/launch-cursor.ts +12 -0
- package/src/integrations/cursor/open-cursor-workspace.ts +8 -14
- package/src/integrations/doppler/__tests__/doppler-errors.test.ts +76 -0
- package/src/integrations/doppler/doppler-cli-auth.ts +12 -4
- package/src/integrations/doppler/doppler-errors.ts +88 -0
- package/src/integrations/doppler/doppler-project.ts +80 -0
- package/src/integrations/doppler/index.ts +3 -1
- package/src/integrations/gh/gh-cli-auth/gh-cli-auth.ts +9 -5
- package/src/integrations/gh/gh-release-prs/gh-release-prs.ts +16 -8
- package/src/integrations/ide/__tests__/ide-facade.test.ts +57 -10
- package/src/integrations/ide/add-ide-worktree-folders.ts +2 -4
- package/src/integrations/ide/open-ide-workspace.ts +6 -6
- package/src/integrations/ide/remove-ide-worktree-folders.ts +95 -30
- package/src/integrations/ide/types.ts +10 -1
- package/src/integrations/zed/__tests__/open-zed-workspace.test.ts +1 -17
- package/src/integrations/zed/__tests__/reuse-zed-workspace.test.ts +86 -0
- package/src/integrations/zed/index.ts +1 -0
- package/src/integrations/zed/open-zed-workspace.ts +4 -10
- package/src/integrations/zed/reuse-zed-workspace.ts +57 -0
- package/src/lib/command-catalog/__tests__/__snapshots__/command-catalog.test.ts.snap +212 -0
- package/src/lib/command-catalog/__tests__/command-catalog.test.ts +193 -0
- package/src/lib/command-catalog/command-catalog.ts +141 -0
- package/src/lib/command-catalog/index.ts +2 -0
- package/src/lib/command-echo/__tests__/command-echo.test.ts +127 -0
- package/src/lib/constants/constants.ts +13 -0
- package/src/lib/constants/index.ts +2 -0
- package/src/lib/env-autoload/__tests__/env-autoload.test.ts +288 -0
- package/src/lib/env-autoload/env-autoload.ts +294 -0
- package/src/lib/env-autoload/index.ts +9 -0
- package/src/lib/errors/operation-error.ts +1 -1
- package/src/lib/infra-kit-config/__tests__/env-autoload-schema.test.ts +71 -0
- package/src/lib/infra-kit-config/__tests__/infra-kit-config.test.ts +77 -6
- package/src/lib/infra-kit-config/index.ts +9 -1
- package/src/lib/infra-kit-config/infra-kit-config.ts +71 -11
- package/src/lib/json-output/__tests__/json-output.test.ts +139 -0
- package/src/lib/json-output/index.ts +1 -0
- package/src/lib/json-output/json-output.ts +47 -0
- package/src/lib/managed-block/managed-block.ts +4 -4
- package/src/lib/path-display/index.ts +1 -0
- package/src/lib/path-display/path-display.ts +42 -0
- package/src/lib/render/__tests__/render.test.ts +48 -0
- package/src/lib/render/index.ts +1 -0
- package/src/lib/render/render.ts +24 -0
- package/src/lib/vendor/__tests__/config-schema.test.ts +31 -0
- package/src/lib/vendor/__tests__/config.test.ts +63 -0
- package/src/lib/vendor/__tests__/factory-config.test.ts +92 -0
- package/src/lib/vendor/__tests__/vendor-lib.test.ts +158 -0
- package/src/lib/vendor/__tests__/zx-mock.ts +32 -0
- package/src/lib/vendor/config-schema.ts +78 -0
- package/src/lib/vendor/config.ts +58 -0
- package/src/lib/vendor/factory-config-schema.ts +35 -0
- package/src/lib/vendor/factory-config.ts +91 -0
- package/src/lib/vendor/hash.ts +16 -0
- package/src/lib/vendor/index.ts +23 -0
- package/src/lib/vendor/manifest.ts +151 -0
- package/src/lib/vendor/skip-sets.ts +48 -0
- package/src/lib/vendor/sync-ops.ts +290 -0
- package/src/lib/vendor/walk.ts +56 -0
- package/src/lib/worktrees/remove-worktrees.ts +15 -0
- package/src/mcp/tools/index.ts +5 -42
- package/src/sanity.test.tsx +1 -0
- package/src/tui/__tests__/no-react-boundary.test.ts +51 -0
- package/src/tui/boot.tsx +45 -0
- package/src/tui/screens/__tests__/command-palette.test.tsx +136 -0
- package/src/tui/screens/command-palette.tsx +159 -0
- package/src/tui/types.ts +8 -0
- package/tsconfig.json +1 -0
- package/tsconfig.tsbuildinfo +1 -1
- package/vitest.config.ts +8 -0
- package/src/commands/worktrees-open/__tests__/open-cmux.test.ts +0 -96
- package/src/commands/worktrees-open/index.ts +0 -1
- package/src/commands/worktrees-open/worktrees-open.ts +0 -195
package/dist/cli.js
CHANGED
|
@@ -1,116 +1,20 @@
|
|
|
1
|
-
import
|
|
2
|
-
`).filter(Boolean),o={release:Mn,feature:Dn};return t.map(o[e]).filter(n=>n!==null)},Wo=e=>{let r=e.trimEnd();if(!r.endsWith("]"))return null;let t=r.lastIndexOf("[");if(t===-1)return null;let o=r.slice(t+1,-1);return o.length>0?o:null},Mn=e=>{let r=Wo(e);return ke(r)?r:null},Dn=e=>{let r=Wo(e);return r?.startsWith("feature/")?r:null},R=async()=>(await Z`git rev-parse --show-toplevel`).stdout.trim(),jr=async()=>(await Z`git rev-parse --abbrev-ref HEAD`).stdout.trim(),It=async()=>(await Z`git status --porcelain`).stdout.trim().length===0,$t=async()=>{let e=await R(),[r,t]=await Promise.all([Z({cwd:e})`git rev-parse --absolute-git-dir`,Z({cwd:e})`git rev-parse --git-common-dir`]),o=r.stdout.trim(),n=Lo.resolve(e,t.stdout.trim());return o!==n},N=async()=>{let e=await R();return Lo.basename(e)},St=async e=>{(await Z`git branch --list ${e}`).stdout.trim().length!==0&&await jr()!==e&&await Z`git branch -D ${e}`},At=async e=>{(await Z`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await Z`git push origin --delete ${e}`};import Ln from"node:process";import Wn from"pino";import Bn from"pino-pretty";var Vn=()=>{let e=Ln.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Wn({level:e},Bn({destination:2,ignore:r.join(","),colorize:!0}))},a=Vn();var se={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},Nt={requiredScripts:["build","dev","test","qa","check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","check"]},_t=(e,r=se)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import{z as ie}from"zod";var Ot=ie.strictObject({requiredScripts:ie.array(ie.string().min(1)).optional(),requiredFiles:ie.array(ie.string().min(1)).optional(),turbo:ie.strictObject({requiredTasks:ie.array(ie.string().min(1)).optional()}).optional()});import Jn from"node:fs/promises";var Q=async e=>{try{return await Jn.access(e),!0}catch{return!1}};import rs from"node:path";import Bo from"node:fs/promises";import Vo from"node:path";import{pathToFileURL as Kn}from"node:url";import{z as zn}from"zod";var ae="infra-kit.config.ts",Ft=async e=>{try{let r=await Bo.readFile(Vo.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},rr=async(e,r=se)=>{let t=Vo.join(e,ae);if(!await Q(t))throw new Error(`${ae} not found at ${t}`);let o=await Bo.stat(t),i=(await import(`${Kn(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${ae} at ${t} has no default export`);let c=typeof i=="function"?await i():i,l=Ot.safeParse(c);if(!l.success)throw new Error(`Invalid ${ae} at ${t}: ${zn.prettifyError(l.error)}`);return _t(l.data,r)};import Jo from"node:fs/promises";import Mr from"node:path";import qn from"yaml";var Gn="pnpm-workspace.yaml",Un=async e=>(await Jo.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Mr.join(e,t.name)),Hn=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await Un(o));continue}let n=Mr.join(o,r);await Q(n)&&t.push(n)}return t},Zn=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await Hn(t,o);return t},tr=async e=>{let r=await Jo.readFile(Mr.join(e,Gn),"utf-8"),o=((qn.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await Zn(e,s);for(let c of i)await Q(Mr.join(c,"package.json"))&&n.add(c)}return[...n].sort()};var jt=async(e,r=se)=>{try{let t=await rr(e,r);return{check:{name:ae,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:ae,status:"fail",message:t.message},rules:null}}};import Xn from"node:fs/promises";import Yn from"node:path";var Mt=async(e,r)=>Promise.all(r.map(async t=>{let o=await Xn.stat(Yn.join(e,t)).catch(()=>null);return o?o.isFile()?{name:`file:${t}`,status:"pass",message:"exists"}:{name:`file:${t}`,status:"fail",message:`not a file: ${t} (found a directory)`}:{name:`file:${t}`,status:"fail",message:`missing file: ${t}`}}));var Dt=(e,r)=>r.map(t=>{let o=e[t];return typeof o!="string"?{name:`script:${t}`,status:"fail",message:`missing "${t}" in package.json scripts`}:o.trim().length===0?{name:`script:${t}`,status:"fail",message:`"${t}" is empty in package.json scripts`}:{name:`script:${t}`,status:"pass",message:"defined"}});import Qn from"node:fs/promises";import es from"node:path";var De="turbo.json",Lt=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await Qn.readFile(es.join(e,De),"utf-8");t=JSON.parse(n)}catch(n){return[{name:De,status:"fail",message:`cannot read/parse ${De}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:De,status:"fail",message:`no "tasks" object defined in ${De}`}]:r.map(n=>{let s=n in o||`//#${n}`in o;return{name:`turbo:${n}`,status:s?"pass":"fail",message:s?"defined":`missing turbo task "${n}" in ${De}`}})};var Wt=async(e,r=se)=>{let t=await Ft(e),o=t.name??rs.basename(e),{check:n,rules:s}=await jt(e,r),i=[n];s&&(i.push(...Dt(t.scripts??{},s.requiredScripts)),i.push(...await Mt(e,s.requiredFiles)),i.push(...await Lt(e,s.turboTasks)));let c=i.every(l=>l.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:c}};var h=e=>[{type:"text",text:e}],w=e=>e;var os=async e=>{let r=or.resolve(e);for(;r!==or.dirname(r);){if(await Q(or.join(r,"package.json")))return r;r=or.dirname(r)}if(await Q(or.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},ns=async e=>e.root?[{dir:await R(),baseline:Nt}]:e.all?(await tr(await R())).map(t=>({dir:t})):[{dir:await os(e.cwd??ts.cwd())}],ss=e=>{let r=e.passed?"PASS":"FAIL";a.info(`
|
|
3
|
-
${e.packageName} \u2014 ${r}`);for(let t of e.checks){let o=t.status==="pass"?"[PASS]":"[FAIL]";a.info(` ${o} ${t.name}: ${t.message}`)}},Dr=async(e={})=>{let r=await ns(e),t=[];for(let s of r)t.push(await Wt(s.dir,s.baseline));for(let s of t)ss(s);let o=t.every(s=>s.passed);a.info(`
|
|
4
|
-
${o?"\u2705 All valid":"\u274C Audit failed"} (${t.length} checked)`);let n={allPassed:o,packages:t.map(s=>({name:s.packageName,passed:s.passed,checks:s.checks}))};return{content:h(JSON.stringify(n,null,2)),structuredContent:n}},is={all:B.boolean().optional().describe("Audit every non-vendor workspace package"),root:B.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},as={allPassed:B.boolean().describe("Whether every audited package passed all checks"),packages:B.array(B.object({name:B.string(),passed:B.boolean(),checks:B.array(B.object({name:B.string(),status:B.enum(["pass","fail"]),message:B.string()}))})).describe("Per-package check results")},cs=w({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:is,outputSchema:as,handler:e=>Dr({all:e.all,root:e.root})});import Br from"node:fs/promises";import Es from"node:os";import Ts from"node:path";import Go from"node:process";import{$ as Is}from"zx";import Vt from"node:fs/promises";import ls from"node:os";import Lr from"node:path";import{z as v}from"zod";var Ko="infra-kit.json",ds=".infra-kit",ps="config.json",ms="projects",us=v.object({provider:v.literal("doppler"),config:v.object({name:v.string().min(1)})}),fs=v.discriminatedUnion("provider",[us]),gs=v.object({workspaceConfigPath:v.string().min(1)}),hs=v.object({provider:v.literal("cursor"),config:gs}),ws=v.object({}),ks=v.object({provider:v.literal("zed"),config:ws}),zo=v.discriminatedUnion("provider",[hs,ks]),vs=v.union([zo,v.array(zo).min(1)]),ys=v.object({provider:v.literal("jira"),config:v.object({baseUrl:v.string().url(),projectId:v.number().int().positive()})}),Rs=v.discriminatedUnion("provider",[ys]),bs=v.object({openInGithubDesktop:v.boolean().optional(),openInCmux:v.boolean().optional()}),qo=v.object({environments:v.array(v.string().min(1)).min(1),envManagement:fs,ide:vs.optional(),taskManager:Rs.optional(),worktrees:bs.optional()}),Wr=qo.superRefine((e,r)=>{if(!Array.isArray(e.ide))return;let t=new Set;for(let o of e.ide){if(t.has(o.provider)){r.addIssue({code:"custom",message:"each IDE provider may appear at most once",path:["ide"]});return}t.add(o.provider)}}),nr=qo.partial(),q=e=>{let r=e.ide;return r?Array.isArray(r)?r:[r]:[]},Le=null,j=async()=>{let e=await R(),r=await N(),t=Lr.join(ls.homedir(),ds);return{main:Lr.join(e,Ko),userGlobal:Lr.join(t,ps),userProject:Lr.join(t,ms,r,Ko),projectName:r}},b=async()=>{let e=await j(),r;try{r=await Vt.stat(e.main)}catch{Le=null;let l=e.main.replace(/\.json$/,".yml");throw await Bt(l)?new Error(`infra-kit.json not found at ${e.main}. A legacy infra-kit.yml exists \u2014 run \`infra-kit init\` to convert it.`):new Error(`infra-kit.json not found at ${e.main}`)}let[t,o]=await Promise.all([Bt(e.userGlobal),Bt(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(Le&&Cs(Le.mtimes,n))return Le.value;let s=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/config.json",path:e.userGlobal,required:!1},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,path:e.userProject,required:!1}],i={};for(let l of s){let d=await Ps(l);d!==null&&(i={...i,...d})}let c=Wr.safeParse(i);if(!c.success)throw new Error(`Invalid merged infra-kit config: ${v.prettifyError(c.error)}`);return Le={mtimes:n,value:c.data},c.data},ee=()=>{Le=null},Bt=async e=>{try{return await Vt.stat(e)}catch{return null}},xs=async e=>{try{return await Vt.readFile(e,"utf-8")}catch{return null}},Cs=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},Ps=async e=>{let r=await xs(e.path);if(r===null){if(e.required)throw new Error(`${e.label} not found at ${e.path}`);return null}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in ${e.label} at ${e.path}: ${n.message}`)}let o=nr.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${v.prettifyError(o.error)}`);return o.data};var Uo=async e=>{try{return await Br.access(e),!0}catch{return!1}},Vr=e=>{let r=Es.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e},Jt=async()=>{let e=await j(),r=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async o=>({...o,exists:await Uo(o.path)})));a.info(`Project name: ${e.projectName}
|
|
1
|
+
import{A as de,B as me,C as le,D as pe,E as fe,F as ue,G as ge,H as ve,I as ye,J as he,K as we,L as ke,M as Ce,N as Ae,O as xe,P as _,Q as Ee,R as Se,S as Re,T as Le,U as be,W as j,a as U,d as a,e as B,f as T,g as z,h as Y,i as h,j as u,k as D,l as q,m as Q,n as I,o as X,p as Z,q as ee,r as oe,s as te,t as re,u as ne,v as ie,w as C,x as ae,y as se,z as ce}from"./chunk-VPBZR2PY.js";import{e as $}from"./chunk-RTSP2FCA.js";import vo,{Separator as x}from"@inquirer/select";import{Command as yo}from"commander";import w from"node:process";import N from"node:fs/promises";import Xe from"node:path";import je from"node:process";import{$ as Ze}from"zx";var O=async()=>{let e=await T(),o=await Promise.all([{label:"project (committed)",path:e.main},{label:"user global",path:e.userGlobal},{label:"user project",path:e.userProject}].map(async r=>({...r,exists:await h(r.path)})));a.info(`Project name: ${e.projectName}
|
|
5
2
|
`),a.info(`Config merge chain (later overrides earlier):
|
|
6
|
-
`);for(let
|
|
7
|
-
`,"utf-8"),await
|
|
3
|
+
`);for(let r of o){let c=r.exists?" [\u2713]":" [ ]";a.info(`${c} ${r.label.padEnd(22)} ${u(r.path)}`)}let t={projectName:e.projectName,layers:o.map(r=>({label:r.label,path:r.path,exists:r.exists}))};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},M=async()=>{let e=await T(),o=je.env.EDITOR||je.env.VISUAL||"vi";if(await N.mkdir(Xe.dirname(e.userProject),{recursive:!0}),!await h(e.userProject)){let r=eo(e.userProject);await N.writeFile(e.userProject,`{}
|
|
4
|
+
`,"utf-8"),await N.writeFile(r,oo(e.projectName),"utf-8"),a.info(`Created ${u(e.userProject)} \u2014 see ${u(r)} for the annotated reference.`)}a.info(`Opening ${u(e.userProject)} in ${o}`),await Ze({stdio:"inherit"})`${o} ${e.userProject}`,Y();let t={path:e.userProject,editor:o};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},eo=e=>e.replace(/\.json$/,".example.jsonc"),oo=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
8
5
|
//
|
|
9
6
|
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top
|
|
10
|
-
// of <repo>/infra-kit.json and ~/.infra-kit/
|
|
11
|
-
// (environments, envManagement, ide, taskManager, worktrees) replace wholesale.
|
|
7
|
+
// of <repo>/infra-kit.json and ~/.infra-kit/infra-kit.json \u2014 top-level keys
|
|
8
|
+
// (environments, envManagement, ide, taskManager, worktrees, envAutoLoad) replace wholesale.
|
|
12
9
|
//
|
|
13
10
|
// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
|
|
14
11
|
// in the sibling infra-kit.json (strict JSON: no comments, double-quoted keys).
|
|
15
12
|
{
|
|
16
|
-
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true }
|
|
13
|
+
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true, "cmux": { "layout": "two-columns" } },
|
|
14
|
+
// // Auto-load Doppler env here. trigger (pick one): shell-startup | cli-invocation; config: an environment name.
|
|
15
|
+
// "envAutoLoad": { "trigger": "shell-startup", "config": "dev" }
|
|
17
16
|
}
|
|
18
|
-
`;import
|
|
19
|
-
|
|
20
|
-
${r}
|
|
21
|
-
${t}`,ve=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=Ho(t,r,o),i=We(e,t,o);if(n==="replace-in-place"&&i){let d=e.indexOf(t),p=e.indexOf(o)+o.length;return e.slice(0,d)+s+e.slice(p)}let l=(i?sr(e,t,o)??e:e).replace(/\n+$/,"");return l.length>0?`${l}
|
|
22
|
-
${s}
|
|
23
|
-
`:`${s}
|
|
24
|
-
`};var Jr={name:"infra-kit",type:"module",version:"0.1.113",description:"infra-kit",main:"dist/index.js",module:"dist/index.js",types:"dist/entry/index.d.ts",exports:{".":{types:"./dist/entry/index.d.ts",import:"./dist/index.js"}},bin:{"infra-kit":"dist/cli.js"},engines:{node:">=24.x"},scripts:{inspector:"npx @modelcontextprotocol/inspector node ./dist/mcp.js --debug",build:"pnpm run clean-artifacts && node ./scripts/build.js",check:"node ./dist/cli.js check","clean-artifacts":"rm -rf dist","clean-cache":"rm -rf node_modules/.cache .eslintcache tsconfig.tsbuildinfo .turbo .swc","prettier-fix":"pnpm exec prettier **/* --write --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","prettier-check":"pnpm exec prettier **/* --check --no-error-on-unmatched-pattern --log-level silent --ignore-path ../../../.prettierignore","eslint-check":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src","eslint-fix":"pnpm exec eslint --cache --quiet --report-unused-disable-directives ./src --fix","ts-check":"tsc --noEmit",test:"pnpm exec vitest run --reporter=minimal","test-watch":"pnpm exec vitest --watch --silent passed-only","test-ui":"pnpm exec vitest --ui --silent passed-only","test-report":"pnpm exec vitest run --coverage --silent passed-only",qa:"pnpm run prettier-check && pnpm run eslint-check && pnpm run ts-check && pnpm run test && echo \u2705 Success",fix:"pnpm run prettier-fix && pnpm run eslint-fix && pnpm run qa"},dependencies:{"@inquirer/checkbox":"^5.2.1","@inquirer/confirm":"^6.1.1","@inquirer/select":"^5.2.1","@modelcontextprotocol/sdk":"^1.29.0",commander:"^15.0.0",pino:"^10.3.1","pino-pretty":"^13.1.3",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1",typescript:"^6.0.3"}};var ce="<!-- infra-kit:begin -->",le="<!-- infra-kit:end -->",Ns="<!-- infra-kit:version ",ir="<!-- infra-kit:import:begin -->",ar="<!-- infra-kit:import:end -->",Zo="AGENTS.md",_s="CLAUDE.md",Os=ye.join(".cursor","rules","infra-kit.mdc"),Fs=["---","description: infra-kit CLI usage and conventions","alwaysApply: true","---",""].join(`
|
|
25
|
-
`),js=e=>`${Ns}${e} -->`,Ms=e=>[js(e),"","# infra-kit","","This repository uses the **infra-kit** CLI for environment, worktree, and release workflows.","This block is generated by `infra-kit init` \u2014 edit text *outside* the markers, never inside.","","## Commands (`ik` = `pnpm exec infra-kit`)","","- `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.","- `ik worktrees-add` / `worktrees-list` / `worktrees-open` / `worktrees-remove` / `worktrees-sync` \u2014 manage release and feature git worktrees.","- `ik release-create` / `release-list` / `release-deploy-all` / `release-deploy-selected` / `release-deliver` / `release-desc-edit` \u2014 release-branch and deploy flow.","- `ik merge-dev` \u2014 merge the dev branch into every release branch.","- `ik audit` \u2014 audit packages against `infra-kit.config.ts` rules.","- `ik doctor` \u2014 check gh / doppler / aws / rtk install + auth and repo setup.","- `ik init` \u2014 (re)install shell integration and regenerate these agent-instruction files.","","## Conventions","","- 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.","- Environment variables are managed through Doppler via `ik env-load` \u2014 never commit secrets."].join(`
|
|
26
|
-
`),Ds=e=>{if(G.existsSync(e)&&G.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},zt=(e,r)=>{Ds(e);let t=G.existsSync(e);if((t?G.readFileSync(e,"utf-8"):null)===r)return"unchanged";if(t){let n=new Date().toISOString().replace(/[:.]/g,"-");G.copyFileSync(e,`${e}.backup.${n}`)}return G.mkdirSync(ye.dirname(e),{recursive:!0}),G.writeFileSync(e,r,"utf-8"),t?"updated":"created"},qt=(e,r)=>G.existsSync(e)?G.readFileSync(e,"utf-8"):r,Gt=(e,r,t)=>{let o=G.readFileSync(e,"utf-8");if(!We(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Ut=async()=>{let e;try{e=(await j()).main}catch{return a.info("Skipped agent-instruction files \u2014 not inside an infra-kit repo"),{skipped:!0,root:null,written:[]}}if(!G.existsSync(e))return a.info("Skipped agent-instruction files \u2014 no infra-kit.json at the repo root"),{skipped:!0,root:null,written:[]};let r=ye.dirname(e),t=Jr.version,o=Ms(t),n=ye.join(r,Zo),s=ye.join(r,_s),i=ye.join(r,Os),c=ve({content:qt(n,""),body:o,startMarker:ce,endMarker:le}),l=ve({content:qt(s,""),body:`@${Zo}`,startMarker:ir,endMarker:ar}),d=ve({content:qt(i,Fs),body:o,startMarker:ce,endMarker:le}),p=[{path:n,action:zt(n,c)},{path:s,action:zt(s,l)},{path:i,action:zt(i,d)}];Gt(n,ce,le),Gt(s,ir,ar),Gt(i,ce,le);for(let u of p)a.info(` ${u.action.padEnd(9)} ${ye.relative(r,u.path)}`);return a.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:p}};import be from"node:fs";import Qo from"node:os";import Kr from"node:path";import Re from"node:fs/promises";import Ls from"node:os";import Ws from"node:path";import Bs from"yaml";import{z as Vs}from"zod";var de=e=>{let r=Ls.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e},Zt=async e=>{try{return await Re.access(e),!0}catch{return!1}},Ht=e=>e.replace(/\.json$/,".yml"),Xo=async()=>{let e;try{e=await j()}catch{return}let r=[{label:"infra-kit.json",yml:Ht(e.main),json:e.main,schema:Wr},{label:"~/.infra-kit/config.json",yml:Ht(e.userGlobal),json:e.userGlobal,schema:nr},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Ht(e.userProject),json:e.userProject,schema:nr}],t=0;for(let o of r){let[n,s]=await Promise.all([Zt(o.yml),Zt(o.json)]);if(n){if(s){a.info(`\u26A0 Skipped ${de(o.yml)} \u2014 ${de(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await Re.readFile(o.yml,"utf-8"),c=Bs.parse(i)??{},l=o.schema.safeParse(c);if(!l.success){a.info(`\u26A0 Skipped ${de(o.yml)} \u2014 invalid config: ${Vs.prettifyError(l.error)}`);continue}await Re.mkdir(Ws.dirname(o.json),{recursive:!0}),await Re.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
|
|
27
|
-
`,"utf-8"),await Re.rm(o.yml,{force:!0}),a.info(`\u2713 Migrated ${de(o.yml)} \u2192 ${de(o.json)}`),t++}catch(i){a.info(`\u26A0 Skipped ${de(o.yml)} \u2014 ${i.message}`)}}}t>0&&ee()},Js=e=>{let r=e.ide;if(r===null||typeof r!="object")return{changed:!1,result:e};let t=!1,o=s=>{if(s===null||typeof s!="object"||!("config"in s))return s;let i=s.config;if(i===null||typeof i!="object"||!("mode"in i))return s;t=!0;let c=Object.fromEntries(Object.entries(i).filter(([l])=>l!=="mode"));return{...s,config:c}},n=Array.isArray(r)?r.map(o):o(r);return t?{changed:!0,result:{...e,ide:n}}:{changed:!1,result:e}},Yo=async()=>{let e;try{e=await j()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await Zt(o))try{let n=await Re.readFile(o,"utf-8");if(n.trim()==="")continue;let s=JSON.parse(n),{changed:i,result:c}=Js(s);if(!i)continue;await Re.writeFile(o,`${JSON.stringify(c,null,2)}
|
|
28
|
-
`,"utf-8"),a.info(`\u2713 Normalized ide config in ${de(o)} (removed legacy "mode")`),t++}catch(n){a.info(`\u26A0 Skipped normalizing ${de(o)} \u2014 ${n.message}`)}t>0&&ee()};var cr="# -- infra-kit:begin --",Be="# -- infra-kit:end --",Ks=[["# region infra-kit","# endregion infra-kit"]],zs="# infra-kit shell functions",qs=`{}
|
|
29
|
-
`,Gs=`// infra-kit user-global config \u2014 ~/.infra-kit/config.json
|
|
30
|
-
//
|
|
31
|
-
// Merge chain (later layers override earlier ones at top-level keys):
|
|
32
|
-
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
33
|
-
// 2. ~/.infra-kit/config.json \u2014 user-global (the sibling of this file)
|
|
34
|
-
// 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override
|
|
35
|
-
//
|
|
36
|
-
// Merge is shallow: setting a top-level key replaces that whole section from
|
|
37
|
-
// layer 1. Arrays do not concatenate. Top-level keys recognized:
|
|
38
|
-
// environments, envManagement, ide, taskManager, worktrees.
|
|
39
|
-
//
|
|
40
|
-
// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
|
|
41
|
-
// overrides in the sibling config.json (strict JSON: no comments, double-quoted
|
|
42
|
-
// keys). Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
|
|
43
|
-
{
|
|
44
|
-
// "ide": {
|
|
45
|
-
// "provider": "cursor",
|
|
46
|
-
// "config": { "workspaceConfigPath": "/path/to/your.code-workspace" }
|
|
47
|
-
// },
|
|
48
|
-
// // Or, for Zed (no workspace file \u2014 one window with all worktrees via "zed <root> <wt...>"):
|
|
49
|
-
// "ide": { "provider": "zed", "config": {} },
|
|
50
|
-
// // Or drive BOTH editors at once with an array (at most one entry per provider):
|
|
51
|
-
// "ide": [
|
|
52
|
-
// { "provider": "cursor", "config": { "workspaceConfigPath": "/path/to/your.code-workspace" } },
|
|
53
|
-
// { "provider": "zed", "config": {} }
|
|
54
|
-
// ],
|
|
55
|
-
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true }
|
|
56
|
-
}
|
|
57
|
-
`,Xt=async()=>{let e=Kr.join(Qo.homedir(),".zshrc"),r=be.existsSync(e)?Zs(be.readFileSync(e,"utf-8")):"",t=ve({content:r,body:en(),startMarker:cr,endMarker:Be,placement:"append-end"});be.writeFileSync(e,t),a.info(`Added infra-kit shell functions to ${e}`),await Xo(),await Yo(),Us(),await Ut(),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},Us=()=>{let e=Kr.join(Qo.homedir(),".infra-kit"),r=Kr.join(e,"config.json"),t=Kr.join(e,"config.example.jsonc");if(be.existsSync(r)){a.info(`User-global config already present at ${r}`);return}be.mkdirSync(e,{recursive:!0}),be.writeFileSync(r,qs,"utf-8"),be.writeFileSync(t,Gs,"utf-8"),a.info(`Wrote user-global config to ${r} (see ${t} for the annotated reference)`)},Hs=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("export _INFRA_KIT_")||e.startsWith(": ${_INFRA_KIT_")||e.startsWith("fi")||e.startsWith("zmodload ")||e.startsWith("autoload ")||e.startsWith("add-zsh-hook ")||e.startsWith("_infra_kit_autoload"),Zs=e=>{let r=sr(e,cr,Be);if(r!==null)return r;for(let[c,l]of Ks){let d=sr(e,c,l);if(d!==null)return d}let t=e.indexOf(zs);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
|
|
58
|
-
`),s=0;for(;s<n.length&&Hs(n[s]);)s++;let i=n.slice(s).join(`
|
|
59
|
-
`);return o+(i?`
|
|
60
|
-
${i}`:"")},en=()=>{let e="pnpm exec infra-kit";return["zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null",'if [[ -z "${INFRA_KIT_SESSION}" ]]; then'," export INFRA_KIT_SESSION=$(head -c 4 /dev/urandom | xxd -p)","fi",": ${_INFRA_KIT_LAST_LOAD_MTIME:=0}",": ${_INFRA_KIT_LAST_CLEAR_MTIME:=0}",": ${_INFRA_KIT_SHELL_STARTED:=${EPOCHSECONDS:-0}}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED",`env-load() { local f m; f=$(${e} env-load "$@") || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_LOAD_MTIME=$m; source "$f"; ${e} env-status; }`,`env-clear() { local f m; f=$(${e} env-clear) || return; m=$(zstat +mtime -- "$f" 2>/dev/null || echo 0); _INFRA_KIT_LAST_CLEAR_MTIME=$m; source "$f"; ${e} env-status; }`,`env-status() { ${e} env-status; }`,`alias ik='${e}'`,"_infra_kit_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local dir="$cache_root/$INFRA_KIT_SESSION"',' local load_file="$dir/env-load.sh"',' local clear_file="$dir/env-clear.sh"'," local mtime",' if [[ -f "$load_file" ]]; then',' mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)'," if (( mtime > _INFRA_KIT_LAST_LOAD_MTIME && mtime >= _INFRA_KIT_SHELL_STARTED )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$mtime",' print -u2 "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," fi",' if [[ -f "$clear_file" ]]; then',' mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( mtime > _INFRA_KIT_LAST_CLEAR_MTIME && mtime >= _INFRA_KIT_SHELL_STARTED )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$mtime",' print -u2 "infra-kit: auto-cleared env"'," fi"," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi"].join(`
|
|
61
|
-
`)},rn=()=>`${cr}
|
|
62
|
-
${en()}
|
|
63
|
-
${Be}`;var Je=async(e,r,t,o)=>{try{return await Yt`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Xs=()=>{let e="zshrc init block",r=lr.join(tn.homedir(),".zshrc");if(!pe.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=pe.readFileSync(r,"utf-8"),o=t.indexOf(cr),n=t.indexOf(Be);if(o===-1||n===-1||n<o)return{name:e,status:"fail",message:"infra-kit shell block missing from ~/.zshrc. Run: infra-kit init"};let s=t.slice(o,n+Be.length).trim(),i=rn().trim();return s!==i?{name:e,status:"fail",message:"infra-kit shell block in ~/.zshrc is out of date. Run: infra-kit init"}:{name:e,status:"pass",message:"infra-kit shell block in ~/.zshrc is up to date"}},Ys=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await R(),t=lr.join(r,"pnpm-workspace.yaml");if(!pe.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=pe.readFileSync(t,"utf-8");return/^\s*enableGlobalVirtualStore\s*:\s*true\s*$/m.test(o)?{name:e,status:"pass",message:"enableGlobalVirtualStore: true is set"}:{name:e,status:"fail",message:"enableGlobalVirtualStore: true is missing in pnpm-workspace.yaml"}}catch(r){return{name:e,status:"fail",message:`Failed to read pnpm-workspace.yaml: ${r.message}`}}},Qs=async()=>{let e="infra-kit config valid";try{return ee(),await b(),{name:e,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}}catch(r){return{name:e,status:"fail",message:r.message}}},ei=async()=>{let e="user override path";try{let r=await j(),t=tn.homedir(),o=r.userProject.startsWith(t)?`~${r.userProject.slice(t.length)}`:r.userProject,s=pe.existsSync(r.userProject)?"(exists)":"(not yet created)";return{name:e,status:"pass",message:`${o} ${s} \u2014 project: ${r.projectName}`}}catch(r){return{name:e,status:"fail",message:r.message}}},ri={cursor:{command:["cursor","--version"],label:"Cursor",failMsg:"Cursor is not installed. Install from: https://cursor.com/"},zed:{command:["zed","--version"],label:"Zed",failMsg:"Zed is not installed. Install from: https://zed.dev/"}},ti=async e=>{let r=ri[e];try{return await Yt`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},oi=async()=>{let e="ide installed",r;try{ee();let n=await b();r=q(n).map(s=>s.provider)}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"}}if(r.length===0)return{name:e,status:"pass",message:"No IDE configured (ide unset)"};let t=await Promise.all(r.map(n=>ti(n))),o=t.filter(n=>!n.ok);return o.length===0?{name:e,status:"pass",message:`Installed: ${t.map(n=>n.label).join(", ")}`}:{name:e,status:"fail",message:o.map(n=>n.failMsg).join("; ")}},ni=[1,2,3,5,7],si=async()=>{let e="rtk configured";try{let t=(await Yt`rtk init --show`).stdout.split(`
|
|
64
|
-
`).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of ni){let s=t[n-1];(!s||!s.startsWith("[ok]"))&&o.push(n)}return o.length>0?{name:e,status:"fail",message:`rtk setup incomplete (items ${o.join(", ")} not [ok]). Run: rtk init -g --auto-patch`}:{name:e,status:"pass",message:"rtk hook, RTK.md, global CLAUDE.md, settings.json, and Cursor hook are configured"}}catch(r){return{name:e,status:"fail",message:`Failed to run 'rtk init --show': ${r.message}`}}},ii=async()=>{let e;try{e=(await j()).main}catch{return[]}if(!pe.existsSync(e))return[];let r=lr.dirname(e),t=(n,s,i)=>{let c=lr.join(r,n),l=pe.existsSync(c)?pe.readFileSync(c,"utf-8"):"";return We(l,s,i)};return[{name:"AGENTS.md block",present:t("AGENTS.md",ce,le),okMessage:"AGENTS.md block present",missingMessage:"infra-kit block missing from AGENTS.md. Run: infra-kit init"},{name:"CLAUDE.md import",present:t("CLAUDE.md",ir,ar),okMessage:"CLAUDE.md imports @AGENTS.md",missingMessage:"@AGENTS.md import block missing from CLAUDE.md. Run: infra-kit init"},{name:".cursor/rules block",present:t(lr.join(".cursor","rules","infra-kit.mdc"),ce,le),okMessage:".cursor/rules/infra-kit.mdc block present",missingMessage:".cursor/rules/infra-kit.mdc block missing. Run: infra-kit init"}].map(n=>({name:n.name,status:n.present?"pass":"fail",message:n.present?n.okMessage:n.missingMessage}))},zr=async()=>{let r=[...await Promise.all([Je("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),Je("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),Je("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),Je("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),Je("aws installed",["aws","--version"],"AWS CLI is installed","AWS CLI is not installed. Install from: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html"),Je("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),si(),Promise.resolve(Xs()),Ys(),Qs(),ei(),oi()]),...await ii()];a.info(`Doctor check results:
|
|
65
|
-
`);for(let o of r){let n=o.status==="pass"?"[PASS]":"[FAIL]";a.info(` ${n} ${o.name}: ${o.message}`)}let t={checks:r.map(o=>({name:o.name,status:o.status,message:o.message})),allPassed:r.every(o=>o.status==="pass")};return{content:h(JSON.stringify(t,null,2)),structuredContent:t}},ai=w({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:Ve.array(Ve.object({name:Ve.string().describe("Name of the check"),status:Ve.enum(["pass","fail"]).describe("Check result"),message:Ve.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:Ve.boolean().describe("Whether all checks passed")},handler:zr});import to from"node:fs";import nn from"node:path";import li from"node:process";import{z as qr}from"zod";import dr from"node:fs";import ci from"node:os";import Qt from"node:path";import eo from"node:process";var xe="env-load.sh",ro="env-clear.sh",pr="INFRA_KIT_SESSION",Ce="INFRA_KIT_ENV_CONFIG",Pe="INFRA_KIT_ENV_PROJECT",Ee="INFRA_KIT_ENV_LOADED_AT",mr=/^([A-Z_]\w*)=/i,ur=e=>{if(!dr.existsSync(e))return[];let r=dr.readFileSync(e,"utf-8"),t=[];for(let o of r.split(`
|
|
66
|
-
`)){let n=mr.exec(o);n&&t.push(n[1])}return t},on=()=>{let e=eo.env.XDG_CACHE_HOME,r=e&&e.length>0?e:Qt.join(ci.homedir(),".cache");return Qt.join(r,"infra-kit")},Te=()=>{let e=eo.env[pr];if(!e)throw new Error(`${pr} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return Qt.join(on(),e)},fr=(e,r,t)=>{let o=`${e}.tmp.${eo.pid}`;dr.writeFileSync(o,r,{mode:t});try{dr.renameSync(o,e)}catch(n){throw dr.rmSync(o,{force:!0}),n}},M="-worktrees";var Gr=async()=>{let e=Te(),r=nn.join(e,xe);if(!to.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=ur(r),o=[...t.map(i=>`unset ${i}`),`unset ${Ce}`,`unset ${Pe}`,`unset ${Ee}`],n=nn.resolve(e,ro);to.mkdirSync(e,{recursive:!0,mode:448}),fr(n,`${o.join(`
|
|
67
|
-
`)}
|
|
68
|
-
`,384),li.stdout.write(`${n}
|
|
69
|
-
`),to.unlinkSync(r);let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},di=w({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. When `infra-kit init` has installed the zsh shell integration, the user\'s terminal auto-sources the unset script on its next prompt (precmd hook) \u2014 so calling this via MCP will clear the vars in the shell that launched Claude Code automatically. Other callers must source "<filePath>" themselves or surface it to the user. Errors if no env is currently loaded.',inputSchema:{},outputSchema:{filePath:qr.string().describe("Path to the file that must be sourced to apply"),variableCount:qr.number().describe("Number of variables cleared"),unsetStatements:qr.array(qr.string()).describe("Unset statements generated")},handler:Gr});import{z as oo}from"zod";var gr=async()=>{let{envManagement:e}=await b();return e.config.name};var Ur=async()=>{let e=await gr(),{environments:r}=await b();a.info(`Doppler project: ${e}
|
|
70
|
-
`),a.info("Available configs:");for(let o of r)a.info(` - ${o}`);let t={project:e,configs:r};return{content:h(JSON.stringify(t,null,2)),structuredContent:t}},pi=w({name:"env-list",description:"List the environments the project is configured to support. Returns the `environments` list declared in infra-kit.json at the project root (not a live fetch from Doppler) plus the Doppler project name resolved from the same file. Read-only.",inputSchema:{},outputSchema:{project:oo.string().describe("Detected Doppler project name"),configs:oo.array(oo.string()).describe("Available environment configs")},handler:Ur});import ui from"@inquirer/select";import{Buffer as fi}from"node:buffer";import gi from"node:fs";import hi from"node:path";import an from"node:process";import{z as wr}from"zod";import{$ as Hr}from"zx";import{$ as sn}from"zx";var hr=async()=>{try{await sn`doppler --version`}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await sn`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var mi=()=>{let e="",r=[],t=!1;return{start(o){e=o,r=[],t=!1},setInteractive(){t=!0},addOption(o,n){r.push({flag:o,value:n})},print(){if(!t||r.length===0)return;let o=r.map(n=>typeof n.value=="boolean"?n.value?n.flag:"":Array.isArray(n.value)?`${n.flag} "${n.value.join(", ")}"`:`${n.flag} "${n.value}"`).filter(Boolean).join(" ");a.info(`\u{1F4DF} Equivalent command:
|
|
71
|
-
pnpm exec infra-kit ${e} ${o}
|
|
72
|
-
`)},reset(){e="",r=[],t=!1}}},m=mi();var Zr=async e=>{await hr();let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{let{environments:u}=await b();m.setInteractive(),t=await ui({message:"Select environment config",choices:u.map(g=>({name:g,value:g}))},{output:an.stderr})}m.addOption("--config",t);let o=await gr(),n=await ki(o,t);bi(n);let s=new Date().toISOString(),i=["set -a",n,`${Ce}=${no(t)}`,`${Pe}=${no(o)}`,`${Ee}=${no(s)}`,"set +a"],c=Te(),l=hi.resolve(c,xe);gi.mkdirSync(c,{recursive:!0,mode:448}),fr(l,`${i.join(`
|
|
73
|
-
`)}
|
|
74
|
-
`,384),an.stdout.write(`${l}
|
|
75
|
-
`),m.print();let d=yi(n),p={filePath:l,variableCount:d,project:o,config:t};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},cn=1024*1024,wi=3e4,ki=async(e,r)=>{let t=Hr.quiet;Hr.quiet=!0;try{let o=await Hr`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(wi);return vi(o.stdout),o.stdout.trim()}finally{Hr.quiet=t}},vi=e=>{let r=fi.byteLength(e,"utf-8");if(r>cn)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${cn}) \u2014 refusing to write to disk`)},yi=e=>e.split(`
|
|
76
|
-
`).filter(r=>mr.test(r)).length,Ri=new Set(["set -a","set +a"]),no=e=>`'${e.replaceAll("'","'\\''")}'`,bi=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
|
|
77
|
-
`)){let t=r.trim();if(!(t.length===0||Ri.has(t))&&!mr.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},xi=w({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. "config" is required when invoked via MCP (the CLI interactive picker is unreachable without a TTY).',inputSchema:{config:wr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:wr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:wr.number().describe("Number of variables loaded"),project:wr.string().describe("Doppler project name"),config:wr.string().describe("Doppler config name")},handler:Zr});import Ci from"node:path";import kr from"node:process";import{z as Ke}from"zod";var Xr=async()=>{await hr(),a.info("Environment session status:");let e=Te(),r=kr.env[pr],t=Ci.join(e,xe),o=0,n=0,s=kr.env[Ce]??null,i=kr.env[Pe]??null,c=kr.env[Ee]??null;if(s){let d=ur(t);d.length>0&&(n=d.length,o=d.filter(u=>u in kr.env).length);let p=c?.replace(/\.\d{3}Z$/,"")??null;if(a.info(` ${s}: ${o} of ${n} vars loaded (project: ${i}, loadedAt: ${p}, session: ${r})
|
|
78
|
-
`),n>0&&o<n){let u=n-o;a.warn(` ${u} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else a.info(` Session ${r}: no env loaded
|
|
79
|
-
`);let l={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:c};return{content:h(JSON.stringify(l,null,2)),structuredContent:l}},Pi=w({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. Read-only \u2014 use env-load / env-clear to change the terminal session.",inputSchema:{},outputSchema:{sessionId:Ke.string().describe("Current terminal session ID"),sessionLoadedCount:Ke.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Ke.number().describe("Total number of cached var names"),sessionConfig:Ke.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Ke.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Ke.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Xr});import $i from"@inquirer/checkbox";import Si from"@inquirer/confirm";import Ai from"node:process";import{z as He}from"zod";import{$ as U}from"zx";import{$ as rm}from"zx";import rt from"node:process";import{$ as O}from"zx";import{$ as yr}from"zx";import vr from"node:process";var so=async(e,r)=>{try{let{baseUrl:t,token:o,email:n,projectId:s}=r,i={name:e.name,projectId:e.projectId||s,description:e.description||"",released:e.released||!1,archived:e.archived||!1},c=`${t}/rest/api/3/version`,l=btoa(`${n}:${o}`),d=await fetch(c,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(i)});if(!d.ok){let u=await d.text();throw a.error({status:d.status,statusText:d.statusText,error:u},"Failed to create Jira version"),new Error(`HTTP ${d.status}: ${d.statusText}`)}return{success:!0,version:await d.json()}}catch(t){throw a.error({error:t},"Error creating Jira version"),t}},ze=async e=>{try{let{baseUrl:r,token:t,email:o,projectId:n}=e,s=`${r}/rest/api/3/project/${n}/versions`,i=btoa(`${o}:${t}`),c=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});if(!c.ok){let d=await c.text();throw a.error({status:c.status,statusText:c.statusText,error:d},"Failed to get Jira project versions"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return await c.json()}catch(r){throw a.error({error:r},"Error getting Jira project versions"),r}},Yr=async(e,r)=>{try{return(await ze(r)).find(n=>n.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Qr=async(e,r)=>{try{let{baseUrl:t,token:o,email:n}=r,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=`${t}/rest/api/3/version/${e.versionId}`,c=btoa(`${n}:${o}`),l=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(s)});if(!l.ok){let p=await l.text();throw a.error({status:l.status,statusText:l.statusText,error:p},"Failed to update Jira version"),new Error(`HTTP ${l.status}: ${l.statusText}`)}return{success:!0,version:await l.json()}}catch(t){throw a.error({error:t},"Error updating Jira version"),t}},io=async(e,r)=>{try{let{versionName:t}=e,o=await Yr(t,r);if(!o)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Qr({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw a.error({error:t},"Error delivering Jira release"),t}},qe=async()=>{let e=vr.env.JIRA_BASE_URL,r=vr.env.JIRA_TOKEN||vr.env.JIRA_API_TOKEN,t=vr.env.JIRA_PROJECT_ID,o=vr.env.JIRA_EMAIL,n=[];if(e||n.push("JIRA_BASE_URL (e.g., https://your-domain.atlassian.net)"),r||n.push("JIRA_TOKEN or JIRA_API_TOKEN (your Jira API token)"),t||n.push("JIRA_PROJECT_ID (numeric project ID)"),o||n.push("JIRA_EMAIL (your Jira email address)"),n.length>0){let i=["Jira configuration is required but incomplete.","Please configure the following environment variables:",...n.map(c=>` - ${c}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
80
|
-
`);throw new Error(i)}let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new TypeError(`Invalid JIRA_PROJECT_ID: "${t}" must be a numeric value (e.g., 10001)`);return{baseUrl:e.replace(/\/$/,""),token:r,projectId:s,email:o}},Ie=async()=>{try{return await qe()}catch(e){return a.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var Ti=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},Ii=(e,r)=>{let t=r.stderrExcerpt??Ti(e),o=[`failed to ${r.operation}`];return t&&o.push(`stderr: ${t.slice(0,200).trim()}`),r.remediation&&o.push(`try: ${r.remediation}`),o.join(" \u2014 ")},f=class extends Error{operation;remediation;constructor(r,t){super(Ii(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var ln="dev",Ge=e=>e==="hotfix"?"main":"dev",ao=async(e="regular")=>{let r=Ge(e);yr.quiet=!0,await yr`git fetch origin`,await yr`git switch ${r}`,await yr`git pull origin ${r}`,yr.quiet=!1},co=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=W(r),i=await so({name:s,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),c=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,l=await et({id:r,jiraVersionUrl:c,type:n,description:o});return{version:T(r),type:n,branchName:l.branchName,prUrl:l.prUrl,jiraVersionUrl:c}},I=async()=>{let e=new Map,r=await Ie();if(!r)return e;try{let t=await ze(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},Ue=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},C=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",dn=e=>e.flatMap(r=>{let t=x(r);return t?[{branch:r,id:t,label:T(t)}]:[]}),re=e=>{try{return Y(H(e))}catch(r){throw new f(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},Rr=e=>{if(e===ln)return ln;let r=x(e);return r?T(r):e},$e=e=>e.flatMap(r=>{let t=x(r);return t?[T(t)]:[]}),_=e=>{let{branches:r,descriptions:t,types:o}=e,n=dn(r),s=Math.max(0,...n.map(i=>i.label.length));return n.map(({branch:i,id:c,label:l})=>{let d=o?o.get(i)||"regular":void 0,p=t.get(W(c)),u=" ".repeat(s-l.length+3),g=d?Ue(l,d,s):l;return p&&(g=d?`${g} ${p}`:`${l}${u}${p}`),{name:g,value:i}})};var pn=e=>e.map(r=>({pr:r,id:x(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>Tt(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),mn=async()=>{let e=await O`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await O`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName,createdAt`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],o=new Set;return t.filter(n=>o.has(n.headRefName)?!1:(o.add(n.headRefName),!0))},tt=async()=>{try{let e=await mn();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),rt.exit(1)),pn(e).map(r=>r.headRefName)}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),rt.exit(1)}},P=async()=>{try{let e=await mn();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),rt.exit(1)),pn(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),rt.exit(1)}},ot=async e=>{let{branch:r,body:t}=e;try{O.quiet=!0,await O`gh pr edit ${r} --body ${t}`,O.quiet=!1}catch(o){throw a.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},et=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=Et(r,o),i=Ge(o),c=Y(r),l=n&&n.trim()!==""?`${t}
|
|
81
|
-
|
|
82
|
-
${n}`:`${t}
|
|
83
|
-
`;try{O.quiet=!0,await O`git switch ${i}`,await O`git pull origin ${i}`,await O`git checkout -b ${c}`,await O`git push -u origin ${c}`,await O`git commit --allow-empty-message --allow-empty --message ''`,await O`git push origin ${c}`;let p=(await O`gh pr create --title ${s} --body ${l} --base ${i} --head ${c}`).stdout.trim();return await O`git switch ${i}`,O.quiet=!1,{branchName:c,prUrl:p}}catch(d){throw a.error({error:d,branchName:c},`Error creating release branch ${c}`),d}};var D=async e=>{let{operation:r,requiredBranch:t}=e;if(await $t())throw new f(void 0,{operation:r,remediation:"run this from the main repository checkout, not a linked git worktree",stderrExcerpt:"command run from inside a linked worktree"});if(t){let o=await jr();if(o!==t)throw new f(void 0,{operation:r,remediation:`switch to ${t} first (git switch ${t})`,stderrExcerpt:`current branch is "${o}", expected "${t}"`})}if(!await It())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};var nt=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev"),await D({operation:"merge dev into release branches",requiredBranch:"dev"});let n=(await P()).filter(p=>C(p.title)==="regular").map(p=>p.branch);if(n.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(JSON.stringify({successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0},null,2)),structuredContent:{successfulMerges:0,failedMerges:0,failedBranches:[],totalBranches:0}};let s=[];if(r)s=n;else{m.setInteractive();let p=await I();s=await $i({required:!0,message:"\u{1F33F} Select release branches",choices:_({branches:n,descriptions:p})})}s.length===n.length?m.addOption("--all",!0):m.addOption("--versions",$e(s));let c=t?!0:await Si({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||m.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),Ai.exit(0)),t||m.addOption("--yes",!0),U.quiet=!0,await U`git fetch origin`,await U`git switch dev`,await U`git pull origin dev`;let l=[];for(let p of s)await Ni(p)||l.push(p);if(U.quiet=!1,l.length>0){a.info(`
|
|
84
|
-
\u26A0\uFE0F ${l.length} branch(es) failed to merge automatically.
|
|
85
|
-
`),a.info("\u{1F4CB} Manual merge script for failed branches:");for(let p of l)a.info(`# Merge dev into ${p} and resolve conflicts if any
|
|
86
|
-
|
|
87
|
-
git switch ${p} && git pull origin ${p} && git merge origin/dev
|
|
88
|
-
git push origin ${p} && git switch dev
|
|
89
|
-
`);a.info(`\u2705 ${s.length-l.length}/${s.length} merges completed successfully.`)}else a.info(`\u2705 All merges completed successfully!
|
|
90
|
-
`);m.print();let d={successfulMerges:s.length-l.length,failedMerges:l.length,failedBranches:l,totalBranches:s.length};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}},Ni=async e=>{try{return await U`git switch ${e}`,await U`git pull origin ${e}`,await U`git merge origin/dev --no-edit`,await U`git push origin ${e}`,await U`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new f(r,{operation:`merge dev into ${e}`,remediation:"resolve conflicts manually or rerun after 'git fetch origin'"});return a.error({error:r,branch:e,msg:t.message}),await U`git reset --merge HEAD~1`,!1}},_i=w({name:"gh-merge-dev",description:"Merge origin/dev into every open regular (non-hotfix) release branch and push the result. Mutates local git state and the remote release branches. When invoked via MCP, pass all=true \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.",inputSchema:{all:He.boolean().optional().describe("Target every open regular release branch. Must be true for MCP calls (the interactive picker is unavailable without a TTY).")},outputSchema:{successfulMerges:He.number().describe("Number of successful merges"),failedMerges:He.number().describe("Number of failed merges"),failedBranches:He.array(He.string()).describe("List of branches that failed to merge"),totalBranches:He.number().describe("Total number of branches processed")},handler:nt});import Li from"@inquirer/confirm";import Wi from"@inquirer/select";import Bi from"node:process";import{z as Pr}from"zod";import{$ as L}from"zx";var un=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},br=e=>{if(e===null||typeof e!="object")return{message:String(e)};let r=e,t={};e instanceof Error?(t.name=e.name,t.message=e.message):typeof r.message=="string"&&(t.message=r.message);let o=r.exitCode;(typeof o=="number"||o===null)&&(t.exitCode=o);let n=un(r.stderr,500);n&&(t.stderr=n);let s=un(r.stdout,200);return s&&(t.stdout=s),t};import{$ as lo}from"zx";var Oi=/\bv(\d+\.\d+\.\d+)\b/g,V=e=>e.trim().replace(/\s+/g," ").replace(Oi,"$1");import{$ as fn}from"zx";var Se=async e=>{try{let r=(await fn`cmux list-workspaces`.quiet()).stdout,t=Fi(r,e);if(!t)return;await fn`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},Fi=(e,r)=>{let t=V(r);for(let o of e.split(`
|
|
91
|
-
`)){let n=o.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let s=n[1],i=n[2]?.trim()??"";if(V(i)===t)return s}};import{$ as ji}from"zx";var Ae=async()=>{try{let e=(await ji`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
|
|
92
|
-
`)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(V(n))}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as xr}from"zx";var Ne=async e=>{let{cwd:r,title:t}=e,o=(await xr`cmux workspace create --cwd ${r}`).stdout,n=Di(o),s=(await xr`cmux list-pane-surfaces --workspace ${n}`).stdout,i=Mi(s);await xr`cmux new-split right --workspace ${n} --surface ${i}`,await xr`cmux new-split down --workspace ${n} --surface ${i}`,t&&await xr`cmux workspace rename --workspace ${n} --title ${t}`},Mi=e=>{let r=e.match(/surface:\d+/);if(!r)throw new Error("cmux: could not locate initial surface in list-pane-surfaces output");return r[0]},Di=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in workspace create output");return r[0]};var J=e=>{let{repoName:r,branch:t}=e,o=x(t),n=o?T(o):t;return`${r} ${n}`};var Cr=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:n=!1}=e,s=await Promise.allSettled(r.map(async c=>{let l=`${t}/${c}`,d=J({repoName:o,branch:c});return await Se(d),await lo`git worktree remove ${l}`,c})),i=[];for(let[c,l]of s.entries())if(l.status==="fulfilled")i.push(l.value);else{let d=r[c],p=new f(l.reason,{operation:`remove worktree for ${d}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:l.reason,msg:p.message})}return n&&i.length===r.length&&(await lo`git worktree prune`,await lo`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var Ze=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:br(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},hn=async e=>{let r=await L`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},Vi=async e=>{let r=Fr(e),t=await L`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(s=>s.title===r)??null},gn=async()=>{let e=await L`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},Ji=async e=>{let r=re(e),t=await hn(r);if(!t)throw a.error(`\u274C No PR found for branch ${r}.`),new f(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},Ki=async()=>{let e=await P(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,C(i.title)]));m.setInteractive();let o=await I(),n=await Wi({message:"\u{1F33F} Select release branch",choices:_({branches:r,descriptions:o,types:t})}),s=e.find(i=>i.branch===n);if(!s)throw a.error(`\u274C Release branch ${n} not found in open PRs.`),new f(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},zi=async e=>{if(!(await A("release")).includes(e))return;let[t,o]=await Promise.all([R(),N()]),n=`${t}${M}`;if((await Cr({branches:[e],worktreeDir:n,repoName:o})).length===0)throw new f(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${n}/${e} (use --force if uncommitted changes)`})},qi=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await hn(r);if(!n)throw new f(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(n.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(n.state==="CLOSED")throw new f(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await Ze(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await L`gh pr merge ${r} --squash --admin --delete-branch`})},Gi=async e=>{let r=T(e),t=Fr(e),o=await gn();if(o){let s=o.number;return o.title!==t&&(a.info(`Adopting open dev \u2192 main PR #${s} ("${o.title}") and retitling for ${r}`),await Ze(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await L`gh pr edit ${s} --title ${t}`})),s}await Ze(`create RC PR (dev \u2192 main) for ${r}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await L`gh pr create --base main --head dev --title ${t} --body ""`});let n=await gn();if(!n)throw new f(void 0,{operation:`look up RC PR for ${r}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return n.number},Ui=async e=>{let r=T(e);if(await Vi(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Gi(e);await Ze(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await L`gh pr merge ${o} --squash --admin`})},Hi=async()=>{L.quiet=!1,await Ze("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await L`gh workflow run deploy-all.yml --ref main -f environment=prod`}),L.quiet=!0},Zi=async()=>{await Ze("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 L`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Xi=async e=>{try{await St(e)}catch(r){a.warn({err:br(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await At(e)}catch(r){a.warn({err:br(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},Yi=async e=>{let r=await Ie();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=W(e);await io({versionName:t},r)}catch(t){a.error({err:br(t)},"Failed to deliver Jira release (non-blocking)")}},st=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver"),await D({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await Ji(r):await Ki(),s=x(o);if(!s)throw new f(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=T(s);m.addOption("--version",i),a.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let c=C(n),l=t?!0:await Li({message:`Are you sure you want to deliver version ${o} to production?`});t||m.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),Bi.exit(0)),m.addOption("--yes",!0),L.quiet=!0,await zi(o),await qi({selectedReleaseBranch:o,releaseType:c}),c!=="hotfix"&&await Ui(s),await Hi(),await Zi(),await Xi(o),L.quiet=!1,await Yi(s),a.info(`Successfully delivered ${o} to production!`),m.print();let d={releaseBranch:o,version:i,type:c,success:!0};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}},Qi=w({name:"gh-release-deliver",description:'Deliver a release to production. For hotfixes: squash-merges the release branch to main and dispatches the deploy-all workflow. For regular releases: squash-merges to dev, opens an RC PR, merges dev into main, dispatches the deploy-all workflow, then syncs main back to dev. Also releases the matching Jira fix version if Jira is configured. Dispatches the deploy workflow fire-and-forget \u2014 the tool returns once the workflow is accepted by GitHub, not when the deployment finishes. PR-merge steps are idempotent: re-running after a partial failure skips PRs that are already merged. Irreversible production operation: the confirmation prompt is auto-skipped for MCP calls, so the caller is responsible for gating. "version" is required when invoked via MCP (the picker is unreachable without a TTY).',inputSchema:{version:Pr.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:Pr.string().describe("The release branch that was delivered"),version:Pr.string().describe("The version that was delivered"),type:Pr.enum(["regular","hotfix"]).describe("Release type"),success:Pr.boolean().describe("Whether the delivery was successful")},handler:st});import wn from"@inquirer/select";import{z as me}from"zod";import{$ as po}from"zx";var it=async e=>{let{version:r,env:t,skipTerraform:o}=e;m.start("release-deploy-all");let n="";if(r)n=r==="dev"?"dev":re(r);else{m.setInteractive();let d=await P(),p=d.map(k=>k.branch),u=new Map(d.map(k=>[k.branch,C(k.title)])),g=await I();n=await wn({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},..._({branches:p,descriptions:g,types:u})]})}let s=Rr(n);m.addOption("--version",s);let{environments:i}=await b(),c="";if(t?c=t:(m.setInteractive(),c=await wn({message:"\u{1F9EA} Select environment",choices:i.map(d=>({name:d,value:d}))})),m.addOption("--env",c),!i.includes(c))throw new f(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${i.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let l=o??!1;l&&m.addOption("--skip-terraform",!0);try{po.quiet=!0,await po`gh workflow run deploy-all.yml --ref ${n} -f environment=${c} ${l?["-f","skip_terraform_deploy=true"]:[]}`,po.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${c}`),m.print();let p={releaseBranch:n,version:s,environment:c,skipTerraformDeploy:l,success:!0};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}}catch(d){throw a.error({error:d},"\u274C Error launching workflow"),new f(d,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},ea=w({name:"gh-release-deploy-all",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. Both "version" and "env" are required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:me.string().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. Required for MCP calls.'),env:me.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:me.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:me.string().describe("The release branch that was deployed"),version:me.string().describe("The version that was deployed"),environment:me.string().describe("The environment deployed to"),skipTerraformDeploy:me.boolean().describe("Whether terraform deployment was skipped"),success:me.boolean().describe("Whether the deployment was successful")},handler:it});import ra from"@inquirer/checkbox";import kn from"@inquirer/select";import ta from"node:fs/promises";import{resolve as oa}from"node:path";import na from"yaml";import{z as K}from"zod";import{$ as mo}from"zx";var at=async e=>{let{version:r,env:t,services:o,skipTerraform:n}=e;m.start("release-deploy-selected");let s="";if(r)s=r==="dev"?"dev":re(r);else{m.setInteractive();let k=await P(),S=k.map(z=>z.branch),$=new Map(k.map(z=>[z.branch,C(z.title)])),F=await I();s=await kn({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},..._({branches:S,descriptions:F,types:$})]})}let i=Rr(s);m.addOption("--version",i);let{environments:c}=await b(),l="";if(t?l=t:(m.setInteractive(),l=await kn({message:"\u{1F9EA} Select environment",choices:c.map(k=>({name:k,value:k}))})),m.addOption("--env",l),!c.includes(l))throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${c.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let d=await sa();if(d.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let p=[];if(o&&o.length>0?p=o:(m.setInteractive(),p=await ra({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:d.map(k=>({name:k,value:k}))})),m.addOption("--services",p),p.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${d.join(", ")}`,stderrExcerpt:"no services selected"});let u=p.filter(k=>!d.includes(k));if(u.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${d.join(", ")}`,stderrExcerpt:`invalid services: ${u.join(", ")}`});let g=n??!1;g&&m.addOption("--skip-terraform",!0);try{mo.quiet=!0;let k=p.flatMap(F=>["-f",`${F}=true`]);await mo`gh workflow run deploy-selected-services.yml --ref ${s} -f environment=${l} ${k} ${g?["-f","skip_terraform_deploy=true"]:[]}`,mo.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${s}, environment: ${l}, services: ${p.join(", ")}`),m.print();let $={releaseBranch:s,version:i,environment:l,services:p,skipTerraformDeploy:g,success:!0};return{content:h(JSON.stringify($,null,2)),structuredContent:$}}catch(k){throw a.error({error:k},"\u274C Error launching workflow"),new f(k,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},sa=async()=>{let e=await R(),r=oa(e,".github/workflows/deploy-selected-services.yml"),t=await ta.readFile(r,"utf-8"),n=na.parse(t).on.workflow_dispatch.inputs,s=[];for(let[i,c]of Object.entries(n))c.type==="boolean"&&i!=="skip_terraform_deploy"&&s.push(i);return s},ia=w({name:"gh-release-deploy-selected",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. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:K.string().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. Required for MCP calls.'),env:K.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:K.array(K.string()).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"). Required for MCP calls.'),skipTerraform:K.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:K.string().describe("The release branch that was deployed"),version:K.string().describe("The version that was deployed"),environment:K.string().describe("The environment deployed to"),services:K.array(K.string()).describe("The services that were deployed"),skipTerraformDeploy:K.boolean().describe("Whether terraform deployment was skipped"),success:K.boolean().describe("Whether the deployment was successful")},handler:at});import{z as Xe}from"zod";var ct=async()=>{let r=(await P()).flatMap(i=>{let c=x(i.branch);return c?[{version:T(c),jiraKey:W(c),type:C(i.title)}]:[]}),t=await I(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let c=Ue(i.version,i.type,o),l=t.get(i.jiraKey);return l?`${c} ${l}`:c});a.info(`All release branches:
|
|
93
|
-
`),a.info(`
|
|
94
|
-
${n.join(`
|
|
95
|
-
`)}
|
|
96
|
-
`);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},aa=w({name:"gh-release-list",description:"List every open release PR with its version, type (regular / hotfix), and associated Jira fix-version description. Read-only; sourced from GitHub and Jira.",inputSchema:{},outputSchema:{releases:Xe.array(Xe.object({version:Xe.string().describe("Release version"),type:Xe.enum(["regular","hotfix"]).describe("Release type"),description:Xe.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:Xe.number().describe("Number of release branches")},handler:ct});import Cn from"@inquirer/confirm";import bn from"@inquirer/select";import pt from"node:process";import{z as E}from"zod";import{question as Co}from"zx";import{$ as dt}from"zx";var ue=e=>e.slice(1).split(".").map(Number),uo=e=>[...e].sort((r,t)=>{let[o,n,s]=ue(r),[i,c,l]=ue(t);return o!==i?(o??0)-(i??0):n!==c?(n??0)-(c??0):(s??0)-(l??0)});var yn="next",ca=/^v?(\d+)\.(\d+)\.(\d+)$/,la=e=>e.replace(/^.*release\//,""),go=e=>{let r=la(e.trim()),t=ca.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},vn=e=>`${e[0]}.${e[1]}.${e[2]}`,ho=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=go(n);if(!s)continue;let i=vn(s);o.has(i)||(o.add(i),t.push(s))}return uo(t.map(n=>vn(n))).map(n=>ue(`v${n}`))},_e=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},lt=(e,r)=>{if(e.length===0)throw new _e;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,c=e.reduce((l,d)=>d[0]===s&&d[1]===i?Math.max(l,d[2]):l,0);return`${s}.${i}.${c+1}`}let[o,n]=t;return`${o}.${n+1}.0`},wo=e=>e.trim().toLowerCase()===yn,da=e=>e==="regular"||e==="hotfix",Rn=e=>"name"in e,ko=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":"),o=r,n="regular",s="";if(t!==-1){o=r.slice(0,t).trim();let c=r.slice(t+1),l=c.indexOf(":"),d=l===-1?c.trim():c.slice(0,l).trim();s=l===-1?"":c.slice(l+1).trim();let p=d.toLowerCase();if(!da(p))throw new Error(`Invalid release type "${d}". Expected "regular" or "hotfix".`);n=p}if(wo(o)||go(o)!==null){let c={version:o,type:n};return s!==""&&(c.description=s),c}let i={name:o,type:n};return s!==""&&(i.description=s),i},vo=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},fo=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,pa=e=>{let r=e.name.trim();return we(r),fo({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},yo=(e,r)=>{let t=[...r];return e.map(o=>{if(Rn(o))return pa(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(wo(n)){let c=lt(t,o.type);return t.push(ue(`v${c}`)),fo({id:H(c),type:o.type},o.description)}let s=go(n);if(!s)throw new Error(`Invalid version "${n}". Expected semver like "1.2.5" or the token "next".`);let i=`${s[0]}.${s[1]}.${s[2]}`;return t.push(s),fo({id:H(i),type:o.type},o.description)})},Ro=e=>e.some(r=>!Rn(r)&&wo(r.version));var ma=e=>e.split(`
|
|
97
|
-
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:x(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),ua=async()=>{let e=dt.quiet;try{dt.quiet=!0;let r=await dt`git ls-remote --heads origin 'release/v*'`;return ma(r.stdout)}finally{dt.quiet=e}},fa=async()=>{let e=await Ie();return e?(await ze(e)).map(t=>t.name):[]},bo=async()=>{let[e,r]=await Promise.allSettled([ua(),fa()]);return e.status==="rejected"&&a.warn({error:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&a.warn({error:r.reason},"Failed to fetch Jira versions; continuing without them"),ho({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var ga='"1.2.5" or "next"',ha=(e,r)=>{try{return lt(e,r)}catch(t){if(t instanceof _e)return null;throw t}},xo=(e,r)=>{try{return yo(e,r)}catch(t){throw t instanceof _e?new f(t,{operation:"resolve release version",remediation:'pass an explicit version (e.g. "1.2.5") instead of "next" when there are no prior versions'}):t instanceof X?new f(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},wa=async(e,r)=>{let t=ha(e,r),o=t?` [${t}]`:"",n=(await Co(` Version (e.g. ${ga})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(a.error("No version provided. Exiting..."),pt.exit(1)),s},ka=async()=>{let e=(await Co(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(a.error("No name provided. Exiting..."),pt.exit(1));try{we(e)}catch(r){let t=r instanceof Error?r.message:String(r);a.error(`${t} Exiting...`),pt.exit(1)}return e},va=async e=>{m.setInteractive();let r=null,t=[],o=async()=>(r===null&&(r=await e(),t.push(...r)),t),n=[],s=!0;for(;s;){let i=n.length+1,c=await bn({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),l=await bn({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),d;if(c==="name"){let u=await ka();d=xo([{name:u,type:l}],[])[0]}else{let u=await wa(await o(),l);d=xo([{version:u,type:l}],t)[0],d.id.kind==="version"&&t.push(ue(`v${d.id.raw}`))}let p=(await Co(" Description (optional, press Enter to skip): ")).trim();n.push({...d,...p!==""?{description:p}:{}}),s=await Cn({message:"Add another release?",default:!1})}return n},ya=e=>{let t=[e.id.kind==="version"?`v${e.id.raw}`:e.id.name,e.type];return e.description&&t.push(e.description),t.join(" \xB7 ")},xn=e=>{for(let r of e)m.addOption("--release",vo(r))},Ra=async(e,r)=>{if(e&&e.length>0){let o=Ro(e)?await r():[],n=xo(e,o);return xn(n),n}let t=await va(r);return xn(t),t},ba=e=>{if(new Set(e.map(t=>t.type)).size>1)throw new f(void 0,{operation:"create release",remediation:"create regular and hotfix releases in separate invocations",stderrExcerpt:"mixed regular and hotfix releases in one batch are not supported"})},xa=async(e,r)=>{let t=e.map(ya).join(`
|
|
98
|
-
- `),o=r?!0:await Cn({message:`Create the following ${e.length} release(s)?
|
|
99
|
-
- ${t}
|
|
100
|
-
`});r||m.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),pt.exit(0)),m.addOption("--yes",!0)},Ca=async e=>{let{entry:r,jiraConfig:t}=e,o=T(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await ao(r.type);let s=await co({id:r.id,jiraConfig:t,description:r.description,type:r.type});return a.info(`\u2705 Successfully created release: ${n} (${r.type})`),a.info(`\u{1F517} GitHub PR: ${s.prUrl}`),a.info(`\u{1F517} Jira Version: ${s.jiraVersionUrl}
|
|
101
|
-
`),{result:s}}catch(s){let i=new f(s,{operation:`create release ${n} (${r.type})`,remediation:"verify the version or name is unique and the base branch is clean"});return a.error(`\u274C ${i.message}
|
|
102
|
-
`),{failure:{version:o,error:i.message}}}},Pa=(e,r,t)=>{r===e?a.info(`\u2705 All ${e} release branch(es) were created successfully.`):r>0?(a.warn(`\u26A0\uFE0F ${r} of ${e} release branches were created successfully.`),a.warn(`\u274C ${t} release(s) failed.`)):a.error(`\u274C All ${e} release branch(es) failed to create.`)},mt=async e=>{let{releases:r,confirmedCommand:t}=e;m.start("release-create");let o=await qe(),n=null,i=await Ra(r,async()=>(n===null&&(n=await bo()),n));if(i.length===0)throw new f(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});ba(i),await D({operation:"create release",requiredBranch:Ge(i[0].type)}),await xa(i,!!t);let c=[],l=[];for(let p of i){let{result:u,failure:g}=await Ca({entry:p,jiraConfig:o});u&&c.push(u),g&&l.push(g)}Pa(i.length,c.length,l.length),m.print();let d={createdBranches:c.map(p=>p.branchName),successCount:c.length,failureCount:l.length,releases:c,failedReleases:l};return{content:h(JSON.stringify(d,null,2)),structuredContent:d}},Ea=w({name:"release-create",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. Confirmation is auto-skipped for MCP calls, so the caller is responsible for gating. Continues on per-release failure and reports successes/failures.',inputSchema:{releases:E.array(E.object({version:E.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:E.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:E.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:E.string().optional().describe("Optional description for the Jira version.")}).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=>e.name!==void 0?{name:e.name,type:e.type,...e.description?{description:e.description}:{}}:{version:e.version,type:e.type,...e.description?{description:e.description}:{}})).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.')},outputSchema:{createdBranches:E.array(E.string()).describe("List of created release branch names"),successCount:E.number().describe("Number of releases created successfully"),failureCount:E.number().describe("Number of releases that failed"),releases:E.array(E.object({version:E.string().describe("Version number"),type:E.enum(["regular","hotfix"]).describe("Release type"),branchName:E.string().describe("Release branch name"),prUrl:E.string().describe("GitHub PR URL"),jiraVersionUrl:E.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:E.array(E.object({version:E.string().describe("Version number that failed"),error:E.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:mt});import Ta from"@inquirer/confirm";import Ia from"@inquirer/select";import $a from"node:process";import{z as fe}from"zod";import{question as Sa}from"zx";var Pn=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,Aa=(e,r)=>r.trim()!==""?`${e}
|
|
103
|
-
|
|
104
|
-
${r}`:`${e}
|
|
105
|
-
`,Na=async()=>{let e=await P(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,C(s.title)])),o=await I(),n=await Ia({message:"\u{1F33F} Select release branch",choices:_({branches:r,descriptions:o,types:t})});return{branch:n,type:t.get(n)||"regular"}},_a=async e=>{let t=(await P()).find(o=>o.branch===e);if(!t)throw new f(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return C(t.title)},Oa=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await Sa(` New description ${r}
|
|
106
|
-
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},ut=async e=>{let{version:r,description:t,confirmedCommand:o}=e;m.start("release-desc-edit");let n=await qe(),s;r?(s=re(r),await _a(s)):(m.setInteractive(),s=(await Na()).branch);let i=x(s);if(!i)throw new f(void 0,{operation:`edit description for ${s}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let c=T(i);m.addOption("--version",c);let l=W(i),d=await Yr(l,n);if(!d)throw new f(void 0,{operation:`edit description for ${l}`,remediation:`create the Jira fix version "${l}" first or pick a different release`});let p=d.description??"",u;if(t!==void 0?(u=t,m.addOption("--description",u)):(m.setInteractive(),u=await Oa(p)),u===p){a.info(`No change \u2014 description for ${l} is already: "${p}"`),m.print();let F={version:c,branch:s,jiraVersionUrl:Pn(n,d),previousDescription:p,newDescription:u,changed:!1};return{content:h(JSON.stringify(F,null,2)),structuredContent:F}}let g=o?!0:await Ta({message:`Update description for ${l}?
|
|
107
|
-
from: "${p}"
|
|
108
|
-
to: "${u}"
|
|
109
|
-
`});o||m.setInteractive(),g||(a.info("Operation cancelled. Exiting..."),$a.exit(0)),m.addOption("--yes",!0),await Qr({versionId:d.id,description:u},n);let k=Pn(n,d),S=Aa(k,u);await ot({branch:s,body:S}),a.info(`\u2705 Updated description for ${l}`),a.info(`\u{1F517} Jira Version: ${k}`),a.info(`\u{1F517} PR branch: ${s}
|
|
110
|
-
`),m.print();let $={version:c,branch:s,jiraVersionUrl:k,previousDescription:p,newDescription:u,changed:!0};return{content:h(JSON.stringify($,null,2)),structuredContent:$}},Fa=w({name:"release-desc-edit",description:"Edit a release's description in Jira and in the matching 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. Both `version` and `description` are required for MCP calls (the picker/prompt are unreachable without a TTY). Empty `description` clears the description on both sides. Confirmation is auto-skipped for MCP, so the caller is responsible for gating.",inputSchema:{version:fe.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:fe.string().describe("New description. Empty string clears the description.")},outputSchema:{version:fe.string().describe("Release version"),branch:fe.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:fe.string().describe("Jira fix version URL"),previousDescription:fe.string().describe("The description before the update"),newDescription:fe.string().describe("The description after the update"),changed:fe.boolean().describe("Whether the description actually changed")},handler:ut});import{z as ja}from"zod";var ft=async()=>{let e=Jr.version;a.info(e);let r={version:e};return{content:h(JSON.stringify(r,null,2)),structuredContent:r}},Ma=w({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:ja.string().describe("Installed infra-kit CLI version (from package.json)")},handler:ft});import Ja from"@inquirer/checkbox";import So from"@inquirer/confirm";import Ka from"node:process";import{z as oe}from"zod";import{$ as Ar}from"zx";import{$ as Va}from"zx";import En from"node:fs/promises";import gt from"node:path";var Er=async e=>{let{workspacePath:r,folderPaths:t}=e,o=gt.dirname(r),n;try{n=await En.readFile(r,"utf-8")}catch(p){throw new Error(`Cursor workspace file not found at ${r}: ${p.message}`)}let s;try{s=JSON.parse(n)}catch(p){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${p.message}`)}let i=s.folders??[],c=new Set(i.map(p=>gt.resolve(o,p.path))),l=[],d=[];for(let p of t){let u=gt.resolve(p);if(c.has(u)){d.push(p);continue}let g=gt.relative(o,u);i.push({path:g}),c.add(u),l.push(p)}return s.folders=i,await En.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
111
|
-
`,"utf-8"),{added:l,skipped:d}};import{$ as La}from"zx";import Da from"node:fs/promises";import wt from"node:path";import Tn from"node:fs/promises";import ht from"node:path";var Tr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=ht.dirname(r),n;try{n=await Tn.readFile(r,"utf-8")}catch(g){throw new Error(`Cursor workspace file not found at ${r}: ${g.message}`)}let s;try{s=JSON.parse(n)}catch(g){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${g.message}`)}let i=s.folders??[],c=new Set(t.map(g=>ht.resolve(g))),l=new Set,d=i.filter(g=>{let k=ht.resolve(o,g.path);return c.has(k)?(l.add(k),!1):!0});s.folders=d,await Tn.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
112
|
-
`,"utf-8");let p=[],u=[];for(let g of t){let k=ht.resolve(g);l.has(k)?p.push(g):u.push(g)}return{removed:p,notFound:u}};var Po=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=wt.dirname(r),s=wt.resolve(`${t}/release`),i=await Da.readFile(r,"utf-8"),l=JSON.parse(i).folders??[],d=new Set(o.map(S=>wt.resolve(`${t}/${S}`))),p=[];for(let S of l){let $=wt.resolve(n,S.path);($===s||$.startsWith(`${s}/`))&&!d.has($)&&p.push($)}let u=[];p.length>0&&(u=(await Tr({workspacePath:r,folderPaths:p})).removed);let g=o.map(S=>`${t}/${S}`),{added:k}=g.length>0?await Er({workspacePath:r,folderPaths:g}):{added:[]};return{added:k,removed:u}};import In from"node:path";var Oe=(e,r)=>In.isAbsolute(e)?e:In.resolve(r,e);var Eo=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,skipRelaunchWhenEmpty:n,cursorConfig:s}=e;if(!s.workspaceConfigPath)return a.warn("\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set."),{ran:!1,added:0,removed:0};let i=Oe(s.workspaceConfigPath,r);try{let{added:c,removed:l}=await Po({workspacePath:i,worktreeDir:t,currentBranches:o});return n&&o.length===0||await La`cursor ${i}`,{ran:!0,added:c.length,removed:l.length}}catch(c){return a.warn({error:c},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${i}`),{ran:!1,added:0,removed:0}}};import{$ as Wa}from"zx";var To=async e=>{let{folderPaths:r}=e;for(let t of r)await Wa`zed --add ${t}`;return{added:r}};import{$ as Ba}from"zx";var Io=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,skipRelaunchWhenEmpty:n}=e;if(n&&o.length===0)return{ran:!1,added:0,removed:0};let s=[r,...o.map(i=>`${t}/${i}`)];try{return await Ba`zed ${s}`,{ran:!0,added:o.length,removed:0}}catch(i){return a.warn({error:i},"\u26A0\uFE0F Failed to open Zed workspace"),{ran:!1,added:0,removed:0}}};var te=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var $o=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,n=await b(),s=q(n),i=o.map(l=>`${t}/${l}`),c=[];for(let l of s)switch(l.provider){case"cursor":{if(!l.config.workspaceConfigPath){a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),c.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let d=Oe(l.config.workspaceConfigPath,r),{added:p,skipped:u}=await Er({workspacePath:d,folderPaths:i}),g=u.length>0?` (${u.length} already present)`:"";a.info(`\u2705 Added ${p.length} folder(s) to ${d}${g}`),await Va`cursor ${d}`,c.push({ran:!0,provider:"cursor",added:p.length,skipped:u.length});break}case"zed":{let{added:d}=await To({folderPaths:i});a.info(`\u2705 Added ${d.length} folder(s) to Zed workspace`),c.push({ran:!0,provider:"zed",added:d.length,skipped:0});break}default:te(l)}return c};var Ir=async e=>{let r=await b(),t=q(r),o=[];for(let n of t)switch(n.provider){case"cursor":{let s=await Eo({...e,cursorConfig:n.config});o.push({...s,provider:"cursor"});break}case"zed":{let s=await Io(e);o.push({...s,provider:"zed"});break}default:te(n)}return o};var $r=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return te(e)}};var Sr=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e;if(o.length===0)return[];let n=await b(),s=q(n),i=o.map(l=>`${t}/${l}`),c=[];for(let l of s)switch(l.provider){case"cursor":{if(!l.config.workspaceConfigPath){c.push({provider:"cursor",supported:!0,removed:[]});break}let d=Oe(l.config.workspaceConfigPath,r);try{let{removed:p}=await Tr({workspacePath:d,folderPaths:i});p.length>0&&a.info(`\u2705 Removed ${p.length} folder(s) from ${d}`),c.push({provider:"cursor",supported:!0,removed:p})}catch(p){a.warn({error:p},`\u26A0\uFE0F Failed to update Cursor workspace at ${d}`),c.push({provider:"cursor",supported:!0,removed:[]})}break}case"zed":{a.info("\u2139\uFE0F Zed has no folder-remove CLI; close removed worktree folders in Zed manually if needed."),c.push({provider:"zed",supported:!1,removed:[]});break}default:te(l)}return c};var Fe=["workspace","none"];var za="feature",qa="release",kt=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:n,cmux:s}=e,i=e.ide??e.cursor;m.start("worktrees-add"),await D({operation:"create worktrees",requiredBranch:"dev"});try{let c=await A("release"),l=await R(),d=`${l}${M}`;await $n(`${d}/${qa}`),await $n(`${d}/${za}`);let p=[];if(o)p=o.split(",").map(ne=>Y(H(ne.trim())));else{let ne=await P(),er=ne.map(je=>je.branch);if(er.length===0)return a.info("\u2139\uFE0F No open release branches found"),m.print(),{content:h(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)p=er;else{m.setInteractive();let je=new Map(ne.map(_o=>[_o.branch,C(_o.title)])),_r=await I();p=await Ja({required:!0,message:"\u{1F33F} Select release branches",choices:_({branches:er,descriptions:_r,types:je})})}}t?m.addOption("--all",!0):m.addOption("--versions",$e(p));let u=r?!0:await So({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),Ka.exit(0)),r||m.addOption("--yes",!0);let g=await b(),k=i??(q(g).length>0?"workspace":"none");m.addOption("--ide",k);let S=n??g.worktrees?.openInGithubDesktop??await So({message:"Open created worktrees in GitHub Desktop?"});typeof n>"u"&&g.worktrees?.openInGithubDesktop===void 0&&m.setInteractive(),S?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let $=s??g.worktrees?.openInCmux??await So({message:"Open created worktrees in cmux?"});typeof s>"u"&&g.worktrees?.openInCmux===void 0&&m.setInteractive(),$?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:F}=Ga({selectedReleaseBranches:p,currentWorktrees:c}),z=await Ua(F,d);if(Ha(z),k==="workspace"&&await $o({projectRoot:l,worktreeDir:d,branches:z}),S)for(let ne of z)await Ar`github ${d}/${ne}`,await Ar`sleep 5`;if($){let ne=await N(),er=await Ae();for(let je of z){let _r=J({repoName:ne,branch:je});er.has(V(_r))||await Ne({cwd:`${d}/${je}`,title:_r})}}m.print();let No={createdWorktrees:z,count:z.length};return{content:h(JSON.stringify(No,null,2)),structuredContent:No}}catch(c){throw a.error({error:c},"\u274C Error managing worktrees"),new f(c,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},$n=async e=>{await Ar`mkdir -p ${e}`},Ga=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>ke(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},Ua=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Ar`git worktree add ${s} ${n}`,await Ar({cwd:s})`pnpm install`,n})),o=[];for(let[n,s]of t.entries())if(s.status==="fulfilled")o.push(s.value);else{let i=e[n],c=new f(s.reason,{operation:`git worktree add for ${i}`,remediation:"check the branch name and that the parent dir is writable"});a.error({error:s.reason,msg:c.message})}return o},Ha=e=>{if(e.length>0){a.info("\u2705 Created git worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No new git worktrees to create")},Za=w({name:"worktrees-add",description:'Create local git worktrees for release branches under the worktrees directory and run "pnpm install" in each. Mutates the local filesystem. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker and "open in Cursor / GitHub Desktop / cmux" follow-up prompts are unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls.',inputSchema:{all:oe.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:oe.string().optional().describe('Comma-separated release versions or names to target (e.g. "1.2.5, 1.2.6" or "checkout-redesign, 1.2.5"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.'),ide:oe.enum(Fe).optional().describe('Editor open mode for created worktrees, applied to all configured editors (Cursor and/or Zed, per the "ide" config). "workspace" (the only attach style) adds each worktree to every configured editor workspace and opens it. "none" skips the editor. Resolution order: this flag \u2192 "workspace" when at least one "ide" is configured \u2192 "none" otherwise.'),cursor:oe.enum(Fe).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:oe.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).'),cmux:oe.boolean().optional().describe('Open each created worktree in a new cmux workspace with a 3-pane layout (left-top, left-bottom, full-height right), all rooted at the worktree directory. Resolution order: this flag \u2192 "worktrees.openInCmux" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).')},outputSchema:{createdWorktrees:oe.array(oe.string()).describe("List of created git worktree branches"),count:oe.number().describe("Number of git worktrees created")},handler:kt});import{z as Ye}from"zod";var vt=async()=>{let e=await A("release");if(e.length===0)return a.info("\u2139\uFE0F No active worktrees found"),{content:h(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([P(),I()]),o=new Map(r.map(l=>[l.branch,C(l.title)])),n=e.flatMap(l=>{let d=x(l);if(!d)return[];let p=T(d),u=o.get(l)||"regular",g=t.get(W(d))||null;return[{version:p,type:u,description:g}]}),s=Math.max(...n.map(l=>l.version.length)),i=n.map(l=>{let d=Ue(l.version,l.type,s);return l.description?`${d} ${l.description}`:d});a.info("\u{1F33F} Active worktrees:"),a.info(`
|
|
113
|
-
${i.join(`
|
|
114
|
-
`)}
|
|
115
|
-
`);let c={worktrees:n,count:n.length};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},Xa=w({name:"worktrees-list",description:"List existing release-branch worktrees with version, release type (regular / hotfix), and Jira fix-version description. Read-only.",inputSchema:{},outputSchema:{worktrees:Ye.array(Ye.object({version:Ye.string().describe("Release version"),type:Ye.enum(["regular","hotfix"]).describe("Release type"),description:Ye.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Ye.number().describe("Number of worktrees")},handler:vt});import{z as ge}from"zod";var yt=async()=>{m.start("worktrees-open");try{let e=await R(),r=`${e}${M}`,t=await A("release"),o=await Ir({projectRoot:e,worktreeDir:r,currentBranches:t,skipRelaunchWhenEmpty:!1}),n=await Ya({worktreeDir:r,currentBranches:t}),s={openedCmux:n.opened,skippedCmux:n.skipped,ideProviders:o.filter(i=>i.ran).map(i=>i.provider),ideFoldersAdded:o.reduce((i,c)=>i+c.added,0),ideFoldersRemoved:o.reduce((i,c)=>i+c.removed,0)};return Qa(s,{ideRan:o.some(i=>i.ran),cmuxRan:n.ran}),m.print(),{content:h(JSON.stringify(s,null,2)),structuredContent:{...s}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),new f(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},Ya=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let o=await N(),n=await Ae(),s=[],i=[];for(let c of t){let l=J({repoName:o,branch:c});if(n.has(V(l))){i.push(l);continue}try{await Ne({cwd:`${r}/${c}`,title:l}),s.push(l)}catch(d){a.warn({error:d,title:l},`\u26A0\uFE0F Failed to open cmux workspace for ${c}`)}}return{ran:!0,opened:s,skipped:i}},Qa=(e,r)=>{if(r.ideRan){let t=e.ideProviders.map(o=>$r(o)).join(", ");e.ideFoldersAdded>0&&a.info(`\u2705 Added ${e.ideFoldersAdded} folder(s) to ${t} workspace(s)`),e.ideFoldersRemoved>0&&a.info(`\u{1F9F9} Removed ${e.ideFoldersRemoved} dangling folder(s) from ${t} workspace(s)`)}if(e.openedCmux.length>0){a.info("\u2705 Opened cmux workspaces:");for(let t of e.openedCmux)a.info(t)}e.skippedCmux.length>0&&a.info(`\u2139\uFE0F Skipped ${e.skippedCmux.length} cmux workspace(s) already open`),!r.ideRan&&e.openedCmux.length===0&&e.skippedCmux.length===0&&e.ideFoldersAdded===0&&e.ideFoldersRemoved===0&&a.info("\u2139\uFE0F Nothing to open")},ec=w({name:"worktrees-open",description:"Open every configured editor (Cursor and/or Zed) against its workspace and ensure a cmux workspace exists for each existing release worktree. Idempotent and additive \u2014 never removes worktrees, never recreates running cmux workspaces. Use after a cold start (editor + cmux closed). For stale-worktree cleanup, use worktrees-sync.",inputSchema:{},outputSchema:{openedCmux:ge.array(ge.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:ge.array(ge.string()).describe("Titles of cmux workspaces that were already open"),ideProviders:ge.array(ge.string()).describe("Configured IDE providers that were opened (cursor | zed); empty if none configured"),ideFoldersAdded:ge.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:ge.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:yt});import{z as he}from"zod";var Rt=async()=>{m.start("worktrees-reload");try{let e=await R(),r=`${e}${M}`,t=await A("release"),o=await N(),n=await rc({currentBranches:t,repoName:o}),[s,{opened:i}]=await Promise.all([Ir({projectRoot:e,worktreeDir:r,currentBranches:t,skipRelaunchWhenEmpty:!0}),tc({worktreeDir:r,currentBranches:t,repoName:o})]),c={closedCmux:n,openedCmux:i,ideProviders:s.filter(l=>l.ran).map(l=>l.provider),ideFoldersAdded:s.reduce((l,d)=>l+d.added,0),ideFoldersRemoved:s.reduce((l,d)=>l+d.removed,0)};return oc(c,{ideRan:s.some(l=>l.ran)}),m.print(),{content:h(JSON.stringify(c,null,2)),structuredContent:{...c}}}catch(e){throw a.error({error:e},"\u274C Error reloading worktrees"),new f(e,{operation:"reload worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},rc=async e=>{let{currentBranches:r,repoName:t}=e;if(r.length===0)return[];let o=await Ae(),n=[];for(let s of r){let i=J({repoName:t,branch:s});o.has(V(i))&&(await Se(i),n.push(i))}return n},tc=async e=>{let{worktreeDir:r,currentBranches:t,repoName:o}=e,n=[];for(let s of t){let i=J({repoName:o,branch:s});try{await Ne({cwd:`${r}/${s}`,title:i}),n.push(i)}catch(c){a.warn({error:c,title:i},`\u26A0\uFE0F Failed to reopen cmux workspace for ${s}`)}}return{opened:n}},oc=(e,r)=>{if(e.closedCmux.length>0&&a.info(`\u{1F9F9} Closed ${e.closedCmux.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>$r(o)).join(", ");e.ideFoldersAdded>0&&a.info(`\u2705 Added ${e.ideFoldersAdded} folder(s) to ${t} workspace(s)`),e.ideFoldersRemoved>0&&a.info(`\u{1F9F9} Removed ${e.ideFoldersRemoved} dangling folder(s) from ${t} workspace(s)`)}if(e.openedCmux.length>0){a.info("\u2705 Reopened cmux workspaces:");for(let t of e.openedCmux)a.info(t)}!r.ideRan&&e.closedCmux.length===0&&e.openedCmux.length===0&&e.ideFoldersAdded===0&&e.ideFoldersRemoved===0&&a.info("\u2139\uFE0F Nothing to reload")},nc=w({name:"worktrees-reload",description:"Close all open cmux workspaces for the current release worktrees, then reopen the full set. Disruptive \u2014 closes live cmux windows (unlike the additive worktrees-open). Every configured editor (Cursor and/or Zed) is reconciled + relaunched (no per-window close). Safe to run from any branch. Use to refresh stale windows after restarting cmux/the editor.",inputSchema:{},outputSchema:{closedCmux:he.array(he.string()).describe("Titles of cmux workspaces a close was attempted for (best-effort)"),openedCmux:he.array(he.string()).describe("Titles of cmux workspaces reopened during this run"),ideProviders:he.array(he.string()).describe("Configured IDE providers that were reloaded (cursor | zed); empty if none configured"),ideFoldersAdded:he.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:he.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:Rt});import sc from"@inquirer/checkbox";import ic from"@inquirer/confirm";import ac from"node:process";import{z as Nr}from"zod";var bt=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;m.start("worktrees-remove"),await D({operation:"remove worktrees",requiredBranch:"dev"});try{let n=await A("release");if(n.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await R(),i=`${s}${M}`,c=[];if(t)c=n;else if(o)c=o.split(",").map(k=>Y(H(k.trim())));else{m.setInteractive();let[k,S]=await Promise.all([I(),P()]),$=new Map(S.map(F=>[F.branch,C(F.title)]));c=await sc({required:!0,message:"\u{1F33F} Select release branches",choices:_({branches:n,descriptions:k,types:$})})}let l=c.length===n.length;l?m.addOption("--all",!0):m.addOption("--versions",$e(c));let d=r?!0:await ic({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),d||(a.info("Operation cancelled. Exiting..."),ac.exit(0)),r||m.addOption("--yes",!0);let p=await N(),u=await Cr({branches:c,worktreeDir:i,repoName:p,pruneFolder:l});await Sr({projectRoot:s,worktreeDir:i,branches:u}),cc(u),m.print();let g={removedWorktrees:u,count:u.length};return{content:h(JSON.stringify(g,null,2)),structuredContent:g}}catch(n){throw a.error({error:n},"\u274C Error managing worktrees"),new f(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},cc=e=>{if(e.length>0){a.info("\u274C Removed worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No unused worktrees to remove")},lc=w({name:"worktrees-remove",description:'Remove local git worktrees for release branches. When everything is removed, also runs "git worktree prune" and deletes the worktrees directory. When invoked via MCP, pass either "versions" (comma-separated) or all=true \u2014 the branch picker is unreachable without a TTY, and the CLI confirmation is auto-skipped for MCP calls, so the caller is responsible for gating.',inputSchema:{all:Nr.boolean().optional().describe('Remove every existing worktree. Either "all" or "versions" must be provided for MCP calls (the interactive picker is unavailable without a TTY). Ignored if "versions" is provided.'),versions:Nr.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.')},outputSchema:{removedWorktrees:Nr.array(Nr.string()).describe("List of removed git worktree branches"),count:Nr.number().describe("Number of git worktrees removed")},handler:bt});import dc from"@inquirer/confirm";import pc from"node:process";import{z as Ao}from"zod";import{$ as mc}from"zx";var xt=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync"),await D({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await A("release"),o=await R(),n=`${o}${M}`,s=await tt(),i=r?!0:await dc({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),pc.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:c}=uc({releasePRsList:s,currentWorktrees:t}),l=await N(),d=await fc({branches:c,worktreeDir:n,repoName:l});await Sr({projectRoot:o,worktreeDir:n,branches:d}),gc(d),m.print();let p={removedWorktrees:d,count:d.length};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new f(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},uc=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>ke(s)).filter(s=>!r.includes(s))}},fc=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,c=J({repoName:o,branch:s});await Se(c),await mc`git worktree remove ${i}`,n.push(s)}catch(i){let c=new f(i,{operation:`remove stale worktree for ${s}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:s,msg:c.message})}return n},gc=e=>{if(e.length>0){a.info("\u274C Removed worktrees:");for(let r of e)a.info(r);a.info("")}else a.info("\u2139\uFE0F No unused worktrees to remove")},hc=w({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.",inputSchema:{},outputSchema:{removedWorktrees:Ao.array(Ao.string()).describe("List of removed worktree branches"),count:Ao.number().describe("Number of worktrees removed during sync")},handler:xt});var y=new kc,vc=(e,r)=>[...r,e],Sn=(e,r)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&Fe.includes(e))return e;throw new Error(`Invalid ${r} value "${String(e)}". Expected one of: ${Fe.join(", ")}.`)}},An=async e=>{try{e?await y.parseAsync(e):await y.parseAsync()}catch(r){let t=r instanceof Error?r.message:String(r);a.error(t),Ct.exit(1)}};y.command("merge-dev").description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async e=>{await nt({all:e.all,confirmedCommand:e.yes})});y.command("release-list").description("List all release branches").action(async()=>{await ct()});y.command("release-create").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>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',vc,[]).option("-y, --yes","Skip confirmation prompt").action(async e=>{let t=e.release.map(ko),o=t.length>0?t:void 0;await mt({releases:o,confirmedCommand:e.yes})});y.command("release-desc-edit").description("Edit a release's description in Jira and 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("-y, --yes","Skip confirmation prompt").action(async e=>{await ut({version:e.version,description:e.description,confirmedCommand:e.yes})});y.command("release-deploy-all").description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await it({version:e.version,env:e.env,skipTerraform:e.skipTerraform})});y.command("release-deploy-selected").description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await at({version:e.version,env:e.env,services:e.services,skipTerraform:e.skipTerraform})});y.command("release-deliver").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 e=>{await st({version:e.version,confirmedCommand:e.yes})});y.command("worktrees-sync").description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async e=>{await xt({confirmedCommand:e.yes})});y.command("worktrees-add").description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async e=>{let r=Sn(e.ide,"--ide")??Sn(e.cursor,"--cursor");await kt({confirmedCommand:e.yes,all:e.all,versions:e.versions,ide:r,githubDesktop:e.githubDesktop,cmux:e.cmux})});y.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await vt()});y.command("worktrees-remove").description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async e=>{await bt({confirmedCommand:e.yes,all:e.all,versions:e.versions})});y.command("worktrees-open").description("Open the configured editor (Cursor/Zed) + cmux for existing release worktrees (cold-start restore)").action(async()=>{await yt()});y.command("worktrees-reload").description("Close all cmux/editor worktree windows, then reopen the current release worktrees").action(async()=>{await Rt()});var Nn=y.command("config").description("Manage infra-kit configuration files");Nn.command("path").description("Show the resolved config merge chain and file paths").action(async()=>{await Jt()});Nn.command("edit").description("Open the user-scope per-project override file in $EDITOR").action(async()=>{await Kt()});y.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)").action(async e=>{(await Dr({all:e.all,root:e.root})).structuredContent.allPassed||(Ct.exitCode=1)});y.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await zr()});y.command("version").description("Print the installed infra-kit CLI version").action(async()=>{await ft()});y.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await Xr()});y.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await Ur()});y.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{await Xt()});y.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async e=>{await Zr({config:e.config})});y.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await Gr()});if(Ct.argv.length<=2){let e=["merge-dev","release-list","release-create","release-desc-edit","release-deploy-all","release-deploy-selected","release-deliver"],r=["worktrees-add","worktrees-list","worktrees-open","worktrees-reload","worktrees-remove","worktrees-sync"],t=["audit","doctor","init","version","config","env-status","env-list","env-load","env-clear"],o=new Map(y.commands.map(l=>[l.name(),l])),n=[...e,...r,...t],s=Math.max(...n.map(l=>l.length)),i=l=>l.filter(d=>o.has(d)).map(d=>({name:`${d.padEnd(s)} ${o.get(d).description()}`,value:d})),c=await wc({message:"Select a command to run",choices:[new Qe(" "),new Qe("\u2014 Release Management \u2014"),...i(e),new Qe(" "),new Qe("\u2014 Worktrees \u2014"),...i(r),new Qe(" "),new Qe("\u2014 Environment \u2014"),...i(t)]},{output:Ct.stderr});await An(["node","infra-kit",c])}else await An();
|
|
17
|
+
`;import f from"node:fs";import A from"node:path";import E from"node:process";var to="autoload-warn.flag",F="autoload-fail.flag",ro=3e4,Pe=async(e=!0)=>{let o;try{o=await z()}catch{return null}let t=o.envAutoLoad;return t?o.environments.includes(t.config)?{trigger:t.trigger,config:t.config,project:o.envManagement.config.name}:(e&&De(`infra-kit: envAutoLoad.config "${t.config}" is not one of environments [${o.environments.join(", ")}] \u2014 env auto-load disabled.`),null):null},Te=e=>{let{trigger:o,expectedTrigger:t,targetConfig:r,targetProject:c,env:s}=e;return o!==t||!s.session||s.cleared||s.currentConfig&&!s.autoLoadedMarker||s.autoLoadedMarker&&s.currentConfig===r&&s.currentProject===c?"skip":"load"},S=async({expectedTrigger:e})=>{let o=e==="cli-invocation";try{let t=await Pe(o);if(!t||Te({trigger:t.trigger,expectedTrigger:e,targetConfig:t.config,targetProject:t.project,env:no()})==="skip"||io()||ao())return null;let c=await ae({config:t.config,autoLoaded:!0});return co(),c.filePath}catch(t){let r=t.message;return so(),o?De(`infra-kit: env auto-load failed \u2014 ${r} (will retry later)`):a.debug(`env auto-load skipped: ${r}`),null}},no=()=>({session:E.env[oe],cleared:E.env[ie],currentConfig:E.env[te],currentProject:E.env[re],autoLoadedMarker:E.env[ne]}),io=()=>{try{let e=C(),o=A.join(e,ee);if(!f.existsSync(o))return!1;let t=A.join(e,Z);return f.existsSync(t)?f.statSync(o).mtimeMs>=f.statSync(t).mtimeMs:!0}catch{return!1}},ao=()=>{try{let e=A.join(C(),F);return f.existsSync(e)?Date.now()-f.statSync(e).mtimeMs<ro:!1}catch{return!1}},so=()=>{try{let e=C();f.mkdirSync(e,{recursive:!0,mode:448}),f.writeFileSync(A.join(e,F),"",{mode:384})}catch{}},co=()=>{try{f.rmSync(A.join(C(),F),{force:!0})}catch{}},De=e=>{try{let o=C(),t=A.join(o,to);if(f.existsSync(t))return;f.mkdirSync(o,{recursive:!0,mode:448}),f.writeFileSync(t,"",{mode:384})}catch{}a.warn(e)};var V=async()=>{await S({expectedTrigger:"shell-startup"})};import G from"node:fs/promises";import J from"node:path";import Ie from"node:process";import{pathToFileURL as mo}from"node:url";var $e="~/projects",W=async(e={})=>{if(e.init){await po(e.cwd);return}await lo()},lo=async()=>{let e=D(),o=await h(e);if(a.info(`Factory config: ${u(e)} ${o?"[\u2713]":"[ ]"}`),!o){a.info("\nNot found \u2014 run `infra-kit vendor-config --init` to scaffold it."),Ie.exitCode=1;return}let{workspaceDir:t,targets:r}=await Q(),c=q(t),s=await h(c);a.info(`workspaceDir: ${t} (resolved: ${c}) ${s?"[\u2713 exists]":"[ ] not found"}`),a.info("Targets:");let l=s;for(let d of r){let g=J.join(c,d),p=await h(g);p||(l=!1);let v=p?"[\u2713]":"[ ]",y=p?"":" (not found \u2014 clone or remove)";a.info(` ${v} ${d} ${u(g)}${y}`)}l||(Ie.exitCode=1)},po=async e=>{let o=D();if(await h(o)){a.info(`Factory config already exists at ${u(o)} \u2014 leaving it untouched.`);return}let t=e??await U(),r=await fo(t);await G.mkdir(J.dirname(o),{recursive:!0}),await G.writeFile(o,uo(r),"utf-8"),a.info(`\u2713 Created ${u(o)}`),r.length>0&&a.info(` Seeded ${r.length} target(s) from the source ${$}.`),a.info(` Edit \`workspaceDir\` (placeholder: ${$e}) to point at where your repos live.`),r.length===0&&a.info(" Add at least one repo name to `targets` before running vendor sync/manifest/diff.")},fo=async e=>{try{let o=J.join(e,$),t=await G.stat(o),s=(await import(`${mo(o).href}?mtime=${Number(t.mtimeMs)}`)).default,l=typeof s=="function"?await s():s;if(l&&typeof l=="object"&&"targets"in l){let d=l.targets;if(Array.isArray(d)&&d.every(g=>typeof g=="string"))return d}}catch{}return[]},uo=e=>`${JSON.stringify({workspaceDir:$e,targets:e},null,2)}
|
|
18
|
+
`;import go from"node:process";var R={enabled:!1},i=(e,o=t=>{go.stdout.write(t)})=>(R.enabled&&e&&e.structuredContent!=null&&o(`${JSON.stringify(e.structuredContent,null,2)}
|
|
19
|
+
`),e),P=e=>{e.options.some(t=>t.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(P)};var K=(e,o=" ")=>{let t=e.reduce((r,[c])=>Math.max(r,c.length),0);return e.map(([r,c])=>`${r.padEnd(t)}${o}${c}`)};var n=new yo,ho=(e,o)=>[...o,e],H=e=>typeof e=="string"?e.split(",").filter(Boolean):void 0,_e=(e,o)=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&_.includes(e))return e;throw new Error(`Invalid ${o} value "${String(e)}". Expected one of: ${_.join(", ")}.`)}},Ne=async e=>{try{e?await n.parseAsync(e):await n.parseAsync()}catch(o){let t=o instanceof Error?o.message:String(o);a.error(t),w.exit(1)}},Oe={value:!1},m=(e,o)=>e.hook("preAction",()=>{Oe.value||a.warn(`"${e.name()}" is a deprecated alias; use "${o}" instead.`)}),Me=e=>e.description("Merge dev branch into every release branch").option("-a, --all","Select all active release branches").option("-y, --yes","Skip confirmation prompt").action(async o=>{i(await le({all:o.all,confirmedCommand:o.yes}))}),Fe=e=>e.description("List all release branches").action(async()=>{i(await ge())}),Ve=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>[:type[:description]]" (repeatable). The token is a semver ("1.2.5"), the literal "next", or a kebab-case name ("checkout-redesign"). Type is regular|hotfix (default regular). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend", "checkout-redesign:regular:Q3 redesign".',ho,[]).option("-y, --yes","Skip confirmation prompt").action(async o=>{let r=o.release.map(ve),c=r.length>0?r:void 0;i(await ye({releases:c,confirmedCommand:o.yes}))}),Ge=e=>e.description("Edit a release's description in Jira and 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("-y, --yes","Skip confirmation prompt").action(async o=>{i(await he({version:o.version,description:o.description,confirmedCommand:o.yes}))}),Je=e=>e.description("Deploy any release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async o=>{i(await fe({version:o.version,env:o.env,skipTerraform:o.skipTerraform,confirmedCommand:o.yes}))}),We=e=>e.description("Deploy selected services from release branch to any environment").option("-v, --version <version>",'Version (e.g. 1.2.5) or release name (e.g. checkout-redesign) to deploy; "dev" deploys from the dev branch').option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("-s, --services <services...>","Specify services to deploy, e.g. client-be client-fe").option("--skip-terraform","Skip terraform deployment step").option("-y, --yes","Skip confirmation prompt").action(async o=>{i(await ue({version:o.version,env:o.env,services:o.services,skipTerraform:o.skipTerraform,confirmedCommand:o.yes}))}),Ke=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 o=>{i(await pe({version:o.version,confirmedCommand:o.yes}))}),He=e=>e.description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async o=>{i(await be({confirmedCommand:o.yes}))}),Ue=e=>e.description("Add git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").option("-i, --ide [mode]","Editor mode for created worktrees: workspace (default) | none").option("--no-ide","Skip the editor (alias for --ide none)").option("-c, --cursor [mode]","Deprecated alias for --ide").option("--no-cursor","Deprecated alias for --no-ide").option("-g, --github-desktop","Open created worktrees in GitHub Desktop").option("--no-github-desktop","Skip GitHub Desktop prompt").option("-m, --cmux","Open created worktrees in cmux (3-pane layout)").option("--no-cmux","Skip cmux prompt").action(async o=>{let t=_e(o.ide,"--ide")??_e(o.cursor,"--cursor");i(await Ee({confirmedCommand:o.yes,all:o.all,versions:o.versions,ide:t,githubDesktop:o.githubDesktop,cmux:o.cmux}))}),Be=e=>e.description("List all git worktrees with detailed information").action(async()=>{i(await Se())}),ze=e=>e.description("Remove git worktrees for release branches").option("-y, --yes","Skip confirmation prompt").option("-a, --all","Select all active release branches").option("-v, --versions <versions>","Specify versions by comma, e.g. 1.2.5, 1.2.6").action(async o=>{i(await Le({confirmedCommand:o.yes,all:o.all,versions:o.versions}))}),Ye=e=>e.description("Close all cmux/editor worktree windows, then reopen the current release worktrees (also cold-start restore)").action(async()=>{i(await Re())}),qe=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 o=>{i(await W({init:o.init}))}),k=n.command("release").description("Release management commands");Me(k.command("merge-dev"));Fe(k.command("list"));Ve(k.command("create"));Ge(k.command("desc-edit"));Je(k.command("deploy-all"));We(k.command("deploy-selected"));Ke(k.command("deliver"));var L=n.command("worktrees").description("Git worktree management commands");Ue(L.command("add"));Be(L.command("list"));ze(L.command("remove"));He(L.command("sync"));Ye(L.command("reload"));m(Me(n.command("merge-dev")),"release merge-dev");m(Fe(n.command("release-list")),"release list");m(Ve(n.command("release-create")),"release create");m(Ge(n.command("release-desc-edit")),"release desc-edit");m(Je(n.command("release-deploy-all")),"release deploy-all");m(We(n.command("release-deploy-selected")),"release deploy-selected");m(Ke(n.command("release-deliver")),"release deliver");m(Ue(n.command("worktrees-add")),"worktrees add");m(Be(n.command("worktrees-list")),"worktrees list");m(ze(n.command("worktrees-remove")),"worktrees remove");m(He(n.command("worktrees-sync")),"worktrees sync");m(Ye(n.command("worktrees-reload")),"worktrees reload");var Qe=n.command("config").description("Manage infra-kit configuration files");Qe.command("path").description("Show the resolved config merge chain and file paths").action(async()=>{i(await O())});Qe.command("edit").description("Open the user-scope per-project override file in $EDITOR").action(async()=>{i(await M())});n.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)").action(async e=>{let o=await B({all:e.all,root:e.root});i(o),o.structuredContent.allPassed||(w.exitCode=1)});var b=n.command("vendor").description("Verify and sync the mirrored vendor/ tree");b.command("check").description("Verify vendor/ matches vendor/.sync-manifest.json (self-contained; for any consumer repo)").action(async()=>{let e=await we();i(e),e.structuredContent.ok||(w.exitCode=1)});b.command("sync").description("Copy vendored files from the source repo into each target and regenerate manifests").option("-y, --yes","Skip confirmation prompt").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async e=>{i(await Ae({confirmedCommand:e.yes,repos:H(e.repos)}))});b.command("manifest").description("Regenerate each target vendor/.sync-manifest.json + README from current content (no copy)").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async e=>{i(await Ce({confirmedCommand:!0,repos:H(e.repos)}))});b.command("diff").description("Source-aware drift check (rsync dry-run) of each target vendored subtree vs the source").option("-r, --repos <repos>","Restrict to comma-separated target repo names").action(async e=>{let o=await ke({repos:H(e.repos)});i(o),o.structuredContent.ok||(w.exitCode=1)});qe(b.command("config"));m(qe(n.command("vendor-config")),"vendor config");n.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{i(await X())});n.command("version").description("Print the installed infra-kit CLI version").action(async()=>{i(await xe())});n.command("env-status").description("Show which env is loaded in this session (local introspection; no Doppler call)").action(async()=>{i(await me())});n.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{i(await de())});n.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{i(await I())});n.command("env-load").description("Load Doppler env vars for a config. Source the returned file path to apply.").option("-c, --config <config>","Environment config name to load (e.g. dev, arthur)").action(async e=>{i(await se({config:e.config}))});n.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{i(await ce())});n.command("env-autoload",{hidden:!0}).description("Internal: prime env for the shell-startup auto-load trigger").action(async()=>{await V()});n.commands.forEach(P);var wo=e=>e.startsWith("env-")||e==="init"||e==="doctor"||e==="version";n.hook("preAction",async(e,o)=>{R.enabled=!!o.optsWithGlobals().json,R.enabled&&(a.level="warn"),wo(o.name())||await S({expectedTrigger:"cli-invocation"})});if(w.argv.length<=2){let e=j("release"),o=j("worktrees"),t=j("environment"),r=new Map(n.commands.map(d=>[d.name(),d])),s=[{label:"Release Management",names:e},{label:"Worktrees",names:o},{label:"Environment",names:t}].flatMap(({label:d,names:g})=>g.filter(p=>r.has(p)).map(p=>({name:p,description:r.get(p).description(),group:d}))),l;if(w.stdout.isTTY&&w.stdin.isTTY){let{runCommandPalette:d}=await import("./boot-K4QUAFSP.js");l=await d(s)}else{let d=K(s.map(v=>[v.name,v.description])),g=new Map;s.forEach((v,y)=>{g.set(v.name,d[y]??v.name)});let p=v=>v.filter(y=>r.has(y)).map(y=>({name:g.get(y)??y,value:y}));l=await vo({message:"Select a command to run",choices:[new x(" "),new x("\u2014 Release Management \u2014"),...p(e),new x(" "),new x("\u2014 Worktrees \u2014"),...p(o),new x(" "),new x("\u2014 Environment \u2014"),...p(t)]},{output:w.stderr})}l&&(Oe.value=!0,await Ne(["node","infra-kit",l]))}else await Ne();
|
|
116
20
|
//# sourceMappingURL=cli.js.map
|