@buddysh/buddy 0.11.1 → 0.11.2

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 (246) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +54 -43
  3. package/bin/cli.ts +282 -135
  4. package/dist/bin/cli.d.ts +5 -1
  5. package/dist/bin/cli.js +84 -91
  6. package/dist/chunk-05me15qw.js +2 -0
  7. package/dist/{chunk-bxfc4g2x.js → chunk-08x5b93v.js} +2 -13
  8. package/dist/chunk-0eg3kxb5.js +5 -0
  9. package/dist/chunk-0hc97k0t.js +44 -0
  10. package/dist/chunk-0paakbpj.js +2 -0
  11. package/dist/{chunk-hfvezfxh.js → chunk-0scz1dv5.js} +1 -1
  12. package/dist/{chunk-sp818c27.js → chunk-0w695m54.js} +5 -5
  13. package/dist/{chunk-vyapg8ca.js → chunk-11hdrnf6.js} +3 -3
  14. package/dist/{chunk-1stt2whn.js → chunk-15r904nz.js} +2 -2
  15. package/dist/{chunk-5k40mwd4.js → chunk-193abzy6.js} +1 -1
  16. package/dist/chunk-19zyq15p.js +2 -0
  17. package/dist/chunk-1c4690h9.js +79 -0
  18. package/dist/{chunk-q9n79dd3.js → chunk-1cpdz49v.js} +1 -1
  19. package/dist/{chunk-thaxgm5p.js → chunk-1qgr52wx.js} +1 -1
  20. package/dist/chunk-24c2ab29.js +2 -0
  21. package/dist/chunk-25sz1y7j.js +16 -0
  22. package/dist/chunk-2et8yavs.js +3 -0
  23. package/dist/chunk-2wj5xtdn.js +2 -0
  24. package/dist/{chunk-7mgec8kb.js → chunk-3901s7h9.js} +1 -1
  25. package/dist/{chunk-xvptf9jy.js → chunk-3cvng2nz.js} +2 -2
  26. package/dist/chunk-3fzbvs2p.js +2 -0
  27. package/dist/chunk-3pqra420.js +2 -0
  28. package/dist/{chunk-yk23nc4t.js → chunk-40znfg3x.js} +1 -1
  29. package/dist/chunk-428c5652.js +2 -0
  30. package/dist/chunk-49znmbh8.js +2 -0
  31. package/dist/chunk-5044y9en.js +5 -0
  32. package/dist/chunk-5yfaptmp.js +7 -0
  33. package/dist/{chunk-h7hs95wn.js → chunk-61xecp1z.js} +2 -2
  34. package/dist/{chunk-x0ya2r4r.js → chunk-657nbbp7.js} +2 -2
  35. package/dist/chunk-68fw3ma0.js +2 -0
  36. package/dist/{chunk-9h04nskh.js → chunk-69qyr9ef.js} +1 -1
  37. package/dist/chunk-6bd8ghkz.js +27 -0
  38. package/dist/{chunk-vh504tcv.js → chunk-6p4qz8qv.js} +2 -2
  39. package/dist/chunk-847g7jde.js +2 -0
  40. package/dist/{chunk-r3zyw8x0.js → chunk-8fw0v7bv.js} +2 -2
  41. package/dist/chunk-8hjvthz4.js +92 -0
  42. package/dist/chunk-90zmqn5k.js +2 -0
  43. package/dist/{chunk-3zdcekfj.js → chunk-929h6hhp.js} +2 -2
  44. package/dist/chunk-96ht6hwd.js +4 -0
  45. package/dist/chunk-97qf7mdt.js +2 -0
  46. package/dist/chunk-a4hzzn28.js +2 -0
  47. package/dist/chunk-aa277p5r.js +2 -0
  48. package/dist/chunk-b357cgb0.js +2 -0
  49. package/dist/chunk-b9escac0.js +4 -0
  50. package/dist/{chunk-56q4pwb5.js → chunk-be629jhq.js} +2 -2
  51. package/dist/chunk-bffxf4xy.js +2 -0
  52. package/dist/chunk-brfyymhf.js +2 -0
  53. package/dist/{chunk-zs3jaj0g.js → chunk-bymwaezh.js} +165 -119
  54. package/dist/chunk-c3es7pgf.js +2 -0
  55. package/dist/{chunk-9750tenz.js → chunk-c8rzx3a1.js} +1 -1
  56. package/dist/{chunk-tzs22es2.js → chunk-cgvt98pd.js} +1 -1
  57. package/dist/chunk-cwfkm7h9.js +3 -0
  58. package/dist/chunk-cwqhxqv7.js +2 -0
  59. package/dist/chunk-dgfb8k0h.js +2 -0
  60. package/dist/chunk-dqbk3kcj.js +104 -0
  61. package/dist/chunk-ds4stft2.js +2 -0
  62. package/dist/{chunk-1h3ey7k5.js → chunk-e68nf7cm.js} +1 -1
  63. package/dist/chunk-emyvrx5t.js +2 -0
  64. package/dist/{chunk-16yqbccr.js → chunk-eseshkd0.js} +1 -1
  65. package/dist/chunk-f53y8ans.js +3 -0
  66. package/dist/chunk-fjp3a7hp.js +26 -0
  67. package/dist/chunk-fpnjpgrb.js +2 -0
  68. package/dist/chunk-fr5c326k.js +2 -0
  69. package/dist/chunk-g24hav8e.js +370 -0
  70. package/dist/{chunk-6md7qf2g.js → chunk-g30dr44w.js} +2 -2
  71. package/dist/chunk-gkpd5nw2.js +2 -0
  72. package/dist/chunk-hbhmns7s.js +2 -0
  73. package/dist/chunk-hd5j9e3c.js +2 -0
  74. package/dist/{chunk-akffynkc.js → chunk-hfjywbbc.js} +1 -1
  75. package/dist/chunk-hmskwy76.js +2 -0
  76. package/dist/chunk-hns85dqw.js +2 -0
  77. package/dist/{chunk-wtjhehz9.js → chunk-hptfq3rg.js} +1 -1
  78. package/dist/{chunk-54sc18p8.js → chunk-hsa07n7c.js} +1 -1
  79. package/dist/chunk-hwxmhkxp.js +2 -0
  80. package/dist/{chunk-52x8mvh4.js → chunk-jnb80k2x.js} +2 -2
  81. package/dist/chunk-jtxcr5yw.js +4 -0
  82. package/dist/{chunk-tn8prpny.js → chunk-k26wnmzk.js} +7 -7
  83. package/dist/{chunk-2bp7tqca.js → chunk-kprtsn8c.js} +1 -1
  84. package/dist/chunk-m4p7cnvk.js +2 -0
  85. package/dist/chunk-mcwxpdg9.js +2 -0
  86. package/dist/chunk-mkzmjg3f.js +4 -0
  87. package/dist/chunk-ncrq3fvv.js +2 -0
  88. package/dist/chunk-ng7px8gx.js +2 -0
  89. package/dist/{chunk-vagxqhef.js → chunk-nrr8z2z7.js} +2 -2
  90. package/dist/{chunk-g0w8n555.js → chunk-p6qbqsyp.js} +2 -2
  91. package/dist/chunk-p8tmms5h.js +3 -0
  92. package/dist/{chunk-hw70wbzg.js → chunk-phfmnnne.js} +2 -2
  93. package/dist/{chunk-tb5y0350.js → chunk-pkr6905p.js} +1 -1
  94. package/dist/chunk-ppmabn5h.js +2 -0
  95. package/dist/chunk-pskqrv5r.js +2 -0
  96. package/dist/{chunk-4xsq18p3.js → chunk-q2tjkhez.js} +1 -1
  97. package/dist/{chunk-6g1y9yqh.js → chunk-q4t568hv.js} +1 -1
  98. package/dist/chunk-qd2s51gc.js +2 -0
  99. package/dist/chunk-r763e19p.js +6 -0
  100. package/dist/{chunk-74pxb991.js → chunk-rc2mk5x6.js} +2 -2
  101. package/dist/{chunk-zb62jhwm.js → chunk-s4zb0fcj.js} +13 -9
  102. package/dist/chunk-s6z3gm2s.js +5 -0
  103. package/dist/chunk-sc7emb71.js +2 -0
  104. package/dist/chunk-sw2538r0.js +49 -0
  105. package/dist/chunk-t25apff9.js +2 -0
  106. package/dist/{chunk-p4zwy518.js → chunk-tjc2vgwn.js} +2 -2
  107. package/dist/{chunk-gngwjf70.js → chunk-tw047td6.js} +2 -2
  108. package/dist/chunk-tws3npt7.js +38 -0
  109. package/dist/{chunk-6d9hmjt8.js → chunk-txtrpypt.js} +2 -2
  110. package/dist/chunk-v1wfa758.js +2 -0
  111. package/dist/{chunk-dfesffnr.js → chunk-vckhctmr.js} +1 -1
  112. package/dist/chunk-vdd1cghr.js +2 -0
  113. package/dist/{chunk-fvpr07dn.js → chunk-vgtmrd4c.js} +1 -1
  114. package/dist/chunk-vj1sdxpp.js +2 -0
  115. package/dist/{chunk-fm8ckj9b.js → chunk-vqa6vte3.js} +1 -1
  116. package/dist/{chunk-82dv4p13.js → chunk-wn6pbyzn.js} +1 -1
  117. package/dist/chunk-x23a6szw.js +2 -0
  118. package/dist/{chunk-xqx460y2.js → chunk-xs12dtf1.js} +1 -1
  119. package/dist/chunk-xznnmhyt.js +2 -0
  120. package/dist/chunk-y3dd8v85.js +2 -0
  121. package/dist/chunk-yk183r6z.js +2 -0
  122. package/dist/{chunk-1c1gznm9.js → chunk-yngahb11.js} +2 -2
  123. package/dist/{chunk-qyf90zz3.js → chunk-yp1tgdh3.js} +1 -1
  124. package/dist/chunk-ys1qqcpp.js +2 -0
  125. package/dist/{chunk-8rc6042h.js → chunk-ytmxd5fk.js} +2 -2
  126. package/dist/chunk-zgkrhymn.js +2 -0
  127. package/dist/chunk-zxgkp71x.js +2 -0
  128. package/dist/src/agent/index.d.ts +6 -1
  129. package/dist/src/agent/modes.d.ts +0 -8
  130. package/dist/src/agent/plan.d.ts +28 -0
  131. package/dist/src/agent/tasks.d.ts +20 -0
  132. package/dist/src/agent/tools/issue.d.ts +19 -0
  133. package/dist/src/ci/attempts.d.ts +36 -0
  134. package/dist/src/ci/base.d.ts +55 -0
  135. package/dist/src/ci/fix.d.ts +27 -18
  136. package/dist/src/ci/index.d.ts +5 -1
  137. package/dist/src/ci/run.d.ts +28 -0
  138. package/dist/src/commands/handlers.d.ts +3 -0
  139. package/dist/src/dashboard/dashboard-generator.d.ts +4 -0
  140. package/dist/src/events/index.d.ts +12 -0
  141. package/dist/src/gates/checks.d.ts +10 -0
  142. package/dist/src/gates/index.d.ts +1 -0
  143. package/dist/src/gates/post-merge.d.ts +13 -1
  144. package/dist/src/git/github-provider.d.ts +5 -1
  145. package/dist/src/git/gitlab-provider.d.ts +5 -1
  146. package/dist/src/git/provider.d.ts +40 -0
  147. package/dist/src/index.d.ts +3 -0
  148. package/dist/src/index.js +1 -1
  149. package/dist/src/registry/registry-client.d.ts +1 -1
  150. package/dist/src/reports/index.d.ts +1 -0
  151. package/dist/src/reports/publish-gate.d.ts +22 -0
  152. package/dist/src/review/filters.d.ts +36 -0
  153. package/dist/src/review/index.d.ts +4 -1
  154. package/dist/src/review/marker.d.ts +18 -0
  155. package/dist/src/review/poster.d.ts +11 -1
  156. package/dist/src/review/resolve.d.ts +20 -0
  157. package/dist/src/review/run.d.ts +35 -0
  158. package/dist/src/rules/engine.d.ts +19 -0
  159. package/dist/src/scanner/package-json-extras.d.ts +34 -1
  160. package/dist/src/setup.d.ts +49 -17
  161. package/dist/src/setup.js +1 -1
  162. package/dist/src/templates/github-actions.d.ts +2 -0
  163. package/dist/src/types.d.ts +4 -1
  164. package/dist/src/upgrades/migrate.d.ts +3 -0
  165. package/dist/src/upgrades/report.d.ts +1 -0
  166. package/dist/src/utils/dockerfile-parser.d.ts +2 -2
  167. package/dist/src/utils/helpers.d.ts +10 -1
  168. package/dist/src/version/version-resolver.d.ts +1 -0
  169. package/package.json +12 -10
  170. package/dist/chunk-0j7z87kh.js +0 -3
  171. package/dist/chunk-0r8zt3d7.js +0 -2
  172. package/dist/chunk-1a53wj0h.js +0 -1
  173. package/dist/chunk-1wjnd24b.js +0 -24
  174. package/dist/chunk-1xe07hzm.js +0 -2
  175. package/dist/chunk-2dbkpfy9.js +0 -2
  176. package/dist/chunk-3q6czqs4.js +0 -6
  177. package/dist/chunk-49ey79p0.js +0 -5
  178. package/dist/chunk-4c9m61yd.js +0 -5
  179. package/dist/chunk-4efbxdjr.js +0 -4
  180. package/dist/chunk-4f7panqj.js +0 -21
  181. package/dist/chunk-4hd3rre0.js +0 -2
  182. package/dist/chunk-5c3qf34r.js +0 -2
  183. package/dist/chunk-5kt03hx5.js +0 -2
  184. package/dist/chunk-63ept76v.js +0 -2
  185. package/dist/chunk-65b3vq52.js +0 -2
  186. package/dist/chunk-6k653r8w.js +0 -2
  187. package/dist/chunk-6patq6bw.js +0 -2
  188. package/dist/chunk-6sgh49z1.js +0 -2
  189. package/dist/chunk-7tfrww3v.js +0 -2
  190. package/dist/chunk-7xk28xrv.js +0 -2
  191. package/dist/chunk-8661pvb8.js +0 -3
  192. package/dist/chunk-887s0w81.js +0 -2
  193. package/dist/chunk-978wtejw.js +0 -44
  194. package/dist/chunk-9eqpaxfz.js +0 -2
  195. package/dist/chunk-9p1xkmjy.js +0 -2
  196. package/dist/chunk-agdesgzv.js +0 -2
  197. package/dist/chunk-ar01x04a.js +0 -2
  198. package/dist/chunk-ay43f085.js +0 -2
  199. package/dist/chunk-bk9bqd5j.js +0 -2
  200. package/dist/chunk-bm8d40j0.js +0 -69
  201. package/dist/chunk-c3fczawt.js +0 -2
  202. package/dist/chunk-c9r9nd4t.js +0 -1
  203. package/dist/chunk-ctsz0ynx.js +0 -3
  204. package/dist/chunk-czremqk7.js +0 -2
  205. package/dist/chunk-da3wbh04.js +0 -2
  206. package/dist/chunk-dat582cg.js +0 -2
  207. package/dist/chunk-djntbp7a.js +0 -105
  208. package/dist/chunk-eagjp0dh.js +0 -3
  209. package/dist/chunk-eht72nnj.js +0 -2
  210. package/dist/chunk-f4nv5x3z.js +0 -2
  211. package/dist/chunk-fdfk918n.js +0 -2
  212. package/dist/chunk-fdj0tewy.js +0 -20
  213. package/dist/chunk-fqj7e6xa.js +0 -2
  214. package/dist/chunk-frm8zz31.js +0 -2
  215. package/dist/chunk-g0nv8psv.js +0 -2
  216. package/dist/chunk-gkmvxjbe.js +0 -2
  217. package/dist/chunk-j8asz4hb.js +0 -15
  218. package/dist/chunk-k62w2v03.js +0 -2
  219. package/dist/chunk-mcrfxphm.js +0 -5
  220. package/dist/chunk-mh3x7j6h.js +0 -2
  221. package/dist/chunk-naq32yx3.js +0 -86
  222. package/dist/chunk-nsmcjkas.js +0 -2
  223. package/dist/chunk-p1xm1jvz.js +0 -2
  224. package/dist/chunk-p3wsm8kz.js +0 -2
  225. package/dist/chunk-p7zgy37f.js +0 -2
  226. package/dist/chunk-ph1b3vbp.js +0 -315
  227. package/dist/chunk-pkjm2r0a.js +0 -2
  228. package/dist/chunk-pkkwb0n0.js +0 -4
  229. package/dist/chunk-pnpx1kqn.js +0 -6
  230. package/dist/chunk-qpz9k66h.js +0 -2
  231. package/dist/chunk-qvn1rtgp.js +0 -2
  232. package/dist/chunk-r06ce5g6.js +0 -2
  233. package/dist/chunk-r2sbprdb.js +0 -49
  234. package/dist/chunk-rqdep14r.js +0 -2
  235. package/dist/chunk-s1km8cyq.js +0 -2
  236. package/dist/chunk-s4ms8zag.js +0 -2
  237. package/dist/chunk-ts35hc5t.js +0 -3
  238. package/dist/chunk-vkctfqpm.js +0 -3
  239. package/dist/chunk-wdwvt7gb.js +0 -43
  240. package/dist/chunk-x3kragh9.js +0 -12
  241. package/dist/chunk-x9ctz1qc.js +0 -1
  242. package/dist/chunk-xakpdqaq.js +0 -3
  243. package/dist/chunk-yncea6ty.js +0 -2
  244. package/dist/chunk-yq0gxtzv.js +0 -2
  245. package/dist/chunk-yqhs08ky.js +0 -2
  246. package/dist/chunk-zve5d96e.js +0 -2
@@ -0,0 +1,38 @@
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 L}from"./chunk-e68nf7cm.js";import{Bh as A,Ch as C,Fh as F}from"./chunk-hfjywbbc.js";import{Buffer as W}from"buffer";import{spawn as k}from"child_process";import M 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"}}class f{token;owner;repo;hasWorkflowPermissions;workflowToken;apiUrl;cache={pullRequests:new Map,issues:new Map};cacheTTL=120000;logger;constructor(Q,X,Y,Z=!1,$,J,x){this.token=Q;this.owner=X;this.repo=Y;this.hasWorkflowPermissions=Z;this.workflowToken=$;this.apiUrl=J?J.replace(/\/+$/,""):P(),this.logger=x??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}: ${C(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}: ${C(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 K=Bun.file("README.md");if(await K.exists()){let G=`${await K.text()}
3
+
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(M.env.NODE_ENV==="test"||M.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(!(M.env.NODE_ENV==="test"||M.env.BUN_ENV==="test")){let V=Y.map((K)=>K.path.replace(/^\.\//,"").replace(/^\/+/,"")),j=y(V);if(j.length>0){this.logger.info(`\uD83D\uDD12 Regenerating lock files for: ${j.join(", ")}`);let K=M.cwd(),q=[];for(let G of j)try{let H=await v(G,K);if(H.success)for(let z of T())try{await this.runCommand("git",["add",z])}catch{}else q.push(`${G}: ${H.message}`)}catch(H){q.push(`${G}: ${H instanceof Error?H.message:String(H)}`)}if(q.length>0){let G=q.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: ${C($)}`),$}}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,K=(await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/commits/${V}`)).tree.sha;await S(Y,async(z)=>{let U=z.split("/").map((O)=>encodeURIComponent(O)).join("/");try{return await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${U}?ref=${encodeURIComponent(Z)}`),!0}catch(O){if(O.message?.includes("404"))return!1;throw O}});let q=[];for(let z of Y){let U=R(z.path);if(z.type==="delete")q.push({path:U,mode:"100644",type:"blob",sha:null});else{let O=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/blobs`,{content:W.from(z.content).toString("base64"),encoding:"base64"});q.push({path:U,mode:"100644",type:"blob",sha:O.sha})}}let G=await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/git/trees`,{base_tree:K,tree:q});if(G.sha===K){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}: ${C($)}`),$}}async createPullRequest(Q){try{return await this.createPullRequestWithCLI(Q)}catch(X){return this.logger.warn(`\u26A0\uFE0F GitHub CLI failed, falling back to API: ${X}`),await this.createPullRequestWithAPI(Q)}}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(x){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${x}`);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}: ${C(X)}`),X}}async createPullRequestWithAPI(Q){try{let X=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});if(Q.reviewers&&Q.reviewers.length>0)try{this.logger.info(`\uD83D\uDD0D Adding reviewers to PR #${X.number}: ${Q.reviewers.join(", ")}`),await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/pulls/${X.number}/requested_reviewers`,{reviewers:Q.reviewers,team_reviewers:Q.teamReviewers||[]}),this.logger.info(`\u2705 Successfully added reviewers: ${Q.reviewers.join(", ")}`)}catch(Y){this.logger.error(`\u274C Failed to add reviewers: ${Y}`),this.logger.error(` Reviewers: ${Q.reviewers.join(", ")}`),this.logger.error(` Repository: ${this.owner}/${this.repo}`),this.logger.error(` PR: #${X.number}`)}if(Q.assignees&&Q.assignees.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${X.number}/assignees`,{assignees:Q.assignees})}catch(Y){this.logger.warn(`\u26A0\uFE0F Failed to add assignees: ${Y}`)}if(Q.labels&&Q.labels.length>0)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${X.number}/labels`,{labels:Q.labels})}catch(Y){this.logger.warn(`\u26A0\uFE0F Failed to add labels: ${Y}`);for(let Z of Q.labels)try{await this.apiRequest(`POST /repos/${this.owner}/${this.repo}/issues/${X.number}/labels`,{labels:[Z]})}catch($){this.logger.warn(`\u26A0\uFE0F Failed to add label '${Z}': ${$}`)}}return this.logger.info(`\u2705 Created PR #${X.number}: ${Q.title}`),{number:X.number,title:X.title,body:X.body||"",head:X.head.ref,base:X.base.ref,state:X.state,url:X.html_url,createdAt:new Date(X.created_at),updatedAt:new Date(X.updated_at),author:X.user.login,reviewers:Q.reviewers||[],assignees:Q.assignees||[],labels:Q.labels||[],draft:X.draft}}catch(X){throw this.logger.error(`\u274C Failed to create PR with API: ${Q.title}: ${C(X)}`),X}}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 x=k(Q,X,{stdio:"pipe",env:{...M.env,GITHUB_TOKEN:Z,GH_TOKEN:Z}}),_="",V="";x.stdout?.on("data",(j)=>{_+=j.toString()}),x.stderr?.on("data",(j)=>{V+=j.toString()}),x.on("close",(j)=>{if(j===0)$(_);else J(Error(`Command failed with code ${j}: ${g(V,Z)}`))}),x.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 x=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:x,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${x.length} PRs (state: ${Q})`),x}catch(Z){throw this.logger.error(`\u274C Failed to get PRs: ${C(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(x){this.logger.warn(`\u26A0\uFE0F Failed to add label '${J}' to PR #${Q}: ${x}`)}}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}: ${C(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}: ${C(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}: ${C(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}: ${C(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}: ${C(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}: ${C(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 A&&X.isNotFound)return!1;return this.logger.warn(`\u26A0\uFE0F Could not resolve permissions for @${Q}: ${C(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}: ${C(Y)}`)}}async getWorkflowRunLogs(Q){try{let X=await L(`${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}: ${C(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}: ${C(Z)}`),[]}}async rerunWorkflowRun(Q,X=!0){let Y=X?"rerun-failed-jobs":"rerun";try{let Z=await L(`${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}: ${C(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}: ${C(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 A&&Y.isNotFound)return null;throw Y}}async getPullRequestDiff(Q){let X=await L(`${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 A(`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}: ${C(Z)}`),Z;return this.logger.warn(`\u26A0\uFE0F Review with inline comments was rejected (${C(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
+ enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
9
+ pullRequest { number }
10
+ }
11
+ }`,$=await this.graphqlRequest(`mutation($pullRequestId: ID!, $mergeMethod: PullRequestMergeMethod!) {
12
+ enablePullRequestAutoMerge(input: { pullRequestId: $pullRequestId, mergeMethod: $mergeMethod }) {
13
+ pullRequest { number }
14
+ }
15
+ }`,{pullRequestId:Y.node_id,mergeMethod:X.toUpperCase()});if($.errors?.length){let J=$.errors.map((x)=>x.message).join("; ");return this.logger.info(`\u2139\uFE0F GitHub could not queue auto-merge for PR #${Q}: ${J}`),!1}return this.logger.success(`\u2705 Auto-merge queued for PR #${Q} (${X})`),!0}async listReviewThreads(Q){try{let Y=await this.graphqlRequest(`query($owner: String!, $repo: String!, $number: Int!) {
16
+ repository(owner: $owner, name: $repo) {
17
+ pullRequest(number: $number) {
18
+ reviewThreads(first: 100) {
19
+ nodes {
20
+ id
21
+ isResolved
22
+ path
23
+ comments(first: 10) { nodes { author { login } } }
24
+ }
25
+ }
26
+ }
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}: ${C(Y)}`),[]}}async resolveReviewThread(Q,X){try{let Z=await this.graphqlRequest(`mutation($threadId: ID!) {
29
+ resolveReviewThread(input: { threadId: $threadId }) {
30
+ thread { isResolved }
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: ${C(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??[],x=(Z?.statuses?.length??0)>0;if(J.length===0&&!x)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}: ${C(X)}`),"pending"}}async graphqlRequest(Q,X){let Y=await L(`${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 A(`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(C(X))){this.logger.info(`\u2139\uFE0F Branch ${Q} was already gone`);return}throw this.logger.warn(`\u26A0\uFE0F Failed to delete remote branch ${Q}: ${C(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],x=$[1],_=$.slice(2).join(" "),V=J.replace(/^origin\//,"");if(!V.startsWith("buddy/"))continue;try{let j=new Date(_);X.push({name:V,sha:x,lastCommitDate:j})}catch{this.logger.warn(`\u26A0\uFE0F Failed to parse date for branch ${V}: ${_}`),X.push({name:V,sha:x,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 x=await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/commits/${J.commit.sha}`);return{name:J.name,sha:J.commit.sha,lastCommitDate:new Date(x.commit.committer.date)}}catch(x){return this.logger.warn(`\u26A0\uFE0F Failed to get commit info for branch ${J.name}: ${C(x)}`),{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=[],x=[];this.logger.info(`\uD83E\uDDF9 Cleaning up ${$.length} stale branches...`);let _=5;for(let V=0;V<$.length;V+=_){let j=$.slice(V,V+_),K=Math.floor(V/_)+1,q=Math.ceil($.length/_);this.logger.info(`\uD83D\uDD04 Processing batch ${K}/${q} (${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){x.push(G.name),this.logger.warn(`\u274C Failed to delete ${G.name}: ${C(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: ${x.length} branches`),x.length>0)this.logger.info("\u274C Failed branches:"),x.forEach((V)=>this.logger.info(` - ${V}`));return{deleted:J,failed:x}}async apiRequest(Q,X,Y,Z=0){let[$,J]=Q.split(" "),x=`${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 L(x,{...V,retries:Z,onRetry:({delayMs:K,reason:q})=>this.logger.info(`\u23F3 ${q} on ${$} ${J}, retrying in ${Math.round(K/1000)}s...`)});if(!j.ok){let K=await j.text(),q=_?"token present ([REDACTED])":"NO TOKEN \u2014 ensure GITHUB_TOKEN or BUDDY_TOKEN is set";throw new A(`GitHub API error: ${j.status} ${j.statusText}
34
+ URL: ${$} ${x}
35
+ Auth: ${q}
36
+ Repo: ${this.owner}/${this.repo}
37
+ ${K}`,j.status,$,x,`${this.owner}/${this.repo}`,K)}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}: ${C(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 x=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:x,timestamp:Date.now()}),this.logger.info(`\u2705 Fetched and cached ${x.length} issues (state: ${Q})`),x}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}: ${C(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}: ${C(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 x=J.errors.map((_)=>_.message).join("; ");return this.logger.info(`\u26A0\uFE0F Failed to ${Y} issue #${Q}: ${x}`),!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}: ${C(Z)}`),!1}}}
38
+ export{f as Jc};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Rj as K}from"./chunk-akffynkc.js";import{Fk as N}from"./chunk-6g1y9yqh.js";function F(q){return(q.split(/[/\\]/).pop()||"")==="build.zig.zon"}async function S(q,z){try{if(!F(q))return null;let J=[],j=z.match(/\.dependencies\s*=\s*\.?\{/);if(j){let Q=j.index+j[0].length,A=1,T=Q;while(T<z.length&&A>0){if(z[T]==="{")A++;else if(z[T]==="}")A--;T++}let G=z.slice(Q,T-1),O=/\.(\w+)\s*=\s*\.?\{/g,W=O.exec(G);while(W!==null){let b=W[1],X=W.index+W[0].length,Y=1,V=X;while(V<G.length&&Y>0){if(G[V]==="{")Y++;else if(G[V]==="}")Y--;V++}let _=G.slice(X,V-1),$=_.match(/\.url\s*=\s*"([^"]+)"/),R=_.match(/\.hash\s*=\s*"([^"]+)"/);if($){let H=$[1],v=H.match(/\/v?(\d+\.\d+\.\d+(?:-[\w.]+)?)/i),E=v?v[1]:"unknown",Z={url:H};if(R)Z.hash=R[1];J.push({name:b,currentVersion:E,type:"zig-dependencies",file:q,metadata:Z})}W=O.exec(G)}}return{path:q,type:"build.zig.zon",content:z,dependencies:J}}catch(J){return K().warn(`Failed to parse Zig manifest ${q}:`,J),null}}async function w(q,z,J){try{if(!F(q))return K().info(`\u26A0\uFE0F updateZigManifest: ${q} is not a Zig manifest file, returning original content`),z;let j=z;for(let Q of J){let A=Q.name.trim(),T=new RegExp(`(\\.${A}\\s*=\\s*\\.?\\{[^}]*\\.url\\s*=\\s*")([^"]+)("[^}]*\\})`,"s"),G=j.match(T);if(G){let[O,W,b,X]=G,Y=/\/v?(\d+\.\d+\.\d+(?:-[\w.]+)?)/i,V=b.replace(Y,(H)=>{return H.startsWith("/v")?`/v${Q.newVersion}`:`/${Q.newVersion}`}),_=Q.resolved?.hash,$=X;if(_)$=X.replace(/(\.hash\s*=\s*")([^"]+)(")/,`$1${_}$3`);else if(/\.hash\s*=/.test(X)){K().warn(`\u26A0\uFE0F No hash available for ${A}; leaving ${q} unchanged to avoid a hash mismatch`);continue}let R=`${W}${V}${$}`;j=j.replace(O,R),K().info(`\u2705 Updated ${A} from ${G[2]} to ${V}`)}else K().warn(`\u26A0\uFE0F Could not find dependency block for ${A} in ${q}`)}return j}catch(j){return K().warn(`Failed to update Zig manifest ${q}:`,j),z}}async function U(q){let z=[],J=new Map;for(let j of q)if(F(j.file)){if(!J.has(j.file))J.set(j.file,[]);J.get(j.file).push(j)}for(let[j,Q]of J)try{let A=await import("fs");if(A.existsSync(j)){let T=A.readFileSync(j,"utf-8"),G=await w(j,T,Q);if(G!==T)z.push({path:j,content:G,type:"update"}),K().info(`\u2705 Generated update for ${j} with ${Q.length} package changes`);else K().info(`\u2139\uFE0F No changes needed for ${j} - versions already up to date`)}else K().warn(`\u26A0\uFE0F Zig manifest file ${j} does not exist`)}catch(A){K().warn(`Failed to generate updates for Zig manifest ${j}:`,A)}return z}
3
- export{F as Ke,S as Le,w as Me,U as Ne};
2
+ import{Fh as K}from"./chunk-hfjywbbc.js";import{Wk as N}from"./chunk-q4t568hv.js";function F(q){return(q.split(/[/\\]/).pop()||"")==="build.zig.zon"}async function S(q,z){try{if(!F(q))return null;let J=[],j=z.match(/\.dependencies\s*=\s*\.?\{/);if(j){let Q=j.index+j[0].length,A=1,T=Q;while(T<z.length&&A>0){if(z[T]==="{")A++;else if(z[T]==="}")A--;T++}let G=z.slice(Q,T-1),O=/\.(\w+)\s*=\s*\.?\{/g,W=O.exec(G);while(W!==null){let b=W[1],X=W.index+W[0].length,Y=1,V=X;while(V<G.length&&Y>0){if(G[V]==="{")Y++;else if(G[V]==="}")Y--;V++}let _=G.slice(X,V-1),$=_.match(/\.url\s*=\s*"([^"]+)"/),R=_.match(/\.hash\s*=\s*"([^"]+)"/);if($){let H=$[1],v=H.match(/\/v?(\d+\.\d+\.\d+(?:-[\w.]+)?)/i),E=v?v[1]:"unknown",Z={url:H};if(R)Z.hash=R[1];J.push({name:b,currentVersion:E,type:"zig-dependencies",file:q,metadata:Z})}W=O.exec(G)}}return{path:q,type:"build.zig.zon",content:z,dependencies:J}}catch(J){return K().warn(`Failed to parse Zig manifest ${q}:`,J),null}}async function w(q,z,J){try{if(!F(q))return K().info(`\u26A0\uFE0F updateZigManifest: ${q} is not a Zig manifest file, returning original content`),z;let j=z;for(let Q of J){let A=Q.name.trim(),T=new RegExp(`(\\.${A}\\s*=\\s*\\.?\\{[^}]*\\.url\\s*=\\s*")([^"]+)("[^}]*\\})`,"s"),G=j.match(T);if(G){let[O,W,b,X]=G,Y=/\/v?(\d+\.\d+\.\d+(?:-[\w.]+)?)/i,V=b.replace(Y,(H)=>{return H.startsWith("/v")?`/v${Q.newVersion}`:`/${Q.newVersion}`}),_=Q.resolved?.hash,$=X;if(_)$=X.replace(/(\.hash\s*=\s*")([^"]+)(")/,`$1${_}$3`);else if(/\.hash\s*=/.test(X)){K().warn(`\u26A0\uFE0F No hash available for ${A}; leaving ${q} unchanged to avoid a hash mismatch`);continue}let R=`${W}${V}${$}`;j=j.replace(O,R),K().info(`\u2705 Updated ${A} from ${G[2]} to ${V}`)}else K().warn(`\u26A0\uFE0F Could not find dependency block for ${A} in ${q}`)}return j}catch(j){return K().warn(`Failed to update Zig manifest ${q}:`,j),z}}async function U(q){let z=[],J=new Map;for(let j of q)if(F(j.file)){if(!J.has(j.file))J.set(j.file,[]);J.get(j.file).push(j)}for(let[j,Q]of J)try{let A=await import("fs");if(A.existsSync(j)){let T=A.readFileSync(j,"utf-8"),G=await w(j,T,Q);if(G!==T)z.push({path:j,content:G,type:"update"}),K().info(`\u2705 Generated update for ${j} with ${Q.length} package changes`);else K().info(`\u2139\uFE0F No changes needed for ${j} - versions already up to date`)}else K().warn(`\u26A0\uFE0F Zig manifest file ${j} does not exist`)}catch(A){K().warn(`Failed to generate updates for Zig manifest ${j}:`,A)}return z}
3
+ export{F as Se,S as Te,w as Ue,U as Ve};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{aa as a,ba as b,ca as c,da as d,ea as e,fa as f,ga as g,ha as h,ia as i,ja as j}from"./chunk-69qyr9ef.js";import"./chunk-q4t568hv.js";export{d as similarity,j as renderQuickLinks,b as renderPackageContext,h as parseQuickSelection,a as findMentionedPackages,e as findDuplicates,c as constrainLabels,i as clearQuickSelection,f as QUICK_LINKS_MARKER,g as QUICK_ACTIONS};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var{semver:B}=globalThis.Bun;function G(j){return[...j].sort((q,k)=>B.order(k,q))}function D(j,q){let k=j.trim();if(!k||k==="*"||k==="latest")return!0;if(/^(?:workspace|file|link|git|github|npm):/i.test(k)||k.includes("/"))return!0;try{return B.satisfies(q,k)}catch{return!0}}function H(j){let q=G(j.available);if(q.length===0)return null;let k=q[0],z=q.find((A)=>j.declared.every((E)=>D(E.range,A)));if(!z)return null;let C=j.declared.filter((A)=>!D(A.range,k)).filter((A)=>A.by!==I);if(B.order(j.installed,z)<0)return{name:j.name,kind:"lockfile",installed:j.installed,reachable:z,latest:k,capping:C};if(C.length>0&&B.order(z,k)<0)return{name:j.name,kind:"capped",installed:j.installed,reachable:z,latest:k,capping:C};return null}var I="root";function L(j){let q=[];for(let k of j){let z=H(k);if(z)q.push(z)}return q.sort((k,z)=>{if(k.kind!==z.kind)return k.kind==="capped"?-1:1;return B.order(z.latest,k.latest)})}function M(j){let q=`${j.name} ${j.installed} is installed, ${j.reachable} is reachable`;if(j.kind==="lockfile")return`${q}. Nothing is capping it - the lockfile is behind.`;let k=j.capping.map((z)=>`${z.by} (${z.range})`).join(", ");return j.reachable===j.latest?`${q}, and ${j.latest} exists but is capped by ${k}.`:`${q}. ${j.latest} exists but is capped by ${k}.`}
3
- export{H as vb,I as wb,L as xb,M as yb};
3
+ export{H as Hb,I as Ib,L as Jb,M as Kb};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{gf as a,hf as b,if as c}from"./chunk-8hjvthz4.js";import"./chunk-yngahb11.js";import"./chunk-08x5b93v.js";import"./chunk-p6qbqsyp.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-c8rzx3a1.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as matchesGlobs,c as appendUpgradeReport,b as analyzeGroupMajors};
@@ -13,4 +13,4 @@ var G=["pretty","json","github","agent"];function Q(k,j){switch(k){case"staged":
13
13
  `);if(j<1||j>z.length)return null;return z.splice(j-1,1,...q.split(`
14
14
  `)),z.join(`
15
15
  `)}function P(k,j="major"){let q=["critical","major","minor","nit"],z=q.indexOf(j);return k.some((D)=>q.indexOf(D.severity)<=z)}
16
- export{G as Rd,Q as Sd,L as Td,X as Ud,Z as Vd,$ as Wd,B as Xd,N as Yd,O as Zd,P as _d};
16
+ export{G as yd,Q as zd,L as Ad,X as Bd,Z as Cd,$ as Dd,B as Ed,N as Fd,O as Gd,P as Hd};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{$c as a}from"./chunk-phfmnnne.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{a as DeprecatedDependenciesChecker};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Rj as X}from"./chunk-akffynkc.js";import"./chunk-6g1y9yqh.js";import{readFileSync as _}from"fs";function L(q){let z=q.split("/").pop()||"";return z==="composer.json"||z==="composer.lock"}async function R(q,z){try{let j=JSON.parse(z),A=[];if(j.require)J(j.require,"require",q,A);if(j["require-dev"])J(j["require-dev"],"require-dev",q,A);return{path:q,type:"composer.json",content:z,dependencies:A}}catch(j){return X().warn(`Failed to parse composer.json file ${q}:`,j),null}}async function S(q,z){try{let j=JSON.parse(z),A=[];if(j.packages){for(let b of j.packages)if(b.name&&b.version)A.push({name:b.name,currentVersion:b.version,type:"require",file:q})}if(j["packages-dev"]){for(let b of j["packages-dev"])if(b.name&&b.version)A.push({name:b.name,currentVersion:b.version,type:"require-dev",file:q})}return{path:q,type:"composer.lock",content:z,dependencies:A}}catch(j){return X().warn(`Failed to parse composer.lock file ${q}:`,j),null}}async function v(q,z){let j=q.split("/").pop()||"";if(j==="composer.json")return R(q,z);if(j==="composer.lock")return S(q,z);return null}function J(q,z,j,A){for(let[b,Z]of Object.entries(q)){if(b==="php"||b.startsWith("ext-"))continue;if(b.includes("/"))A.push({name:b,currentVersion:Z,type:z,file:j})}}async function U(q){let z=[],j=q.filter((b)=>b.file.endsWith("composer.json"));if(j.length===0)return z;let A=new Map;for(let b of j){if(!A.has(b.file))A.set(b.file,[]);A.get(b.file).push({name:b.name,newVersion:b.newVersion})}for(let[b,Z]of A)try{let K=_(b,"utf-8"),T=JSON.parse(K);for(let E of Z){let Y=!1;if(T.require&&T.require[E.name]){let H=T.require[E.name],O;if(H.includes(",")){let G=H.match(/\d+\.\d+(?:\.\d+)?/),Q=G?G[0]:null;O=H.replace(/\d+\.\d+(?:\.\d+)?/g,(W)=>{return Q!==null&&W===Q?E.newVersion:W})}else{let G=H.match(/^(\D*)/);O=`${G?G[1]:""}${E.newVersion}`}let $=new RegExp(`("${E.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"\\s*:\\s*")([^"]+)(")`,"g");K=K.replace($,`$1${O}$3`),Y=!0}if(!Y&&T["require-dev"]&&T["require-dev"][E.name]){let H=T["require-dev"][E.name],O;if(H.includes(",")){let G=H.match(/\d+\.\d+(?:\.\d+)?/),Q=G?G[0]:null;O=H.replace(/\d+\.\d+(?:\.\d+)?/g,(W)=>{return Q!==null&&W===Q?E.newVersion:W})}else{let G=H.match(/^(\D*)/);O=`${G?G[1]:""}${E.newVersion}`}let $=new RegExp(`("${E.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"\\s*:\\s*")([^"]+)(")`,"g");K=K.replace($,`$1${O}$3`),Y=!0}if(!Y)X().warn(`Package ${E.name} not found in ${b}`)}z.push({path:b,content:K,type:"update"})}catch(K){X().error(`Failed to update ${b}:`,K)}return z}export{S as parseComposerLock,R as parseComposerJson,v as parseComposerFile,L as isComposerFile,U as generateComposerUpdates};
2
+ import{Fh as X}from"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";import{readFileSync as _}from"fs";function L(q){let z=q.split("/").pop()||"";return z==="composer.json"||z==="composer.lock"}async function R(q,z){try{let j=JSON.parse(z),A=[];if(j.require)J(j.require,"require",q,A);if(j["require-dev"])J(j["require-dev"],"require-dev",q,A);return{path:q,type:"composer.json",content:z,dependencies:A}}catch(j){return X().warn(`Failed to parse composer.json file ${q}:`,j),null}}async function S(q,z){try{let j=JSON.parse(z),A=[];if(j.packages){for(let b of j.packages)if(b.name&&b.version)A.push({name:b.name,currentVersion:b.version,type:"require",file:q})}if(j["packages-dev"]){for(let b of j["packages-dev"])if(b.name&&b.version)A.push({name:b.name,currentVersion:b.version,type:"require-dev",file:q})}return{path:q,type:"composer.lock",content:z,dependencies:A}}catch(j){return X().warn(`Failed to parse composer.lock file ${q}:`,j),null}}async function v(q,z){let j=q.split("/").pop()||"";if(j==="composer.json")return R(q,z);if(j==="composer.lock")return S(q,z);return null}function J(q,z,j,A){for(let[b,Z]of Object.entries(q)){if(b==="php"||b.startsWith("ext-"))continue;if(b.includes("/"))A.push({name:b,currentVersion:Z,type:z,file:j})}}async function U(q){let z=[],j=q.filter((b)=>b.file.endsWith("composer.json"));if(j.length===0)return z;let A=new Map;for(let b of j){if(!A.has(b.file))A.set(b.file,[]);A.get(b.file).push({name:b.name,newVersion:b.newVersion})}for(let[b,Z]of A)try{let K=_(b,"utf-8"),T=JSON.parse(K);for(let E of Z){let Y=!1;if(T.require&&T.require[E.name]){let H=T.require[E.name],O;if(H.includes(",")){let G=H.match(/\d+\.\d+(?:\.\d+)?/),Q=G?G[0]:null;O=H.replace(/\d+\.\d+(?:\.\d+)?/g,(W)=>{return Q!==null&&W===Q?E.newVersion:W})}else{let G=H.match(/^(\D*)/);O=`${G?G[1]:""}${E.newVersion}`}let $=new RegExp(`("${E.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"\\s*:\\s*")([^"]+)(")`,"g");K=K.replace($,`$1${O}$3`),Y=!0}if(!Y&&T["require-dev"]&&T["require-dev"][E.name]){let H=T["require-dev"][E.name],O;if(H.includes(",")){let G=H.match(/\d+\.\d+(?:\.\d+)?/),Q=G?G[0]:null;O=H.replace(/\d+\.\d+(?:\.\d+)?/g,(W)=>{return Q!==null&&W===Q?E.newVersion:W})}else{let G=H.match(/^(\D*)/);O=`${G?G[1]:""}${E.newVersion}`}let $=new RegExp(`("${E.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"\\s*:\\s*")([^"]+)(")`,"g");K=K.replace($,`$1${O}$3`),Y=!0}if(!Y)X().warn(`Package ${E.name} not found in ${b}`)}z.push({path:b,content:K,type:"update"})}catch(K){X().error(`Failed to update ${b}:`,K)}return z}export{S as parseComposerLock,R as parseComposerJson,v as parseComposerFile,L as isComposerFile,U as generateComposerUpdates};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{bc as a,cc as b,dc as c,ec as d,fc as e,gc as f,hc as g,ic as h,jc as i,kc as j,lc as k,mc as l,nc as m,oc as n,pc as o,qc as p,rc as q,sc as r,tc as s,uc as t,vc as u}from"./chunk-vh504tcv.js";import"./chunk-1h3ey7k5.js";import"./chunk-akffynkc.js";import"./chunk-6g1y9yqh.js";export{t as stripOperators,l as splitConstraint,s as scanEcosystems,o as rustAdapter,n as rubyAdapter,c as regenerateWith,u as regenerateLockfiles,m as pythonAdapter,k as pep440UpdateType,h as parsePep440,f as numericUpdateType,j as isPep440Prerelease,g as goAdapter,a as escapeRegex,b as detectFiles,i as comparePep440,e as compareNumeric,d as commandAvailable,r as adapterNamed,q as adapterFor,p as BUILTIN_ADAPTERS};
2
+ import{Ac as m,Bc as n,Cc as o,Dc as p,Ec as q,Fc as r,Gc as s,Hc as t,Ic as u,oc as a,pc as b,qc as c,rc as d,sc as e,tc as f,uc as g,vc as h,wc as i,xc as j,yc as k,zc as l}from"./chunk-6p4qz8qv.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{t as stripOperators,l as splitConstraint,s as scanEcosystems,o as rustAdapter,n as rubyAdapter,c as regenerateWith,u as regenerateLockfiles,m as pythonAdapter,k as pep440UpdateType,h as parsePep440,f as numericUpdateType,j as isPep440Prerelease,g as goAdapter,a as escapeRegex,b as detectFiles,i as comparePep440,e as compareNumeric,d as commandAvailable,r as adapterNamed,q as adapterFor,p as BUILTIN_ADAPTERS};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Da as a}from"./chunk-657nbbp7.js";import"./chunk-dqbk3kcj.js";import"./chunk-phfmnnne.js";import"./chunk-r763e19p.js";import"./chunk-be629jhq.js";import"./chunk-pkr6905p.js";import"./chunk-eseshkd0.js";import"./chunk-11hdrnf6.js";import"./chunk-mkzmjg3f.js";import"./chunk-p8tmms5h.js";import"./chunk-ytmxd5fk.js";import"./chunk-b9escac0.js";import"./chunk-g30dr44w.js";import"./chunk-2et8yavs.js";import"./chunk-txtrpypt.js";import"./chunk-8hjvthz4.js";import"./chunk-yngahb11.js";import"./chunk-08x5b93v.js";import"./chunk-p6qbqsyp.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-c8rzx3a1.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as Scheduler};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  import{existsSync as O,readdirSync as R,statSync as A}from"fs";import{join as U,relative as L}from"path";function T(z,K){try{let V=Bun.YAML.parse(K);if(!V||typeof V!=="object")return null;return{file:z,raw:K,data:V}}catch{return null}}function B(z,K){if(!K)return;let V=z.indexOf(K);if(V<0)return;let M=1;for(let Y=0;Y<V;Y++)if(z.charCodeAt(Y)===10)M++;return M}async function W(z){let K=U(z,".github","workflows");if(!O(K))return[];let V=R(K),M=[];for(let Y of V){if(!Y.endsWith(".yml")&&!Y.endsWith(".yaml"))continue;let Q=U(K,Y);if(!A(Q).isFile())continue;let Z=await Bun.file(Q).text(),N=T(L(z,Q),Z);if(N)M.push(N)}return M}function*X(z){let K=z.data.jobs;if(!K||typeof K!=="object")return;for(let[V,M]of Object.entries(K)){if(!M||typeof M!=="object")continue;let Y=M.steps;if(!Array.isArray(Y))continue;for(let Q=0;Q<Y.length;Q++){let Z=Y[Q];if(!Z||typeof Z!=="object")continue;yield{jobId:V,job:M,stepIndex:Q,step:Z}}}}function*$(z){let K=z.data.jobs;if(!K||typeof K!=="object")return;for(let[V,M]of Object.entries(K)){if(!M||typeof M!=="object")continue;yield{jobId:V,job:M}}}var F={id:"bash-injection",defaultSeverity:"error",description:"Avoid `${{ }}` interpolation of untrusted input inside `run:` blocks.",check(z){let K=[];for(let{jobId:V,step:M,stepIndex:Y}of X(z)){let Q=typeof M.run==="string"?M.run:null;if(!Q)continue;let Z=[...Q.matchAll(/\$\{\{\s*([^}]+?)\s*\}\}/g)];for(let N of Z){let C=N[1].trim();if(I(C))continue;K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\`, step ${Y+1}: \`${C}\` is interpolated into a shell.`,detail:"GitHub evaluates `${{ ... }}` before the shell runs, so attacker-controlled values become part of the command line. Move the value into `env:` and reference it as a shell variable.",file:z.file,line:B(z.raw,N[0]),fix:'Put the value in `env:` and reference it with `"$NAME"` instead.'})}}return K}},_=["secrets.","vars.","runner.","env.","inputs.","matrix.","strategy.","job.","steps.","needs."],S=new Set(["github.repository","github.repository_owner","github.workflow","github.run_id","github.run_number","github.run_attempt","github.event_name","github.sha","github.ref_name","github.token","github.actor","github.actor_id","github.api_url","github.server_url","github.graphql_url","github.workspace","github.action","github.action_path","github.action_ref","github.action_repository","github.action_status","github.job","github.job_workflow_sha"]);function I(z){if(S.has(z))return!0;return _.some((K)=>z.startsWith(K))}var J={id:"dangerous-pull-request-target",defaultSeverity:"error",description:"Avoid checking out PR-author code from a `pull_request_target` workflow.",check(z){if(!x(z.data.on,"pull_request_target"))return[];let K=[];for(let{jobId:V,step:M}of X(z)){if(!(typeof M.uses==="string"?M.uses:"").startsWith("actions/checkout@"))continue;let Q=typeof M.with?.ref==="string"?M.with.ref:null;if(!Q)continue;if(Q.includes("pull_request")||Q.includes("head.sha")||Q.includes("head.ref")||Q.includes("github.head_ref"))K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\` checks out PR-author code under \`pull_request_target\`.`,detail:"This grants attacker-controlled code access to repository secrets and write tokens. Move the build to `pull_request` or run untrusted code in a sandboxed second workflow without secrets.",file:z.file,line:B(z.raw,Q),fix:"Either switch the trigger to `pull_request`, or split into two workflows: one privileged (no checkout of head) and one unprivileged (checkout of head, no secrets)."})}return K}};function x(z,K){if(typeof z==="string")return z===K;if(Array.isArray(z))return z.includes(K);if(z&&typeof z==="object")return K in z;return!1}var q={id:"excessive-permissions",defaultSeverity:"warning",description:"Workflows and jobs should declare a least-privilege `permissions:` block.",check(z){let K=[],V=z.data.permissions;if(V===void 0)K.push({ruleId:this.id,severity:this.defaultSeverity,message:"Workflow does not declare top-level `permissions:`.",detail:"Without an explicit `permissions:` block, jobs inherit the repository default \u2014 historically `write-all`. Add a least-privilege block at the workflow root.",file:z.file,line:1,fix:"Add `permissions:\\n contents: read` at the top of the workflow, then narrow per-job as needed."});else if(V==="write-all")K.push({ruleId:this.id,severity:"error",message:"Workflow grants `permissions: write-all`.",file:z.file,line:B(z.raw,"write-all"),fix:"Replace with explicit per-scope grants (e.g. `contents: read`, `pull-requests: write`)."});else if(V!=="read-all"&&typeof V==="object")K.push(...P(this.id,z.file,z.raw,V,"workflow"));for(let{jobId:M,job:Y}of $(z)){let Q=Y.permissions;if(Q===void 0)continue;if(Q==="write-all")K.push({ruleId:this.id,severity:"error",message:`Job \`${M}\` grants \`permissions: write-all\`.`,file:z.file,line:B(z.raw,"write-all"),fix:"Replace with explicit per-scope grants."});else if(Q!=="read-all"&&typeof Q==="object")K.push(...P(this.id,z.file,z.raw,Q,`job \`${M}\``))}return K}};function P(z,K,V,M,Y){let Q=[];if(typeof M!=="object"||M===null)return Q;for(let[Z,N]of Object.entries(M))if(N==="write"&&(Z==="actions"||Z==="id-token"))Q.push({ruleId:z,severity:"warning",message:`${Y} grants \`${Z}: write\` \u2014 verify this is required.`,detail:Z==="id-token"?"`id-token: write` is needed for OIDC federation but should never be combined with running untrusted code.":"`actions: write` allows the workflow to dispatch other workflows, increasing blast radius if compromised.",file:K,line:B(V,`${Z}: write`)});return Q}var D={id:"missing-timeout",defaultSeverity:"warning",description:"Jobs should declare an explicit `timeout-minutes` to bound runaway execution.",check(z){let K=[];for(let{jobId:V,job:M}of $(z)){let Y=M["timeout-minutes"];if(typeof Y==="number"&&Y>0)continue;K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\` has no \`timeout-minutes\`.`,file:z.file,line:B(z.raw,`${V}:`),fix:"Add `timeout-minutes: <n>` (15\u201360 is a reasonable default for most CI jobs)."})}return K}};var G={id:"self-hosted-exposure",defaultSeverity:"warning",description:"Self-hosted runners should be scoped with additional labels, not used bare.",check(z){let K=[];for(let{jobId:V,job:M}of $(z)){let Y=M["runs-on"];if(!Y)continue;if(typeof Y==="string"){if(Y==="self-hosted")K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\` uses bare \`runs-on: self-hosted\`.`,file:z.file,line:B(z.raw,"runs-on: self-hosted"),fix:"Add at least one scoping label, e.g. `runs-on: [self-hosted, my-project]`, and disable persistence on the runner."});continue}if(Array.isArray(Y)){let Q=Y.filter((Z)=>typeof Z==="string");if(Q.includes("self-hosted")&&Q.length===1)K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\` uses \`runs-on: [self-hosted]\` with no additional labels.`,file:z.file,line:B(z.raw,"self-hosted"),fix:"Add at least one scoping label (project name, environment) so the pool is explicit."})}}return K}};var v=/^[0-9a-f]{40}$/i,E={id:"unpinned-action",defaultSeverity:"warning",description:"Third-party actions should be pinned to a full commit SHA, not a tag or branch.",check(z){let K=[];for(let{step:V}of X(z)){let M=typeof V.uses==="string"?V.uses:null;if(!M)continue;if(M.startsWith("./")||M.startsWith("docker://"))continue;let Y=M.lastIndexOf("@");if(Y<0){K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Action \`${M}\` is missing a version reference.`,file:z.file,line:B(z.raw,M),fix:`Pin to a commit SHA: \`${M}@<full-sha> # vX.Y.Z\``});continue}let Q=M.slice(0,M.indexOf("/")),Z=M.slice(Y+1);if(Q==="actions"||Q==="github")continue;if(v.test(Z))continue;K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Action \`${M}\` is pinned to a mutable ref (\`${Z}\`).`,file:z.file,line:B(z.raw,M),fix:`Replace with a SHA-pinned reference: \`${M.slice(0,Y)}@<full-sha> # ${Z}\``})}return K}};var H=[E,q,J,F,D,G];async function Tz(z,K={}){let V=await W(z);return y(V,K)}function y(z,K={}){let V=(K.rules??H).filter((Q)=>{return!K.ignore?.includes(Q.id)}),M=[];for(let Q of z)for(let Z of V){let N=Z.check(Q);for(let C of N)M.push(C)}let Y=M.some((Q)=>Q.severity==="error");return{workflows:z,findings:M,failed:Y}}
3
- export{Tz as Ed,y as Fd};
3
+ export{Tz as ae,y as be};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{nd as a}from"./chunk-11hdrnf6.js";import"./chunk-g30dr44w.js";import"./chunk-0hc97k0t.js";import"./chunk-3901s7h9.js";import"./chunk-jtxcr5yw.js";import"./chunk-qd2s51gc.js";import"./chunk-193abzy6.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-g24hav8e.js";import"./chunk-q4t568hv.js";export{a as PullRequestGenerator};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{W as a,X as b}from"./chunk-929h6hhp.js";import"./chunk-tjc2vgwn.js";import"./chunk-0eg3kxb5.js";import"./chunk-eseshkd0.js";import"./chunk-cwfkm7h9.js";import"./chunk-mkzmjg3f.js";import"./chunk-nrr8z2z7.js";import"./chunk-xs12dtf1.js";import"./chunk-p8tmms5h.js";import"./chunk-1cpdz49v.js";import"./chunk-cgvt98pd.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{b as renderDoctorReport,a as diagnose};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ae as a,be as b}from"./chunk-xs12dtf1.js";import"./chunk-q4t568hv.js";export{b as auditParsed,a as audit};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Be as K}from"./chunk-q9n79dd3.js";import{Ye as D}from"./chunk-978wtejw.js";var F=[[0,59],[0,23],[1,31],[1,12],[0,6]];function I(j,J){let[U,B]=F[J],H=new Set;for(let Q of j.split(",")){let[X,Z]=Q.split("/"),q=Z===void 0?1:Number(Z);if(!Number.isInteger(q)||q<1)return null;let $,G;if(X==="*")$=U,G=B;else if(X.includes("-")){let[Y,_]=X.split("-").map(Number);if(!Number.isInteger(Y)||!Number.isInteger(_))return null;$=Y,G=_}else{let Y=Number(X);if(!Number.isInteger(Y))return null;$=Y,G=Y}if($<U||G>B||$>G)return null;for(let Y=$;Y<=G;Y+=q)H.add(Y)}return H.size>0?H:null}function L(j){let J=j.trim().split(/\s+/);if(J.length!==5)return null;let U=J.map((Z,q)=>I(Z,q));if(U.some((Z)=>Z===null))return null;let[,B,H,Q,X]=U;return{hours:B,daysOfMonth:H,months:Q,daysOfWeek:X}}function N(j,J){if(!J)return{hour:j.getHours(),day:j.getDate(),month:j.getMonth()+1,weekday:j.getDay()};let U=new Intl.DateTimeFormat("en-US",{timeZone:J,hour:"numeric",hour12:!1,day:"numeric",month:"numeric",weekday:"short"}),B=Object.fromEntries(U.formatToParts(j).map((Q)=>[Q.type,Q.value])),H=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return{hour:Number(B.hour)%24,day:Number(B.day),month:Number(B.month),weekday:Math.max(0,H.indexOf(B.weekday))}}function C(j,J=new Date,U){let B=L(j);if(!B)return!1;let{hour:H,day:Q,month:X,weekday:Z}=N(J,U);if(!B.hours.has(H)||!B.months.has(X))return!1;let q=B.daysOfMonth.size<31,$=B.daysOfWeek.size<7;if(q&&$)return B.daysOfMonth.has(Q)||B.daysOfWeek.has(Z);return B.daysOfMonth.has(Q)&&B.daysOfWeek.has(Z)}function W(j){if(j.dependencyType==="github-actions")return"github-actions";if(j.dependencyType==="docker-image")return"docker";if(j.dependencyType==="zig-dependencies")return"zig";if(j.dependencyType==="python"||j.dependencyType==="rust"||j.dependencyType==="go"||j.dependencyType==="ruby")return j.dependencyType;if(j.file.endsWith("composer.json")||j.file.endsWith("composer.lock"))return"composer";if(j.file.endsWith("package.json"))return"npm";return"pkgx"}function A(j,J,U=new Date){if(j.matchPackages?.length){if(!K(j.matchPackages).matches(J.name))return!1}if(j.matchEcosystems?.length&&!j.matchEcosystems.includes(W(J)))return!1;if(j.matchDepTypes?.length&&!j.matchDepTypes.includes(J.dependencyType))return!1;if(j.matchUpdateTypes?.length&&!j.matchUpdateTypes.includes(J.updateType))return!1;if(j.matchFiles?.length){if(!K(j.matchFiles).matches(J.file))return!1}if(j.matchCurrentVersion&&!E(J.currentVersion,j.matchCurrentVersion))return!1;if(j.schedule&&!C(j.schedule,U,j.scheduleTimezone))return!1;return!0}function E(j,J){let U=j.replace(/^[\^~>=<\s]+/,"").trim();return U?D(U,J):!1}function S(j,J=[],U=new Date){let B={enabled:!0,labels:[],reviewers:[],assignees:[],prPriority:0};for(let H of J){if(!A(H,j,U))continue;if(H.enabled!==void 0)B.enabled=H.enabled;if(H.strategy!==void 0)B.strategy=H.strategy;if(H.groupName!==void 0)B.groupName=H.groupName;if(H.autoMerge!==void 0)B.autoMerge=H.autoMerge;if(H.minimumReleaseAge!==void 0)B.minimumReleaseAge=H.minimumReleaseAge;if(H.prPriority!==void 0)B.prPriority=H.prPriority;if(H.autoMigrate!==void 0)B.autoMigrate=H.autoMigrate;for(let Q of H.labels??[])if(!B.labels.includes(Q))B.labels.push(Q);for(let Q of H.reviewers??[])if(!B.reviewers.includes(Q))B.reviewers.push(Q);for(let Q of H.assignees??[])if(!B.assignees.includes(Q))B.assignees.push(Q)}return B}function k(j,J=[],U=new Date){let B=[];for(let H of j){let Q=S(H,J,U);if(!Q.enabled)continue;if(Q.strategy&&!V(Q.strategy,H.updateType))continue;B.push({update:H,effects:Q})}return B}function T(j){let J=new Set,U=new Set,B=new Set,H=0;for(let Q of j)Q.labels.forEach((X)=>J.add(X)),Q.reviewers.forEach((X)=>U.add(X)),Q.assignees.forEach((X)=>B.add(X)),H=Math.max(H,Q.prPriority);return{labels:[...J],reviewers:[...U],assignees:[...B],autoMerge:j.length>0&&j.every((Q)=>Q.autoMerge===!0),prPriority:H,autoMigrate:j.some((Q)=>Q.autoMigrate===!0)}}function V(j,J){switch(j){case"all":return!0;case"major":return J==="major";case"minor":return J==="minor"||J==="patch";case"patch":return J==="patch"}}function b(j=[]){return j.map((J)=>({matchPackages:J.patterns,groupName:J.name,...J.strategy?{strategy:J.strategy}:{}}))}
3
- export{W as Xc,A as Yc,S as Zc,k as _c,T as $c,b as ad};
2
+ import{Jf as K}from"./chunk-1cpdz49v.js";import{cg as D}from"./chunk-0hc97k0t.js";var F=[[0,59],[0,23],[1,31],[1,12],[0,6]];function I(j,J){let[U,B]=F[J],H=new Set;for(let Q of j.split(",")){let[X,Z]=Q.split("/"),q=Z===void 0?1:Number(Z);if(!Number.isInteger(q)||q<1)return null;let $,G;if(X==="*")$=U,G=B;else if(X.includes("-")){let[Y,_]=X.split("-").map(Number);if(!Number.isInteger(Y)||!Number.isInteger(_))return null;$=Y,G=_}else{let Y=Number(X);if(!Number.isInteger(Y))return null;$=Y,G=Y}if($<U||G>B||$>G)return null;for(let Y=$;Y<=G;Y+=q)H.add(Y)}return H.size>0?H:null}function L(j){let J=j.trim().split(/\s+/);if(J.length!==5)return null;let U=J.map((Z,q)=>I(Z,q));if(U.some((Z)=>Z===null))return null;let[,B,H,Q,X]=U;return{hours:B,daysOfMonth:H,months:Q,daysOfWeek:X}}function N(j,J){if(!J)return{hour:j.getHours(),day:j.getDate(),month:j.getMonth()+1,weekday:j.getDay()};let U=new Intl.DateTimeFormat("en-US",{timeZone:J,hour:"numeric",hour12:!1,day:"numeric",month:"numeric",weekday:"short"}),B=Object.fromEntries(U.formatToParts(j).map((Q)=>[Q.type,Q.value])),H=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];return{hour:Number(B.hour)%24,day:Number(B.day),month:Number(B.month),weekday:Math.max(0,H.indexOf(B.weekday))}}function C(j,J=new Date,U){let B=L(j);if(!B)return!1;let{hour:H,day:Q,month:X,weekday:Z}=N(J,U);if(!B.hours.has(H)||!B.months.has(X))return!1;let q=B.daysOfMonth.size<31,$=B.daysOfWeek.size<7;if(q&&$)return B.daysOfMonth.has(Q)||B.daysOfWeek.has(Z);return B.daysOfMonth.has(Q)&&B.daysOfWeek.has(Z)}function W(j){if(j.dependencyType==="github-actions")return"github-actions";if(j.dependencyType==="docker-image")return"docker";if(j.dependencyType==="zig-dependencies")return"zig";if(j.dependencyType==="python"||j.dependencyType==="rust"||j.dependencyType==="go"||j.dependencyType==="ruby")return j.dependencyType;if(j.file.endsWith("composer.json")||j.file.endsWith("composer.lock"))return"composer";if(j.file.endsWith("package.json"))return"npm";return"pkgx"}function A(j,J,U=new Date){if(j.matchPackages?.length){if(!K(j.matchPackages).matches(J.name))return!1}if(j.matchEcosystems?.length&&!j.matchEcosystems.includes(W(J)))return!1;if(j.matchDepTypes?.length&&!j.matchDepTypes.includes(J.dependencyType))return!1;if(j.matchUpdateTypes?.length&&!j.matchUpdateTypes.includes(J.updateType))return!1;if(j.matchFiles?.length){if(!K(j.matchFiles).matches(J.file))return!1}if(j.matchCurrentVersion&&!E(J.currentVersion,j.matchCurrentVersion))return!1;if(j.schedule&&!C(j.schedule,U,j.scheduleTimezone))return!1;return!0}function E(j,J){let U=j.replace(/^[\^~>=<\s]+/,"").trim();return U?D(U,J):!1}function S(j,J=[],U=new Date){let B={enabled:!0,labels:[],reviewers:[],assignees:[],prPriority:0};for(let H of J){if(!A(H,j,U))continue;if(H.enabled!==void 0)B.enabled=H.enabled;if(H.strategy!==void 0)B.strategy=H.strategy;if(H.groupName!==void 0)B.groupName=H.groupName;if(H.autoMerge!==void 0)B.autoMerge=H.autoMerge;if(H.minimumReleaseAge!==void 0)B.minimumReleaseAge=H.minimumReleaseAge;if(H.prPriority!==void 0)B.prPriority=H.prPriority;if(H.autoMigrate!==void 0)B.autoMigrate=H.autoMigrate;for(let Q of H.labels??[])if(!B.labels.includes(Q))B.labels.push(Q);for(let Q of H.reviewers??[])if(!B.reviewers.includes(Q))B.reviewers.push(Q);for(let Q of H.assignees??[])if(!B.assignees.includes(Q))B.assignees.push(Q)}return B}function k(j,J=[],U=new Date){let B=[];for(let H of j){let Q=S(H,J,U);if(!Q.enabled)continue;if(Q.strategy&&!V(Q.strategy,H.updateType))continue;B.push({update:H,effects:Q})}return B}function T(j){let J=new Set,U=new Set,B=new Set,H=0;for(let Q of j)Q.labels.forEach((X)=>J.add(X)),Q.reviewers.forEach((X)=>U.add(X)),Q.assignees.forEach((X)=>B.add(X)),H=Math.max(H,Q.prPriority);return{labels:[...J],reviewers:[...U],assignees:[...B],autoMerge:j.length>0&&j.every((Q)=>Q.autoMerge===!0),prPriority:H,autoMigrate:j.some((Q)=>Q.autoMigrate===!0)}}function V(j,J){switch(j){case"all":return!0;case"major":return J==="major";case"minor":return J==="minor"||J==="patch";case"patch":return J==="patch"}}function b(j=[]){return j.map((J)=>({matchPackages:J.patterns,groupName:J.name,...J.strategy?{strategy:J.strategy}:{}}))}
3
+ export{W as jf,A as kf,S as lf,k as mf,T as nf,V as of,b as pf};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{wb as $}from"./chunk-dfesffnr.js";import"./chunk-6g1y9yqh.js";import{readdir as Z}from"fs/promises";import{join as W}from"path";var w=["dependencies","peerDependencies","optionalDependencies"];async function x(U,V,M,Q){let J=await G(M,Q);if(J.length===0)return[];let H=new Map,z=(q,v,E)=>{let X=H.get(q),Y={by:v,range:E};if(X)X.push(Y);else H.set(q,[Y])};for(let q of U)for(let v of q.dependencies)z(v.name,$,v.currentVersion);for(let q of J)for(let[v,E]of Object.entries(q.ranges))z(v,q.name,E);let D=[];for(let q of J){let v=H.get(q.name);if(!v||v.length===0)continue;try{let E=await V.getPackageMetadata(q.name);if(!E?.versions?.length)continue;D.push({name:q.name,installed:q.version,available:E.versions,declared:v})}catch(E){Q.debug(`Skipping drift analysis for ${q.name}: ${E}`)}}return D}async function G(U,V){let M=W(U,"node_modules"),Q=[],J;try{J=await Z(M)}catch{return V.debug("No node_modules directory, skipping resolution drift analysis"),[]}let H=[];for(let z of J){if(z.startsWith("."))continue;if(z.startsWith("@")){try{let D=await Z(W(M,z));H.push(...D.map((q)=>`${z}/${q}`))}catch{continue}continue}H.push(z)}return await Promise.all(H.map(async(z)=>{try{let D=await Bun.file(W(M,z,"package.json")).json();if(!D.name||!D.version)return;let q={};for(let v of w)Object.assign(q,D[v]??{});Q.push({name:D.name,version:D.version,ranges:q})}catch{}})),Q}export{x as collectDriftInputs};
2
+ import{Ib as $}from"./chunk-vckhctmr.js";import"./chunk-q4t568hv.js";import{readdir as Z}from"fs/promises";import{join as W}from"path";var w=["dependencies","peerDependencies","optionalDependencies"];async function x(U,V,M,Q){let J=await G(M,Q);if(J.length===0)return[];let H=new Map,z=(q,v,E)=>{let X=H.get(q),Y={by:v,range:E};if(X)X.push(Y);else H.set(q,[Y])};for(let q of U)for(let v of q.dependencies)z(v.name,$,v.currentVersion);for(let q of J)for(let[v,E]of Object.entries(q.ranges))z(v,q.name,E);let D=[];for(let q of J){let v=H.get(q.name);if(!v||v.length===0)continue;try{let E=await V.getPackageMetadata(q.name);if(!E?.versions?.length)continue;D.push({name:q.name,installed:q.version,available:E.versions,declared:v})}catch(E){Q.debug(`Skipping drift analysis for ${q.name}: ${E}`)}}return D}async function G(U,V){let M=W(U,"node_modules"),Q=[],J;try{J=await Z(M)}catch{return V.debug("No node_modules directory, skipping resolution drift analysis"),[]}let H=[];for(let z of J){if(z.startsWith("."))continue;if(z.startsWith("@")){try{let D=await Z(W(M,z));H.push(...D.map((q)=>`${z}/${q}`))}catch{continue}continue}H.push(z)}return await Promise.all(H.map(async(z)=>{try{let D=await Bun.file(W(M,z,"package.json")).json();if(!D.name||!D.version)return;let q={};for(let v of w)Object.assign(q,D[v]??{});Q.push({name:D.name,version:D.version,ranges:q})}catch{}})),Q}export{x as collectDriftInputs};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{De as a,Ee as b,Fe as c,Ge as d,He as e,Ie as f}from"./chunk-b9escac0.js";import"./chunk-e68nf7cm.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{e as updateDockerfile,d as resolveDockerDigest,b as parseDockerfile,a as isDockerfile,f as generateDockerfileUpdates,c as fetchLatestDockerImageVersion};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Aj as H}from"./chunk-5k40mwd4.js";import{Lj as M}from"./chunk-1h3ey7k5.js";import{Rj as E}from"./chunk-akffynkc.js";import{Fk as T}from"./chunk-6g1y9yqh.js";import W from"process";function v(J){let q=J.replace(/\\/g,"/");return q.includes(".github/workflows/")&&(q.endsWith(".yml")||q.endsWith(".yaml"))}async function N(J,q){try{if(!v(J))return null;let I=[],j=q.split(`
2
+ import{oh as H}from"./chunk-193abzy6.js";import{zh as M}from"./chunk-e68nf7cm.js";import{Fh as E}from"./chunk-hfjywbbc.js";import{Wk as T}from"./chunk-q4t568hv.js";import W from"process";function v(J){let q=J.replace(/\\/g,"/");return q.includes(".github/workflows/")&&(q.endsWith(".yml")||q.endsWith(".yaml"))}async function N(J,q){try{if(!v(J))return null;let I=[],j=q.split(`
3
3
  `);for(let Q=0;Q<j.length;Q++){let Z=j[Q].trim().match(/^-?\s*uses:\s*(.+)/);if(Z){let _=Z[1].trim().replace(/['"`]/g,"");if(_.startsWith("./")||_.startsWith("docker://"))continue;let K=_.split("@");if(K.length===2){let[X,O]=K;if(!X||!X.trim())continue;let x=O.split("#")[0].trim(),$={name:X.trim(),currentVersion:x,type:"github-actions",file:J};if(!I.find((S)=>S.name===$.name&&S.currentVersion===$.currentVersion))I.push($)}}}return{path:J,type:"github-actions",content:q,dependencies:I}}catch(I){return E().warn(`Failed to parse GitHub Actions file ${J}:`,I),null}}async function A(J,q,I){try{if(!v(J))return q;let j=q;for(let Q of I){let V=Q.name.replace(/\s*\(.*\)$/,""),Y=new RegExp(`((?:^\\s*-\\s*)?uses:\\s*["']?)(${V.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})@(${Q.currentVersion.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")})(["']?)`,"gm");j=j.replace(Y,`$1$2@${Q.newVersion}$4`)}return j}catch(j){return E().warn(`Failed to update GitHub Actions file ${J}:`,j),q}}async function L(J){let q=[],I=new Map;for(let j of J)if(v(j.file)){if(!I.has(j.file))I.set(j.file,[]);I.get(j.file).push(j)}for(let[j,Q]of I)try{let V=await import("fs");if(V.existsSync(j)){let Y=V.readFileSync(j,"utf-8"),Z=await A(j,Y,Q);q.push({path:j,content:Z,type:"update"})}}catch(V){E().warn(`Failed to generate updates for GitHub Actions file ${j}:`,V)}return q}async function R(J){try{if(!J.includes("/"))return E().info(`\u26A0\uFE0F Invalid action name format: ${J}`),null;let[q,I]=J.split("/");E().info(`\uD83D\uDD0D Fetching latest version for ${q}/${I}`);let j={Accept:"application/vnd.github.v3+json","User-Agent":"buddy"},Q=W.env.BUDDY_TOKEN||W.env.GITHUB_TOKEN||W.env.GH_TOKEN;if(Q)j.Authorization=`Bearer ${Q}`;let V=H();E().info(`\uD83D\uDCE1 Trying latest release for ${q}/${I}`);let Y=await M(`${V}/repos/${q}/${I}/releases/latest`,{headers:j});if(Y.ok){let K=await Y.json();if(K.tag_name)return E().info(`\u2705 Found latest release: ${K.tag_name}`),K.tag_name}else E().info(`\u26A0\uFE0F Latest release not found: ${Y.status} ${Y.statusText}`);E().info(`\uD83D\uDCE1 Trying all releases for ${q}/${I}`);let Z=await M(`${V}/repos/${q}/${I}/releases?per_page=10`,{headers:j});if(Z.ok){let K=await Z.json();if(!Array.isArray(K))E().info("\u26A0\uFE0F Unexpected releases response format (expected array)");else{E().info(`\uD83D\uDCCB Found ${K.length} releases`);let X=K.filter((O)=>O.tag_name&&!O.tag_name.includes("-")).sort((O,x)=>{let $=O.published_at?new Date(O.published_at).getTime():0;return(x.published_at?new Date(x.published_at).getTime():0)-$});if(X.length>0)return E().info(`\u2705 Found latest stable release: ${X[0].tag_name}`),X[0].tag_name||null}}else E().info(`\u26A0\uFE0F Releases not found: ${Z.status} ${Z.statusText}`);E().info(`\uD83D\uDCE1 Trying tags for ${q}/${I}`);let _=await M(`${V}/repos/${q}/${I}/tags?per_page=10`,{headers:j});if(_.ok){let K=await _.json();if(!Array.isArray(K))E().info("\u26A0\uFE0F Unexpected tags response format (expected array)");else{E().info(`\uD83D\uDCCB Found ${K.length} tags`);let X=K.filter((O)=>O.name&&!O.name.includes("-")).map((O)=>O.name).sort((O,x)=>{let $=O.replace(/^v/,""),z=x.replace(/^v/,""),S=$.split(".").map(Number),y=z.split(".").map(Number);for(let k=0;k<Math.max(S.length,y.length);k++){let B=S[k]||0,G=y[k]||0;if(B!==G)return G-B}return 0});if(X.length>0)return E().info(`\u2705 Found latest stable tag: ${X[0]}`),X[0]}}else E().info(`\u26A0\uFE0F Tags not found: ${_.status} ${_.statusText}`);return E().info(`\u274C No version found for ${J}`),null}catch(q){return E().warn(`Failed to fetch latest version for ${J}:`,q),null}}
4
- export{v as fe,N as ge,A as he,L as ie,R as je};
4
+ export{v as ne,N as oe,A as pe,L as qe,R as re};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{I as a,J as b,K as c,L as d,M as e,N as f,O as g,P as h,Q as i,R as j,S as k,T as l,U as m,V as n}from"./chunk-0w695m54.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{m as withNarrative,n as shouldPublishReport,l as renderReport,c as parseHistory,f as loadHistory,e as findPrevious,i as computeMetrics,j as computeDeltas,d as appendHistory,g as REPORT_PERIODS,k as REPORT_MARKER,h as PERIOD_DAYS,a as HISTORY_PATH,b as HISTORY_LIMIT};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Se as a,Te as b,Ue as c,Ve as d}from"./chunk-txtrpypt.js";import"./chunk-hfjywbbc.js";import"./chunk-q4t568hv.js";export{c as updateZigManifest,b as parseZigManifest,a as isZigManifest,d as generateZigManifestUpdates};
@@ -1,3 +1,4 @@
1
+ export type { RunPlanOptions } from './plan';
1
2
  export type { FinishingTouch, TouchOutput } from './tasks';
2
3
  export type { AgentRunOptions } from './runner';
3
4
  export type {
@@ -16,9 +17,9 @@ export {
16
17
  getAgentMode,
17
18
  implementMode,
18
19
  planMode,
19
- restrictedMode,
20
20
  reviewMode,
21
21
  } from './modes';
22
+ export { runPlan } from './plan';
22
23
  export { runAgent, wrapUntrusted } from './runner';
23
24
  export {
24
25
  autofixTouch,
@@ -28,6 +29,9 @@ export {
28
29
  parseTouchSelections,
29
30
  planTouch,
30
31
  renderTouchOffer,
32
+ TOUCH_OFFER_MARKER,
33
+ hasTouchOffer,
34
+ withTouchOffer,
31
35
  simplifyTouch,
32
36
  unitTestsTouch,
33
37
  } from './tasks';
@@ -42,3 +46,4 @@ export {
42
46
  TEST_COMMANDS,
43
47
  verifyChanges,
44
48
  } from './stacked';
49
+ export { createReadIssueTool } from './tools/issue';
@@ -21,13 +21,5 @@ export declare const implementMode: AgentMode;
21
21
  export declare const fixCiMode: AgentMode;
22
22
  /** Research and planning, with no ability to change anything. */
23
23
  export declare const planMode: AgentMode;
24
- /**
25
- * The tier every non-collaborator gets.
26
- *
27
- * Public repositories accept input from anyone, so a run triggered by someone
28
- * without write access is capped at reading — the same reasoning as
29
- * review-mode's tier list, applied to the actor rather than the task.
30
- */
31
- export declare const restrictedMode: AgentMode;
32
24
  /** Every built-in mode, by name. */
33
25
  export declare const AGENT_MODES: Record<string, AgentMode>;
@@ -0,0 +1,28 @@
1
+ import type { BuddyConfig } from '../types';
2
+ import type { GitProvider } from '../git/provider';
3
+ import type { Logger } from '../utils/logger';
4
+ /**
5
+ * Research the repository and write an implementation plan.
6
+ *
7
+ * Runs in `planMode`, whose tier list is the guarantee rather than the
8
+ * instruction: a planning run is offered read tools only, so no wording in an
9
+ * issue body can talk it into changing the repository it is describing.
10
+ *
11
+ * @param options - Repository context and what to plan
12
+ * @returns The plan, ready to post as a comment
13
+ * @example
14
+ * ```ts
15
+ * const plan = await runPlan({ config, provider, number: 42, isPullRequest: false })
16
+ * ```
17
+ */
18
+ export declare function runPlan(options: RunPlanOptions): Promise<string>;
19
+ /** Inputs to a planning run. */
20
+ export declare interface RunPlanOptions {
21
+ config: BuddyConfig
22
+ provider: GitProvider
23
+ number: number
24
+ isPullRequest: boolean
25
+ request?: string
26
+ workspace?: string
27
+ logger?: Logger
28
+ }
@@ -15,6 +15,24 @@ export declare function getFinishingTouch(name: string): FinishingTouch;
15
15
  * @param names - Touches to offer
16
16
  */
17
17
  export declare function renderTouchOffer(names?: string[]): string;
18
+ /**
19
+ * Whether a pull request body already carries the offer.
20
+ *
21
+ * Checked before appending, because the job that posts it runs on more than
22
+ * one event and a body that accumulated the block twice would show a second
23
+ * set of boxes that tick independently of the first.
24
+ *
25
+ * @param body - Pull request body
26
+ */
27
+ export declare function hasTouchOffer(body: string | null | undefined): boolean;
28
+ /**
29
+ * Append the offer to a pull request body, once.
30
+ *
31
+ * @param body - Current body
32
+ * @param names - Touches to offer
33
+ * @returns The body with the offer, or unchanged when it already has one
34
+ */
35
+ export declare function withTouchOffer(body: string | null | undefined, names?: string[]): string;
18
36
  /** Parse which touches a maintainer ticked. */
19
37
  export declare function parseTouchSelections(body: string | null | undefined): string[];
20
38
  /** Generate missing documentation comments for changed public APIs. */
@@ -29,6 +47,8 @@ export declare const simplifyTouch: FinishingTouch;
29
47
  export declare const planTouch: FinishingTouch;
30
48
  /** Every built-in finishing touch, by name. */
31
49
  export declare const FINISHING_TOUCHES: Record<string, FinishingTouch>;
50
+ /** Opens the offer block, so it can be found and replaced rather than repeated. */
51
+ export declare const TOUCH_OFFER_MARKER: '<!-- buddy:touches -->';
32
52
  /** A named, repeatable agent task. */
33
53
  export declare interface FinishingTouch {
34
54
  name: string
@@ -0,0 +1,19 @@
1
+ import type { AgentTool } from '../types';
2
+ import type { GitProvider } from '../../git/provider';
3
+ /**
4
+ * Build a tool that reads one specific issue or pull request.
5
+ *
6
+ * Scoped to a single number on purpose. A plan needs the thing it is planning,
7
+ * and a tool that could fetch any issue in the repository would widen what a
8
+ * comment from a stranger can make the agent go and read.
9
+ *
10
+ * @param provider - Provider to read from
11
+ * @param number - Issue or pull request number
12
+ * @param isPullRequest - Whether the number is a pull request
13
+ * @returns A read-tier tool returning the title and body as untrusted data
14
+ * @example
15
+ * ```ts
16
+ * const tools = [...BUILTIN_TOOLS, createReadIssueTool(provider, 42, false)]
17
+ * ```
18
+ */
19
+ export declare function createReadIssueTool(provider: GitProvider, number: number, isPullRequest: boolean): AgentTool;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Read the attempt count out of a pull request body.
3
+ *
4
+ * A missing or unreadable marker reads as zero attempts rather than as an
5
+ * error: the guard exists to stop a loop, and refusing to act because the
6
+ * bookkeeping is unparseable would be a worse failure than one extra try.
7
+ *
8
+ * @param body - Pull request body, possibly null
9
+ * @returns The recorded state, or `null` when absent or unreadable
10
+ */
11
+ export declare function parseFixAttempts(body: string | null | undefined): FixAttemptState | null;
12
+ /**
13
+ * Record an attempt on a pull request body.
14
+ *
15
+ * Counted per pull request rather than per commit, deliberately. Buddy's own
16
+ * repair pushes a commit, so keying the count to the head sha would reset it
17
+ * every time a fix landed and defeat the guard it exists to provide.
18
+ *
19
+ * @param body - Current pull request body
20
+ * @param attempts - Total attempts including the one just made
21
+ * @param now - Timestamp to record
22
+ * @returns The body with exactly one, current, marker
23
+ * @example
24
+ * ```ts
25
+ * const attempts = (parseFixAttempts(pr.body)?.attempts ?? 0) + 1
26
+ * await provider.updatePullRequest(number, { body: upsertFixAttempts(pr.body, attempts) })
27
+ * ```
28
+ */
29
+ export declare function upsertFixAttempts(body: string | null | undefined, attempts: number, now?: Date): string;
30
+ /** Schema version emitted by this build. */
31
+ export declare const FIX_ATTEMPTS_VERSION: 1;
32
+ /** Attempt bookkeeping for one pull request. */
33
+ export declare interface FixAttemptState {
34
+ attempts: number
35
+ lastAttemptAt: string
36
+ }
@@ -0,0 +1,55 @@
1
+ import type { FailureKind } from './classify';
2
+ import type { ListWorkflowRunsOptions, WorkflowRun } from '../git/provider';
3
+ import type { Logger } from '../utils/logger';
4
+ /**
5
+ * Whether the base branch is already failing the same way.
6
+ *
7
+ * Not "is the base red" but "is the base red *in the same way*". A pull
8
+ * request that adds a test to a repository whose lint is broken should still
9
+ * have its own test failure diagnosed, and a bot that downed tools whenever
10
+ * the base was red would be useless on exactly the repositories that need it.
11
+ *
12
+ * Comparing classifications is an approximation, and the direction it errs in
13
+ * is deliberate. Two unrelated type errors both classify as `type-error`, so a
14
+ * genuine regression on a base branch that already fails to type-check reads
15
+ * as inherited — Buddy declines and says why, rather than committing a guess
16
+ * about code it has already been told is broken.
17
+ *
18
+ * @param reader - Provider slice that can list runs and read their logs
19
+ * @param baseBranch - Branch the pull request targets
20
+ * @param kind - Failure classified from the pull request's own run
21
+ * @param logger - Optional logger
22
+ * @returns Whether the base branch fails the same way
23
+ * @example
24
+ * ```ts
25
+ * const inherited = await failsOnBaseBranch(provider, 'main', failure.kind)
26
+ * ```
27
+ */
28
+ export declare function failsOnBaseBranch(reader: RunHistoryReader, baseBranch: string, kind: FailureKind, logger?: Logger): Promise<boolean>;
29
+ /**
30
+ * Reduce a run list to the newest failure of each distinct workflow.
31
+ *
32
+ * Providers interleave runs from every workflow, so the newest run overall
33
+ * often belongs to something unrelated. Taking the newest *per workflow*
34
+ * answers the question actually being asked — is this workflow red on base
35
+ * right now — and drops a workflow whose latest run has since gone green.
36
+ *
37
+ * Also used to pick *which* run a comment is asking about: the same
38
+ * interleaving that makes a base-branch check ambiguous makes "the run that
39
+ * failed on this pull request" ambiguous too.
40
+ *
41
+ * @param runs - Runs, most recent first
42
+ * @returns The newest run of each workflow, kept only where it failed
43
+ */
44
+ export declare function latestFailurePerWorkflow(runs: WorkflowRun[]): WorkflowRun[];
45
+ /**
46
+ * The slice of a provider this check needs.
47
+ *
48
+ * Narrow on purpose: the check is pure reasoning over two reads, and taking a
49
+ * whole `GitProvider` would make it awkward to test something that deserves
50
+ * direct tests.
51
+ */
52
+ export declare interface RunHistoryReader {
53
+ listWorkflowRuns: (branch: string, options?: ListWorkflowRunsOptions) => Promise<WorkflowRun[]>
54
+ getWorkflowRunLogs: (runId: number) => Promise<string | null>
55
+ }
@@ -1,22 +1,6 @@
1
1
  import type { AiClient } from '../ai/types';
2
- import type { ClassifiedFailure } from './classify';
2
+ import type { ClassifiedFailure, FailureKind } from './classify';
3
3
  import type { Logger } from '../utils/logger';
4
- /**
5
- * Diagnose a failing CI run and repair it when the fix is clear.
6
- *
7
- * Ordered cheapest-first: a failure that also happens on the base branch is
8
- * not this change's to fix, a known-mechanical failure is fixed without a
9
- * model, and only what remains reaches the agent. This is also why fix-ci is
10
- * useful with no AI configured at all.
11
- *
12
- * @param options - Log, repository context and repair hooks
13
- * @returns What was done and a report ready to post
14
- * @example
15
- * ```ts
16
- * const outcome = await attemptFix({ log, workspace, baseBranch: 'main' })
17
- * await provider.createComment(pr, outcome.report)
18
- * ```
19
- */
20
4
  export declare function attemptFix(options: FixOptions): Promise<FixOutcome>;
21
5
  /** Render a failure and its outcome as a comment body. */
22
6
  declare function report(failure: ClassifiedFailure, conclusion: string): string;
@@ -31,12 +15,37 @@ export declare interface FixOutcome {
31
15
  export declare interface FixOptions {
32
16
  log: string
33
17
  failsOnBase?: boolean
18
+ checkBase?: (kind: FailureKind) => Promise<boolean>
34
19
  workspace: string
35
20
  branch?: string
36
21
  baseBranch: string
37
22
  priorAttempts?: number
38
23
  maxAttempts?: number
39
24
  ai?: AiClient | null
40
- regenerateLockfile?: () => Promise<boolean>
25
+ regenerateLockfile?: () => Promise<LockfileRepair>
26
+ rerun?: () => Promise<boolean>
27
+ dryRun?: boolean
28
+ analysisOnly?: boolean
41
29
  logger?: Logger
42
30
  }
31
+ /**
32
+ * Diagnose a failing CI run and repair it when the fix is clear.
33
+ *
34
+ * Ordered cheapest-first: a failure that also happens on the base branch is
35
+ * not this change's to fix, a known-mechanical failure is fixed without a
36
+ * model, and only what remains reaches the agent. This is also why fix-ci is
37
+ * useful with no AI configured at all.
38
+ *
39
+ * @param options - Log, repository context and repair hooks
40
+ * @returns What was done and a report ready to post
41
+ * @example
42
+ * ```ts
43
+ * const outcome = await attemptFix({ log, workspace, baseBranch: 'main' })
44
+ * await provider.createComment(pr, outcome.report)
45
+ * ```
46
+ */
47
+ /** What the mechanical lock-file repair managed to do. */
48
+ export declare interface LockfileRepair {
49
+ regenerated: boolean
50
+ pushed: boolean
51
+ }