infra-kit 0.1.102 → 0.1.107
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-0a58307d-2a37-4c69-851c-83a646502d62.jsonl +1 -0
- package/.omc/state/agent-replay-11c41aa0-51fa-49e1-a1dc-26dcd6ac26cc.jsonl +16 -0
- package/.omc/state/agent-replay-4cf1c186-81b2-497c-b002-d7f84e7839f3.jsonl +9 -0
- package/.omc/state/agent-replay-5c4ab554-64f1-42ae-83e3-21e0237e955c.jsonl +11 -0
- package/.omc/state/agent-replay-a60ac2ec-afbd-449f-a540-6df287392fc2.jsonl +1 -0
- package/.omc/state/agent-replay-afc6290b-40d3-4bef-b3b6-14484c034ab9.jsonl +14 -0
- package/.omc/state/agent-replay-be37e426-6fc8-47f4-8178-221c8494551c.jsonl +3 -0
- package/.omc/state/agent-replay-c967c819-3d1c-447b-ab48-56a8448ef9f8.jsonl +2 -0
- package/.omc/state/agent-replay-e947a3c6-989d-4a60-91dd-6b0ddd827b2d.jsonl +3 -0
- package/.omc/state/idle-notif-cooldown.json +3 -0
- package/.omc/state/last-tool-error.json +4 -4
- package/.omc/state/mission-state.json +53 -0
- package/.omc/state/sessions/0a58307d-2a37-4c69-851c-83a646502d62/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/0a58307d-2a37-4c69-851c-83a646502d62/subagent-tracking-state.json +7 -0
- package/.omc/state/sessions/11c41aa0-51fa-49e1-a1dc-26dcd6ac26cc/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/11c41aa0-51fa-49e1-a1dc-26dcd6ac26cc/mission-state.json +117 -0
- package/.omc/state/sessions/11c41aa0-51fa-49e1-a1dc-26dcd6ac26cc/pre-tool-advisory-throttle.json +42 -0
- package/.omc/state/sessions/11c41aa0-51fa-49e1-a1dc-26dcd6ac26cc/subagent-tracking-state.json +53 -0
- package/.omc/state/sessions/4cf1c186-81b2-497c-b002-d7f84e7839f3/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/4cf1c186-81b2-497c-b002-d7f84e7839f3/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/4cf1c186-81b2-497c-b002-d7f84e7839f3/subagent-tracking-state.json +7 -0
- package/.omc/state/sessions/5c4ab554-64f1-42ae-83e3-21e0237e955c/mission-state.json +117 -0
- package/.omc/state/sessions/5c4ab554-64f1-42ae-83e3-21e0237e955c/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/5c4ab554-64f1-42ae-83e3-21e0237e955c/subagent-tracking-state.json +17 -0
- package/.omc/state/sessions/a60ac2ec-afbd-449f-a540-6df287392fc2/pre-tool-advisory-throttle.json +18 -0
- package/.omc/state/sessions/a60ac2ec-afbd-449f-a540-6df287392fc2/subagent-tracking-state.json +7 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/mission-state.json +89 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/pre-tool-advisory-throttle.json +34 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/ralph-state.json +13 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/skill-active-state.json +15 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/subagent-tracking-state.json +35 -0
- package/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/ultrawork-state.json +11 -0
- package/.omc/state/sessions/c967c819-3d1c-447b-ab48-56a8448ef9f8/pre-tool-advisory-throttle.json +10 -0
- package/.omc/state/sessions/c967c819-3d1c-447b-ab48-56a8448ef9f8/subagent-tracking-state.json +7 -0
- package/.omc/state/sessions/e947a3c6-989d-4a60-91dd-6b0ddd827b2d/last-tool-error-state.json +7 -0
- package/.omc/state/sessions/e947a3c6-989d-4a60-91dd-6b0ddd827b2d/pre-tool-advisory-throttle.json +10 -0
- package/.omc/state/sessions/e947a3c6-989d-4a60-91dd-6b0ddd827b2d/subagent-tracking-state.json +26 -0
- package/.omc/state/subagent-tracking.json +14 -4
- package/.turbo/turbo-build.log +7 -0
- package/.turbo/turbo-check.log +14 -0
- package/.turbo/turbo-prettier-fix.log +2 -1
- package/.turbo/turbo-test.log +28 -5
- package/.turbo/turbo-validate.log +14 -0
- package/dist/cli.js +88 -74
- package/dist/cli.js.map +4 -4
- package/dist/entry/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +7 -0
- package/dist/lib/package-config/package-config.d.ts +71 -0
- package/dist/mcp.js +43 -41
- package/dist/mcp.js.map +4 -4
- package/eslint.config.js +1 -1
- package/infra-kit.config.ts +5 -0
- package/package.json +20 -13
- package/scripts/build.js +32 -3
- package/src/.omc/state/sessions/0a58307d-2a37-4c69-851c-83a646502d62/pre-tool-advisory-throttle.json +18 -0
- package/src/commands/.omc/state/sessions/afc6290b-40d3-4bef-b3b6-14484c034ab9/pre-tool-advisory-throttle.json +14 -0
- package/src/commands/.omc/state/sessions/c967c819-3d1c-447b-ab48-56a8448ef9f8/pre-tool-advisory-throttle.json +18 -0
- package/src/commands/audit/__tests__/audit.test.ts +59 -0
- package/src/commands/audit/audit.ts +177 -0
- package/src/commands/audit/index.ts +1 -0
- package/src/commands/config/config.ts +49 -7
- package/src/commands/doctor/__tests__/agent-files.test.ts +110 -0
- package/src/commands/doctor/doctor.ts +69 -4
- package/src/commands/env-clear/env-clear.ts +1 -1
- package/src/commands/env-list/env-list.ts +3 -3
- package/src/commands/env-load/env-load.ts +1 -1
- package/src/commands/env-status/env-status.ts +1 -1
- package/src/commands/gh-merge-dev/gh-merge-dev.ts +3 -8
- package/src/commands/gh-release-deliver/gh-release-deliver.ts +47 -21
- package/src/commands/gh-release-deploy-all/gh-release-deploy-all.ts +13 -7
- package/src/commands/gh-release-deploy-selected/gh-release-deploy-selected.ts +12 -6
- package/src/commands/gh-release-list/gh-release-list.ts +19 -8
- package/src/commands/init/__tests__/agent-files.test.ts +147 -0
- package/src/commands/init/__tests__/migrate-config.test.ts +160 -0
- package/src/commands/init/agent-files.ts +199 -0
- package/src/commands/init/index.ts +7 -0
- package/src/commands/init/init.ts +82 -60
- package/src/commands/init/migrate-config.ts +146 -0
- package/src/commands/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
- package/src/commands/release-create/__tests__/release-create.test.ts +55 -0
- package/src/commands/release-create/release-create.ts +142 -38
- package/src/commands/release-desc-edit/release-desc-edit.ts +28 -8
- package/src/commands/version/version.ts +1 -1
- package/src/commands/worktrees-add/worktrees-add.ts +7 -12
- package/src/commands/worktrees-list/worktrees-list.ts +13 -5
- package/src/commands/worktrees-open/worktrees-open.ts +1 -1
- package/src/commands/worktrees-remove/worktrees-remove.ts +6 -10
- package/src/commands/worktrees-sync/worktrees-sync.ts +3 -5
- package/src/entry/cli.ts +50 -7
- package/src/entry/index.ts +5 -0
- package/src/integrations/cmux/open-workspace-with-layout.ts +4 -4
- package/src/integrations/cmux/workspace-title.ts +10 -4
- package/src/integrations/doppler/doppler-project.ts +1 -1
- package/src/integrations/gh/gh-release-prs/__tests__/gh-release-prs.test.ts +115 -0
- package/src/integrations/gh/gh-release-prs/gh-release-prs.ts +49 -32
- package/src/lib/.omc/state/sessions/a60ac2ec-afbd-449f-a540-6df287392fc2/pre-tool-advisory-throttle.json +14 -0
- package/src/lib/constants/index.ts +15 -0
- package/src/lib/git-utils/__tests__/git-utils.test.ts +49 -0
- package/src/lib/git-utils/git-utils.ts +3 -1
- package/src/lib/infra-kit-config/__tests__/infra-kit-config.test.ts +270 -0
- package/src/lib/infra-kit-config/index.ts +7 -1
- package/src/lib/infra-kit-config/infra-kit-config.ts +46 -28
- package/src/lib/managed-block/__tests__/managed-block.test.ts +121 -0
- package/src/lib/managed-block/index.ts +8 -0
- package/src/lib/managed-block/managed-block.ts +145 -0
- package/src/lib/package-config/__tests__/package-config.test.ts +95 -0
- package/src/lib/package-config/index.ts +3 -0
- package/src/lib/package-config/package-config-schema.ts +19 -0
- package/src/lib/package-config/package-config.ts +99 -0
- package/src/lib/package-validator/__tests__/package-validator.test.ts +263 -0
- package/src/lib/package-validator/checks/__tests__/checks.test.ts +130 -0
- package/src/lib/package-validator/checks/config-check.ts +30 -0
- package/src/lib/package-validator/checks/files-check.ts +29 -0
- package/src/lib/package-validator/checks/index.ts +4 -0
- package/src/lib/package-validator/checks/scripts-check.ts +23 -0
- package/src/lib/package-validator/checks/turbo-check.ts +47 -0
- package/src/lib/package-validator/fs-utils.ts +18 -0
- package/src/lib/package-validator/index.ts +3 -0
- package/src/lib/package-validator/loader/config-loader.ts +77 -0
- package/src/lib/package-validator/loader/index.ts +2 -0
- package/src/lib/package-validator/loader/package-discovery.ts +98 -0
- package/src/lib/package-validator/package-validator.ts +48 -0
- package/src/lib/package-validator/types.ts +15 -0
- package/src/lib/release-id/__tests__/release-id.test.ts +351 -0
- package/src/lib/release-id/__tests__/versioned-regression.test.ts +69 -0
- package/src/lib/release-id/index.ts +15 -0
- package/src/lib/release-id/release-id.ts +257 -0
- package/src/lib/release-utils/__tests__/release-utils.test.ts +122 -0
- package/src/lib/release-utils/index.ts +4 -0
- package/src/lib/release-utils/release-utils.ts +85 -17
- package/src/lib/version-utils/__tests__/load-existing-versions.test.ts +37 -0
- package/src/lib/version-utils/__tests__/next-version.test.ts +119 -13
- package/src/lib/version-utils/index.ts +3 -0
- package/src/lib/version-utils/load-existing-versions.ts +29 -10
- package/src/lib/version-utils/next-version.ts +67 -12
- package/src/lib/version-utils/version-utils.ts +13 -4
- package/src/mcp/tools/index.ts +2 -0
- package/src/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
- package/src/types.ts +1 -1
- package/tsconfig.tsbuildinfo +1 -1
- package/src/lib/__tests__/infra-kit-config.test.ts +0 -231
- /package/src/integrations/{clickup → linear}/.gitkeep +0 -0
- /package/src/lib/{__tests__ → constants/__tests__}/constants.test.ts +0 -0
- /package/src/lib/{constants.ts → constants/constants.ts} +0 -0
package/dist/cli.js
CHANGED
|
@@ -1,94 +1,108 @@
|
|
|
1
|
-
import
|
|
2
|
-
`).filter(Boolean),o={release:
|
|
1
|
+
import Wa,{Separator as Ge}from"@inquirer/select";import{Command as Va}from"commander";import dt from"node:process";import ze from"node:path";import Mn from"node:process";import{z as L}from"zod";import wn from"node:path";import{$ as ho}from"zx";var dn=/^v?(\d+)\.(\d+)\.(\d+)$/,un=/^(\d+)\.(\d+)\.(\d+)$/,fn=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,gn="release/",ut="release/v",ft="release/n/",po="refs/heads/",hn="next";var mo=new Set(["dev","main","next","hotfix","regular","release"]),U=class extends Error{constructor(r){super(r),this.name="InvalidReleaseNameError"}},$e=class extends Error{constructor(r){super(r),this.name="InvalidReleaseRefError"}},fo=e=>e.startsWith(po)?e.slice(po.length):e,go=(e,r,t)=>({kind:"version",semver:{major:e,minor:r,patch:t},raw:`${e}.${r}.${t}`}),me=e=>{if(e.length===0)throw new U('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new U(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!fn.test(e))throw new U(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(mo.has(e))throw new U(`Release name "${e}" is reserved. Reserved names: ${[...mo].join(", ")}.`)},R=e=>{let r=fo(e.trim());if(r.startsWith(ut)){let t=r.slice(ut.length),o=un.exec(t);return o?go(Number(o[1]),Number(o[2]),Number(o[3])):null}if(r.startsWith(ft)){let t=r.slice(ft.length);try{me(t)}catch{return null}return{kind:"name",name:t,raw:t}}return null},G=e=>{let r=e.trim();if(fo(r).startsWith(gn)){let n=R(r);if(!n)throw new $e(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/n/<name> ref.`);return n}let o=dn.exec(r);if(o)return go(Number(o[1]),Number(o[2]),Number(o[3]));if(r.toLowerCase()===hn)throw new $e('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{me(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new $e(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:r,raw:r}},q=e=>e.kind==="version"?`${ut}${e.raw}`:`${ft}${e.name}`,gt=(e,r)=>{let t=r==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${t} v${e.raw}`:`${t} ${e.name}`},Pr=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,D=e=>e.kind==="version"?`v${e.raw}`:e.name,T=e=>e.raw,de=e=>e==null?!1:R(e)!==null,uo=e=>{if(e===void 0)return null;let r=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(r)?null:r},ht=(e,r,t)=>{if(e.kind==="version"&&r.kind==="version")return e.semver.major!==r.semver.major?e.semver.major-r.semver.major:e.semver.minor!==r.semver.minor?e.semver.minor-r.semver.minor:e.semver.patch-r.semver.patch;if(e.kind==="version")return-1;if(r.kind==="version")return 1;let o=uo(t?.a),n=uo(t?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<r.name?-1:e.name>r.name?1:0};var j=async e=>{let t=(await ho`git worktree list`).stdout.split(`
|
|
2
|
+
`).filter(Boolean),o={release:vn,feature:kn};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},vn=e=>{let r=wo(e);return de(r)?r:null},kn=e=>{let r=wo(e);return r?.startsWith("feature/")?r:null},b=async()=>(await ho`git rev-parse --show-toplevel`).stdout.trim(),F=async()=>{let e=await b();return wn.basename(e)};import yn from"node:process";import Rn from"pino";import bn from"pino-pretty";var xn=()=>{let e=yn.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Rn({level:e},bn({destination:2,ignore:r.join(","),colorize:!0}))},a=xn();var Q={requiredScripts:["build","ts-check","eslint-check","prettier-check","test"],requiredFiles:["tsconfig.json","eslint.config.js","readme.md"],turboTasks:[]},wt={requiredScripts:["build","dev","test","qa","check","fix"],requiredFiles:["turbo.json","pnpm-workspace.yaml"],turboTasks:["build","test","ts-check","eslint-check","prettier-check","check"]},vt=(e,r=Q)=>({requiredScripts:e.requiredScripts??[...r.requiredScripts],requiredFiles:e.requiredFiles??[...r.requiredFiles],turboTasks:e.turbo?.requiredTasks??[...r.turboTasks]});import{z as ee}from"zod";var kt=ee.strictObject({requiredScripts:ee.array(ee.string().min(1)).optional(),requiredFiles:ee.array(ee.string().min(1)).optional(),turbo:ee.strictObject({requiredTasks:ee.array(ee.string().min(1)).optional()}).optional()});import Cn from"node:fs/promises";var z=async e=>{try{return await Cn.access(e),!0}catch{return!1}};import Fn from"node:path";import vo from"node:fs/promises";import ko from"node:path";import{pathToFileURL as Pn}from"node:url";import{z as En}from"zod";var re="infra-kit.config.ts",yt=async e=>{try{let r=await vo.readFile(ko.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},Ue=async(e,r=Q)=>{let t=ko.join(e,re);if(!await z(t))throw new Error(`${re} not found at ${t}`);let o=await vo.stat(t),i=(await import(`${Pn(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${re} at ${t} has no default export`);let l=typeof i=="function"?await i():i,c=kt.safeParse(l);if(!c.success)throw new Error(`Invalid ${re} at ${t}: ${En.prettifyError(c.error)}`);return vt(c.data,r)};import yo from"node:fs/promises";import Er from"node:path";import Tn from"yaml";var $n="pnpm-workspace.yaml",Sn=async e=>(await yo.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Er.join(e,t.name)),In=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await Sn(o));continue}let n=Er.join(o,r);await z(n)&&t.push(n)}return t},An=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await In(t,o);return t},qe=async e=>{let r=await yo.readFile(Er.join(e,$n),"utf-8"),o=((Tn.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await An(e,s);for(let l of i)await z(Er.join(l,"package.json"))&&n.add(l)}return[...n].sort()};var Rt=async(e,r=Q)=>{try{let t=await Ue(e,r);return{check:{name:re,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:re,status:"fail",message:t.message},rules:null}}};import Nn from"node:fs/promises";import _n from"node:path";var bt=async(e,r)=>Promise.all(r.map(async t=>{let o=await Nn.stat(_n.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 xt=(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 On from"node:fs/promises";import jn from"node:path";var Se="turbo.json",Ct=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await On.readFile(jn.join(e,Se),"utf-8");t=JSON.parse(n)}catch(n){return[{name:Se,status:"fail",message:`cannot read/parse ${Se}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:Se,status:"fail",message:`no "tasks" object defined in ${Se}`}]: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 ${Se}`}})};var Pt=async(e,r=Q)=>{let t=await yt(e),o=t.name??Fn.basename(e),{check:n,rules:s}=await Rt(e,r),i=[n];s&&(i.push(...xt(t.scripts??{},s.requiredScripts)),i.push(...await bt(e,s.requiredFiles)),i.push(...await Ct(e,s.turboTasks)));let l=i.every(c=>c.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:l}};var h=e=>[{type:"text",text:e}],v=e=>e;var Dn=async e=>{let r=ze.resolve(e);for(;r!==ze.dirname(r);){if(await z(ze.join(r,"package.json")))return r;r=ze.dirname(r)}if(await z(ze.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Ln=async e=>e.root?[{dir:await b(),baseline:wt}]:e.all?(await qe(await b())).map(t=>({dir:t})):[{dir:await Dn(e.cwd??Mn.cwd())}],Wn=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}`)}},Tr=async(e={})=>{let r=await Ln(e),t=[];for(let s of r)t.push(await Pt(s.dir,s.baseline));for(let s of t)Wn(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}},Vn={all:L.boolean().optional().describe("Audit every non-vendor workspace package"),root:L.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Jn={allPassed:L.boolean().describe("Whether every audited package passed all checks"),packages:L.array(L.object({name:L.string(),passed:L.boolean(),checks:L.array(L.object({name:L.string(),status:L.enum(["pass","fail"]),message:L.string()}))})).describe("Per-package check results")},Bn=v({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:Vn,outputSchema:Jn,handler:e=>Tr({all:e.all,root:e.root})});import Sr from"node:fs/promises";import ss from"node:os";import is from"node:path";import bo from"node:process";import{$ as as}from"zx";import Tt from"node:fs/promises";import Kn from"node:os";import $r from"node:path";import{z as k}from"zod";var Ro="infra-kit.json",Gn=".infra-kit",Un="config.json",qn="projects",zn=k.object({provider:k.literal("doppler"),config:k.object({name:k.string().min(1)})}),Hn=k.discriminatedUnion("provider",[zn]),Xn=k.object({mode:k.enum(["workspace","windows"]).default("workspace"),workspaceConfigPath:k.string().min(1).optional()}).refine(e=>e.mode!=="workspace"||!!e.workspaceConfigPath,{message:'workspaceConfigPath is required when mode is "workspace"',path:["workspaceConfigPath"]}),Yn=k.object({provider:k.literal("cursor"),config:Xn}),Zn=k.discriminatedUnion("provider",[Yn]),Qn=k.object({provider:k.literal("jira"),config:k.object({baseUrl:k.string().url(),projectId:k.number().int().positive()})}),es=k.discriminatedUnion("provider",[Qn]),rs=k.object({openInGithubDesktop:k.boolean().optional(),openInCmux:k.boolean().optional()}),He=k.object({environments:k.array(k.string().min(1)).min(1),envManagement:Hn,ide:Zn.optional(),taskManager:es.optional(),worktrees:rs.optional()}),Xe=He.partial(),Ie=null,W=async()=>{let e=await b(),r=await F(),t=$r.join(Kn.homedir(),Gn);return{main:$r.join(e,Ro),userGlobal:$r.join(t,Un),userProject:$r.join(t,qn,r,Ro),projectName:r}},x=async()=>{let e=await W(),r;try{r=await Tt.stat(e.main)}catch{Ie=null;let c=e.main.replace(/\.json$/,".yml");throw await Et(c)?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([Et(e.userGlobal),Et(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(Ie&&os(Ie.mtimes,n))return Ie.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 c of s){let p=await ns(c);p!==null&&(i={...i,...p})}let l=He.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${k.prettifyError(l.error)}`);return Ie={mtimes:n,value:l.data},l.data},ue=()=>{Ie=null},Et=async e=>{try{return await Tt.stat(e)}catch{return null}},ts=async e=>{try{return await Tt.readFile(e,"utf-8")}catch{return null}},os=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},ns=async e=>{let r=await ts(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=Xe.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${k.prettifyError(o.error)}`);return o.data};var xo=async e=>{try{return await Sr.access(e),!0}catch{return!1}},Ir=e=>{let r=ss.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e},$t=async()=>{let e=await W(),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 xo(o.path)})));a.info(`Project name: ${e.projectName}
|
|
3
5
|
`),a.info(`Config merge chain (later overrides earlier):
|
|
4
|
-
`);for(let o of r){let
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
# environments, envManagement, ide, taskManager, worktrees.
|
|
19
|
-
#
|
|
20
|
-
# Uncomment the blocks you want to apply globally across every project on this
|
|
21
|
-
# machine. Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
|
|
22
|
-
|
|
23
|
-
# Per-developer IDE config
|
|
24
|
-
# ide:
|
|
25
|
-
# provider: cursor
|
|
26
|
-
# config:
|
|
27
|
-
# mode: workspace
|
|
28
|
-
# workspaceConfigPath: /path/to/your.code-workspace
|
|
29
|
-
|
|
30
|
-
# Worktree prompt defaults \u2014 silences the follow-up prompts in \`worktrees-add\`
|
|
31
|
-
# worktrees:
|
|
32
|
-
# openInGithubDesktop: false
|
|
33
|
-
# openInCmux: true
|
|
34
|
-
`,Sr=async()=>{let e=Er.join(pt.homedir(),".zshrc"),r=Ir();if(H.existsSync(e)){let t=H.readFileSync(e,"utf-8"),o=Co(t);H.writeFileSync(e,o)}H.appendFileSync(e,`
|
|
6
|
+
`);for(let o of r){let n=o.exists?" [\u2713]":" [ ]";a.info(`${n} ${o.label.padEnd(22)} ${Ir(o.path)}`)}let t={projectName:e.projectName,layers:r.map(o=>({label:o.label,path:o.path,exists:o.exists}))};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},St=async()=>{let e=await W(),r=bo.env.EDITOR||bo.env.VISUAL||"vi";if(await Sr.mkdir(is.dirname(e.userProject),{recursive:!0}),!await xo(e.userProject)){let o=cs(e.userProject);await Sr.writeFile(e.userProject,`{}
|
|
7
|
+
`,"utf-8"),await Sr.writeFile(o,ls(e.projectName),"utf-8"),a.info(`Created ${Ir(e.userProject)} \u2014 see ${Ir(o)} for the annotated reference.`)}a.info(`Opening ${Ir(e.userProject)} in ${r}`),await as({stdio:"inherit"})`${r} ${e.userProject}`,ue();let t={path:e.userProject,editor:r};return{content:[{type:"text",text:JSON.stringify(t,null,2)}],structuredContent:t}},cs=e=>e.replace(/\.json$/,".example.jsonc"),ls=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
|
|
8
|
+
//
|
|
9
|
+
// Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top
|
|
10
|
+
// of <repo>/infra-kit.json and ~/.infra-kit/config.json \u2014 top-level keys
|
|
11
|
+
// (environments, envManagement, ide, taskManager, worktrees) replace wholesale.
|
|
12
|
+
//
|
|
13
|
+
// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
|
|
14
|
+
// in the sibling infra-kit.json (strict JSON: no comments, double-quoted keys).
|
|
15
|
+
{
|
|
16
|
+
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true }
|
|
17
|
+
}
|
|
18
|
+
`;import ne from"node:fs";import Ao from"node:os";import tr from"node:path";import{z as Oe}from"zod";import{$ as No}from"zx";import J from"node:fs";import ge from"node:path";var Ae=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},Ye=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);if(o===-1||n===-1||n<o)return null;let s=e.slice(0,o).replace(/\n+$/,""),i=e.slice(n+t.length).replace(/^\n+/,"");return s+(i?`
|
|
19
|
+
${i}`:"")};var Co=(e,r,t)=>`${e}
|
|
35
20
|
${r}
|
|
36
|
-
|
|
37
|
-
${
|
|
38
|
-
|
|
21
|
+
${t}`,fe=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=Co(t,r,o),i=Ae(e,t,o);if(n==="replace-in-place"&&i){let p=e.indexOf(t),m=e.indexOf(o)+o.length;return e.slice(0,p)+s+e.slice(m)}let c=(i?Ye(e,t,o)??e:e).replace(/\n+$/,"");return c.length>0?`${c}
|
|
22
|
+
${s}
|
|
23
|
+
`:`${s}
|
|
24
|
+
`};var Ar={name:"infra-kit",type:"module",version:"0.1.107",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 te="<!-- infra-kit:begin -->",oe="<!-- infra-kit:end -->",ms="<!-- infra-kit:version ",Ze="<!-- infra-kit:import:begin -->",Qe="<!-- infra-kit:import:end -->",Po="AGENTS.md",ds="CLAUDE.md",us=ge.join(".cursor","rules","infra-kit.mdc"),fs=["---","description: infra-kit CLI usage and conventions","alwaysApply: true","---",""].join(`
|
|
25
|
+
`),gs=e=>`${ms}${e} -->`,hs=e=>[gs(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
|
+
`),ws=e=>{if(J.existsSync(e)&&J.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},It=(e,r)=>{ws(e);let t=J.existsSync(e);if((t?J.readFileSync(e,"utf-8"):null)===r)return"unchanged";if(t){let n=new Date().toISOString().replace(/[:.]/g,"-");J.copyFileSync(e,`${e}.backup.${n}`)}return J.mkdirSync(ge.dirname(e),{recursive:!0}),J.writeFileSync(e,r,"utf-8"),t?"updated":"created"},At=(e,r)=>J.existsSync(e)?J.readFileSync(e,"utf-8"):r,Nt=(e,r,t)=>{let o=J.readFileSync(e,"utf-8");if(!Ae(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},_t=async()=>{let e;try{e=(await W()).main}catch{return a.info("Skipped agent-instruction files \u2014 not inside an infra-kit repo"),{skipped:!0,root:null,written:[]}}if(!J.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=ge.dirname(e),t=Ar.version,o=hs(t),n=ge.join(r,Po),s=ge.join(r,ds),i=ge.join(r,us),l=fe({content:At(n,""),body:o,startMarker:te,endMarker:oe}),c=fe({content:At(s,""),body:`@${Po}`,startMarker:Ze,endMarker:Qe}),p=fe({content:At(i,fs),body:o,startMarker:te,endMarker:oe}),m=[{path:n,action:It(n,l)},{path:s,action:It(s,c)},{path:i,action:It(i,p)}];Nt(n,te,oe),Nt(s,Ze,Qe),Nt(i,te,oe);for(let u of m)a.info(` ${u.action.padEnd(9)} ${ge.relative(r,u.path)}`);return a.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:m}};import he from"node:fs";import $o from"node:os";import Nr from"node:path";import er from"node:fs/promises";import vs from"node:os";import ks from"node:path";import ys from"yaml";import{z as Rs}from"zod";var Ne=e=>{let r=vs.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e},Eo=async e=>{try{return await er.access(e),!0}catch{return!1}},Ot=e=>e.replace(/\.json$/,".yml"),To=async()=>{let e;try{e=await W()}catch{return}let r=[{label:"infra-kit.json",yml:Ot(e.main),json:e.main,schema:He},{label:"~/.infra-kit/config.json",yml:Ot(e.userGlobal),json:e.userGlobal,schema:Xe},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Ot(e.userProject),json:e.userProject,schema:Xe}],t=0;for(let o of r){let[n,s]=await Promise.all([Eo(o.yml),Eo(o.json)]);if(n){if(s){a.info(`\u26A0 Skipped ${Ne(o.yml)} \u2014 ${Ne(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await er.readFile(o.yml,"utf-8"),l=ys.parse(i)??{},c=o.schema.safeParse(l);if(!c.success){a.info(`\u26A0 Skipped ${Ne(o.yml)} \u2014 invalid config: ${Rs.prettifyError(c.error)}`);continue}await er.mkdir(ks.dirname(o.json),{recursive:!0}),await er.writeFile(o.json,`${JSON.stringify(c.data,null,2)}
|
|
27
|
+
`,"utf-8"),await er.rm(o.yml,{force:!0}),a.info(`\u2713 Migrated ${Ne(o.yml)} \u2192 ${Ne(o.json)}`),t++}catch(i){a.info(`\u26A0 Skipped ${Ne(o.yml)} \u2014 ${i.message}`)}}}t>0&&ue()};var rr="# -- infra-kit:begin --",_e="# -- infra-kit:end --",bs=[["# region infra-kit","# endregion infra-kit"]],xs="# infra-kit shell functions",Cs=`{}
|
|
28
|
+
`,Ps=`// infra-kit user-global config \u2014 ~/.infra-kit/config.json
|
|
29
|
+
//
|
|
30
|
+
// Merge chain (later layers override earlier ones at top-level keys):
|
|
31
|
+
// 1. <repo>/infra-kit.json \u2014 committed project config (required)
|
|
32
|
+
// 2. ~/.infra-kit/config.json \u2014 user-global (the sibling of this file)
|
|
33
|
+
// 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override
|
|
34
|
+
//
|
|
35
|
+
// Merge is shallow: setting a top-level key replaces that whole section from
|
|
36
|
+
// layer 1. Arrays do not concatenate. Top-level keys recognized:
|
|
37
|
+
// environments, envManagement, ide, taskManager, worktrees.
|
|
38
|
+
//
|
|
39
|
+
// This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
|
|
40
|
+
// overrides in the sibling config.json (strict JSON: no comments, double-quoted
|
|
41
|
+
// keys). Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
|
|
42
|
+
{
|
|
43
|
+
// "ide": {
|
|
44
|
+
// "provider": "cursor",
|
|
45
|
+
// "config": { "mode": "workspace", "workspaceConfigPath": "/path/to/your.code-workspace" }
|
|
46
|
+
// },
|
|
47
|
+
// "worktrees": { "openInGithubDesktop": false, "openInCmux": true }
|
|
48
|
+
}
|
|
49
|
+
`,jt=async()=>{let e=Nr.join($o.homedir(),".zshrc"),r=he.existsSync(e)?$s(he.readFileSync(e,"utf-8")):"",t=fe({content:r,body:So(),startMarker:rr,endMarker:_e,placement:"append-end"});he.writeFileSync(e,t),a.info(`Added infra-kit shell functions to ${e}`),await To(),Es(),await _t(),a.info("Run `source ~/.zshrc` or open a new terminal to activate.")},Es=()=>{let e=Nr.join($o.homedir(),".infra-kit"),r=Nr.join(e,"config.json"),t=Nr.join(e,"config.example.jsonc");if(he.existsSync(r)){a.info(`User-global config already present at ${r}`);return}he.mkdirSync(e,{recursive:!0}),he.writeFileSync(r,Cs,"utf-8"),he.writeFileSync(t,Ps,"utf-8"),a.info(`Wrote user-global config to ${r} (see ${t} for the annotated reference)`)},Ts=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"),$s=e=>{let r=Ye(e,rr,_e);if(r!==null)return r;for(let[l,c]of bs){let p=Ye(e,l,c);if(p!==null)return p}let t=e.indexOf(xs);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
|
|
50
|
+
`),s=0;for(;s<n.length&&Ts(n[s]);)s++;let i=n.slice(s).join(`
|
|
39
51
|
`);return o+(i?`
|
|
40
|
-
${i}`:"")},
|
|
41
|
-
`)}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
`))
|
|
52
|
+
${i}`:"")},So=()=>{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(`
|
|
53
|
+
`)},Io=()=>`${rr}
|
|
54
|
+
${So()}
|
|
55
|
+
${_e}`;var je=async(e,r,t,o)=>{try{return await No`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Ss=()=>{let e="zshrc init block",r=tr.join(Ao.homedir(),".zshrc");if(!ne.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=ne.readFileSync(r,"utf-8"),o=t.indexOf(rr),n=t.indexOf(_e);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+_e.length).trim(),i=Io().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"}},Is=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await b(),t=tr.join(r,"pnpm-workspace.yaml");if(!ne.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=ne.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}`}}},As=async()=>{let e="infra-kit config valid";try{return ue(),await x(),{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}}},Ns=async()=>{let e="user override path";try{let r=await W(),t=Ao.homedir(),o=r.userProject.startsWith(t)?`~${r.userProject.slice(t.length)}`:r.userProject,s=ne.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}}},_s=[1,2,3,5,7],Os=async()=>{let e="rtk configured";try{let t=(await No`rtk init --show`).stdout.split(`
|
|
56
|
+
`).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of _s){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}`}}},js=async()=>{let e;try{e=(await W()).main}catch{return[]}if(!ne.existsSync(e))return[];let r=tr.dirname(e),t=(n,s,i)=>{let l=tr.join(r,n),c=ne.existsSync(l)?ne.readFileSync(l,"utf-8"):"";return Ae(c,s,i)};return[{name:"AGENTS.md block",present:t("AGENTS.md",te,oe),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",Ze,Qe),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(tr.join(".cursor","rules","infra-kit.mdc"),te,oe),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}))},_r=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"),Os(),Promise.resolve(Ss()),Is(),As(),Ns()]),...await js()];a.info(`Doctor check results:
|
|
57
|
+
`);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}},Fs=v({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:Oe.array(Oe.object({name:Oe.string().describe("Name of the check"),status:Oe.enum(["pass","fail"]).describe("Check result"),message:Oe.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:Oe.boolean().describe("Whether all checks passed")},handler:_r});import Lt from"node:fs";import Oo from"node:path";import Ds from"node:process";import{z as Or}from"zod";import or from"node:fs";import Ms from"node:os";import Ft from"node:path";import Mt from"node:process";var we="env-load.sh",Dt="env-clear.sh",nr="INFRA_KIT_SESSION",ve="INFRA_KIT_ENV_CONFIG",ke="INFRA_KIT_ENV_PROJECT",ye="INFRA_KIT_ENV_LOADED_AT",sr=/^([A-Z_]\w*)=/i,ir=e=>{if(!or.existsSync(e))return[];let r=or.readFileSync(e,"utf-8"),t=[];for(let o of r.split(`
|
|
58
|
+
`)){let n=sr.exec(o);n&&t.push(n[1])}return t},_o=()=>{let e=Mt.env.XDG_CACHE_HOME,r=e&&e.length>0?e:Ft.join(Ms.homedir(),".cache");return Ft.join(r,"infra-kit")},Re=()=>{let e=Mt.env[nr];if(!e)throw new Error(`${nr} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return Ft.join(_o(),e)},ar=(e,r,t)=>{let o=`${e}.tmp.${Mt.pid}`;or.writeFileSync(o,r,{mode:t});try{or.renameSync(o,e)}catch(n){throw or.rmSync(o,{force:!0}),n}},B="-worktrees";var jr=async()=>{let e=Re(),r=Oo.join(e,we);if(!Lt.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=ir(r),o=[...t.map(i=>`unset ${i}`),`unset ${ve}`,`unset ${ke}`,`unset ${ye}`],n=Oo.resolve(e,Dt);Lt.mkdirSync(e,{recursive:!0,mode:448}),ar(n,`${o.join(`
|
|
45
59
|
`)}
|
|
46
|
-
`,384),
|
|
47
|
-
`),
|
|
48
|
-
`),a.info("Available configs:");for(let o of r)a.info(` - ${o}`);let t={project:e,configs:r};return{content:
|
|
60
|
+
`,384),Ds.stdout.write(`${n}
|
|
61
|
+
`),Lt.unlinkSync(r);let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:h(JSON.stringify(s,null,2)),structuredContent:s}},Ls=v({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:Or.string().describe("Path to the file that must be sourced to apply"),variableCount:Or.number().describe("Number of variables cleared"),unsetStatements:Or.array(Or.string()).describe("Unset statements generated")},handler:jr});import{z as Wt}from"zod";var cr=async()=>{let{envManagement:e}=await x();return e.config.name};var Fr=async()=>{let e=await cr(),{environments:r}=await x();a.info(`Doppler project: ${e}
|
|
62
|
+
`),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}},Ws=v({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:Wt.string().describe("Detected Doppler project name"),configs:Wt.array(Wt.string()).describe("Available environment configs")},handler:Fr});import Js from"@inquirer/select";import{Buffer as Bs}from"node:buffer";import Ks from"node:fs";import Gs from"node:path";import Fo from"node:process";import{z as pr}from"zod";import{$ as Mr}from"zx";import{$ as jo}from"zx";var lr=async()=>{try{await jo`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 jo`doppler me`}catch(e){throw new Error("Doppler CLI is not authenticated. Run: doppler login",{cause:e})}};var Vs=()=>{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:
|
|
49
63
|
pnpm exec infra-kit ${e} ${o}
|
|
50
|
-
`)},reset(){e="",r=[],t=!1}}},d=
|
|
64
|
+
`)},reset(){e="",r=[],t=!1}}},d=Vs();var Dr=async e=>{await lr();let{config:r}=e;d.start("env-load");let t="";if(r)t=r;else{let{environments:u}=await x();d.setInteractive(),t=await Js({message:"Select environment config",choices:u.map(f=>({name:f,value:f}))},{output:Fo.stderr})}d.addOption("--config",t);let o=await cr(),n=await qs(o,t);Ys(n);let s=new Date().toISOString(),i=["set -a",n,`${ve}=${Vt(t)}`,`${ke}=${Vt(o)}`,`${ye}=${Vt(s)}`,"set +a"],l=Re(),c=Gs.resolve(l,we);Ks.mkdirSync(l,{recursive:!0,mode:448}),ar(c,`${i.join(`
|
|
51
65
|
`)}
|
|
52
|
-
`,384),
|
|
53
|
-
`),d.print();let p=
|
|
54
|
-
`).filter(r=>
|
|
55
|
-
`)){let t=r.trim();if(!(t.length===0||
|
|
56
|
-
`),
|
|
57
|
-
`);let c={sessionId:r,sessionLoadedCount:o,sessionTotalCount:
|
|
58
|
-
`);throw new Error(i)}let
|
|
59
|
-
`).map(o=>{let s=o.indexOf(" ");return s===-1?"":o.slice(s+1).replace(/^refs\/heads\//,"")}).filter(Boolean)}finally{sr.quiet=e}},rs=async()=>{let e=await X();return e?(await pe(e)).map(t=>t.name):[]},Kr=async()=>{let[e,r]=await Promise.allSettled([es(),rs()]);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"),Lr({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Ct=async()=>{let e=await A`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName`,r=await A`gh pr list --search "Hotfix in:title" --base main --json number,title,headRefName,state,baseRefName`,t=[...JSON.parse(e.stdout),...JSON.parse(r.stdout)],o=new Set;return t.filter(s=>o.has(s.headRefName)?!1:(o.add(s.headRefName),!0))},ir=async()=>{try{let e=await Ct();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),nr.exit(1)),ue(e.map(r=>r.headRefName))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),nr.exit(1)}},C=async()=>{try{let e=await Ct();e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),nr.exit(1));let r=ue(e.map(o=>o.headRefName)),t=new Map(e.map(o=>[o.headRefName,o]));return r.map(o=>({branch:o,title:t.get(o).title}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),nr.exit(1)}},ar=async e=>{let{branch:r,body:t}=e;try{A.quiet=!0,await A`gh pr edit ${r} --body ${t}`,A.quiet=!1}catch(o){throw a.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},tr=async e=>{let{version:r,jiraVersionUrl:t,type:o,description:s}=e,n=o==="hotfix"?"Hotfix":"Release",i=rr(o),l=`release/v${r}`,c=s&&s.trim()!==""?`${t}
|
|
66
|
+
`,384),Fo.stdout.write(`${c}
|
|
67
|
+
`),d.print();let p=Hs(n),m={filePath:c,variableCount:p,project:o,config:t};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}},Mo=1024*1024,Us=3e4,qs=async(e,r)=>{let t=Mr.quiet;Mr.quiet=!0;try{let o=await Mr`doppler secrets download --no-file --format env --project ${e} --config ${r}`.timeout(Us);return zs(o.stdout),o.stdout.trim()}finally{Mr.quiet=t}},zs=e=>{let r=Bs.byteLength(e,"utf-8");if(r>Mo)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Mo}) \u2014 refusing to write to disk`)},Hs=e=>e.split(`
|
|
68
|
+
`).filter(r=>sr.test(r)).length,Xs=new Set(["set -a","set +a"]),Vt=e=>`'${e.replaceAll("'","'\\''")}'`,Ys=e=>{if(e.trim().length===0)throw new Error("doppler returned empty output for env-load");for(let r of e.split(`
|
|
69
|
+
`)){let t=r.trim();if(!(t.length===0||Xs.has(t))&&!sr.test(t))throw new Error(`doppler returned unexpected output for env-load (expected KEY=value lines, got: ${JSON.stringify(t.slice(0,80))})`)}},Zs=v({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:pr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:pr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:pr.number().describe("Number of variables loaded"),project:pr.string().describe("Doppler project name"),config:pr.string().describe("Doppler config name")},handler:Dr});import Qs from"node:path";import mr from"node:process";import{z as Fe}from"zod";var Lr=async()=>{await lr(),a.info("Environment session status:");let e=Re(),r=mr.env[nr],t=Qs.join(e,we),o=0,n=0,s=mr.env[ve]??null,i=mr.env[ke]??null,l=mr.env[ye]??null;if(s){let p=ir(t);p.length>0&&(n=p.length,o=p.filter(u=>u in mr.env).length);let m=l?.replace(/\.\d{3}Z$/,"")??null;if(a.info(` ${s}: ${o} of ${n} vars loaded (project: ${i}, loadedAt: ${m}, session: ${r})
|
|
70
|
+
`),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
|
|
71
|
+
`);let c={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:l};return{content:h(JSON.stringify(c,null,2)),structuredContent:c}},ei=v({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:Fe.string().describe("Current terminal session ID"),sessionLoadedCount:Fe.number().describe("Number of cached vars active in the current session"),sessionTotalCount:Fe.number().describe("Total number of cached var names"),sessionConfig:Fe.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:Fe.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:Fe.string().nullable().describe("ISO 8601 timestamp of when the env was loaded")},handler:Lr});import ni from"@inquirer/checkbox";import si from"@inquirer/confirm";import ii from"node:process";import{z as We}from"zod";import{$ as K}from"zx";import{$ as Cm}from"zx";import Kr from"node:process";import{$ as N}from"zx";import{$ as ur}from"zx";import dr from"node:process";var Jt=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},l=`${t}/rest/api/3/version`,c=btoa(`${n}:${o}`),p=await fetch(l,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${c}`},body:JSON.stringify(i)});if(!p.ok){let u=await p.text();throw a.error({status:p.status,statusText:p.statusText,error:u},"Failed to create Jira version"),new Error(`HTTP ${p.status}: ${p.statusText}`)}return{success:!0,version:await p.json()}}catch(t){throw a.error({error:t},"Error creating Jira version"),t}},Me=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}`),l=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});if(!l.ok){let p=await l.text();throw a.error({status:l.status,statusText:l.statusText,error:p},"Failed to get Jira project versions"),new Error(`HTTP ${l.status}: ${l.statusText}`)}return await l.json()}catch(r){throw a.error({error:r},"Error getting Jira project versions"),r}},Wr=async(e,r)=>{try{return(await Me(r)).find(n=>n.name===e)||null}catch(t){throw a.error({error:t,versionName:e},"Error finding Jira version by name"),t}},Vr=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}`,l=btoa(`${n}:${o}`),c=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(s)});if(!c.ok){let m=await c.text();throw a.error({status:c.status,statusText:c.statusText,error:m},"Failed to update Jira version"),new Error(`HTTP ${c.status}: ${c.statusText}`)}return{success:!0,version:await c.json()}}catch(t){throw a.error({error:t},"Error updating Jira version"),t}},Bt=async(e,r)=>{try{let{versionName:t}=e,o=await Wr(t,r);if(!o)throw a.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await Vr({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}},De=async()=>{let e=dr.env.JIRA_BASE_URL,r=dr.env.JIRA_TOKEN||dr.env.JIRA_API_TOKEN,t=dr.env.JIRA_PROJECT_ID,o=dr.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(l=>` - ${l}`),"","You can set these in your .env file or as environment variables."].join(`
|
|
72
|
+
`);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}},be=async()=>{try{return await De()}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},oi=(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 ")},g=class extends Error{operation;remediation;constructor(r,t){super(oi(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var Do="dev",Jr=e=>e==="hotfix"?"main":"dev",Kt=async(e="regular")=>{let r=Jr(e);ur.quiet=!0,await ur`git fetch origin`,await ur`git switch ${r}`,await ur`git pull origin ${r}`,ur.quiet=!1},Gt=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=D(r),i=await Jt({name:s,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),l=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,c=await Br({id:r,jiraVersionUrl:l,type:n,description:o});return{version:T(r),type:n,branchName:c.branchName,prUrl:c.prUrl,jiraVersionUrl:l}},$=async()=>{let e=new Map,r=await be();if(!r)return e;try{let t=await Me(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},Le=(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",Lo=e=>e.flatMap(r=>{let t=R(r);return t?[{branch:r,id:t,label:T(t)}]:[]}),H=e=>{try{return q(G(e))}catch(r){throw new g(r,{operation:`resolve release ref "${e}"`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'})}},fr=e=>{if(e===Do)return Do;let r=R(e);return r?T(r):e},xe=e=>e.flatMap(r=>{let t=R(r);return t?[T(t)]:[]}),A=e=>{let{branches:r,descriptions:t,types:o}=e,n=Lo(r),s=Math.max(0,...n.map(i=>i.label.length));return n.map(({branch:i,id:l,label:c})=>{let p=o?o.get(i)||"regular":void 0,m=t.get(D(l)),u=" ".repeat(s-c.length+3),f=p?Le(c,p,s):c;return m&&(f=p?`${f} ${m}`:`${c}${u}${m}`),{name:f,value:i}})};var Wo=e=>e.map(r=>({pr:r,id:R(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>ht(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),Vo=async()=>{let e=await N`gh pr list --search "Release in:title" --base dev --json number,title,headRefName,state,baseRefName,createdAt`,r=await N`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))},Gr=async()=>{try{let e=await Vo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Kr.exit(1)),Wo(e).map(r=>r.headRefName)}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),Kr.exit(1)}},P=async()=>{try{let e=await Vo();return e.length===0&&(a.error("\u274C No release PRs found. Check the project folder for the script. Exiting..."),Kr.exit(1)),Wo(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){a.error({error:e},"\u274C Error fetching release PRs"),Kr.exit(1)}},Ur=async e=>{let{branch:r,body:t}=e;try{N.quiet=!0,await N`gh pr edit ${r} --body ${t}`,N.quiet=!1}catch(o){throw a.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},Br=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=gt(r,o),i=Jr(o),l=q(r),c=n&&n.trim()!==""?`${t}
|
|
60
73
|
|
|
61
|
-
${
|
|
62
|
-
`;try{
|
|
74
|
+
${n}`:`${t}
|
|
75
|
+
`;try{N.quiet=!0,await N`git switch ${i}`,await N`git pull origin ${i}`,await N`git checkout -b ${l}`,await N`git push -u origin ${l}`,await N`git commit --allow-empty-message --allow-empty --message ''`,await N`git push origin ${l}`;let m=(await N`gh pr create --title "${s}" --body ${c} --base ${i} --head ${l}`).stdout.trim();return await N`git switch ${i}`,N.quiet=!1,{branchName:l,prUrl:m}}catch(p){throw a.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var qr=async e=>{let{all:r,confirmedCommand:t}=e;d.start("merge-dev");let n=(await P()).filter(m=>C(m.title)==="regular").map(m=>m.branch);if(n.length===0)return a.info("\u2139\uFE0F No open release branches found"),d.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{d.setInteractive();let m=await $();s=await ni({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:m})})}s.length===n.length?d.addOption("--all",!0):d.addOption("--versions",xe(s));let l=t?!0:await si({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||d.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),ii.exit(0)),t||d.addOption("--yes",!0),K.quiet=!0,await K`git fetch origin`,await K`git switch dev`,await K`git pull origin dev`;let c=[];for(let m of s)await ai(m)||c.push(m);if(K.quiet=!1,c.length>0){a.info(`
|
|
63
76
|
\u26A0\uFE0F ${c.length} branch(es) failed to merge automatically.
|
|
64
77
|
`),a.info("\u{1F4CB} Manual merge script for failed branches:");for(let m of c)a.info(`# Merge dev into ${m} and resolve conflicts if any
|
|
65
78
|
|
|
66
79
|
git switch ${m} && git pull origin ${m} && git merge origin/dev
|
|
67
80
|
git push origin ${m} && git switch dev
|
|
68
|
-
`);a.info(`\u2705 ${
|
|
69
|
-
`);d.print();let p={successfulMerges:
|
|
70
|
-
`)){let o=t.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let
|
|
71
|
-
`)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let s=o[1]?.trim();s&&r.add(s)}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as Ae}from"zx";var _e=async e=>{let{cwd:r,title:t}=e,o=(await Ae`cmux new-workspace --cwd ${r}`).stdout,s=ds(o),n=(await Ae`cmux list-pane-surfaces --workspace ${s}`).stdout,i=ms(n);await Ae`cmux new-split right --workspace ${s} --surface ${i}`,await Ae`cmux new-split down --workspace ${s} --surface ${i}`,t&&await Ae`cmux rename-workspace --workspace ${s} ${t}`},ms=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]},ds=e=>{let r=e.match(/workspace:\d+/);if(!r)throw new Error("cmux: could not locate workspace ref in new-workspace output");return r[0]};var W=e=>{let{repoName:r,branch:t}=e,o=t.replace("release/","");return`${r} ${o}`};var Oe=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:s=!1}=e,n=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=W({repoName:o,branch:l});return await Ie(p),await Gr`git worktree remove ${c}`,l})),i=[];for(let[l,c]of n.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l],m=new w(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:c.reason,msg:m.message})}return s&&i.length===r.length&&(await Gr`git worktree prune`,await Gr`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var ge=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:qr(o)},`\u274C Failed to ${e}`),new w(o,{operation:e,remediation:r})}},Pt=async e=>{let r=await N`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},hs=async e=>{let r=`Release v${e} (RC)`,t=await N`gh pr list --head dev --base main --state merged --json number,state,title --limit 20`;return JSON.parse(t.stdout).find(n=>n.title===r)??null},$t=async()=>{let e=await N`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},ws=async e=>{let r=`release/v${e}`,t=await Pt(r);if(!t)throw a.error(`\u274C No PR found for branch ${r}.`),new w(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},vs=async()=>{let e=await C(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,b(i.title)]));d.setInteractive();let o=await T(),s=await fs({message:"\u{1F33F} Select release branch",choices:I({branches:r,descriptions:o,types:t})}),n=e.find(i=>i.branch===s);if(!n)throw a.error(`\u274C Release branch ${s} not found in open PRs.`),new w(void 0,{operation:`deliver release ${s}`,remediation:`confirm an open PR exists for ${s} ('gh pr list')`});return{selectedReleaseBranch:s,releasePrTitle:n.title}},ys=async e=>{if(!(await _("release")).includes(e))return;let[t,o]=await Promise.all([E(),O()]),s=`${t}${F}`;if((await Oe({branches:[e],worktreeDir:s,repoName:o})).length===0)throw new w(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${s}/${e} (use --force if uncommitted changes)`})},ks=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",s=await Pt(r);if(!s)throw new w(void 0,{operation:`look up release PR for ${r}`,remediation:"verify the PR exists in GitHub"});if(s.state==="MERGED"){a.info(`\u2713 Release PR ${r} already merged \u2014 skipping`);return}if(s.state==="CLOSED")throw new w(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await ge(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await N`gh pr merge ${r} --squash --admin --delete-branch`})},Rs=async e=>{let r=`Release v${e} (RC)`,t=await $t();if(t){let s=t.number;return t.title!==r&&(a.info(`Adopting open dev \u2192 main PR #${s} ("${t.title}") and retitling for v${e}`),await ge(`retitle dev \u2192 main PR #${s} to "${r}"`,`update manually: gh pr edit ${s} --title "${r}"`,async()=>{await N`gh pr edit ${s} --title ${r}`})),s}await ge(`create RC PR (dev \u2192 main) for v${e}`,"run 'gh pr create --base main --head dev' manually to surface the underlying error (e.g. no commits between dev and main)",async()=>{await N`gh pr create --base main --head dev --title ${r} --body ""`});let o=await $t();if(!o)throw new w(void 0,{operation:`look up RC PR for v${e}`,remediation:"verify the RC PR was created ('gh pr list --head dev --base main')"});return o.number},bs=async e=>{if(await hs(e)){a.info(`\u2713 RC PR for v${e} already merged into main \u2014 skipping`);return}let t=await Rs(e);await ge(`merge RC PR #${t} (dev \u2192 main) for v${e}`,`check 'gh pr view ${t}' for mergeability and required reviews`,async()=>{await N`gh pr merge ${t} --squash --admin`})},Cs=async()=>{N.quiet=!1,await ge("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await N`gh workflow run deploy-all.yml --ref main -f environment=prod`}),N.quiet=!0},xs=async()=>{await ge("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 N`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Ts=async e=>{let r=await X();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=e.replace("release/","");await Mr({versionName:t},r)}catch(t){a.error({err:qr(t)},"Failed to deliver Jira release (non-blocking)")}},lr=async e=>{let{version:r,confirmedCommand:t}=e;d.start("release-deliver");let{selectedReleaseBranch:o,releasePrTitle:s}=r?await ws(r):await vs(),n=o.replace("release/v","");d.addOption("--version",n);let i=b(s),l=t?!0:await us({message:`Are you sure you want to deliver version ${o} to production?`});t||d.setInteractive(),l||(a.info("Operation cancelled. Exiting..."),gs.exit(0)),d.addOption("--yes",!0),N.quiet=!0,await ys(o),await ks({selectedReleaseBranch:o,releaseType:i}),i!=="hotfix"&&await bs(n),await Cs(),await xs(),N.quiet=!1,await Ts(o),a.info(`Successfully delivered ${o} to production!`),d.print();let c={releaseBranch:o,version:n,type:i,success:!0};return{content:g(JSON.stringify(c,null,2)),structuredContent:c}},$s=v({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:Ne.string().describe('Release version to deliver to production (e.g., "1.2.5"). Required for MCP calls.')},outputSchema:{releaseBranch:Ne.string().describe("The release branch that was delivered"),version:Ne.string().describe("The version that was delivered"),type:Ne.enum(["regular","hotfix"]).describe("Release type"),success:Ne.boolean().describe("Whether the delivery was successful")},handler:lr});import Et from"@inquirer/select";import{z as B}from"zod/v4";import{$ as Ur}from"zx";var pr=async e=>{let{version:r,env:t,skipTerraform:o}=e;d.start("release-deploy-all");let s="";if(r)s=r==="dev"?"dev":`release/v${r}`;else{d.setInteractive();let p=await C(),m=p.map(h=>h.branch),f=new Map(p.map(h=>[h.branch,b(h.title)])),u=await T();s=await Et({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...I({branches:m,descriptions:u,types:f})]})}let n=s==="dev"?"dev":s.replace("release/v","");d.addOption("--version",n);let{environments:i}=await R(),l="";if(t?l=t:(d.setInteractive(),l=await Et({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),d.addOption("--env",l),!i.includes(l))throw new w(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${i.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let c=o??!1;c&&d.addOption("--skip-terraform",!0);try{Ur.quiet=!0,await Ur`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,Ur.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),d.print();let m={releaseBranch:s,version:s.replace("release/v",""),environment:l,skipTerraformDeploy:c,success:!0};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw a.error({error:p},"\u274C Error launching workflow"),new w(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Ps=v({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:B.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:B.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:B.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:B.string().describe("The release branch that was deployed"),version:B.string().describe("The version that was deployed"),environment:B.string().describe("The environment deployed to"),skipTerraformDeploy:B.boolean().describe("Whether terraform deployment was skipped"),success:B.boolean().describe("Whether the deployment was successful")},handler:pr});import Es from"@inquirer/checkbox";import St from"@inquirer/select";import Ss from"node:fs/promises";import{resolve as Is}from"node:path";import As from"yaml";import{z as D}from"zod/v4";import{$ as Hr}from"zx";var mr=async e=>{let{version:r,env:t,services:o,skipTerraform:s}=e;d.start("release-deploy-selected");let n="";if(r)n=r==="dev"?"dev":`release/v${r}`;else{d.setInteractive();let h=await C(),$=h.map(ee=>ee.branch),P=new Map(h.map(ee=>[ee.branch,b(ee.title)])),M=await T();n=await St({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...I({branches:$,descriptions:M,types:P})]})}let i=n==="dev"?"dev":n.replace("release/v","");d.addOption("--version",i);let{environments:l}=await R(),c="";if(t?c=t:(d.setInteractive(),c=await St({message:"\u{1F9EA} Select environment",choices:l.map(h=>({name:h,value:h}))})),d.addOption("--env",c),!l.includes(c))throw new w(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=await _s();if(p.length===0)throw new w(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 m=[];if(o&&o.length>0?m=o:(d.setInteractive(),m=await Es({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(h=>({name:h,value:h}))})),d.addOption("--services",m),m.length===0)throw new w(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let f=m.filter(h=>!p.includes(h));if(f.length>0)throw new w(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${f.join(", ")}`});let u=s??!1;u&&d.addOption("--skip-terraform",!0);try{Hr.quiet=!0;let h=m.flatMap(M=>["-f",`${M}=true`]);await Hr`gh workflow run deploy-selected-services.yml --ref ${n} -f environment=${c} ${h} ${u?["-f","skip_terraform_deploy=true"]:[]}`,Hr.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${n}, environment: ${c}, services: ${m.join(", ")}`),d.print();let P={releaseBranch:n,version:n.replace("release/v",""),environment:c,services:m,skipTerraformDeploy:u,success:!0};return{content:g(JSON.stringify(P,null,2)),structuredContent:P}}catch(h){throw a.error({error:h},"\u274C Error launching workflow"),new w(h,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},_s=async()=>{let e=await E(),r=Is(e,".github/workflows/deploy-selected-services.yml"),t=await Ss.readFile(r,"utf-8"),s=As.parse(t).on.workflow_dispatch.inputs,n=[];for(let[i,l]of Object.entries(s))l.type==="boolean"&&i!=="skip_terraform_deploy"&&n.push(i);return n},Os=v({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:D.string().describe('Release version to deploy from (e.g. "1.2.5") \u2014 resolves to the release/vX.Y.Z branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:D.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:D.array(D.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:D.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:D.string().describe("The release branch that was deployed"),version:D.string().describe("The version that was deployed"),environment:D.string().describe("The environment deployed to"),services:D.array(D.string()).describe("The services that were deployed"),skipTerraformDeploy:D.boolean().describe("Whether terraform deployment was skipped"),success:D.boolean().describe("Whether the deployment was successful")},handler:mr});import{z as he}from"zod/v4";var dr=async()=>{let r=(await C()).map(i=>({version:i.branch.replace("release/",""),type:b(i.title)})),t=await T(),o=Math.max(...r.map(i=>i.version.length)),s=r.map(i=>{let l=de(i.version,i.type,o),c=t.get(i.version);return c?`${l} ${c}`:l});a.info(`All release branches:
|
|
81
|
+
`);a.info(`\u2705 ${s.length-c.length}/${s.length} merges completed successfully.`)}else a.info(`\u2705 All merges completed successfully!
|
|
82
|
+
`);d.print();let p={successfulMerges:s.length-c.length,failedMerges:c.length,failedBranches:c,totalBranches:s.length};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},ai=async e=>{try{return await K`git switch ${e}`,await K`git pull origin ${e}`,await K`git merge origin/dev --no-edit`,await K`git push origin ${e}`,await K`git switch dev`,a.info(`Successfully merged dev into ${e}`),!0}catch(r){let t=new g(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 K`git reset --merge HEAD~1`,!1}},ci=v({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:We.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:We.number().describe("Number of successful merges"),failedMerges:We.number().describe("Number of failed merges"),failedBranches:We.array(We.string()).describe("List of branches that failed to merge"),totalBranches:We.number().describe("Total number of branches processed")},handler:qr});import ui from"@inquirer/confirm";import fi from"@inquirer/select";import gi from"node:process";import{z as kr}from"zod";import{$ as M}from"zx";var Jo=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},Ut=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=Jo(r.stderr,500);n&&(t.stderr=n);let s=Jo(r.stdout,200);return s&&(t.stdout=s),t};import{$ as zt}from"zx";import{$ as Bo}from"zx";var gr=async e=>{try{let r=(await Bo`cmux list-workspaces`.quiet()).stdout,t=li(r,e);if(!t)return;await Bo`cmux close-workspace --workspace ${t}`.quiet()}catch(r){a.debug({error:r,title:e},"cmux: skipped closing workspace")}},li=(e,r)=>{for(let t of e.split(`
|
|
83
|
+
`)){let o=t.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1];if((o[2]?.trim()??"")===r)return n}};import{$ as pi}from"zx";var qt=async()=>{try{let e=(await pi`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
|
|
84
|
+
`)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(n)}return r}catch(e){return a.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as hr}from"zx";var wr=async e=>{let{cwd:r,title:t}=e,o=(await hr`cmux workspace create --cwd ${r}`).stdout,n=di(o),s=(await hr`cmux list-pane-surfaces --workspace ${n}`).stdout,i=mi(s);await hr`cmux new-split right --workspace ${n} --surface ${i}`,await hr`cmux new-split down --workspace ${n} --surface ${i}`,t&&await hr`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 X=e=>{let{repoName:r,branch:t}=e,o=R(t),n=o?T(o):t;return`${r} ${n}`};var vr=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:n=!1}=e,s=await Promise.allSettled(r.map(async l=>{let c=`${t}/${l}`,p=X({repoName:o,branch:l});return await gr(p),await zt`git worktree remove ${c}`,l})),i=[];for(let[l,c]of s.entries())if(c.status==="fulfilled")i.push(c.value);else{let p=r[l],m=new g(c.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});a.error({error:c.reason,msg:m.message})}return n&&i.length===r.length&&(await zt`git worktree prune`,await zt`rm -rf ${t}`,a.info(`\u{1F5D1}\uFE0F Removed worktree folder: ${t}`),a.info("")),i};var Ve=async(e,r,t)=>{try{return await t()}catch(o){throw a.error({err:Ut(o)},`\u274C Failed to ${e}`),new g(o,{operation:e,remediation:r})}},Go=async e=>{let r=await M`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},hi=async e=>{let r=Pr(e),t=await M`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},Ko=async()=>{let e=await M`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},wi=async e=>{let r=H(e),t=await Go(r);if(!t)throw a.error(`\u274C No PR found for branch ${r}.`),new g(void 0,{operation:`deliver release ${r}`,remediation:`confirm a PR exists ('gh pr list --head ${r} --state all')`});return{selectedReleaseBranch:r,releasePrTitle:t.title}},vi=async()=>{let e=await P(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,C(i.title)]));d.setInteractive();let o=await $(),n=await fi({message:"\u{1F33F} Select release branch",choices:A({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 g(void 0,{operation:`deliver release ${n}`,remediation:`confirm an open PR exists for ${n} ('gh pr list')`});return{selectedReleaseBranch:n,releasePrTitle:s.title}},ki=async e=>{if(!(await j("release")).includes(e))return;let[t,o]=await Promise.all([b(),F()]),n=`${t}${B}`;if((await vr({branches:[e],worktreeDir:n,repoName:o})).length===0)throw new g(void 0,{operation:`remove worktree for ${e} before merge`,remediation:`run manually: git worktree remove ${n}/${e} (use --force if uncommitted changes)`})},yi=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await Go(r);if(!n)throw new g(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 g(void 0,{operation:`merge release PR ${r} into ${o}`,remediation:"the PR is closed without merge; reopen it or create a new release"});await Ve(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await M`gh pr merge ${r} --squash --admin --delete-branch`})},Ri=async e=>{let r=T(e),t=Pr(e),o=await Ko();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 Ve(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await M`gh pr edit ${s} --title ${t}`})),s}await Ve(`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 M`gh pr create --base main --head dev --title ${t} --body ""`});let n=await Ko();if(!n)throw new g(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},bi=async e=>{let r=T(e);if(await hi(e)){a.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Ri(e);await Ve(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await M`gh pr merge ${o} --squash --admin`})},xi=async()=>{M.quiet=!1,await Ve("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await M`gh workflow run deploy-all.yml --ref main -f environment=prod`}),M.quiet=!0},Ci=async()=>{await Ve("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 M`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Pi=async e=>{let r=await be();if(!r){a.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=D(e);await Bt({versionName:t},r)}catch(t){a.error({err:Ut(t)},"Failed to deliver Jira release (non-blocking)")}},zr=async e=>{let{version:r,confirmedCommand:t}=e;d.start("release-deliver");let{selectedReleaseBranch:o,releasePrTitle:n}=r?await wi(r):await vi(),s=R(o);if(!s)throw new g(void 0,{operation:`deliver release ${o}`,remediation:'pass a version (e.g. "1.2.5") or a release name (e.g. "checkout-redesign")'});let i=T(s);d.addOption("--version",i),a.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let l=C(n),c=t?!0:await ui({message:`Are you sure you want to deliver version ${o} to production?`});t||d.setInteractive(),c||(a.info("Operation cancelled. Exiting..."),gi.exit(0)),d.addOption("--yes",!0),M.quiet=!0,await ki(o),await yi({selectedReleaseBranch:o,releaseType:l}),l!=="hotfix"&&await bi(s),await xi(),await Ci(),M.quiet=!1,await Pi(s),a.info(`Successfully delivered ${o} to production!`),d.print();let p={releaseBranch:o,version:i,type:l,success:!0};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},Ei=v({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:kr.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:kr.string().describe("The release branch that was delivered"),version:kr.string().describe("The version that was delivered"),type:kr.enum(["regular","hotfix"]).describe("Release type"),success:kr.boolean().describe("Whether the delivery was successful")},handler:zr});import Uo from"@inquirer/select";import{z as se}from"zod";import{$ as Ht}from"zx";var Hr=async e=>{let{version:r,env:t,skipTerraform:o}=e;d.start("release-deploy-all");let n="";if(r)n=r==="dev"?"dev":H(r);else{d.setInteractive();let p=await P(),m=p.map(w=>w.branch),u=new Map(p.map(w=>[w.branch,C(w.title)])),f=await $();n=await Uo({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:m,descriptions:f,types:u})]})}let s=fr(n);d.addOption("--version",s);let{environments:i}=await x(),l="";if(t?l=t:(d.setInteractive(),l=await Uo({message:"\u{1F9EA} Select environment",choices:i.map(p=>({name:p,value:p}))})),d.addOption("--env",l),!i.includes(l))throw new g(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${i.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let c=o??!1;c&&d.addOption("--skip-terraform",!0);try{Ht.quiet=!0,await Ht`gh workflow run deploy-all.yml --ref ${n} -f environment=${l} ${c?["-f","skip_terraform_deploy=true"]:[]}`,Ht.quiet=!1,a.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${n} and environment: ${l}`),d.print();let m={releaseBranch:n,version:s,environment:l,skipTerraformDeploy:c,success:!0};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw a.error({error:p},"\u274C Error launching workflow"),new g(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},Ti=v({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:se.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/n/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:se.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:se.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:se.string().describe("The release branch that was deployed"),version:se.string().describe("The version that was deployed"),environment:se.string().describe("The environment deployed to"),skipTerraformDeploy:se.boolean().describe("Whether terraform deployment was skipped"),success:se.boolean().describe("Whether the deployment was successful")},handler:Hr});import $i from"@inquirer/checkbox";import qo from"@inquirer/select";import Si from"node:fs/promises";import{resolve as Ii}from"node:path";import Ai from"yaml";import{z as V}from"zod";import{$ as Xt}from"zx";var Xr=async e=>{let{version:r,env:t,services:o,skipTerraform:n}=e;d.start("release-deploy-selected");let s="";if(r)s=r==="dev"?"dev":H(r);else{d.setInteractive();let w=await P(),S=w.map(Te=>Te.branch),I=new Map(w.map(Te=>[Te.branch,C(Te.title)])),_=await $();s=await qo({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:S,descriptions:_,types:I})]})}let i=fr(s);d.addOption("--version",i);let{environments:l}=await x(),c="";if(t?c=t:(d.setInteractive(),c=await qo({message:"\u{1F9EA} Select environment",choices:l.map(w=>({name:w,value:w}))})),d.addOption("--env",c),!l.includes(c))throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${c}`});let p=await Ni();if(p.length===0)throw new g(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 m=[];if(o&&o.length>0?m=o:(d.setInteractive(),m=await $i({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(w=>({name:w,value:w}))})),d.addOption("--services",m),m.length===0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let u=m.filter(w=>!p.includes(w));if(u.length>0)throw new g(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${u.join(", ")}`});let f=n??!1;f&&d.addOption("--skip-terraform",!0);try{Xt.quiet=!0;let w=m.flatMap(_=>["-f",`${_}=true`]);await Xt`gh workflow run deploy-selected-services.yml --ref ${s} -f environment=${c} ${w} ${f?["-f","skip_terraform_deploy=true"]:[]}`,Xt.quiet=!1,a.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${s}, environment: ${c}, services: ${m.join(", ")}`),d.print();let I={releaseBranch:s,version:i,environment:c,services:m,skipTerraformDeploy:f,success:!0};return{content:h(JSON.stringify(I,null,2)),structuredContent:I}}catch(w){throw a.error({error:w},"\u274C Error launching workflow"),new g(w,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},Ni=async()=>{let e=await b(),r=Ii(e,".github/workflows/deploy-selected-services.yml"),t=await Si.readFile(r,"utf-8"),n=Ai.parse(t).on.workflow_dispatch.inputs,s=[];for(let[i,l]of Object.entries(n))l.type==="boolean"&&i!=="skip_terraform_deploy"&&s.push(i);return s},_i=v({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:V.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/n/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:V.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:V.array(V.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:V.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:V.string().describe("The release branch that was deployed"),version:V.string().describe("The version that was deployed"),environment:V.string().describe("The environment deployed to"),services:V.array(V.string()).describe("The services that were deployed"),skipTerraformDeploy:V.boolean().describe("Whether terraform deployment was skipped"),success:V.boolean().describe("Whether the deployment was successful")},handler:Xr});import{z as Je}from"zod";var Yr=async()=>{let r=(await P()).flatMap(i=>{let l=R(i.branch);return l?[{version:T(l),jiraKey:D(l),type:C(i.title)}]:[]}),t=await $(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let l=Le(i.version,i.type,o),c=t.get(i.jiraKey);return c?`${l} ${c}`:l});a.info(`All release branches:
|
|
72
85
|
`),a.info(`
|
|
73
|
-
${
|
|
86
|
+
${n.join(`
|
|
74
87
|
`)}
|
|
75
|
-
`);let
|
|
76
|
-
|
|
88
|
+
`);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}},Oi=v({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:Je.array(Je.object({version:Je.string().describe("Release version"),type:Je.enum(["regular","hotfix"]).describe("Release type"),description:Je.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:Je.number().describe("Number of release branches")},handler:Yr});import rn from"@inquirer/confirm";import Qo from"@inquirer/select";import et from"node:process";import{z as E}from"zod";import{question as so}from"zx";import{$ as Qr}from"zx";var ie=e=>e.slice(1).split(".").map(Number),Yt=e=>[...e].sort((r,t)=>{let[o,n,s]=ie(r),[i,l,c]=ie(t);return o!==i?(o??0)-(i??0):n!==l?(n??0)-(l??0):(s??0)-(c??0)});var Ho="next",ji=/^v?(\d+)\.(\d+)\.(\d+)$/,Fi=e=>e.replace(/^.*release\//,""),Xo=e=>{let r=Fi(e.trim()),t=ji.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},zo=e=>`${e[0]}.${e[1]}.${e[2]}`,Qt=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=Xo(n);if(!s)continue;let i=zo(s);o.has(i)||(o.add(i),t.push(s))}return Yt(t.map(n=>zo(n))).map(n=>ie(`v${n}`))},Ce=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},Zr=(e,r)=>{if(e.length===0)throw new Ce;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,l=e.reduce((c,p)=>p[0]===s&&p[1]===i?Math.max(c,p[2]):c,0);return`${s}.${i}.${l+1}`}let[o,n]=t;return`${o}.${n+1}.0`},Yo=e=>e.trim().toLowerCase()===Ho,Mi=e=>e==="regular"||e==="hotfix",Zo=e=>"name"in e,eo=e=>{let r=e.trim();if(r==="")throw new Error("Release spec is empty");let t=r.indexOf(":");if(t===-1)return{version:r,type:"regular"};let o=r.slice(0,t).trim(),n=r.slice(t+1),s=n.indexOf(":"),i=s===-1?n.trim():n.slice(0,s).trim(),l=s===-1?"":n.slice(s+1).trim(),c=i.toLowerCase();if(!Mi(c))throw new Error(`Invalid release type "${i}". Expected "regular" or "hotfix".`);let p={version:o,type:c};return l!==""&&(p.description=l),p},Zt=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,Di=e=>{let r=e.name.trim();return me(r),Zt({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},ro=(e,r)=>{let t=[...r];return e.map(o=>{if(Zo(o))return Di(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(Yo(n)){let l=Zr(t,o.type);return t.push(ie(`v${l}`)),Zt({id:G(l),type:o.type},o.description)}let s=Xo(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),Zt({id:G(i),type:o.type},o.description)})},to=e=>e.some(r=>!Zo(r)&&Yo(r.version));var Li=e=>e.split(`
|
|
89
|
+
`).map(r=>{let t=r.indexOf(" ");return t===-1?null:R(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),Wi=async()=>{let e=Qr.quiet;try{Qr.quiet=!0;let r=await Qr`git ls-remote --heads origin 'release/v*'`;return Li(r.stdout)}finally{Qr.quiet=e}},Vi=async()=>{let e=await be();return e?(await Me(e)).map(t=>t.name):[]},oo=async()=>{let[e,r]=await Promise.allSettled([Wi(),Vi()]);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"),Qt({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};var Ji='"1.2.5" or "next"',Bi=(e,r)=>{try{return Zr(e,r)}catch(t){if(t instanceof Ce)return null;throw t}},no=(e,r)=>{try{return ro(e,r)}catch(t){throw t instanceof Ce?new g(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 U?new g(t,{operation:"validate release name",remediation:'use a kebab-case name like "checkout-redesign" (lowercase, digits, single hyphens, not a reserved word)'}):t}},Ki=async(e,r)=>{let t=Bi(e,r),o=t?` [${t}]`:"",n=(await so(` Version (e.g. ${Ji})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(a.error("No version provided. Exiting..."),et.exit(1)),s},Gi=async()=>{let e=(await so(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(a.error("No name provided. Exiting..."),et.exit(1));try{me(e)}catch(r){let t=r instanceof Error?r.message:String(r);a.error(`${t} Exiting...`),et.exit(1)}return e},Ui=async e=>{d.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,l=await Qo({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),c=await Qo({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),p;if(l==="name"){let u=await Gi();p=no([{name:u,type:c}],[])[0]}else{let u=await Ki(await o(),c);p=no([{version:u,type:c}],t)[0],p.id.kind==="version"&&t.push(ie(`v${p.id.raw}`))}let m=(await so(" Description (optional, press Enter to skip): ")).trim();n.push({...p,...m!==""?{description:m}:{}}),s=await rn({message:"Add another release?",default:!1})}return n},qi=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 ")},en=e=>{for(let r of e){if(r.id.kind==="name"){d.addOption("--name",r.id.name);continue}let t=r.description?`${r.id.raw}:${r.type}:${r.description}`:`${r.id.raw}:${r.type}`;d.addOption("--release",t)}},zi=async(e,r)=>{if(e&&e.length>0){let o=to(e)?await r():[],n=no(e,o);return en(n),n}let t=await Ui(r);return en(t),t},Hi=async(e,r)=>{let t=e.map(qi).join(`
|
|
90
|
+
- `),o=r?!0:await rn({message:`Create the following ${e.length} release(s)?
|
|
77
91
|
- ${t}
|
|
78
|
-
`});r||d.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),
|
|
79
|
-
`),{result:
|
|
80
|
-
`),{failure:{version:
|
|
92
|
+
`});r||d.setInteractive(),o||(a.info("Operation cancelled. Exiting..."),et.exit(0)),d.addOption("--yes",!0)},Xi=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 Kt(r.type);let s=await Gt({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}
|
|
93
|
+
`),{result:s}}catch(s){let i=new g(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}
|
|
94
|
+
`),{failure:{version:o,error:i.message}}}},Yi=(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.`)},rt=async e=>{let{releases:r,confirmedCommand:t}=e;d.start("release-create");let o=await De(),n=null,i=await zi(r,async()=>(n===null&&(n=await oo()),n));if(i.length===0)throw new g(void 0,{operation:"create release",remediation:'pass at least one entry in "releases" (e.g. [{ version: "1.2.5", type: "regular" }])',stderrExcerpt:"no releases provided"});await Hi(i,!!t);let l=[],c=[];for(let m of i){let{result:u,failure:f}=await Xi({entry:m,jiraConfig:o});u&&l.push(u),f&&c.push(f)}Yi(i.length,l.length,c.length),d.print();let p={createdBranches:l.map(m=>m.branchName),successCount:l.length,failureCount:c.length,releases:l,failedReleases:c};return{content:h(JSON.stringify(p,null,2)),structuredContent:p}},Zi=v({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, so regular and hotfix releases can be mixed in the same invocation. 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/n/<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 across mixed types. Named releases never auto-bump and "next" is version-only. 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:rt});import Qi from"@inquirer/confirm";import ea from"@inquirer/select";import ra from"node:process";import{z as ae}from"zod";import{question as ta}from"zx";var tn=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,oa=(e,r)=>r.trim()!==""?`${e}
|
|
81
95
|
|
|
82
96
|
${r}`:`${e}
|
|
83
|
-
`,
|
|
84
|
-
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},
|
|
85
|
-
from: "${
|
|
86
|
-
to: "${
|
|
87
|
-
`});o||d.setInteractive(),f||(a.info("Operation cancelled. Exiting..."),
|
|
88
|
-
`),d.print();let
|
|
89
|
-
`,"utf-8"),{added:c,skipped:p}};import
|
|
90
|
-
`,"utf-8");let m=[],
|
|
97
|
+
`,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 $(),n=await ea({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})});return{branch:n,type:t.get(n)||"regular"}},sa=async e=>{let t=(await P()).find(o=>o.branch===e);if(!t)throw new g(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return C(t.title)},ia=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await ta(` New description ${r}
|
|
98
|
+
(press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},tt=async e=>{let{version:r,description:t,confirmedCommand:o}=e;d.start("release-desc-edit");let n=await De(),s;r?(s=H(r),await sa(s)):(d.setInteractive(),s=(await na()).branch);let i=R(s);if(!i)throw new g(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 l=T(i);d.addOption("--version",l);let c=D(i),p=await Wr(c,n);if(!p)throw new g(void 0,{operation:`edit description for ${c}`,remediation:`create the Jira fix version "${c}" first or pick a different release`});let m=p.description??"",u;if(t!==void 0?(u=t,d.addOption("--description",u)):(d.setInteractive(),u=await ia(m)),u===m){a.info(`No change \u2014 description for ${c} is already: "${m}"`),d.print();let _={version:l,branch:s,jiraVersionUrl:tn(n,p),previousDescription:m,newDescription:u,changed:!1};return{content:h(JSON.stringify(_,null,2)),structuredContent:_}}let f=o?!0:await Qi({message:`Update description for ${c}?
|
|
99
|
+
from: "${m}"
|
|
100
|
+
to: "${u}"
|
|
101
|
+
`});o||d.setInteractive(),f||(a.info("Operation cancelled. Exiting..."),ra.exit(0)),d.addOption("--yes",!0),await Vr({versionId:p.id,description:u},n);let w=tn(n,p),S=oa(w,u);await Ur({branch:s,body:S}),a.info(`\u2705 Updated description for ${c}`),a.info(`\u{1F517} Jira Version: ${w}`),a.info(`\u{1F517} PR branch: ${s}
|
|
102
|
+
`),d.print();let I={version:l,branch:s,jiraVersionUrl:w,previousDescription:m,newDescription:u,changed:!0};return{content:h(JSON.stringify(I,null,2)),structuredContent:I}},aa=v({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/n/<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:ae.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:ae.string().describe("New description. Empty string clears the description.")},outputSchema:{version:ae.string().describe("Release version"),branch:ae.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/n/checkout-redesign")'),jiraVersionUrl:ae.string().describe("Jira fix version URL"),previousDescription:ae.string().describe("The description before the update"),newDescription:ae.string().describe("The description after the update"),changed:ae.boolean().describe("Whether the description actually changed")},handler:tt});import{z as ca}from"zod";var ot=async()=>{let e=Ar.version;a.info(e);let r={version:e};return{content:h(JSON.stringify(r,null,2)),structuredContent:r}},la=v({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:ca.string().describe("Installed infra-kit CLI version (from package.json)")},handler:ot});import ma from"@inquirer/checkbox";import ao from"@inquirer/confirm";import da from"@inquirer/select";import ua from"node:process";import{z as ce}from"zod";import{$ as Ee}from"zx";import on from"node:fs/promises";import nt from"node:path";var yr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=nt.dirname(r),n;try{n=await on.readFile(r,"utf-8")}catch(m){throw new Error(`Cursor workspace file not found at ${r}: ${m.message}`)}let s;try{s=JSON.parse(n)}catch(m){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${m.message}`)}let i=s.folders??[],l=new Set(i.map(m=>nt.resolve(o,m.path))),c=[],p=[];for(let m of t){let u=nt.resolve(m);if(l.has(u)){p.push(m);continue}let f=nt.relative(o,u);i.push({path:f}),l.add(u),c.push(m)}return s.folders=i,await on.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
103
|
+
`,"utf-8"),{added:c,skipped:p}};import pa from"node:fs/promises";import it from"node:path";import nn from"node:fs/promises";import st from"node:path";var Pe=async e=>{let{workspacePath:r,folderPaths:t}=e,o=st.dirname(r),n;try{n=await nn.readFile(r,"utf-8")}catch(f){throw new Error(`Cursor workspace file not found at ${r}: ${f.message}`)}let s;try{s=JSON.parse(n)}catch(f){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${f.message}`)}let i=s.folders??[],l=new Set(t.map(f=>st.resolve(f))),c=new Set,p=i.filter(f=>{let w=st.resolve(o,f.path);return l.has(w)?(c.add(w),!1):!0});s.folders=p,await nn.writeFile(r,`${JSON.stringify(s,null,2)}
|
|
104
|
+
`,"utf-8");let m=[],u=[];for(let f of t){let w=st.resolve(f);c.has(w)?m.push(f):u.push(f)}return{removed:m,notFound:u}};var io=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=it.dirname(r),s=it.resolve(`${t}/release`),i=await pa.readFile(r,"utf-8"),c=JSON.parse(i).folders??[],p=new Set(o.map(S=>it.resolve(`${t}/${S}`))),m=[];for(let S of c){let I=it.resolve(n,S.path);(I===s||I.startsWith(`${s}/`))&&!p.has(I)&&m.push(I)}let u=[];m.length>0&&(u=(await Pe({workspacePath:r,folderPaths:m})).removed);let f=o.map(S=>`${t}/${S}`),{added:w}=f.length>0?await yr({workspacePath:r,folderPaths:f}):{added:[]};return{added:w,removed:u}};import sn from"node:path";var Y=(e,r)=>sn.isAbsolute(e)?e:sn.resolve(r,e);var fa="feature",ga="release",Rr=["workspace","windows","none"],at=async e=>{let{confirmedCommand:r,all:t,versions:o,cursor:n,githubDesktop:s,cmux:i}=e;d.start("worktrees-add");try{let l=await j("release"),c=await b(),p=`${c}${B}`;await an(`${p}/${ga}`),await an(`${p}/${fa}`);let m=[];if(o)m=o.split(",").map(O=>q(G(O.trim())));else{let O=await P(),Z=O.map(pe=>pe.branch);if(Z.length===0)return a.info("\u2139\uFE0F No open release branches found"),d.print(),{content:h(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)m=Z;else{d.setInteractive();let pe=new Map(O.map(Cr=>[Cr.branch,C(Cr.title)])),xr=await $();m=await ma({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:Z,descriptions:xr,types:pe})})}}t?d.addOption("--all",!0):d.addOption("--versions",xe(m));let u=r?!0:await ao({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),u||(a.info("Operation cancelled. Exiting..."),ua.exit(0)),r||d.addOption("--yes",!0);let f=await x(),w=f.ide?.provider==="cursor"?f.ide.config:void 0,S=n??w?.mode??await da({message:"Cursor mode for created worktrees?",default:"workspace",choices:[{name:"Add to workspace file",value:"workspace",description:"Append each worktree as a folder in ide.config.workspaceConfigPath, then open the workspace"},{name:"Open separate windows",value:"windows",description:"Open each created worktree in its own Cursor window"},{name:"Skip",value:"none",description:"Do not open Cursor"}]});typeof n>"u"&&!w?.mode&&d.setInteractive(),d.addOption("--cursor",S);let I=s??f.worktrees?.openInGithubDesktop??await ao({message:"Open created worktrees in GitHub Desktop?"});typeof s>"u"&&f.worktrees?.openInGithubDesktop===void 0&&d.setInteractive(),I?d.addOption("--github-desktop",!0):d.addOption("--no-github-desktop",!0);let _=i??f.worktrees?.openInCmux??await ao({message:"Open created worktrees in cmux?"});typeof i>"u"&&f.worktrees?.openInCmux===void 0&&d.setInteractive(),_?d.addOption("--cmux",!0):d.addOption("--no-cmux",!0);let{branchesToCreate:Te}=ha({selectedReleaseBranches:m,currentWorktrees:l}),le=await wa(Te,p);if(va(le),S==="workspace")if(!w?.workspaceConfigPath)a.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config");else{let O=Y(w.workspaceConfigPath,c),Z=le.map(mn=>`${p}/${mn}`),{added:pe,skipped:xr}=await yr({workspacePath:O,folderPaths:Z}),Cr=xr.length>0?` (${xr.length} already present)`:"";a.info(`\u2705 Added ${pe.length} folder(s) to ${O}${Cr}`),await Ee`cursor ${O}`}else if(S==="windows")for(let O of le)await Ee`cursor ${p}/${O}`;if(I)for(let O of le)await Ee`github ${p}/${O}`,await Ee`sleep 5`;if(_){let O=await F();for(let Z of le){let pe=X({repoName:O,branch:Z});await wr({cwd:`${p}/${Z}`,title:pe})}}d.print();let lo={createdWorktrees:le,count:le.length};return{content:h(JSON.stringify(lo,null,2)),structuredContent:lo}}catch(l){throw a.error({error:l},"\u274C Error managing worktrees"),new g(l,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"})}},an=async e=>{await Ee`mkdir -p ${e}`},ha=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>de(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},wa=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Ee`git worktree add ${s} ${n}`,await Ee({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],l=new g(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:l.message})}return o},va=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")},ka=v({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:ce.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:ce.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.'),cursor:ce.enum(Rr).optional().describe('Cursor open mode for created worktrees. "workspace" appends each worktree as a folder to "ide.config.workspaceConfigPath" in infra-kit config and opens the workspace. "windows" opens each worktree in its own Cursor window. "none" skips Cursor. Resolution order: this flag \u2192 "ide.config.mode" from infra-kit config \u2192 interactive prompt (CLI) / "none" (MCP, no TTY).'),githubDesktop:ce.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:ce.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:ce.array(ce.string()).describe("List of created git worktree branches"),count:ce.number().describe("Number of git worktrees created")},handler:at});import{z as Be}from"zod";var ct=async()=>{let e=await j("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(),$()]),o=new Map(r.map(c=>[c.branch,C(c.title)])),n=e.flatMap(c=>{let p=R(c);if(!p)return[];let m=T(p),u=o.get(c)||"regular",f=t.get(D(p))||null;return[{version:m,type:u,description:f}]}),s=Math.max(...n.map(c=>c.version.length)),i=n.map(c=>{let p=Le(c.version,c.type,s);return c.description?`${p} ${c.description}`:p});a.info("\u{1F33F} Active worktrees:"),a.info(`
|
|
91
105
|
${i.join(`
|
|
92
106
|
`)}
|
|
93
|
-
`);let l={worktrees:s,count:s.length};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},gn=v({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:we.array(we.object({version:we.string().describe("Release version"),type:we.enum(["regular","hotfix"]).describe("Release type"),description:we.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:we.number().describe("Number of worktrees")},handler:kr});import{z as ve}from"zod/v4";import{$ as hn}from"zx";var Rr=async()=>{d.start("worktrees-open");try{let e=await E(),r=`${e}${F}`,t=await _("release"),o=await wn({projectRoot:e,worktreeDir:r,currentBranches:t}),s=await vn({worktreeDir:r,currentBranches:t}),n={openedCmux:s.opened,skippedCmux:s.skipped,cursorFoldersAdded:o.added,cursorFoldersRemoved:o.removed};return yn(n,{cursorRan:o.ran,cmuxRan:s.ran}),d.print(),{content:g(JSON.stringify(n,null,2)),structuredContent:{...n}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),new w(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},wn=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e,s=await R(),n=s.ide?.provider==="cursor"?s.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return a.warn('\u26A0\uFE0F Skipping Cursor: ide.provider must be "cursor", mode "workspace", and workspaceConfigPath set.'),{ran:!1,added:0,removed:0};let i=L(n.workspaceConfigPath,r);try{let{added:l,removed:c}=await Xr({workspacePath:i,worktreeDir:t,currentBranches:o});return await hn`cursor ${i}`,{ran:!0,added:l.length,removed:c.length}}catch(l){return a.warn({error:l},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${i}`),{ran:!1,added:0,removed:0}}},vn=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let o=await O(),s=await zr(),n=[],i=[];for(let l of t){let c=W({repoName:o,branch:l});if(s.has(c)){i.push(c);continue}try{await _e({cwd:`${r}/${l}`,title:c}),n.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:n,skipped:i}},yn=(e,r)=>{if(r.cursorRan&&(e.cursorFoldersAdded>0&&a.info(`\u2705 Added ${e.cursorFoldersAdded} folder(s) to Cursor workspace`),e.cursorFoldersRemoved>0&&a.info(`\u{1F9F9} Removed ${e.cursorFoldersRemoved} dangling folder(s) from Cursor workspace`)),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.cursorRan&&e.openedCmux.length===0&&e.skippedCmux.length===0&&e.cursorFoldersAdded===0&&e.cursorFoldersRemoved===0&&a.info("\u2139\uFE0F Nothing to open")},kn=v({name:"worktrees-open",description:"Open Cursor against the configured workspace file 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 (Cursor + cmux closed). For stale-worktree cleanup, use worktrees-sync.",inputSchema:{},outputSchema:{openedCmux:ve.array(ve.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:ve.array(ve.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:ve.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:ve.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:Rr});import Rn from"@inquirer/checkbox";import bn from"@inquirer/confirm";import Cn from"node:process";import{z as Me}from"zod/v4";var br=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;d.start("worktrees-remove");try{let s=await _("release");if(s.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),d.print(),{content:g(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let n=await E(),i=`${n}${F}`,l=[];if(t)l=s;else if(o)l=o.split(",").map(h=>`release/v${h.trim()}`);else{d.setInteractive();let[h,$]=await Promise.all([T(),C()]),P=new Map($.map(M=>[M.branch,b(M.title)]));l=await Rn({required:!0,message:"\u{1F33F} Select release branches",choices:I({branches:s,descriptions:h,types:P})})}let c=l.length===s.length;c?d.addOption("--all",!0):d.addOption("--versions",l.map(h=>h.replace("release/v","")));let p=r?!0:await bn({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),Cn.exit(0)),r||d.addOption("--yes",!0);let m=await O(),f=await Oe({branches:l,worktreeDir:i,repoName:m,pruneFolder:c});await xn({removedWorktrees:f,worktreeDir:i,projectRoot:n}),Tn(f),d.print();let u={removedWorktrees:f,count:f.length};return{content:g(JSON.stringify(u,null,2)),structuredContent:u}}catch(s){throw a.error({error:s},"\u274C Error managing worktrees"),new w(s,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},xn=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let s=await R(),n=s.ide?.provider==="cursor"?s.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=L(n.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await Z({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},Tn=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")},$n=v({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:Me.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:Me.string().optional().describe('Comma-separated release versions to target (e.g. "1.2.5, 1.2.6"). Either "versions" or all=true must be provided for MCP calls. Overrides "all" when set.')},outputSchema:{removedWorktrees:Me.array(Me.string()).describe("List of removed git worktree branches"),count:Me.number().describe("Number of git worktrees removed")},handler:br});import Pn from"@inquirer/confirm";import En from"node:process";import{z as Zr}from"zod/v4";import{$ as Sn}from"zx";var In="release/v",Cr=async e=>{let{confirmedCommand:r}=e;d.start("worktrees-sync");try{let t=await _("release"),o=await E(),s=`${o}${F}`,n=await ir(),i=r?!0:await Pn({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),En.exit(0)),r||d.addOption("--yes",!0);let{branchesToRemove:l}=An({releasePRsList:n,currentWorktrees:t}),c=await O(),p=await _n({branches:l,worktreeDir:s,repoName:c});await On({removedWorktrees:p,worktreeDir:s,projectRoot:o}),Nn(p),d.print();let m={removedWorktrees:p,count:p.length};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new w(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},An=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(n=>n.startsWith(In)).filter(n=>!r.includes(n))}},_n=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,s=[];for(let n of r)try{let i=`${t}/${n}`,l=W({repoName:o,branch:n});await Ie(l),await Sn`git worktree remove ${i}`,s.push(n)}catch(i){let l=new w(i,{operation:`remove stale worktree for ${n}`,remediation:"inspect the worktree dir manually; rerun with the branch checked out elsewhere"});a.error({error:i,branch:n,msg:l.message})}return s},On=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let s=await R(),n=s.ide?.provider==="cursor"?s.ide.config:void 0;if(!n||n.mode!=="workspace"||!n.workspaceConfigPath)return;let i=L(n.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await Z({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},Nn=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")},Dn=v({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:Zr.array(Zr.string()).describe("List of removed worktree branches"),count:Zr.number().describe("Number of worktrees removed during sync")},handler:Cr});var k=new Mn,Fn=(e,r)=>[...r,e],Wn=e=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&je.includes(e))return e;throw new Error(`Invalid --cursor value "${String(e)}". Expected one of: ${je.join(", ")}.`)}},Jt=async e=>{try{e?await k.parseAsync(e):await k.parseAsync()}catch(r){let t=r instanceof Error?r.message:String(r);a.error(t),Qr.exit(1)}};k.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 cr({all:e.all,confirmedCommand:e.yes})});k.command("release-list").description("List all release branches").action(async()=>{await dr()});k.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[:type[:description]]" (repeatable). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend"',Fn,[]).option("-y, --yes","Skip confirmation prompt").action(async e=>{let r=e.release,t=r.length>0?r.map(Jr):void 0;await ur({releases:t,confirmedCommand:e.yes})});k.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").option("-d, --description <description>",'New description (use "" to clear)').option("-y, --yes","Skip confirmation prompt").action(async e=>{await fr({version:e.version,description:e.description,confirmedCommand:e.yes})});k.command("release-deploy-all").description("Deploy any release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").option("-e, --env <env>","Specify the environment to deploy to, e.g. dev").option("--skip-terraform","Skip terraform deployment step").action(async e=>{await pr({version:e.version,env:e.env,skipTerraform:e.skipTerraform})});k.command("release-deploy-selected").description("Deploy selected services from release branch to any environment").option("-v, --version <version>","Specify the version to deploy, e.g. 1.2.5").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 mr({version:e.version,env:e.env,services:e.services,skipTerraform:e.skipTerraform})});k.command("release-deliver").description("Release a new version to production").option("-v, --version <version>","Specify the version to release, e.g. 1.2.5").option("-y, --yes","Skip confirmation prompt").action(async e=>{await lr({version:e.version,confirmedCommand:e.yes})});k.command("worktrees-sync").description("Remove release worktrees whose PRs are no longer open").option("-y, --yes","Skip confirmation prompt").action(async e=>{await Cr({confirmedCommand:e.yes})});k.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("-c, --cursor [mode]","Cursor mode for created worktrees: workspace (default) | windows | none").option("--no-cursor","Skip Cursor (alias for --cursor none)").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=>{await yr({confirmedCommand:e.yes,all:e.all,versions:e.versions,cursor:Wn(e.cursor),githubDesktop:e.githubDesktop,cmux:e.cmux})});k.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await kr()});k.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 br({confirmedCommand:e.yes,all:e.all,versions:e.versions})});k.command("worktrees-open").description("Open Cursor + cmux for existing release worktrees (cold-start restore)").action(async()=>{await Rr()});var Vt=k.command("config").description("Manage infra-kit configuration files");Vt.command("path").description("Show the resolved config merge chain and file paths").action(async()=>{await $r()});Vt.command("edit").description("Open the user-scope per-project override file in $EDITOR").action(async()=>{await Pr()});k.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await Ve()});k.command("version").description("Print the installed infra-kit CLI version").action(async()=>{await gr()});k.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await Ze()});k.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await He()});k.command("init").description("Inject shell integration into your profile .zshrc").action(async()=>{await Sr()});k.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 Ye({config:e.config})});k.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await Ue()});if(Qr.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-remove","worktrees-sync"],t=["doctor","init","version","config","env-status","env-list","env-load","env-clear"],o=new Map(k.commands.map(c=>[c.name(),c])),s=[...e,...r,...t],n=Math.max(...s.map(c=>c.length)),i=c=>c.filter(p=>o.has(p)).map(p=>({name:`${p.padEnd(n)} ${o.get(p).description()}`,value:p})),l=await jn({message:"Select a command to run",choices:[new ye(" "),new ye("\u2014 Release Management \u2014"),...i(e),new ye(" "),new ye("\u2014 Worktrees \u2014"),...i(r),new ye(" "),new ye("\u2014 Environment \u2014"),...i(t)]},{output:Qr.stderr});await Jt(["node","infra-kit",l])}else await Jt();
|
|
107
|
+
`);let l={worktrees:n,count:n.length};return{content:h(JSON.stringify(l,null,2)),structuredContent:l}},ya=v({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:Be.array(Be.object({version:Be.string().describe("Release version"),type:Be.enum(["regular","hotfix"]).describe("Release type"),description:Be.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:Be.number().describe("Number of worktrees")},handler:ct});import{z as Ke}from"zod";import{$ as Ra}from"zx";var lt=async()=>{d.start("worktrees-open");try{let e=await b(),r=`${e}${B}`,t=await j("release"),o=await ba({projectRoot:e,worktreeDir:r,currentBranches:t}),n=await xa({worktreeDir:r,currentBranches:t}),s={openedCmux:n.opened,skippedCmux:n.skipped,cursorFoldersAdded:o.added,cursorFoldersRemoved:o.removed};return Ca(s,{cursorRan:o.ran,cmuxRan:n.ran}),d.print(),{content:h(JSON.stringify(s,null,2)),structuredContent:{...s}}}catch(e){throw a.error({error:e},"\u274C Error opening worktrees"),new g(e,{operation:"open worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},ba=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e,n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return a.warn('\u26A0\uFE0F Skipping Cursor: ide.provider must be "cursor", mode "workspace", and workspaceConfigPath set.'),{ran:!1,added:0,removed:0};let i=Y(s.workspaceConfigPath,r);try{let{added:l,removed:c}=await io({workspacePath:i,worktreeDir:t,currentBranches:o});return await Ra`cursor ${i}`,{ran:!0,added:l.length,removed:c.length}}catch(l){return a.warn({error:l},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${i}`),{ran:!1,added:0,removed:0}}},xa=async e=>{let{worktreeDir:r,currentBranches:t}=e;if(t.length===0)return{ran:!0,opened:[],skipped:[]};let o=await F(),n=await qt(),s=[],i=[];for(let l of t){let c=X({repoName:o,branch:l});if(n.has(c)){i.push(c);continue}try{await wr({cwd:`${r}/${l}`,title:c}),s.push(c)}catch(p){a.warn({error:p,title:c},`\u26A0\uFE0F Failed to open cmux workspace for ${l}`)}}return{ran:!0,opened:s,skipped:i}},Ca=(e,r)=>{if(r.cursorRan&&(e.cursorFoldersAdded>0&&a.info(`\u2705 Added ${e.cursorFoldersAdded} folder(s) to Cursor workspace`),e.cursorFoldersRemoved>0&&a.info(`\u{1F9F9} Removed ${e.cursorFoldersRemoved} dangling folder(s) from Cursor workspace`)),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.cursorRan&&e.openedCmux.length===0&&e.skippedCmux.length===0&&e.cursorFoldersAdded===0&&e.cursorFoldersRemoved===0&&a.info("\u2139\uFE0F Nothing to open")},Pa=v({name:"worktrees-open",description:"Open Cursor against the configured workspace file 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 (Cursor + cmux closed). For stale-worktree cleanup, use worktrees-sync.",inputSchema:{},outputSchema:{openedCmux:Ke.array(Ke.string()).describe("Titles of cmux workspaces opened during this run"),skippedCmux:Ke.array(Ke.string()).describe("Titles of cmux workspaces that were already open"),cursorFoldersAdded:Ke.number().describe("Number of worktree folders added to the Cursor workspace file"),cursorFoldersRemoved:Ke.number().describe("Number of dangling worktree folders removed from the Cursor workspace file")},handler:lt});import Ea from"@inquirer/checkbox";import Ta from"@inquirer/confirm";import $a from"node:process";import{z as br}from"zod";var pt=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;d.start("worktrees-remove");try{let n=await j("release");if(n.length===0)return a.info("\u2139\uFE0F No active worktrees to remove"),d.print(),{content:h(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await b(),i=`${s}${B}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(w=>q(G(w.trim())));else{d.setInteractive();let[w,S]=await Promise.all([$(),P()]),I=new Map(S.map(_=>[_.branch,C(_.title)]));l=await Ea({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:w,types:I})})}let c=l.length===n.length;c?d.addOption("--all",!0):d.addOption("--versions",xe(l));let p=r?!0:await Ta({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),p||(a.info("Operation cancelled. Exiting..."),$a.exit(0)),r||d.addOption("--yes",!0);let m=await F(),u=await vr({branches:l,worktreeDir:i,repoName:m,pruneFolder:c});await Sa({removedWorktrees:u,worktreeDir:i,projectRoot:s}),Ia(u),d.print();let f={removedWorktrees:u,count:u.length};return{content:h(JSON.stringify(f,null,2)),structuredContent:f}}catch(n){throw a.error({error:n},"\u274C Error managing worktrees"),new g(n,{operation:"remove worktrees",remediation:"check 'git worktree list' for the path; uncommitted changes block removal"})}},Sa=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let i=Y(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await Pe({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},Ia=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")},Aa=v({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:br.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:br.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:br.array(br.string()).describe("List of removed git worktree branches"),count:br.number().describe("Number of git worktrees removed")},handler:pt});import Na from"@inquirer/confirm";import _a from"node:process";import{z as co}from"zod";import{$ as Oa}from"zx";var mt=async e=>{let{confirmedCommand:r}=e;d.start("worktrees-sync");try{let t=await j("release"),o=await b(),n=`${o}${B}`,s=await Gr(),i=r?!0:await Na({message:"Are you sure you want to proceed with these worktree changes?"});r||d.setInteractive(),i||(a.info("Operation cancelled. Exiting..."),_a.exit(0)),r||d.addOption("--yes",!0);let{branchesToRemove:l}=ja({releasePRsList:s,currentWorktrees:t}),c=await F(),p=await Fa({branches:l,worktreeDir:n,repoName:c});await Ma({removedWorktrees:p,worktreeDir:n,projectRoot:o}),Da(p),d.print();let m={removedWorktrees:p,count:p.length};return{content:h(JSON.stringify(m,null,2)),structuredContent:m}}catch(t){throw a.error({error:t},"\u274C Error managing worktrees"),new g(t,{operation:"sync worktrees with remote",remediation:"ensure 'gh auth status' is ok and you can reach origin"})}},ja=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>de(s)).filter(s=>!r.includes(s))}},Fa=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,l=X({repoName:o,branch:s});await gr(l),await Oa`git worktree remove ${i}`,n.push(s)}catch(i){let l=new g(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:l.message})}return n},Ma=async e=>{let{removedWorktrees:r,worktreeDir:t,projectRoot:o}=e;if(r.length===0)return;let n=await x(),s=n.ide?.provider==="cursor"?n.ide.config:void 0;if(!s||s.mode!=="workspace"||!s.workspaceConfigPath)return;let i=Y(s.workspaceConfigPath,o),l=r.map(c=>`${t}/${c}`);try{let{removed:c}=await Pe({workspacePath:i,folderPaths:l});c.length>0&&a.info(`\u2705 Removed ${c.length} folder(s) from ${i}`)}catch(c){a.warn({error:c},`\u26A0\uFE0F Failed to update Cursor workspace at ${i}`)}},Da=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")},La=v({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:co.array(co.string()).describe("List of removed worktree branches"),count:co.number().describe("Number of worktrees removed during sync")},handler:mt});var y=new Va,cn=(e,r)=>[...r,e],Ja=e=>{if(!(typeof e>"u")){if(e===!0)return"workspace";if(e===!1)return"none";if(typeof e=="string"&&Rr.includes(e))return e;throw new Error(`Invalid --cursor value "${String(e)}". Expected one of: ${Rr.join(", ")}.`)}},ln=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),dt.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 qr({all:e.all,confirmedCommand:e.yes})});y.command("release-list").description("List all release branches").action(async()=>{await Yr()});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[:type[:description]]" (repeatable). Examples: "1.2.5", "1.2.5:hotfix", "next:regular:Holiday backend"',cn,[]).option("-n, --name <name>",'Named release (repeatable). Bare kebab-case name, e.g. "checkout-redesign". Creates a regular release; set a description later via release-desc-edit. Can be combined with --release.',cn,[]).option("-y, --yes","Skip confirmation prompt").action(async e=>{let r=e.release,t=e.name,o=r.map(eo),n=t.map(l=>({name:l,type:"regular"})),s=[...o,...n],i=s.length>0?s:void 0;await rt({releases:i,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 tt({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 Hr({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 Xr({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 zr({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 mt({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("-c, --cursor [mode]","Cursor mode for created worktrees: workspace (default) | windows | none").option("--no-cursor","Skip Cursor (alias for --cursor none)").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=>{await at({confirmedCommand:e.yes,all:e.all,versions:e.versions,cursor:Ja(e.cursor),githubDesktop:e.githubDesktop,cmux:e.cmux})});y.command("worktrees-list").description("List all git worktrees with detailed information").action(async()=>{await ct()});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 pt({confirmedCommand:e.yes,all:e.all,versions:e.versions})});y.command("worktrees-open").description("Open Cursor + cmux for existing release worktrees (cold-start restore)").action(async()=>{await lt()});var pn=y.command("config").description("Manage infra-kit configuration files");pn.command("path").description("Show the resolved config merge chain and file paths").action(async()=>{await $t()});pn.command("edit").description("Open the user-scope per-project override file in $EDITOR").action(async()=>{await St()});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 Tr({all:e.all,root:e.root})).structuredContent.allPassed||(dt.exitCode=1)});y.command("doctor").description("Check installation and authentication status of gh and doppler CLIs").action(async()=>{await _r()});y.command("version").description("Print the installed infra-kit CLI version").action(async()=>{await ot()});y.command("env-status").description("Show Doppler authentication status and detected project info").action(async()=>{await Lr()});y.command("env-list").description("List available Doppler configs for the detected project").action(async()=>{await Fr()});y.command("init").description("Inject shell integration into .zshrc and sync repo agent-instruction files").action(async()=>{await jt()});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 Dr({config:e.config})});y.command("env-clear").description("Clear loaded env vars. Source the returned file path to apply.").action(async()=>{await jr()});if(dt.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-remove","worktrees-sync"],t=["audit","doctor","init","version","config","env-status","env-list","env-load","env-clear"],o=new Map(y.commands.map(c=>[c.name(),c])),n=[...e,...r,...t],s=Math.max(...n.map(c=>c.length)),i=c=>c.filter(p=>o.has(p)).map(p=>({name:`${p.padEnd(s)} ${o.get(p).description()}`,value:p})),l=await Wa({message:"Select a command to run",choices:[new Ge(" "),new Ge("\u2014 Release Management \u2014"),...i(e),new Ge(" "),new Ge("\u2014 Worktrees \u2014"),...i(r),new Ge(" "),new Ge("\u2014 Environment \u2014"),...i(t)]},{output:dt.stderr});await ln(["node","infra-kit",l])}else await ln();
|
|
94
108
|
//# sourceMappingURL=cli.js.map
|