infra-kit 0.1.129 → 0.1.131

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 (58) hide show
  1. package/dist/boot-5GFZBDKL.js +2 -0
  2. package/dist/boot-5GFZBDKL.js.map +7 -0
  3. package/dist/chunk-4UUVKJYG.js +2 -0
  4. package/dist/chunk-4UUVKJYG.js.map +7 -0
  5. package/dist/chunk-52WL2IQX.js +4 -0
  6. package/dist/chunk-52WL2IQX.js.map +7 -0
  7. package/dist/chunk-6FU2TRU5.js +2 -0
  8. package/dist/chunk-6FU2TRU5.js.map +7 -0
  9. package/dist/chunk-6YAKVQZN.js +4 -0
  10. package/dist/chunk-6YAKVQZN.js.map +7 -0
  11. package/dist/chunk-C2HRONYA.js +6 -0
  12. package/dist/chunk-C2HRONYA.js.map +7 -0
  13. package/dist/chunk-CHETBZ6M.js +3 -0
  14. package/dist/chunk-CHETBZ6M.js.map +7 -0
  15. package/dist/chunk-F6VCGS3D.js +2 -0
  16. package/dist/chunk-F6VCGS3D.js.map +7 -0
  17. package/dist/chunk-LENH44GY.js +215 -0
  18. package/dist/chunk-LENH44GY.js.map +7 -0
  19. package/dist/chunk-LTKR3F4N.js +2 -0
  20. package/dist/chunk-LTKR3F4N.js.map +7 -0
  21. package/dist/chunk-O3YJM6IR.js +2 -0
  22. package/dist/chunk-O3YJM6IR.js.map +7 -0
  23. package/dist/chunk-SR2GFEY7.js +2 -0
  24. package/dist/chunk-SR2GFEY7.js.map +7 -0
  25. package/dist/chunk-TKZINCST.js +2 -0
  26. package/dist/chunk-TKZINCST.js.map +7 -0
  27. package/dist/chunk-VJPLVBRA.js +5 -0
  28. package/dist/chunk-VJPLVBRA.js.map +7 -0
  29. package/dist/chunk-X2L4F2VM.js +3 -0
  30. package/dist/chunk-X2L4F2VM.js.map +7 -0
  31. package/dist/cli.js +4 -19
  32. package/dist/cli.js.map +4 -4
  33. package/dist/dev-server.js +20 -16
  34. package/dist/dev-server.js.map +4 -4
  35. package/dist/dev-wizard-run-7HEKSAS2.js +2 -0
  36. package/dist/dev-wizard-run-7HEKSAS2.js.map +7 -0
  37. package/dist/lib/release-slug/release-slug.d.ts +26 -2
  38. package/dist/lib/vite/vite.d.ts +18 -4
  39. package/dist/mcp.js +1 -1
  40. package/dist/mcp.js.map +3 -3
  41. package/dist/persistent-ink-dev-ui-4U4B2B7C.js +8 -0
  42. package/dist/persistent-ink-dev-ui-4U4B2B7C.js.map +7 -0
  43. package/dist/program.js +2 -0
  44. package/dist/program.js.map +7 -0
  45. package/dist/update-check.js +2 -0
  46. package/dist/update-check.js.map +7 -0
  47. package/dist/vite.js +1 -1
  48. package/package.json +6 -3
  49. package/dist/boot-SGM5RVLJ.js +0 -2
  50. package/dist/boot-SGM5RVLJ.js.map +0 -7
  51. package/dist/chunk-2PZRQHWF.js +0 -2
  52. package/dist/chunk-2PZRQHWF.js.map +0 -7
  53. package/dist/chunk-6RRAK2QO.js +0 -5
  54. package/dist/chunk-6RRAK2QO.js.map +0 -7
  55. package/dist/chunk-IX2A34UU.js +0 -2
  56. package/dist/chunk-IX2A34UU.js.map +0 -7
  57. package/dist/chunk-V5IDN7ZM.js +0 -162
  58. package/dist/chunk-V5IDN7ZM.js.map +0 -7
@@ -0,0 +1,215 @@
1
+ import{a as u,b as N}from"./chunk-52WL2IQX.js";import{a as qr,b as ze,c as Hr,g as Zr,h as ae,i as Ge}from"./chunk-6YAKVQZN.js";import{F as Ho,G as Zo,I as Yo,J as Xo,N as Qo,O as St,P as X,R as O,S as b,T as en,U as $e,a as Lo,b as Vr,c as I,d as ie,e as fe,f as Wo,g as Ct,h as U,i as S,j as Jr,k as Vo,l as M,m as k,n as Jo,o as Bo,p as Ko,q as Y,r as Uo,s as zo,v as c,x as Go,y as qo}from"./chunk-X2L4F2VM.js";import{b as Pe,c as Pt,d as $t,e as dr,f as nn}from"./chunk-Z6KTUVIC.js";import{a as Br}from"./chunk-SR2GFEY7.js";import{a as L,b as Kr,c as cr,d as tn,e as Ur,f as Ve,g as Je,h as zr,i as Be,j as Ee,k as Ke,l as Gr,n as Ue,o as on,p as lr,q as Se,r as Q}from"./chunk-CHETBZ6M.js";import{a as Et,c as rn}from"./chunk-4UUVKJYG.js";import ur from"node:path";import ti from"node:process";import{z as W}from"zod";import Ls from"node:fs/promises";var ce=async e=>{try{return await Ls.access(e),!0}catch{return!1}};import Ys from"node:path";import sn from"node:fs/promises";import an from"node:path";import{pathToFileURL as Ws}from"node:url";import{z as Vs}from"zod";var ge="infra-kit.config.ts",Tt=async e=>{try{let r=await sn.readFile(an.join(e,"package.json"),"utf-8");return JSON.parse(r)}catch{return{}}},pr=async(e,r=Pe)=>{let t=an.join(e,ge);if(!await ce(t))throw new Error(`${ge} not found at ${t}`);let o=await sn.stat(t),i=(await import(`${Ws(t).href}?mtime=${Number(o.mtimeMs)}`)).default;if(i===void 0)throw new Error(`${ge} at ${t} has no default export`);let a=typeof i=="function"?await i():i,l=Et.safeParse(a);if(!l.success)throw new Error(`Invalid ${ge} at ${t}: ${Vs.prettifyError(l.error)}`);return $t(l.data,r)};import cn from"node:fs/promises";import Yr from"node:path";import Js from"yaml";var Bs="pnpm-workspace.yaml",Ks=async e=>(await cn.readdir(e,{withFileTypes:!0}).catch(()=>[])).filter(t=>t.isDirectory()).map(t=>Yr.join(e,t.name)),Us=async(e,r)=>{let t=[];for(let o of e){if(r==="*"){t.push(...await Ks(o));continue}let n=Yr.join(o,r);await ce(n)&&t.push(n)}return t},zs=async(e,r)=>{let t=[e];for(let o of r.split("/"))t=await Us(t,o);return t},mr=async e=>{let r=await cn.readFile(Yr.join(e,Bs),"utf-8"),o=((Js.parse(r)??{}).packages??[]).filter(s=>!s.startsWith("!")&&!s.startsWith("vendor")),n=new Set;for(let s of o){let i=await zs(e,s);for(let a of i)await ce(Yr.join(a,"package.json"))&&n.add(a)}return[...n].sort()};var It=async(e,r=Pe)=>{try{let t=await pr(e,r);return{check:{name:ge,status:"pass",message:"present and valid"},rules:t}}catch(t){return{check:{name:ge,status:"fail",message:t.message},rules:null}}};import Gs from"node:fs/promises";import qs from"node:path";var At=async(e,r)=>Promise.all(r.map(async t=>{let o=await Gs.stat(qs.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 _t=(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 Hs from"node:fs/promises";import Zs from"node:path";var qe="turbo.json",Ot=async(e,r)=>{if(r.length===0)return[];let t;try{let n=await Hs.readFile(Zs.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 Nt=async(e,r=Pe)=>{let t=await Tt(e),o=t.name??Ys.basename(e),{check:n,rules:s}=await It(e,r),i=[n];s&&(i.push(..._t(t.scripts??{},s.requiredScripts)),i.push(...await At(e,s.requiredFiles)),i.push(...await Ot(e,s.turboTasks)));let a=i.every(l=>l.status==="pass");return{packageDir:e,packageName:o,checks:i,passed:a}};var g=e=>[{type:"text",text:e}],y=e=>e;import Xs from"node:path";var Qs=(e,r)=>{let t=new Set;for(let o of Object.values(e))for(let n of Object.keys(Zo(o,r).proxy))t.add(n);return[...t]},ei=async(e,r)=>{let t={},o=[];return await Promise.all(r.map(async n=>{try{let i=(await rn(Xs.join(e,"apps",n,"ui")))?.proxy?.routes;if(!i)return;t[n]=Object.fromEntries(Object.entries(i).map(([a,l])=>[a,l.packageName]))}catch(s){o.push({app:n,message:s instanceof Error?s.message:String(s)})}})),{routePkg:(n,s)=>t[n]?.[s],loadErrors:o}},ri=(e,r)=>[...r.map(t=>({name:`devServersPresets:config:${t.app}`,status:"fail",message:`could not load apps/${t.app}/ui/infra-kit.config.ts (referenced by a preset proxy override): ${t.message}`})),...e.map(t=>({name:`devServersPresets:${t.preset}`,status:"fail",message:t.message}))],ln=async e=>{let r=(await b()).devServersPresets;if(!r||Object.keys(r).length===0)return null;let t=Ho(r);if(t.length>0){let m=t.map(h=>({name:`devServersPresets:${h.preset}`,status:"fail",message:h.message}));return{packageDir:e,packageName:"devServersPresets",checks:m,passed:!1}}let o=Go(e),n=qo(e),s={api:o.map(m=>m.name),ui:n.map(m=>m.name)},{routePkg:i,loadErrors:a}=await ei(e,Qs(r,s)),l={discovered:s,apiPkgByApp:Object.fromEntries(o.map(m=>[m.name,m.packageName])),routePkg:i},d=ri(Yo(r,l),a),p=d.length===0?[{name:"devServersPresets:proxy-locality",status:"pass",message:"every local proxy override resolves to a backend the preset launches"}]:d;return{packageDir:e,packageName:"devServersPresets",checks:p,passed:d.length===0}};var oi=async e=>{let r=ur.resolve(e);for(;r!==ur.dirname(r);){if(await ce(ur.join(r,"package.json")))return r;r=ur.dirname(r)}if(await ce(ur.join(r,"package.json")))return r;throw new Error(`No package.json found in or above ${e}`)},ni=async e=>e.root?[{dir:await k(),baseline:Pt}]:e.all?(await mr(await k())).map(t=>({dir:t})):[{dir:await oi(e.cwd??ti.cwd())}],si=e=>{let r=e.passed?"PASS":"FAIL";c.info(`
2
+ ${e.packageName} \u2014 ${r}`);for(let t of e.checks){let o=t.status==="pass"?"[PASS]":"[FAIL]";c.info(` ${o} ${t.name}: ${t.message}`)}},dn=async(e={})=>{let r=await ni(e),t=[];for(let s of r)t.push(await Nt(s.dir,s.baseline));if(e.root){let s=await ln(r[0].dir);s&&t.push(s)}for(let s of t)si(s);let o=t.every(s=>s.passed);c.info(`
3
+ ${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}},ii={all:W.boolean().optional().describe("Audit every non-vendor workspace package"),root:W.boolean().optional().describe("Audit the monorepo root (turbo pipeline + root commands)")},ai={allPassed:W.boolean().describe("Whether every audited package passed all checks"),packages:W.array(W.object({name:W.string(),passed:W.boolean(),checks:W.array(W.object({name:W.string(),status:W.enum(["pass","fail"]),message:W.string()}))})).describe("Per-package check results")},ci=y({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:ii,outputSchema:ai,handler:e=>dn({all:e.all,root:e.root})});import Qr from"node:fs/promises";import pi from"node:path";import mi from"node:process";var pn=` // "environments": ["dev", "staging", "prod"], // string[] (>=1) \u2014 required in layer 1
4
+ //
5
+ // "envManagement": { // required in layer 1; provider-tagged
6
+ // "provider": "doppler",
7
+ // "config": { "name": "my-doppler-project" }
8
+ // },
9
+ //
10
+ // "ide": {
11
+ // "provider": "cursor",
12
+ // "config": { "workspaceConfigPath": "/path/to/your.code-workspace" }
13
+ // },
14
+ // // Or, for Zed (no workspace file \u2014 one window with all worktrees via "zed <root> <wt...>"):
15
+ // "ide": { "provider": "zed", "config": {} },
16
+ // // Or drive BOTH editors at once with an array (at most one entry per provider):
17
+ // "ide": [
18
+ // { "provider": "cursor", "config": { "workspaceConfigPath": "/path/to/your.code-workspace" } },
19
+ // { "provider": "zed", "config": {} }
20
+ // ],
21
+ //
22
+ // "taskManager": {
23
+ // "provider": "jira",
24
+ // "config": { "baseUrl": "https://acme.atlassian.net", "projectId": 123 }
25
+ // },
26
+ //
27
+ // "worktrees": {
28
+ // "openInGithubDesktop": false,
29
+ // "openInCmux": true,
30
+ // // cmux pane layout for opened worktrees: "two-columns" (default, left | right)
31
+ // // or "three-pane" (left split top/bottom + full-height right).
32
+ // "cmux": { "layout": "two-columns" }
33
+ // },
34
+ //
35
+ // // Auto-load Doppler env when working inside this project/worktree. Omit to
36
+ // // disable. "trigger" (pick one): "shell-startup" (new shells) | "cli-invocation"
37
+ // // (before each infra-kit command, primes subsequent commands). "config" is the
38
+ // // environment to load (must be one of "environments"). Requires the committed
39
+ // // infra-kit.json at the git repo root, and the zsh shell integration
40
+ // // (infra-kit init + a new shell). zsh only.
41
+ // "envAutoLoad": { "trigger": "shell-startup", "config": "dev" },
42
+ //
43
+ // // Per-app local-dev overrides, keyed by APP FOLDER name (the directory under
44
+ // // apps/). Both fields optional: "port" pins the local listen port (otherwise
45
+ // // <APP>_PORT / PORT / a built-in default), "prefixUrl" pins the URL prefix the
46
+ // // app is served under. An unknown app name is ignored at resolve time, never a
47
+ // // parse error.
48
+ // "dev": {
49
+ // "client": { "port": 4001, "prefixUrl": "/api" }
50
+ // },
51
+ //
52
+ // // Named \`infra-kit dev <preset>\` sessions. The keys under "apps" are PACKAGES \u2014
53
+ // // "<app>/api" or "<app>/ui". A bare "<app>" is a FOLDER, not a package, and is
54
+ // // REJECTED. Per target: "watchDeps" (api targets) rebuilds the shared-package
55
+ // // dependency closure and restarts on change; "proxy" maps a route path to
56
+ // // "local" | "cloud" for this session only. "cmux": true runs each launched target
57
+ // // in its own cmux pane. Omit "apps" entirely to launch every discovered target.
58
+ // "devServersPresets": {
59
+ // "backend": {
60
+ // "apps": {
61
+ // "client/api": { "watchDeps": true, "proxy": { "/api": "local", "/auth": "cloud" } },
62
+ // "client/ui": {}
63
+ // },
64
+ // "cmux": true
65
+ // }
66
+ // },
67
+ //
68
+ // // Local-dev portless proxy \u2014 a ROOT key, NOT nested under "dev". "port" is the
69
+ // // daemon's listen port. Default 80: privileged, so the daemon must already be
70
+ // // installed (one-time \`sudo portless service install --no-tls\`) \u2014 infra-kit never
71
+ // // elevates. 1355 is the zero-sudo fallback: it trades the clean port-free hero URL
72
+ // // (http://<release>.<package>.localhost) for not needing root.
73
+ // "devProxy": { "port": 80 }`,jt=()=>`// infra-kit user-global config \u2014 ~/.infra-kit/infra-kit.json
74
+ //
75
+ // Merge chain (later layers override earlier ones at top-level keys):
76
+ // 1. <repo>/infra-kit.json \u2014 committed project config (required)
77
+ // 2. ~/.infra-kit/infra-kit.json \u2014 user-global (the sibling of this file)
78
+ // 3. ~/.infra-kit/projects/<repo-name>/infra-kit.json \u2014 user-scope per-project override
79
+ //
80
+ // Merge is shallow: setting a top-level key replaces that whole section from
81
+ // layer 1. Arrays do not concatenate. Top-level keys recognized:
82
+ // environments, envManagement, ide, taskManager, worktrees, envAutoLoad, dev,
83
+ // devServersPresets, devProxy. The schema is strict \u2014 an unrecognized top-level
84
+ // key is a parse error, not a silently ignored one.
85
+ //
86
+ // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real global
87
+ // overrides in the sibling infra-kit.json (strict JSON: no comments, double-quoted
88
+ // keys). Per-project tweaks belong in layer 3 \u2014 run \`infra-kit config edit\`.
89
+ //
90
+ // Every recognized key is documented below. NOTE: \`environments\` and
91
+ // \`envManagement\` are REQUIRED in the committed project infra-kit.json (layer 1)
92
+ // and are usually NOT set in this user-global layer \u2014 they are shown here only to
93
+ // document the full, valid config shape.
94
+ {
95
+ ${pn}
96
+ }
97
+ `,Dt=e=>`// infra-kit user override for ${e} \u2014 ~/.infra-kit/projects/${e}/infra-kit.json
98
+ //
99
+ // Layer 3 (highest precedence) of the config merge chain. Shallow-merged on top of
100
+ // <repo>/infra-kit.json (layer 1) and ~/.infra-kit/infra-kit.json (layer 2) \u2014 a
101
+ // top-level key set here replaces that whole section wholesale; arrays do not
102
+ // concatenate. Top-level keys recognized: environments, envManagement, ide,
103
+ // taskManager, worktrees, envAutoLoad, dev, devServersPresets, devProxy. The schema
104
+ // is strict \u2014 an unrecognized top-level key is a parse error, not a silently ignored
105
+ // one.
106
+ //
107
+ // This .example.jsonc is reference only \u2014 it is NOT loaded. Put real overrides
108
+ // in the sibling infra-kit.json (strict JSON: no comments, double-quoted keys).
109
+ //
110
+ // Every recognized key is documented below. NOTE: \`environments\` and
111
+ // \`envManagement\` are REQUIRED in the committed project infra-kit.json (layer 1)
112
+ // and are usually NOT set in this override layer \u2014 they are shown here only to
113
+ // document the full, valid config shape.
114
+ {
115
+ ${pn}
116
+ }
117
+ `,Ft=()=>`// infra-kit factory registry \u2014 ~/.infra-kit/vendor.json
118
+ //
119
+ // Machine-local registry the vendor commands (sync/manifest/diff) read to know
120
+ // where your project repos live and which ones to stamp. This .example.jsonc is
121
+ // reference only \u2014 it is NOT loaded. The real file is the strict-JSON sibling
122
+ // vendor.json (no comments, double-quoted keys); run \`infra-kit vendor config --init\`
123
+ // to scaffold it.
124
+ {
125
+ // "workspaceDir": "~/projects", // string (absolute or ~-prefixed) \u2014 where target repos are cloned
126
+ // "targets": ["my-repo-a", "my-repo-b"] // string[] (>=1) \u2014 repo dir names resolved under workspaceDir
127
+ }
128
+ `;import li from"node:fs/promises";import di from"node:os";var V=async e=>{try{return await li.access(e),!0}catch{return!1}},v=e=>{let r=di.homedir();return e.startsWith(r)?`~${e.slice(r.length)}`:e};var mn=!1,ui=e=>e.replace(/\.json$/,".example.jsonc"),fi=async e=>{try{return await Qr.readFile(e,"utf-8")}catch{return null}},et=async e=>{let r=e.userProject,t=ui(r);await Qr.mkdir(pi.dirname(r),{recursive:!0});let o=!await V(r);o&&await Qr.writeFile(r,`{}
129
+ `,"utf-8");let n=Dt(e.projectName),s=await fi(t)!==n;return s&&await Qr.writeFile(t,n,"utf-8"),o&&en(),{configPath:r,examplePath:t,createdConfig:o,refreshedExample:s}},rt=e=>`Created ${v(e.configPath)} \u2014 see ${v(e.examplePath)} for the annotated reference.`,gi=async()=>{if(mi.env.INFRA_KIT_NO_SEED||mn)return;mn=!0;let e;try{e=await O()}catch{return}if(await V(e.main))try{let r=await et(e);r.createdConfig?c.info(rt(r)):r.refreshedExample&&c.debug(`Refreshed ${v(r.examplePath)} to match the current schema.`)}catch(r){c.debug({err:r,msg:`Skipped seeding ${v(e.userProject)} (config bootstrap failed).`})}};import le from"node:fs";import $n from"node:os";import vr from"node:path";import En from"node:process";var He=(e,r,t)=>{let o=e.indexOf(r),n=e.indexOf(t);return o!==-1&&n!==-1&&n>=o},he=(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?`
130
+ ${i}`:"")};var un=(e,r,t)=>`${e}
131
+ ${r}
132
+ ${t}`,fr=({content:e,body:r,startMarker:t,endMarker:o,placement:n="replace-in-place"})=>{let s=un(t,r,o),i=He(e,t,o);if(n==="replace-in-place"&&i){let d=e.indexOf(t),p=e.indexOf(o)+o.length;return e.slice(0,d)+s+e.slice(p)}let l=(i?he(e,t,o)??e:e).replace(/\n+$/,"");return l.length>0?`${l}
133
+ ${s}
134
+ `:`${s}
135
+ `};import j from"node:fs";import gr from"node:path";var hr="<!-- infra-kit:begin -->",yr="<!-- infra-kit:end -->",hi="<!-- infra-kit:version ",yi="<!-- infra-kit:import:begin -->",vi="<!-- infra-kit:import:end -->",wi="AGENTS.md",ki="CLAUDE.md",Ri=e=>`${hi}${e} -->`,bi=e=>[Ri(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(`
136
+ `),fn=e=>{if(j.existsSync(e)&&j.lstatSync(e).isSymbolicLink())throw new Error(`Refusing to write ${e} because the destination is a symlink`)},gn=e=>{let r=new Date().toISOString().replace(/[:.]/g,"-");j.copyFileSync(e,`${e}.backup.${r}`)},hn=(e,r)=>{fn(e);let t=j.existsSync(e);return(t?j.readFileSync(e,"utf-8"):null)===r?"unchanged":(t&&gn(e),j.mkdirSync(gr.dirname(e),{recursive:!0}),j.writeFileSync(e,r,"utf-8"),t?"updated":"created")},xi=(e,r)=>j.existsSync(e)?j.readFileSync(e,"utf-8"):r,Ci=(e,r,t)=>{let o=j.readFileSync(e,"utf-8");if(!He(o,r,t))throw new Error(`Post-write validation failed: managed block missing from ${e}`)},Pi=e=>{if(!j.existsSync(e))return"unchanged";fn(e);let r=j.readFileSync(e,"utf-8"),t=he(r,hr,yr);return t===null?"unchanged":t.trim()===""?(gn(e),j.rmSync(e),"removed"):hn(e,t)},yn=async()=>{let e;try{e=(await O()).main}catch{return c.info("Skipped agent-instruction files \u2014 not inside an infra-kit repo"),{skipped:!0,root:null,written:[]}}if(!j.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=gr.dirname(e),t=Br.version,o=bi(t),n=gr.join(r,wi),s=gr.join(r,ki),i=xi(s,"");i=he(i,yi,vi)??i,i=fr({content:i,body:o,startMarker:hr,endMarker:yr,placement:"replace-in-place"});let a=[{path:s,action:hn(s,i)},{path:n,action:Pi(n)}];Ci(s,hr,yr);for(let l of a)l.action==="unchanged"&&l.path!==s||c.info(` ${l.action.padEnd(9)} ${gr.relative(r,l.path)}`);return c.info(`Agent-instruction files synced (infra-kit ${t})`),{skipped:!1,root:r,written:a}};import J from"node:fs/promises";import ee from"node:path";import{pathToFileURL as Si}from"node:url";import Ti from"yaml";import{z as Rn}from"zod";import $i from"node:fs/promises";import Mt from"node:os";import Lt from"node:path";import{z as Ei}from"zod";import{z as tt}from"zod";var vn="vendor.json",ot=tt.object({workspaceDir:tt.string().min(1),targets:tt.array(tt.string()).min(1)}).strict();var Wt=()=>Lt.join(Mt.homedir(),Xo,vn),wn=e=>{if(e==="~")return Mt.homedir();if(e.startsWith("~/"))return Lt.join(Mt.homedir(),e.slice(2));if(Lt.isAbsolute(e))return e;throw new Error(`workspaceDir must be absolute or ~-prefixed, got: ${e}`)},Ze=async()=>{let e=Wt(),r;try{r=await $i.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:
137
+
138
+ {
139
+ "workspaceDir": "~/projects",
140
+ "targets": ["my-repo"]
141
+ }
142
+ `)}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=ot.safeParse(t);if(!o.success)throw new Error(`Invalid factory config at ${e}: ${Ei.prettifyError(o.error)}`);return o.data};var kn=e=>e.replace(/\.json$/,".yml"),bn=async()=>{let e;try{e=await O()}catch{return}let r=[{label:"infra-kit.json",yml:kn(e.main),json:e.main,schema:Qo},{label:"~/.infra-kit/infra-kit.json",yml:ee.join(ee.dirname(e.userGlobal),"config.yml"),json:e.userGlobal,schema:St},{label:`~/.infra-kit/projects/${e.projectName}/infra-kit.json`,yml:kn(e.userProject),json:e.userProject,schema:St}],t=0;for(let o of r){let[n,s]=await Promise.all([V(o.yml),V(o.json)]);if(n){if(s){c.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${v(o.json)} already exists (remove the stale .yml manually)`);continue}try{let i=await J.readFile(o.yml,"utf-8"),a=Ti.parse(i)??{},l=o.schema.safeParse(a);if(!l.success){c.info(`\u26A0 Skipped ${v(o.yml)} \u2014 invalid config: ${Rn.prettifyError(l.error)}`);continue}await J.mkdir(ee.dirname(o.json),{recursive:!0}),await J.writeFile(o.json,`${JSON.stringify(l.data,null,2)}
143
+ `,"utf-8"),await J.rm(o.yml,{force:!0}),c.info(`\u2713 Migrated ${v(o.yml)} \u2192 ${v(o.json)}`),t++}catch(i){c.info(`\u26A0 Skipped ${v(o.yml)} \u2014 ${i.message}`)}}}t>0&&$e()},xn=async()=>{let e;try{e=await O()}catch{return}let r=ee.dirname(e.userGlobal),t=[{from:ee.join(r,"config.json"),to:e.userGlobal},{from:ee.join(r,"config.example.jsonc"),to:ee.join(r,"infra-kit.example.jsonc")}],o=0;for(let{from:n,to:s}of t){let[i,a]=await Promise.all([V(n),V(s)]);if(i){if(a){c.info(`\u26A0 Skipped ${v(n)} \u2014 ${v(s)} already exists (remove the stale file manually)`);continue}try{await J.mkdir(ee.dirname(s),{recursive:!0}),await J.rename(n,s),c.info(`\u2713 Renamed ${v(n)} \u2192 ${v(s)}`),o++}catch(l){c.info(`\u26A0 Skipped ${v(n)} \u2014 ${l.message}`)}}}o>0&&$e()},Cn=async()=>{let e=Wt(),r=ee.dirname(e),t=ee.join(r,"vendor.config.ts"),[o,n]=await Promise.all([V(t),V(e)]);if(o){if(n){c.info(`\u26A0 Skipped ${v(t)} \u2014 ${v(e)} already exists (remove the stale vendor.config.ts manually)`);return}try{let s=await J.stat(t),l=(await import(`${Si(t).href}?mtime=${Number(s.mtimeMs)}`)).default,d=typeof l=="function",p=d?await l():l,m=ot.safeParse(p);if(!m.success){c.info(`\u26A0 Skipped ${v(t)} \u2014 invalid factory config: ${Rn.prettifyError(m.error)}`);return}await J.mkdir(r,{recursive:!0}),await J.writeFile(e,`${JSON.stringify(m.data,null,2)}
144
+ `,"utf-8"),await J.rm(t,{force:!0}),d?c.info(`\u26A0 Migrated ${v(t)} \u2192 ${v(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 ${v(e)} directly to change them.`):c.info(`\u2713 Migrated ${v(t)} \u2192 ${v(e)}`)}catch(s){c.info(`\u26A0 Skipped ${v(t)} \u2014 ${s.message}`)}}},Ii=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 a=Object.fromEntries(Object.entries(i).filter(([l])=>l!=="mode"));return{...s,config:a}},n=Array.isArray(r)?r.map(o):o(r);return t?{changed:!0,result:{...e,ide:n}}:{changed:!1,result:e}},Pn=async()=>{let e;try{e=await O()}catch{return}let r=[e.main,e.userGlobal,e.userProject],t=0;for(let o of r)if(await V(o))try{let n=await J.readFile(o,"utf-8");if(n.trim()==="")continue;let s=JSON.parse(n),{changed:i,result:a}=Ii(s);if(!i)continue;await J.writeFile(o,`${JSON.stringify(a,null,2)}
145
+ `,"utf-8"),c.info(`\u2713 Normalized ide config in ${v(o)} (removed legacy "mode")`),t++}catch(n){c.info(`\u26A0 Skipped normalizing ${v(o)} \u2014 ${n.message}`)}t>0&&$e()};var wr="# -- infra-kit:begin --",Ye="# -- infra-kit:end --",Ai=[["# region infra-kit","# endregion infra-kit"]],_i="# infra-kit shell functions",em=async()=>{let e=vr.join($n.homedir(),".zshrc"),r=le.existsSync(e)?Di(le.readFileSync(e,"utf-8")):"",t=fr({content:r,body:Sn(),startMarker:wr,endMarker:Ye,placement:"append-end"});le.writeFileSync(e,t),c.info(`Added infra-kit shell functions to ${e}`),await bn(),await Pn(),await xn(),await Cn(),Oi(),await yn(),await Ni();let o=En.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.")},Oi=()=>{let e=vr.join($n.homedir(),".infra-kit"),r=vr.join(e,"infra-kit.json");if(le.mkdirSync(e,{recursive:!0}),le.writeFileSync(vr.join(e,"infra-kit.example.jsonc"),jt(),"utf-8"),le.writeFileSync(vr.join(e,"vendor.example.jsonc"),Ft(),"utf-8"),le.existsSync(r)){c.info(`User-global config already present at ${r} (refreshed reference examples)`);return}le.writeFileSync(r,`{}
146
+ `,"utf-8"),c.info(`Wrote user-global config to ${r} (see the sibling .example.jsonc files for reference)`)},Ni=async()=>{if(!En.env.INFRA_KIT_NO_SEED)try{let e=await O();if(!le.existsSync(e.main))return;let r=await et(e);r.createdConfig&&c.info(rt(r))}catch(e){c.debug({err:e,msg:"Skipped seeding the user-project config (init)."})}},ji=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"),Di=e=>{let r=he(e,wr,Ye);if(r!==null)return r;for(let[a,l]of Ai){let d=he(e,a,l);if(d!==null)return d}let t=e.indexOf(_i);if(t===-1)return e;let o=e.slice(0,t).replace(/\n+$/,""),n=e.slice(t).split(`
147
+ `),s=0;for(;s<n.length&&ji(n[s]);)s++;let i=n.slice(s).join(`
148
+ `);return o+(i?`
149
+ ${i}`:"")},Sn=()=>{let e="pnpm exec infra-kit";return["zmodload zsh/stat 2>/dev/null","zmodload zsh/datetime 2>/dev/null","zmodload zsh/sched 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}}",": ${_INFRA_KIT_WARM_TTL:=7200}","export _INFRA_KIT_LAST_LOAD_MTIME _INFRA_KIT_LAST_CLEAR_MTIME _INFRA_KIT_SHELL_STARTED _INFRA_KIT_WARM_TTL",`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; }`,"_infra_kit_notify() {"," zle && print -u2 -n $'\\r\\e[K'",' print -u2 -- "$1"'," zle && zle reset-prompt","}","_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",' _infra_kit_notify "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",' _infra_kit_notify "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_AUTOLOAD_WINDOW=6","export _INFRA_KIT_AUTOLOAD_WINDOW","_infra_kit_poll_autoload() {"," _infra_kit_autoload"," if (( _INFRA_KIT_LAST_LOAD_MTIME < _INFRA_KIT_SHELL_STARTED )) && (( ${EPOCHSECONDS:-0} - _INFRA_KIT_SHELL_STARTED < _INFRA_KIT_AUTOLOAD_WINDOW )); then"," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," fi","}","_infra_kit_warm_source() {",' local canon="$1" key'," if (( $+commands[shasum] )); then",' key=$(printf %s "$canon" | shasum -a 256 | cut -c1-64)'," elif (( $+commands[sha256sum] )); then",' key=$(printf %s "$canon" | sha256sum | cut -c1-64)'," else"," return"," fi",' local cache_root="${XDG_CACHE_HOME:-$HOME/.cache}/infra-kit"',' local warm="$cache_root/projects/$key/env-load.sh"',' local wclear="$cache_root/projects/$key/env-clear.sh"',' [[ -f "$warm" ]] || return'," local wm=0 cm=0",' wm=$(zstat +mtime -- "$warm" 2>/dev/null || echo 0)',' [[ -f "$wclear" ]] && cm=$(zstat +mtime -- "$wclear" 2>/dev/null || echo 0)'," (( cm >= wm )) && return"," (( ${EPOCHSECONDS:-0} - wm >= _INFRA_KIT_WARM_TTL )) && return",' source "$warm"',' _infra_kit_notify "infra-kit: loaded cached vars for ${INFRA_KIT_ENV_CONFIG:-?} (refreshing\u2026)"',"}","_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',' local canon="${dir:A}"',' _infra_kit_warm_source "$canon"',` ( ${e} env-autoload --project-dir "$canon" & ) >/dev/null 2>&1`," (( $+builtins[sched] )) && sched +1 _infra_kit_poll_autoload"," return"," fi",' prev="$dir"',' dir="${dir:h}"'," done","}","if (( _INFRA_KIT_SHELL_STARTED > 0 )); then"," _infra_kit_startup_autoload","fi"].join(`
150
+ `)},Tn=()=>`${wr}
151
+ ${Sn()}
152
+ ${Ye}`;import B from"node:fs";import Ji from"node:os";import _e from"node:path";import{z as Xe}from"zod";import{$ as Zt}from"zx";import{$ as In}from"zx";var An=5e3,nt=async()=>{try{await In`doppler --version`.timeout(An)}catch(e){throw new Error("Doppler CLI is not installed. Install it from: https://docs.doppler.com/docs/install-cli",{cause:e})}try{await In`doppler me`.timeout(An)}catch(e){throw new Error("Doppler CLI is not authenticated (or timed out). Run: doppler login",{cause:e})}};var Fi="Could not find requested project",Mi="Could not find requested config",Vt=e=>e.includes(Fi)?"project":e.includes(Mi)?"config":"unknown",Jt=({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(`
153
+ `)};import{$ as kr}from"zx";var Li=5e3,Te=async()=>{let{envManagement:e}=await b();return e.config.name},Rr=async()=>_n(()=>kr`doppler projects --json`),Bt=async e=>_n(()=>kr`doppler configs --project ${e} --json`),_n=async e=>{let r=kr.quiet;kr.quiet=!0;try{let t=await e().timeout(Li);return Wi(t.stdout)}catch{return null}finally{kr.quiet=r}},Wi=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};import Vi from"node:fs/promises";var Kt=async(e,r)=>{if(!r)return{hasOverrides:!1,overrideKeys:[],unreadable:!1};try{let t=await Vi.readFile(e,"utf-8"),o=t.trim()===""?{}:JSON.parse(t);if(typeof o!="object"||o===null||Array.isArray(o))return{hasOverrides:!1,overrideKeys:[],unreadable:!0};let n=Object.keys(o);return{hasOverrides:n.length>0,overrideKeys:n,unreadable:!1}}catch{return{hasOverrides:!1,overrideKeys:[],unreadable:!0}}},Ut=e=>e.unreadable?"(unreadable \u2014 invalid JSON)":e.overrideKeys.length===0?"(empty \u2014 no overrides)":`(${e.overrideKeys.length} override(s): ${e.overrideKeys.join(", ")})`;import Ie from"node:fs";import br from"node:path";var zt=({autoLoaded:e,projectDir:r,canonicalProjectRoot:t})=>!e||!r||!t?!1:t===r,Ae=e=>{if(!e)return"";try{return Ie.realpathSync(e)}catch{return""}},Gt=(e,r)=>{try{let t=lr(e);Ie.mkdirSync(t,{recursive:!0,mode:448}),Se(br.join(t,L),r,384)}catch(t){c.debug(`warm-cache write skipped: ${t.message}`)}},qt=(e=Date.now(),r=cr)=>{let t=on(),o;try{o=Ie.readdirSync(t,{withFileTypes:!0})}catch{return}for(let n of o){if(!n.isDirectory())continue;let s=br.join(t,n.name);try{let{mtimeMs:i}=Ie.statSync(br.join(s,L));e-i>=r*1e3&&Ie.rmSync(s,{recursive:!0,force:!0})}catch{}}},Ht=(e,r)=>{try{let t=lr(e);if(r){Ie.rmSync(t,{recursive:!0,force:!0});return}if(!Ie.existsSync(br.join(t,L)))return;Se(br.join(t,Kr),`# infra-kit warm cache cleared
154
+ `,384)}catch(t){c.debug(`warm-cache invalidate skipped: ${t.message}`)}};var ye=async(e,r,t,o)=>{try{return await Zt`${r}`,{name:e,status:"pass",message:t}}catch{return{name:e,status:"fail",message:o}}},Bi=()=>{let e="zshrc init block",r=_e.join(Ji.homedir(),".zshrc");if(!B.existsSync(r))return{name:e,status:"fail",message:"~/.zshrc not found. Run: infra-kit init"};let t=B.readFileSync(r,"utf-8"),o=t.indexOf(wr),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=Tn().trim();return s!==i?{name:e,status:"fail",message:"infra-kit shell block in ~/.zshrc is out of date. Run: infra-kit init"}:{name:e,status:"pass",message:"infra-kit shell block in ~/.zshrc is up to date"}},Ki=async()=>{let e="warm cache",r;try{r=await k()}catch{return{name:e,status:"pass",message:"warm cache: not a git project"}}let t=Ae(r);if(!t)return{name:e,status:"pass",message:"warm cache: unavailable"};let o=_e.join(lr(t),L);if(!B.existsSync(o))return{name:e,status:"pass",message:"warm cache: none yet (populated on next auto-load)"};let n=Math.floor((Date.now()-B.statSync(o).mtimeMs)/1e3),s=Math.floor(n/60),i=Math.floor(cr/60);return n>=cr?{name:e,status:"pass",message:`warm cache: present but stale (${s}m old, TTL ${i}m) \u2014 will refresh`}:{name:e,status:"pass",message:`warm cache: present, ${s}m old`}},Ui=async()=>{let e="pnpm enableGlobalVirtualStore";try{let r=await k(),t=_e.join(r,"pnpm-workspace.yaml");if(!B.existsSync(t))return{name:e,status:"fail",message:`pnpm-workspace.yaml not found at ${t}`};let o=B.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}`}}},zi=async()=>{let e="infra-kit config valid";try{return $e(),await b(),{name:e,status:"pass",message:"infra-kit.json is valid (user overrides applied if present)"}}catch(r){return{name:e,status:"fail",message:r.message}}},Gi=async()=>{let e="doppler project exists",r;try{r=await Te()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config could not be read (see config check)"}}let t=await Rr();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"}`}},qi=async()=>{let e="user override path";try{let r=await O(),t=B.existsSync(r.userProject),o=await Kt(r.userProject,t),n=t?Ut(o):"(not created \u2014 seed failed?)";return{name:e,status:"pass",message:`${v(r.userProject)} ${n} \u2014 project: ${r.projectName}`}}catch(r){return{name:e,status:"fail",message:r.message}}},Hi=async()=>{let e="legacy user-global config",r;try{r=await O()}catch{return{name:e,status:"pass",message:"Skipped \u2014 infra-kit config paths could not be resolved"}}let t=_e.join(_e.dirname(r.userGlobal),"config.json");return B.existsSync(t)?B.existsSync(r.userGlobal)?{name:e,status:"fail",message:`Stale legacy config.json found at ${v(t)} \u2014 ${v(r.userGlobal)} is active; remove the old file.`}:{name:e,status:"fail",message:`Legacy user-global config.json found at ${v(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"}},Zi={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/"}},Yi=async e=>{let r=Zi[e];try{return await Zt`${r.command}`,{ok:!0,label:r.label,failMsg:r.failMsg}}catch{return{ok:!1,label:r.label,failMsg:r.failMsg}}},Xi=async()=>{let e="ide installed",r;try{$e();let n=await b();r=X(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=>Yi(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("; ")}},Qi=[1,2,3,5,7],ea=async()=>{let e="rtk configured";try{let t=(await Zt`rtk init --show`).stdout.split(`
155
+ `).map(n=>n.trim()).filter(n=>n.startsWith("[ok]")||n.startsWith("[--]")),o=[];for(let n of Qi){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}`}}},ra=async()=>{let e;try{e=(await O()).main}catch{return[]}if(!B.existsSync(e))return[];let r=_e.join(_e.dirname(e),"CLAUDE.md"),t=B.existsSync(r)?B.readFileSync(r,"utf-8"):"",o=He(t,hr,yr);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"}]},On=async()=>{let r=[...await Promise.all([ye("gh installed",["gh","--version"],"GitHub CLI is installed","GitHub CLI is not installed. Install from: https://cli.github.com/"),ye("gh authenticated",["gh","auth","status"],"GitHub CLI is authenticated","GitHub CLI is not authenticated. Run: gh auth login"),ye("doppler installed",["doppler","--version"],"Doppler CLI is installed","Doppler CLI is not installed. Install from: https://docs.doppler.com/docs/install-cli"),ye("doppler authenticated",["doppler","me"],"Doppler CLI is authenticated","Doppler CLI is not authenticated. Run: doppler login"),ye("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"),ye("rtk installed",["rtk","--version"],"RTK is installed","RTK is not installed. Install from: https://github.com/rtk-ai/rtk"),ye("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"),ye("cmux installed",["cmux","--version"],"cmux is installed","cmux is not installed. Install from: https://cmux.com/"),ea(),Promise.resolve(Bi()),Ki(),Ui(),zi(),Gi(),qi(),Hi(),Xi()]),...await ra()];c.info(`Doctor check results:
156
+ `);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}},ta=y({name:"doctor",description:"Check installation and authentication status of gh, doppler, aws, and rtk CLIs",inputSchema:{},outputSchema:{checks:Xe.array(Xe.object({name:Xe.string().describe("Name of the check"),status:Xe.enum(["pass","fail"]).describe("Check result"),message:Xe.string().describe("Details about the check result")})).describe("List of all check results"),allPassed:Xe.boolean().describe("Whether all checks passed")},handler:On});import Yt from"node:fs";import Nn from"node:path";import oa from"node:process";import{z as xr}from"zod";var na=async e=>{let r="";try{r=await k()}catch{return}let t=Ae(r);t&&Ht(t,e)},sa=e=>[...e.map(r=>`unset ${r}`),`unset ${Ur}`,`unset ${Ve}`,`unset ${Je}`,`unset ${zr}`,`unset ${Be}`,`unset ${Ee}`,`export ${Ke}='1'`],jn=async({purge:e=!1}={})=>{let r=Ue(),t=Nn.join(r,L),o=Yt.existsSync(t);if(!o&&!e)throw new Error("No loaded environment found. Run `env-load` first.");await na(e);let n=o?Gr(t):[],s=sa(n),i=Nn.resolve(r,Kr);Yt.mkdirSync(r,{recursive:!0,mode:448}),Se(i,`${s.join(`
157
+ `)}
158
+ `,384),oa.stdout.write(`${i}
159
+ `),o&&Yt.rmSync(t,{force:!0});let a={filePath:i,variableCount:n.length,unsetStatements:s,purged:e};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},ia=y({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:xr.string().describe("Path to the file that must be sourced to apply"),variableCount:xr.number().describe("Number of variables cleared"),unsetStatements:xr.array(xr.string()).describe("Unset statements generated"),purged:xr.boolean().describe("Whether the project warm cache was purged outright")},handler:()=>jn()});import{z as Xt}from"zod";var Dn=async()=>{let e=await Te(),{environments:r}=await b();c.info(`Doppler project: ${e}
160
+ `),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}},aa=y({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:Xt.string().describe("Detected Doppler project name"),configs:Xt.array(Xt.string()).describe("Available environment configs")},handler:Dn});import la from"@inquirer/select";import{Buffer as da}from"node:buffer";import pa from"node:fs";import ma from"node:path";import Fn from"node:process";import{z as Cr}from"zod";import{$ as st}from"zx";var Qt=e=>{if(e===null||typeof e!="object")return;let r=e.stderr;return typeof r=="string"&&r.length>0?r:void 0},ca=(e,r)=>{let t=r.stderrExcerpt??Qt(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(ca(r,t),{cause:r}),this.name="OperationError",this.operation=t.operation,this.remediation=t.remediation}};var ua=e=>e?[`${Ee}=${Oe("1")}`]:[`unset ${Ee}`,`unset ${Ke}`],Ln=({pairs:e,config:r,project:t,projectRoot:o,loadedAt:n,autoLoaded:s})=>["set -a",...e.map(([i,a])=>`${i}=${Oe(a)}`),`${Ur}=${Oe(r)}`,`${Ve}=${Oe(r)}`,`${Je}=${Oe(t)}`,`${zr}=${Oe(o)}`,`${Be}=${Oe(n)}`,...ua(s),"set +a"],fa=async()=>{try{return await k()}catch{return""}},Wn=async({config:e,autoLoaded:r=!1,beforeWrite:t,projectDir:o})=>{await nt();let n=await Te(),s=await fa(),i=await ha(n,e),a=new Date().toISOString(),d=`${Ln({pairs:i,config:e,project:n,projectRoot:s,loadedAt:a,autoLoaded:r}).join(`
161
+ `)}
162
+ `,p=Ue(),m=ma.resolve(p,L);if(t&&!t())return null;pa.mkdirSync(p,{recursive:!0,mode:448}),Se(m,d,384);let h=Ae(s);return zt({autoLoaded:r,projectDir:o,canonicalProjectRoot:h})&&(Gt(o,d),qt()),{filePath:m,variableCount:i.length,project:n,config:e}},Vn=async e=>{let{config:r}=e;u.start("env-load");let t="";if(r)t=r;else{await nt();let{environments:s}=await b();u.setInteractive(),t=await la({message:"Select environment config",choices:s.map(i=>({name:i,value:i}))},{output:Fn.stderr})}u.addOption("--config",t);let o=await Wn({config:t,autoLoaded:!1});if(!o)throw new Error("env-load: write was unexpectedly aborted");Fn.stdout.write(`${o.filePath}
163
+ `),u.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}},Mn=1024*1024,ga=3e4,ha=async(e,r)=>{let t=st.quiet;st.quiet=!0;try{let o;try{o=await st`doppler secrets download --no-file --format json --project ${e} --config ${r}`.timeout(ga)}catch(n){throw await ya(n,e,r)}return va(o.stdout),ka(o.stdout)}finally{st.quiet=t}},ya=async(e,r,t)=>{let o=Qt(e)??(e instanceof Error?e.message:String(e)),n=Vt(o);if(n==="unknown")return e instanceof Error?e:new Error(String(e));let s=n==="project"?await Rr():await Bt(r);return new Error(Jt({kind:n,project:r,config:t,available:s}))},va=e=>{let r=da.byteLength(e,"utf-8");if(r>Mn)throw new Error(`doppler returned unexpectedly large output (${r} bytes > ${Mn}) \u2014 refusing to write to disk`)},Oe=e=>`'${e.replaceAll("'","'\\''")}'`,wa=/^[A-Z_]\w*$/i,ka=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(!wa.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},Ra=y({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:Cr.string().describe('Doppler config / environment name to load (e.g. "dev", "arthur", "renana"). Required for MCP calls.')},outputSchema:{filePath:Cr.string().describe("Path to the file that must be sourced to apply variables"),variableCount:Cr.number().describe("Number of variables loaded"),project:Cr.string().describe("Doppler project name"),config:Cr.string().describe("Doppler config name")},handler:Vn});import ba from"node:path";import Ne from"node:process";import{z as ve}from"zod";var Jn=async()=>{c.info("Environment session status:");let e=Ue(),r=Ne.env[tn],t=ba.join(e,L),o=0,n=0,s=Ne.env[Ve]??null,i=Ne.env[Je]??null,a=Ne.env[Be]??null,l=Ne.env[Ee]==="1",d=!!Ne.env[Ke];if(s){let m=Gr(t);m.length>0&&(n=m.length,o=m.filter(R=>R in Ne.env).length);let h=a?.replace(/\.\d{3}Z$/,"")??null,x=l?"auto-loaded":"manually loaded";if(c.info(` ${s}: ${o} of ${n} vars loaded (${x}, project: ${i}, loadedAt: ${h}, session: ${r})
164
+ `),n>0&&o<n){let R=n-o;c.warn(` ${R} 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 m=d?" (cleared \u2014 auto-load suppressed until a new shell or explicit env-load)":"";c.info(` Session ${r}: no env loaded${m}
165
+ `)}let p={sessionId:r,sessionLoadedCount:o,sessionTotalCount:n,sessionConfig:s,sessionProject:i,sessionLoadedAt:a,autoLoaded:l,cleared:d};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}},xa=y({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:ve.string().describe("Current terminal session ID"),sessionLoadedCount:ve.number().describe("Number of cached vars active in the current session"),sessionTotalCount:ve.number().describe("Total number of cached var names"),sessionConfig:ve.string().nullable().describe("Doppler config name of the loaded session (environment name)"),sessionProject:ve.string().nullable().describe("Doppler project name of the loaded session"),sessionLoadedAt:ve.string().nullable().describe("ISO 8601 timestamp of when the env was loaded"),autoLoaded:ve.boolean().describe("True when the loaded env was applied by env auto-load (not a manual env-load)"),cleared:ve.boolean().describe("True when env-clear is currently suppressing auto-load in this shell")},handler:Jn});import Ca from"node:process";var it={enabled:!1},Pa=(e,r=t=>{Ca.stdout.write(t)})=>(it.enabled&&e&&e.structuredContent!=null&&r(`${JSON.stringify(e.structuredContent,null,2)}
166
+ `),e),Bn=e=>{e.options.some(t=>t.long==="--json")||e.option("--json","Output the structured result as JSON on stdout (human logs stay on stderr)"),e.commands.forEach(Bn)};import{z as or}from"zod";import{$ as z}from"zx";import{$ as Vu}from"zx";import{$ as _}from"zx";import{$ as $r}from"zx";import Pr from"node:process";var eo=async(e,r)=>{if(e.ok)return;let t=await e.text();throw c.error({status:e.status,statusText:e.statusText,error:t},r),new Error(`HTTP ${e.status}: ${e.statusText}`)},ro=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},a=`${t}/rest/api/3/version`,l=btoa(`${n}:${o}`),d=await fetch(a,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${l}`},body:JSON.stringify(i)});return await eo(d,"Failed to create Jira version"),{success:!0,version:await d.json()}}catch(t){throw c.error({error:t},"Error creating Jira version"),t}},Qe=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}`),a=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}});return await eo(a,"Failed to get Jira project versions"),await a.json()}catch(r){throw c.error({error:r},"Error getting Jira project versions"),r}},at=async(e,r)=>{try{return(await Qe(r)).find(n=>n.name===e)||null}catch(t){throw c.error({error:t,versionName:e},"Error finding Jira version by name"),t}},ct=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}`,a=btoa(`${n}:${o}`),l=await fetch(i,{method:"PUT",headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Basic ${a}`},body:JSON.stringify(s)});return await eo(l,"Failed to update Jira version"),{success:!0,version:await l.json()}}catch(t){throw c.error({error:t},"Error updating Jira version"),t}},to=async(e,r)=>{try{let{versionName:t}=e,o=await at(t,r);if(!o)throw c.error({versionName:t},"Jira version not found"),new Error(`Version "${t}" not found in Jira project`);return await ct({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}},er=async()=>{let e=Pr.env.JIRA_BASE_URL,r=Pr.env.JIRA_TOKEN||Pr.env.JIRA_API_TOKEN,t=Pr.env.JIRA_PROJECT_ID,o=Pr.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(a=>` - ${a}`),"","You can set these in your .env file or as environment variables."].join(`
167
+ `);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}},je=async()=>{try{return await er()}catch(e){return c.warn({error:e},"Jira configuration not available, skipping Jira integration"),null}};var Kn="dev",rr=e=>e==="hotfix"?"main":"dev",oo=async(e="regular")=>{let r=rr(e);$r.quiet=!0,await $r`git fetch origin`,await $r`git switch ${r}`,await $r`git pull origin ${r}`,$r.quiet=!1},no=async e=>{let{id:r,jiraConfig:t,description:o,type:n="regular"}=e,s=U(r),i=await ro({name:s,projectId:t.projectId,description:o||"",released:!1,archived:!1},t),a=`${t.baseUrl}/projects/${i.version.projectId}/versions/${i.version.id}/tab/release-report-all-issues`,l=await lt({id:r,jiraVersionUrl:a,type:n,description:o});return{version:S(r),type:n,branchName:l.branchName,prUrl:l.prUrl,jiraVersionUrl:a}},E=async()=>{let e=new Map,r=await je();if(!r)return e;try{let t=await Qe(r);for(let o of t)o.description&&e.set(o.name,o.description)}catch{}return e},Er=(e,r,t)=>{let o=t?" ".repeat(t-e.length+3):" ",n=`[${r}]`.padEnd(11);return`${e}${o}${n}`},C=e=>e.toLowerCase().startsWith("hotfix")?"hotfix":"regular",Un=e=>e.flatMap(r=>{let t=I(r);return t?[{branch:r,id:t,label:S(t)}]:[]}),de=e=>{try{return fe(ie(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")'})}},Sr=e=>{if(e===Kn)return Kn;let r=I(e);return r?S(r):e},De=e=>e.flatMap(r=>{let t=I(r);return t?[S(t)]:[]}),Ea=(e,r)=>r?r.get(e)||"regular":void 0,A=e=>{let{branches:r,descriptions:t,types:o}=e;return Un(r).map(({branch:n,id:s,label:i})=>({value:n,label:i,description:t.get(U(s)),type:Ea(n,o)}))};var Sa=e=>e.map(r=>({pr:r,id:I(r.headRefName)})).filter(r=>r.id!==null).sort((r,t)=>Vo(r.id,t.id,{a:r.pr.createdAt,b:t.pr.createdAt})).map(r=>r.pr),Ta=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))},zn=async()=>{try{let e=await Ta();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 Sa(e)}catch(e){throw e instanceof f?e:(c.error({error:e},"\u274C Error fetching release PRs"),new f(e,{operation:"fetch release PRs"}))}},dt=async()=>(await zn()).map(r=>r.headRefName),P=async()=>(await zn()).map(r=>({branch:r.headRefName,title:r.title,createdAt:r.createdAt})),pt=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}},lt=async e=>{let{id:r,jiraVersionUrl:t,type:o,description:n}=e,s=Wo(r,o),i=rr(o),a=fe(r),l=n&&n.trim()!==""?`${t}
168
+
169
+ ${n}`:`${t}
170
+ `;try{_.quiet=!0,await _`git switch ${i}`,await _`git pull origin ${i}`,await _`git checkout -b ${a}`,await _`git push -u origin ${a}`,await _`git commit --allow-empty-message --allow-empty --message ''`,await _`git push origin ${a}`;let p=(await _`gh pr create --title ${s} --body ${l} --base ${i} --head ${a}`).stdout.trim();return await _`git switch ${i}`,_.quiet=!1,{branchName:a,prUrl:p}}catch(d){throw c.error({error:d,branchName:a},`Error creating release branch ${a}`),d}};var D=async e=>{let{operation:r,requiredBranch:t}=e;if(await Ko())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 Jo();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 Bo())throw new f(void 0,{operation:r,remediation:"commit or stash your changes, then retry",stderrExcerpt:"working tree has uncommitted changes"})};import Ia from"node:process";var Tr=class extends Error{name="PromptCancelledError";constructor(){super("Prompt cancelled")}};var Gn=()=>{if(!Ia.stdin.isTTY||it.enabled)throw new f(void 0,{operation:"interactive branch selection",remediation:"pass the branch selection explicitly (CLI: `--version`/`--versions`/`--all`; MCP: the `version`/`versions`/`all` fields) for non-interactive, --json, or MCP runs"})},we=async e=>{Gn();let{runBranchPicker:r}=await import("./boot-5GFZBDKL.js"),t=await r(e);if(t===null)throw new Tr;return t},tr=async(e,r)=>{Gn();let{runBranchMultiPicker:t}=await import("./boot-5GFZBDKL.js"),o=await t(e,r);if(o===null)throw new Tr;return o};var qn=async e=>{let{all:r,confirmedCommand:t}=e;u.start("merge-dev"),await D({operation:"merge dev into release branches",requiredBranch:"dev"});let n=(await P()).filter(d=>C(d.title)==="regular").map(d=>d.branch);if(n.length===0)return c.info("\u2139\uFE0F No open release branches found"),u.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{u.setInteractive();let d=await E();s=await tr(A({branches:n,descriptions:d}),{required:!0})}s.length===n.length?u.addOption("--all",!0):u.addOption("--versions",De(s)),await N(t,`Are you sure you want to merge dev into these branches: ${s.join(", ")}?`),t||u.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 Aa(d)||a.push(d);if(z.quiet=!1,a.length>0){c.info(`
171
+ \u26A0\uFE0F ${a.length} branch(es) failed to merge automatically.
172
+ `),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
173
+
174
+ git switch ${d} && git pull origin ${d} && git merge origin/dev
175
+ git push origin ${d} && git switch dev
176
+ `);c.info(`\u2705 ${s.length-a.length}/${s.length} merges completed successfully.`)}else c.info(`\u2705 All merges completed successfully!
177
+ `);u.print();let l={successfulMerges:s.length-a.length,failedMerges:a.length,failedBranches:a,totalBranches:s.length};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},Aa=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}},_a=y({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:or.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:or.number().describe("Number of successful merges"),failedMerges:or.number().describe("Number of failed merges"),failedBranches:or.array(or.string()).describe("List of branches that failed to merge"),totalBranches:or.number().describe("Total number of branches processed")},handler:qn});import{z as _r}from"zod";import{$ as F}from"zx";var Hn=(e,r)=>{if(!(typeof e!="string"||e.length===0))return e.slice(-r).trim()},Ir=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=Hn(r.stderr,500);n&&(t.stderr=n);let s=Hn(r.stdout,200);return s&&(t.stdout=s),t};import{$ as Zn}from"zx";var Ar=async e=>{let{branches:r,worktreeDir:t,repoName:o,pruneFolder:n=!1}=e,s=await Promise.allSettled(r.map(async a=>{let l=`${t}/${a}`,d=ae({repoName:o,branch:a});return await ze(d),await Zn`git worktree remove ${l}`,a})),i=[];for(let[a,l]of s.entries())if(l.status==="fulfilled")i.push(l.value);else{let d=r[a],p=new f(l.reason,{operation:`remove worktree for ${d}`,remediation:"check 'git worktree list' for the path; uncommitted changes block removal"});c.error({error:l.reason,msg:p.message})}return n&&i.length===r.length&&await Zn`git worktree prune`,i};var nr=async(e,r,t)=>{try{return await t()}catch(o){throw c.error({err:Ir(o)},`\u274C Failed to ${e}`),new f(o,{operation:e,remediation:r})}},Xn=async e=>{let r=await F`gh pr list --head ${e} --state all --json number,state,title --limit 1`;return JSON.parse(r.stdout)[0]??null},Oa=async e=>{let r=Ct(e),t=await F`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},Yn=async()=>{let e=await F`gh pr list --head dev --base main --state open --json number,state,title --limit 5`;return JSON.parse(e.stdout)[0]??null},Na=async e=>{let r=de(e),t=await Xn(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}},ja=async()=>{let e=await P(),r=e.map(i=>i.branch),t=new Map(e.map(i=>[i.branch,C(i.title)]));u.setInteractive();let o=await E(),n=await we(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}},Da=async e=>{if(!(await M("release")).includes(e))return;let[t,o]=await Promise.all([k(),Y()]),n=`${t}${Q}`;if((await Ar({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)`})},Fa=async e=>{let{selectedReleaseBranch:r,releaseType:t}=e,o=t==="hotfix"?"main":"dev",n=await Xn(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 nr(`merge release PR ${r} into ${o}`,`check 'gh pr view ${r}' for mergeability and required reviews`,async()=>{await F`gh pr merge ${r} --squash --admin --delete-branch`})},Ma=async e=>{let r=S(e),t=Ct(e),o=await Yn();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 nr(`retitle dev \u2192 main PR #${s} to "${t}"`,`update manually: gh pr edit ${s} --title "${t}"`,async()=>{await F`gh pr edit ${s} --title ${t}`})),s}await nr(`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 F`gh pr create --base main --head dev --title ${t} --body ""`});let n=await Yn();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},La=async e=>{let r=S(e);if(await Oa(e)){c.info(`\u2713 RC PR for ${r} already merged into main \u2014 skipping`);return}let o=await Ma(e);await nr(`merge RC PR #${o} (dev \u2192 main) for ${r}`,`check 'gh pr view ${o}' for mergeability and required reviews`,async()=>{await F`gh pr merge ${o} --squash --admin`})},Wa=async()=>{F.quiet=!1,await nr("dispatch deploy-all workflow on main","check 'gh workflow list' and that you have permission to dispatch deploy-all.yml",async()=>{await F`gh workflow run deploy-all.yml --ref main -f environment=prod`}),F.quiet=!0},Va=async()=>{await nr("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 F`git switch main && git pull && git switch dev && git pull && git merge main --no-edit && git push`})},Ja=async e=>{try{await Uo(e)}catch(r){c.warn({err:Ir(r)},`Failed to delete local branch ${e} (non-blocking)`)}try{await zo(e)}catch(r){c.warn({err:Ir(r)},`Failed to delete remote branch ${e} (non-blocking)`)}},Ba=async e=>{let r=await je();if(!r){c.info("\u{1F514} Jira is not configured, skipping Jira release delivery");return}try{let t=U(e);await to({versionName:t},r)}catch(t){c.error({err:Ir(t)},"Failed to deliver Jira release (non-blocking)")}},Qn=async e=>{let{version:r,confirmedCommand:t}=e;u.start("release-deliver"),await D({operation:"deliver release"});let{selectedReleaseBranch:o,releasePrTitle:n}=r?await Na(r):await ja(),s=I(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=S(s);u.addOption("--version",i),c.info(`Delivering ${s.kind==="name"?"named release":"version"} ${o}`);let a=C(n);await N(t,`Are you sure you want to deliver version ${o} to production?`),u.addOption("--yes",!0),F.quiet=!0,await Da(o),await Fa({selectedReleaseBranch:o,releaseType:a}),a!=="hotfix"&&await La(s),await Wa(),await Va(),await Ja(o),F.quiet=!1,await Ba(s),c.info(`Successfully delivered ${o} to production!`),u.print();let l={releaseBranch:o,version:i,type:a,success:!0};return{content:g(JSON.stringify(l,null,2)),structuredContent:l}},Ka=y({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:_r.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:_r.string().describe("The release branch that was delivered"),version:_r.string().describe("The version that was delivered"),type:_r.enum(["regular","hotfix"]).describe("Release type"),success:_r.boolean().describe("Whether the delivery was successful")},handler:Qn});import Ua from"@inquirer/confirm";import za from"@inquirer/select";import{z as ke}from"zod";import{$ as so}from"zx";var Ga=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;u.setInteractive();let n=await Ua({message:`Deploy ${t} \u2192 ${o}?`,default:!1});return n&&u.addOption("--yes",!0),n},es=async e=>{let{version:r,env:t,skipTerraform:o,confirmedCommand:n}=e;u.start("release-deploy-all");let s="";if(r)s=r==="dev"?"dev":de(r);else{u.setInteractive();let p=await P(),m=p.map(R=>R.branch),h=new Map(p.map(R=>[R.branch,C(R.title)])),x=await E();s=await we([{value:"dev",label:"dev"},...A({branches:m,descriptions:x,types:h})])}let i=Sr(s);u.addOption("--version",i);let{environments:a}=await b(),l="";if(t?l=t:(u.setInteractive(),l=await za({message:"\u{1F9EA} Select environment",choices:a.map(p=>({name:p,value:p}))})),u.addOption("--env",l),!a.includes(l))throw new f(void 0,{operation:"launch deploy-all workflow",remediation:`pass one of: ${a.join(", ")}`,stderrExcerpt:`invalid environment: ${l}`});let d=o??!1;if(d&&u.addOption("--skip-terraform",!0),!await Ga({confirmedCommand:n,branch:s,env:l})){c.info("Deployment cancelled");let p={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!1};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}}try{so.quiet=!0,await so`gh workflow run deploy-all.yml --ref ${s} -f environment=${l} ${d?["-f","skip_terraform_deploy=true"]:[]}`,so.quiet=!1,c.info(`Successfully launched deploy-all workflow_dispatch for release branch: ${s} and environment: ${l}`),u.print();let m={releaseBranch:s,version:i,environment:l,skipTerraformDeploy:d,success:!0};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(p){throw c.error({error:p},"\u274C Error launching workflow"),new f(p,{operation:"launch deploy-all workflow",remediation:"check 'gh workflow list' and that deploy-all.yml exists on the target ref"})}},qa=y({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:ke.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:ke.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),skipTerraform:ke.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:ke.string().describe("The release branch that was deployed"),version:ke.string().describe("The version that was deployed"),environment:ke.string().describe("The environment deployed to"),skipTerraformDeploy:ke.boolean().describe("Whether terraform deployment was skipped"),success:ke.boolean().describe("Whether the deployment was successful")},handler:es});import Ha from"@inquirer/checkbox";import Za from"@inquirer/confirm";import Ya from"@inquirer/select";import Xa from"node:fs/promises";import{resolve as Qa}from"node:path";import ec from"yaml";import{z as K}from"zod";import{$ as io}from"zx";var rc=async e=>{let{confirmedCommand:r,branch:t,env:o}=e;if(r)return!0;u.setInteractive();let n=await Za({message:`Deploy ${t} \u2192 ${o}?`,default:!1});return n&&u.addOption("--yes",!0),n},rs=async e=>{let{version:r,env:t,services:o,skipTerraform:n,confirmedCommand:s}=e;u.start("release-deploy-selected");let i="";if(r)i=r==="dev"?"dev":de(r);else{u.setInteractive();let w=await P(),T=w.map(Z=>Z.branch),Le=new Map(w.map(Z=>[Z.branch,C(Z.title)])),H=await E();i=await we([{value:"dev",label:"dev"},...A({branches:T,descriptions:H,types:Le})])}let a=Sr(i);u.addOption("--version",a);let{environments:l}=await b(),d="";if(t?d=t:(u.setInteractive(),d=await Ya({message:"\u{1F9EA} Select environment",choices:l.map(w=>({name:w,value:w}))})),u.addOption("--env",d),!l.includes(d))throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass one of: ${l.join(", ")}`,stderrExcerpt:`invalid environment: ${d}`});let p=await tc();if(p.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:"check .github/workflows/deploy-selected-services.yml for boolean service inputs",stderrExcerpt:"no services found in workflow file"});let m=[];if(o&&o.length>0?m=o:(u.setInteractive(),m=await Ha({message:"\u{1F680} Select services to deploy (space to select, enter to confirm)",choices:p.map(w=>({name:w,value:w}))})),u.addOption("--services",m),m.length===0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass at least one service from: ${p.join(", ")}`,stderrExcerpt:"no services selected"});let h=m.filter(w=>!p.includes(w));if(h.length>0)throw new f(void 0,{operation:"launch deploy-selected workflow",remediation:`pass services from: ${p.join(", ")}`,stderrExcerpt:`invalid services: ${h.join(", ")}`});let x=n??!1;x&&u.addOption("--skip-terraform",!0);let R=w=>{let T={releaseBranch:i,version:a,environment:d,services:m,skipTerraformDeploy:x,success:w};return{content:g(JSON.stringify(T,null,2)),structuredContent:T}};if(!await rc({confirmedCommand:s,branch:i,env:d}))return c.info("Deployment cancelled"),R(!1);try{io.quiet=!0;let w=m.flatMap(Le=>["-f",`${Le}=true`]);return await io`gh workflow run deploy-selected-services.yml --ref ${i} -f environment=${d} ${w} ${x?["-f","skip_terraform_deploy=true"]:[]}`,io.quiet=!1,c.info(`Successfully launched deploy-selected-services workflow_dispatch for release branch: ${i}, environment: ${d}, services: ${m.join(", ")}`),u.print(),R(!0)}catch(w){throw c.error({error:w},"\u274C Error launching workflow"),new f(w,{operation:"launch deploy-selected workflow",remediation:"check 'gh workflow list' and that deploy-selected-services.yml exists on the target ref"})}},tc=async()=>{let e=await k(),r=Qa(e,".github/workflows/deploy-selected-services.yml"),t=await Xa.readFile(r,"utf-8"),n=ec.parse(t).on.workflow_dispatch.inputs,s=[];for(let[i,a]of Object.entries(n))a.type==="boolean"&&i!=="skip_terraform_deploy"&&s.push(i);return s},oc=y({name:"gh-release-deploy-selected",description:'Dispatch the deploy-selected-services.yml GitHub Actions workflow to deploy a chosen subset of services from a release branch to the given environment. Fire-and-forget \u2014 returns once GitHub accepts the workflow_dispatch, NOT when the deployment finishes; watch the workflow run for completion status. Service names are validated against the boolean inputs declared in the workflow. Use gh-release-deploy-all for every service. "version", "env", and "services" are all required when invoked via MCP (interactive pickers are unavailable without a TTY).',inputSchema:{version:K.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign") \u2014 resolves to the release/vX.Y.Z or release/<name> branch. Pass "dev" to deploy from the dev branch instead. Required for MCP calls.'),env:K.string().describe('Target environment name \u2014 must match an env configured for the project (e.g. "dev", "renana", "oriana"). Required for MCP calls.'),services:K.array(K.string()).describe('Service names to deploy. Each must match a boolean input declared in .github/workflows/deploy-selected-services.yml (e.g. "client-be", "client-fe"). Required for MCP calls.'),skipTerraform:K.boolean().optional().describe("Skip the terraform deployment stage.")},outputSchema:{releaseBranch:K.string().describe("The release branch that was deployed"),version:K.string().describe("The version that was deployed"),environment:K.string().describe("The environment deployed to"),services:K.array(K.string()).describe("The services that were deployed"),skipTerraformDeploy:K.boolean().describe("Whether terraform deployment was skipped"),success:K.boolean().describe("Whether the deployment was successful")},handler:rs});import{z as sr}from"zod";var ts=async()=>{let r=(await P()).flatMap(i=>{let a=I(i.branch);return a?[{version:S(a),jiraKey:U(a),type:C(i.title)}]:[]}),t=await E(),o=Math.max(...r.map(i=>i.version.length)),n=r.map(i=>{let a=Er(i.version,i.type,o),l=t.get(i.jiraKey);return l?`${a} ${l}`:a});c.info(`All release branches:
178
+ `),c.info(`
179
+ ${n.join(`
180
+ `)}
181
+ `);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}},nc=y({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:sr.array(sr.object({version:sr.string().describe("Release version"),type:sr.enum(["regular","hotfix"]).describe("Release type"),description:sr.string().nullable().describe("Jira version description")})).describe("List of all release branches"),count:sr.number().describe("Number of release branches")},handler:ts});var Re=e=>e.slice(1).split(".").map(Number),ao=e=>[...e].sort((r,t)=>{let[o,n,s]=Re(r),[i,a,l]=Re(t);return o!==i?(o??0)-(i??0):n!==a?(n??0)-(a??0):(s??0)-(l??0)});var ns="next",sc=/^v?(\d+)\.(\d+)\.(\d+)$/,ic=e=>e.replace(/^.*release\//,""),lo=e=>{let r=ic(e.trim()),t=sc.exec(r);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},os=e=>`${e[0]}.${e[1]}.${e[2]}`,po=e=>{let r=[...e.remoteBranches??[],...e.jiraVersions??[]],t=[],o=new Set;for(let n of r){let s=lo(n);if(!s)continue;let i=os(s);o.has(i)||(o.add(i),t.push(s))}return ao(t.map(n=>os(n))).map(n=>Re(`v${n}`))},Fe=class extends Error{constructor(){super("No prior release versions found from git or Jira. Specify the version explicitly."),this.name="NoPriorVersionsError"}},mt=(e,r)=>{if(e.length===0)throw new Fe;let t=e[e.length-1];if(r==="hotfix"){let[s,i]=t,a=e.reduce((l,d)=>d[0]===s&&d[1]===i?Math.max(l,d[2]):l,0);return`${s}.${i}.${a+1}`}let[o,n]=t;return`${o}.${n+1}.0`},mo=e=>e.trim().toLowerCase()===ns,ac=e=>e==="regular"||e==="hotfix",ss=e=>"name"in e,cc=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 a=r.slice(t+1),l=a.indexOf(":"),d=l===-1?a.trim():a.slice(0,l).trim();s=l===-1?"":a.slice(l+1).trim();let p=d.toLowerCase();if(!ac(p))throw new Error(`Invalid release type "${d}". Expected "regular" or "hotfix".`);n=p}if(mo(o)||lo(o)!==null){let a={version:o,type:n};return s!==""&&(a.description=s),a}let i={name:o,type:n};return s!==""&&(i.description=s),i},uo=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,lc=e=>{let r=e.name.trim();return Vr(r),co({id:{kind:"name",name:r,raw:r},type:e.type},e.description)},fo=(e,r)=>{let t=[...r];return e.map(o=>{if(ss(o))return lc(o);let n=o.version.trim();if(n==="")throw new Error("Release entry has an empty version");if(mo(n)){let a=mt(t,o.type);return t.push(Re(`v${a}`)),co({id:ie(a),type:o.type},o.description)}let s=lo(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:ie(i),type:o.type},o.description)})},go=e=>e.some(r=>!ss(r)&&mo(r.version));import{$ as ut}from"zx";var dc=e=>e.split(`
182
+ `).map(r=>{let t=r.indexOf(" ");return t===-1?null:I(r.slice(t+1))}).filter(r=>r!==null&&r.kind==="version").map(r=>r.raw),pc=async()=>{let e=ut.quiet;try{ut.quiet=!0;let r=await ut`git ls-remote --heads origin 'release/v*'`;return dc(r.stdout)}finally{ut.quiet=e}},mc=async()=>{let e=await je();return e?(await Qe(e)).map(t=>t.name):[]},ho=async()=>{let[e,r]=await Promise.allSettled([pc(),mc()]);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"),po({remoteBranches:e.status==="fulfilled"?e.value:[],jiraVersions:r.status==="fulfilled"?r.value:[]})};import uc from"@inquirer/confirm";import is from"@inquirer/select";import yo from"node:process";import{z as $}from"zod";import{question as wo}from"zx";var fc='"1.2.5" or "next"',gc=(e,r)=>{try{return mt(e,r)}catch(t){if(t instanceof Fe)return null;throw t}},vo=(e,r)=>{try{return fo(e,r)}catch(t){throw t instanceof Fe?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 Lo?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}},hc=async(e,r)=>{let t=gc(e,r),o=t?` [${t}]`:"",n=(await wo(` Version (e.g. ${fc})${o}: `)).trim(),s=n===""?t??"":n;return s===""&&(c.error("No version provided. Exiting..."),yo.exit(1)),s},yc=async()=>{let e=(await wo(' Name (kebab-case, e.g. "checkout-redesign"): ')).trim();e===""&&(c.error("No name provided. Exiting..."),yo.exit(1));try{Vr(e)}catch(r){let t=r instanceof Error?r.message:String(r);c.error(`${t} Exiting...`),yo.exit(1)}return e},vc=async e=>{u.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,a=await is({message:`Release #${i} \u2014 version or name?`,choices:[{name:"version (semver / next)",value:"version"},{name:"name (free-form)",value:"name"}],default:"version"}),l=await is({message:`Release #${i} \u2014 select type:`,choices:[{name:"regular",value:"regular"},{name:"hotfix",value:"hotfix"}],default:"regular"}),d;if(a==="name"){let m=await yc();d=vo([{name:m,type:l}],[])[0]}else{let m=await hc(await o(),l);d=vo([{version:m,type:l}],t)[0],d.id.kind==="version"&&t.push(Re(`v${d.id.raw}`))}let p=(await wo(" Description (optional, press Enter to skip): ")).trim();n.push({...d,...p!==""?{description:p}:{}}),s=await uc({message:"Add another release?",default:!1})}return n},wc=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 ")},as=e=>{for(let r of e)u.addOption("--release",uo(r))},kc=async(e,r)=>{if(e&&e.length>0){let o=go(e)?await r():[],n=vo(e,o);return as(n),n}let t=await vc(r);return as(t),t},Rc=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"})},bc=async(e,r)=>{let t=e.map(wc).join(`
183
+ - `);await N(r,`Create the following ${e.length} release(s)?
184
+ - ${t}
185
+ `),u.addOption("--yes",!0)},xc=async e=>{let{entry:r,jiraConfig:t}=e,o=S(r.id),n=r.id.kind==="version"?`v${r.id.raw}`:r.id.name;try{await oo(r.type);let s=await no({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}
186
+ `),{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}
187
+ `),{failure:{version:o,error:i.message}}}},Cc=(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.`)},cs=async e=>{let{releases:r,confirmedCommand:t}=e;u.start("release-create");let o=await er(),n=null,i=await kc(r,async()=>(n===null&&(n=await ho()),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"});Rc(i),await D({operation:"create release",requiredBranch:rr(i[0].type)}),await bc(i,!!t);let a=[],l=[];for(let p of i){let{result:m,failure:h}=await xc({entry:p,jiraConfig:o});m&&a.push(m),h&&l.push(h)}Cc(i.length,a.length,l.length),u.print();let d={createdBranches:a.map(p=>p.branchName),successCount:a.length,failureCount:l.length,releases:a,failedReleases:l};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}},Pc=y({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:cs});import{z as be}from"zod";import{question as $c}from"zx";var ls=(e,r)=>`${e.baseUrl}/projects/${r.projectId}/versions/${r.id}/tab/release-report-all-issues`,Ec=(e,r)=>r.trim()!==""?`${e}
188
+
189
+ ${r}`:`${e}
190
+ `,Sc=async()=>{let e=await P(),r=e.map(s=>s.branch),t=new Map(e.map(s=>[s.branch,C(s.title)])),o=await E(),n=await we(A({branches:r,descriptions:o,types:t}));return{branch:n,type:t.get(n)||"regular"}},Tc=async e=>{let t=(await P()).find(o=>o.branch===e);if(!t)throw new f(void 0,{operation:`edit description for ${e}`,remediation:`confirm an open PR exists for ${e} ('gh pr list')`});return C(t.title)},Ic=async e=>{let r=e===""?"(no current description)":`current: "${e}"`,o=(await $c(` New description ${r}
191
+ (press Enter to keep current): `)).replace(/\n$/,"");return o===""?e:o},ds=async e=>{let{version:r,description:t,confirmedCommand:o}=e;u.start("release-desc-edit");let n=await er(),s;r?(s=de(r),await Tc(s)):(u.setInteractive(),s=(await Sc()).branch);let i=I(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 a=S(i);u.addOption("--version",a);let l=U(i),d=await at(l,n);if(!d)throw new f(void 0,{operation:`edit description for ${l}`,remediation:`create the Jira fix version "${l}" first or pick a different release`});let p=d.description??"",m;t!==void 0?(m=t,u.addOption("--description",m)):(u.setInteractive(),m=await Ic(p));let h=w=>{let T={version:a,branch:s,jiraVersionUrl:ls(n,d),previousDescription:p,newDescription:m,changed:w};return{content:g(JSON.stringify(T,null,2)),structuredContent:T}};if(m===p)return c.info(`No change \u2014 description for ${l} is already: "${p}"`),u.print(),h(!1);await N(o,`Update description for ${l}?
192
+ from: "${p}"
193
+ to: "${m}"
194
+ `),u.addOption("--yes",!0),await ct({versionId:d.id,description:m},n);let x=ls(n,d),R=Ec(x,m);return await pt({branch:s,body:R}),c.info(`\u2705 Updated description for ${l}`),c.info(`\u{1F517} Jira Version: ${x}`),c.info(`\u{1F517} PR branch: ${s}
195
+ `),u.print(),h(!0)},Ac=y({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:be.string().describe('Accepts a release version (e.g. "1.2.5") OR a release name (e.g. "checkout-redesign").'),description:be.string().describe("New description. Empty string clears the description.")},outputSchema:{version:be.string().describe("Release version"),branch:be.string().describe('Release branch name (e.g. "release/v1.2.5" or "release/checkout-redesign")'),jiraVersionUrl:be.string().describe("Jira fix version URL"),previousDescription:be.string().describe("The description before the update"),newDescription:be.string().describe("The description after the update"),changed:be.boolean().describe("Whether the description actually changed")},handler:ds});import{existsSync as fs}from"node:fs";import gs from"node:path";import Jc from"node:process";import{z as pe}from"zod";import{createHash as _c}from"node:crypto";import{readFileSync as Oc}from"node:fs";var ft=e=>_c("sha256").update(Oc(e)).digest("hex");import{readFileSync as Lc,writeFileSync as Wc}from"node:fs";import yt from"node:path";import{z as re}from"zod";import{readdirSync as Fc}from"node:fs";import ko from"node:path";var G="vendor",Nc=new Set(["node_modules","dist",".turbo",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack"]),jc=new Set([".sync-manifest.json",".eslintcache","log.txt"]),Dc=[".tsbuildinfo"],ps=e=>Nc.has(e),ms=e=>jc.has(e)?!0:Dc.some(r=>e.endsWith(r));var Mc=e=>e.split(ko.sep).join("/"),gt=e=>{let r=[],t=o=>{for(let n of Fc(o,{withFileTypes:!0})){let s=ko.join(o,n.name);if(n.isDirectory()){if(ps(n.name))continue;t(s);continue}ms(n.name)||r.push(Mc(ko.relative(e,s)))}};return t(e),r.sort()};var te=".sync-manifest.json",ht=1,Vc=re.object({schemaVersion:re.number().optional(),source:re.string(),commit:re.string(),syncedAt:re.string(),fileCount:re.number(),files:re.record(re.string(),re.string())}),Ro=e=>(e.schemaVersion??ht)>ht,us=e=>{let r={};for(let t of gt(e))try{r[t]=ft(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},bo=e=>{let r=yt.join(e,te),t;try{t=Lc(r,"utf8")}catch{throw new Error(`Missing ${te} at ${r}`)}let o=Vc.safeParse(JSON.parse(t));if(!o.success)throw new Error(`Invalid ${te} at ${r}: ${re.prettifyError(o.error)}`);return o.data},xo=(e,r)=>{let t=us(e),o={schemaVersion:ht,source:r.source,commit:r.commit,syncedAt:new Date().toISOString(),fileCount:Object.keys(t).length,files:t};return Wc(yt.join(e,te),`${JSON.stringify(o,null,2)}
196
+ `),o},Co=(e,r)=>{let t=r.files,o=gt(e),n=[],s=[];for(let l of o){if(!(l in t)){s.push(l);continue}ft(yt.join(e,l))!==t[l]&&n.push(l)}let i=new Set(o),a=Object.keys(t).filter(l=>!i.has(l));return{modified:n,added:s,removed:a}};var Po=30,$o=(e,r)=>{if(r.length!==0){c.info(`
197
+ ${e} (${r.length}):`);for(let t of r.slice(0,Po))c.info(` ${t}`);r.length>Po&&c.info(` \u2026and ${r.length-Po} more`)}},hs=async(e={})=>{let r=e.cwd??await k(),t=gs.join(r,G),o={modified:[],added:[],removed:[],fileCount:0};if(!fs(t)){c.info(`\u2139\uFE0F No ${G}/ folder found \u2014 nothing to check.`);let p={status:"skipped",ok:!0,...o};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}}if(!fs(gs.join(t,te))){c.error(`\u274C Missing ${G}/${te}. Re-run the vendor sync to generate it.`);let p={status:"missing-manifest",ok:!1,...o};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}}let n=bo(t);if(Ro(n)){c.error(`\u274C ${G}/${te} has a newer schemaVersion (${String(n.schemaVersion)}) than this CLI supports. Upgrade infra-kit.`);let p={status:"unknown-schema",ok:!1,...o};return{content:g(JSON.stringify(p,null,2)),structuredContent:p}}let{modified:s,added:i,removed:a}=Co(t,n),l=s.length>0||i.length>0||a.length>0;l?(c.error(`\u274C ${G}/ has drifted from ${G}/${te}.`),c.error(" These files are mirrored from the source repo \u2014 edit them upstream, not here."),$o("Modified",s),$o("Added (not in manifest)",i),$o("Removed (in manifest, now missing)",a)):c.info(`\u2705 ${G}/ matches manifest (${n.fileCount} files).`);let d={status:l?"drift":"clean",ok:!l,fileCount:n.fileCount,modified:s,added:i,removed:a};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}},Bc={status:pe.enum(["clean","drift","skipped","missing-manifest","unknown-schema"]),ok:pe.boolean().describe("Whether the vendor tree matches its manifest (false \u2192 CI should fail)"),fileCount:pe.number(),modified:pe.array(pe.string()),added:pe.array(pe.string()),removed:pe.array(pe.string())},Kc=y({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:Bc,handler:()=>hs({cwd:Jc.cwd()})});import{z as ne}from"zod";import Uc from"node:fs/promises";import zc from"node:path";import{pathToFileURL as Gc}from"node:url";import{z as qc}from"zod";var vt=async e=>{let r=zc.join(e,dr),t;try{t=await Uc.stat(r)}catch{throw new Error(`${dr} not found at ${r}`)}let s=(await import(`${Gc(r).href}?mtime=${Number(t.mtimeMs)}`)).default;if(s===void 0)throw new Error(`${dr} at ${r} has no default export`);let i=typeof s=="function"?await s():s,a=nn.safeParse(i);if(!a.success)throw new Error(`Invalid ${dr} at ${r}: ${qc.prettifyError(a.error)}`);return a.data};import{existsSync as oe,mkdirSync as Hc,writeFileSync as Zc}from"node:fs";import q from"node:path";import{$ as Or}from"zx";var Yc=["node_modules","dist","*.tsbuildinfo",".turbo",".eslintcache",".omc","__screenshots__",".vitest-attachments",".output",".source",".nitro",".tanstack","log.txt"],Xc=`# vendor/ \u2014 mirrored from the source repo
198
+
199
+ **DO NOT EDIT files in this folder here.**
200
+
201
+ Everything under \`vendor/\` is the single source of truth maintained in the source
202
+ repo and copied into this repo by \`infra-kit vendor sync\`. Local edits are
203
+ overwritten on the next sync and will fail \`infra-kit vendor check\` in CI.
204
+
205
+ To change a vendored package, edit it in the source repo and re-run the sync.
206
+
207
+ See \`.sync-manifest.json\` for the source commit and per-file checksums.
208
+ `,vs=()=>Yc.map(e=>`--exclude=${e}`),wt=async e=>{try{return(await Or({cwd:e})`git rev-parse HEAD`).stdout.trim()}catch{return"unknown"}},Qc=async(e,r)=>{if(!oe(e))return!1;oe(r)&&await Or`rm -rf ${r}`;let t=`${e}/`,o=`${r}/`;return await Or`rsync -a ${vs()} ${t} ${o}`,!0},el=async(e,r)=>{if(!oe(e))return!1;let t=q.dirname(r);return oe(t)||Hc(t,{recursive:!0}),await Or`cp ${e} ${r}`,!0},rl=async(e,r)=>{if(!oe(e))return[];if(!oe(r))return[`missing target: ${r}`];let t=`${e}/`,o=`${r}/`;return(await Or`rsync -ai --dry-run --delete ${vs()} ${t} ${o}`).stdout.split(`
209
+ `).map(s=>s.trim()).filter(Boolean)},ws=(e,r)=>{let t=q.join(e,G);oe(t)&&(Zc(q.join(t,"README.md"),Xc),xo(t,r))},Eo=(e,r)=>q.join(wn(e),r),ir=(e,r)=>r?e.filter(t=>r.includes(t)):e,ys=(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}`})},ks=async(e,r,t,o,n)=>{let s=[];for(let i of o){let a=Eo(t,i);if(!oe(a)){s.push({repo:i,copied:0,total:e.copy.length,skipped:!0});continue}let l=0;for(let d of e.copy){let p=q.join(r,d.source),m=q.join(a,d.target);ys(r,p,"source",d.source,d.name),ys(a,m,"target",d.target,d.name),(d.type==="directory"?await Qc(p,m):await el(p,m))&&l++}ws(a,n),s.push({repo:i,copied:l,total:e.copy.length,skipped:!1})}return{source:n.source,commit:n.commit,repos:s}},Rs=async(e,r,t)=>{let o=[];for(let n of r){let s=Eo(e,n),i=!oe(s);i||ws(s,t),o.push({repo:n,skipped:i})}return o},bs=async(e,r,t,o)=>{let n=[],s=e.copy.filter(i=>i.vendored===!0);for(let i of o){let a=Eo(t,i);if(oe(a))for(let l of s){let d=q.join(r,l.source),p=q.join(a,l.target),m=await rl(d,p);m.length>0&&n.push({repo:i,target:l.target,changes:m})}}return n};var So=20,xs=async(e={})=>{let r=e.cwd??await k(),t=await vt(r),o=await Ze(),n=ir(o.targets,e.repos),s=await bs(t,r,o.workspaceDir,n);if(s.length===0)c.info("\u{1F389} No drift detected.");else for(let a of s){c.info(`\u274C ${a.repo} \u2192 ${a.target} (${a.changes.length} change(s)):`);for(let l of a.changes.slice(0,So))c.info(` ${l}`);a.changes.length>So&&c.info(` \u2026and ${a.changes.length-So} more`)}let i={ok:s.length===0,drifted:s.length,entries:s};return{content:g(JSON.stringify(i,null,2)),structuredContent:i}},tl={ok:ne.boolean().describe("Whether every target is in sync with the source"),drifted:ne.number(),entries:ne.array(ne.object({repo:ne.string(),target:ne.string(),changes:ne.array(ne.string())}))},ol=y({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:ne.array(ne.string()).optional().describe("Restrict to these target repo names")},outputSchema:tl,handler:e=>xs({repos:e.repos})});import nl from"node:path";import{z as xe}from"zod";var Cs=async e=>{let r=e.cwd??await k(),t=await Ze(),o=ir(t.targets,e.repos),n=await wt(r),s=nl.basename(r),i=await Rs(t.workspaceDir,o,{source:s,commit:n});for(let l of i)c.info(l.skipped?`\u26A0\uFE0F ${l.repo}: target does not exist \u2014 skipped`:`\u{1F4DD} ${l.repo}: manifest written`);let a={source:s,commit:n,repos:i};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},sl={source:xe.string(),commit:xe.string(),repos:xe.array(xe.object({repo:xe.string(),skipped:xe.boolean()}))},il=y({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:xe.array(xe.string()).optional().describe("Restrict to these target repo names")},outputSchema:sl,handler:e=>Cs({repos:e.repos,confirmedCommand:e.confirmedCommand})});import al from"@inquirer/confirm";import Ps from"node:path";import $s from"node:process";import{z as se}from"zod";var Es=async e=>{let r=e.cwd??await k(),t=await vt(r),o=await Ze(),n=ir(o.targets,e.repos);e.confirmedCommand||await al({message:`Sync vendor files from ${Ps.basename(r)} into ${n.length} repo(s)?`},{output:$s.stderr})||$s.exit(0);let s=await wt(r),i=Ps.basename(r),a=await ks(t,r,o.workspaceDir,n,{source:i,commit:s});for(let l of a.repos)l.skipped?c.info(`\u26A0\uFE0F ${l.repo}: target does not exist \u2014 skipped`):c.info(`\u2705 ${l.repo}: copied ${l.copied}/${l.total} items + manifest`);return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},cl={source:se.string(),commit:se.string(),repos:se.array(se.object({repo:se.string(),copied:se.number(),total:se.number(),skipped:se.boolean()}))},ll=y({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:se.array(se.string()).optional().describe("Restrict to these target repo names")},outputSchema:cl,handler:e=>Es({repos:e.repos,confirmedCommand:e.confirmedCommand})});import{z as dl}from"zod";var Ss=async()=>{let e=Br.version;c.info(e);let r={version:e};return{content:g(JSON.stringify(r,null,2)),structuredContent:r}},pl=y({name:"version",description:"Print the installed infra-kit CLI version",inputSchema:{},outputSchema:{version:dl.string().describe("Installed infra-kit CLI version (from package.json)")},handler:Ss});var kt=["workspace","none"];import Ts from"node:fs/promises";import Rt from"node:path";var Nr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=Rt.dirname(r),n;try{n=await Ts.readFile(r,"utf-8")}catch(p){throw new Error(`Cursor workspace file not found at ${r}: ${p.message}`)}let s;try{s=JSON.parse(n)}catch(p){throw new Error(`Failed to parse ${r} as JSON. Comments (JSONC) are not supported. ${p.message}`)}let i=s.folders??[],a=new Set(i.map(p=>Rt.resolve(o,p.path))),l=[],d=[];for(let p of t){let m=Rt.resolve(p);if(a.has(m)){d.push(p);continue}let h=Rt.relative(o,m);i.push({path:h}),a.add(m),l.push(p)}return s.folders=i,await Ts.writeFile(r,`${JSON.stringify(s,null,2)}
210
+ `,"utf-8"),{added:l,skipped:d}};import{$ as ml}from"zx";var jr=async e=>{await ml`cursor ${e}`};import ul from"node:fs/promises";import xt from"node:path";import Is from"node:fs/promises";import bt from"node:path";var Dr=async e=>{let{workspacePath:r,folderPaths:t}=e,o=bt.dirname(r),n;try{n=await Is.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??[],a=new Set(t.map(h=>bt.resolve(h))),l=new Set,d=i.filter(h=>{let x=bt.resolve(o,h.path);return a.has(x)?(l.add(x),!1):!0});s.folders=d,await Is.writeFile(r,`${JSON.stringify(s,null,2)}
211
+ `,"utf-8");let p=[],m=[];for(let h of t){let x=bt.resolve(h);l.has(x)?p.push(h):m.push(h)}return{removed:p,notFound:m}};var To=async e=>{let{workspacePath:r,worktreeDir:t,currentBranches:o}=e,n=xt.dirname(r),s=xt.resolve(`${t}/release`),i=await ul.readFile(r,"utf-8"),l=JSON.parse(i).folders??[],d=new Set(o.map(R=>xt.resolve(`${t}/${R}`))),p=[];for(let R of l){let w=xt.resolve(n,R.path);(w===s||w.startsWith(`${s}/`))&&!d.has(w)&&p.push(w)}let m=[];p.length>0&&(m=(await Dr({workspacePath:r,folderPaths:p})).removed);let h=o.map(R=>`${t}/${R}`),{added:x}=h.length>0?await Nr({workspacePath:r,folderPaths:h}):{added:[]};return{added:x,removed:m}};import As from"node:path";var Me=(e,r)=>As.isAbsolute(e)?e:As.resolve(r,e);var Io=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=Me(n.workspaceConfigPath,r);try{let{added:i,removed:a}=await To({workspacePath:s,worktreeDir:t,currentBranches:o});return o.length>0&&await jr(s),{ran:!0,added:i.length,removed:a.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 fl}from"zx";var Ao=async e=>{let{folderPaths:r}=e;for(let t of r)await fl`zed --add ${t}`;return{added:r}};import{$ as gl}from"zx";var _o=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 gl`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 hl}from"zx";var Oo=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o}=e,n=[r,...o.map(s=>`${t}/${s}`)];try{return await hl`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 me=e=>{throw new Error(`Unexpected value: ${JSON.stringify(e)}`)};var No=async e=>{let{projectRoot:r,worktreeDir:t,branches:o}=e,n=await b(),s=X(n),i=o.map(l=>`${t}/${l}`),a=[];for(let l of s)switch(l.provider){case"cursor":{if(!l.config.workspaceConfigPath){c.warn("\u26A0\uFE0F Skipping Cursor: ide.config.workspaceConfigPath is not set in infra-kit config"),a.push({ran:!1,provider:"cursor",added:0,skipped:0});break}let d=Me(l.config.workspaceConfigPath,r),{added:p,skipped:m}=await Nr({workspacePath:d,folderPaths:i}),h=m.length>0?` (${m.length} already present)`:"";c.info(`\u2705 Added ${p.length} folder(s) to ${d}${h}`),await jr(d),a.push({ran:!0,provider:"cursor",added:p.length,skipped:m.length});break}case"zed":{let{added:d}=await Ao({folderPaths:i});c.info(`\u2705 Added ${d.length} folder(s) to Zed workspace`),a.push({ran:!0,provider:"zed",added:d.length,skipped:0});break}default:me(l)}return a};var jo=async e=>{let r=await b(),t=X(r),o=[];for(let n of t)switch(n.provider){case"cursor":{let s=await Io({...e,cursorConfig:n.config});o.push({...s,provider:"cursor"});break}case"zed":{let s=await _o(e);o.push({...s,provider:"zed"});break}default:me(n)}return o};var Do=e=>{switch(e){case"cursor":return"Cursor";case"zed":return"Zed";case void 0:return"IDE";default:return me(e)}};var Fr=async e=>{let{projectRoot:r,worktreeDir:t,currentWorktrees:o,removedWorktrees:n,allowEditorRelaunch:s}=e;if(n.length===0)return[];let i=await b(),a=X(i),l=n.map(m=>`${t}/${m}`),d=o.filter(m=>!n.includes(m)),p=[];for(let m of a)switch(m.provider){case"cursor":{p.push(await yl({ide:m,projectRoot:r,folderPaths:l}));break}case"zed":{p.push(await vl({projectRoot:r,worktreeDir:t,remainingBranches:d,allowEditorRelaunch:s}));break}default:me(m)}return p},yl=async e=>{let{ide:r,projectRoot:t,folderPaths:o}=e;if(!r.config.workspaceConfigPath)return{provider:"cursor",supported:!0,removed:[]};let n=Me(r.config.workspaceConfigPath,t);try{let{removed:s}=await Dr({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:[]}}},vl=async e=>{let{projectRoot:r,worktreeDir:t,remainingBranches:o,allowEditorRelaunch:n}=e;return n?(await Oo({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:[]})};import _s from"@inquirer/confirm";import{z as ue}from"zod";import{$ as Mr}from"zx";var wl="feature",kl="release",Ns=async e=>{let{confirmedCommand:r,all:t,versions:o,githubDesktop:n,cmux:s}=e,i=e.ide??e.cursor;u.start("worktrees-add"),await D({operation:"create worktrees",requiredBranch:"dev"});try{let a=await M("release"),l=await k(),d=`${l}${Q}`;await Os(`${d}/${kl}`),await Os(`${d}/${wl}`);let p=[];if(o)p=o.split(",").map(H=>fe(ie(H.trim())));else{let H=await P(),Z=H.map(We=>We.branch);if(Z.length===0)return c.info("\u2139\uFE0F No open release branches found"),u.print(),{content:g(JSON.stringify({createdWorktrees:[],count:0},null,2)),structuredContent:{createdWorktrees:[],count:0}};if(t)p=Z;else{u.setInteractive();let We=new Map(H.map(Mo=>[Mo.branch,C(Mo.title)])),Wr=await E();p=await tr(A({branches:Z,descriptions:Wr,types:We}),{required:!0})}}t?u.addOption("--all",!0):u.addOption("--versions",De(p)),await N(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let m=await b(),h=i??(X(m).length>0?"workspace":"none");u.addOption("--ide",h);let x=n??m.worktrees?.openInGithubDesktop??await _s({message:"Open created worktrees in GitHub Desktop?"});typeof n>"u"&&m.worktrees?.openInGithubDesktop===void 0&&u.setInteractive(),x?u.addOption("--github-desktop",!0):u.addOption("--no-github-desktop",!0);let R=s??m.worktrees?.openInCmux??await _s({message:"Open created worktrees in cmux?"});typeof s>"u"&&m.worktrees?.openInCmux===void 0&&u.setInteractive(),R?u.addOption("--cmux",!0):u.addOption("--no-cmux",!0);let{branchesToCreate:w}=Rl({selectedReleaseBranches:p,currentWorktrees:a}),T=await bl(w,d);if(xl(T),h==="workspace"&&await No({projectRoot:l,worktreeDir:d,branches:T}),x)for(let H of T)await Mr`github ${d}/${H}`,await Mr`sleep 5`;if(R){let H=await Y(),Z=await Hr();for(let We of T){let Wr=ae({repoName:H,branch:We});Z.has(qr(Wr))||await Zr({cwd:`${d}/${We}`,title:Wr})}}u.print();let Le={createdWorktrees:T,count:T.length};return{content:g(JSON.stringify(Le,null,2)),structuredContent:Le}}catch(a){throw Ge(a)?a:(c.error({error:a},"\u274C Error managing worktrees"),new f(a,{operation:"create worktrees",remediation:"verify branches don't already exist as worktrees: 'git worktree list'"}))}},Os=async e=>{await Mr`mkdir -p ${e}`},Rl=e=>{let{selectedReleaseBranches:r,currentWorktrees:t}=e,o=t.filter(s=>Jr(s));return{branchesToCreate:r.filter(s=>!o.includes(s))}},bl=async(e,r)=>{let t=await Promise.allSettled(e.map(async n=>{let s=`${r}/${n}`;return await Mr`git worktree add ${s} ${n}`,await Mr({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],a=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:a.message})}return o},xl=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")},Cl=y({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:ue.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:ue.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:ue.enum(kt).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:ue.enum(kt).optional().describe('Deprecated alias for "ide". Prefer "ide". Ignored when "ide" is provided.'),githubDesktop:ue.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:ue.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:ue.array(ue.string()).describe("List of created git worktree branches"),count:ue.number().describe("Number of git worktrees created")},handler:Ns});import{z as ar}from"zod";var js=async()=>{let e=await M("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([P(),E()]),o=new Map(r.map(l=>[l.branch,C(l.title)])),n=e.flatMap(l=>{let d=I(l);if(!d)return[];let p=S(d),m=o.get(l)||"regular",h=t.get(U(d))||null;return[{version:p,type:m,description:h}]}),s=Math.max(...n.map(l=>l.version.length)),i=n.map(l=>{let d=Er(l.version,l.type,s);return l.description?`${d} ${l.description}`:d});c.info("\u{1F33F} Active worktrees:"),c.info(`
212
+ ${i.join(`
213
+ `)}
214
+ `);let a={worktrees:n,count:n.length};return{content:g(JSON.stringify(a,null,2)),structuredContent:a}},Pl=y({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:ar.array(ar.object({version:ar.string().describe("Release version"),type:ar.enum(["regular","hotfix"]).describe("Release type"),description:ar.string().nullable().describe("Jira version description")})).describe("List of all worktrees with details"),count:ar.number().describe("Number of worktrees")},handler:js});import{z as Ce}from"zod";var Ds=async()=>{u.start("worktrees-reload");try{let e=await k(),r=`${e}${Q}`,t=await M("release"),o=await Y(),n=await $l({currentBranches:t,repoName:o}),[s,{opened:i}]=await Promise.all([jo({projectRoot:e,worktreeDir:r,currentBranches:t}),El({worktreeDir:r,currentBranches:t,repoName:o})]),a={closedCmux:n,openedCmux:i,ideProviders:s.filter(l=>l.ran).map(l=>l.provider),ideFoldersAdded:s.reduce((l,d)=>l+d.added,0),ideFoldersRemoved:s.reduce((l,d)=>l+d.removed,0)};return Sl(a,{ideRan:s.some(l=>l.ran)}),u.print(),{content:g(JSON.stringify(a,null,2)),structuredContent:{...a}}}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"})}},$l=async e=>{let{currentBranches:r,repoName:t}=e;if(r.length===0)return[];let o=await Hr(),n=[];for(let s of r){let i=ae({repoName:t,branch:s});o.has(qr(i))&&(await ze(i),n.push(i))}return n},El=async e=>{let{worktreeDir:r,currentBranches:t,repoName:o}=e,n=[];for(let s of t){let i=ae({repoName:o,branch:s});try{await Zr({cwd:`${r}/${s}`,title:i}),n.push(i)}catch(a){c.warn({error:a,title:i},`\u26A0\uFE0F Failed to reopen cmux workspace for ${s}`)}}return{opened:n}},Sl=(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=>Do(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")},Tl=y({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:Ce.array(Ce.string()).describe("Titles of cmux workspaces a close was attempted for (best-effort)"),openedCmux:Ce.array(Ce.string()).describe("Titles of cmux workspaces reopened during this run"),ideProviders:Ce.array(Ce.string()).describe("Configured IDE providers that were reloaded (cursor | zed); empty if none configured"),ideFoldersAdded:Ce.number().describe("Total worktree folders added across all configured editor workspaces"),ideFoldersRemoved:Ce.number().describe("Total dangling worktree folders removed across all configured editor workspaces")},handler:Ds});import{z as Lr}from"zod";var Fs=async e=>{let{confirmedCommand:r,all:t,versions:o}=e;u.start("worktrees-remove"),await D({operation:"remove worktrees",requiredBranch:"dev"});try{let n=await M("release");if(n.length===0)return c.info("\u2139\uFE0F No active worktrees to remove"),u.print(),{content:g(JSON.stringify({removedWorktrees:[],count:0},null,2)),structuredContent:{removedWorktrees:[],count:0}};let s=await k(),i=`${s}${Q}`,a=[];if(t)a=n;else if(o)a=o.split(",").map(h=>fe(ie(h.trim())));else{u.setInteractive();let[h,x]=await Promise.all([E(),P()]),R=new Map(x.map(w=>[w.branch,C(w.title)]));a=await tr(A({branches:n,descriptions:h,types:R}),{required:!0})}let l=a.length===n.length;l?u.addOption("--all",!0):u.addOption("--versions",De(a)),await N(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let d=await Y(),p=await Ar({branches:a,worktreeDir:i,repoName:d,pruneFolder:l});await Fr({projectRoot:s,worktreeDir:i,currentWorktrees:n,removedWorktrees:p,allowEditorRelaunch:!r}),Il(p),u.print();let m={removedWorktrees:p,count:p.length};return{content:g(JSON.stringify(m,null,2)),structuredContent:m}}catch(n){throw Ge(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"}))}},Il=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")},Al=y({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:Lr.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:Lr.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:Lr.array(Lr.string()).describe("List of removed git worktree branches"),count:Lr.number().describe("Number of git worktrees removed")},handler:Fs});import{z as Fo}from"zod";import{$ as _l}from"zx";var Ms=async e=>{let{confirmedCommand:r}=e;u.start("worktrees-sync"),await D({operation:"sync worktrees",requiredBranch:"dev"});try{let t=await M("release"),o=await k(),n=`${o}${Q}`,s=await dt();await N(r,"Are you sure you want to proceed with these worktree changes?"),r||u.addOption("--yes",!0);let{branchesToRemove:i}=Ol({releasePRsList:s,currentWorktrees:t}),a=await Y(),l=await Nl({branches:i,worktreeDir:n,repoName:a});await Fr({projectRoot:o,worktreeDir:n,currentWorktrees:t,removedWorktrees:l,allowEditorRelaunch:!1}),jl(l),u.print();let d={removedWorktrees:l,count:l.length};return{content:g(JSON.stringify(d,null,2)),structuredContent:d}}catch(t){throw Ge(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"}))}},Ol=e=>{let{releasePRsList:r,currentWorktrees:t}=e;return{branchesToRemove:t.filter(s=>Jr(s)).filter(s=>!r.includes(s))}},Nl=async e=>{let{branches:r,worktreeDir:t,repoName:o}=e,n=[];for(let s of r)try{let i=`${t}/${s}`,a=ae({repoName:o,branch:s});await ze(a),await _l`git worktree remove ${i}`,n.push(s)}catch(i){let a=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:a.message})}return n},jl=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")},Dl=y({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:Fo.array(Fo.string()).describe("List of removed worktree branches"),count:Fo.number().describe("Number of worktrees removed during sync")},handler:Ms});export{dn as a,ci as b,V as c,v as d,et as e,rt as f,gi as g,Wt as h,wn as i,Ze as j,em as k,Kt as l,Ut as m,On as n,ta as o,jn as p,ia as q,Dn as r,aa as s,Wn as t,Vn as u,Ra as v,Jn as w,xa as x,it as y,Pa as z,Bn as A,qn as B,_a as C,Qn as D,Ka as E,es as F,qa as G,rs as H,oc as I,ts as J,nc as K,cc as L,cs as M,Pc as N,ds as O,Ac as P,hs as Q,Kc as R,xs as S,ol as T,Cs as U,il as V,Es as W,ll as X,Ss as Y,pl as Z,kt as _,Ns as $,Cl as aa,js as ba,Pl as ca,Ds as da,Tl as ea,Fs as fa,Al as ga,Ms as ha,Dl as ia};
215
+ //# sourceMappingURL=chunk-LENH44GY.js.map