infra-kit 0.1.123 → 0.1.125

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 (46) hide show
  1. package/.eslintcache +1 -0
  2. package/.omc/state/agent-replay-2ccbd177-0d5d-4d4a-ab94-a22464786221.jsonl +1 -0
  3. package/.omc/state/agent-replay-eb44055b-c2fa-4e66-b491-a1d9b44f51c7.jsonl +1 -0
  4. package/.omc/state/idle-notif-cooldown.json +1 -1
  5. package/.omc/state/sessions/2ccbd177-0d5d-4d4a-ab94-a22464786221/pre-tool-advisory-throttle.json +18 -0
  6. package/.omc/state/sessions/2ccbd177-0d5d-4d4a-ab94-a22464786221/subagent-tracking-state.json +17 -0
  7. package/.omc/state/sessions/6be1264f-8069-4412-8119-86118ed1943e/pre-tool-advisory-throttle.json +5 -5
  8. package/.omc/state/sessions/eb44055b-c2fa-4e66-b491-a1d9b44f51c7/last-tool-error-state.json +7 -0
  9. package/.omc/state/sessions/eb44055b-c2fa-4e66-b491-a1d9b44f51c7/pre-tool-advisory-throttle.json +18 -0
  10. package/.omc/state/sessions/eb44055b-c2fa-4e66-b491-a1d9b44f51c7/subagent-tracking-state.json +17 -0
  11. package/.turbo/turbo-build.log +6 -6
  12. package/.turbo/turbo-eslint-check.log +1 -1
  13. package/.turbo/turbo-prettier-check.log +1 -1
  14. package/.turbo/turbo-test.log +128 -127
  15. package/.turbo/turbo-ts-check.log +1 -1
  16. package/dist/chunk-VI7TEWVJ.js +164 -0
  17. package/dist/chunk-VI7TEWVJ.js.map +7 -0
  18. package/dist/cli.js +6 -6
  19. package/dist/cli.js.map +3 -3
  20. package/dist/mcp.js +1 -1
  21. package/package.json +1 -1
  22. package/src/.omc/state/agent-replay-2ccbd177-0d5d-4d4a-ab94-a22464786221.jsonl +2 -0
  23. package/src/.omc/state/idle-notif-cooldown.json +1 -1
  24. package/src/.omc/state/sessions/2ccbd177-0d5d-4d4a-ab94-a22464786221/last-tool-error-state.json +7 -0
  25. package/src/.omc/state/sessions/2ccbd177-0d5d-4d4a-ab94-a22464786221/mission-state.json +53 -0
  26. package/src/.omc/state/sessions/2ccbd177-0d5d-4d4a-ab94-a22464786221/pre-tool-advisory-throttle.json +22 -0
  27. package/src/.omc/state/sessions/2ccbd177-0d5d-4d4a-ab94-a22464786221/subagent-tracking-state.json +17 -0
  28. package/src/commands/env-clear/env-clear.ts +4 -1
  29. package/src/commands/env-load/__tests__/env-load.test.ts +99 -66
  30. package/src/commands/env-load/env-load.ts +87 -35
  31. package/src/commands/init/__tests__/shell-body.test.ts +4 -4
  32. package/src/commands/init/init.ts +23 -24
  33. package/src/commands/worktrees-add/worktrees-add.ts +6 -0
  34. package/src/commands/worktrees-remove/worktrees-remove.ts +6 -0
  35. package/src/commands/worktrees-sync/worktrees-sync.ts +6 -0
  36. package/src/entry/cli.ts +60 -45
  37. package/src/lib/constants/__tests__/constants.test.ts +22 -0
  38. package/src/lib/constants/constants.ts +40 -4
  39. package/src/lib/constants/index.ts +1 -0
  40. package/src/lib/env-autoload/__tests__/env-autoload.test.ts +15 -1
  41. package/src/lib/env-autoload/env-autoload.ts +54 -6
  42. package/src/lib/errors/__tests__/is-prompt-cancellation.test.ts +48 -0
  43. package/src/lib/errors/is-prompt-cancellation.ts +38 -0
  44. package/tsconfig.tsbuildinfo +1 -1
  45. package/dist/chunk-YMXDO43V.js +0 -166
  46. package/dist/chunk-YMXDO43V.js.map +0 -7
@@ -0,0 +1,164 @@
1
+ import{b as Ie,c as Tt,d as $t,e as ur,f as fn}from"./chunk-WA4BQRDC.js";import hn from"node:process";import Pt from"pino";import ci from"pino-pretty";var gn="/tmp/mcp-infra-kit.log",xp=()=>{let e=hn.argv.includes("--debug")?"debug":"info",r=Pt({level:e},Pt.destination({dest:gn}));return r.info(`Logger initialized with level: ${e}. Logging to: ${gn}`),r},li=()=>{let e=hn.argv.includes("--debug")?"debug":"info",r=["time","pid","hostname"];return e==="debug"&&r.push("level"),Pt({level:e},ci({destination:2,ignore:r.join(","),colorize:!0}))},c=li();import hr from"node:path";import Ii from"node:process";import{z as L}from"zod";import bn from"node:path";import{$ as X}from"zx";var pi=/^v?(\d+)\.(\d+)\.(\d+)$/,di=/^(\d+)\.(\d+)\.(\d+)$/,mi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Zr="release/",It="release/v",wn="refs/heads/",ui="next";var vn=new Set(["dev","main","next","hotfix","regular","release"]),ae=class extends Error{constructor(r){super(r),this.name="InvalidReleaseNameError"}},Ue=class extends Error{constructor(r){super(r),this.name="InvalidReleaseRefError"}},kn=e=>e.startsWith(wn)?e.slice(wn.length):e,Rn=(e,r,t)=>({kind:"version",semver:{major:e,minor:r,patch:t},raw:`${e}.${r}.${t}`}),Se=e=>{if(e.length===0)throw new ae('Release name is empty. Provide a kebab-case name like "checkout-redesign".');if(e.length>50)throw new ae(`Release name "${e}" is ${e.length} characters; the maximum is 50.`);if(!mi.test(e))throw new ae(`Release name "${e}" is not kebab-case. Use lowercase letters, digits, and single hyphens, e.g. "checkout-redesign".`);if(vn.has(e))throw new ae(`Release name "${e}" is reserved. Reserved names: ${[...vn].join(", ")}.`)},C=e=>{let r=kn(e.trim());if(!r.startsWith(Zr))return null;if(r.startsWith(It)){let o=r.slice(It.length),n=di.exec(o);if(n)return Rn(Number(n[1]),Number(n[2]),Number(n[3]))}let t=r.slice(Zr.length);try{Se(t)}catch{return null}return{kind:"name",name:t,raw:t}},Z=e=>{let r=e.trim();if(kn(r).startsWith(Zr)){let n=C(r);if(!n)throw new Ue(`"${e}" looks like a release branch but is not a valid release/v<semver> or release/<name> ref.`);return n}let o=pi.exec(r);if(o)return Rn(Number(o[1]),Number(o[2]),Number(o[3]));if(r.toLowerCase()===ui)throw new Ue('The "next" token must be resolved to a concrete version (via computeNextVersion) before parsing a release ref.');try{Se(r)}catch(n){let s=n instanceof Error?n.message:String(n);throw new Ue(`Cannot parse "${e}" as a release ref: ${s}`)}return{kind:"name",name:r,raw:r}},ce=e=>e.kind==="version"?`${It}${e.raw}`:`${Zr}${e.name}`,St=(e,r)=>{let t=r==="hotfix"?"Hotfix":"Release";return e.kind==="version"?`${t} v${e.raw}`:`${t} ${e.name}`},Xr=e=>e.kind==="version"?`Release v${e.raw} (RC)`:`Release ${e.name} (RC)`,M=e=>e.kind==="version"?`v${e.raw}`:e.name,P=e=>e.raw,Ae=e=>e==null?!1:C(e)!==null,yn=e=>{if(e===void 0)return null;let r=e instanceof Date?e.getTime():new Date(e).getTime();return Number.isNaN(r)?null:r},At=(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=yn(t?.a),n=yn(t?.b);return o!==null&&n!==null&&o!==n?o-n:e.name<r.name?-1:e.name>r.name?1:0};var F=async e=>{let t=(await X`git worktree list`).stdout.split(`
2
+ `).filter(Boolean),o={release:fi,feature:gi};return t.map(o[e]).filter(n=>n!==null)},xn=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},fi=e=>{let r=xn(e);return Ae(r)?r:null},gi=e=>{let r=xn(e);return r?.startsWith("feature/")?r:null},k=async()=>(await X`git rev-parse --show-toplevel`).stdout.trim(),Yr=async()=>(await X`git rev-parse --abbrev-ref HEAD`).stdout.trim(),_t=async()=>(await X`git status --porcelain`).stdout.trim().length===0,Nt=async()=>{let e=await k(),[r,t]=await Promise.all([X({cwd:e})`git rev-parse --absolute-git-dir`,X({cwd:e})`git rev-parse --git-common-dir`]),o=r.stdout.trim(),n=bn.resolve(e,t.stdout.trim());return o!==n},J=async()=>{let e=await k();return bn.basename(e)},Ot=async e=>{(await X`git branch --list ${e}`).stdout.trim().length!==0&&await Yr()!==e&&await X`git branch -D ${e}`},Ft=async e=>{(await X`git ls-remote --heads origin ${e}`).stdout.trim().length!==0&&await X`git push origin --delete ${e}`};import{z as he}from"zod";var jt=he.strictObject({requiredScripts:he.array(he.string().min(1)).optional(),requiredFiles:he.array(he.string().min(1)).optional(),turbo:he.strictObject({requiredTasks:he.array(he.string().min(1)).optional()}).optional()});import hi from"node:fs/promises";var le=async e=>{try{return await hi.access(e),!0}catch{return!1}};import Pi from"node:path";import Cn from"node:fs/promises";import En from"node:path";import{pathToFileURL as wi}from"node:url";import{z as vi}from"zod";var we="infra-kit.config.ts",Dt=async e=>{try{let r=await Cn.readFile(En.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},fr=async(e,r=Ie)=>{let t=En.join(e,we);if(!await le(t))throw new Error(`${we} not found at ${t}`);let o=await Cn.stat(t),i=(await import(`${wi(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${we} at ${t} has no default export`);let l=typeof i=="function"?await i():i,a=jt.safeParse(l);if(!a.success)throw new Error(`Invalid ${we} at ${t}: ${vi.prettifyError(a.error)}`);return $t(a.data,r)};import Tn from"node:fs/promises";import Qr from"node:path";import yi from"yaml";var ki="pnpm-workspace.yaml",Ri=async e=>(await Tn.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Qr.join(e,t.name)),bi=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await Ri(o));continue}let n=Qr.join(o,r);await le(n)&&t.push(n)}return t},xi=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await bi(t,o);return t},gr=async e=>{let r=await Tn.readFile(Qr.join(e,ki),"utf-8"),o=((yi.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await xi(e,s);for(let l of i)await le(Qr.join(l,"package.json"))&&n.add(l)}return[...n].sort()};var Mt=async(e,r=Ie)=>{try{let t=await fr(e,r);return{check:{name:we,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:we,status:"fail",message:t.message},rules:null}}};import Ci from"node:fs/promises";import Ei from"node:path";var Lt=async(e,r)=>Promise.all(r.map(async t=>{let o=await Ci.stat(Ei.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 Ti from"node:fs/promises";import $i from"node:path";var qe="turbo.json",Vt=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await Ti.readFile($i.join(e,qe),"utf-8");t=JSON.parse(n)}catch(n){return[{name:qe,status:"fail",message:`cannot read/parse ${qe}: ${n.message}`}]}let o=t.tasks;return o===null||typeof o!="object"?[{name:qe,status:"fail",message:`no "tasks" object defined in ${qe}`}]: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 ${qe}`}})};var Bt=async(e,r=Ie)=>{let t=await Dt(e),o=t.name??Pi.basename(e),{check:n,rules:s}=await Mt(e,r),i=[n];s&&(i.push(...Wt(t.scripts??{},s.requiredScripts)),i.push(...await Lt(e,s.requiredFiles)),i.push(...await Vt(e,s.turboTasks)));let l=i.every(a=>a.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:l}};var g=e=>[{type:"text",text:e}],w=e=>e;var Si=async e=>{let r=hr.resolve(e);for(;r!==hr.dirname(r);){if(await le(hr.join(r,"package.json")))return r;r=hr.dirname(r)}if(await le(hr.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},Ai=async e=>e.root?[{dir:await k(),baseline:Tt}]:e.all?(await gr(await k())).map(t=>({dir:t})):[{dir:await Si(e.cwd??Ii.cwd())}],_i=e=>{let r=e.passed?"PASS":"FAIL";c.info(`
3
+ ${e.packageName} \u2014 ${r}`);for(let t of e.checks){let o=t.status==="pass"?"[PASS]":"[FAIL]";c.info(` ${o} ${t.name}: ${t.message}`)}},$n=async(e={})=>{let r=await Ai(e),t=[];for(let s of r)t.push(await Bt(s.dir,s.baseline));for(let s of t)_i(s);let o=t.every(s=>s.passed);c.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:g(JSON.stringify(n,null,2)),structuredContent:n}},Ni={all:L.boolean().optional().describe("Audit every non-vendor workspace package"),root:L.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},Oi={allPassed:L.boolean().describe("Whether every audited package passed all checks"),packages:L.array(L.object({name:L.string(),passed:L.boolean(),checks:L.array(L.object({name:L.string(),status:L.enum(["pass","fail"]),message:L.string()}))})).describe("Per-package check results")},Jt=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:Ni,outputSchema:Oi,handler:e=>$n({all:e.all,root:e.root})});import ke from"node:fs";import Kn from"node:os";import xr from"node:path";import ya from"node:process";var He=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},ve=(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?`
5
+ ${i}`:"")};var Pn=(e,r,t)=>`${e}
6
+ ${r}
7
+ ${t}`,wr=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=Pn(t,r,o),i=He(e,t,o);if(n==="replace-in-place"&&i){let p=e.indexOf(t),d=e.indexOf(o)+o.length;return e.slice(0,p)+s+e.slice(d)}let a=(i?ve(e,t,o)??e:e).replace(/\n+$/,"");return a.length>0?`${a}
8
+ ${s}
9
+ `:`${s}
10
+ `};import O from"node:fs";import kr from"node:path";import Gt from"node:fs/promises";import Fi from"node:os";import vr from"node:path";import{z as y}from"zod";var In="infra-kit.json",et=".infra-kit",ji="infra-kit.json",Di="projects",Mi=y.object({provider:y.literal("doppler"),config:y.object({name:y.string().min(1)})}),Li=y.discriminatedUnion("provider",[Mi]),Wi=y.object({workspaceConfigPath:y.string().min(1)}),Vi=y.object({provider:y.literal("cursor"),config:Wi}),Bi=y.object({}),Ji=y.object({provider:y.literal("zed"),config:Bi}),Sn=y.discriminatedUnion("provider",[Vi,Ji]),Ki=y.union([Sn,y.array(Sn).min(1)]),Gi=y.object({provider:y.literal("jira"),config:y.object({baseUrl:y.string().url(),projectId:y.number().int().positive()})}),zi=y.discriminatedUnion("provider",[Gi]),Ui=["two-columns","three-pane"],qi=y.object({layout:y.enum(Ui).optional()}),Hi=y.object({openInGithubDesktop:y.boolean().optional(),openInCmux:y.boolean().optional(),cmux:qi.optional()}),Zi=y.object({trigger:y.enum(["shell-startup","cli-invocation"]),config:y.string().min(1)}).strict(),An=y.object({environments:y.array(y.string().min(1)).min(1),envManagement:Li,ide:Ki.optional(),taskManager:zi.optional(),worktrees:Hi.optional(),envAutoLoad:Zi.optional()}),rt=An.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)}}),yr=An.partial(),K=e=>{let r=e.ide;return r?Array.isArray(r)?r:[r]:[]},Xi="two-columns",zt=e=>e.worktrees?.cmux?.layout??Xi,Ze=null,W=async()=>{let e=await k(),r=vr.basename(e),t=vr.join(Fi.homedir(),et);return{main:vr.join(e,In),userGlobal:vr.join(t,ji),userProject:vr.join(t,Di,r,In),projectName:r}},x=async()=>{let e=await W(),r;try{r=await Gt.stat(e.main)}catch{Ze=null;let a=e.main.replace(/\.json$/,".yml");throw await Kt(a)?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([Kt(e.userGlobal),Kt(e.userProject)]),n={main:Number(r.mtimeMs),userGlobal:t?Number(t.mtimeMs):null,userProject:o?Number(o.mtimeMs):null};if(Ze&&Qi(Ze.mtimes,n))return Ze.value;let s=[{label:"infra-kit.json",path:e.main,required:!0},{label:"~/.infra-kit/infra-kit.json",path:e.userGlobal,required:!1},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,path:e.userProject,required:!1}],i={};for(let a of s){let p=await ea(a);p!==null&&(i={...i,...p})}let l=rt.safeParse(i);if(!l.success)throw new Error(`Invalid merged infra-kit config: ${y.prettifyError(l.error)}`);return Ze={mtimes:n,value:l.data},l.data},ye=()=>{Ze=null},Kt=async e=>{try{return await Gt.stat(e)}catch{return null}},Yi=async e=>{try{return await Gt.readFile(e,"utf-8")}catch{return null}},Qi=(e,r)=>{let t=Object.keys(e);return t.length!==Object.keys(r).length?!1:t.every(o=>e[o]===r[o])},ea=async e=>{let r=await Yi(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=yr.safeParse(t);if(!o.success)throw new Error(`Invalid ${e.label} at ${e.path}: ${y.prettifyError(o.error)}`);return o.data};var tt={name:"infra-kit",type:"module",version:"0.1.125",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",ink:"^7.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.7",yaml:"^2.9.0",zod:"^4.4.3",zx:"^8.8.5"},devDependencies:{"@types/react":"catalog:","@wl/eslint-config":"workspace:*","@wl/vitest-config":"workspace:*",esbuild:"^0.28.1","ink-testing-library":"^4.0.0",typescript:"^6.0.3"}};var Rr="<!-- infra-kit:begin -->",br="<!-- infra-kit:end -->",ta="<!-- infra-kit:version ",oa="<!-- infra-kit:import:begin -->",na="<!-- infra-kit:import:end -->",sa="AGENTS.md",ia="CLAUDE.md",aa=e=>`${ta}${e} -->`,ca=e=>[aa(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 reload` / `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 release 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(`
11
+ `),_n=e=>{if(O.existsSync(e)&&O.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},Nn=e=>{let r=new Date().toISOString().replace(/[:.]/g,"-");O.copyFileSync(e,`${e}.backup.${r}`)},On=(e,r)=>{_n(e);let t=O.existsSync(e);return(t?O.readFileSync(e,"utf-8"):null)===r?"unchanged":(t&&Nn(e),O.mkdirSync(kr.dirname(e),{recursive:!0}),O.writeFileSync(e,r,"utf-8"),t?"updated":"created")},la=(e,r)=>O.existsSync(e)?O.readFileSync(e,"utf-8"):r,pa=(e,r,t)=>{let o=O.readFileSync(e,"utf-8");if(!He(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},da=e=>{if(!O.existsSync(e))return"unchanged";_n(e);let r=O.readFileSync(e,"utf-8"),t=ve(r,Rr,br);return t===null?"unchanged":t.trim()===""?(Nn(e),O.rmSync(e),"removed"):On(e,t)},Fn=async()=>{let e;try{e=(await W()).main}catch{return c.info("Skipped agent-instruction files \u2014 not inside an infra-kit repo"),{skipped:!0,root:null,written:[]}}if(!O.existsSync(e))return c.info("Skipped agent-instruction files \u2014 no infra-kit.json at the repo root"),{skipped:!0,root:null,written:[]};let r=kr.dirname(e),t=tt.version,o=ca(t),n=kr.join(r,sa),s=kr.join(r,ia),i=la(s,"");i=ve(i,oa,na)??i,i=wr({content:i,body:o,startMarker:Rr,endMarker:br,placement:"replace-in-place"});let l=[{path:s,action:On(s,i)},{path:n,action:da(n)}];pa(s,Rr,br);for(let a of l)a.action==="unchanged"&&a.path!==s||c.info(` ${a.action.padEnd(9)} ${kr.relative(r,a.path)}`);return c.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:l}};import V from"node:fs/promises";import Y from"node:path";import{pathToFileURL as ha}from"node:url";import wa from"yaml";import{z as Ln}from"zod";import ma from"node:fs/promises";import ua from"node:os";var pe=async e=>{try{return await ma.access(e),!0}catch{return!1}},R=e=>{let r=ua.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e};import fa from"node:fs/promises";import Ut from"node:os";import qt from"node:path";import{z as ga}from"zod";import{z as ot}from"zod";var jn="vendor.json",nt=ot.object({workspaceDir:ot.string().min(1),targets:ot.array(ot.string()).min(1)}).strict();var Ht=()=>qt.join(Ut.homedir(),et,jn),Dn=e=>{if(e==="~")return Ut.homedir();if(e.startsWith("~/"))return qt.join(Ut.homedir(),e.slice(2));if(qt.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Xe=async()=>{let e=Ht(),r;try{r=await fa.readFile(e,"utf-8")}catch{throw new Error(`Factory config not found at ${e}. infra-kit needs a machine-local factory registry to know where your project repos live and which to stamp. Run \`infra-kit vendor-config --init\` to scaffold it, or create it manually as JSON:
12
+
13
+ {
14
+ "workspaceDir": "~/projects",
15
+ "targets": ["my-repo"]
16
+ }
17
+ `)}let t;try{t=r.trim()===""?{}:JSON.parse(r)}catch(n){throw new Error(`Invalid JSON in vendor.json at ${e}: ${n.message}`)}let o=nt.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${ga.prettifyError(o.error)}`);return o.data};var Mn=e=>e.replace(/\.json$/,".yml"),Wn=async()=>{let e;try{e=await W()}catch{return}let r=[{label:"infra-kit.json",yml:Mn(e.main),json:e.main,schema:rt},{label:"~/.infra-kit/infra-kit.json",yml:Y.join(Y.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:yr},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:Mn(e.userProject),json:e.userProject,schema:yr}],t=0;for(let o of r){let[n,s]=await Promise.all([pe(o.yml),pe(o.json)]);if(n){if(s){c.info(`\u26A0 Skipped ${R(o.yml)} \u2014 ${R(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await V.readFile(o.yml,"utf-8"),l=wa.parse(i)??{},a=o.schema.safeParse(l);if(!a.success){c.info(`\u26A0 Skipped ${R(o.yml)} \u2014 invalid config: ${Ln.prettifyError(a.error)}`);continue}await V.mkdir(Y.dirname(o.json),{recursive:!0}),await V.writeFile(o.json,`${JSON.stringify(a.data,null,2)}
18
+ `,"utf-8"),await V.rm(o.yml,{force:!0}),c.info(`\u2713 Migrated ${R(o.yml)} \u2192 ${R(o.json)}`),t++}catch(i){c.info(`\u26A0 Skipped ${R(o.yml)} \u2014 ${i.message}`)}}}t>0&&ye()},Vn=async()=>{let e;try{e=await W()}catch{return}let r=Y.dirname(e.userGlobal),t=[{from:Y.join(r,"config.json"),to:e.userGlobal},{from:Y.join(r,"config.example.jsonc"),to:Y.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:n,to:s}of t){let[i,l]=await Promise.all([pe(n),pe(s)]);if(i){if(l){c.info(`\u26A0 Skipped ${R(n)} \u2014 ${R(s)} already exists (remove the stale file manually)`);continue}try{await V.mkdir(Y.dirname(s),{recursive:!0}),await V.rename(n,s),c.info(`\u2713 Renamed ${R(n)} \u2192 ${R(s)}`),o++}catch(a){c.info(`\u26A0 Skipped ${R(n)} \u2014 ${a.message}`)}}}o>0&&ye()},Bn=async()=>{let e=Ht(),r=Y.dirname(e),t=Y.join(r,"vendor.config.ts"),[o,n]=await Promise.all([pe(t),pe(e)]);if(o){if(n){c.info(`\u26A0 Skipped ${R(t)} \u2014 ${R(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await V.stat(t),a=(await import(`${ha(t).href}?mtime=${Number(s.mtimeMs)}`)).default,p=typeof a=="function",d=p?await a():a,u=nt.safeParse(d);if(!u.success){c.info(`\u26A0 Skipped ${R(t)} \u2014 invalid factory config: ${Ln.prettifyError(u.error)}`);return}await V.mkdir(r,{recursive:!0}),await V.writeFile(e,`${JSON.stringify(u.data,null,2)}
19
+ `,"utf-8"),await V.rm(t,{force:!0}),p?c.info(`\u26A0 Migrated ${R(t)} \u2192 ${R(e)} as a STATIC SNAPSHOT \u2014 the old file was a function (export default () => ({...})); computed values (env vars, directory globbing) were frozen at their current values and no longer re-evaluate. Edit ${R(e)} directly to change them.`):c.info(`\u2713 Migrated ${R(t)} \u2192 ${R(e)}`)}catch(s){c.info(`\u26A0 Skipped ${R(t)} \u2014 ${s.message}`)}}},va=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(([a])=>a!=="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}},Jn=async()=>{let e;try{e=await W()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await pe(o))try{let n=await V.readFile(o,"utf-8");if(n.trim()==="")continue;let s=JSON.parse(n),{changed:i,result:l}=va(s);if(!i)continue;await V.writeFile(o,`${JSON.stringify(l,null,2)}
20
+ `,"utf-8"),c.info(`\u2713 Normalized ide config in ${R(o)} (removed legacy "mode")`),t++}catch(n){c.info(`\u26A0 Skipped normalizing ${R(o)} \u2014 ${n.message}`)}t>0&&ye()};var Cr="# -- infra-kit:begin --",Ye="# -- infra-kit:end --",ka=[["# region infra-kit","# endregion infra-kit"]],Ra="# infra-kit shell functions",ba=`{}
21
+ `,xa=`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
22
+ //
23
+ // Merge chain (later layers override earlier ones at top-level keys):
24
+ // 1. <repo>/infra-kit.json \u2014 committed project config (required)
25
+ // 2. ~/.infra-kit/infra-kit.json \u2014 user-global (the sibling of this file)
26
+ // 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override
27
+ //
28
+ // Merge is shallow: setting a top-level key replaces that whole section from
29
+ // layer 1. Arrays do not concatenate. Top-level keys recognized:
30
+ // environments, envManagement, ide, taskManager, worktrees, envAutoLoad.
31
+ //
32
+ // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
33
+ // overrides in the sibling infra-kit.json (strict JSON: no comments, double-quoted
34
+ // keys). Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
35
+ //
36
+ // Every recognized key is documented below. NOTE: \`environments\` and
37
+ // \`envManagement\` are REQUIRED in the committed project infra-kit.json (layer 1)
38
+ // and are usually NOT set in this user-global layer \u2014 they are shown here only to
39
+ // document the full, valid config shape.
40
+ {
41
+ // "environments": ["dev", "staging", "prod"], // string[] (>=1) \u2014 required in layer 1
42
+ //
43
+ // "envManagement": { // required in layer 1; provider-tagged
44
+ // "provider": "doppler",
45
+ // "config": { "name": "my-doppler-project" }
46
+ // },
47
+ //
48
+ // "ide": {
49
+ // "provider": "cursor",
50
+ // "config": { "workspaceConfigPath": "/path/to/your.code-workspace" }
51
+ // },
52
+ // // Or, for Zed (no workspace file \u2014 one window with all worktrees via "zed <root> <wt...>"):
53
+ // "ide": { "provider": "zed", "config": {} },
54
+ // // Or drive BOTH editors at once with an array (at most one entry per provider):
55
+ // "ide": [
56
+ // { "provider": "cursor", "config": { "workspaceConfigPath": "/path/to/your.code-workspace" } },
57
+ // { "provider": "zed", "config": {} }
58
+ // ],
59
+ //
60
+ // "taskManager": {
61
+ // "provider": "jira",
62
+ // "config": { "baseUrl": "https://acme.atlassian.net", "projectId": 123 }
63
+ // },
64
+ //
65
+ // "worktrees": {
66
+ // "openInGithubDesktop": false,
67
+ // "openInCmux": true,
68
+ // // cmux pane layout for opened worktrees: "two-columns" (default, left | right)
69
+ // // or "three-pane" (left split top/bottom + full-height right).
70
+ // "cmux": { "layout": "two-columns" }
71
+ // },
72
+ //
73
+ // // Auto-load Doppler env when working inside this project/worktree. Omit to
74
+ // // disable. "trigger" (pick one): "shell-startup" (new shells) | "cli-invocation"
75
+ // // (before each infra-kit command, primes subsequent commands). "config" is the
76
+ // // environment to load (must be one of "environments"). Requires the committed
77
+ // // infra-kit.json at the git repo root, and the zsh shell integration
78
+ // // (infra-kit init + a new shell). zsh only.
79
+ // "envAutoLoad": { "trigger": "shell-startup", "config": "dev" }
80
+ }
81
+ `,Ca=`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
82
+ //
83
+ // Machine-local registry the vendor commands (sync/manifest/diff) read to know
84
+ // where your project repos live and which ones to stamp. This .example.jsonc is
85
+ // reference only \u2014 it is NOT loaded. The real file is the strict-JSON sibling
86
+ // vendor.json (no comments, double-quoted keys); run \`infra-kit vendor config --init\`
87
+ // to scaffold it.
88
+ {
89
+ // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
90
+ // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
91
+ }
92
+ `,Mm=async()=>{let e=xr.join(Kn.homedir(),".zshrc"),r=ke.existsSync(e)?$a(ke.readFileSync(e,"utf-8")):"",t=wr({content:r,body:Gn(),startMarker:Cr,endMarker:Ye,placement:"append-end"});ke.writeFileSync(e,t),c.info(`Added infra-kit shell functions to ${e}`),await Wn(),await Jn(),await Vn(),await Bn(),Ea(),await Fn();let o=ya.env.SHELL??"";o.includes("zsh")||c.warn(`Your login shell ($SHELL=${o||"unset"}) is not zsh. The infra-kit shell integration (env-load/env-clear/auto-load) is zsh-only and won't activate in bash/fish.`),c.info("Run `source ~/.zshrc` or open a new terminal to activate.")},Ea=()=>{let e=xr.join(Kn.homedir(),".infra-kit"),r=xr.join(e,"infra-kit.json");if(ke.mkdirSync(e,{recursive:!0}),ke.writeFileSync(xr.join(e,"infra-kit.example.jsonc"),xa,"utf-8"),ke.writeFileSync(xr.join(e,"vendor.example.jsonc"),Ca,"utf-8"),ke.existsSync(r)){c.info(`User-global config already present at ${r} (refreshed reference examples)`);return}ke.writeFileSync(r,ba,"utf-8"),c.info(`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`)},Ta=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"),$a=e=>{let r=ve(e,Cr,Ye);if(r!==null)return r;for(let[l,a]of ka){let p=ve(e,l,a);if(p!==null)return p}let t=e.indexOf(Ra);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
93
+ `),s=0;for(;s<n.length&&Ta(n[s]);)s++;let i=n.slice(s).join(`
94
+ `);return o+(i?`
95
+ ${i}`:"")},Gn=()=>{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 load_mtime=0 clear_mtime=0",' [[ -f "$load_file" ]] && load_mtime=$(zstat +mtime -- "$load_file" 2>/dev/null || echo 0)',' [[ -f "$clear_file" ]] && clear_mtime=$(zstat +mtime -- "$clear_file" 2>/dev/null || echo 0)'," if (( load_mtime > _INFRA_KIT_LAST_LOAD_MTIME && load_mtime >= _INFRA_KIT_SHELL_STARTED && load_mtime >= clear_mtime )); then",' source "$load_file"'," _INFRA_KIT_LAST_LOAD_MTIME=$load_mtime",' print -u2 "infra-kit: auto-loaded vars for ${INFRA_KIT_ENV_CONFIG:-?}"'," fi"," if (( clear_mtime > _INFRA_KIT_LAST_CLEAR_MTIME && clear_mtime >= _INFRA_KIT_SHELL_STARTED && clear_mtime > load_mtime )); then",' source "$clear_file"'," _INFRA_KIT_LAST_CLEAR_MTIME=$clear_mtime",' print -u2 "infra-kit: auto-cleared env"'," fi","}","autoload -Uz add-zsh-hook","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," add-zsh-hook precmd _infra_kit_autoload","fi","_infra_kit_startup_autoload() {",' [[ -z "$INFRA_KIT_SESSION" ]] && return',' local dir="$PWD" prev=""',' while [[ -n "$dir" && "$dir" != "$prev" ]]; do',' if [[ -f "$dir/infra-kit.json" ]]; then',' [[ -n "$INFRA_KIT_ENV_CONFIG" && "$dir" == "$INFRA_KIT_ENV_PROJECT_ROOT" ]] && return',` ( ${e} env-autoload & ) >/dev/null 2>&1`," return"," fi",' prev="$dir"',' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
96
+ `)},zn=()=>`${Cr}
97
+ ${Gn()}
98
+ ${Ye}`;import Q from"node:fs";import Zn from"node:os";import er from"node:path";import{z as Qe}from"zod";import{$ as Qt}from"zx";import{$ as Un}from"zx";var qn=5e3,st=async()=>{try{await Un`doppler --version`.timeout(qn)}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await Un`doppler me`.timeout(qn)}catch(e){throw new Error("Doppler CLI is not authenticated (or timed out). Run: doppler login",{cause:e})}};var Pa="Could not find requested project",Ia="Could not find requested config",Zt=e=>e.includes(Pa)?"project":e.includes(Ia)?"config":"unknown",Xt=({kind:e,project:r,config:t,available:o})=>{let n=e==="project"?[`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name).`]:[`Doppler config "${t}" not found in project "${r}" (set in infra-kit.json \u2192 environments).`];if(o&&o.length>0){let s=e==="project"?"Available projects":`Available configs in "${r}"`;n.push(`${s}: ${o.join(", ")}.`)}return n.push(e==="project"?"Fix: update envManagement.config.name to an existing project, or create it in Doppler.":"Fix: update environments to an existing config, or create it in Doppler."),n.join(`
99
+ `)};import{$ as Er}from"zx";var Sa=5e3,_e=async()=>{let{envManagement:e}=await x();return e.config.name},Tr=async()=>Hn(()=>Er`doppler projects --json`),Yt=async e=>Hn(()=>Er`doppler configs --project ${e} --json`),Hn=async e=>{let r=Er.quiet;Er.quiet=!0;try{let t=await e().timeout(Sa);return Aa(t.stdout)}catch{return null}finally{Er.quiet=r}},Aa=e=>{let r;try{r=JSON.parse(e)}catch{return null}return Array.isArray(r)?r.map(t=>t!==null&&typeof t=="object"?t.name:void 0).filter(t=>typeof t=="string"):null};var Ne=async(e,r,t,o)=>{try{return await Qt`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},_a=()=>{let e="zshrc init block",r=er.join(Zn.homedir(),".zshrc");if(!Q.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=Q.readFileSync(r,"utf-8"),o=t.indexOf(Cr),n=t.indexOf(Ye);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+Ye.length).trim(),i=zn().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"}},Na=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await k(),t=er.join(r,"pnpm-workspace.yaml");if(!Q.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=Q.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}`}}},Oa=async()=>{let e="infra-kit config valid";try{return ye(),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}}},Fa=async()=>{let e="doppler project exists",r;try{r=await _e()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"}}let t=await Tr();return t===null?{name:e,status:"pass",message:"Skipped \u2014 could not list Doppler projects (see doppler auth check)"}:t.includes(r)?{name:e,status:"pass",message:`Doppler project "${r}" exists`}:{name:e,status:"fail",message:`Doppler project "${r}" not found (set in infra-kit.json \u2192 envManagement.config.name). Available: ${t.length>0?t.join(", "):"none"}`}},ja=async()=>{let e="user override path";try{let r=await W(),t=Zn.homedir(),o=r.userProject.startsWith(t)?`~${r.userProject.slice(t.length)}`:r.userProject,s=Q.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}}},Da=async()=>{let e="legacy user-global config",r;try{r=await W()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=er.join(er.dirname(r.userGlobal),"config.json");return Q.existsSync(t)?Q.existsSync(r.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${R(t)} \u2014 ${R(r.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${R(t)} \u2014 run \`infra-kit init\` to migrate it (your overrides are not being applied).`}:{name:e,status:"pass",message:"No legacy user-global config.json"}},Ma={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/"}},La=async e=>{let r=Ma[e];try{return await Qt`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},Wa=async()=>{let e="ide installed",r;try{ye();let n=await x();r=K(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=>La(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("; ")}},Va=[1,2,3,5,7],Ba=async()=>{let e="rtk configured";try{let t=(await Qt`rtk init --show`).stdout.split(`
100
+ `).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of Va){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}`}}},Ja=async()=>{let e;try{e=(await W()).main}catch{return[]}if(!Q.existsSync(e))return[];let r=er.join(er.dirname(e),"CLAUDE.md"),t=Q.existsSync(r)?Q.readFileSync(r,"utf-8"):"",o=He(t,Rr,br);return[{name:"CLAUDE.md block",status:o?"pass":"fail",message:o?"CLAUDE.md block present":"infra-kit block missing from CLAUDE.md. Run: infra-kit init"}]},Xn=async()=>{let r=[...await Promise.all([Ne("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),Ne("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),Ne("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),Ne("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),Ne("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"),Ne("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),Ne("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"),Ba(),Promise.resolve(_a()),Na(),Oa(),Fa(),ja(),Da(),Wa()]),...await Ja()];c.info(`Doctor check results:
101
+ `);for(let o of r){let n=o.status==="pass"?"[PASS]":"[FAIL]";c.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:g(JSON.stringify(t,null,2)),structuredContent:t}},eo=w({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:Qe.array(Qe.object({name:Qe.string().describe("Name of the check"),status:Qe.enum(["pass","fail"]).describe("Check result"),message:Qe.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:Qe.boolean().describe("Whether all checks passed")},handler:Xn});import qa from"@inquirer/select";import{Buffer as Ha}from"node:buffer";import Za from"node:fs";import Xa from"node:path";import es from"node:process";import{z as _r}from"zod";import{$ as it}from"zx";var Ka=()=>{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(" ");c.info(`\u{1F4DF} Equivalent command:
102
+ pnpm exec infra-kit ${e} ${o}
103
+ `)},reset(){e="",r=[],t=!1}}},m=Ka();import $r from"node:fs";import Ga from"node:os";import ro from"node:path";import to from"node:process";var Oe="env-load.sh",oo="env-clear.sh",Pr="INFRA_KIT_SESSION",Fe="INFRA_KIT_ENV_CONFIG",je="INFRA_KIT_ENV_PROJECT",Ir="INFRA_KIT_ENV_PROJECT_ROOT",De="INFRA_KIT_ENV_LOADED_AT",Re="INFRA_KIT_ENV_AUTOLOADED",Me="INFRA_KIT_ENV_CLEARED",Yn=/^([A-Z_]\w*)=/i,za=(e,r)=>{let t=r;for(let o=0;o<e.length;o++){if(!t&&e[o]==="\\"){o++;continue}e[o]==="'"&&(t=!t)}return t},Sr=e=>{if(!$r.existsSync(e))return[];let r=$r.readFileSync(e,"utf-8"),t=[],o=!1;for(let n of r.split(`
104
+ `)){if(!o){let s=Yn.exec(n);s&&t.push(s[1])}o=za(n,o)}return t},Qn=()=>{let e=to.env.XDG_CACHE_HOME,r=e&&e.length>0?e:ro.join(Ga.homedir(),".cache");return ro.join(r,"infra-kit")},Le=()=>{let e=to.env[Pr];if(!e)throw new Error(`${Pr} is not set. Run \`infra-kit init\` then \`source ~/.zshrc\`.`);return ro.join(Qn(),e)},Ar=(e,r,t)=>{let o=`${e}.tmp.${to.pid}`;$r.writeFileSync(o,r,{mode:t});try{$r.renameSync(o,e)}catch(n){throw $r.rmSync(o,{force:!0}),n}},G="-worktrees";var no=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},Ua=(e,r)=>{let t=r.stderrExcerpt??no(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(Ua(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var Ya=e=>e?[`${Re}=${rr("1")}`]:[`unset ${Re}`,`unset ${Me}`],ts=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:n,autoLoaded:s})=>["set -a",...e.map(([i,l])=>`${i}=${rr(l)}`),`${Fe}=${rr(r)}`,`${je}=${rr(t)}`,`${Ir}=${rr(o)}`,`${De}=${rr(n)}`,...Ya(s),"set +a"],Qa=async()=>{try{return await k()}catch{return""}},os=async({config:e,autoLoaded:r=!1,beforeWrite:t})=>{await st();let o=await _e(),n=await Qa(),s=await rc(o,e),i=new Date().toISOString(),l=ts({pairs:s,config:e,project:o,projectRoot:n,loadedAt:i,autoLoaded:r}),a=Le(),p=Xa.resolve(a,Oe);return t&&!t()?null:(Za.mkdirSync(a,{recursive:!0,mode:448}),Ar(p,`${l.join(`
105
+ `)}
106
+ `,384),{filePath:p,variableCount:s.length,project:o,config:e})},ns=async e=>{let{config:r}=e;m.start("env-load");let t="";if(r)t=r;else{await st();let{environments:s}=await x();m.setInteractive(),t=await qa({message:"Select environment config",choices:s.map(i=>({name:i,value:i}))},{output:es.stderr})}m.addOption("--config",t);let o=await os({config:t,autoLoaded:!1});if(!o)throw new Error("env-load: write was unexpectedly aborted");es.stdout.write(`${o.filePath}
107
+ `),m.print();let n={filePath:o.filePath,variableCount:o.variableCount,project:o.project,config:o.config};return{content:g(JSON.stringify(n,null,2)),structuredContent:n}},rs=1024*1024,ec=3e4,rc=async(e,r)=>{let t=it.quiet;it.quiet=!0;try{let o;try{o=await it`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(ec)}catch(n){throw await tc(n,e,r)}return oc(o.stdout),sc(o.stdout)}finally{it.quiet=t}},tc=async(e,r,t)=>{let o=no(e)??(e instanceof Error?e.message:String(e)),n=Zt(o);if(n==="unknown")return e instanceof Error?e:new Error(String(e));let s=n==="project"?await Tr():await Yt(r);return new Error(Xt({kind:n,project:r,config:t,available:s}))},oc=e=>{let r=Ha.byteLength(e,"utf-8");if(r>rs)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${rs}) \u2014 refusing to write to disk`)},rr=e=>`'${e.replaceAll("'","'\\''")}'`,nc=/^[A-Z_]\w*$/i,sc=e=>{let r;try{r=JSON.parse(e)}catch{throw new Error(`doppler returned non-JSON output for env-load (got: ${JSON.stringify(e.slice(0,80))})`)}if(r===null||typeof r!="object"||Array.isArray(r))throw new Error("doppler returned unexpected JSON shape for env-load (expected an object of KEY: value pairs)");let t=[];for(let[o,n]of Object.entries(r)){if(!nc.test(o))throw new Error(`doppler returned an invalid env var name for env-load (got: ${JSON.stringify(o.slice(0,80))})`);if(typeof n!="string")throw new TypeError(`doppler returned a non-string value for "${o}" (got ${typeof n})`);t.push([o,n])}if(t.length===0)throw new Error("doppler returned empty output for env-load");return t},so=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:_r.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:_r.string().describe("Path to the file that must be sourced to apply variables"),variableCount:_r.number().describe("Number of variables loaded"),project:_r.string().describe("Doppler project name"),config:_r.string().describe("Doppler config name")},handler:ns});import io from"node:fs";import ss from"node:path";import ic from"node:process";import{z as at}from"zod";var ac=e=>[...e.map(r=>`unset ${r}`),`unset ${Fe}`,`unset ${je}`,`unset ${Ir}`,`unset ${De}`,`unset ${Re}`,`export ${Me}='1'`],is=async()=>{let e=Le(),r=ss.join(e,Oe);if(!io.existsSync(r))throw new Error("No loaded environment found. Run `env-load` first.");let t=Sr(r),o=ac(t),n=ss.resolve(e,oo);io.mkdirSync(e,{recursive:!0,mode:448}),Ar(n,`${o.join(`
108
+ `)}
109
+ `,384),ic.stdout.write(`${n}
110
+ `),io.rmSync(r,{force:!0});let s={filePath:n,variableCount:t.length,unsetStatements:o};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},ao=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:at.string().describe("Path to the file that must be sourced to apply"),variableCount:at.number().describe("Number of variables cleared"),unsetStatements:at.array(at.string()).describe("Unset statements generated")},handler:is});import{z as co}from"zod";var as=async()=>{let e=await _e(),{environments:r}=await x();c.info(`Doppler project: ${e}
111
+ `),c.info("Available configs:");for(let o of r)c.info(` - ${o}`);let t={project:e,configs:r};return{content:g(JSON.stringify(t,null,2)),structuredContent:t}},lo=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:co.string().describe("Detected Doppler project name"),configs:co.array(co.string()).describe("Available environment configs")},handler:as});import cc from"node:path";import We from"node:process";import{z as be}from"zod";var cs=async()=>{c.info("Environment session status:");let e=Le(),r=We.env[Pr],t=cc.join(e,Oe),o=0,n=0,s=We.env[Fe]??null,i=We.env[je]??null,l=We.env[De]??null,a=We.env[Re]==="1",p=!!We.env[Me];if(s){let u=Sr(t);u.length>0&&(n=u.length,o=u.filter(v=>v in We.env).length);let h=l?.replace(/\.\d{3}Z$/,"")??null,b=a?"auto-loaded":"manually loaded";if(c.info(` ${s}: ${o} of ${n} vars loaded (${b}, project: ${i}, loadedAt: ${h}, session: ${r})
112
+ `),n>0&&o<n){let v=n-o;c.warn(` ${v} cached var(s) are not present in the current process \u2014 env-load needs to be re-sourced, or vars were unset manually.`)}}else{let u=p?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";c.info(` Session ${r}: no env loaded${u}
113
+ `)}let d={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:l,autoLoaded:a,cleared:p};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}},po=w({name:"env-status",description:"Report which Doppler project/config is currently loaded in the terminal session, when it was loaded, how many variables are cached, whether it was auto-loaded, and whether a clear is suppressing auto-load. Pure local introspection \u2014 makes NO Doppler call (use doctor for auth). Read-only \u2014 use env-load / env-clear to change the terminal session.",inputSchema:{},outputSchema:{sessionId:be.string().describe("Current terminal session ID"),sessionLoadedCount:be.number().describe("Number of cached vars active in the current session"),sessionTotalCount:be.number().describe("Total number of cached var names"),sessionConfig:be.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:be.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:be.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:be.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:be.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:cs});import pc from"@inquirer/checkbox";import dc from"@inquirer/confirm";import mc from"node:process";import{z as ir}from"zod";import{$ as z}from"zx";import{$ as wf}from"zx";import{$ as _}from"zx";import{$ as Or}from"zx";import Nr from"node:process";var mo=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`,a=btoa(`${n}:${o}`),p=await fetch(l,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(i)});if(!p.ok){let u=await p.text();throw c.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 c.error({error:t},"Error creating Jira version"),t}},tr=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 c.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 c.error({error:r},"Error getting Jira project versions"),r}},ct=async(e,r)=>{try{return(await tr(r)).find(n=>n.name===e)||null}catch(t){throw c.error({error:t,versionName:e},"Error finding Jira version by name"),t}},lt=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}`),a=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(s)});if(!a.ok){let d=await a.text();throw c.error({status:a.status,statusText:a.statusText,error:d},"Failed to update Jira version"),new Error(`HTTP ${a.status}: ${a.statusText}`)}return{success:!0,version:await a.json()}}catch(t){throw c.error({error:t},"Error updating Jira version"),t}},uo=async(e,r)=>{try{let{versionName:t}=e,o=await ct(t,r);if(!o)throw c.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await lt({versionId:o.id,released:!0,releaseDate:new Date().toISOString().split("T")[0]},r)}catch(t){throw c.error({error:t},"Error delivering Jira release"),t}},or=async()=>{let e=Nr.env.JIRA_BASE_URL,r=Nr.env.JIRA_TOKEN||Nr.env.JIRA_API_TOKEN,t=Nr.env.JIRA_PROJECT_ID,o=Nr.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(`
114
+ `);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}},Ve=async()=>{try{return await or()}catch(e){return c.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var ls="dev",nr=e=>e==="hotfix"?"main":"dev",fo=async(e="regular")=>{let r=nr(e);Or.quiet=!0,await Or`git fetch origin`,await Or`git switch ${r}`,await Or`git pull origin ${r}`,Or.quiet=!1},go=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=M(r),i=await mo({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`,a=await pt({id:r,jiraVersionUrl:l,type:n,description:o});return{version:P(r),type:n,branchName:a.branchName,prUrl:a.prUrl,jiraVersionUrl:l}},I=async()=>{let e=new Map,r=await Ve();if(!r)return e;try{let t=await tr(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},sr=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},E=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",ps=e=>e.flatMap(r=>{let t=C(r);return t?[{branch:r,id:t,label:P(t)}]:[]}),de=e=>{try{return ce(Z(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")'})}},Fr=e=>{if(e===ls)return ls;let r=C(e);return r?P(r):e},Be=e=>e.flatMap(r=>{let t=C(r);return t?[P(t)]:[]}),A=e=>{let{branches:r,descriptions:t,types:o}=e,n=ps(r),s=Math.max(0,...n.map(i=>i.label.length));return n.map(({branch:i,id:l,label:a})=>{let p=o?o.get(i)||"regular":void 0,d=t.get(M(l)),u=" ".repeat(s-a.length+3),h=p?sr(a,p,s):a;return d&&(h=p?`${h} ${d}`:`${a}${u}${d}`),{name:h,value:i}})};var ds=e=>e.map(r=>({pr:r,id:C(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>At(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),ms=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))},dt=async()=>{try{let e=await ms();if(e.length===0)throw new f(void 0,{operation:"find open release PRs",remediation:"open a release PR first, or check you are in the right repo"});return ds(e).map(r=>r.headRefName)}catch(e){throw e instanceof f?e:(c.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},T=async()=>{try{let e=await ms();if(e.length===0)throw new f(void 0,{operation:"find open release PRs",remediation:"open a release PR first, or check you are in the right repo"});return ds(e).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt}))}catch(e){throw e instanceof f?e:(c.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},mt=async e=>{let{branch:r,body:t}=e;try{_.quiet=!0,await _`gh pr edit ${r} --body ${t}`,_.quiet=!1}catch(o){throw c.error({error:o,branch:r},`Error updating release PR body for ${r}`),o}},pt=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=St(r,o),i=nr(o),l=ce(r),a=n&&n.trim()!==""?`${t}
115
+
116
+ ${n}`:`${t}
117
+ `;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 d=(await _`gh pr create --title ${s} --body ${a} --base ${i} --head ${l}`).stdout.trim();return await _`git switch ${i}`,_.quiet=!1,{branchName:l,prUrl:d}}catch(p){throw c.error({error:p,branchName:l},`Error creating release branch ${l}`),p}};var j=async e=>{let{operation:r,requiredBranch:t}=e;if(await Nt())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 Yr();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 _t())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};var us=async e=>{let{all:r,confirmedCommand:t}=e;m.start("merge-dev"),await j({operation:"merge dev into release branches",requiredBranch:"dev"});let n=(await T()).filter(d=>E(d.title)==="regular").map(d=>d.branch);if(n.length===0)return c.info("\u2139\uFE0F No open release branches found"),m.print(),{content:g(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 d=await I();s=await pc({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:d})})}s.length===n.length?m.addOption("--all",!0):m.addOption("--versions",Be(s));let l=t?!0:await dc({message:`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`});t||m.setInteractive(),l||(c.info("Operation cancelled. Exiting..."),mc.exit(0)),t||m.addOption("--yes",!0),z.quiet=!0,await z`git fetch origin`,await z`git switch dev`,await z`git pull origin dev`;let a=[];for(let d of s)await uc(d)||a.push(d);if(z.quiet=!1,a.length>0){c.info(`
118
+ \u26A0\uFE0F ${a.length} branch(es) failed to merge automatically.
119
+ `),c.info("\u{1F4CB} Manual merge script for failed branches:");for(let d of a)c.info(`# Merge dev into ${d} and resolve conflicts if any
120
+
121
+ git switch ${d} && git pull origin ${d} && git merge origin/dev
122
+ git push origin ${d} && git switch dev
123
+ `);c.info(`\u2705 ${s.length-a.length}/${s.length} merges completed successfully.`)}else c.info(`\u2705 All merges completed successfully!
124
+ `);m.print();let p={successfulMerges:s.length-a.length,failedMerges:a.length,failedBranches:a,totalBranches:s.length};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},uc=async e=>{try{return await z`git switch ${e}`,await z`git pull origin ${e}`,await z`git merge origin/dev --no-edit`,await z`git push origin ${e}`,await z`git switch dev`,c.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 c.error({error:r,branch:e,msg:t.message}),await z`git reset --merge HEAD~1`,!1}},ho=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:ir.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:ir.number().describe("Number of successful merges"),failedMerges:ir.number().describe("Number of failed merges"),failedBranches:ir.array(ir.string()).describe("List of branches that failed to merge"),totalBranches:ir.number().describe("Total number of branches processed")},handler:us});import yc from"@inquirer/confirm";import kc from"@inquirer/select";import Rc from"node:process";import{z as Vr}from"zod";import{$ as D}from"zx";var fs=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},jr=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=fs(r.stderr,500);n&&(t.stderr=n);let s=fs(r.stdout,200);return s&&(t.stdout=s),t};import{$ as hs}from"zx";var fc=/\bv(\d+\.\d+\.\d+)\b/g,ee=e=>e.trim().replace(/\s+/g," ").replace(fc,"$1");import{$ as gs}from"zx";var Je=async e=>{try{let r=(await gs`cmux list-workspaces`.quiet()).stdout,t=gc(r,e);if(!t)return;await gs`cmux close-workspace --workspace ${t}`.quiet()}catch(r){c.debug({error:r,title:e},"cmux: skipped closing workspace")}},gc=(e,r)=>{let t=ee(r);for(let o of e.split(`
125
+ `)){let n=o.match(/^[* ]\s*(workspace:\d+)\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!n)continue;let s=n[1],i=n[2]?.trim()??"";if(ee(i)===t)return s}};import{$ as hc}from"zx";var Dr=async()=>{try{let e=(await hc`cmux list-workspaces`.quiet()).stdout,r=new Set;for(let t of e.split(`
126
+ `)){let o=t.match(/^[* ]\s*workspace:\d+\s+(.+?)(?:\s+\[selected\])?\s*$/);if(!o)continue;let n=o[1]?.trim();n&&r.add(ee(n))}return r}catch(e){return c.debug({error:e},"cmux: skipped listing workspace titles"),new Set}};import{$ as Mr}from"zx";var Lr=async e=>{let{cwd:r,title:t}=e,o=zt(await x()),n=(await Mr`cmux workspace create --cwd ${r}`).stdout,s=vc(n),i=(await Mr`cmux list-pane-surfaces --workspace ${s}`).stdout,l=wc(i);await Mr`cmux new-split right --workspace ${s} --surface ${l}`,o==="three-pane"&&await Mr`cmux new-split down --workspace ${s} --surface ${l}`,t&&await Mr`cmux workspace rename --workspace ${s} --title ${t}`},wc=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]},vc=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 re=e=>{let{repoName:r,branch:t}=e,o=C(t),n=o?P(o):t;return`${r} ${n}`};var Wr=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:n=!1}=e,s=await Promise.allSettled(r.map(async l=>{let a=`${t}/${l}`,p=re({repoName:o,branch:l});return await Je(p),await hs`git worktree remove ${a}`,l})),i=[];for(let[l,a]of s.entries())if(a.status==="fulfilled")i.push(a.value);else{let p=r[l],d=new f(a.reason,{operation:`remove worktree for ${p}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});c.error({error:a.reason,msg:d.message})}return n&&i.length===r.length&&await hs`git worktree prune`,i};var ar=async(e,r,t)=>{try{return await t()}catch(o){throw c.error({err:jr(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},vs=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},bc=async e=>{let r=Xr(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},ws=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},xc=async e=>{let r=de(e),t=await vs(r);if(!t)throw c.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}},Cc=async()=>{let e=await T(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,E(i.title)]));m.setInteractive();let o=await I(),n=await kc({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})}),s=e.find(i=>i.branch===n);if(!s)throw c.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}},Ec=async e=>{if(!(await F("release")).includes(e))return;let[t,o]=await Promise.all([k(),J()]),n=`${t}${G}`;if((await Wr({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)`})},Tc=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await vs(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"){c.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 ar(`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`})},$c=async e=>{let r=P(e),t=Xr(e),o=await ws();if(o){let s=o.number;return o.title!==t&&(c.info(`Adopting open dev \u2192 main PR #${s} ("${o.title}") and retitling for ${r}`),await ar(`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 ar(`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 ws();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},Pc=async e=>{let r=P(e);if(await bc(e)){c.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await $c(e);await ar(`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`})},Ic=async()=>{D.quiet=!1,await ar("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},Sc=async()=>{await ar("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`})},Ac=async e=>{try{await Ot(e)}catch(r){c.warn({err:jr(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await Ft(e)}catch(r){c.warn({err:jr(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},_c=async e=>{let r=await Ve();if(!r){c.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=M(e);await uo({versionName:t},r)}catch(t){c.error({err:jr(t)},"Failed to deliver Jira release (non-blocking)")}},ys=async e=>{let{version:r,confirmedCommand:t}=e;m.start("release-deliver"),await j({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await xc(r):await Cc(),s=C(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=P(s);m.addOption("--version",i),c.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let l=E(n),a=t?!0:await yc({message:`Are you sure you want to deliver version ${o} to production?`});t||m.setInteractive(),a||(c.info("Operation cancelled. Exiting..."),Rc.exit(0)),m.addOption("--yes",!0),D.quiet=!0,await Ec(o),await Tc({selectedReleaseBranch:o,releaseType:l}),l!=="hotfix"&&await Pc(s),await Ic(),await Sc(),await Ac(o),D.quiet=!1,await _c(s),c.info(`Successfully delivered ${o} to production!`),m.print();let p={releaseBranch:o,version:i,type:l,success:!0};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},wo=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:Vr.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:Vr.string().describe("The release branch that was delivered"),version:Vr.string().describe("The version that was delivered"),type:Vr.enum(["regular","hotfix"]).describe("Release type"),success:Vr.boolean().describe("Whether the delivery was successful")},handler:ys});import Nc from"@inquirer/confirm";import ks from"@inquirer/select";import{z as xe}from"zod";import{$ as vo}from"zx";var Oc=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;m.setInteractive();let n=await Nc({message:`Deploy ${t} \u2192 ${o}?`,default:!1});return n&&m.addOption("--yes",!0),n},Rs=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:n}=e;m.start("release-deploy-all");let s="";if(r)s=r==="dev"?"dev":de(r);else{m.setInteractive();let d=await T(),u=d.map(v=>v.branch),h=new Map(d.map(v=>[v.branch,E(v.title)])),b=await I();s=await ks({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:u,descriptions:b,types:h})]})}let i=Fr(s);m.addOption("--version",i);let{environments:l}=await x(),a="";if(t?a=t:(m.setInteractive(),a=await ks({message:"\u{1F9EA} Select environment",choices:l.map(d=>({name:d,value:d}))})),m.addOption("--env",a),!l.includes(a))throw new f(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${a}`});let p=o??!1;if(p&&m.addOption("--skip-terraform",!0),!await Oc({confirmedCommand:n,branch:s,env:a})){c.info("Deployment cancelled");let d={releaseBranch:s,version:i,environment:a,skipTerraformDeploy:p,success:!1};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}try{vo.quiet=!0,await vo`gh workflow run deploy-all.yml --ref ${s} -f environment=${a} ${p?["-f","skip_terraform_deploy=true"]:[]}`,vo.quiet=!1,c.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${a}`),m.print();let u={releaseBranch:s,version:i,environment:a,skipTerraformDeploy:p,success:!0};return{content:g(JSON.stringify(u,null,2)),structuredContent:u}}catch(d){throw c.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"})}},yo=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:xe.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:xe.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:xe.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:xe.string().describe("The release branch that was deployed"),version:xe.string().describe("The version that was deployed"),environment:xe.string().describe("The environment deployed to"),skipTerraformDeploy:xe.boolean().describe("Whether terraform deployment was skipped"),success:xe.boolean().describe("Whether the deployment was successful")},handler:Rs});import Fc from"@inquirer/checkbox";import jc from"@inquirer/confirm";import bs from"@inquirer/select";import Dc from"node:fs/promises";import{resolve as Mc}from"node:path";import Lc from"yaml";import{z as B}from"zod";import{$ as ko}from"zx";var Wc=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;m.setInteractive();let n=await jc({message:`Deploy ${t} \u2192 ${o}?`,default:!1});return n&&m.addOption("--yes",!0),n},xs=async e=>{let{version:r,env:t,services:o,skipTerraform:n,confirmedCommand:s}=e;m.start("release-deploy-selected");let i="";if(r)i=r==="dev"?"dev":de(r);else{m.setInteractive();let v=await T(),S=v.map(Pe=>Pe.branch),N=new Map(v.map(Pe=>[Pe.branch,E(Pe.title)])),H=await I();i=await bs({message:"\u{1F33F} Select release branch",choices:[{name:"dev",value:"dev"},...A({branches:S,descriptions:H,types:N})]})}let l=Fr(i);m.addOption("--version",l);let{environments:a}=await x(),p="";if(t?p=t:(m.setInteractive(),p=await bs({message:"\u{1F9EA} Select environment",choices:a.map(v=>({name:v,value:v}))})),m.addOption("--env",p),!a.includes(p))throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${a.join(", ")}`,stderrExcerpt:`invalid environment: ${p}`});let d=await Vc();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 u=[];if(o&&o.length>0?u=o:(m.setInteractive(),u=await Fc({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:d.map(v=>({name:v,value:v}))})),m.addOption("--services",u),u.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 h=u.filter(v=>!d.includes(v));if(h.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${d.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let b=n??!1;if(b&&m.addOption("--skip-terraform",!0),!await Wc({confirmedCommand:s,branch:i,env:p})){c.info("Deployment cancelled");let v={releaseBranch:i,version:l,environment:p,services:u,skipTerraformDeploy:b,success:!1};return{content:g(JSON.stringify(v,null,2)),structuredContent:v}}try{ko.quiet=!0;let v=u.flatMap(H=>["-f",`${H}=true`]);await ko`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${p} ${v} ${b?["-f","skip_terraform_deploy=true"]:[]}`,ko.quiet=!1,c.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${p}, services: ${u.join(", ")}`),m.print();let N={releaseBranch:i,version:l,environment:p,services:u,skipTerraformDeploy:b,success:!0};return{content:g(JSON.stringify(N,null,2)),structuredContent:N}}catch(v){throw c.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"})}},Vc=async()=>{let e=await k(),r=Mc(e,".github/workflows/deploy-selected-services.yml"),t=await Dc.readFile(r,"utf-8"),n=Lc.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},Ro=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:B.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:B.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:B.array(B.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:B.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:B.string().describe("The release branch that was deployed"),version:B.string().describe("The version that was deployed"),environment:B.string().describe("The environment deployed to"),services:B.array(B.string()).describe("The services that were deployed"),skipTerraformDeploy:B.boolean().describe("Whether terraform deployment was skipped"),success:B.boolean().describe("Whether the deployment was successful")},handler:xs});import{z as cr}from"zod";var Cs=async()=>{let r=(await T()).flatMap(i=>{let l=C(i.branch);return l?[{version:P(l),jiraKey:M(l),type:E(i.title)}]:[]}),t=await I(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let l=sr(i.version,i.type,o),a=t.get(i.jiraKey);return a?`${l} ${a}`:l});c.info(`All release branches:
127
+ `),c.info(`
128
+ ${n.join(`
129
+ `)}
130
+ `);let s={releases:r.map(i=>({version:i.version,type:i.type,description:t.get(i.jiraKey)||null})),count:r.length};return{content:g(JSON.stringify(s,null,2)),structuredContent:s}},bo=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:cr.array(cr.object({version:cr.string().describe("Release version"),type:cr.enum(["regular","hotfix"]).describe("Release type"),description:cr.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:cr.number().describe("Number of release branches")},handler:Cs});var Ce=e=>e.slice(1).split(".").map(Number),xo=e=>[...e].sort((r,t)=>{let[o,n,s]=Ce(r),[i,l,a]=Ce(t);return o!==i?(o??0)-(i??0):n!==l?(n??0)-(l??0):(s??0)-(a??0)});var Ts="next",Bc=/^v?(\d+)\.(\d+)\.(\d+)$/,Jc=e=>e.replace(/^.*release\//,""),Eo=e=>{let r=Jc(e.trim()),t=Bc.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},Es=e=>`${e[0]}.${e[1]}.${e[2]}`,To=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=Eo(n);if(!s)continue;let i=Es(s);o.has(i)||(o.add(i),t.push(s))}return xo(t.map(n=>Es(n))).map(n=>Ce(`v${n}`))},Ke=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},ut=(e,r)=>{if(e.length===0)throw new Ke;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,l=e.reduce((a,p)=>p[0]===s&&p[1]===i?Math.max(a,p[2]):a,0);return`${s}.${i}.${l+1}`}let[o,n]=t;return`${o}.${n+1}.0`},$o=e=>e.trim().toLowerCase()===Ts,Kc=e=>e==="regular"||e==="hotfix",$s=e=>"name"in e,Gc=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),a=l.indexOf(":"),p=a===-1?l.trim():l.slice(0,a).trim();s=a===-1?"":l.slice(a+1).trim();let d=p.toLowerCase();if(!Kc(d))throw new Error(`Invalid release type "${p}". Expected "regular" or "hotfix".`);n=d}if($o(o)||Eo(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},Po=e=>{let r=e.id.raw;return e.description!==void 0&&e.description!==""?`${r}:${e.type}:${e.description}`:e.type==="hotfix"?`${r}:hotfix`:r},Co=(e,r)=>r!==void 0&&r!==""?{...e,description:r}:e,zc=e=>{let r=e.name.trim();return Se(r),Co({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},Io=(e,r)=>{let t=[...r];return e.map(o=>{if($s(o))return zc(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if($o(n)){let l=ut(t,o.type);return t.push(Ce(`v${l}`)),Co({id:Z(l),type:o.type},o.description)}let s=Eo(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),Co({id:Z(i),type:o.type},o.description)})},So=e=>e.some(r=>!$s(r)&&$o(r.version));import{$ as ft}from"zx";var Uc=e=>e.split(`
131
+ `).map(r=>{let t=r.indexOf(" ");return t===-1?null:C(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),qc=async()=>{let e=ft.quiet;try{ft.quiet=!0;let r=await ft`git ls-remote --heads origin 'release/v*'`;return Uc(r.stdout)}finally{ft.quiet=e}},Hc=async()=>{let e=await Ve();return e?(await tr(e)).map(t=>t.name):[]},Ao=async()=>{let[e,r]=await Promise.allSettled([qc(),Hc()]);return e.status==="rejected"&&c.warn({error:e.reason},"Failed to list remote release branches; continuing without them"),r.status==="rejected"&&c.warn({error:r.reason},"Failed to fetch Jira versions; continuing without them"),To({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};import Ss from"@inquirer/confirm";import Ps from"@inquirer/select";import gt from"node:process";import{z as $}from"zod";import{question as No}from"zx";var Zc='"1.2.5" or "next"',Xc=(e,r)=>{try{return ut(e,r)}catch(t){if(t instanceof Ke)return null;throw t}},_o=(e,r)=>{try{return Io(e,r)}catch(t){throw t instanceof Ke?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 ae?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}},Yc=async(e,r)=>{let t=Xc(e,r),o=t?` [${t}]`:"",n=(await No(` Version (e.g. ${Zc})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(c.error("No version provided. Exiting..."),gt.exit(1)),s},Qc=async()=>{let e=(await No(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(c.error("No name provided. Exiting..."),gt.exit(1));try{Se(e)}catch(r){let t=r instanceof Error?r.message:String(r);c.error(`${t} Exiting...`),gt.exit(1)}return e},el=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 Ps({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),a=await Ps({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),p;if(l==="name"){let u=await Qc();p=_o([{name:u,type:a}],[])[0]}else{let u=await Yc(await o(),a);p=_o([{version:u,type:a}],t)[0],p.id.kind==="version"&&t.push(Ce(`v${p.id.raw}`))}let d=(await No(" Description (optional, press Enter to skip): ")).trim();n.push({...p,...d!==""?{description:d}:{}}),s=await Ss({message:"Add another release?",default:!1})}return n},rl=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 ")},Is=e=>{for(let r of e)m.addOption("--release",Po(r))},tl=async(e,r)=>{if(e&&e.length>0){let o=So(e)?await r():[],n=_o(e,o);return Is(n),n}let t=await el(r);return Is(t),t},ol=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"})},nl=async(e,r)=>{let t=e.map(rl).join(`
132
+ - `),o=r?!0:await Ss({message:`Create the following ${e.length} release(s)?
133
+ - ${t}
134
+ `});r||m.setInteractive(),o||(c.info("Operation cancelled. Exiting..."),gt.exit(0)),m.addOption("--yes",!0)},sl=async e=>{let{entry:r,jiraConfig:t}=e,o=P(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await fo(r.type);let s=await go({id:r.id,jiraConfig:t,description:r.description,type:r.type});return c.info(`\u2705 Successfully created release: ${n} (${r.type})`),c.info(`\u{1F517} GitHub PR: ${s.prUrl}`),c.info(`\u{1F517} Jira Version: ${s.jiraVersionUrl}
135
+ `),{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 c.error(`\u274C ${i.message}
136
+ `),{failure:{version:o,error:i.message}}}},il=(e,r,t)=>{r===e?c.info(`\u2705 All ${e} release branch(es) were created successfully.`):r>0?(c.warn(`\u26A0\uFE0F ${r} of ${e} release branches were created successfully.`),c.warn(`\u274C ${t} release(s) failed.`)):c.error(`\u274C All ${e} release branch(es) failed to create.`)},As=async e=>{let{releases:r,confirmedCommand:t}=e;m.start("release-create");let o=await or(),n=null,i=await tl(r,async()=>(n===null&&(n=await Ao()),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"});ol(i),await j({operation:"create release",requiredBranch:nr(i[0].type)}),await nl(i,!!t);let l=[],a=[];for(let d of i){let{result:u,failure:h}=await sl({entry:d,jiraConfig:o});u&&l.push(u),h&&a.push(h)}il(i.length,l.length,a.length),m.print();let p={createdBranches:l.map(d=>d.branchName),successCount:l.length,failureCount:a.length,releases:l,failedReleases:a};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},Oo=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:$.array($.object({version:$.string().optional().describe('Version to create (e.g., "1.2.5") or the literal token "next" for auto-increment. Mutually exclusive with "name".'),name:$.string().optional().describe('Free-form kebab-case release name (e.g., "checkout-redesign"). Mutually exclusive with "version". Named releases never auto-bump.'),type:$.enum(["regular","hotfix"]).optional().default("regular").describe('Release type: "regular" (branches off dev) or "hotfix" (branches off main).'),description:$.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:$.array($.string()).describe("List of created release branch names"),successCount:$.number().describe("Number of releases created successfully"),failureCount:$.number().describe("Number of releases that failed"),releases:$.array($.object({version:$.string().describe("Version number"),type:$.enum(["regular","hotfix"]).describe("Release type"),branchName:$.string().describe("Release branch name"),prUrl:$.string().describe("GitHub PR URL"),jiraVersionUrl:$.string().describe("Jira version URL")})).describe("Detailed information for each created release with URLs"),failedReleases:$.array($.object({version:$.string().describe("Version number that failed"),error:$.string().describe("Error message")})).describe("List of releases that failed with error messages")},handler:As});import al from"@inquirer/confirm";import cl from"@inquirer/select";import ll from"node:process";import{z as Ee}from"zod";import{question as pl}from"zx";var _s=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,dl=(e,r)=>r.trim()!==""?`${e}
137
+
138
+ ${r}`:`${e}
139
+ `,ml=async()=>{let e=await T(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,E(s.title)])),o=await I(),n=await cl({message:"\u{1F33F} Select release branch",choices:A({branches:r,descriptions:o,types:t})});return{branch:n,type:t.get(n)||"regular"}},ul=async e=>{let t=(await T()).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 E(t.title)},fl=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await pl(` New description ${r}
140
+ (press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},Ns=async e=>{let{version:r,description:t,confirmedCommand:o}=e;m.start("release-desc-edit");let n=await or(),s;r?(s=de(r),await ul(s)):(m.setInteractive(),s=(await ml()).branch);let i=C(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=P(i);m.addOption("--version",l);let a=M(i),p=await ct(a,n);if(!p)throw new f(void 0,{operation:`edit description for ${a}`,remediation:`create the Jira fix version "${a}" first or pick a different release`});let d=p.description??"",u;if(t!==void 0?(u=t,m.addOption("--description",u)):(m.setInteractive(),u=await fl(d)),u===d){c.info(`No change \u2014 description for ${a} is already: "${d}"`),m.print();let N={version:l,branch:s,jiraVersionUrl:_s(n,p),previousDescription:d,newDescription:u,changed:!1};return{content:g(JSON.stringify(N,null,2)),structuredContent:N}}let h=o?!0:await al({message:`Update description for ${a}?
141
+ from: "${d}"
142
+ to: "${u}"
143
+ `});o||m.setInteractive(),h||(c.info("Operation cancelled. Exiting..."),ll.exit(0)),m.addOption("--yes",!0),await lt({versionId:p.id,description:u},n);let b=_s(n,p),v=dl(b,u);await mt({branch:s,body:v}),c.info(`\u2705 Updated description for ${a}`),c.info(`\u{1F517} Jira Version: ${b}`),c.info(`\u{1F517} PR branch: ${s}
144
+ `),m.print();let S={version:l,branch:s,jiraVersionUrl:b,previousDescription:d,newDescription:u,changed:!0};return{content:g(JSON.stringify(S,null,2)),structuredContent:S}},Fo=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:Ee.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:Ee.string().describe("New description. Empty string clears the description.")},outputSchema:{version:Ee.string().describe("Release version"),branch:Ee.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:Ee.string().describe("Jira fix version URL"),previousDescription:Ee.string().describe("The description before the update"),newDescription:Ee.string().describe("The description after the update"),changed:Ee.boolean().describe("Whether the description actually changed")},handler:Ns});import{existsSync as Ds}from"node:fs";import Ms from"node:path";import El from"node:process";import{z as me}from"zod";import{createHash as gl}from"node:crypto";import{readFileSync as hl}from"node:fs";var ht=e=>gl("sha256").update(hl(e)).digest("hex");import{readFileSync as bl,writeFileSync as xl}from"node:fs";import yt from"node:path";import{z as te}from"zod";import{readdirSync as kl}from"node:fs";import jo from"node:path";var U="vendor",wl=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),vl=new Set([".sync-manifest.json",".eslintcache","log.txt"]),yl=[".tsbuildinfo"],Os=e=>wl.has(e),Fs=e=>vl.has(e)?!0:yl.some(r=>e.endsWith(r));var Rl=e=>e.split(jo.sep).join("/"),wt=e=>{let r=[],t=o=>{for(let n of kl(o,{withFileTypes:!0})){let s=jo.join(o,n.name);if(n.isDirectory()){if(Os(n.name))continue;t(s);continue}Fs(n.name)||r.push(Rl(jo.relative(e,s)))}};return t(e),r.sort()};var oe=".sync-manifest.json",vt=1,Cl=te.object({schemaVersion:te.number().optional(),source:te.string(),commit:te.string(),syncedAt:te.string(),fileCount:te.number(),files:te.record(te.string(),te.string())}),Do=e=>(e.schemaVersion??vt)>vt,js=e=>{let r={};for(let t of wt(e))try{r[t]=ht(yt.join(e,t))}catch(o){let n=o instanceof Error?o.message:String(o);throw new Error(`Cannot hash vendor file "${t}" (broken symlink or unreadable file): ${n}`)}return r},Mo=e=>{let r=yt.join(e,oe),t;try{t=bl(r,"utf8")}catch{throw new Error(`Missing ${oe} at ${r}`)}let o=Cl.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${oe} at ${r}: ${te.prettifyError(o.error)}`);return o.data},Lo=(e,r)=>{let t=js(e),o={schemaVersion:vt,source:r.source,commit:r.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(t).length,files:t};return xl(yt.join(e,oe),`${JSON.stringify(o,null,2)}
145
+ `),o},Wo=(e,r)=>{let t=r.files,o=wt(e),n=[],s=[];for(let a of o){if(!(a in t)){s.push(a);continue}ht(yt.join(e,a))!==t[a]&&n.push(a)}let i=new Set(o),l=Object.keys(t).filter(a=>!i.has(a));return{modified:n,added:s,removed:l}};var Vo=30,Bo=(e,r)=>{if(r.length!==0){c.info(`
146
+ ${e} (${r.length}):`);for(let t of r.slice(0,Vo))c.info(` ${t}`);r.length>Vo&&c.info(` \u2026and ${r.length-Vo} more`)}},Ls=async(e={})=>{let r=e.cwd??await k(),t=Ms.join(r,U),o={modified:[],added:[],removed:[],fileCount:0};if(!Ds(t)){c.info(`\u2139\uFE0F No ${U}/ folder found \u2014 nothing to check.`);let d={status:"skipped",ok:!0,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}if(!Ds(Ms.join(t,oe))){c.error(`\u274C Missing ${U}/${oe}. Re-run the vendor sync to generate it.`);let d={status:"missing-manifest",ok:!1,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}let n=Mo(t);if(Do(n)){c.error(`\u274C ${U}/${oe} has a newer schemaVersion (${String(n.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let d={status:"unknown-schema",ok:!1,...o};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}let{modified:s,added:i,removed:l}=Wo(t,n),a=s.length>0||i.length>0||l.length>0;a?(c.error(`\u274C ${U}/ has drifted from ${U}/${oe}.`),c.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),Bo("Modified",s),Bo("Added (not in manifest)",i),Bo("Removed (in manifest, now missing)",l)):c.info(`\u2705 ${U}/ matches manifest (${n.fileCount} files).`);let p={status:a?"drift":"clean",ok:!a,fileCount:n.fileCount,modified:s,added:i,removed:l};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},Tl={status:me.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:me.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:me.number(),modified:me.array(me.string()),added:me.array(me.string()),removed:me.array(me.string())},Jo=w({name:"vendor-check",description:"Verify that files under vendor/ match the checksums in vendor/.sync-manifest.json. Self-contained (no source repo or config needed). Returns ok=false on drift, missing manifest, or an unknown future schemaVersion; ok=true when clean or when no vendor/ folder exists.",inputSchema:{},outputSchema:Tl,handler:()=>Ls({cwd:El.cwd()})});import{z as se}from"zod";import $l from"node:fs/promises";import Pl from"node:path";import{pathToFileURL as Il}from"node:url";import{z as Sl}from"zod";var kt=async e=>{let r=Pl.join(e,ur),t;try{t=await $l.stat(r)}catch{throw new Error(`${ur} not found at ${r}`)}let s=(await import(`${Il(r).href}?mtime=${Number(t.mtimeMs)}`)).default;if(s===void 0)throw new Error(`${ur} at ${r} has no default export`);let i=typeof s=="function"?await s():s,l=fn.safeParse(i);if(!l.success)throw new Error(`Invalid ${ur} at ${r}: ${Sl.prettifyError(l.error)}`);return l.data};import{existsSync as ne,mkdirSync as Al,writeFileSync as _l}from"node:fs";import q from"node:path";import{$ as Br}from"zx";var Nl=["node_modules","dist","*.tsbuildinfo",".turbo",".eslintcache",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack","log.txt"],Ol=`# vendor/ \u2014 mirrored from the source repo
147
+
148
+ **DO NOT EDIT files in this folder here.**
149
+
150
+ Everything under \`vendor/\` is the single source of truth maintained in the source
151
+ repo and copied into this repo by \`infra-kit vendor sync\`. Local edits are
152
+ overwritten on the next sync and will fail \`infra-kit vendor check\` in CI.
153
+
154
+ To change a vendored package, edit it in the source repo and re-run the sync.
155
+
156
+ See \`.sync-manifest.json\` for the source commit and per-file checksums.
157
+ `,Vs=()=>Nl.map(e=>`--exclude=${e}`),Rt=async e=>{try{return(await Br({cwd:e})`git rev-parse HEAD`).stdout.trim()}catch{return"unknown"}},Fl=async(e,r)=>{if(!ne(e))return!1;ne(r)&&await Br`rm -rf ${r}`;let t=`${e}/`,o=`${r}/`;return await Br`rsync -a ${Vs()} ${t} ${o}`,!0},jl=async(e,r)=>{if(!ne(e))return!1;let t=q.dirname(r);return ne(t)||Al(t,{recursive:!0}),await Br`cp ${e} ${r}`,!0},Dl=async(e,r)=>{if(!ne(e))return[];if(!ne(r))return[`missing target: ${r}`];let t=`${e}/`,o=`${r}/`;return(await Br`rsync -ai --dry-run --delete ${Vs()} ${t} ${o}`).stdout.split(`
158
+ `).map(s=>s.trim()).filter(Boolean)},Bs=(e,r)=>{let t=q.join(e,U);ne(t)&&(_l(q.join(t,"README.md"),Ol),Lo(t,r))},Ko=(e,r)=>q.join(Dn(e),r),lr=(e,r)=>r?e.filter(t=>r.includes(t)):e,Ws=(e,r,t,o,n)=>{let s=q.resolve(e),i=q.resolve(r);if(i!==s&&!i.startsWith(s+q.sep))throw new f(void 0,{operation:`sync vendor item ${n}`,stderrExcerpt:`${t} escapes repo root: ${o}`})},Js=async(e,r,t,o,n)=>{let s=[];for(let i of o){let l=Ko(t,i);if(!ne(l)){s.push({repo:i,copied:0,total:e.copy.length,skipped:!0});continue}let a=0;for(let p of e.copy){let d=q.join(r,p.source),u=q.join(l,p.target);Ws(r,d,"source",p.source,p.name),Ws(l,u,"target",p.target,p.name),(p.type==="directory"?await Fl(d,u):await jl(d,u))&&a++}Bs(l,n),s.push({repo:i,copied:a,total:e.copy.length,skipped:!1})}return{source:n.source,commit:n.commit,repos:s}},Ks=async(e,r,t)=>{let o=[];for(let n of r){let s=Ko(e,n),i=!ne(s);i||Bs(s,t),o.push({repo:n,skipped:i})}return o},Gs=async(e,r,t,o)=>{let n=[],s=e.copy.filter(i=>i.vendored===!0);for(let i of o){let l=Ko(t,i);if(ne(l))for(let a of s){let p=q.join(r,a.source),d=q.join(l,a.target),u=await Dl(p,d);u.length>0&&n.push({repo:i,target:a.target,changes:u})}}return n};var Go=20,zs=async(e={})=>{let r=e.cwd??await k(),t=await kt(r),o=await Xe(),n=lr(o.targets,e.repos),s=await Gs(t,r,o.workspaceDir,n);if(s.length===0)c.info("\u{1F389} No drift detected.");else for(let l of s){c.info(`\u274C ${l.repo} \u2192 ${l.target} (${l.changes.length} change(s)):`);for(let a of l.changes.slice(0,Go))c.info(` ${a}`);l.changes.length>Go&&c.info(` \u2026and ${l.changes.length-Go} more`)}let i={ok:s.length===0,drifted:s.length,entries:s};return{content:g(JSON.stringify(i,null,2)),structuredContent:i}},Ml={ok:se.boolean().describe("Whether every target is in sync with the source"),drifted:se.number(),entries:se.array(se.object({repo:se.string(),target:se.string(),changes:se.array(se.string())}))},zo=w({name:"vendor-diff",description:"Source-aware drift check: compare each target repo vendored subtree against the source via rsync dry-run. Read-only; run from the source repo root. ok=false when any target has drifted.",inputSchema:{repos:se.array(se.string()).optional().describe("Restrict to these target repo names")},outputSchema:Ml,handler:e=>zs({repos:e.repos})});import Ll from"node:path";import{z as Te}from"zod";var Us=async e=>{let r=e.cwd??await k(),t=await Xe(),o=lr(t.targets,e.repos),n=await Rt(r),s=Ll.basename(r),i=await Ks(t.workspaceDir,o,{source:s,commit:n});for(let a of i)c.info(a.skipped?`\u26A0\uFE0F ${a.repo}: target does not exist \u2014 skipped`:`\u{1F4DD} ${a.repo}: manifest written`);let l={source:s,commit:n,repos:i};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},Wl={source:Te.string(),commit:Te.string(),repos:Te.array(Te.object({repo:Te.string(),skipped:Te.boolean()}))},Uo=w({name:"vendor-manifest",description:"Regenerate each target repo vendor/.sync-manifest.json + README from current content without copying. Mutating; run from the source repo root.",inputSchema:{repos:Te.array(Te.string()).optional().describe("Restrict to these target repo names")},outputSchema:Wl,handler:e=>Us({repos:e.repos,confirmedCommand:e.confirmedCommand})});import Vl from"@inquirer/confirm";import qs from"node:path";import Hs from"node:process";import{z as ie}from"zod";var Zs=async e=>{let r=e.cwd??await k(),t=await kt(r),o=await Xe(),n=lr(o.targets,e.repos);e.confirmedCommand||await Vl({message:`Sync vendor files from ${qs.basename(r)} into ${n.length} repo(s)?`},{output:Hs.stderr})||Hs.exit(0);let s=await Rt(r),i=qs.basename(r),l=await Js(t,r,o.workspaceDir,n,{source:i,commit:s});for(let a of l.repos)a.skipped?c.info(`\u26A0\uFE0F ${a.repo}: target does not exist \u2014 skipped`):c.info(`\u2705 ${a.repo}: copied ${a.copied}/${a.total} items + manifest`);return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},Bl={source:ie.string(),commit:ie.string(),repos:ie.array(ie.object({repo:ie.string(),copied:ie.number(),total:ie.number(),skipped:ie.boolean()}))},qo=w({name:"vendor-sync",description:"Copy vendored files from the source repo (vendor.config.ts) into each target repo and regenerate their vendor/.sync-manifest.json + README. Mutating; run from the source repo root.",inputSchema:{repos:ie.array(ie.string()).optional().describe("Restrict to these target repo names")},outputSchema:Bl,handler:e=>Zs({repos:e.repos,confirmedCommand:e.confirmedCommand})});import{z as Jl}from"zod";var Xs=async()=>{let e=tt.version;c.info(e);let r={version:e};return{content:g(JSON.stringify(r,null,2)),structuredContent:r}},Ho=w({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:Jl.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Xs});var bt=["workspace","none"];import Ys from"node:fs/promises";import xt from"node:path";var Jr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=xt.dirname(r),n;try{n=await Ys.readFile(r,"utf-8")}catch(d){throw new Error(`Cursor workspace file not found at ${r}: ${d.message}`)}let s;try{s=JSON.parse(n)}catch(d){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${d.message}`)}let i=s.folders??[],l=new Set(i.map(d=>xt.resolve(o,d.path))),a=[],p=[];for(let d of t){let u=xt.resolve(d);if(l.has(u)){p.push(d);continue}let h=xt.relative(o,u);i.push({path:h}),l.add(u),a.push(d)}return s.folders=i,await Ys.writeFile(r,`${JSON.stringify(s,null,2)}
159
+ `,"utf-8"),{added:a,skipped:p}};import{$ as Kl}from"zx";var Kr=async e=>{await Kl`cursor ${e}`};import Gl from"node:fs/promises";import Et from"node:path";import Qs from"node:fs/promises";import Ct from"node:path";var Gr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=Ct.dirname(r),n;try{n=await Qs.readFile(r,"utf-8")}catch(h){throw new Error(`Cursor workspace file not found at ${r}: ${h.message}`)}let s;try{s=JSON.parse(n)}catch(h){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${h.message}`)}let i=s.folders??[],l=new Set(t.map(h=>Ct.resolve(h))),a=new Set,p=i.filter(h=>{let b=Ct.resolve(o,h.path);return l.has(b)?(a.add(b),!1):!0});s.folders=p,await Qs.writeFile(r,`${JSON.stringify(s,null,2)}
160
+ `,"utf-8");let d=[],u=[];for(let h of t){let b=Ct.resolve(h);a.has(b)?d.push(h):u.push(h)}return{removed:d,notFound:u}};var Zo=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=Et.dirname(r),s=Et.resolve(`${t}/release`),i=await Gl.readFile(r,"utf-8"),a=JSON.parse(i).folders??[],p=new Set(o.map(v=>Et.resolve(`${t}/${v}`))),d=[];for(let v of a){let S=Et.resolve(n,v.path);(S===s||S.startsWith(`${s}/`))&&!p.has(S)&&d.push(S)}let u=[];d.length>0&&(u=(await Gr({workspacePath:r,folderPaths:d})).removed);let h=o.map(v=>`${t}/${v}`),{added:b}=h.length>0?await Jr({workspacePath:r,folderPaths:h}):{added:[]};return{added:b,removed:u}};import ei from"node:path";var Ge=(e,r)=>ei.isAbsolute(e)?e:ei.resolve(r,e);var Xo=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o,cursorConfig:n}=e;if(!n.workspaceConfigPath)return c.warn("\u26A0\uFE0F Skipping Cursor: workspaceConfigPath is not set."),{ran:!1,added:0,removed:0};let s=Ge(n.workspaceConfigPath,r);try{let{added:i,removed:l}=await Zo({workspacePath:s,worktreeDir:t,currentBranches:o});return o.length>0&&await Kr(s),{ran:!0,added:i.length,removed:l.length}}catch(i){return c.warn({error:i},`\u26A0\uFE0F Failed to reconcile/open Cursor workspace at ${s}`),{ran:!1,added:0,removed:0}}};import{$ as zl}from"zx";var Yo=async e=>{let{folderPaths:r}=e;for(let t of r)await zl`zed --add ${t}`;return{added:r}};import{$ as Ul}from"zx";var Qo=async e=>{let{projectRoot:r,worktreeDir:t,currentBranches:o}=e;if(o.length===0)return{ran:!1,added:0,removed:0};let n=[r,...o.map(s=>`${t}/${s}`)];try{return await Ul`zed ${n}`,{ran:!0,added:o.length,removed:0}}catch(s){return c.warn({error:s},"\u26A0\uFE0F Failed to open Zed workspace"),{ran:!1,added:0,removed:0}}};import{$ as ql}from"zx";var en=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,n=[r,...o.map(s=>`${t}/${s}`)];try{return await ql`zed --reuse ${n}`,c.info(`\u21BB Refreshed Zed workspace to root + ${o.length} release worktree(s) (other folders in the focused window are not preserved)`),{ran:!0}}catch(s){return c.warn({error:s},"\u26A0\uFE0F Failed to refresh Zed workspace"),{ran:!1}}};var ue=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var rn=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,n=await x(),s=K(n),i=o.map(a=>`${t}/${a}`),l=[];for(let a of s)switch(a.provider){case"cursor":{if(!a.config.workspaceConfigPath){c.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 p=Ge(a.config.workspaceConfigPath,r),{added:d,skipped:u}=await Jr({workspacePath:p,folderPaths:i}),h=u.length>0?` (${u.length} already present)`:"";c.info(`\u2705 Added ${d.length} folder(s) to ${p}${h}`),await Kr(p),l.push({ran:!0,provider:"cursor",added:d.length,skipped:u.length});break}case"zed":{let{added:p}=await Yo({folderPaths:i});c.info(`\u2705 Added ${p.length} folder(s) to Zed workspace`),l.push({ran:!0,provider:"zed",added:p.length,skipped:0});break}default:ue(a)}return l};var tn=async e=>{let r=await x(),t=K(r),o=[];for(let n of t)switch(n.provider){case"cursor":{let s=await Xo({...e,cursorConfig:n.config});o.push({...s,provider:"cursor"});break}case"zed":{let s=await Qo(e);o.push({...s,provider:"zed"});break}default:ue(n)}return o};var on=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return ue(e)}};var zr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:n,allowEditorRelaunch:s}=e;if(n.length===0)return[];let i=await x(),l=K(i),a=n.map(u=>`${t}/${u}`),p=o.filter(u=>!n.includes(u)),d=[];for(let u of l)switch(u.provider){case"cursor":{d.push(await Hl({ide:u,projectRoot:r,folderPaths:a}));break}case"zed":{d.push(await Zl({projectRoot:r,worktreeDir:t,remainingBranches:p,allowEditorRelaunch:s}));break}default:ue(u)}return d},Hl=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let n=Ge(r.config.workspaceConfigPath,t);try{let{removed:s}=await Gr({workspacePath:n,folderPaths:o});return s.length>0&&c.info(`\u2705 Removed ${s.length} folder(s) from ${n}`),{provider:"cursor",supported:!0,removed:s}}catch(s){return c.warn({error:s},`\u26A0\uFE0F Failed to update Cursor workspace at ${n}`),{provider:"cursor",supported:!0,removed:[]}}},Zl=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:n}=e;return n?(await en({projectRoot:r,worktreeDir:t,remainingBranches:o}),{provider:"zed",supported:!0,removed:[]}):(c.info("\u2139\uFE0F Zed folder removal skipped (no interactive session); close removed worktree folders in Zed manually if needed."),{provider:"zed",supported:!0,removed:[]})};var Xl=new Set(["ExitPromptError","AbortPromptError"]),ri=e=>e instanceof Error&&Xl.has(e.name),pr=e=>{if(ri(e))return!0;let r=e?.cause;return ri(r)};import Yl from"@inquirer/checkbox";import nn from"@inquirer/confirm";import Ql from"node:process";import{z as fe}from"zod";import{$ as Ur}from"zx";var ep="feature",rp="release",oi=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:n,cmux:s}=e,i=e.ide??e.cursor;m.start("worktrees-add"),await j({operation:"create worktrees",requiredBranch:"dev"});try{let l=await F("release"),a=await k(),p=`${a}${G}`;await ti(`${p}/${rp}`),await ti(`${p}/${ep}`);let d=[];if(o)d=o.split(",").map(ge=>ce(Z(ge.trim())));else{let ge=await T(),mr=ge.map(ze=>ze.branch);if(mr.length===0)return c.info("\u2139\uFE0F No open release branches found"),m.print(),{content:g(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)d=mr;else{m.setInteractive();let ze=new Map(ge.map(un=>[un.branch,E(un.title)])),Hr=await I();d=await Yl({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:mr,descriptions:Hr,types:ze})})}}t?m.addOption("--all",!0):m.addOption("--versions",Be(d));let u=r?!0:await nn({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),u||(c.info("Operation cancelled. Exiting..."),Ql.exit(0)),r||m.addOption("--yes",!0);let h=await x(),b=i??(K(h).length>0?"workspace":"none");m.addOption("--ide",b);let v=n??h.worktrees?.openInGithubDesktop??await nn({message:"Open created worktrees in GitHub Desktop?"});typeof n>"u"&&h.worktrees?.openInGithubDesktop===void 0&&m.setInteractive(),v?m.addOption("--github-desktop",!0):m.addOption("--no-github-desktop",!0);let S=s??h.worktrees?.openInCmux??await nn({message:"Open created worktrees in cmux?"});typeof s>"u"&&h.worktrees?.openInCmux===void 0&&m.setInteractive(),S?m.addOption("--cmux",!0):m.addOption("--no-cmux",!0);let{branchesToCreate:N}=tp({selectedReleaseBranches:d,currentWorktrees:l}),H=await op(N,p);if(np(H),b==="workspace"&&await rn({projectRoot:a,worktreeDir:p,branches:H}),v)for(let ge of H)await Ur`github ${p}/${ge}`,await Ur`sleep 5`;if(S){let ge=await J(),mr=await Dr();for(let ze of H){let Hr=re({repoName:ge,branch:ze});mr.has(ee(Hr))||await Lr({cwd:`${p}/${ze}`,title:Hr})}}m.print();let Pe={createdWorktrees:H,count:H.length};return{content:g(JSON.stringify(Pe,null,2)),structuredContent:Pe}}catch(l){throw pr(l)?l:(c.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'"}))}},ti=async e=>{await Ur`mkdir -p ${e}`},tp=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>Ae(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},op=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Ur`git worktree add ${s} ${n}`,await Ur({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"});c.error({error:s.reason,msg:l.message})}return o},np=e=>{if(e.length>0){c.info("\u2705 Created git worktrees:");for(let r of e)c.info(r);c.info("")}else c.info("\u2139\uFE0F No new git worktrees to create")},sn=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:fe.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:fe.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:fe.enum(bt).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:fe.enum(bt).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:fe.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:fe.boolean().optional().describe('Open each created worktree in a new cmux workspace, all rooted at the worktree directory. Pane layout follows "worktrees.cmux.layout" (default "two-columns": left | right; or "three-pane": left split top/bottom + full-height right). Resolution order: this flag \u2192 "worktrees.openInCmux" from infra-kit config \u2192 interactive prompt (CLI) / false (MCP, no TTY).')},outputSchema:{createdWorktrees:fe.array(fe.string()).describe("List of created git worktree branches"),count:fe.number().describe("Number of git worktrees created")},handler:oi});import{z as dr}from"zod";var ni=async()=>{let e=await F("release");if(e.length===0)return c.info("\u2139\uFE0F No active worktrees found"),{content:g(JSON.stringify({worktrees:[],count:0},null,2)),structuredContent:{worktrees:[],count:0}};let[r,t]=await Promise.all([T(),I()]),o=new Map(r.map(a=>[a.branch,E(a.title)])),n=e.flatMap(a=>{let p=C(a);if(!p)return[];let d=P(p),u=o.get(a)||"regular",h=t.get(M(p))||null;return[{version:d,type:u,description:h}]}),s=Math.max(...n.map(a=>a.version.length)),i=n.map(a=>{let p=sr(a.version,a.type,s);return a.description?`${p} ${a.description}`:p});c.info("\u{1F33F} Active worktrees:"),c.info(`
161
+ ${i.join(`
162
+ `)}
163
+ `);let l={worktrees:n,count:n.length};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},an=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:dr.array(dr.object({version:dr.string().describe("Release version"),type:dr.enum(["regular","hotfix"]).describe("Release type"),description:dr.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:dr.number().describe("Number of worktrees")},handler:ni});import{z as $e}from"zod";var si=async()=>{m.start("worktrees-reload");try{let e=await k(),r=`${e}${G}`,t=await F("release"),o=await J(),n=await sp({currentBranches:t,repoName:o}),[s,{opened:i}]=await Promise.all([tn({projectRoot:e,worktreeDir:r,currentBranches:t}),ip({worktreeDir:r,currentBranches:t,repoName:o})]),l={closedCmux:n,openedCmux:i,ideProviders:s.filter(a=>a.ran).map(a=>a.provider),ideFoldersAdded:s.reduce((a,p)=>a+p.added,0),ideFoldersRemoved:s.reduce((a,p)=>a+p.removed,0)};return ap(l,{ideRan:s.some(a=>a.ran)}),m.print(),{content:g(JSON.stringify(l,null,2)),structuredContent:{...l}}}catch(e){throw c.error({error:e},"\u274C Error reloading worktrees"),new f(e,{operation:"reload worktrees",remediation:"run 'worktrees-list' to confirm the branches exist"})}},sp=async e=>{let{currentBranches:r,repoName:t}=e;if(r.length===0)return[];let o=await Dr(),n=[];for(let s of r){let i=re({repoName:t,branch:s});o.has(ee(i))&&(await Je(i),n.push(i))}return n},ip=async e=>{let{worktreeDir:r,currentBranches:t,repoName:o}=e,n=[];for(let s of t){let i=re({repoName:o,branch:s});try{await Lr({cwd:`${r}/${s}`,title:i}),n.push(i)}catch(l){c.warn({error:l,title:i},`\u26A0\uFE0F Failed to reopen cmux workspace for ${s}`)}}return{opened:n}},ap=(e,r)=>{if(e.closedCmux.length>0&&c.info(`\u{1F9F9} Closed ${e.closedCmux.length} cmux workspace(s)`),r.ideRan){let t=e.ideProviders.map(o=>on(o)).join(", ");e.ideFoldersAdded>0&&c.info(`\u2705 Added ${e.ideFoldersAdded} folder(s) to ${t} workspace(s)`),e.ideFoldersRemoved>0&&c.info(`\u{1F9F9} Removed ${e.ideFoldersRemoved} dangling folder(s) from ${t} workspace(s)`)}if(e.openedCmux.length>0){c.info("\u2705 Reopened cmux workspaces:");for(let t of e.openedCmux)c.info(t)}!r.ideRan&&e.closedCmux.length===0&&e.openedCmux.length===0&&e.ideFoldersAdded===0&&e.ideFoldersRemoved===0&&c.info("\u2139\uFE0F Nothing to reload")},cn=w({name:"worktrees-reload",description:"Close all open cmux workspaces for the current release worktrees, then reopen the full set \u2014 the single window-restore command. Every configured editor (Cursor and/or Zed) is reconciled + relaunched (no per-window close). Disruptive: closes live cmux windows first. Safe to run from any branch. Use to refresh stale windows or to restore everything after a cold start (editor + cmux closed).",inputSchema:{},outputSchema:{closedCmux:$e.array($e.string()).describe("Titles of cmux workspaces a close was attempted for (best-effort)"),openedCmux:$e.array($e.string()).describe("Titles of cmux workspaces reopened during this run"),ideProviders:$e.array($e.string()).describe("Configured IDE providers that were reloaded (cursor | zed); empty if none configured"),ideFoldersAdded:$e.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:$e.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:si});import cp from"@inquirer/checkbox";import lp from"@inquirer/confirm";import pp from"node:process";import{z as qr}from"zod";var ii=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;m.start("worktrees-remove"),await j({operation:"remove worktrees",requiredBranch:"dev"});try{let n=await F("release");if(n.length===0)return c.info("\u2139\uFE0F No active worktrees to remove"),m.print(),{content:g(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await k(),i=`${s}${G}`,l=[];if(t)l=n;else if(o)l=o.split(",").map(b=>ce(Z(b.trim())));else{m.setInteractive();let[b,v]=await Promise.all([I(),T()]),S=new Map(v.map(N=>[N.branch,E(N.title)]));l=await cp({required:!0,message:"\u{1F33F} Select release branches",choices:A({branches:n,descriptions:b,types:S})})}let a=l.length===n.length;a?m.addOption("--all",!0):m.addOption("--versions",Be(l));let p=r?!0:await lp({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),p||(c.info("Operation cancelled. Exiting..."),pp.exit(0)),r||m.addOption("--yes",!0);let d=await J(),u=await Wr({branches:l,worktreeDir:i,repoName:d,pruneFolder:a});await zr({projectRoot:s,worktreeDir:i,currentWorktrees:n,removedWorktrees:u,allowEditorRelaunch:!r}),dp(u),m.print();let h={removedWorktrees:u,count:u.length};return{content:g(JSON.stringify(h,null,2)),structuredContent:h}}catch(n){throw pr(n)?n:(c.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"}))}},dp=e=>{if(e.length>0){c.info("\u274C Removed worktrees:");for(let r of e)c.info(r);c.info("")}else c.info("\u2139\uFE0F No unused worktrees to remove")},ln=w({name:"worktrees-remove",description:'Remove local git worktrees for release branches. When everything is removed, also runs "git worktree prune" to clear stale metadata; the worktrees directory and its release/feature subfolders are left in place. 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:qr.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:qr.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:qr.array(qr.string()).describe("List of removed git worktree branches"),count:qr.number().describe("Number of git worktrees removed")},handler:ii});import mp from"@inquirer/confirm";import up from"node:process";import{z as pn}from"zod";import{$ as fp}from"zx";var ai=async e=>{let{confirmedCommand:r}=e;m.start("worktrees-sync"),await j({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await F("release"),o=await k(),n=`${o}${G}`,s=await dt(),i=r?!0:await mp({message:"Are you sure you want to proceed with these worktree changes?"});r||m.setInteractive(),i||(c.info("Operation cancelled. Exiting..."),up.exit(0)),r||m.addOption("--yes",!0);let{branchesToRemove:l}=gp({releasePRsList:s,currentWorktrees:t}),a=await J(),p=await hp({branches:l,worktreeDir:n,repoName:a});await zr({projectRoot:o,worktreeDir:n,currentWorktrees:t,removedWorktrees:p,allowEditorRelaunch:!1}),wp(p),m.print();let d={removedWorktrees:p,count:p.length};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}catch(t){throw pr(t)?t:(c.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"}))}},gp=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>Ae(s)).filter(s=>!r.includes(s))}},hp=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,l=re({repoName:o,branch:s});await Je(l),await fp`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"});c.error({error:i,branch:s,msg:l.message})}return n},wp=e=>{if(e.length>0){c.info("\u274C Removed worktrees:");for(let r of e)c.info(r);c.info("")}else c.info("\u2139\uFE0F No unused worktrees to remove")},dn=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:pn.array(pn.string()).describe("List of removed worktree branches"),count:pn.number().describe("Number of worktrees removed during sync")},handler:ai});var mn=[{cliName:"merge-dev",menuGroup:"release",mcpTool:ho,mcpExposed:!0},{cliName:"release-list",menuGroup:"release",mcpTool:bo,mcpExposed:!0},{cliName:"release-create",menuGroup:"release",mcpTool:Oo,mcpExposed:!0},{cliName:"release-desc-edit",menuGroup:"release",mcpTool:Fo,mcpExposed:!0},{cliName:"release-deploy-all",menuGroup:"release",mcpTool:yo,mcpExposed:!0},{cliName:"release-deploy-selected",menuGroup:"release",mcpTool:Ro,mcpExposed:!0},{cliName:"release-deliver",menuGroup:"release",mcpTool:wo,mcpExposed:!1},{cliName:"worktrees-add",menuGroup:"worktrees",mcpTool:sn,mcpExposed:!0},{cliName:"worktrees-list",menuGroup:"worktrees",mcpTool:an,mcpExposed:!0},{cliName:"worktrees-reload",menuGroup:"worktrees",mcpTool:cn,mcpExposed:!0},{cliName:"worktrees-remove",menuGroup:"worktrees",mcpTool:ln,mcpExposed:!1},{cliName:"worktrees-sync",menuGroup:"worktrees",mcpTool:dn,mcpExposed:!0},{cliName:"audit",menuGroup:"environment",mcpTool:Jt,mcpExposed:!0},{cliName:"vendor",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"vendor-config",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"doctor",menuGroup:"environment",mcpTool:eo,mcpExposed:!1},{cliName:"init",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"version",menuGroup:"environment",mcpTool:Ho,mcpExposed:!0},{cliName:"config",menuGroup:"environment",mcpTool:null,mcpExposed:!1},{cliName:"env-status",menuGroup:"environment",mcpTool:po,mcpExposed:!0},{cliName:"env-list",menuGroup:"environment",mcpTool:lo,mcpExposed:!0},{cliName:"env-load",menuGroup:"environment",mcpTool:so,mcpExposed:!0},{cliName:"env-clear",menuGroup:"environment",mcpTool:ao,mcpExposed:!0},{cliName:"env-autoload",menuGroup:null,mcpTool:null,mcpExposed:!1},{cliName:"vendor-check",menuGroup:null,mcpTool:Jo,mcpExposed:!0},{cliName:"vendor-diff",menuGroup:null,mcpTool:zo,mcpExposed:!0},{cliName:"vendor-manifest",menuGroup:null,mcpTool:Uo,mcpExposed:!1},{cliName:"vendor-sync",menuGroup:null,mcpTool:qo,mcpExposed:!1}],vp=()=>mn.flatMap(e=>e.mcpExposed&&e.mcpTool?[e.mcpTool]:[]),yp=e=>mn.flatMap(r=>r.menuGroup===e?[r.cliName]:[]);export{k as a,gn as b,xp as c,c as d,$n as e,W as f,x as g,ye as h,pe as i,R as j,Ht as k,Dn as l,Xe as m,Mm as n,Xn as o,Oe as p,oo as q,Pr as r,Fe as s,je as t,Re as u,Me as v,Le as w,os as x,ns as y,is as z,as as A,cs as B,us as C,ys as D,Rs as E,xs as F,Cs as G,Gc as H,As as I,Ns as J,Ls as K,zs as L,Us as M,Zs as N,Xs as O,bt as P,pr as Q,oi as R,ni as S,si as T,ii as U,ai as V,vp as W,yp as X};
164
+ //# sourceMappingURL=chunk-VI7TEWVJ.js.map