@buddysh/buddy 0.11.4 → 0.11.6

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 (163) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/bin/cli.js +19 -19
  3. package/dist/chunk-042211k4.js +2 -0
  4. package/dist/chunk-04sy4xt9.js +2 -0
  5. package/dist/chunk-0j7rmr49.js +2 -0
  6. package/dist/{chunk-yp1tgdh3.js → chunk-0t8q4880.js} +1 -1
  7. package/dist/{chunk-hsa07n7c.js → chunk-0xxqw1h6.js} +1 -1
  8. package/dist/{chunk-zgkrhymn.js → chunk-1p9hgr6z.js} +1 -1
  9. package/dist/{chunk-8hjvthz4.js → chunk-1zv0s60b.js} +2 -2
  10. package/dist/{chunk-ngh4jbgp.js → chunk-1zz8bd1c.js} +2 -2
  11. package/dist/chunk-217bhn06.js +2 -0
  12. package/dist/{chunk-428c5652.js → chunk-27jza51d.js} +1 -1
  13. package/dist/chunk-2k4gkkc6.js +2 -0
  14. package/dist/chunk-2kkwhrfz.js +2 -0
  15. package/dist/{chunk-f53y8ans.js → chunk-2r5s586j.js} +2 -2
  16. package/dist/{chunk-yr8eta7p.js → chunk-2vmaeyh3.js} +8 -8
  17. package/dist/{chunk-hd5j9e3c.js → chunk-3f34dgnn.js} +1 -1
  18. package/dist/{chunk-jnb80k2x.js → chunk-3k62kevg.js} +1 -1
  19. package/dist/{chunk-5av2vnvv.js → chunk-3nygvd78.js} +2 -2
  20. package/dist/{chunk-96ht6hwd.js → chunk-43p5vzvb.js} +2 -2
  21. package/dist/{chunk-p6qbqsyp.js → chunk-47ancrn1.js} +2 -2
  22. package/dist/{chunk-bmnx3s41.js → chunk-4m1vgh1w.js} +9 -9
  23. package/dist/{chunk-q4t568hv.js → chunk-4sqwtry6.js} +1 -1
  24. package/dist/{chunk-qd2s51gc.js → chunk-56q8k98m.js} +1 -1
  25. package/dist/{chunk-rayxmbcx.js → chunk-5bedx7s3.js} +1 -1
  26. package/dist/{chunk-pkr6905p.js → chunk-5qssa20j.js} +1 -1
  27. package/dist/{chunk-kprtsn8c.js → chunk-6qb96bg0.js} +1 -1
  28. package/dist/{chunk-ds4stft2.js → chunk-7g13yp3v.js} +1 -1
  29. package/dist/{chunk-c3es7pgf.js → chunk-86kymmen.js} +1 -1
  30. package/dist/{chunk-5044y9en.js → chunk-88k998tw.js} +2 -2
  31. package/dist/{chunk-11hdrnf6.js → chunk-8dq3gews.js} +2 -2
  32. package/dist/{chunk-phfmnnne.js → chunk-8mrbvnae.js} +2 -2
  33. package/dist/chunk-90x7e4ra.js +106 -0
  34. package/dist/{chunk-61xecp1z.js → chunk-95je030a.js} +1 -1
  35. package/dist/{chunk-05me15qw.js → chunk-9cnq8y3d.js} +1 -1
  36. package/dist/chunk-9ychha5r.js +2 -0
  37. package/dist/{chunk-3901s7h9.js → chunk-abfyz98y.js} +1 -1
  38. package/dist/{chunk-jtxcr5yw.js → chunk-ak9s0vnr.js} +2 -2
  39. package/dist/chunk-az2vad31.js +2 -0
  40. package/dist/{chunk-e68nf7cm.js → chunk-b4a5gw9c.js} +1 -1
  41. package/dist/chunk-ba1t70ph.js +2 -0
  42. package/dist/{chunk-sw2538r0.js → chunk-bjg4gxs4.js} +2 -2
  43. package/dist/{chunk-hfjywbbc.js → chunk-bprmzg0p.js} +1 -1
  44. package/dist/{chunk-rc2mk5x6.js → chunk-bxdbf2kj.js} +1 -1
  45. package/dist/{chunk-mkzmjg3f.js → chunk-c64qrkpz.js} +2 -2
  46. package/dist/{chunk-yngahb11.js → chunk-d1yhv10h.js} +2 -2
  47. package/dist/{chunk-0hc97k0t.js → chunk-d73ympxb.js} +3 -3
  48. package/dist/{chunk-g30dr44w.js → chunk-d7e6tqmr.js} +2 -2
  49. package/dist/{chunk-aa277p5r.js → chunk-d84k4mek.js} +1 -1
  50. package/dist/chunk-dbawp9kg.js +2 -0
  51. package/dist/{chunk-m4p7cnvk.js → chunk-df75rm51.js} +1 -1
  52. package/dist/chunk-dh9dw57m.js +2 -0
  53. package/dist/chunk-dkhvqxrk.js +2 -0
  54. package/dist/{chunk-cwfkm7h9.js → chunk-e1cvrjf0.js} +2 -2
  55. package/dist/{chunk-2et8yavs.js → chunk-e3wax332.js} +1 -1
  56. package/dist/{chunk-vqa6vte3.js → chunk-e4bcngja.js} +1 -1
  57. package/dist/{chunk-tjc2vgwn.js → chunk-e6wny1pp.js} +1 -1
  58. package/dist/chunk-ecs7b2kg.js +2 -0
  59. package/dist/chunk-edgg7wxb.js +2 -0
  60. package/dist/{chunk-cs066zt9.js → chunk-ej7gpg23.js} +2 -2
  61. package/dist/{chunk-patms7t8.js → chunk-erbqszzp.js} +1 -1
  62. package/dist/{chunk-cgvt98pd.js → chunk-f7aw9cr3.js} +1 -1
  63. package/dist/{chunk-08x5b93v.js → chunk-ffb50kwa.js} +1 -1
  64. package/dist/{chunk-r763e19p.js → chunk-ffp0mgf5.js} +3 -3
  65. package/dist/{chunk-b1w41hfs.js → chunk-ge2r1zmq.js} +1 -1
  66. package/dist/chunk-h82t0mnh.js +2 -0
  67. package/dist/{chunk-g24hav8e.js → chunk-j3bzf5m0.js} +7 -7
  68. package/dist/{chunk-be629jhq.js → chunk-j8era2yj.js} +2 -2
  69. package/dist/{chunk-25sz1y7j.js → chunk-jaewrjw3.js} +1 -1
  70. package/dist/{chunk-vbeeyhhe.js → chunk-jhfkzveb.js} +2 -2
  71. package/dist/chunk-k10hm62v.js +2 -0
  72. package/dist/{chunk-nrr8z2z7.js → chunk-k53ndvfv.js} +2 -2
  73. package/dist/{chunk-k26wnmzk.js → chunk-k8pnnyq1.js} +1 -1
  74. package/dist/{chunk-0w695m54.js → chunk-kbkvw42w.js} +1 -1
  75. package/dist/{chunk-b9escac0.js → chunk-kqam9qmd.js} +2 -2
  76. package/dist/{chunk-c8rzx3a1.js → chunk-kypdeb29.js} +1 -1
  77. package/dist/{chunk-wn6pbyzn.js → chunk-kzgyhhtz.js} +1 -1
  78. package/dist/{chunk-3pqra420.js → chunk-m1zp48mr.js} +1 -1
  79. package/dist/{chunk-0scz1dv5.js → chunk-mfhwcnxr.js} +1 -1
  80. package/dist/chunk-mmc8tvbb.js +2 -0
  81. package/dist/{chunk-txtrpypt.js → chunk-mtp0aygy.js} +2 -2
  82. package/dist/{chunk-xs12dtf1.js → chunk-myswpb7z.js} +1 -1
  83. package/dist/{chunk-jz5zs812.js → chunk-nf9dfx4t.js} +1 -1
  84. package/dist/{chunk-fjp3a7hp.js → chunk-nj38e2km.js} +1 -1
  85. package/dist/{chunk-68fw3ma0.js → chunk-nr1c0dny.js} +1 -1
  86. package/dist/chunk-nz0ns7ah.js +3 -0
  87. package/dist/chunk-p3qck29r.js +2 -0
  88. package/dist/{chunk-hptfq3rg.js → chunk-pkcvytq6.js} +1 -1
  89. package/dist/{chunk-hmskwy76.js → chunk-pqbzatbq.js} +1 -1
  90. package/dist/{chunk-40znfg3x.js → chunk-pwa2tt2e.js} +1 -1
  91. package/dist/chunk-qe63pqwy.js +2 -0
  92. package/dist/{chunk-4jyw358y.js → chunk-qmhd1bgx.js} +1 -1
  93. package/dist/chunk-qxc77b08.js +2 -0
  94. package/dist/{chunk-bffxf4xy.js → chunk-qzens4rg.js} +1 -1
  95. package/dist/chunk-r9k5vnrw.js +2 -0
  96. package/dist/{chunk-v1wfa758.js → chunk-rfvn4j6n.js} +1 -1
  97. package/dist/chunk-rnv477z3.js +2 -0
  98. package/dist/{chunk-3cvng2nz.js → chunk-rp3ytb19.js} +1 -1
  99. package/dist/{chunk-pskqrv5r.js → chunk-rpkwbqr8.js} +1 -1
  100. package/dist/chunk-s7da3h7c.js +2 -0
  101. package/dist/chunk-swphrsyr.js +2 -0
  102. package/dist/chunk-sx8pyc83.js +2 -0
  103. package/dist/chunk-sy3h7j1x.js +2 -0
  104. package/dist/{chunk-eseshkd0.js → chunk-t3340cv5.js} +1 -1
  105. package/dist/{chunk-1qgr52wx.js → chunk-te6etc5c.js} +1 -1
  106. package/dist/chunk-ttx1jk5b.js +2 -0
  107. package/dist/{chunk-tw047td6.js → chunk-tvrz1xp5.js} +1 -1
  108. package/dist/chunk-v5qn8kjd.js +2 -0
  109. package/dist/chunk-vj9stet1.js +2 -0
  110. package/dist/chunk-w6bd9r6p.js +2 -0
  111. package/dist/{chunk-193abzy6.js → chunk-wkq57ssc.js} +1 -1
  112. package/dist/{chunk-s4zb0fcj.js → chunk-wsxy4w86.js} +1 -1
  113. package/dist/chunk-x59yras6.js +2 -0
  114. package/dist/chunk-xfmzts7d.js +2 -0
  115. package/dist/chunk-xj99g66b.js +4 -0
  116. package/dist/{chunk-6p4qz8qv.js → chunk-y1hppm93.js} +1 -1
  117. package/dist/{chunk-1cpdz49v.js → chunk-yj6xx2b8.js} +1 -1
  118. package/dist/{chunk-3fzbvs2p.js → chunk-zc7g037n.js} +1 -1
  119. package/dist/{chunk-s6z3gm2s.js → chunk-zhfrmseh.js} +1 -1
  120. package/dist/{chunk-vgtmrd4c.js → chunk-zpxg12ep.js} +1 -1
  121. package/dist/src/git/github-provider.d.ts +12 -0
  122. package/dist/src/git/provider.d.ts +1 -0
  123. package/dist/src/index.js +1 -1
  124. package/dist/src/setup.js +1 -1
  125. package/dist/src/types.d.ts +1 -0
  126. package/dist/src/utils/github-actions-parser.d.ts +10 -0
  127. package/dist/src/utils/lock-file.d.ts +26 -2
  128. package/package.json +1 -1
  129. package/dist/chunk-0paakbpj.js +0 -2
  130. package/dist/chunk-19zyq15p.js +0 -2
  131. package/dist/chunk-24c2ab29.js +0 -2
  132. package/dist/chunk-28y7eayr.js +0 -2
  133. package/dist/chunk-2wj5xtdn.js +0 -2
  134. package/dist/chunk-49znmbh8.js +0 -2
  135. package/dist/chunk-86x1vsjw.js +0 -2
  136. package/dist/chunk-8fw0v7bv.js +0 -3
  137. package/dist/chunk-90zmqn5k.js +0 -2
  138. package/dist/chunk-97qf7mdt.js +0 -2
  139. package/dist/chunk-a4hzzn28.js +0 -2
  140. package/dist/chunk-b357cgb0.js +0 -2
  141. package/dist/chunk-brfyymhf.js +0 -2
  142. package/dist/chunk-dgfb8k0h.js +0 -2
  143. package/dist/chunk-e0gweha1.js +0 -2
  144. package/dist/chunk-e2t5jq26.js +0 -106
  145. package/dist/chunk-emb5v4wv.js +0 -2
  146. package/dist/chunk-emyvrx5t.js +0 -2
  147. package/dist/chunk-fpnjpgrb.js +0 -2
  148. package/dist/chunk-fr5c326k.js +0 -2
  149. package/dist/chunk-gkpd5nw2.js +0 -2
  150. package/dist/chunk-hns85dqw.js +0 -2
  151. package/dist/chunk-mcwxpdg9.js +0 -2
  152. package/dist/chunk-ng7px8gx.js +0 -2
  153. package/dist/chunk-ppmabn5h.js +0 -2
  154. package/dist/chunk-rwggcfgn.js +0 -2
  155. package/dist/chunk-s25rb4t2.js +0 -2
  156. package/dist/chunk-sc7emb71.js +0 -2
  157. package/dist/chunk-vdd1cghr.js +0 -2
  158. package/dist/chunk-vj1sdxpp.js +0 -2
  159. package/dist/chunk-xznnmhyt.js +0 -2
  160. package/dist/chunk-yk183r6z.js +0 -2
  161. package/dist/chunk-ys1qqcpp.js +0 -2
  162. package/dist/chunk-ytmxd5fk.js +0 -4
  163. package/dist/chunk-zxgkp71x.js +0 -2
@@ -1,10 +1,10 @@
1
1
  // @bun
2
- import{Kc as T,Lc as v,Mc as y}from"./chunk-8fw0v7bv.js";import{Rf as D,Sf as R,Tf as S}from"./chunk-c8rzx3a1.js";import{oh as P}from"./chunk-193abzy6.js";import{zh as U}from"./chunk-e68nf7cm.js";import{Bh as L,Ch as x,Fh as F}from"./chunk-hfjywbbc.js";import{Buffer as W}from"buffer";import{spawn as k}from"child_process";import q from"process";var B=/\b(?:gh[pousr]_[A-Z0-9_]{20,}|github_pat_[A-Z0-9_]{20,}|[A-Z0-9]{40,})\b/gi;function E(Q){return Q==="completed"||Q==="in_progress"?Q:"queued"}function w(Q){if(typeof Q!=="string")return null;if(Q==="success"||Q==="cancelled")return Q;if(Q==="failure"||Q==="timed_out"||Q==="action_required")return"failure";return"skipped"}function g(Q,X){let Y=Q.replace(B,"[REDACTED]");if(X&&X.length>=8)Y=Y.split(X).join("[REDACTED]");return Y}class I extends Error{constructor(Q){super(Q);this.name="LockfileRegenerationError"}}function f(Q){let X=`${x(Q)} ${Q?.message??""}`;return/not permitted to create or approve pull requests/i.test(X)||Q?.status===403&&/pull/i.test(X)}class N{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,K){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):P(),this.logger=K??F()}capabilities(){return{pinIssues:!0,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!0,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}isCacheValid(Q){return Date.now()-Q<this.cacheTTL}clearCache(){this.cache.pullRequests.clear(),this.cache.issues.clear()}async branchExists(Q){try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Q}`),!0}catch(X){if(X.message?.includes("404"))return!1;return this.logger.warn(`\u26A0\uFE0F Error checking branch ${Q}: ${x(X)}`),!1}}async createBranch(Q,X){try{let Z=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${X}`)).object.sha;await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/refs`,{ref:`refs/heads/${Q}`,sha:Z}),this.logger.info(`\u2705 Created branch ${Q} from ${X}`)}catch(Y){throw this.logger.error(`\u274C Failed to create branch ${Q}: ${x(Y)}`),Y}}async commitChanges(Q,X,Y,Z="main"){try{await this.commitChangesWithGit(Q,X,Y,Z)}catch($){if($ instanceof I||$ instanceof D)throw $;this.logger.warn(`\u26A0\uFE0F Git CLI commit failed, falling back to GitHub API: ${$}`),await this.commitChangesWithAPI(Q,X,Y,Z)}}async commitChangesWithGit(Q,X,Y,Z="main"){try{let $=Y.filter((V)=>V.path.includes(".github/workflows/")),J=Y.filter((V)=>!V.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((V)=>V.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. BUDDY_TOKEN not detected or lacks workflow permissions."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, ensure BUDDY_TOKEN is set with workflow:write permissions."),this.logger.info('\uD83D\uDCDD Creating empty commit to avoid "No commits between branches" error...');try{await this.runCommand("git",["commit","--allow-empty","-m","Workflow files require elevated permissions - no changes committed"]),this.logger.info("\u2705 Created empty commit for workflow-only PR")}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to create empty commit: ${V}`);try{let C=Bun.file("README.md");if(await C.exists()){let G=`${await C.text()}
2
+ import{Mc as T,Nc as v,Oc as y}from"./chunk-nz0ns7ah.js";import{Yf as D,Zf as S,_f as I}from"./chunk-kypdeb29.js";import{vh as P}from"./chunk-wkq57ssc.js";import{Gh as U}from"./chunk-b4a5gw9c.js";import{Ih as L,Jh as G,Mh as F}from"./chunk-bprmzg0p.js";import{Buffer as R}from"buffer";import{spawn as B}from"child_process";import q from"process";var E=/\b(?:gh[pousr]_[A-Z0-9_]{20,}|github_pat_[A-Z0-9_]{20,}|[A-Z0-9]{40,})\b/gi;function w(Q){return Q==="completed"||Q==="in_progress"?Q:"queued"}function g(Q){if(typeof Q!=="string")return null;if(Q==="success"||Q==="cancelled")return Q;if(Q==="failure"||Q==="timed_out"||Q==="action_required")return"failure";return"skipped"}function N(Q,X){let Y=Q.replace(E,"[REDACTED]");if(X&&X.length>=8)Y=Y.split(X).join("[REDACTED]");return Y}class W extends Error{constructor(Q){super(Q);this.name="LockfileRegenerationError"}}class k extends Error{constructor(Q){super(Q);this.name="WorkflowPermissionError"}}function f(Q){let X=`${G(Q)} ${Q?.message??""}`;return/refusing to allow (?:a GitHub App|an OAuth App|a Personal Access Token)[^\n]*workflow/i.test(X)}function d(Q){let X=`${G(Q)} ${Q?.message??""}`;return/not permitted to create or approve pull requests/i.test(X)||Q?.status===403&&/pull/i.test(X)}class h{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,K){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):P(),this.logger=K??F()}capabilities(){return{pinIssues:!0,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!0,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}isCacheValid(Q){return Date.now()-Q<this.cacheTTL}clearCache(){this.cache.pullRequests.clear(),this.cache.issues.clear()}async branchExists(Q){try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Q}`),!0}catch(X){if(X.message?.includes("404"))return!1;return this.logger.warn(`\u26A0\uFE0F Error checking branch ${Q}: ${G(X)}`),!1}}async createBranch(Q,X){try{let Z=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${X}`)).object.sha;await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/refs`,{ref:`refs/heads/${Q}`,sha:Z}),this.logger.info(`\u2705 Created branch ${Q} from ${X}`)}catch(Y){throw this.logger.error(`\u274C Failed to create branch ${Q}: ${G(Y)}`),Y}}async commitChanges(Q,X,Y,Z="main"){try{await this.commitChangesWithGit(Q,X,Y,Z)}catch($){if($ instanceof W||$ instanceof D)throw $;if(f($)){let J=Y.filter((_)=>!_.path.includes(".github/workflows/")),K=Y.length-J.length;if(J.length===0)throw new k(`The token may not update workflow files (${K} in this change). Grant the GitHub App the Workflows permission, or use a PAT with the workflow scope as BUDDY_TOKEN.`);this.logger.warn(`\u26A0\uFE0F The token may not update workflow files; committing the ${J.length} other file(s) without the ${K} workflow file(s)`),await this.commitChangesWithGit(Q,X,J,Z);return}this.logger.warn(`\u26A0\uFE0F Git CLI commit failed, falling back to GitHub API: ${$}`),await this.commitChangesWithAPI(Q,X,Y,Z)}}async commitChangesWithGit(Q,X,Y,Z="main"){try{let $=Y.filter((V)=>V.path.includes(".github/workflows/")),J=Y.filter((V)=>!V.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((V)=>V.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. BUDDY_TOKEN not detected or lacks workflow permissions."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, ensure BUDDY_TOKEN is set with workflow:write permissions."),this.logger.info('\uD83D\uDCDD Creating empty commit to avoid "No commits between branches" error...');try{await this.runCommand("git",["commit","--allow-empty","-m","Workflow files require elevated permissions - no changes committed"]),this.logger.info("\u2705 Created empty commit for workflow-only PR")}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to create empty commit: ${V}`);try{let x=Bun.file("README.md");if(await x.exists()){let H=`${await x.text()}
3
3
 
4
4
  <!-- Updated by Buddy -->
5
- `;await Bun.write("README.md",G),await this.runCommand("git",["add","README.md"]),await this.runCommand("git",["commit","-m","Update README for workflow-only PR"]),this.logger.info("\u2705 Created README update for workflow-only PR")}}catch(j){this.logger.error(`\u274C Failed to create any commit: ${j}`)}}return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);try{await this.runCommand("git",["config","user.name","github-actions[bot]"]),await this.runCommand("git",["config","user.email","41898282+github-actions[bot]@users.noreply.github.com"]),this.logger.info("\u2705 Git identity configured for github-actions[bot]")}catch(V){this.logger.warn("\u26A0\uFE0F Failed to configure Git identity:",V)}await this.runCommand("git",["fetch","origin"]),this.logger.info(`\uD83D\uDD04 Recreating ${Q} from origin/${Z} (Renovate-style)...`);try{await this.runCommand("git",["checkout",Q])}catch{try{await this.runCommand("git",["checkout","-b",Q,`origin/${Q}`])}catch{await this.runCommand("git",["checkout","-b",Q])}}await this.runCommand("git",["reset","--hard",`origin/${Z}`]),await this.runCommand("git",["clean","-fd"]),this.logger.info(`\u2705 Reset ${Q} to origin/${Z}`),await S(Y,async(V)=>{try{return await this.runCommand("git",["cat-file","-e",`origin/${Z}:${V}`]),!0}catch{return!1}});for(let V of Y){let j=R(V.path);if(q.env.NODE_ENV==="test"||q.env.BUN_ENV==="test"){if(["package.json","bun.lock","bun.lockb","package-lock.json","yarn.lock"].includes(j)&&V.content==='{"name":"x"}'){this.logger.warn(`\u26A0\uFE0F Skipping test file write to ${j} to prevent overwriting project files`);continue}}if(V.type==="delete")try{await this.runCommand("git",["rm",j])}catch{}else await Bun.write(j,V.content),await this.runCommand("git",["add",j])}if(!(q.env.NODE_ENV==="test"||q.env.BUN_ENV==="test")){let V=Y.map((C)=>C.path.replace(/^\.\//,"").replace(/^\/+/,"")),j=y(V);if(j.length>0){this.logger.info(`\uD83D\uDD12 Regenerating lock files for: ${j.join(", ")}`);let C=q.cwd(),M=[];for(let G of j)try{let H=await v(G,C);if(H.success)for(let z of T())try{await this.runCommand("git",["add",z])}catch{}else M.push(`${G}: ${H.message}`)}catch(H){M.push(`${G}: ${H instanceof Error?H.message:String(H)}`)}if(M.length>0){let G=M.map((H)=>` - ${H}`).join(`
6
- `);throw new I(`Lock file regeneration failed; refusing to open PR with stale lockfiles.
7
- ${G}`)}}}if((await this.runCommand("git",["status","--porcelain"])).trim()){await this.runCommand("git",["commit","-m",X]);let V=$.length>0&&this.hasWorkflowPermissions?this.getEffectiveToken(!0):void 0;await this.runCommand("git",["push","origin",Q,"--force-with-lease"],V),this.logger.info(`\u2705 Successfully recreated ${Q} with fresh changes from ${Z}: ${X}`)}else this.logger.info(`\u2139\uFE0F No file changes after resetting to ${Z} \u2014 skipping push to prevent PR auto-close`)}catch($){throw this.logger.error(`\u274C Failed to commit changes to ${Q} with Git CLI: ${x($)}`),$}}async commitChangesWithAPI(Q,X,Y,Z="main"){try{let $=Y.filter((z)=>z.path.includes(".github/workflows/")),J=Y.filter((z)=>!z.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((z)=>z.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. Consider using a GitHub App with workflow permissions for workflow updates."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, consider using a GitHub App with appropriate permissions.");return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);if(Y.some((z)=>z.path.endsWith("package.json")||z.path.endsWith("composer.json")))this.logger.warn("\u26A0\uFE0F Committing manifest files via API \u2014 lock files will not be updated."),this.logger.warn(" Lock file regeneration requires the Git CLI commit path (local filesystem).");this.logger.info(`\uD83D\uDD04 Recreating ${Q} from ${Z} via API (Renovate-style)...`);let V=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Z}`)).object.sha,C=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/commits/${V}`)).tree.sha;await S(Y,async(z)=>{let O=z.split("/").map((A)=>encodeURIComponent(A)).join("/");try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${O}?ref=${encodeURIComponent(Z)}`),!0}catch(A){if(A.message?.includes("404"))return!1;throw A}});let M=[];for(let z of Y){let O=R(z.path);if(z.type==="delete")M.push({path:O,mode:"100644",type:"blob",sha:null});else{let A=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/blobs`,{content:W.from(z.content).toString("base64"),encoding:"base64"});M.push({path:O,mode:"100644",type:"blob",sha:A.sha})}}let G=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/trees`,{base_tree:C,tree:M});if(G.sha===C){this.logger.info(`\u2139\uFE0F No file changes relative to ${Z} \u2014 skipping push to prevent PR auto-close`);return}let H=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/commits`,{message:X,tree:G.sha,parents:[V],author:{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"},committer:{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"}});await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/git/refs/heads/${Q}`,{sha:H.sha,force:!0}),this.logger.info(`\u2705 Committed changes to ${Q}: ${X}`)}catch($){throw this.logger.error(`\u274C Failed to commit changes to ${Q}: ${x($)}`),$}}async createPullRequest(Q){try{return await this.createPullRequestWithCLI(Q)}catch(X){this.logger.warn(`\u26A0\uFE0F GitHub CLI failed, falling back to API: ${X}`)}try{return await this.createPullRequestWithAPI(Q)}catch(X){if(!f(X))throw X;if(this.workflowToken&&this.workflowToken!==this.token)return this.logger.info("\uD83D\uDD11 GITHUB_TOKEN may not open pull requests in this repository, retrying with BUDDY_TOKEN"),await this.createPullRequestWithAPI(Q,this.workflowToken);throw Error('GitHub Actions may not open pull requests in this repository. Either set a BUDDY_TOKEN repository secret (a token with contents, pull requests and workflows write access), or enable Settings > Actions > General > "Allow GitHub Actions to create and approve pull requests".',{cause:X})}}async createPullRequestWithCLI(Q){try{let X=["pr","create","--title",Q.title,"--body",Q.body,"--head",Q.head,"--base",Q.base];if(Q.draft)X.push("--draft");if(Q.reviewers&&Q.reviewers.length>0)this.logger.info(`\uD83D\uDD0D Adding reviewers via CLI: ${Q.reviewers.join(", ")}`),X.push("--reviewer",Q.reviewers.join(","));if(Q.assignees&&Q.assignees.length>0)X.push("--assignee",Q.assignees.join(","));let Z=(await this.runCommand("gh",X)).match(/https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/);if(!Z)throw Error("Failed to parse PR number from GitHub CLI output");let $=Number.parseInt(Z[1]),J=Z[0];if(this.logger.info(`\u2705 Created PR #${$}: ${Q.title}`),Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${$}/labels`,{labels:Q.labels}),this.logger.info(`\u2705 Added labels to PR #${$}: ${Q.labels.join(", ")}`)}catch(K){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${K}`);for(let _ of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${$}/labels`,{labels:[_]})}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to add label '${_}': ${V}`)}}return{number:$,title:Q.title,body:Q.body,head:Q.head,base:Q.base,state:"open",url:J,createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:Q.draft||!1}}catch(X){throw this.logger.error(`\u274C Failed to create PR with GitHub CLI: ${Q.title}: ${x(X)}`),X}}async createPullRequestWithAPI(Q,X){try{let Y=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls`,{title:Q.title,body:Q.body,head:Q.head,base:Q.base,draft:Q.draft||!1},X);if(Q.reviewers&&Q.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to PR #${Y.number}: ${Q.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${Y.number}/requested_reviewers`,{reviewers:Q.reviewers,team_reviewers:Q.teamReviewers||[]}),this.logger.info(`\u2705 Successfully added reviewers: ${Q.reviewers.join(", ")}`)}catch(Z){this.logger.error(`\u274C Failed to add reviewers: ${Z}`),this.logger.error(` Reviewers: ${Q.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`),this.logger.error(` PR: #${Y.number}`)}if(Q.assignees&&Q.assignees.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/assignees`,{assignees:Q.assignees})}catch(Z){this.logger.warn(`\u26A0\uFE0F Failed to add assignees: ${Z}`)}if(Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/labels`,{labels:Q.labels})}catch(Z){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${Z}`);for(let $ of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/labels`,{labels:[$]})}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to add label '${$}': ${J}`)}}return this.logger.info(`\u2705 Created PR #${Y.number}: ${Q.title}`),{number:Y.number,title:Y.title,body:Y.body||"",head:Y.head.ref,base:Y.base.ref,state:Y.state,url:Y.html_url,createdAt:new Date(Y.created_at),updatedAt:new Date(Y.updated_at),author:Y.user.login,reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:Y.draft}}catch(Y){throw this.logger.error(`\u274C Failed to create PR with API: ${Q.title}: ${x(Y)}`),Y}}getEffectiveToken(Q=!1){if(Q&&this.workflowToken)return this.workflowToken;return this.token}async runCommand(Q,X,Y){let Z=Y||this.token;return new Promise(($,J)=>{let K=k(Q,X,{stdio:"pipe",env:{...q.env,GITHUB_TOKEN:Z,GH_TOKEN:Z}}),_="",V="";K.stdout?.on("data",(j)=>{_+=j.toString()}),K.stderr?.on("data",(j)=>{V+=j.toString()}),K.on("close",(j)=>{if(j===0)$(_);else J(Error(`Command failed with code ${j}: ${g(V,Z)}`))}),K.on("error",(j)=>{J(j)})})}async getPullRequests(Q="open"){let X=`${Q}`,Y=this.cache.pullRequests.get(X);if(Y&&this.isCacheValid(Y.timestamp))return this.logger.info(`\uD83D\uDCE6 Using cached PRs (state: ${Q}, ${Y.data.length} PRs)`),Y.data;try{let J=[];for(let _=1;_<=20;_++){let V=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/pulls?state=${Q}&per_page=100&page=${_}`);if(!Array.isArray(V)||V.length===0)break;if(J.push(...V),V.length<100)break}let K=J.map((_)=>({number:_.number,title:_.title,body:_.body??"",head:_.head.ref,base:_.base.ref,state:_.state,url:_.html_url,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),mergedAt:_.merged_at?new Date(_.merged_at):void 0,author:_.user.login,reviewers:_.requested_reviewers?.map((V)=>V.login)??[],assignees:_.assignees?.map((V)=>V.login)??[],labels:_.labels?.map((V)=>V.name)??[],draft:_.draft}));return this.cache.pullRequests.set(X,{data:K,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${K.length} PRs (state: ${Q})`),K}catch(Z){throw this.logger.error(`\u274C Failed to get PRs: ${x(Z)}`),Z}}async updatePullRequest(Q,X){this.cache.pullRequests.clear();try{let Y={};if(X.title)Y.title=X.title;if(X.body)Y.body=X.body;if(X.base)Y.base=X.base;if(X.draft!==void 0)Y.draft=X.draft;let Z=await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,Y);if(X.labels&&X.labels.length>0)try{await this.apiRequest(`PUT /repos/${this.owner}/${this.repo}/issues/${Q}/labels`,{labels:X.labels}),this.logger.info(`\u2705 Updated labels for PR #${Q}: ${X.labels.join(", ")}`)}catch($){this.logger.warn(`\u26A0\uFE0F Failed to update labels for PR #${Q}: ${$}`);for(let J of X.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Q}/labels`,{labels:[J]})}catch(K){this.logger.warn(`\u26A0\uFE0F Failed to add label '${J}' to PR #${Q}: ${K}`)}}if(X.reviewers&&X.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to existing PR #${Q}: ${X.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${Q}/requested_reviewers`,{reviewers:X.reviewers,team_reviewers:X.teamReviewers||[]}),this.logger.info(`\u2705 Updated reviewers for PR #${Q}: ${X.reviewers.join(", ")}`)}catch($){this.logger.error(`\u274C Failed to update reviewers for PR #${Q}: ${$}`),this.logger.error(` Reviewers: ${X.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`)}if(X.assignees&&X.assignees.length>0)try{await this.runCommand("gh",["issue","edit",Q.toString(),"--add-assignee",X.assignees.join(",")]),this.logger.info(`\u2705 Updated assignees for PR #${Q}: ${X.assignees.join(", ")}`)}catch($){this.logger.warn(`\u26A0\uFE0F Failed to update assignees for PR #${Q}: ${$}`)}return this.logger.info(`\u2705 Updated PR #${Q}`),{number:Z.number,title:Z.title,body:Z.body||"",head:Z.head.ref,base:Z.base.ref,state:Z.state,url:Z.html_url,createdAt:new Date(Z.created_at),updatedAt:new Date(Z.updated_at),author:Z.user.login,reviewers:[],assignees:[],labels:X.labels||[],draft:Z.draft}}catch(Y){throw this.logger.error(`\u274C Failed to update PR #${Q}: ${x(Y)}`),Y}}async closePullRequest(Q){this.cache.pullRequests.clear();try{await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,{state:"closed"}),this.logger.info(`\u2705 Closed PR #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to close PR #${Q}: ${x(X)}`),X}}async reopenPullRequest(Q){this.cache.pullRequests.clear();try{await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,{state:"open"}),this.logger.info(`\u2705 Reopened PR #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to reopen PR #${Q}: ${x(X)}`),X}}async createComment(Q,X){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Q}/comments`,{body:X}),this.logger.info(`\uD83D\uDCAC Added comment to PR #${Q}`)}catch(Y){throw this.logger.error(`\u274C Failed to add comment to PR #${Q}: ${x(Y)}`),Y}}async mergePullRequest(Q,X="merge"){try{let Y=X==="rebase"?"rebase":X==="squash"?"squash":"merge",$=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`)).head.ref;await this.apiRequest(`PUT /repos/${this.owner}/${this.repo}/pulls/${Q}/merge`,{merge_method:Y}),this.logger.info(`\u2705 Merged PR #${Q} using ${X}`);try{await this.deleteBranch($),this.logger.info(`\uD83E\uDDF9 Cleaned up branch ${$} after merge`)}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to clean up branch ${$}:`,J)}}catch(Y){throw this.logger.error(`\u274C Failed to merge PR #${Q}: ${x(Y)}`),Y}}async getPullRequestHeadSha(Q){try{return(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`))?.head?.sha??""}catch(X){return this.logger.debug(`Could not read head SHA for PR #${Q}: ${x(X)}`),""}}async hasWriteAccess(Q){try{let X=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/collaborators/${encodeURIComponent(Q)}/permission`);return["write","maintain","admin"].includes(X?.permission)}catch(X){if(X instanceof L&&X.isNotFound)return!1;return this.logger.warn(`\u26A0\uFE0F Could not resolve permissions for @${Q}: ${x(X)}`),!1}}async reactToComment(Q,X){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/comments/${Q}/reactions`,{content:X})}catch(Y){this.logger.debug(`Could not react to comment ${Q}: ${x(Y)}`)}}async getWorkflowRunLogs(Q){try{let X=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/actions/runs/${Q}/logs`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!X.ok)return this.logger.debug(`Could not fetch logs for run ${Q}: ${X.status}`),null;return W.from(await X.arrayBuffer()).toString("utf-8").replace(/[^\t\n\r\x20-\x7E]+/g," ")}catch(X){return this.logger.debug(`Could not fetch logs for run ${Q}: ${x(X)}`),null}}async listWorkflowRuns(Q,X={}){let Y=new URLSearchParams({branch:Q,per_page:String(X.limit??20)});if(X.status)Y.set("status",X.status);try{return((await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/actions/runs?${Y.toString()}`))?.workflow_runs??[]).map((J)=>({id:Number(J.id),name:String(J.name??""),headSha:String(J.head_sha??""),headBranch:String(J.head_branch??Q),status:E(J.status),conclusion:w(J.conclusion),createdAt:new Date(String(J.created_at??new Date().toISOString()))}))}catch(Z){return this.logger.debug(`Could not list workflow runs for ${Q}: ${x(Z)}`),[]}}async rerunWorkflowRun(Q,X=!0){let Y=X?"rerun-failed-jobs":"rerun";try{let Z=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/actions/runs/${Q}/${Y}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!Z.ok)return this.logger.warn(`Could not re-run workflow run ${Q}: ${Z.status} ${Z.statusText}`),!1;return!0}catch(Z){return this.logger.warn(`Could not re-run workflow run ${Q}: ${x(Z)}`),!1}}async createCheckRun(Q,X,Y){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/check-runs`,{name:Q,head_sha:X,status:"completed",conclusion:Y.conclusion,completed_at:new Date().toISOString(),output:{title:Y.title,summary:Y.summary}}),this.logger.info(`\u2705 Reported check run ${Q}: ${Y.conclusion}`)}catch(Z){this.logger.warn(`\u26A0\uFE0F Could not report check run ${Q}: ${x(Z)}`)}}async getFileContent(Q,X){try{let Y=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${encodeURIComponent(Q)}?ref=${encodeURIComponent(X)}`);if(!Y?.content)return null;return W.from(Y.content,Y.encoding==="base64"?"base64":"utf-8").toString("utf-8")}catch(Y){if(Y instanceof L&&Y.isNotFound)return null;throw Y}}async getPullRequestDiff(Q){let X=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/pulls/${Q}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github.v3.diff","User-Agent":"buddy"}});if(!X.ok)throw new L(`Failed to fetch diff for PR #${Q}: ${X.status} ${X.statusText}`,X.status,"GET",`${this.apiUrl}/repos/${this.owner}/${this.repo}/pulls/${Q}`,`${this.owner}/${this.repo}`);return await X.text()}async createReview(Q,X){let Y=`POST /repos/${this.owner}/${this.repo}/pulls/${Q}/reviews`;try{return await this.apiRequest(Y,{body:X.body,event:X.event,...X.comments?.length?{comments:X.comments}:{}}),this.logger.success(`\u2705 Posted review on PR #${Q} (${X.comments?.length??0} inline comment(s))`),{posted:!0,inlineComments:X.comments?.length??0}}catch(Z){if(!X.comments?.length)throw this.logger.error(`\u274C Failed to post review on PR #${Q}: ${x(Z)}`),Z;return this.logger.warn(`\u26A0\uFE0F Review with inline comments was rejected (${x(Z)}); posting the summary alone`),await this.apiRequest(Y,{body:X.body,event:X.event}),{posted:!0,inlineComments:0}}}async enableAutoMerge(Q,X="squash"){let Y=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`),Z=`mutation($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
5
+ `;await Bun.write("README.md",H),await this.runCommand("git",["add","README.md"]),await this.runCommand("git",["commit","-m","Update README for workflow-only PR"]),this.logger.info("\u2705 Created README update for workflow-only PR")}}catch(j){this.logger.error(`\u274C Failed to create any commit: ${j}`)}}return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);try{await this.runCommand("git",["config","user.name","github-actions[bot]"]),await this.runCommand("git",["config","user.email","41898282+github-actions[bot]@users.noreply.github.com"]),this.logger.info("\u2705 Git identity configured for github-actions[bot]")}catch(V){this.logger.warn("\u26A0\uFE0F Failed to configure Git identity:",V)}await this.runCommand("git",["fetch","origin"]),this.logger.info(`\uD83D\uDD04 Recreating ${Q} from origin/${Z} (Renovate-style)...`);try{await this.runCommand("git",["checkout",Q])}catch{try{await this.runCommand("git",["checkout","-b",Q,`origin/${Q}`])}catch{await this.runCommand("git",["checkout","-b",Q])}}await this.runCommand("git",["reset","--hard",`origin/${Z}`]),await this.runCommand("git",["clean","-fd"]),this.logger.info(`\u2705 Reset ${Q} to origin/${Z}`),await I(Y,async(V)=>{try{return await this.runCommand("git",["cat-file","-e",`origin/${Z}:${V}`]),!0}catch{return!1}});for(let V of Y){let j=S(V.path);if(q.env.NODE_ENV==="test"||q.env.BUN_ENV==="test"){if(["package.json","bun.lock","bun.lockb","package-lock.json","yarn.lock"].includes(j)&&V.content==='{"name":"x"}'){this.logger.warn(`\u26A0\uFE0F Skipping test file write to ${j} to prevent overwriting project files`);continue}}if(V.type==="delete")try{await this.runCommand("git",["rm",j])}catch{}else await Bun.write(j,V.content),await this.runCommand("git",["add",j])}if(!(q.env.NODE_ENV==="test"||q.env.BUN_ENV==="test")){let V=Y.map((x)=>x.path.replace(/^\.\//,"").replace(/^\/+/,"")),j=y(V);if(j.length>0){this.logger.info(`\uD83D\uDD12 Regenerating lock files for: ${j.join(", ")}`);let x=q.cwd(),M=[];for(let H of j)try{let z=await v(H,x);if(z.success)for(let C of T())try{await this.runCommand("git",["add",C])}catch{}else M.push(`${H}: ${z.message}`)}catch(z){M.push(`${H}: ${z instanceof Error?z.message:String(z)}`)}if(M.length>0){let H=M.map((z)=>` - ${z}`).join(`
6
+ `);throw new W(`Lock file regeneration failed; refusing to open PR with stale lockfiles.
7
+ ${H}`)}}}if((await this.runCommand("git",["status","--porcelain"])).trim()){await this.runCommand("git",["commit","-m",X]);let V=$.length>0&&this.hasWorkflowPermissions?this.getEffectiveToken(!0):void 0;await this.runCommand("git",["push","origin",Q,"--force-with-lease"],V),this.logger.info(`\u2705 Successfully recreated ${Q} with fresh changes from ${Z}: ${X}`)}else this.logger.info(`\u2139\uFE0F No file changes after resetting to ${Z} \u2014 skipping push to prevent PR auto-close`)}catch($){throw this.logger.error(`\u274C Failed to commit changes to ${Q} with Git CLI: ${G($)}`),$}}async commitChangesWithAPI(Q,X,Y,Z="main"){try{let $=Y.filter((C)=>C.path.includes(".github/workflows/")),J=Y.filter((C)=>!C.path.includes(".github/workflows/"));if($.length>0&&!this.hasWorkflowPermissions)if(this.logger.warn(`\u26A0\uFE0F Detected ${$.length} workflow file(s). These require elevated permissions.`),this.logger.warn(`\u26A0\uFE0F Workflow files: ${$.map((C)=>C.path).join(", ")}`),this.logger.warn("\u2139\uFE0F Workflow files will be skipped in this commit. Consider using a GitHub App with workflow permissions for workflow updates."),J.length>0)this.logger.info(`\uD83D\uDCDD Committing ${J.length} non-workflow files...`),Y=J;else{this.logger.warn("\u26A0\uFE0F All files are workflow files. No files will be committed in this PR."),this.logger.warn("\uD83D\uDCA1 To update workflow files, consider using a GitHub App with appropriate permissions.");return}else if($.length>0)this.logger.info(`\u2705 Including ${$.length} workflow file(s) with elevated permissions`);if(Y.some((C)=>C.path.endsWith("package.json")||C.path.endsWith("composer.json")))this.logger.warn("\u26A0\uFE0F Committing manifest files via API \u2014 lock files will not be updated."),this.logger.warn(" Lock file regeneration requires the Git CLI commit path (local filesystem).");this.logger.info(`\uD83D\uDD04 Recreating ${Q} from ${Z} via API (Renovate-style)...`);let V=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/ref/heads/${Z}`)).object.sha,x=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/commits/${V}`)).tree.sha;await I(Y,async(C)=>{let O=C.split("/").map((A)=>encodeURIComponent(A)).join("/");try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${O}?ref=${encodeURIComponent(Z)}`),!0}catch(A){if(A.message?.includes("404"))return!1;throw A}});let M=[];for(let C of Y){let O=S(C.path);if(C.type==="delete")M.push({path:O,mode:"100644",type:"blob",sha:null});else{let A=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/blobs`,{content:R.from(C.content).toString("base64"),encoding:"base64"});M.push({path:O,mode:"100644",type:"blob",sha:A.sha})}}let H=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/trees`,{base_tree:x,tree:M});if(H.sha===x){this.logger.info(`\u2139\uFE0F No file changes relative to ${Z} \u2014 skipping push to prevent PR auto-close`);return}let z=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/commits`,{message:X,tree:H.sha,parents:[V],author:{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"},committer:{name:"github-actions[bot]",email:"41898282+github-actions[bot]@users.noreply.github.com"}});await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/git/refs/heads/${Q}`,{sha:z.sha,force:!0}),this.logger.info(`\u2705 Committed changes to ${Q}: ${X}`)}catch($){throw this.logger.error(`\u274C Failed to commit changes to ${Q}: ${G($)}`),$}}async createPullRequest(Q){try{return await this.createPullRequestWithCLI(Q)}catch(X){this.logger.warn(`\u26A0\uFE0F GitHub CLI failed, falling back to API: ${X}`)}try{return await this.createPullRequestWithAPI(Q)}catch(X){if(!d(X))throw X;if(this.workflowToken&&this.workflowToken!==this.token)return this.logger.info("\uD83D\uDD11 GITHUB_TOKEN may not open pull requests in this repository, retrying with BUDDY_TOKEN"),await this.createPullRequestWithAPI(Q,this.workflowToken);throw Error('GitHub Actions may not open pull requests in this repository. Either set a BUDDY_TOKEN repository secret (a token with contents, pull requests and workflows write access), or enable Settings > Actions > General > "Allow GitHub Actions to create and approve pull requests".',{cause:X})}}async createPullRequestWithCLI(Q){try{let X=["pr","create","--title",Q.title,"--body",Q.body,"--head",Q.head,"--base",Q.base];if(Q.draft)X.push("--draft");if(Q.reviewers&&Q.reviewers.length>0)this.logger.info(`\uD83D\uDD0D Adding reviewers via CLI: ${Q.reviewers.join(", ")}`),X.push("--reviewer",Q.reviewers.join(","));if(Q.assignees&&Q.assignees.length>0)X.push("--assignee",Q.assignees.join(","));let Z=(await this.runCommand("gh",X)).match(/https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/);if(!Z)throw Error("Failed to parse PR number from GitHub CLI output");let $=Number.parseInt(Z[1]),J=Z[0];if(this.logger.info(`\u2705 Created PR #${$}: ${Q.title}`),Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${$}/labels`,{labels:Q.labels}),this.logger.info(`\u2705 Added labels to PR #${$}: ${Q.labels.join(", ")}`)}catch(K){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${K}`);for(let _ of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${$}/labels`,{labels:[_]})}catch(V){this.logger.warn(`\u26A0\uFE0F Failed to add label '${_}': ${V}`)}}return{number:$,title:Q.title,body:Q.body,head:Q.head,base:Q.base,state:"open",url:J,createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:Q.draft||!1}}catch(X){throw this.logger.error(`\u274C Failed to create PR with GitHub CLI: ${Q.title}: ${G(X)}`),X}}async createPullRequestWithAPI(Q,X){try{let Y=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls`,{title:Q.title,body:Q.body,head:Q.head,base:Q.base,draft:Q.draft||!1},X);if(Q.reviewers&&Q.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to PR #${Y.number}: ${Q.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${Y.number}/requested_reviewers`,{reviewers:Q.reviewers,team_reviewers:Q.teamReviewers||[]}),this.logger.info(`\u2705 Successfully added reviewers: ${Q.reviewers.join(", ")}`)}catch(Z){this.logger.error(`\u274C Failed to add reviewers: ${Z}`),this.logger.error(` Reviewers: ${Q.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`),this.logger.error(` PR: #${Y.number}`)}if(Q.assignees&&Q.assignees.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/assignees`,{assignees:Q.assignees})}catch(Z){this.logger.warn(`\u26A0\uFE0F Failed to add assignees: ${Z}`)}if(Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/labels`,{labels:Q.labels})}catch(Z){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${Z}`);for(let $ of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Y.number}/labels`,{labels:[$]})}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to add label '${$}': ${J}`)}}return this.logger.info(`\u2705 Created PR #${Y.number}: ${Q.title}`),{number:Y.number,title:Y.title,body:Y.body||"",head:Y.head.ref,base:Y.base.ref,state:Y.state,url:Y.html_url,createdAt:new Date(Y.created_at),updatedAt:new Date(Y.updated_at),author:Y.user.login,reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:Y.draft}}catch(Y){throw this.logger.error(`\u274C Failed to create PR with API: ${Q.title}: ${G(Y)}`),Y}}getEffectiveToken(Q=!1){if(Q&&this.workflowToken)return this.workflowToken;return this.token}async runCommand(Q,X,Y){let Z=Y||this.token;return new Promise(($,J)=>{let K=B(Q,X,{stdio:"pipe",env:{...q.env,GITHUB_TOKEN:Z,GH_TOKEN:Z}}),_="",V="";K.stdout?.on("data",(j)=>{_+=j.toString()}),K.stderr?.on("data",(j)=>{V+=j.toString()}),K.on("close",(j)=>{if(j===0)$(_);else J(Error(`Command failed with code ${j}: ${N(V,Z)}`))}),K.on("error",(j)=>{J(j)})})}async getPullRequestFiles(Q){let X=[];for(let Y=1;Y<=30;Y++){let Z=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}/files?per_page=100&page=${Y}`);if(X.push(...Z.map(($)=>$.filename)),Z.length<100)break}return X}async getPullRequests(Q="open"){let X=`${Q}`,Y=this.cache.pullRequests.get(X);if(Y&&this.isCacheValid(Y.timestamp))return this.logger.info(`\uD83D\uDCE6 Using cached PRs (state: ${Q}, ${Y.data.length} PRs)`),Y.data;try{let J=[];for(let _=1;_<=20;_++){let V=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/pulls?state=${Q}&per_page=100&page=${_}`);if(!Array.isArray(V)||V.length===0)break;if(J.push(...V),V.length<100)break}let K=J.map((_)=>({number:_.number,title:_.title,body:_.body??"",head:_.head.ref,base:_.base.ref,state:_.state,url:_.html_url,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),mergedAt:_.merged_at?new Date(_.merged_at):void 0,author:_.user.login,reviewers:_.requested_reviewers?.map((V)=>V.login)??[],assignees:_.assignees?.map((V)=>V.login)??[],labels:_.labels?.map((V)=>V.name)??[],draft:_.draft}));return this.cache.pullRequests.set(X,{data:K,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${K.length} PRs (state: ${Q})`),K}catch(Z){throw this.logger.error(`\u274C Failed to get PRs: ${G(Z)}`),Z}}async updatePullRequest(Q,X){this.cache.pullRequests.clear();try{let Y={};if(X.title)Y.title=X.title;if(X.body)Y.body=X.body;if(X.base)Y.base=X.base;if(X.draft!==void 0)Y.draft=X.draft;let Z=await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,Y);if(X.labels&&X.labels.length>0)try{await this.apiRequest(`PUT /repos/${this.owner}/${this.repo}/issues/${Q}/labels`,{labels:X.labels}),this.logger.info(`\u2705 Updated labels for PR #${Q}: ${X.labels.join(", ")}`)}catch($){this.logger.warn(`\u26A0\uFE0F Failed to update labels for PR #${Q}: ${$}`);for(let J of X.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Q}/labels`,{labels:[J]})}catch(K){this.logger.warn(`\u26A0\uFE0F Failed to add label '${J}' to PR #${Q}: ${K}`)}}if(X.reviewers&&X.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to existing PR #${Q}: ${X.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${Q}/requested_reviewers`,{reviewers:X.reviewers,team_reviewers:X.teamReviewers||[]}),this.logger.info(`\u2705 Updated reviewers for PR #${Q}: ${X.reviewers.join(", ")}`)}catch($){this.logger.error(`\u274C Failed to update reviewers for PR #${Q}: ${$}`),this.logger.error(` Reviewers: ${X.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`)}if(X.assignees&&X.assignees.length>0)try{await this.runCommand("gh",["issue","edit",Q.toString(),"--add-assignee",X.assignees.join(",")]),this.logger.info(`\u2705 Updated assignees for PR #${Q}: ${X.assignees.join(", ")}`)}catch($){this.logger.warn(`\u26A0\uFE0F Failed to update assignees for PR #${Q}: ${$}`)}return this.logger.info(`\u2705 Updated PR #${Q}`),{number:Z.number,title:Z.title,body:Z.body||"",head:Z.head.ref,base:Z.base.ref,state:Z.state,url:Z.html_url,createdAt:new Date(Z.created_at),updatedAt:new Date(Z.updated_at),author:Z.user.login,reviewers:[],assignees:[],labels:X.labels||[],draft:Z.draft}}catch(Y){throw this.logger.error(`\u274C Failed to update PR #${Q}: ${G(Y)}`),Y}}async closePullRequest(Q){this.cache.pullRequests.clear();try{await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,{state:"closed"}),this.logger.info(`\u2705 Closed PR #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to close PR #${Q}: ${G(X)}`),X}}async reopenPullRequest(Q){this.cache.pullRequests.clear();try{await this.apiRequest(`PATCH /repos/${this.owner}/${this.repo}/pulls/${Q}`,{state:"open"}),this.logger.info(`\u2705 Reopened PR #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to reopen PR #${Q}: ${G(X)}`),X}}async createComment(Q,X){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${Q}/comments`,{body:X}),this.logger.info(`\uD83D\uDCAC Added comment to PR #${Q}`)}catch(Y){throw this.logger.error(`\u274C Failed to add comment to PR #${Q}: ${G(Y)}`),Y}}async mergePullRequest(Q,X="merge"){try{let Y=X==="rebase"?"rebase":X==="squash"?"squash":"merge",$=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`)).head.ref;await this.apiRequest(`PUT /repos/${this.owner}/${this.repo}/pulls/${Q}/merge`,{merge_method:Y}),this.logger.info(`\u2705 Merged PR #${Q} using ${X}`);try{await this.deleteBranch($),this.logger.info(`\uD83E\uDDF9 Cleaned up branch ${$} after merge`)}catch(J){this.logger.warn(`\u26A0\uFE0F Failed to clean up branch ${$}:`,J)}}catch(Y){throw this.logger.error(`\u274C Failed to merge PR #${Q}: ${G(Y)}`),Y}}async getPullRequestHeadSha(Q){try{return(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`))?.head?.sha??""}catch(X){return this.logger.debug(`Could not read head SHA for PR #${Q}: ${G(X)}`),""}}async hasWriteAccess(Q){try{let X=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/collaborators/${encodeURIComponent(Q)}/permission`);return["write","maintain","admin"].includes(X?.permission)}catch(X){if(X instanceof L&&X.isNotFound)return!1;return this.logger.warn(`\u26A0\uFE0F Could not resolve permissions for @${Q}: ${G(X)}`),!1}}async reactToComment(Q,X){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/comments/${Q}/reactions`,{content:X})}catch(Y){this.logger.debug(`Could not react to comment ${Q}: ${G(Y)}`)}}async getWorkflowRunLogs(Q){try{let X=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/actions/runs/${Q}/logs`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!X.ok)return this.logger.debug(`Could not fetch logs for run ${Q}: ${X.status}`),null;return R.from(await X.arrayBuffer()).toString("utf-8").replace(/[^\t\n\r\x20-\x7E]+/g," ")}catch(X){return this.logger.debug(`Could not fetch logs for run ${Q}: ${G(X)}`),null}}async listWorkflowRuns(Q,X={}){let Y=new URLSearchParams({branch:Q,per_page:String(X.limit??20)});if(X.status)Y.set("status",X.status);try{return((await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/actions/runs?${Y.toString()}`))?.workflow_runs??[]).map((J)=>({id:Number(J.id),name:String(J.name??""),headSha:String(J.head_sha??""),headBranch:String(J.head_branch??Q),status:w(J.status),conclusion:g(J.conclusion),createdAt:new Date(String(J.created_at??new Date().toISOString()))}))}catch(Z){return this.logger.debug(`Could not list workflow runs for ${Q}: ${G(Z)}`),[]}}async rerunWorkflowRun(Q,X=!0){let Y=X?"rerun-failed-jobs":"rerun";try{let Z=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/actions/runs/${Q}/${Y}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github+json","User-Agent":"buddy"}});if(!Z.ok)return this.logger.warn(`Could not re-run workflow run ${Q}: ${Z.status} ${Z.statusText}`),!1;return!0}catch(Z){return this.logger.warn(`Could not re-run workflow run ${Q}: ${G(Z)}`),!1}}async createCheckRun(Q,X,Y){try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/check-runs`,{name:Q,head_sha:X,status:"completed",conclusion:Y.conclusion,completed_at:new Date().toISOString(),output:{title:Y.title,summary:Y.summary}}),this.logger.info(`\u2705 Reported check run ${Q}: ${Y.conclusion}`)}catch(Z){this.logger.warn(`\u26A0\uFE0F Could not report check run ${Q}: ${G(Z)}`)}}async getFileContent(Q,X){try{let Y=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${encodeURIComponent(Q)}?ref=${encodeURIComponent(X)}`);if(!Y?.content)return null;return R.from(Y.content,Y.encoding==="base64"?"base64":"utf-8").toString("utf-8")}catch(Y){if(Y instanceof L&&Y.isNotFound)return null;throw Y}}async getPullRequestDiff(Q){let X=await U(`${this.apiUrl}/repos/${this.owner}/${this.repo}/pulls/${Q}`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github.v3.diff","User-Agent":"buddy"}});if(!X.ok)throw new L(`Failed to fetch diff for PR #${Q}: ${X.status} ${X.statusText}`,X.status,"GET",`${this.apiUrl}/repos/${this.owner}/${this.repo}/pulls/${Q}`,`${this.owner}/${this.repo}`);return await X.text()}async createReview(Q,X){let Y=`POST /repos/${this.owner}/${this.repo}/pulls/${Q}/reviews`;try{return await this.apiRequest(Y,{body:X.body,event:X.event,...X.comments?.length?{comments:X.comments}:{}}),this.logger.success(`\u2705 Posted review on PR #${Q} (${X.comments?.length??0} inline comment(s))`),{posted:!0,inlineComments:X.comments?.length??0}}catch(Z){if(!X.comments?.length)throw this.logger.error(`\u274C Failed to post review on PR #${Q}: ${G(Z)}`),Z;return this.logger.warn(`\u26A0\uFE0F Review with inline comments was rejected (${G(Z)}); posting the summary alone`),await this.apiRequest(Y,{body:X.body,event:X.event}),{posted:!0,inlineComments:0}}}async enableAutoMerge(Q,X="squash"){let Y=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`),Z=`mutation($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
8
8
  enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
9
9
  pullRequest { number }
10
10
  }
@@ -25,14 +25,14 @@ ${G}`)}}}if((await this.runCommand("git",["status","--porcelain"])).trim()){awai
25
25
  }
26
26
  }
27
27
  }
28
- }`,{owner:this.owner,repo:this.repo,number:Q});if(Y.errors?.length)return this.logger.debug(`Could not read review threads on #${Q}: ${Y.errors.map(($)=>$.message).join("; ")}`),[];return(Y.data?.repository?.pullRequest?.reviewThreads?.nodes??[]).filter(Boolean).map(($)=>({id:String($.id),isResolved:Boolean($.isResolved),...$.path?{path:String($.path)}:{},authorLogins:($.comments?.nodes??[]).map((J)=>J?.author?.login).filter((J)=>typeof J==="string")}))}catch(Y){return this.logger.debug(`Could not read review threads on #${Q}: ${x(Y)}`),[]}}async resolveReviewThread(Q,X){try{let Z=await this.graphqlRequest(`mutation($threadId: ID!) {
28
+ }`,{owner:this.owner,repo:this.repo,number:Q});if(Y.errors?.length)return this.logger.debug(`Could not read review threads on #${Q}: ${Y.errors.map(($)=>$.message).join("; ")}`),[];return(Y.data?.repository?.pullRequest?.reviewThreads?.nodes??[]).filter(Boolean).map(($)=>({id:String($.id),isResolved:Boolean($.isResolved),...$.path?{path:String($.path)}:{},authorLogins:($.comments?.nodes??[]).map((J)=>J?.author?.login).filter((J)=>typeof J==="string")}))}catch(Y){return this.logger.debug(`Could not read review threads on #${Q}: ${G(Y)}`),[]}}async resolveReviewThread(Q,X){try{let Z=await this.graphqlRequest(`mutation($threadId: ID!) {
29
29
  resolveReviewThread(input: { threadId: $threadId }) {
30
30
  thread { isResolved }
31
31
  }
32
- }`,{threadId:X});if(Z.errors?.length)return this.logger.warn(`Could not resolve review thread: ${Z.errors.map(($)=>$.message).join("; ")}`),!1;return Boolean(Z.data?.resolveReviewThread?.thread?.isResolved)}catch(Z){return this.logger.warn(`Could not resolve review thread: ${x(Z)}`),!1}}async getPullRequestChecksState(Q){try{let Y=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`)).head.sha,[Z,$]=await Promise.all([this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${Y}/status`),this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${Y}/check-runs?per_page=100`)]),J=$?.check_runs??[],K=(Z?.statuses?.length??0)>0;if(J.length===0&&!K)return"none";if(J.some((j)=>j.conclusion!==null&&["failure","cancelled","timed_out","action_required"].includes(j.conclusion))||Z?.state==="failure"||Z?.state==="error")return"failure";if(J.some((j)=>j.status!=="completed")||Z?.state==="pending")return"pending";return"success"}catch(X){return this.logger.warn(`\u26A0\uFE0F Could not read check state for PR #${Q}: ${x(X)}`),"pending"}}async graphqlRequest(Q,X){let Y=await U(`${this.apiUrl}/graphql`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({query:Q,variables:X})});if(!Y.ok)throw new L(`GraphQL request failed: ${Y.status} ${Y.statusText}`,Y.status,"POST",`${this.apiUrl}/graphql`,`${this.owner}/${this.repo}`);return await Y.json()}async deleteBranch(Q){try{await this.runCommand("git",["push","origin","--delete",Q]),this.logger.info(`\u2705 Deleted branch ${Q} via git`)}catch(X){try{await this.runCommand("git",["branch","-D",Q])}catch{}if(/remote ref does not exist|unable to delete '[^']*': remote ref/i.test(x(X))){this.logger.info(`\u2139\uFE0F Branch ${Q} was already gone`);return}throw this.logger.warn(`\u26A0\uFE0F Failed to delete remote branch ${Q}: ${x(X)}`),X}}async getBuddyBranches(){try{let Q=await this.runCommand("git",["branch","-r","--format=%(refname:short) %(objectname) %(committerdate:iso8601)"]),X=[];for(let Y of Q.split(`
33
- `)){let Z=Y.trim();if(!Z)continue;let $=Z.split(" ");if($.length<3)continue;let J=$[0],K=$[1],_=$.slice(2).join(" "),V=J.replace(/^origin\//,"");if(!V.startsWith("buddy/"))continue;try{let j=new Date(_);X.push({name:V,sha:K,lastCommitDate:j})}catch{this.logger.warn(`\u26A0\uFE0F Failed to parse date for branch ${V}: ${_}`),X.push({name:V,sha:K,lastCommitDate:new Date(0)})}}return this.logger.info(`\uD83D\uDD0D Found ${X.length} buddy branches using local git`),X}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to fetch buddy branches via git, falling back to API:",Q),this.getBuddyBranchesViaAPI()}}async getBuddyBranchesViaAPI(){try{let Q=[],X=1,Y=100;while(!0){let J=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/branches?per_page=${Y}&page=${X}`);if(!J||J.length===0)break;if(Q=Q.concat(J),J.length<Y)break;X++}this.logger.info(`\uD83D\uDD0D Found ${Q.length} total branches in repository`);let Z=Q.filter((J)=>J.name.startsWith("buddy/"));return this.logger.info(`\uD83E\uDD16 Found ${Z.length} buddy branches`),await Promise.all(Z.map(async(J)=>{try{let K=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${J.commit.sha}`);return{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(K.commit.committer.date)}}catch(K){return this.logger.warn(`\u26A0\uFE0F Failed to get commit info for branch ${J.name}: ${x(K)}`),{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(0)}}}))}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to fetch buddy branches:",Q),[]}}async getOrphanedBuddyBranches(){try{let Q=await this.getBuddyBranches(),X=await this.getOpenPRBranches();return Q.filter((Z)=>!X.has(Z.name))}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to identify orphaned branches:",Q),[]}}prDetectionSuccessful=!1;async getOpenPRBranches(){this.prDetectionSuccessful=!1;try{let Q=await this.getPullRequests("open"),X=new Set(Q.map((Y)=>Y.head).filter((Y)=>Y.startsWith("buddy/")));return this.logger.info(`\uD83D\uDD0D GitHub API reports ${Q.length} open PR(s); ${X.size} are buddy branches`),this.logger.info(`\uD83D\uDEE1\uFE0F Protecting ${X.size} branches with confirmed open PRs`),this.prDetectionSuccessful=!0,X}catch(Q){this.logger.warn("\u26A0\uFE0F Failed to fetch open PRs via API, falling back to age-based protection:",Q);try{let X=await this.getBuddyBranches(),Y=new Date;Y.setDate(Y.getDate()-30);let Z=new Set;for(let $ of X)if($.lastCommitDate>Y)Z.add($.name);return this.logger.info(`\uD83D\uDEE1\uFE0F Conservative fallback: protecting ${Z.size} branches newer than 30 days`),Z}catch{return this.logger.info("\u26A0\uFE0F Could not enumerate branches for age-based fallback"),new Set}}}async cleanupStaleBranches(Q=7,X=!1){this.logger.info("\uD83D\uDD0D Looking for buddy branches without open PRs...");let Y=await this.getOrphanedBuddyBranches();this.logger.info(`\uD83D\uDD0D Found ${Y.length} orphaned buddy branches (no associated open PRs)`);let Z=Y;if(this.prDetectionSuccessful)this.logger.info(`\uD83C\uDFAF PR detection successful - cleaning up ALL ${Z.length} orphaned branches (any age)`);else{let V=new Date;V.setDate(V.getDate()-Q),Z=Y.filter((j)=>j.lastCommitDate<V),this.logger.info(`\u26A0\uFE0F PR detection failed - only deleting branches older than ${Q} days`),this.logger.info(`\uD83D\uDD0D Found ${Z.length} stale buddy branches (older than ${Q} days)`)}if(Z.length>0){if(this.logger.info("\uD83D\uDCCB Sample of branches to delete:"),Z.slice(0,5).forEach((V)=>{let j=Math.floor((Date.now()-V.lastCommitDate.getTime())/86400000);this.logger.info(` - ${V.name} (${j} days old)`)}),Z.length>5)this.logger.info(` ... and ${Z.length-5} more`)}if(Z.length===0)return this.logger.info("\u2705 No branches to clean up!"),{deleted:[],failed:[]};let $=Z;if(X)return this.logger.info("\uD83D\uDD0D [DRY RUN] Would delete the following branches:"),$.forEach((V)=>{let j=Math.floor((Date.now()-V.lastCommitDate.getTime())/86400000);this.logger.info(` - ${V.name} (${j} days old, last commit: ${V.lastCommitDate.toISOString()})`)}),{deleted:$.map((V)=>V.name),failed:[]};let J=[],K=[];this.logger.info(`\uD83E\uDDF9 Cleaning up ${$.length} stale branches...`);let _=5;for(let V=0;V<$.length;V+=_){let j=$.slice(V,V+_),C=Math.floor(V/_)+1,M=Math.ceil($.length/_);this.logger.info(`\uD83D\uDD04 Processing batch ${C}/${M} (${j.length} branches)`);for(let G of j){try{await this.deleteBranch(G.name),J.push(G.name),this.logger.info(`\u2705 Deleted: ${G.name}`)}catch(H){K.push(G.name),this.logger.warn(`\u274C Failed to delete ${G.name}: ${x(H)}`)}await new Promise((H)=>setTimeout(H,200))}if(V+_<$.length)this.logger.info(`\u23F3 Waiting ${3} seconds before next batch...`),await new Promise((H)=>setTimeout(H,3000))}if(this.logger.info("\uD83C\uDF89 Cleanup complete!"),this.logger.info(` \u2705 Successfully deleted: ${J.length} branches`),this.logger.info(` \u274C Failed to delete: ${K.length} branches`),K.length>0)this.logger.info("\u274C Failed branches:"),K.forEach((V)=>this.logger.info(` - ${V}`));return{deleted:J,failed:K}}async apiRequest(Q,X,Y,Z=0){let[$,J]=Q.split(" "),K=`${this.apiUrl}${J}`,_=Y||this.token,V={method:$,headers:{Authorization:`Bearer ${_}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json","User-Agent":"buddy"}};if(X&&($==="POST"||$==="PATCH"||$==="PUT"))V.body=JSON.stringify(X);let j=await U(K,{...V,retries:Z,onRetry:({delayMs:C,reason:M})=>this.logger.info(`\u23F3 ${M} on ${$} ${J}, retrying in ${Math.round(C/1000)}s...`)});if(!j.ok){let C=await j.text(),M=_?"token present ([REDACTED])":"NO TOKEN \u2014 ensure GITHUB_TOKEN or BUDDY_TOKEN is set";throw new L(`GitHub API error: ${j.status} ${j.statusText}
32
+ }`,{threadId:X});if(Z.errors?.length)return this.logger.warn(`Could not resolve review thread: ${Z.errors.map(($)=>$.message).join("; ")}`),!1;return Boolean(Z.data?.resolveReviewThread?.thread?.isResolved)}catch(Z){return this.logger.warn(`Could not resolve review thread: ${G(Z)}`),!1}}async getPullRequestChecksState(Q){try{let Y=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/pulls/${Q}`)).head.sha,[Z,$]=await Promise.all([this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${Y}/status`),this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${Y}/check-runs?per_page=100`)]),J=$?.check_runs??[],K=(Z?.statuses?.length??0)>0;if(J.length===0&&!K)return"none";if(J.some((j)=>j.conclusion!==null&&["failure","cancelled","timed_out","action_required"].includes(j.conclusion))||Z?.state==="failure"||Z?.state==="error")return"failure";if(J.some((j)=>j.status!=="completed")||Z?.state==="pending")return"pending";return"success"}catch(X){return this.logger.warn(`\u26A0\uFE0F Could not read check state for PR #${Q}: ${G(X)}`),"pending"}}async graphqlRequest(Q,X){let Y=await U(`${this.apiUrl}/graphql`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json","User-Agent":"buddy"},body:JSON.stringify({query:Q,variables:X})});if(!Y.ok)throw new L(`GraphQL request failed: ${Y.status} ${Y.statusText}`,Y.status,"POST",`${this.apiUrl}/graphql`,`${this.owner}/${this.repo}`);return await Y.json()}async deleteBranch(Q){try{await this.runCommand("git",["push","origin","--delete",Q]),this.logger.info(`\u2705 Deleted branch ${Q} via git`)}catch(X){try{await this.runCommand("git",["branch","-D",Q])}catch{}if(/remote ref does not exist|unable to delete '[^']*': remote ref/i.test(G(X))){this.logger.info(`\u2139\uFE0F Branch ${Q} was already gone`);return}throw this.logger.warn(`\u26A0\uFE0F Failed to delete remote branch ${Q}: ${G(X)}`),X}}async getBuddyBranches(){try{let Q=await this.runCommand("git",["branch","-r","--format=%(refname:short) %(objectname) %(committerdate:iso8601)"]),X=[];for(let Y of Q.split(`
33
+ `)){let Z=Y.trim();if(!Z)continue;let $=Z.split(" ");if($.length<3)continue;let J=$[0],K=$[1],_=$.slice(2).join(" "),V=J.replace(/^origin\//,"");if(!V.startsWith("buddy/"))continue;try{let j=new Date(_);X.push({name:V,sha:K,lastCommitDate:j})}catch{this.logger.warn(`\u26A0\uFE0F Failed to parse date for branch ${V}: ${_}`),X.push({name:V,sha:K,lastCommitDate:new Date(0)})}}return this.logger.info(`\uD83D\uDD0D Found ${X.length} buddy branches using local git`),X}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to fetch buddy branches via git, falling back to API:",Q),this.getBuddyBranchesViaAPI()}}async getBuddyBranchesViaAPI(){try{let Q=[],X=1,Y=100;while(!0){let J=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/branches?per_page=${Y}&page=${X}`);if(!J||J.length===0)break;if(Q=Q.concat(J),J.length<Y)break;X++}this.logger.info(`\uD83D\uDD0D Found ${Q.length} total branches in repository`);let Z=Q.filter((J)=>J.name.startsWith("buddy/"));return this.logger.info(`\uD83E\uDD16 Found ${Z.length} buddy branches`),await Promise.all(Z.map(async(J)=>{try{let K=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${J.commit.sha}`);return{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(K.commit.committer.date)}}catch(K){return this.logger.warn(`\u26A0\uFE0F Failed to get commit info for branch ${J.name}: ${G(K)}`),{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(0)}}}))}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to fetch buddy branches:",Q),[]}}async getOrphanedBuddyBranches(){try{let Q=await this.getBuddyBranches(),X=await this.getOpenPRBranches();return Q.filter((Z)=>!X.has(Z.name))}catch(Q){return this.logger.warn("\u26A0\uFE0F Failed to identify orphaned branches:",Q),[]}}prDetectionSuccessful=!1;async getOpenPRBranches(){this.prDetectionSuccessful=!1;try{let Q=await this.getPullRequests("open"),X=new Set(Q.map((Y)=>Y.head).filter((Y)=>Y.startsWith("buddy/")));return this.logger.info(`\uD83D\uDD0D GitHub API reports ${Q.length} open PR(s); ${X.size} are buddy branches`),this.logger.info(`\uD83D\uDEE1\uFE0F Protecting ${X.size} branches with confirmed open PRs`),this.prDetectionSuccessful=!0,X}catch(Q){this.logger.warn("\u26A0\uFE0F Failed to fetch open PRs via API, falling back to age-based protection:",Q);try{let X=await this.getBuddyBranches(),Y=new Date;Y.setDate(Y.getDate()-30);let Z=new Set;for(let $ of X)if($.lastCommitDate>Y)Z.add($.name);return this.logger.info(`\uD83D\uDEE1\uFE0F Conservative fallback: protecting ${Z.size} branches newer than 30 days`),Z}catch{return this.logger.info("\u26A0\uFE0F Could not enumerate branches for age-based fallback"),new Set}}}async cleanupStaleBranches(Q=7,X=!1){this.logger.info("\uD83D\uDD0D Looking for buddy branches without open PRs...");let Y=await this.getOrphanedBuddyBranches();this.logger.info(`\uD83D\uDD0D Found ${Y.length} orphaned buddy branches (no associated open PRs)`);let Z=Y;if(this.prDetectionSuccessful)this.logger.info(`\uD83C\uDFAF PR detection successful - cleaning up ALL ${Z.length} orphaned branches (any age)`);else{let V=new Date;V.setDate(V.getDate()-Q),Z=Y.filter((j)=>j.lastCommitDate<V),this.logger.info(`\u26A0\uFE0F PR detection failed - only deleting branches older than ${Q} days`),this.logger.info(`\uD83D\uDD0D Found ${Z.length} stale buddy branches (older than ${Q} days)`)}if(Z.length>0){if(this.logger.info("\uD83D\uDCCB Sample of branches to delete:"),Z.slice(0,5).forEach((V)=>{let j=Math.floor((Date.now()-V.lastCommitDate.getTime())/86400000);this.logger.info(` - ${V.name} (${j} days old)`)}),Z.length>5)this.logger.info(` ... and ${Z.length-5} more`)}if(Z.length===0)return this.logger.info("\u2705 No branches to clean up!"),{deleted:[],failed:[]};let $=Z;if(X)return this.logger.info("\uD83D\uDD0D [DRY RUN] Would delete the following branches:"),$.forEach((V)=>{let j=Math.floor((Date.now()-V.lastCommitDate.getTime())/86400000);this.logger.info(` - ${V.name} (${j} days old, last commit: ${V.lastCommitDate.toISOString()})`)}),{deleted:$.map((V)=>V.name),failed:[]};let J=[],K=[];this.logger.info(`\uD83E\uDDF9 Cleaning up ${$.length} stale branches...`);let _=5;for(let V=0;V<$.length;V+=_){let j=$.slice(V,V+_),x=Math.floor(V/_)+1,M=Math.ceil($.length/_);this.logger.info(`\uD83D\uDD04 Processing batch ${x}/${M} (${j.length} branches)`);for(let H of j){try{await this.deleteBranch(H.name),J.push(H.name),this.logger.info(`\u2705 Deleted: ${H.name}`)}catch(z){K.push(H.name),this.logger.warn(`\u274C Failed to delete ${H.name}: ${G(z)}`)}await new Promise((z)=>setTimeout(z,200))}if(V+_<$.length)this.logger.info(`\u23F3 Waiting ${3} seconds before next batch...`),await new Promise((z)=>setTimeout(z,3000))}if(this.logger.info("\uD83C\uDF89 Cleanup complete!"),this.logger.info(` \u2705 Successfully deleted: ${J.length} branches`),this.logger.info(` \u274C Failed to delete: ${K.length} branches`),K.length>0)this.logger.info("\u274C Failed branches:"),K.forEach((V)=>this.logger.info(` - ${V}`));return{deleted:J,failed:K}}async apiRequest(Q,X,Y,Z=0){let[$,J]=Q.split(" "),K=`${this.apiUrl}${J}`,_=Y||this.token,V={method:$,headers:{Authorization:`Bearer ${_}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json","User-Agent":"buddy"}};if(X&&($==="POST"||$==="PATCH"||$==="PUT"))V.body=JSON.stringify(X);let j=await U(K,{...V,retries:Z,onRetry:({delayMs:x,reason:M})=>this.logger.info(`\u23F3 ${M} on ${$} ${J}, retrying in ${Math.round(x/1000)}s...`)});if(!j.ok){let x=await j.text(),M=_?"token present ([REDACTED])":"NO TOKEN \u2014 ensure GITHUB_TOKEN or BUDDY_TOKEN is set";throw new L(`GitHub API error: ${j.status} ${j.statusText}
34
34
  URL: ${$} ${K}
35
35
  Auth: ${M}
36
36
  Repo: ${this.owner}/${this.repo}
37
- ${C}`,j.status,$,K,`${this.owner}/${this.repo}`,C)}if(j.headers.get("content-type")?.includes("application/json"))return j.json();return j.text()}async apiRequestWithRetry(Q,X,Y=3){return this.apiRequest(Q,X,void 0,Math.max(0,Y-1))}async createIssue(Q){this.cache.issues.clear();try{let X=await this.apiRequestWithRetry(`POST /repos/${this.owner}/${this.repo}/issues`,{title:Q.title,body:Q.body,assignees:Q.assignees||[],labels:Q.labels||[],milestone:Q.milestone});return this.logger.info(`\u2705 Created issue #${X.number}: ${Q.title}`),{number:X.number,title:X.title,body:X.body,state:X.state,url:X.html_url,createdAt:new Date(X.created_at),updatedAt:new Date(X.updated_at),closedAt:X.closed_at?new Date(X.closed_at):void 0,author:X.user.login,assignees:X.assignees?.map((Y)=>Y.login)||[],labels:X.labels?.map((Y)=>typeof Y==="string"?Y:Y.name)||[],pinned:!1}}catch(X){throw this.logger.error(`\u274C Failed to create issue: ${Q.title}: ${x(X)}`),X}}async getIssues(Q="open"){let X=`${Q}`,Y=this.cache.issues.get(X);if(Y&&this.isCacheValid(Y.timestamp))return this.logger.info(`\uD83D\uDCE6 Using cached issues (state: ${Q}, ${Y.data.length} issues)`),Y.data;try{let J=[];for(let _=1;_<=20;_++){let V=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/issues?state=${Q}&sort=updated&direction=desc&per_page=100&page=${_}`);if(!Array.isArray(V)||V.length===0)break;if(J.push(...V),V.length<100)break}let K=J.filter((_)=>!_.pull_request).map((_)=>({number:_.number,title:_.title,body:_.body||"",state:_.state,url:_.html_url,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),closedAt:_.closed_at?new Date(_.closed_at):void 0,author:_.user.login,assignees:_.assignees?.map((V)=>V.login)||[],labels:_.labels?.map((V)=>typeof V==="string"?V:V.name)||[],pinned:!1}));return this.cache.issues.set(X,{data:K,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${K.length} issues (state: ${Q})`),K}catch(Z){throw this.logger.error("\u274C Failed to get issues:",Z),Z}}async updateIssue(Q,X){this.cache.issues.clear();try{let Y={};if(X.title!==void 0)Y.title=X.title;if(X.body!==void 0)Y.body=X.body;if(X.assignees!==void 0)Y.assignees=X.assignees;if(X.labels!==void 0)Y.labels=X.labels;if(X.milestone!==void 0)Y.milestone=X.milestone;let Z=await this.apiRequestWithRetry(`PATCH /repos/${this.owner}/${this.repo}/issues/${Q}`,Y);return this.logger.info(`\u2705 Updated issue #${Q}: ${Z.title}`),{number:Z.number,title:Z.title,body:Z.body,state:Z.state,url:Z.html_url,createdAt:new Date(Z.created_at),updatedAt:new Date(Z.updated_at),closedAt:Z.closed_at?new Date(Z.closed_at):void 0,author:Z.user.login,assignees:Z.assignees?.map(($)=>$.login)||[],labels:Z.labels?.map(($)=>typeof $==="string"?$:$.name)||[],pinned:!1}}catch(Y){throw this.logger.error(`\u274C Failed to update issue #${Q}: ${x(Y)}`),Y}}async closeIssue(Q){this.cache.issues.clear();try{await this.apiRequestWithRetry(`PATCH /repos/${this.owner}/${this.repo}/issues/${Q}`,{state:"closed"}),this.logger.info(`\u2705 Closed issue #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to close issue #${Q}: ${x(X)}`),X}}async pinIssue(Q){return await this.setIssuePinned(Q,!0)}async unpinIssue(Q){return await this.setIssuePinned(Q,!1)}async setIssuePinned(Q,X){let Y=X?"pin":"unpin";try{let Z=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/issues/${Q}`),$=X?"mutation($issueId: ID!) { pinIssue(input: { issueId: $issueId }) { issue { number } } }":"mutation($issueId: ID!) { unpinIssue(input: { issueId: $issueId }) { issue { number } } }",J=await this.graphqlRequest($,{issueId:Z.node_id});if(J.errors?.length){let K=J.errors.map((_)=>_.message).join("; ");return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${K}`),!1}return this.logger.info(`\uD83D\uDCCC ${X?"Pinned":"Unpinned"} issue #${Q}`),!0}catch(Z){return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${x(Z)}`),!1}}}
38
- export{N as Jc};
37
+ ${x}`,j.status,$,K,`${this.owner}/${this.repo}`,x)}if(j.headers.get("content-type")?.includes("application/json"))return j.json();return j.text()}async apiRequestWithRetry(Q,X,Y=3){return this.apiRequest(Q,X,void 0,Math.max(0,Y-1))}async createIssue(Q){this.cache.issues.clear();try{let X=await this.apiRequestWithRetry(`POST /repos/${this.owner}/${this.repo}/issues`,{title:Q.title,body:Q.body,assignees:Q.assignees||[],labels:Q.labels||[],milestone:Q.milestone});return this.logger.info(`\u2705 Created issue #${X.number}: ${Q.title}`),{number:X.number,title:X.title,body:X.body,state:X.state,url:X.html_url,createdAt:new Date(X.created_at),updatedAt:new Date(X.updated_at),closedAt:X.closed_at?new Date(X.closed_at):void 0,author:X.user.login,assignees:X.assignees?.map((Y)=>Y.login)||[],labels:X.labels?.map((Y)=>typeof Y==="string"?Y:Y.name)||[],pinned:!1}}catch(X){throw this.logger.error(`\u274C Failed to create issue: ${Q.title}: ${G(X)}`),X}}async getIssues(Q="open"){let X=`${Q}`,Y=this.cache.issues.get(X);if(Y&&this.isCacheValid(Y.timestamp))return this.logger.info(`\uD83D\uDCE6 Using cached issues (state: ${Q}, ${Y.data.length} issues)`),Y.data;try{let J=[];for(let _=1;_<=20;_++){let V=await this.apiRequestWithRetry(`GET /repos/${this.owner}/${this.repo}/issues?state=${Q}&sort=updated&direction=desc&per_page=100&page=${_}`);if(!Array.isArray(V)||V.length===0)break;if(J.push(...V),V.length<100)break}let K=J.filter((_)=>!_.pull_request).map((_)=>({number:_.number,title:_.title,body:_.body||"",state:_.state,url:_.html_url,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),closedAt:_.closed_at?new Date(_.closed_at):void 0,author:_.user.login,assignees:_.assignees?.map((V)=>V.login)||[],labels:_.labels?.map((V)=>typeof V==="string"?V:V.name)||[],pinned:!1}));return this.cache.issues.set(X,{data:K,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${K.length} issues (state: ${Q})`),K}catch(Z){throw this.logger.error("\u274C Failed to get issues:",Z),Z}}async updateIssue(Q,X){this.cache.issues.clear();try{let Y={};if(X.title!==void 0)Y.title=X.title;if(X.body!==void 0)Y.body=X.body;if(X.assignees!==void 0)Y.assignees=X.assignees;if(X.labels!==void 0)Y.labels=X.labels;if(X.milestone!==void 0)Y.milestone=X.milestone;let Z=await this.apiRequestWithRetry(`PATCH /repos/${this.owner}/${this.repo}/issues/${Q}`,Y);return this.logger.info(`\u2705 Updated issue #${Q}: ${Z.title}`),{number:Z.number,title:Z.title,body:Z.body,state:Z.state,url:Z.html_url,createdAt:new Date(Z.created_at),updatedAt:new Date(Z.updated_at),closedAt:Z.closed_at?new Date(Z.closed_at):void 0,author:Z.user.login,assignees:Z.assignees?.map(($)=>$.login)||[],labels:Z.labels?.map(($)=>typeof $==="string"?$:$.name)||[],pinned:!1}}catch(Y){throw this.logger.error(`\u274C Failed to update issue #${Q}: ${G(Y)}`),Y}}async closeIssue(Q){this.cache.issues.clear();try{await this.apiRequestWithRetry(`PATCH /repos/${this.owner}/${this.repo}/issues/${Q}`,{state:"closed"}),this.logger.info(`\u2705 Closed issue #${Q}`)}catch(X){throw this.logger.error(`\u274C Failed to close issue #${Q}: ${G(X)}`),X}}async pinIssue(Q){return await this.setIssuePinned(Q,!0)}async unpinIssue(Q){return await this.setIssuePinned(Q,!1)}async setIssuePinned(Q,X){let Y=X?"pin":"unpin";try{let Z=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/issues/${Q}`),$=X?"mutation($issueId: ID!) { pinIssue(input: { issueId: $issueId }) { issue { number } } }":"mutation($issueId: ID!) { unpinIssue(input: { issueId: $issueId }) { issue { number } } }",J=await this.graphqlRequest($,{issueId:Z.node_id});if(J.errors?.length){let K=J.errors.map((_)=>_.message).join("; ");return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${K}`),!1}return this.logger.info(`\uD83D\uDCCC ${X?"Pinned":"Unpinned"} issue #${Q}`),!0}catch(Z){return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${G(Z)}`),!1}}}
38
+ export{k as Jc,f as Kc,h as Lc};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var j=Object.create;var{getPrototypeOf:k,defineProperty:i,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,q=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?j(k(a)):{};let c=b||!a||!a.__esModule?i(d,"default",{value:a,enumerable:!0}):d;for(let e of l(a))if(!m.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0});if(f)g.set(a,c);return c};var r=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var s=import.meta.require;
3
- export{q as Uk,r as Vk,s as Wk};
3
+ export{q as $k,r as al,s as bl};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{execSync as h}from"child_process";import{existsSync as P,mkdirSync as F,mkdtempSync as L,rmSync as V,writeFileSync as U}from"fs";import{tmpdir as G}from"os";import{join as w}from"path";var i=new Set,A=!1;function q(){if(A)return;A=!0;let a=()=>{for(let e of i)try{h(`pantry stop ${e}`,{stdio:"ignore",timeout:1e4})}catch{}i.clear()};process.on("exit",a),process.on("SIGINT",()=>{a(),process.exit(130)}),process.on("SIGTERM",()=>{a(),process.exit(143)})}function o(a,e=!1){let s={encoding:"utf-8",timeout:30000,stdio:e?"pipe":["pipe","pipe","pipe"]};return h(`pantry ${a}`,s)}function O(a){let e=a.match(/Name:\s+(\S+)/)?.[1]??"",s=/Status:\s+running/i.test(a),t=a.match(/Port:\s+(\d+)/),r=a.match(/PID:\s+(\d+)/),S=a.match(/Data Dir:\s+(.+)/);return{name:e,running:s,port:t?Number.parseInt(t[1],10):null,pid:r?Number.parseInt(r[1],10):null,dataDir:S?S[1].trim():null}}class n{config;_startedByUs=!1;constructor(a){this.config={name:a.name,port:a.port??0,readyTimeoutMs:a.readyTimeoutMs??15000,pollIntervalMs:a.pollIntervalMs??200,quiet:a.quiet??!0}}static isAvailable(){try{return h("pantry --version",{stdio:"ignore",timeout:5000}),!0}catch{return!1}}status(){try{let a=o(`inspect ${this.config.name}`,!0);return O(a)}catch{return{name:this.config.name,running:!1,port:null,pid:null,dataDir:null}}}isRunning(){return this.status().running}getPort(){return this.status().port}async start(){if(q(),this.isRunning())return this.status();return o(`start ${this.config.name}`,this.config.quiet),this._startedByUs=!0,i.add(this.config.name),await this.waitReady(),this.status()}async stop(){if(!this._startedByUs)return;try{o(`stop ${this.config.name}`,this.config.quiet)}catch{}i.delete(this.config.name),this._startedByUs=!1}async forceStop(){try{o(`stop ${this.config.name}`,this.config.quiet)}catch{}i.delete(this.config.name),this._startedByUs=!1}async ensureRunning(){if(this.isRunning())return this.status();return this.start()}async waitReady(){let a=Date.now()+this.config.readyTimeoutMs;while(Date.now()<a){if(this.isRunning())return;await new Promise((e)=>setTimeout(e,this.config.pollIntervalMs))}throw Error(`Service '${this.config.name}' did not become ready within ${this.config.readyTimeoutMs}ms`)}}var v=new n({name:"mysql"});async function c(a){let e=await v.ensureRunning();return{port:a?.port??e.port??3306,host:a?.host??"localhost",database:a?.database??"test",username:a?.username??"root"}}async function u(){await v.stop()}function I(a){let e=null;return{get connection(){if(!e)throw Error("MySQL not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await c(a)},afterAll:async()=>{await u(),e=null}}}async function D(a,e){let s=await c(e);try{return await a(s)}finally{if(e?.stopAfter!==!1)await u()}}var R=new n({name:"postgres"});async function p(a){let e=await R.ensureRunning();return{port:a?.port??e.port??5432,host:a?.host??"localhost",database:a?.database??"postgres",username:a?.username??process.env.USER??"postgres"}}async function g(){await R.stop()}function T(a){let e=null;return{get connection(){if(!e)throw Error("Postgres not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await p(a)},afterAll:async()=>{await g(),e=null}}}async function C(a,e){let s=await p(e);try{return await a(s)}finally{if(e?.stopAfter!==!1)await g()}}var M=new n({name:"redis"});async function f(a){let e=await M.ensureRunning(),s=a?.port??e.port??6379,t=a?.host??"localhost";return{port:s,host:t,url:`redis://${t}:${s}`}}async function d(){await M.stop()}function E(a){let e=null;return{get connection(){if(!e)throw Error("Redis not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await f(a)},afterAll:async()=>{await d(),e=null}}}async function b(a,e){let s=await f(e);try{return await a(s)}finally{if(e?.stopAfter!==!1)await d()}}var l=new Set,k=!1;function H(){if(k)return;k=!0;let a=()=>{for(let e of l)try{if(P(e))V(e,{recursive:!0,force:!0})}catch{}l.clear()};process.on("exit",a),process.on("SIGINT",()=>{a(),process.exit(130)}),process.on("SIGTERM",()=>{a(),process.exit(143)})}function m(a="pantry-test-"){H();let e=L(w(G(),a));return l.add(e),e}function y(a){l.delete(a);try{if(P(a))V(a,{recursive:!0,force:!0})}catch{}}async function N(a,e){let s=m(a);try{return await e(s)}finally{y(s)}}function x(a,e){let s=m(a);try{return e(s)}finally{y(s)}}function _(a,e,s){let t=w(a,e),r=t.substring(0,t.lastIndexOf("/"));if(r&&!P(r))F(r,{recursive:!0});return U(t,s),t}function B(a,e){let s=w(a,e);return F(s,{recursive:!0}),s}var $={createTempDir:m,createTestDir:B,createTestFile:_,PantryService:n,removeTempDir:y,startMysql:c,startPostgres:p,startRedis:f,stopMysql:u,stopPostgres:g,stopRedis:d,useMysql:I,usePostgres:T,useRedis:E,withMysql:D,withPostgres:C,withRedis:b,withTempDir:N,withTempDirSync:x};export{n as ug,c as vg,u as wg,I as xg,D as yg,p as zg,g as Ag,T as Bg,C as Cg,f as Dg,d as Eg,E as Fg,b as Gg,m as Hg,y as Ig,N as Jg,x as Kg,_ as Lg,B as Mg,$ as Ng};
2
+ import{execSync as h}from"child_process";import{existsSync as P,mkdirSync as F,mkdtempSync as L,rmSync as V,writeFileSync as U}from"fs";import{tmpdir as G}from"os";import{join as w}from"path";var i=new Set,A=!1;function q(){if(A)return;A=!0;let a=()=>{for(let e of i)try{h(`pantry stop ${e}`,{stdio:"ignore",timeout:1e4})}catch{}i.clear()};process.on("exit",a),process.on("SIGINT",()=>{a(),process.exit(130)}),process.on("SIGTERM",()=>{a(),process.exit(143)})}function o(a,e=!1){let s={encoding:"utf-8",timeout:30000,stdio:e?"pipe":["pipe","pipe","pipe"]};return h(`pantry ${a}`,s)}function O(a){let e=a.match(/Name:\s+(\S+)/)?.[1]??"",s=/Status:\s+running/i.test(a),t=a.match(/Port:\s+(\d+)/),r=a.match(/PID:\s+(\d+)/),S=a.match(/Data Dir:\s+(.+)/);return{name:e,running:s,port:t?Number.parseInt(t[1],10):null,pid:r?Number.parseInt(r[1],10):null,dataDir:S?S[1].trim():null}}class n{config;_startedByUs=!1;constructor(a){this.config={name:a.name,port:a.port??0,readyTimeoutMs:a.readyTimeoutMs??15000,pollIntervalMs:a.pollIntervalMs??200,quiet:a.quiet??!0}}static isAvailable(){try{return h("pantry --version",{stdio:"ignore",timeout:5000}),!0}catch{return!1}}status(){try{let a=o(`inspect ${this.config.name}`,!0);return O(a)}catch{return{name:this.config.name,running:!1,port:null,pid:null,dataDir:null}}}isRunning(){return this.status().running}getPort(){return this.status().port}async start(){if(q(),this.isRunning())return this.status();return o(`start ${this.config.name}`,this.config.quiet),this._startedByUs=!0,i.add(this.config.name),await this.waitReady(),this.status()}async stop(){if(!this._startedByUs)return;try{o(`stop ${this.config.name}`,this.config.quiet)}catch{}i.delete(this.config.name),this._startedByUs=!1}async forceStop(){try{o(`stop ${this.config.name}`,this.config.quiet)}catch{}i.delete(this.config.name),this._startedByUs=!1}async ensureRunning(){if(this.isRunning())return this.status();return this.start()}async waitReady(){let a=Date.now()+this.config.readyTimeoutMs;while(Date.now()<a){if(this.isRunning())return;await new Promise((e)=>setTimeout(e,this.config.pollIntervalMs))}throw Error(`Service '${this.config.name}' did not become ready within ${this.config.readyTimeoutMs}ms`)}}var v=new n({name:"mysql"});async function c(a){let e=await v.ensureRunning();return{port:a?.port??e.port??3306,host:a?.host??"localhost",database:a?.database??"test",username:a?.username??"root"}}async function u(){await v.stop()}function I(a){let e=null;return{get connection(){if(!e)throw Error("MySQL not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await c(a)},afterAll:async()=>{await u(),e=null}}}async function D(a,e){let s=await c(e);try{return await a(s)}finally{if(e?.stopAfter!==!1)await u()}}var R=new n({name:"postgres"});async function p(a){let e=await R.ensureRunning();return{port:a?.port??e.port??5432,host:a?.host??"localhost",database:a?.database??"postgres",username:a?.username??process.env.USER??"postgres"}}async function g(){await R.stop()}function T(a){let e=null;return{get connection(){if(!e)throw Error("Postgres not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await p(a)},afterAll:async()=>{await g(),e=null}}}async function C(a,e){let s=await p(e);try{return await a(s)}finally{if(e?.stopAfter!==!1)await g()}}var M=new n({name:"redis"});async function f(a){let e=await M.ensureRunning(),s=a?.port??e.port??6379,t=a?.host??"localhost";return{port:s,host:t,url:`redis://${t}:${s}`}}async function d(){await M.stop()}function E(a){let e=null;return{get connection(){if(!e)throw Error("Redis not started. Ensure beforeAll has run.");return e},beforeAll:async()=>{e=await f(a)},afterAll:async()=>{await d(),e=null}}}async function b(a,e){let s=await f(e);try{return await a(s)}finally{if(e?.stopAfter!==!1)await d()}}var l=new Set,k=!1;function H(){if(k)return;k=!0;let a=()=>{for(let e of l)try{if(P(e))V(e,{recursive:!0,force:!0})}catch{}l.clear()};process.on("exit",a),process.on("SIGINT",()=>{a(),process.exit(130)}),process.on("SIGTERM",()=>{a(),process.exit(143)})}function m(a="pantry-test-"){H();let e=L(w(G(),a));return l.add(e),e}function y(a){l.delete(a);try{if(P(a))V(a,{recursive:!0,force:!0})}catch{}}async function N(a,e){let s=m(a);try{return await e(s)}finally{y(s)}}function x(a,e){let s=m(a);try{return e(s)}finally{y(s)}}function _(a,e,s){let t=w(a,e),r=t.substring(0,t.lastIndexOf("/"));if(r&&!P(r))F(r,{recursive:!0});return U(t,s),t}function B(a,e){let s=w(a,e);return F(s,{recursive:!0}),s}var $={createTempDir:m,createTestDir:B,createTestFile:_,PantryService:n,removeTempDir:y,startMysql:c,startPostgres:p,startRedis:f,stopMysql:u,stopPostgres:g,stopRedis:d,useMysql:I,usePostgres:T,useRedis:E,withMysql:D,withPostgres:C,withRedis:b,withTempDir:N,withTempDirSync:x};export{n as Bg,c as Cg,u as Dg,I as Eg,D as Fg,p as Gg,g as Hg,T as Ig,C as Jg,f as Kg,d as Lg,E as Mg,b as Ng,m as Og,y as Pg,N as Qg,x as Rg,_ as Sg,B as Tg,$ as Ug};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ec as Z}from"./chunk-tjc2vgwn.js";import{Sc as X}from"./chunk-cs066zt9.js";import{Nd as x,_d as V}from"./chunk-nrr8z2z7.js";import{he as U,ie as Y}from"./chunk-5av2vnvv.js";import H from"process";var K=[["actionlint","actionlint"],["shellcheck","shellcheck"],["hadolint","hadolint"],["markdownlint","markdownlint"]];async function T(j,J={}){let W=J.env??H.env,Q=J.cwd??H.cwd(),F=J.hasCommand??x,G=[];G.push({name:"bun",status:"ok",detail:`Bun ${Bun.version}`});let C=await Bun.file(`${Q}/.git/HEAD`).exists();G.push(C?{name:"git repository",status:"ok",detail:Q}:{name:"git repository",status:"fail",detail:`${Q} is not a git repository`,remediation:"Run buddy from inside a repository, or run `git init`."});let $=X(j);G.push($.length===0?{name:"configuration",status:"ok",detail:"valid"}:{name:"configuration",status:"fail",detail:`${$.length} problem(s): ${$.slice(0,3).map((q)=>`${q.path} ${q.message}`).join("; ")}`,remediation:"Fix the paths reported above in buddy.config.ts."});let P=Boolean(j.repository?.owner&&j.repository.name);G.push(P?{name:"repository config",status:"ok",detail:`${j.repository.owner}/${j.repository.name}`}:{name:"repository config",status:"warn",detail:"owner and name are not set",remediation:"Set repository.owner and repository.name, or run in Actions where GITHUB_REPOSITORY is available. Local review works without them."});let B=j.repository?.provider??"github",D=j.repository?.token?{token:j.repository.token,source:"repository.token"}:Y(B,W);G.push(D?{name:"git token",status:"ok",detail:`found in ${D.source}`}:{name:"git token",status:"warn",detail:"no token found",remediation:`Set one of ${(U[B]??[]).join(", ")}. Local review does not need one.`});let b=Z(j,W);G.push(b?{name:"ai provider",status:"ok",detail:`${b.provider} via ${b.apiKeyEnv}`}:{name:"ai provider",status:"warn",detail:"no API key found",remediation:"Set ANTHROPIC_API_KEY (or OPENAI_API_KEY / GOOGLE_API_KEY). Dependency updates and static analysis work without one."});for(let[q,M]of K){let I=await F(M);G.push(I?{name:`analyzer: ${q}`,status:"ok",detail:`${M} found`}:{name:`analyzer: ${q}`,status:"warn",detail:`${M} not installed`,remediation:`Install ${M} to enable the ${q} analyzer. Reviews run without it and report it as skipped.`})}let w=V.filter((q)=>!K.some(([M])=>M===q.name)).map((q)=>q.name);return G.push({name:"native analyzers",status:"ok",detail:`${w.join(", ")} \u2014 always available`}),{checks:G,healthy:!G.some((q)=>q.status==="fail")}}var S={ok:"\u2705",warn:"\u26A0\uFE0F ",fail:"\u274C"};function E(j){let J=["","Buddy environment",""];for(let F of j.checks)if(J.push(`${S[F.status]} ${F.name}: ${F.detail}`),F.remediation)J.push(` \u2192 ${F.remediation}`);let W=j.checks.filter((F)=>F.status==="fail").length,Q=j.checks.filter((F)=>F.status==="warn").length;return J.push(""),J.push(j.healthy?`Ready. ${Q} optional capability/capabilities unavailable.`:`${W} problem(s) must be fixed before buddy can run.`),`${J.join(`
2
+ import{ec as Z}from"./chunk-e6wny1pp.js";import{Wc as X}from"./chunk-ej7gpg23.js";import{Rd as x,ce as V}from"./chunk-k53ndvfv.js";import{le as U,me as Y}from"./chunk-3nygvd78.js";import H from"process";var K=[["actionlint","actionlint"],["shellcheck","shellcheck"],["hadolint","hadolint"],["markdownlint","markdownlint"]];async function T(j,J={}){let W=J.env??H.env,Q=J.cwd??H.cwd(),F=J.hasCommand??x,G=[];G.push({name:"bun",status:"ok",detail:`Bun ${Bun.version}`});let C=await Bun.file(`${Q}/.git/HEAD`).exists();G.push(C?{name:"git repository",status:"ok",detail:Q}:{name:"git repository",status:"fail",detail:`${Q} is not a git repository`,remediation:"Run buddy from inside a repository, or run `git init`."});let $=X(j);G.push($.length===0?{name:"configuration",status:"ok",detail:"valid"}:{name:"configuration",status:"fail",detail:`${$.length} problem(s): ${$.slice(0,3).map((q)=>`${q.path} ${q.message}`).join("; ")}`,remediation:"Fix the paths reported above in buddy.config.ts."});let P=Boolean(j.repository?.owner&&j.repository.name);G.push(P?{name:"repository config",status:"ok",detail:`${j.repository.owner}/${j.repository.name}`}:{name:"repository config",status:"warn",detail:"owner and name are not set",remediation:"Set repository.owner and repository.name, or run in Actions where GITHUB_REPOSITORY is available. Local review works without them."});let B=j.repository?.provider??"github",D=j.repository?.token?{token:j.repository.token,source:"repository.token"}:Y(B,W);G.push(D?{name:"git token",status:"ok",detail:`found in ${D.source}`}:{name:"git token",status:"warn",detail:"no token found",remediation:`Set one of ${(U[B]??[]).join(", ")}. Local review does not need one.`});let b=Z(j,W);G.push(b?{name:"ai provider",status:"ok",detail:`${b.provider} via ${b.apiKeyEnv}`}:{name:"ai provider",status:"warn",detail:"no API key found",remediation:"Set ANTHROPIC_API_KEY (or OPENAI_API_KEY / GOOGLE_API_KEY). Dependency updates and static analysis work without one."});for(let[q,M]of K){let I=await F(M);G.push(I?{name:`analyzer: ${q}`,status:"ok",detail:`${M} found`}:{name:`analyzer: ${q}`,status:"warn",detail:`${M} not installed`,remediation:`Install ${M} to enable the ${q} analyzer. Reviews run without it and report it as skipped.`})}let w=V.filter((q)=>!K.some(([M])=>M===q.name)).map((q)=>q.name);return G.push({name:"native analyzers",status:"ok",detail:`${w.join(", ")} \u2014 always available`}),{checks:G,healthy:!G.some((q)=>q.status==="fail")}}var S={ok:"\u2705",warn:"\u26A0\uFE0F ",fail:"\u274C"};function E(j){let J=["","Buddy environment",""];for(let F of j.checks)if(J.push(`${S[F.status]} ${F.name}: ${F.detail}`),F.remediation)J.push(` \u2192 ${F.remediation}`);let W=j.checks.filter((F)=>F.status==="fail").length,Q=j.checks.filter((F)=>F.status==="warn").length;return J.push(""),J.push(j.healthy?`Ready. ${Q} optional capability/capabilities unavailable.`:`${W} problem(s) must be fixed before buddy can run.`),`${J.join(`
3
3
  `)}
4
4
  `}
5
5
  export{T as W,E as X};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var c=new Set(["bower_components","node_modules","pantry","ts-pantry","vendor"]),f=new Set([".cache",".idea",".next",".nuxt",".nyc_output",".vscode","build","coverage","dist","temp","tmp"]);function g(b){return b.startsWith(".")||c.has(b)||f.has(b)}
3
- export{g as gd};
3
+ export{g as kd};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import"./chunk-q4t568hv.js";function f(i){return JSON.stringify({ok:!i.failed,summary:{workflows:i.workflows.length,findings:i.findings.length,errors:i.findings.filter((n)=>n.severity==="error").length,warnings:i.findings.filter((n)=>n.severity==="warning").length,info:i.findings.filter((n)=>n.severity==="info").length},findings:i.findings},null,2)}export{f as formatJson};
2
+ import"./chunk-4sqwtry6.js";function f(i){return JSON.stringify({ok:!i.failed,summary:{workflows:i.workflows.length,findings:i.findings.length,errors:i.findings.filter((n)=>n.severity==="error").length,warnings:i.findings.filter((n)=>n.severity==="warning").length,info:i.findings.filter((n)=>n.severity==="info").length},findings:i.findings},null,2)}export{f as formatJson};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Aa as d,Ba as e,Ca as f,xa as a,ya as b,za as c}from"./chunk-3cvng2nz.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{b as productFor,f as describeEol,c as cycleFor,d as checkEol,e as EOL_WARNING_DAYS,a as EOL_PRODUCTS};
2
+ import{Aa as d,Ba as e,Ca as f,xa as a,ya as b,za as c}from"./chunk-rp3ytb19.js";import"./chunk-b4a5gw9c.js";import"./chunk-bprmzg0p.js";import"./chunk-4sqwtry6.js";export{b as productFor,f as describeEol,c as cycleFor,d as checkEol,e as EOL_WARNING_DAYS,a as EOL_PRODUCTS};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Va as t,Wa as u}from"./chunk-s6z3gm2s.js";import{$a as z,Xa as v,Ya as w,Za as x,_a as y,ab as A,bb as B,cb as C,db as D,eb as E,fb as F,gb as G}from"./chunk-s4zb0fcj.js";import{hb as H,ib as I,jb as J,kb as K,lb as L}from"./chunk-tw047td6.js";import"./chunk-rc2mk5x6.js";import"./chunk-tjc2vgwn.js";import{qf as a,rf as b,sf as c,tf as d,uf as e,vf as f}from"./chunk-08x5b93v.js";import{Af as k,Bf as l,Cf as m,Df as n,Ef as o,Ff as p,Gf as q,Hf as r,If as s,wf as g,xf as h,yf as i,zf as j}from"./chunk-p6qbqsyp.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-c8rzx3a1.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{i as writeFileTool,r as wrapUntrusted,F as withTouchOffer,I as verifyChanges,w as unitTestsTouch,J as stackedBranchName,y as simplifyTouch,n as shellTool,K as runStackedTouch,u as runPlan,s as runAgent,a as reviewMode,g as resolveWorkspacePath,D as renderTouchOffer,h as readFileTool,z as planTouch,d as planMode,G as parseTouchSelections,j as listDirTool,b as implementMode,E as hasTouchOffer,B as getFinishingTouch,f as getAgentMode,k as fsTools,c as fixCiMode,v as docstringsTouch,L as detectChangedFiles,t as createReadIssueTool,m as buildShellEnv,x as autofixTouch,q as Toolbelt,o as ToolPermissionError,C as TOUCH_OFFER_MARKER,H as TEST_COMMANDS,l as SHELL_ENV_ALLOWLIST,A as FINISHING_TOUCHES,p as BUILTIN_TOOLS,e as AGENT_MODES};
2
+ import{Va as t,Wa as u}from"./chunk-zhfrmseh.js";import{$a as z,Xa as v,Ya as w,Za as x,_a as y,ab as A,bb as B,cb as C,db as D,eb as E,fb as F,gb as G}from"./chunk-wsxy4w86.js";import{hb as H,ib as I,jb as J,kb as K,lb as L}from"./chunk-tvrz1xp5.js";import"./chunk-bxdbf2kj.js";import"./chunk-e6wny1pp.js";import{Af as d,Bf as e,Cf as f,xf as a,yf as b,zf as c}from"./chunk-ffb50kwa.js";import{Df as g,Ef as h,Ff as i,Gf as j,Hf as k,If as l,Jf as m,Kf as n,Lf as o,Mf as p,Nf as q,Of as r,Pf as s}from"./chunk-47ancrn1.js";import"./chunk-yj6xx2b8.js";import"./chunk-f7aw9cr3.js";import"./chunk-kypdeb29.js";import"./chunk-b4a5gw9c.js";import"./chunk-bprmzg0p.js";import"./chunk-4sqwtry6.js";export{i as writeFileTool,r as wrapUntrusted,F as withTouchOffer,I as verifyChanges,w as unitTestsTouch,J as stackedBranchName,y as simplifyTouch,n as shellTool,K as runStackedTouch,u as runPlan,s as runAgent,a as reviewMode,g as resolveWorkspacePath,D as renderTouchOffer,h as readFileTool,z as planTouch,d as planMode,G as parseTouchSelections,j as listDirTool,b as implementMode,E as hasTouchOffer,B as getFinishingTouch,f as getAgentMode,k as fsTools,c as fixCiMode,v as docstringsTouch,L as detectChangedFiles,t as createReadIssueTool,m as buildShellEnv,x as autofixTouch,q as Toolbelt,o as ToolPermissionError,C as TOUCH_OFFER_MARKER,H as TEST_COMMANDS,l as SHELL_ENV_ALLOWLIST,A as FINISHING_TOUCHES,p as BUILTIN_TOOLS,e as AGENT_MODES};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{zh as P}from"./chunk-e68nf7cm.js";import{Ch as M,Fh as Q}from"./chunk-hfjywbbc.js";function V(z){if(z==="running")return"in_progress";if(z==="success"||z==="failed"||z==="canceled"||z==="skipped"||z==="manual")return"completed";return"queued"}function X(z){switch(z){case"success":return"success";case"failed":return"failure";case"canceled":return"cancelled";case"skipped":case"manual":return"skipped";default:return null}}class Y{token;apiUrl;logger;projectId;constructor(z,A,F,G,H){this.token=z;this.apiUrl=(G??"https://gitlab.com/api/v4").replace(/\/+$/,""),this.logger=H??Q(),this.projectId=encodeURIComponent(`${A}/${F}`)}capabilities(){return{pinIssues:!1,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!1,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}async request(z,A,F,G={}){let H=await P(`${this.apiUrl}${A}`,{method:z,headers:{"PRIVATE-TOKEN":this.token,Accept:G.raw?"text/plain":"application/json","User-Agent":"buddy",...F?{"Content-Type":"application/json"}:{}},...F?{body:JSON.stringify(F)}:{}});if(!H.ok){let K=await H.text().catch(()=>"");throw Error(`GitLab ${z} ${A} failed: ${H.status} ${K.slice(0,200)}`)}let J=await H.text();if(G.raw)return J;return J.trim()?JSON.parse(J):void 0}async optional(z,A,F={}){try{return await this.request(z,A,void 0,F)}catch(G){if(String(G).includes("404"))return null;throw G}}async branchExists(z){return await this.optional("GET",`/projects/${this.projectId}/repository/branches/${encodeURIComponent(z)}`)!==null}async createBranch(z,A){await this.request("POST",`/projects/${this.projectId}/repository/branches`,{branch:z,ref:A})}async deleteBranch(z){await this.request("DELETE",`/projects/${this.projectId}/repository/branches/${encodeURIComponent(z)}`)}async commitChanges(z,A,F,G="main"){if(F.length===0)return;if(await this.branchExists(z))await this.deleteBranch(z);await this.createBranch(z,G);let J=await Promise.all(F.map(async(K)=>{if(K.type==="delete")return{action:"delete",file_path:K.path};return{action:await this.getFileContent(K.path,G)!==null?"update":"create",file_path:K.path,content:K.content}}));await this.request("POST",`/projects/${this.projectId}/repository/commits`,{branch:z,commit_message:A,actions:J})}async getFileContent(z,A){let F=await this.optional("GET",`/projects/${this.projectId}/repository/files/${encodeURIComponent(z)}?ref=${encodeURIComponent(A)}`);if(!F?.content)return null;return F.encoding==="base64"?Buffer.from(F.content,"base64").toString("utf-8"):F.content}async createPullRequest(z){let A=await this.request("POST",`/projects/${this.projectId}/merge_requests`,{source_branch:z.head,target_branch:z.base,title:z.draft?`Draft: ${z.title}`:z.title,description:z.body,...z.labels?.length?{labels:z.labels.join(",")}:{},remove_source_branch:!0});return await this.assignPeople(A.iid,z),this.toPullRequest(A)}async assignPeople(z,A){let F=async(J=[])=>{return(await Promise.all(J.map(async(O)=>{return(await this.optional("GET",`/users?username=${encodeURIComponent(O)}`))?.[0]?.id??null}))).filter((O)=>O!==null)},[G,H]=await Promise.all([F(A.reviewers),F(A.assignees)]);if(G.length===0&&H.length===0)return;try{await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{...G.length?{reviewer_ids:G}:{},...H.length?{assignee_ids:H}:{}})}catch(J){this.logger.warn(`\u26A0\uFE0F Could not assign reviewers on !${z}: ${M(J)}`)}}async getPullRequests(z="open"){let A=z==="all"?"state=all":z==="open"?"state=opened":"state=all",G=(await this.request("GET",`/projects/${this.projectId}/merge_requests?${A}&per_page=100`)).map((H)=>this.toPullRequest(H));return z==="closed"?G.filter((H)=>H.state!=="open"):G}async updatePullRequest(z,A){let F=await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{...A.title!==void 0?{title:A.draft?`Draft: ${A.title}`:A.title}:{},...A.body!==void 0?{description:A.body}:{},...A.base!==void 0?{target_branch:A.base}:{},...A.labels!==void 0?{labels:A.labels.join(",")}:{}});return this.toPullRequest(F)}async closePullRequest(z){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{state_event:"close"})}async reopenPullRequest(z){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{state_event:"reopen"})}async mergePullRequest(z,A="squash"){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}/merge`,{squash:A==="squash",should_remove_source_branch:!0})}async getPullRequestDiff(z){return((await this.request("GET",`/projects/${this.projectId}/merge_requests/${z}/changes`)).changes??[]).map((F)=>[`diff --git a/${F.old_path} b/${F.new_path}`,`--- a/${F.old_path}`,`+++ b/${F.new_path}`,F.diff.replace(/\n$/,"")].join(`
2
+ import{Gh as P}from"./chunk-b4a5gw9c.js";import{Jh as M,Mh as Q}from"./chunk-bprmzg0p.js";function V(z){if(z==="running")return"in_progress";if(z==="success"||z==="failed"||z==="canceled"||z==="skipped"||z==="manual")return"completed";return"queued"}function X(z){switch(z){case"success":return"success";case"failed":return"failure";case"canceled":return"cancelled";case"skipped":case"manual":return"skipped";default:return null}}class Y{token;apiUrl;logger;projectId;constructor(z,A,F,G,H){this.token=z;this.apiUrl=(G??"https://gitlab.com/api/v4").replace(/\/+$/,""),this.logger=H??Q(),this.projectId=encodeURIComponent(`${A}/${F}`)}capabilities(){return{pinIssues:!1,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!0,nativeAutoMerge:!0,commentReactions:!0,ciLogs:!0,ciRuns:!0,reviewThreads:!0,teamReviewers:!1,draftPullRequests:!0,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!0,labels:!0}}async request(z,A,F,G={}){let H=await P(`${this.apiUrl}${A}`,{method:z,headers:{"PRIVATE-TOKEN":this.token,Accept:G.raw?"text/plain":"application/json","User-Agent":"buddy",...F?{"Content-Type":"application/json"}:{}},...F?{body:JSON.stringify(F)}:{}});if(!H.ok){let K=await H.text().catch(()=>"");throw Error(`GitLab ${z} ${A} failed: ${H.status} ${K.slice(0,200)}`)}let J=await H.text();if(G.raw)return J;return J.trim()?JSON.parse(J):void 0}async optional(z,A,F={}){try{return await this.request(z,A,void 0,F)}catch(G){if(String(G).includes("404"))return null;throw G}}async branchExists(z){return await this.optional("GET",`/projects/${this.projectId}/repository/branches/${encodeURIComponent(z)}`)!==null}async createBranch(z,A){await this.request("POST",`/projects/${this.projectId}/repository/branches`,{branch:z,ref:A})}async deleteBranch(z){await this.request("DELETE",`/projects/${this.projectId}/repository/branches/${encodeURIComponent(z)}`)}async commitChanges(z,A,F,G="main"){if(F.length===0)return;if(await this.branchExists(z))await this.deleteBranch(z);await this.createBranch(z,G);let J=await Promise.all(F.map(async(K)=>{if(K.type==="delete")return{action:"delete",file_path:K.path};return{action:await this.getFileContent(K.path,G)!==null?"update":"create",file_path:K.path,content:K.content}}));await this.request("POST",`/projects/${this.projectId}/repository/commits`,{branch:z,commit_message:A,actions:J})}async getFileContent(z,A){let F=await this.optional("GET",`/projects/${this.projectId}/repository/files/${encodeURIComponent(z)}?ref=${encodeURIComponent(A)}`);if(!F?.content)return null;return F.encoding==="base64"?Buffer.from(F.content,"base64").toString("utf-8"):F.content}async createPullRequest(z){let A=await this.request("POST",`/projects/${this.projectId}/merge_requests`,{source_branch:z.head,target_branch:z.base,title:z.draft?`Draft: ${z.title}`:z.title,description:z.body,...z.labels?.length?{labels:z.labels.join(",")}:{},remove_source_branch:!0});return await this.assignPeople(A.iid,z),this.toPullRequest(A)}async assignPeople(z,A){let F=async(J=[])=>{return(await Promise.all(J.map(async(O)=>{return(await this.optional("GET",`/users?username=${encodeURIComponent(O)}`))?.[0]?.id??null}))).filter((O)=>O!==null)},[G,H]=await Promise.all([F(A.reviewers),F(A.assignees)]);if(G.length===0&&H.length===0)return;try{await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{...G.length?{reviewer_ids:G}:{},...H.length?{assignee_ids:H}:{}})}catch(J){this.logger.warn(`\u26A0\uFE0F Could not assign reviewers on !${z}: ${M(J)}`)}}async getPullRequests(z="open"){let A=z==="all"?"state=all":z==="open"?"state=opened":"state=all",G=(await this.request("GET",`/projects/${this.projectId}/merge_requests?${A}&per_page=100`)).map((H)=>this.toPullRequest(H));return z==="closed"?G.filter((H)=>H.state!=="open"):G}async updatePullRequest(z,A){let F=await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{...A.title!==void 0?{title:A.draft?`Draft: ${A.title}`:A.title}:{},...A.body!==void 0?{description:A.body}:{},...A.base!==void 0?{target_branch:A.base}:{},...A.labels!==void 0?{labels:A.labels.join(",")}:{}});return this.toPullRequest(F)}async closePullRequest(z){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{state_event:"close"})}async reopenPullRequest(z){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}`,{state_event:"reopen"})}async mergePullRequest(z,A="squash"){await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}/merge`,{squash:A==="squash",should_remove_source_branch:!0})}async getPullRequestDiff(z){return((await this.request("GET",`/projects/${this.projectId}/merge_requests/${z}/changes`)).changes??[]).map((F)=>[`diff --git a/${F.old_path} b/${F.new_path}`,`--- a/${F.old_path}`,`+++ b/${F.new_path}`,F.diff.replace(/\n$/,"")].join(`
3
3
  `)).join(`
4
4
  `)}async getPullRequestHeadSha(z){return(await this.request("GET",`/projects/${this.projectId}/merge_requests/${z}`)).sha??""}async createComment(z,A){try{await this.request("POST",`/projects/${this.projectId}/merge_requests/${z}/notes`,{body:A})}catch(F){if(!String(F).includes("404"))throw F;await this.request("POST",`/projects/${this.projectId}/issues/${z}/notes`,{body:A})}}async createIssue(z){let A=await this.request("POST",`/projects/${this.projectId}/issues`,{title:z.title,description:z.body,...z.labels?.length?{labels:z.labels.join(",")}:{}});return this.toIssue(A)}async getIssues(z="open"){let A=z==="all"?"state=all":`state=${z==="open"?"opened":"closed"}`;return(await this.request("GET",`/projects/${this.projectId}/issues?${A}&per_page=100`)).map((G)=>this.toIssue(G))}async updateIssue(z,A){let F=await this.request("PUT",`/projects/${this.projectId}/issues/${z}`,{...A.title!==void 0?{title:A.title}:{},...A.body!==void 0?{description:A.body}:{},...A.labels!==void 0?{labels:A.labels.join(",")}:{}});return this.toIssue(F)}async closeIssue(z){await this.request("PUT",`/projects/${this.projectId}/issues/${z}`,{state_event:"close"})}async unpinIssue(z){return!1}async enableAutoMerge(z,A="squash"){try{return await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}/merge`,{merge_when_pipeline_succeeds:!0,squash:A==="squash",should_remove_source_branch:!0}),!0}catch(F){return this.logger.debug(`Could not queue !${z} for auto-merge: ${M(F)}`),!1}}async getPullRequestChecksState(z){let F=(await this.optional("GET",`/projects/${this.projectId}/merge_requests/${z}/pipelines`))?.[0]?.status;if(!F)return"none";if(F==="success")return"success";if(["failed","canceled"].includes(F))return"failure";if(["running","pending","created","waiting_for_resource","preparing","scheduled"].includes(F))return"pending";return"none"}async createReview(z,A){if(await this.request("POST",`/projects/${this.projectId}/merge_requests/${z}/notes`,{body:A.body}),!A.comments?.length)return{posted:!0,inlineComments:0};let G=(await this.optional("GET",`/projects/${this.projectId}/merge_requests/${z}/versions`))?.[0];if(!G)return this.logger.warn("\u26A0\uFE0F Could not resolve diff positions; inline comments were not posted"),{posted:!0,inlineComments:0};let H=0;for(let J of A.comments)try{await this.request("POST",`/projects/${this.projectId}/merge_requests/${z}/discussions`,{body:J.body,position:{position_type:"text",base_sha:G.base_commit_sha,start_sha:G.start_commit_sha,head_sha:G.head_commit_sha,new_path:J.path,old_path:J.path,...J.side==="RIGHT"?{new_line:J.line}:{old_line:J.line}}}),H++}catch(K){this.logger.debug(`Could not place a comment on ${J.path}:${J.line}: ${M(K)}`)}return{posted:!0,inlineComments:H}}async createCheckRun(z,A,F){try{await this.request("POST",`/projects/${this.projectId}/statuses/${A}`,{state:F.conclusion==="failure"?"failed":"success",name:z,description:F.title.slice(0,140)})}catch(G){this.logger.warn(`\u26A0\uFE0F Could not report status ${z}: ${M(G)}`)}}async reactToComment(z,A){let F={eyes:"eyes","+1":"thumbsup","-1":"thumbsdown",rocket:"rocket",confused:"confused"};try{await this.request("POST",`/projects/${this.projectId}/notes/${z}/award_emoji`,{name:F[A]??"eyes"})}catch(G){this.logger.debug(`Could not react to note ${z}: ${M(G)}`)}}async hasWriteAccess(z){return(await this.optional("GET",`/projects/${this.projectId}/members/all?query=${encodeURIComponent(z)}`)??[]).some((F)=>F.username===z&&F.access_level>=30)}async getWorkflowRunLogs(z){return this.optional("GET",`/projects/${this.projectId}/jobs/${z}/trace`,{raw:!0}).catch((A)=>{return this.logger.debug(`Could not read the trace for job ${z}: ${M(A)}`),null})}async listWorkflowRuns(z,A={}){let F=A.limit??20;try{return(await this.request("GET",`/projects/${this.projectId}/jobs?per_page=${Math.min(F*5,100)}`)??[]).filter((H)=>H.ref===z).map((H)=>({id:H.id,name:H.name??"",headSha:H.commit?.id??"",headBranch:H.ref??z,status:V(H.status),conclusion:X(H.status),createdAt:new Date(H.created_at??new Date().toISOString())})).filter((H)=>!A.status||H.status===A.status).slice(0,F)}catch(G){return this.logger.debug(`Could not list CI jobs for ${z}: ${M(G)}`),[]}}async rerunWorkflowRun(z){try{return await this.request("POST",`/projects/${this.projectId}/jobs/${z}/retry`),!0}catch(A){return this.logger.warn(`Could not retry job ${z}: ${M(A)}`),!1}}async listReviewThreads(z){try{return(await this.request("GET",`/projects/${this.projectId}/merge_requests/${z}/discussions?per_page=100`)??[]).filter((F)=>(F.notes??[]).some((G)=>G.resolvable)).map((F)=>({id:F.id,isResolved:(F.notes??[]).every((G)=>!G.resolvable||G.resolved),...F.notes?.[0]?.position?.new_path?{path:F.notes[0].position.new_path}:{},authorLogins:(F.notes??[]).map((G)=>G.author?.username).filter((G)=>typeof G==="string")}))}catch(A){return this.logger.debug(`Could not read discussions on !${z}: ${M(A)}`),[]}}async resolveReviewThread(z,A){try{return await this.request("PUT",`/projects/${this.projectId}/merge_requests/${z}/discussions/${encodeURIComponent(A)}`,{resolved:!0}),!0}catch(F){return this.logger.warn(`Could not resolve discussion ${A}: ${M(F)}`),!1}}async getBuddyBranches(){return(await this.request("GET",`/projects/${this.projectId}/repository/branches?search=buddy&per_page=100`)).filter((A)=>A.name.startsWith("buddy/")).map((A)=>({name:A.name,sha:A.commit?.id??"",lastCommitDate:A.commit?.committed_date?new Date(A.commit.committed_date):new Date(0)}))}async getOrphanedBuddyBranches(){let[z,A]=await Promise.all([this.getBuddyBranches(),this.getPullRequests("open")]),F=new Set(A.map((G)=>G.head));return z.filter((G)=>!F.has(G.name))}async cleanupStaleBranches(z=7,A=!1){let F=new Date(Date.now()-z*24*60*60*1000),G=(await this.getOrphanedBuddyBranches()).filter((K)=>K.lastCommitDate<F);if(A)return{deleted:G.map((K)=>K.name),failed:[]};let H=[],J=[];for(let K of G)try{await this.deleteBranch(K.name),H.push(K.name)}catch{J.push(K.name)}return{deleted:H,failed:J}}toPullRequest(z){let A=Boolean(z.draft??z.work_in_progress)||/^(?:draft|wip):/i.test(z.title);return{number:z.iid,title:z.title.replace(/^(?:draft|wip):\s*/i,""),body:z.description??"",head:z.source_branch,base:z.target_branch,state:z.state==="merged"?"merged":z.state==="opened"?"open":"closed",url:z.web_url,createdAt:new Date(z.created_at),updatedAt:new Date(z.updated_at),...z.merged_at?{mergedAt:new Date(z.merged_at)}:{},author:z.author?.username??"",reviewers:(z.reviewers??[]).map((F)=>F.username),assignees:(z.assignees??[]).map((F)=>F.username),labels:z.labels??[],draft:A}}toIssue(z){return{number:z.iid,title:z.title,body:z.description??"",state:z.state==="closed"?"closed":"open",url:z.web_url,createdAt:new Date(z.created_at),updatedAt:new Date(z.updated_at),...z.closed_at?{closedAt:new Date(z.closed_at)}:{},author:z.author?.username??"",assignees:(z.assignees??[]).map((A)=>A.username),labels:z.labels??[]}}}
5
- export{Y as th};
5
+ export{Y as Ah};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Je as l}from"./chunk-g30dr44w.js";import{Uf as c,bg as A}from"./chunk-0hc97k0t.js";import{jg as y}from"./chunk-3901s7h9.js";import{ph as k}from"./chunk-193abzy6.js";import{Fh as i}from"./chunk-hfjywbbc.js";import u from"process";var d=/\{([a-z_]+)\}/gi,b={title:"title",message:"message",group:"group",count:"count",strategy:"strategy",update_type:"updateType",updateType:"updateType",packages:"packages",updates_table:"updatesTable",release_notes:"releaseNotes",footer:"footer",package_count:"packageCount"};function C(W,$){return W.replace(d,(Y,R)=>{let K=b[R]??b[R.toLowerCase()];if(!K)return Y;let H=$[K];return H===void 0?Y:String(H)})}function f(W,$={},Y){return{...$,group:W.name,count:W.updates.length,packageCount:W.updates.length,updateType:W.updateType,packages:W.updates.map((R)=>R.name).join(", "),...Y?{strategy:Y}:{}}}class p{config;releaseNotesFetcher=new l;verbose=!1;logger;constructor(W,$){this.config=W;this.verbose=W?.verbose||u.env.BUDDY_VERBOSE==="true",this.logger=$??i()}get releaseNotesSettings(){let W=this.config?.releaseNotes;return{enabled:W?.enabled??!0,maxReleases:W?.maxReleases??3,maxBodyLength:W?.maxBodyLength??1000,includeCompareLinks:W?.includeCompareLinks??!0}}repositoryFileUrl(W){let $=k(this.config),{owner:Y,name:R,baseBranch:K}=this.config?.repository??{};return`${$}/${Y}/${R}/blob/${K||"main"}/${W}`}log(W,$){if(this.verbose){let Y=new Date().toISOString();if(this.logger.info(`[${Y}] PR-GEN: ${W}`),$)this.logger.info(JSON.stringify($,null,2))}}async generatePullRequests(W){let $=[];for(let Y of W){let R=this.generateTitle(Y),K=await this.generateBody(Y),H={number:0,title:R,body:K,head:`buddy/update-${Y.name.toLowerCase().replace(/\s+/g,"-")}`,base:"main",state:"open",url:"",createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:[],assignees:[],labels:this.generateLabels(Y),draft:!1};$.push(H)}return $}generateLabels(W){let $=["dependencies"];if(W.updateType==="major")$.push("major");else if(W.updateType==="minor")$.push("minor");else if(W.updateType==="patch")$.push("patch");let Y=W.updates.filter((B)=>B.file==="package.json"||B.file.endsWith("/package.json")||B.file.endsWith("\\package.json")).length,R=W.updates.filter((B)=>B.file.endsWith("composer.json")||B.file.endsWith("composer.lock")).length,K=W.updates.filter((B)=>B.file.endsWith("build.zig.zon")).length,H=W.updates.filter((B)=>(B.file.includes(".yaml")||B.file.includes(".yml"))&&!B.file.includes(".github/workflows/")).length,Z=W.updates.filter((B)=>B.file.includes(".github/workflows/")).length;if(Y>0)$.push("npm");if(R>0)$.push("composer");if(K>0)$.push("zig");if(H>0)$.push("system");if(Z>0)$.push("github-actions");if(W.updates.length===1){let B=W.updates[0];$.push(B.name)}if(W.updates.length>=5)$.push("bulk-update");return $}generateTitle(W){let $=this.config?.pullRequest?.titleFormat;if($)return C($,f(W,{title:this.defaultTitle(W)},this.config?.packages?.strategy));return this.defaultTitle(W)}defaultTitle(W){if(W.updates.length===1){let R=W.updates[0];return`chore(deps): update dependency ${R.name} to v${R.newVersion}`}let $=W.updates.filter((R)=>R.updateType==="major").length,Y=W.updates.filter((R)=>R.updateType==="minor").length;if($>0)return`chore(deps): update ${W.updates.length} dependencies (major)`;else if(Y>0)return`chore(deps): update ${W.updates.length} dependencies (minor)`;else return`chore(deps): update ${W.updates.length} dependencies (patch)`}async generateBody(W){if(this.log("\uD83D\uDE80 Starting PR body generation",{groupName:W.name,totalUpdates:W.updates.length,updates:W.updates.map((Q)=>({name:Q.name,file:Q.file,dependencyType:Q.dependencyType,currentVersion:Q.currentVersion,newVersion:Q.newVersion,updateType:Q.updateType}))}),W.updates.length===0)this.log("\u26A0\uFE0F WARNING: No updates in group - this will result in sparse PR body",{groupName:W.name,groupTitle:W.title});let $=W.updates.filter((Q)=>Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")).length,Y=W.updates.filter((Q)=>(Q.file.includes(".yaml")||Q.file.includes(".yml"))&&!Q.file.includes(".github/workflows/")).length,R=W.updates.filter((Q)=>Q.file.includes(".github/workflows/")).length,K=W.updates.filter((Q)=>Q.file.endsWith("composer.json")||Q.file.endsWith("composer.lock")).length,H=W.updates.filter((Q)=>Q.file.endsWith("build.zig.zon")).length;if(this.log("\uD83D\uDCCA Package type counts",{packageJsonCount:$,dependencyFileCount:Y,githubActionsCount:R,composerCount:K,total:W.updates.length}),W.updates.length>0)this.log("\uD83D\uDD0D File path analysis",{files:W.updates.map((Q)=>({name:Q.name,file:Q.file,isExactMatch:Q.file==="package.json",endsWithSlash:Q.file.endsWith("/package.json"),endsWithBackslash:Q.file.endsWith("\\package.json"),matchesAny:Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")}))});let Z=`This PR contains the following updates:
2
+ import{Ue as l}from"./chunk-d7e6tqmr.js";import{$f as c,ig as A}from"./chunk-d73ympxb.js";import{qg as y}from"./chunk-abfyz98y.js";import{wh as k}from"./chunk-wkq57ssc.js";import{Mh as i}from"./chunk-bprmzg0p.js";import u from"process";var d=/\{([a-z_]+)\}/gi,b={title:"title",message:"message",group:"group",count:"count",strategy:"strategy",update_type:"updateType",updateType:"updateType",packages:"packages",updates_table:"updatesTable",release_notes:"releaseNotes",footer:"footer",package_count:"packageCount"};function C(W,$){return W.replace(d,(Y,R)=>{let K=b[R]??b[R.toLowerCase()];if(!K)return Y;let H=$[K];return H===void 0?Y:String(H)})}function f(W,$={},Y){return{...$,group:W.name,count:W.updates.length,packageCount:W.updates.length,updateType:W.updateType,packages:W.updates.map((R)=>R.name).join(", "),...Y?{strategy:Y}:{}}}class p{config;releaseNotesFetcher=new l;verbose=!1;logger;constructor(W,$){this.config=W;this.verbose=W?.verbose||u.env.BUDDY_VERBOSE==="true",this.logger=$??i()}get releaseNotesSettings(){let W=this.config?.releaseNotes;return{enabled:W?.enabled??!0,maxReleases:W?.maxReleases??3,maxBodyLength:W?.maxBodyLength??1000,includeCompareLinks:W?.includeCompareLinks??!0}}repositoryFileUrl(W){let $=k(this.config),{owner:Y,name:R,baseBranch:K}=this.config?.repository??{};return`${$}/${Y}/${R}/blob/${K||"main"}/${W}`}log(W,$){if(this.verbose){let Y=new Date().toISOString();if(this.logger.info(`[${Y}] PR-GEN: ${W}`),$)this.logger.info(JSON.stringify($,null,2))}}async generatePullRequests(W){let $=[];for(let Y of W){let R=this.generateTitle(Y),K=await this.generateBody(Y),H={number:0,title:R,body:K,head:`buddy/update-${Y.name.toLowerCase().replace(/\s+/g,"-")}`,base:"main",state:"open",url:"",createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:[],assignees:[],labels:this.generateLabels(Y),draft:!1};$.push(H)}return $}generateLabels(W){let $=["dependencies"];if(W.updateType==="major")$.push("major");else if(W.updateType==="minor")$.push("minor");else if(W.updateType==="patch")$.push("patch");let Y=W.updates.filter((B)=>B.file==="package.json"||B.file.endsWith("/package.json")||B.file.endsWith("\\package.json")).length,R=W.updates.filter((B)=>B.file.endsWith("composer.json")||B.file.endsWith("composer.lock")).length,K=W.updates.filter((B)=>B.file.endsWith("build.zig.zon")).length,H=W.updates.filter((B)=>(B.file.includes(".yaml")||B.file.includes(".yml"))&&!B.file.includes(".github/workflows/")).length,Z=W.updates.filter((B)=>B.file.includes(".github/workflows/")).length;if(Y>0)$.push("npm");if(R>0)$.push("composer");if(K>0)$.push("zig");if(H>0)$.push("system");if(Z>0)$.push("github-actions");if(W.updates.length===1){let B=W.updates[0];$.push(B.name)}if(W.updates.length>=5)$.push("bulk-update");return $}generateTitle(W){let $=this.config?.pullRequest?.titleFormat;if($)return C($,f(W,{title:this.defaultTitle(W)},this.config?.packages?.strategy));return this.defaultTitle(W)}defaultTitle(W){if(W.updates.length===1){let R=W.updates[0];return`chore(deps): update dependency ${R.name} to v${R.newVersion}`}let $=W.updates.filter((R)=>R.updateType==="major").length,Y=W.updates.filter((R)=>R.updateType==="minor").length;if($>0)return`chore(deps): update ${W.updates.length} dependencies (major)`;else if(Y>0)return`chore(deps): update ${W.updates.length} dependencies (minor)`;else return`chore(deps): update ${W.updates.length} dependencies (patch)`}async generateBody(W){if(this.log("\uD83D\uDE80 Starting PR body generation",{groupName:W.name,totalUpdates:W.updates.length,updates:W.updates.map((Q)=>({name:Q.name,file:Q.file,dependencyType:Q.dependencyType,currentVersion:Q.currentVersion,newVersion:Q.newVersion,updateType:Q.updateType}))}),W.updates.length===0)this.log("\u26A0\uFE0F WARNING: No updates in group - this will result in sparse PR body",{groupName:W.name,groupTitle:W.title});let $=W.updates.filter((Q)=>Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")).length,Y=W.updates.filter((Q)=>(Q.file.includes(".yaml")||Q.file.includes(".yml"))&&!Q.file.includes(".github/workflows/")).length,R=W.updates.filter((Q)=>Q.file.includes(".github/workflows/")).length,K=W.updates.filter((Q)=>Q.file.endsWith("composer.json")||Q.file.endsWith("composer.lock")).length,H=W.updates.filter((Q)=>Q.file.endsWith("build.zig.zon")).length;if(this.log("\uD83D\uDCCA Package type counts",{packageJsonCount:$,dependencyFileCount:Y,githubActionsCount:R,composerCount:K,total:W.updates.length}),W.updates.length>0)this.log("\uD83D\uDD0D File path analysis",{files:W.updates.map((Q)=>({name:Q.name,file:Q.file,isExactMatch:Q.file==="package.json",endsWithSlash:Q.file.endsWith("/package.json"),endsWithBackslash:Q.file.endsWith("\\package.json"),matchesAny:Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")}))});let Z=`This PR contains the following updates:
3
3
 
4
4
  `;Z+=c(W.updates);let B=W.updates.length>1;if(B){if(Z+=`## Package Updates Summary
5
5
 
@@ -183,4 +183,4 @@ import{Je as l}from"./chunk-g30dr44w.js";import{Uf as c,bg as A}from"./chunk-0hc
183
183
  `).trim();$=this.sanitizeMentions($),$=this.sanitizeGitHubReferences($);let Y=this.config?.releaseNotes?.maxBodyLength??1000;if($.length>Y)$=`${$.substring(0,Y)}...
184
184
 
185
185
  *[View full release notes]*`;return $}sanitizeMentions(W){let $=[],Y=[],R=W.replace(/```[\s\S]*?```/g,(K)=>{return $.push(K),`__FENCE_PLACEHOLDER_${$.length-1}__`});return R=R.replace(/`[^`\n]+`/g,(K)=>{return Y.push(K),`__INLINE_CODE_PLACEHOLDER_${Y.length-1}__`}),R=R.replace(/(?<![\w./])@([A-Z0-9-]+)(?![A-Z0-9-])/gi,(K,H)=>{return`[${H}](https://github.com/${H})`}),R=R.replace(/__INLINE_CODE_PLACEHOLDER_(\d+)__/g,(K,H)=>Y[Number(H)]),R=R.replace(/__FENCE_PLACEHOLDER_(\d+)__/g,(K,H)=>$[Number(H)]),R}sanitizeGitHubReferences(W){if(this.config?.releaseNotes?.sanitizeReferences===!1)return W;let $=[],Y=[],R=W.replace(/```[\s\S]*?```/g,(K)=>{return $.push(K),`__FENCE_PLACEHOLDER_${$.length-1}__`});return R=R.replace(/`[^`\n]+`/g,(K)=>{return Y.push(K),`__INLINE_CODE_PLACEHOLDER_${Y.length-1}__`}),R=R.replace(/https?:\/\/github\.com\/([^/]+)\/([^/]+)\/(?:pull|issues)\/(\d+)/g,(K,H,Z,B)=>`\`${H}/${Z}#${B}\``),R=R.replace(/(?<![`\w])#(\d+)(?!\d)/g,"`#$1`"),R=R.replace(/__INLINE_CODE_PLACEHOLDER_(\d+)__/g,(K,H)=>Y[Number(H)]),R=R.replace(/__FENCE_PLACEHOLDER_(\d+)__/g,(K,H)=>$[Number(H)]),R}generateCustomTemplate(W,$,Y={}){let R=$,H={...{"{title}":this.generateTitle(W),"{package_count}":W.updates.length.toString(),"{update_type}":W.updateType,"{packages}":W.updates.map((Z)=>Z.name).join(", "),"{date}":new Date().toISOString().split("T")[0]},...Y};for(let[Z,B]of Object.entries(H))R=R.replace(new RegExp(Z,"g"),B);return R}formatVersionChange(W,$){let Y=W.match(/^(\D+)/),R=Y?Y[1]:"";if(R){let K=W.replace(/^\D+/,""),H=$.replace(/^\D+/,"");return`\`${R}${K}\` \u2192 \`${R}${H}\``}return`\`${W}\` \u2192 \`${$}\``}getVersionChangeDescription(W,$,Y){return{major:"\uD83D\uDD34 Breaking changes possible",minor:"\uD83D\uDFE1 New features added",patch:"\uD83D\uDFE2 Bug fixes & patches"}[Y]}}
186
- export{C as ld,f as md,p as nd};
186
+ export{C as pd,f as qd,p as rd};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{rh as B,sh as E}from"./chunk-193abzy6.js";import{zh as z}from"./chunk-e68nf7cm.js";import{Fh as A}from"./chunk-hfjywbbc.js";class H{logger;constructor(b){this.logger=b??A()}async checkDeprecatedDependencies(b){let j=[];for(let q of b){let w=await this.checkFileForDeprecatedDependencies(q);j.push(...w)}return j}async checkFileForDeprecatedDependencies(b){let j=[];for(let q of b.dependencies){let w=await this.checkDependencyDeprecation(q,b.type);if(w.deprecated)j.push({name:q.name,currentVersion:q.currentVersion,datasource:this.getDatasourceFromFileType(b.type),file:b.path,type:q.type,replacementAvailable:!1,deprecationMessage:w.message,suggestedReplacement:w.suggestedReplacement})}return j}async checkDependencyDeprecation(b,j){try{if(j==="package.json"||j.includes("lock"))return await this.checkNpmDeprecation(b);else if(j==="composer.json"||j==="composer.lock")return await this.checkComposerDeprecation(b);else if(j==="deps.yaml"||j==="deps.yml"||j.includes("deps"))return await this.checkBunDeprecation(b);return{deprecated:!1}}catch(q){return this.logger.warn(`Failed to check deprecation for ${b.name}:`,q),{deprecated:!1}}}async checkNpmDeprecation(b){try{let j=B(b.name),q=await z(`${j}/${encodeURIComponent(b.name).replace("%40","@")}`,{headers:{"User-Agent":"buddy"}});if(!q.ok)return{deprecated:!1};let w=await q.json();if(w.deprecated)return{deprecated:!0,message:w.deprecated,suggestedReplacement:this.extractSuggestedReplacement(w.deprecated)};let x=w.versions?.[b.currentVersion];if(x?.deprecated)return{deprecated:!0,message:x.deprecated,suggestedReplacement:this.extractSuggestedReplacement(x.deprecated)};return{deprecated:!1}}catch(j){return this.logger.warn(`Failed to check npm deprecation for ${b.name}:`,j),{deprecated:!1}}}async checkComposerDeprecation(b){try{let j=await z(`${E()}/packages/${b.name}.json`,{headers:{"User-Agent":"buddy"}});if(!j.ok)return{deprecated:!1};let q=await j.json();if(q.package?.abandoned){let w=typeof q.package.abandoned==="string"?q.package.abandoned:null;return{deprecated:!0,message:`Package is abandoned${w?`, use ${w} instead`:""}`,suggestedReplacement:w||void 0}}return{deprecated:!1}}catch(j){return this.logger.warn(`Failed to check Composer deprecation for ${b.name}:`,j),{deprecated:!1}}}async checkBunDeprecation(b){return await this.checkNpmDeprecation(b)}extractSuggestedReplacement(b){let j=[/use\s+([a-z0-9@/-]+)\s+instead/i,/replaced\s+by\s+([a-z0-9@/-]+)/i,/migrate\s+to\s+([a-z0-9@/-]+)/i,/switch\s+to\s+([a-z0-9@/-]+)/i];for(let q of j){let w=b.match(q);if(w)return w[1]}return}getDatasourceFromFileType(b){if(b==="package.json"||b.includes("lock"))return"npm";else if(b==="composer.json"||b==="composer.lock")return"composer";else if(b==="deps.yaml"||b==="deps.yml"||b.includes("deps"))return"bun";else if(b==="github-actions")return"github-actions";return"unknown"}}
3
- export{H as $c};
2
+ import{yh as B,zh as E}from"./chunk-wkq57ssc.js";import{Gh as z}from"./chunk-b4a5gw9c.js";import{Mh as A}from"./chunk-bprmzg0p.js";class H{logger;constructor(b){this.logger=b??A()}async checkDeprecatedDependencies(b){let j=[];for(let q of b){let w=await this.checkFileForDeprecatedDependencies(q);j.push(...w)}return j}async checkFileForDeprecatedDependencies(b){let j=[];for(let q of b.dependencies){let w=await this.checkDependencyDeprecation(q,b.type);if(w.deprecated)j.push({name:q.name,currentVersion:q.currentVersion,datasource:this.getDatasourceFromFileType(b.type),file:b.path,type:q.type,replacementAvailable:!1,deprecationMessage:w.message,suggestedReplacement:w.suggestedReplacement})}return j}async checkDependencyDeprecation(b,j){try{if(j==="package.json"||j.includes("lock"))return await this.checkNpmDeprecation(b);else if(j==="composer.json"||j==="composer.lock")return await this.checkComposerDeprecation(b);else if(j==="deps.yaml"||j==="deps.yml"||j.includes("deps"))return await this.checkBunDeprecation(b);return{deprecated:!1}}catch(q){return this.logger.warn(`Failed to check deprecation for ${b.name}:`,q),{deprecated:!1}}}async checkNpmDeprecation(b){try{let j=B(b.name),q=await z(`${j}/${encodeURIComponent(b.name).replace("%40","@")}`,{headers:{"User-Agent":"buddy"}});if(!q.ok)return{deprecated:!1};let w=await q.json();if(w.deprecated)return{deprecated:!0,message:w.deprecated,suggestedReplacement:this.extractSuggestedReplacement(w.deprecated)};let x=w.versions?.[b.currentVersion];if(x?.deprecated)return{deprecated:!0,message:x.deprecated,suggestedReplacement:this.extractSuggestedReplacement(x.deprecated)};return{deprecated:!1}}catch(j){return this.logger.warn(`Failed to check npm deprecation for ${b.name}:`,j),{deprecated:!1}}}async checkComposerDeprecation(b){try{let j=await z(`${E()}/packages/${b.name}.json`,{headers:{"User-Agent":"buddy"}});if(!j.ok)return{deprecated:!1};let q=await j.json();if(q.package?.abandoned){let w=typeof q.package.abandoned==="string"?q.package.abandoned:null;return{deprecated:!0,message:`Package is abandoned${w?`, use ${w} instead`:""}`,suggestedReplacement:w||void 0}}return{deprecated:!1}}catch(j){return this.logger.warn(`Failed to check Composer deprecation for ${b.name}:`,j),{deprecated:!1}}}async checkBunDeprecation(b){return await this.checkNpmDeprecation(b)}extractSuggestedReplacement(b){let j=[/use\s+([a-z0-9@/-]+)\s+instead/i,/replaced\s+by\s+([a-z0-9@/-]+)/i,/migrate\s+to\s+([a-z0-9@/-]+)/i,/switch\s+to\s+([a-z0-9@/-]+)/i];for(let q of j){let w=b.match(q);if(w)return w[1]}return}getDatasourceFromFileType(b){if(b==="package.json"||b.includes("lock"))return"npm";else if(b==="composer.json"||b==="composer.lock")return"composer";else if(b==="deps.yaml"||b==="deps.yml"||b.includes("deps"))return"bun";else if(b==="github-actions")return"github-actions";return"unknown"}}
3
+ export{H as dd};