infra-kit 0.1.133 → 0.3.0

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