infra-kit 0.1.111 → 0.1.114

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