@buddysh/buddy 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/CHANGELOG.md +1633 -0
  2. package/LICENSE.md +21 -0
  3. package/README.md +1087 -0
  4. package/bin/cli.ts +3401 -0
  5. package/dist/bin/cli.d.ts +1 -0
  6. package/dist/bin/cli.js +188 -0
  7. package/dist/chunk-0j7z87kh.js +3 -0
  8. package/dist/chunk-0r8zt3d7.js +2 -0
  9. package/dist/chunk-16yqbccr.js +3 -0
  10. package/dist/chunk-1a53wj0h.js +1 -0
  11. package/dist/chunk-1c1gznm9.js +3 -0
  12. package/dist/chunk-1h3ey7k5.js +3 -0
  13. package/dist/chunk-1stt2whn.js +62 -0
  14. package/dist/chunk-1wjnd24b.js +24 -0
  15. package/dist/chunk-1xe07hzm.js +2 -0
  16. package/dist/chunk-2bp7tqca.js +2 -0
  17. package/dist/chunk-2dbkpfy9.js +2 -0
  18. package/dist/chunk-3q6czqs4.js +6 -0
  19. package/dist/chunk-3zdcekfj.js +5 -0
  20. package/dist/chunk-49ey79p0.js +5 -0
  21. package/dist/chunk-4c9m61yd.js +5 -0
  22. package/dist/chunk-4efbxdjr.js +4 -0
  23. package/dist/chunk-4f7panqj.js +21 -0
  24. package/dist/chunk-4hd3rre0.js +2 -0
  25. package/dist/chunk-4xsq18p3.js +9 -0
  26. package/dist/chunk-52x8mvh4.js +15 -0
  27. package/dist/chunk-54sc18p8.js +2 -0
  28. package/dist/chunk-56q4pwb5.js +3 -0
  29. package/dist/chunk-5c3qf34r.js +2 -0
  30. package/dist/chunk-5k40mwd4.js +4 -0
  31. package/dist/chunk-5kt03hx5.js +2 -0
  32. package/dist/chunk-63ept76v.js +2 -0
  33. package/dist/chunk-65b3vq52.js +2 -0
  34. package/dist/chunk-6d9hmjt8.js +3 -0
  35. package/dist/chunk-6g1y9yqh.js +3 -0
  36. package/dist/chunk-6k653r8w.js +2 -0
  37. package/dist/chunk-6md7qf2g.js +4 -0
  38. package/dist/chunk-6patq6bw.js +2 -0
  39. package/dist/chunk-6sgh49z1.js +2 -0
  40. package/dist/chunk-74pxb991.js +7 -0
  41. package/dist/chunk-7mgec8kb.js +7 -0
  42. package/dist/chunk-7tfrww3v.js +2 -0
  43. package/dist/chunk-7xk28xrv.js +2 -0
  44. package/dist/chunk-82dv4p13.js +2 -0
  45. package/dist/chunk-8661pvb8.js +3 -0
  46. package/dist/chunk-887s0w81.js +2 -0
  47. package/dist/chunk-8rc6042h.js +4 -0
  48. package/dist/chunk-9750tenz.js +3 -0
  49. package/dist/chunk-978wtejw.js +44 -0
  50. package/dist/chunk-9eqpaxfz.js +2 -0
  51. package/dist/chunk-9h04nskh.js +8 -0
  52. package/dist/chunk-9p1xkmjy.js +2 -0
  53. package/dist/chunk-agdesgzv.js +2 -0
  54. package/dist/chunk-akffynkc.js +3 -0
  55. package/dist/chunk-ar01x04a.js +2 -0
  56. package/dist/chunk-ay43f085.js +2 -0
  57. package/dist/chunk-bk9bqd5j.js +2 -0
  58. package/dist/chunk-bm8d40j0.js +69 -0
  59. package/dist/chunk-bxfc4g2x.js +73 -0
  60. package/dist/chunk-c3fczawt.js +2 -0
  61. package/dist/chunk-c9r9nd4t.js +1 -0
  62. package/dist/chunk-ctsz0ynx.js +3 -0
  63. package/dist/chunk-czremqk7.js +2 -0
  64. package/dist/chunk-da3wbh04.js +2 -0
  65. package/dist/chunk-dat582cg.js +2 -0
  66. package/dist/chunk-dfesffnr.js +3 -0
  67. package/dist/chunk-djntbp7a.js +105 -0
  68. package/dist/chunk-eagjp0dh.js +3 -0
  69. package/dist/chunk-eht72nnj.js +2 -0
  70. package/dist/chunk-f4nv5x3z.js +2 -0
  71. package/dist/chunk-fdfk918n.js +2 -0
  72. package/dist/chunk-fdj0tewy.js +20 -0
  73. package/dist/chunk-fm8ckj9b.js +2 -0
  74. package/dist/chunk-fqj7e6xa.js +2 -0
  75. package/dist/chunk-frm8zz31.js +2 -0
  76. package/dist/chunk-fvpr07dn.js +16 -0
  77. package/dist/chunk-g0nv8psv.js +2 -0
  78. package/dist/chunk-g0w8n555.js +19 -0
  79. package/dist/chunk-gkmvxjbe.js +2 -0
  80. package/dist/chunk-gngwjf70.js +7 -0
  81. package/dist/chunk-h7hs95wn.js +5 -0
  82. package/dist/chunk-hfvezfxh.js +3 -0
  83. package/dist/chunk-hw70wbzg.js +3 -0
  84. package/dist/chunk-j8asz4hb.js +15 -0
  85. package/dist/chunk-k62w2v03.js +2 -0
  86. package/dist/chunk-mcrfxphm.js +5 -0
  87. package/dist/chunk-mh3x7j6h.js +2 -0
  88. package/dist/chunk-naq32yx3.js +86 -0
  89. package/dist/chunk-nsmcjkas.js +2 -0
  90. package/dist/chunk-p1xm1jvz.js +2 -0
  91. package/dist/chunk-p3wsm8kz.js +2 -0
  92. package/dist/chunk-p4zwy518.js +4 -0
  93. package/dist/chunk-p7zgy37f.js +2 -0
  94. package/dist/chunk-ph1b3vbp.js +315 -0
  95. package/dist/chunk-pkjm2r0a.js +2 -0
  96. package/dist/chunk-pkkwb0n0.js +4 -0
  97. package/dist/chunk-pnpx1kqn.js +6 -0
  98. package/dist/chunk-q9n79dd3.js +3 -0
  99. package/dist/chunk-qpz9k66h.js +2 -0
  100. package/dist/chunk-qvn1rtgp.js +2 -0
  101. package/dist/chunk-qyf90zz3.js +2 -0
  102. package/dist/chunk-r06ce5g6.js +2 -0
  103. package/dist/chunk-r2sbprdb.js +49 -0
  104. package/dist/chunk-r3zyw8x0.js +3 -0
  105. package/dist/chunk-rb1fh9vd.js +1 -0
  106. package/dist/chunk-rqdep14r.js +2 -0
  107. package/dist/chunk-s1km8cyq.js +2 -0
  108. package/dist/chunk-s4ms8zag.js +2 -0
  109. package/dist/chunk-sp818c27.js +9 -0
  110. package/dist/chunk-tb5y0350.js +3 -0
  111. package/dist/chunk-thaxgm5p.js +2 -0
  112. package/dist/chunk-tn8prpny.js +503 -0
  113. package/dist/chunk-ts35hc5t.js +3 -0
  114. package/dist/chunk-tzs22es2.js +3 -0
  115. package/dist/chunk-vagxqhef.js +13 -0
  116. package/dist/chunk-vh504tcv.js +6 -0
  117. package/dist/chunk-vkctfqpm.js +3 -0
  118. package/dist/chunk-vyapg8ca.js +186 -0
  119. package/dist/chunk-wdwvt7gb.js +43 -0
  120. package/dist/chunk-wtjhehz9.js +4 -0
  121. package/dist/chunk-x0ya2r4r.js +3 -0
  122. package/dist/chunk-x3kragh9.js +12 -0
  123. package/dist/chunk-x9ctz1qc.js +1 -0
  124. package/dist/chunk-xakpdqaq.js +3 -0
  125. package/dist/chunk-xqx460y2.js +3 -0
  126. package/dist/chunk-xvptf9jy.js +3 -0
  127. package/dist/chunk-yk23nc4t.js +2 -0
  128. package/dist/chunk-yncea6ty.js +2 -0
  129. package/dist/chunk-yq0gxtzv.js +2 -0
  130. package/dist/chunk-yqhs08ky.js +2 -0
  131. package/dist/chunk-zb62jhwm.js +31 -0
  132. package/dist/chunk-zs3jaj0g.js +1023 -0
  133. package/dist/chunk-zve5d96e.js +2 -0
  134. package/dist/src/agent/index.d.ts +44 -0
  135. package/dist/src/agent/modes.d.ts +33 -0
  136. package/dist/src/agent/runner.d.ts +44 -0
  137. package/dist/src/agent/stacked.d.ts +83 -0
  138. package/dist/src/agent/tasks.d.ts +41 -0
  139. package/dist/src/agent/toolbelt.d.ts +19 -0
  140. package/dist/src/agent/tools/fs.d.ts +26 -0
  141. package/dist/src/agent/tools/shell.d.ts +32 -0
  142. package/dist/src/agent/types.d.ts +56 -0
  143. package/dist/src/ai/aliases.d.ts +62 -0
  144. package/dist/src/ai/client.d.ts +42 -0
  145. package/dist/src/ai/index.d.ts +35 -0
  146. package/dist/src/ai/learnings.d.ts +78 -0
  147. package/dist/src/ai/providers/anthropic.d.ts +12 -0
  148. package/dist/src/ai/providers/google.d.ts +12 -0
  149. package/dist/src/ai/providers/openai.d.ts +15 -0
  150. package/dist/src/ai/redact.d.ts +30 -0
  151. package/dist/src/ai/types.d.ts +75 -0
  152. package/dist/src/analysis/analyzers/actionlint.d.ts +11 -0
  153. package/dist/src/analysis/analyzers/external.d.ts +57 -0
  154. package/dist/src/analysis/analyzers/github-actions.d.ts +9 -0
  155. package/dist/src/analysis/analyzers/hadolint.d.ts +9 -0
  156. package/dist/src/analysis/analyzers/linter.d.ts +53 -0
  157. package/dist/src/analysis/analyzers/markdownlint.d.ts +11 -0
  158. package/dist/src/analysis/analyzers/secrets.d.ts +23 -0
  159. package/dist/src/analysis/analyzers/shellcheck.d.ts +8 -0
  160. package/dist/src/analysis/analyzers/syntax.d.ts +13 -0
  161. package/dist/src/analysis/engine.d.ts +38 -0
  162. package/dist/src/analysis/index.d.ts +13 -0
  163. package/dist/src/analysis/types.d.ts +14 -0
  164. package/dist/src/buddy.d.ts +17 -0
  165. package/dist/src/ci/classify.d.ts +49 -0
  166. package/dist/src/ci/fix.d.ts +42 -0
  167. package/dist/src/ci/index.d.ts +8 -0
  168. package/dist/src/commands/dispatcher.d.ts +49 -0
  169. package/dist/src/commands/handlers.d.ts +23 -0
  170. package/dist/src/commands/index.d.ts +22 -0
  171. package/dist/src/commands/parser.d.ts +71 -0
  172. package/dist/src/config-validation.d.ts +38 -0
  173. package/dist/src/config.d.ts +22 -0
  174. package/dist/src/dashboard/dashboard-generator.d.ts +10 -0
  175. package/dist/src/doctor.d.ts +44 -0
  176. package/dist/src/ecosystems/go.d.ts +10 -0
  177. package/dist/src/ecosystems/index.d.ts +60 -0
  178. package/dist/src/ecosystems/pep440.d.ts +57 -0
  179. package/dist/src/ecosystems/python.d.ts +12 -0
  180. package/dist/src/ecosystems/ruby.d.ts +9 -0
  181. package/dist/src/ecosystems/rust.d.ts +8 -0
  182. package/dist/src/ecosystems/scan.d.ts +49 -0
  183. package/dist/src/ecosystems/shared.d.ts +45 -0
  184. package/dist/src/ecosystems/types.d.ts +58 -0
  185. package/dist/src/events/bus.d.ts +41 -0
  186. package/dist/src/events/index.d.ts +11 -0
  187. package/dist/src/events/sinks.d.ts +33 -0
  188. package/dist/src/gates/ai-checks.d.ts +77 -0
  189. package/dist/src/gates/checks.d.ts +84 -0
  190. package/dist/src/gates/index.d.ts +17 -0
  191. package/dist/src/gates/post-merge.d.ts +56 -0
  192. package/dist/src/git/bitbucket-provider.d.ts +50 -0
  193. package/dist/src/git/github-provider.d.ts +50 -0
  194. package/dist/src/git/gitlab-provider.d.ts +51 -0
  195. package/dist/src/git/provider.d.ts +210 -0
  196. package/dist/src/headless/run.d.ts +78 -0
  197. package/dist/src/index.d.ts +243 -0
  198. package/dist/src/index.js +2 -0
  199. package/dist/src/issues/enrichment.d.ts +76 -0
  200. package/dist/src/issues/index.d.ts +16 -0
  201. package/dist/src/issues/quick-links.d.ts +55 -0
  202. package/dist/src/pr/auto-merge.d.ts +75 -0
  203. package/dist/src/pr/pr-generator.d.ts +9 -0
  204. package/dist/src/pr/pr-manifest.d.ts +82 -0
  205. package/dist/src/pr/templates.d.ts +44 -0
  206. package/dist/src/registry/docker-tags.d.ts +56 -0
  207. package/dist/src/registry/eol.d.ts +87 -0
  208. package/dist/src/registry/oci-client.d.ts +98 -0
  209. package/dist/src/registry/registry-client.d.ts +39 -0
  210. package/dist/src/reports/history.d.ts +51 -0
  211. package/dist/src/reports/index.d.ts +23 -0
  212. package/dist/src/reports/metrics.d.ts +89 -0
  213. package/dist/src/reports/render.d.ts +33 -0
  214. package/dist/src/review/diff.d.ts +50 -0
  215. package/dist/src/review/engine.d.ts +49 -0
  216. package/dist/src/review/findings.d.ts +102 -0
  217. package/dist/src/review/guidelines.d.ts +46 -0
  218. package/dist/src/review/index.d.ts +48 -0
  219. package/dist/src/review/local.d.ts +81 -0
  220. package/dist/src/review/marker.d.ts +34 -0
  221. package/dist/src/review/poster.d.ts +39 -0
  222. package/dist/src/review/run.d.ts +24 -0
  223. package/dist/src/rules/engine.d.ts +108 -0
  224. package/dist/src/rules/index.d.ts +9 -0
  225. package/dist/src/rules/renovate.d.ts +25 -0
  226. package/dist/src/rules/schedule.d.ts +44 -0
  227. package/dist/src/scanner/catalog-scan.d.ts +39 -0
  228. package/dist/src/scanner/package-json-extras.d.ts +101 -0
  229. package/dist/src/scanner/package-scanner.d.ts +17 -0
  230. package/dist/src/scanner/resolution-drift.d.ts +81 -0
  231. package/dist/src/scanner/workspace-catalog.d.ts +53 -0
  232. package/dist/src/scheduler/scheduler.d.ts +27 -0
  233. package/dist/src/security/engine.d.ts +12 -0
  234. package/dist/src/security/loader.d.ts +7 -0
  235. package/dist/src/security/parser.d.ts +15 -0
  236. package/dist/src/security/rules/bash-injection.d.ts +18 -0
  237. package/dist/src/security/rules/dangerous-pull-request-target.d.ts +18 -0
  238. package/dist/src/security/rules/excessive-permissions.d.ts +14 -0
  239. package/dist/src/security/rules/index.d.ts +16 -0
  240. package/dist/src/security/rules/missing-timeout.d.ts +9 -0
  241. package/dist/src/security/rules/self-hosted-exposure.d.ts +13 -0
  242. package/dist/src/security/rules/unpinned-action.d.ts +10 -0
  243. package/dist/src/security/rules/walk.d.ts +13 -0
  244. package/dist/src/security/types.d.ts +64 -0
  245. package/dist/src/services/deprecated-dependencies-checker.d.ts +16 -0
  246. package/dist/src/services/release-notes-fetcher.d.ts +70 -0
  247. package/dist/src/services/security-advisories.d.ts +59 -0
  248. package/dist/src/setup.d.ts +162 -0
  249. package/dist/src/setup.js +2 -0
  250. package/dist/src/templates/github-actions.d.ts +31 -0
  251. package/dist/src/templates/gitlab-ci.d.ts +46 -0
  252. package/dist/src/types.d.ts +449 -0
  253. package/dist/src/upgrades/index.d.ts +18 -0
  254. package/dist/src/upgrades/migrate.d.ts +45 -0
  255. package/dist/src/upgrades/plan.d.ts +112 -0
  256. package/dist/src/upgrades/report.d.ts +22 -0
  257. package/dist/src/upgrades/span.d.ts +47 -0
  258. package/dist/src/upgrades/usage.d.ts +30 -0
  259. package/dist/src/upgrades/wire.d.ts +61 -0
  260. package/dist/src/utils/concurrency.d.ts +50 -0
  261. package/dist/src/utils/dependency-file-parser.d.ts +17 -0
  262. package/dist/src/utils/dockerfile-parser.d.ts +69 -0
  263. package/dist/src/utils/endpoints.d.ts +58 -0
  264. package/dist/src/utils/errors.d.ts +35 -0
  265. package/dist/src/utils/file-changes.d.ts +14 -0
  266. package/dist/src/utils/github-actions-parser.d.ts +21 -0
  267. package/dist/src/utils/globs.d.ts +22 -0
  268. package/dist/src/utils/helpers.d.ts +73 -0
  269. package/dist/src/utils/http.d.ts +81 -0
  270. package/dist/src/utils/lock-file.d.ts +28 -0
  271. package/dist/src/utils/logger.d.ts +45 -0
  272. package/dist/src/utils/package-paths.d.ts +6 -0
  273. package/dist/src/utils/pantry-parser.d.ts +30 -0
  274. package/dist/src/utils/repository.d.ts +41 -0
  275. package/dist/src/utils/security-format.d.ts +18 -0
  276. package/dist/src/utils/zig-parser.d.ts +18 -0
  277. package/dist/src/version/version-resolver.d.ts +9 -0
  278. package/package.json +115 -0
package/bin/cli.ts ADDED
@@ -0,0 +1,3401 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import type { GitProvider } from '../src/git/provider'
4
+ import type { ReviewFinding } from '../src/review/findings'
5
+ import type { ReviewFormat } from '../src/review/local'
6
+ import type { BuddyConfig } from '../src/types'
7
+ import fs from 'node:fs'
8
+ import process from 'node:process'
9
+ import { CLI } from '@stacksjs/clapp'
10
+ import prompts from 'prompts'
11
+ import { version } from '../package.json'
12
+ import { Buddy } from '../src/buddy'
13
+ import { getConfig } from '../src/config'
14
+ import { assertSupports, createProvider, supports } from '../src/git/provider'
15
+ import {
16
+ hasDashboardActions,
17
+ parseDashboardActions,
18
+ uncheckDashboardActions,
19
+ } from '../src/dashboard/dashboard-actions'
20
+ import { manifestUpdates, parseManifest } from '../src/pr/pr-manifest'
21
+ import {
22
+ analyzeProject,
23
+ ConfigurationMigrator,
24
+ confirmTokenSetup,
25
+ createProgressTracker,
26
+ detectRepository,
27
+ displayProgress,
28
+ displayValidationResults,
29
+ generateConfigFile,
30
+ generateCoreWorkflows,
31
+ getWorkflowPreset,
32
+ guideRepositorySettings,
33
+ guideTokenCreation,
34
+ PluginManager,
35
+ runPreflightChecks,
36
+ setupCustomWorkflow,
37
+ showFinalInstructions,
38
+ updateProgress,
39
+ validateRepositoryAccess,
40
+ validateWorkflowGeneration,
41
+ } from '../src/setup'
42
+ import { applySuggestion, REVIEW_FORMATS } from '../src/review/local'
43
+ import { formatError } from '../src/utils/errors'
44
+ import { Logger } from '../src/utils/logger'
45
+
46
+ let _resolvedConfig: BuddyConfig | null = null
47
+
48
+ /**
49
+ * Load the configuration once per process.
50
+ *
51
+ * @param configPath - Explicit config file from `--config`, bypassing discovery
52
+ */
53
+ async function resolveConfig(configPath?: string): Promise<BuddyConfig> {
54
+ if (configPath)
55
+ return await getConfig(configPath)
56
+
57
+ if (!_resolvedConfig)
58
+ _resolvedConfig = await getConfig()
59
+ return _resolvedConfig
60
+ }
61
+
62
+ /**
63
+ * Build the git provider for a command, or exit with a usable message.
64
+ *
65
+ * Every provider-backed command needs the same three things — repository
66
+ * coordinates, a token, and a supported provider — and every one of them
67
+ * should fail the same way. Centralising it means adding a provider touches
68
+ * one place rather than seven.
69
+ *
70
+ * @param config - Resolved configuration
71
+ * @param purpose - What the provider is needed for, used in the error
72
+ * @param logger - Where to report the failure
73
+ * @returns A provider bound to the configured repository
74
+ */
75
+ async function providerFor(config: BuddyConfig, purpose: string, logger: Logger): Promise<GitProvider> {
76
+ if (!config.repository?.owner || !config.repository.name) {
77
+ logger.error(`❌ Repository owner and name are required for ${purpose}`)
78
+ logger.info('Configure repository.owner and repository.name in buddy.config.ts')
79
+ process.exit(1)
80
+ }
81
+
82
+ try {
83
+ return await createProvider({
84
+ provider: config.repository.provider,
85
+ owner: config.repository.owner,
86
+ name: config.repository.name,
87
+ ...(config.repository.token ? { token: config.repository.token } : {}),
88
+ ...(config.repository.apiUrl ? { apiUrl: config.repository.apiUrl } : {}),
89
+ }, { logger })
90
+ }
91
+ catch (error) {
92
+ logger.error(`❌ ${formatError(error)}`)
93
+ process.exit(1)
94
+ }
95
+ }
96
+
97
+
98
+ /**
99
+ * Apply committable suggestions to the working tree.
100
+ *
101
+ * Confirmation is per finding unless `--yes`, because a suggestion is a
102
+ * proposal: a reviewer reads each one before accepting it, and applying a
103
+ * batch unseen is how a review turns into an unreviewed commit.
104
+ *
105
+ * Findings are applied bottom-up within each file so that replacing a line
106
+ * cannot shift the line numbers of the ones still to be applied.
107
+ *
108
+ * @param findings - Findings from the review
109
+ * @param assumeYes - Apply without asking
110
+ * @param logger - Where to report progress
111
+ * @returns How many suggestions were applied
112
+ */
113
+ async function applyFixes(findings: ReviewFinding[], assumeYes: boolean, logger: Logger): Promise<number> {
114
+ const fixable = findings.filter(finding => finding.suggestion)
115
+ if (fixable.length === 0) {
116
+ logger.info('No committable suggestions in this review')
117
+ return 0
118
+ }
119
+
120
+ const byFile = new Map<string, ReviewFinding[]>()
121
+ for (const finding of fixable) {
122
+ const existing = byFile.get(finding.path)
123
+ if (existing)
124
+ existing.push(finding)
125
+ else
126
+ byFile.set(finding.path, [finding])
127
+ }
128
+
129
+ let applied = 0
130
+
131
+ for (const [path, fileFindings] of byFile) {
132
+ const file = Bun.file(path)
133
+ if (!(await file.exists())) {
134
+ logger.warn(`⚠️ Skipping ${path}: not in the working tree`)
135
+ continue
136
+ }
137
+
138
+ let content = await file.text()
139
+
140
+ for (const finding of [...fileFindings].sort((a, b) => b.line - a.line)) {
141
+ if (!assumeYes) {
142
+ const response = await prompts({
143
+ type: 'confirm',
144
+ name: 'apply',
145
+ message: `${path}:${finding.line} — ${finding.message}\n ${finding.suggestion}\nApply?`,
146
+ initial: false,
147
+ })
148
+
149
+ // A cancelled prompt (Ctrl-C) leaves `apply` undefined; treating that
150
+ // as "no" is the only safe reading.
151
+ if (!response.apply)
152
+ continue
153
+ }
154
+
155
+ const updated = applySuggestion(content, finding.line, finding.suggestion!)
156
+ if (updated === null) {
157
+ logger.warn(`⚠️ Skipping ${path}:${finding.line}: the file changed since the review`)
158
+ continue
159
+ }
160
+
161
+ content = updated
162
+ applied++
163
+ }
164
+
165
+ await Bun.write(path, content)
166
+ }
167
+
168
+ return applied
169
+ }
170
+
171
+ /**
172
+ * Collect what buddy knows about this repository's dependencies.
173
+ *
174
+ * Used to enrich an issue that names a package. Failures are swallowed: the
175
+ * context is an extra, and losing it must not stop the quick-links comment
176
+ * that carries the actions.
177
+ *
178
+ * @param config - Resolved configuration
179
+ * @param logger - Where to report a failure
180
+ * @returns One entry per declared dependency
181
+ */
182
+ async function collectPackageContext(
183
+ config: BuddyConfig,
184
+ logger: Logger,
185
+ ): Promise<Array<{ name: string, declaredVersion?: string }>> {
186
+ try {
187
+ const { PackageScanner } = await import('../src/scanner/package-scanner')
188
+ const files = await new PackageScanner(process.cwd(), logger, config.packages?.ignorePaths).scanProject()
189
+
190
+ const seen = new Map<string, string>()
191
+ for (const file of files) {
192
+ for (const dependency of file.dependencies) {
193
+ if (!seen.has(dependency.name))
194
+ seen.set(dependency.name, dependency.currentVersion)
195
+ }
196
+ }
197
+
198
+ return [...seen].map(([name, declaredVersion]) => ({ name, declaredVersion }))
199
+ }
200
+ catch (error) {
201
+ logger.debug(`Could not collect dependency context: ${formatError(error)}`)
202
+ return []
203
+ }
204
+ }
205
+
206
+ const cli = new CLI('buddy')
207
+
208
+ cli.usage(`[command] [options]
209
+
210
+ 🐶 Buddy - AI code review and dependency updates, in one teammate
211
+
212
+ Reviews pull requests and local changes, answers @buddy comments, gates merges,
213
+ repairs failing CI, and keeps dependencies current across npm, Bun, yarn, pnpm,
214
+ Composer, pkgx, Launchpad, GitHub Actions, Docker, Go, Rust, Python and Ruby.
215
+
216
+ CODE REVIEW & AI:
217
+ review 🔍 Review a pull request, or local changes when no number is given
218
+ gate 🚦 Run pre-merge gates and publish the result as a check run
219
+ fix-ci 🛠️ Diagnose a failing workflow run and repair it when the fix is clear
220
+ handle-comment 💬 Handle an @buddy command from a GitHub event payload
221
+ handle-issue 🎫 Post quick-links on a new issue, or run a ticked action
222
+ post-merge ✅ Run post-merge actions for a merged pull request
223
+ run ⚡ Run a prompt headlessly, with optional schema-validated output
224
+
225
+ DEPENDENCY MANAGEMENT:
226
+ setup 🚀 Interactive setup for automated updates (recommended)
227
+ scan 🔍 Scan for dependency updates
228
+ dashboard 📊 Create or update dependency dashboard issue
229
+ update ⬆️ Update dependencies and create PRs
230
+ rebase 🔄 Rebase/retry a pull request with latest updates
231
+ update-check 🔍 Auto-detect and rebase PRs with checked rebase box
232
+ check 📋 Check specific packages for updates
233
+ schedule ⏰ Run automated updates on schedule
234
+
235
+ PACKAGE INFORMATION:
236
+ info 📦 Show detailed package information
237
+ versions 📈 Show all available versions of a package
238
+ latest ⭐ Get the latest version of a package
239
+ exists ✅ Check if a package exists in the registry
240
+ deps 🔗 Show package dependencies
241
+ compare ⚖️ Compare two versions of a package
242
+ search 🔍 Search for packages in the registry
243
+
244
+ BRANCH MANAGEMENT:
245
+ cleanup 🧹 Clean up stale buddy branches
246
+ list-branches 📋 List all buddy branches and their status
247
+
248
+ REPORTING & DIAGNOSTICS:
249
+ report 📈 Generate a dependency-health and activity report
250
+ doctor 🩺 Diagnose credentials, git state and analyzer tooling
251
+
252
+ CONFIGURATION & SETUP:
253
+ open-settings 🔧 Open GitHub repository and organization settings pages
254
+
255
+ Examples:
256
+ buddy review # Review your working tree before pushing
257
+ buddy review --staged --light # Analyzers only, no API key, for a git hook
258
+ buddy review 128 --format github # Review PR #128 as Actions annotations
259
+ buddy gate 128 # Run pre-merge gates on PR #128
260
+ buddy fix-ci --run-id 42 # Explain and repair a failing run
261
+ buddy setup # Interactive setup with migration
262
+ buddy setup --non-interactive # Automated setup for CI/CD
263
+ buddy scan --verbose # Scan for updates (npm + Composer + Dockerfiles)
264
+ buddy rebase 17 # Rebase PR #17
265
+ buddy update-check # Auto-rebase checked PRs
266
+ buddy cleanup # Clean up stale branches
267
+ buddy info laravel/framework # Get Composer package info
268
+ buddy versions react --latest 5 # Show recent versions
269
+ buddy doctor # Check this environment
270
+
271
+ In a pull request, talk to Buddy directly:
272
+ @buddy review | full-review | summary | resolve | pause | resume
273
+ @buddy fix-ci | plan | rebase | merge | remember <text> | help
274
+ Anything else after the mention is treated as a question.
275
+
276
+ Migration:
277
+ - Automatically detects Renovate and Dependabot configurations
278
+ - Converts settings to Buddy format with compatibility report
279
+ - Generates optimized GitHub Actions workflows
280
+ - Provides migration guidance and best practices`)
281
+
282
+ // Define CLI options interface to match our core types
283
+ interface CLIOptions {
284
+ verbose?: boolean
285
+ config?: string
286
+ packages?: string
287
+ pattern?: string
288
+ strategy?: 'major' | 'minor' | 'patch' | 'all'
289
+ ignore?: string
290
+ dryRun?: boolean
291
+ respectLatest?: boolean
292
+ }
293
+
294
+ cli
295
+ .command('setup', '🚀 Interactive setup for automated dependency updates (recommended)')
296
+ .option('--verbose, -v', 'Enable verbose logging')
297
+ .option('--non-interactive', 'Run setup without prompts (use defaults)')
298
+ .option('--preset <type>', 'Workflow preset: standard|high-frequency|security|minimal|testing', { default: 'standard' })
299
+ .option('--token-setup <type>', 'Token setup: existing-secret|new-pat|default-token', { default: 'default-token' })
300
+ .example('buddy setup')
301
+ .example('buddy setup --verbose')
302
+ .example('buddy setup --non-interactive')
303
+ .example('buddy setup --non-interactive --preset testing --verbose')
304
+ .action(async (options: CLIOptions & { nonInteractive?: boolean, preset?: string, tokenSetup?: string }) => {
305
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
306
+
307
+ try {
308
+ console.log('🤖 Welcome to Buddy Setup!')
309
+ console.log('Let\'s configure automated dependency updates for your project.\n')
310
+
311
+ // Initialize progress tracking
312
+ const progress = createProgressTracker(10) // Updated total steps including new features
313
+ displayProgress(progress)
314
+
315
+ // Configuration Migration Detection
316
+ updateProgress(progress, 'Detecting existing configurations')
317
+ displayProgress(progress)
318
+
319
+ const migrator = new ConfigurationMigrator()
320
+ const existingTools = await migrator.detectExistingTools()
321
+ const migrationResults: any[] = []
322
+
323
+ if (existingTools.length > 0 && !options.nonInteractive) {
324
+ console.log(`\n🔍 Configuration Migration Detection:`)
325
+ console.log(`Found ${existingTools.length} existing dependency management tool(s):`)
326
+ existingTools.forEach(tool => console.log(` • ${tool.name} (${tool.configFile})`))
327
+
328
+ const migrateResponse = await prompts({
329
+ type: 'confirm',
330
+ name: 'migrate',
331
+ message: 'Would you like to migrate existing configurations to Buddy?',
332
+ initial: true,
333
+ })
334
+
335
+ if (migrateResponse.migrate) {
336
+ console.log('\n📋 Migrating configurations...')
337
+ for (const tool of existingTools) {
338
+ try {
339
+ let result
340
+ if (tool.name === 'renovate') {
341
+ result = await migrator.migrateFromRenovate(tool.configFile)
342
+ }
343
+ else if (tool.name === 'dependabot') {
344
+ result = await migrator.migrateFromDependabot(tool.configFile)
345
+ }
346
+ else {
347
+ continue
348
+ }
349
+ migrationResults.push(result)
350
+ console.log(`✅ Migrated ${tool.name} configuration`)
351
+ }
352
+ catch (error) {
353
+ console.log(`⚠️ Failed to migrate ${tool.name}: ${error instanceof Error ? error.message : 'Unknown error'}`)
354
+ }
355
+ }
356
+
357
+ if (migrationResults.length > 0) {
358
+ const report = await migrator.generateMigrationReport(migrationResults)
359
+ console.log(`\n${report}`)
360
+ }
361
+ }
362
+ }
363
+ else if (existingTools.length > 0 && options.nonInteractive) {
364
+ console.log(`\n🔍 Found ${existingTools.length} existing tool(s), skipping migration in non-interactive mode`)
365
+ }
366
+
367
+ // Plugin Discovery
368
+ updateProgress(progress, 'Discovering integrations', true)
369
+ displayProgress(progress)
370
+
371
+ const pluginManager = new PluginManager()
372
+ const availablePlugins = await pluginManager.discoverPlugins()
373
+
374
+ if (availablePlugins.length > 0 && !options.nonInteractive) {
375
+ console.log(`\n🔌 Integration Discovery:`)
376
+ console.log(`Found ${availablePlugins.length} available integration(s):`)
377
+ availablePlugins.forEach(plugin => console.log(` • ${plugin.name} v${plugin.version}`))
378
+
379
+ const pluginResponse = await prompts({
380
+ type: 'confirm',
381
+ name: 'enablePlugins',
382
+ message: 'Would you like to enable these integrations?',
383
+ initial: true,
384
+ })
385
+
386
+ if (pluginResponse.enablePlugins) {
387
+ for (const plugin of availablePlugins) {
388
+ await pluginManager.loadPlugin(plugin)
389
+ }
390
+ }
391
+ }
392
+ else if (availablePlugins.length > 0 && options.nonInteractive) {
393
+ console.log(`\n🔌 Found ${availablePlugins.length} integration(s), skipping in non-interactive mode`)
394
+ }
395
+
396
+ // Pre-flight checks
397
+ updateProgress(progress, 'Running pre-flight checks', true)
398
+ displayProgress(progress)
399
+
400
+ const preflightResults = await runPreflightChecks()
401
+ displayValidationResults(preflightResults, '🔍 Pre-flight Validation')
402
+
403
+ if (!preflightResults.success) {
404
+ console.log('\n❌ Pre-flight checks failed. Please fix the errors above and try again.')
405
+ process.exit(1)
406
+ }
407
+
408
+ // Project analysis
409
+ updateProgress(progress, 'Analyzing project', true)
410
+ displayProgress(progress)
411
+
412
+ const projectAnalysis = await analyzeProject()
413
+ console.log(`\n🔍 Project Analysis:`)
414
+ console.log(`📦 Project Type: ${projectAnalysis.type}`)
415
+ console.log(`⚙️ Package Manager: ${projectAnalysis.packageManager}`)
416
+ console.log(`🔒 Lock File: ${projectAnalysis.hasLockFile ? 'Found' : 'Not found'}`)
417
+ console.log(`📄 Dependency Files: ${projectAnalysis.hasDependencyFiles ? 'Found' : 'None'}`)
418
+ console.log(`🔄 GitHub Actions: ${projectAnalysis.hasGitHubActions ? 'Found' : 'None'}`)
419
+ console.log(`💡 Recommended Preset: ${projectAnalysis.recommendedPreset}`)
420
+
421
+ if (projectAnalysis.recommendations.length > 0) {
422
+ console.log('\n📋 Recommendations:')
423
+ projectAnalysis.recommendations.forEach((rec: string) => console.log(` • ${rec}`))
424
+ }
425
+
426
+ // Step 1: Repository Detection
427
+ updateProgress(progress, 'Repository Detection', true)
428
+ displayProgress(progress)
429
+
430
+ console.log('\n📍 Repository Detection')
431
+ const repoInfo = await detectRepository()
432
+ if (!repoInfo) {
433
+ console.log('❌ Could not detect repository. Please ensure you\'re in a Git repository.')
434
+ process.exit(1)
435
+ }
436
+
437
+ console.log(`✅ Detected repository: ${repoInfo.owner}/${repoInfo.name}`)
438
+ console.log(`🔗 GitHub URL: https://github.com/${repoInfo.owner}/${repoInfo.name}`)
439
+
440
+ // Validate repository access
441
+ const repoValidation = await validateRepositoryAccess(repoInfo)
442
+ if (repoValidation.warnings.length > 0 || repoValidation.suggestions.length > 0) {
443
+ displayValidationResults(repoValidation, '🔍 Repository Validation')
444
+ }
445
+
446
+ // Step 2: Token Setup Guide
447
+ updateProgress(progress, 'GitHub Token Setup', true)
448
+ displayProgress(progress)
449
+
450
+ console.log('\n🔑 GitHub Token Setup')
451
+ console.log('For full functionality, Buddy needs appropriate GitHub permissions.')
452
+ console.log('This enables workflow file updates and advanced GitHub Actions features.\n')
453
+
454
+ let tokenSetup
455
+ if (options.nonInteractive) {
456
+ // Use default token setup based on flag
457
+ switch (options.tokenSetup) {
458
+ case 'existing-secret':
459
+ tokenSetup = { hasCustomToken: true, needsGuide: false }
460
+ console.log('✅ Using existing organization/repository secrets')
461
+ break
462
+ case 'new-pat':
463
+ tokenSetup = { hasCustomToken: true, needsGuide: true }
464
+ console.log('⚠️ Non-interactive mode: Will use custom token but skip setup guide')
465
+ break
466
+ case 'default-token':
467
+ default:
468
+ tokenSetup = { hasCustomToken: false, needsGuide: false }
469
+ console.log('✅ Using default GITHUB_TOKEN (limited functionality)')
470
+ break
471
+ }
472
+ }
473
+ else {
474
+ tokenSetup = await confirmTokenSetup()
475
+ if (tokenSetup.needsGuide) {
476
+ await guideTokenCreation(repoInfo)
477
+ }
478
+ }
479
+
480
+ // Step 3: Repository Settings
481
+ updateProgress(progress, 'Repository Settings', true)
482
+ displayProgress(progress)
483
+
484
+ console.log('\n🔧 Repository Settings')
485
+ await guideRepositorySettings(repoInfo)
486
+
487
+ // Step 4: Workflow Configuration
488
+ updateProgress(progress, 'Workflow Configuration', true)
489
+ displayProgress(progress)
490
+
491
+ console.log('\n⚙️ Workflow Configuration')
492
+ let workflowResponse
493
+ if (options.nonInteractive) {
494
+ workflowResponse = { useCase: options.preset }
495
+ console.log(`✅ Using ${options.preset} preset for workflow configuration`)
496
+ }
497
+ else {
498
+ workflowResponse = await prompts([
499
+ {
500
+ type: 'select',
501
+ name: 'useCase',
502
+ message: 'What type of update schedule would you like?',
503
+ choices: [
504
+ {
505
+ title: 'Standard Setup (Recommended)',
506
+ description: 'Dashboard updates 3x/week, dependency updates on schedule',
507
+ value: 'standard',
508
+ },
509
+ {
510
+ title: 'High Frequency',
511
+ description: 'Check for updates multiple times per day',
512
+ value: 'high-frequency',
513
+ },
514
+ {
515
+ title: 'Security Focused',
516
+ description: 'Frequent patch updates with security-first approach',
517
+ value: 'security',
518
+ },
519
+ {
520
+ title: 'Minimal Updates',
521
+ description: 'Weekly checks, lower frequency',
522
+ value: 'minimal',
523
+ },
524
+ {
525
+ title: 'Development/Testing',
526
+ description: 'Manual triggers + frequent checks for testing',
527
+ value: 'testing',
528
+ },
529
+ {
530
+ title: 'Custom Configuration',
531
+ description: 'Create your own schedule',
532
+ value: 'custom',
533
+ },
534
+ ],
535
+ },
536
+ ])
537
+
538
+ if (!workflowResponse.useCase) {
539
+ console.log('Setup cancelled.')
540
+ return
541
+ }
542
+ }
543
+
544
+ // Step 5: Generate Configuration File
545
+ updateProgress(progress, 'Configuration File', true)
546
+ displayProgress(progress)
547
+
548
+ console.log('\n📝 Configuration File')
549
+ await generateConfigFile(repoInfo, tokenSetup.hasCustomToken)
550
+
551
+ // Step 6: Generate Workflows
552
+ updateProgress(progress, 'Workflow Generation', true)
553
+ displayProgress(progress)
554
+
555
+ console.log('\n🔄 Workflow Generation')
556
+ const preset = getWorkflowPreset(workflowResponse.useCase)
557
+
558
+ if (workflowResponse.useCase === 'custom' && !options.nonInteractive) {
559
+ await setupCustomWorkflow(preset, logger)
560
+ }
561
+ else {
562
+ console.log(`✨ Setting up ${preset.name}...`)
563
+ console.log(`📋 ${preset.description}`)
564
+ }
565
+
566
+ // Generate the core workflows based on the provided templates
567
+ await generateCoreWorkflows(preset, repoInfo, tokenSetup.hasCustomToken, logger)
568
+
569
+ // Step 7: Workflow Validation
570
+ updateProgress(progress, 'Workflow Validation', true)
571
+ displayProgress(progress)
572
+
573
+ console.log('\n🔍 Validating Generated Workflows')
574
+
575
+ // Validate each generated workflow
576
+ const workflowFiles = [
577
+ { name: 'buddy-dashboard.yml', content: '' },
578
+ { name: 'buddy-check.yml', content: '' },
579
+ { name: 'buddy-update.yml', content: '' },
580
+ ]
581
+
582
+ let validationPassed = true
583
+ for (const workflowFile of workflowFiles) {
584
+ try {
585
+ const workflowPath = `.github/workflows/${workflowFile.name}`
586
+ if (fs.existsSync(workflowPath)) {
587
+ const content = fs.readFileSync(workflowPath, 'utf8')
588
+ const validation = await validateWorkflowGeneration(content)
589
+
590
+ if (!validation.success) {
591
+ console.log(`❌ ${workflowFile.name} validation failed`)
592
+ displayValidationResults(validation, `${workflowFile.name} Issues`)
593
+ validationPassed = false
594
+ }
595
+ else {
596
+ console.log(`✅ ${workflowFile.name} validated successfully`)
597
+ }
598
+ }
599
+ }
600
+ catch {
601
+ console.log(`⚠️ Could not validate ${workflowFile.name}`)
602
+ }
603
+ }
604
+
605
+ if (!validationPassed) {
606
+ console.log('\n⚠️ Some workflows have validation issues. Please review the warnings above.')
607
+ }
608
+
609
+ // Step 8: Final Setup Instructions & Plugin Execution
610
+ updateProgress(progress, 'Setup Complete', true)
611
+ displayProgress(progress)
612
+
613
+ console.log('\n🎉 Setup Complete!')
614
+ await showFinalInstructions(repoInfo, tokenSetup.hasCustomToken)
615
+
616
+ // Execute plugin hooks for setup completion
617
+ if (availablePlugins.length > 0) {
618
+ console.log('\n🔌 Executing integration hooks...')
619
+ const setupContext = {
620
+ step: 'setup_complete',
621
+ progress,
622
+ config: migrationResults.length > 0 ? migrationResults[0].migratedSettings : {},
623
+ repository: repoInfo,
624
+ analysis: projectAnalysis,
625
+ plugins: availablePlugins,
626
+ }
627
+
628
+ pluginManager.setContext(setupContext)
629
+ await pluginManager.executePluginHooks({ event: 'setup_complete' })
630
+ }
631
+ }
632
+ catch (error) {
633
+ logger.error('Setup failed:', error)
634
+ process.exit(1)
635
+ }
636
+ })
637
+
638
+ cli
639
+ .command('scan', 'Scan for dependency updates')
640
+ .option('--verbose, -v', 'Enable verbose logging')
641
+ .option('--packages <names>', 'Comma-separated list of packages to check')
642
+ .option('--pattern <pattern>', 'Glob pattern to match packages')
643
+ .option('--strategy <type>', 'Update strategy: major|minor|patch|all', { default: 'all' })
644
+ .option('--ignore <names>', 'Comma-separated list of packages to ignore')
645
+ .option('--respect-latest', 'Respect "latest", "*", and other dynamic version indicators (default: true)')
646
+ .option('--no-respect-latest', 'Allow updating "latest", "*", and other dynamic version indicators')
647
+ .example('buddy scan')
648
+ .example('buddy scan --verbose')
649
+ .example('buddy scan --packages "react,typescript,laravel/framework"')
650
+ .example('buddy scan --pattern "@types/*"')
651
+ .example('buddy scan --strategy minor')
652
+ .example('buddy scan --no-respect-latest')
653
+ .action(async (options: CLIOptions) => {
654
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
655
+ const config = await resolveConfig(options.config)
656
+
657
+ try {
658
+ logger.info('Loading configuration...')
659
+
660
+ // Parse packages from string if provided
661
+ let packages: string[] | undefined
662
+ if (options.packages) {
663
+ packages = options.packages.split(',').map(p => p.trim())
664
+ }
665
+
666
+ // Parse ignore list from string if provided
667
+ let ignore: string[] | undefined
668
+ if (options.ignore) {
669
+ ignore = options.ignore.split(',').map(p => p.trim())
670
+ }
671
+
672
+ // Override config with CLI options
673
+ const finalConfig: BuddyConfig = {
674
+ ...config,
675
+ verbose: options.verbose ?? config.verbose,
676
+ packages: {
677
+ ...config.packages,
678
+ strategy: options.strategy ?? config.packages?.strategy ?? 'all',
679
+ ignore: ignore ?? config.packages?.ignore,
680
+ respectLatest: options.respectLatest ?? config.packages?.respectLatest ?? true,
681
+ },
682
+ }
683
+
684
+ const buddy = new Buddy(finalConfig)
685
+
686
+ if (packages?.length) {
687
+ logger.info(`Checking specific packages: ${packages.join(', ')}`)
688
+ const updates = await buddy.checkPackages(packages)
689
+
690
+ if (updates.length === 0) {
691
+ logger.success('All specified packages are up to date!')
692
+ }
693
+ else {
694
+ logger.info(`Found ${updates.length} updates:`)
695
+ for (const update of updates) {
696
+ logger.info(` ${update.name}: ${update.currentVersion} → ${update.newVersion} (${update.updateType})`)
697
+ }
698
+ }
699
+ return
700
+ }
701
+
702
+ if (options.pattern) {
703
+ logger.info(`Checking packages with pattern: ${options.pattern}`)
704
+ const updates = await buddy.checkPackagesWithPattern(options.pattern)
705
+
706
+ if (updates.length === 0) {
707
+ logger.success('All matching packages are up to date!')
708
+ }
709
+ else {
710
+ logger.info(`Found ${updates.length} updates:`)
711
+ for (const update of updates) {
712
+ logger.info(` ${update.name}: ${update.currentVersion} → ${update.newVersion} (${update.updateType})`)
713
+ }
714
+ }
715
+ return
716
+ }
717
+
718
+ // Full project scan
719
+ const scanResult = await buddy.scanForUpdates()
720
+
721
+ if (scanResult.updates.length === 0) {
722
+ logger.success('All dependencies are up to date!')
723
+ return
724
+ }
725
+
726
+ logger.info(`\nScan Results:`)
727
+ logger.info(`📦 Total packages: ${scanResult.totalPackages}`)
728
+ logger.info(`🔄 Available updates: ${scanResult.updates.length}`)
729
+ logger.info(`⏱️ Scan duration: ${scanResult.duration}ms`)
730
+
731
+ // Group updates by type
732
+ const majorUpdates = scanResult.updates.filter(u => u.updateType === 'major')
733
+ const minorUpdates = scanResult.updates.filter(u => u.updateType === 'minor')
734
+ const patchUpdates = scanResult.updates.filter(u => u.updateType === 'patch')
735
+
736
+ if (majorUpdates.length > 0) {
737
+ logger.warn(`\n🚨 Major updates (${majorUpdates.length}):`)
738
+ for (const update of majorUpdates) {
739
+ logger.info(` ${update.name}: ${update.currentVersion} → ${update.newVersion}`)
740
+ }
741
+ }
742
+
743
+ if (minorUpdates.length > 0) {
744
+ logger.info(`\n✨ Minor updates (${minorUpdates.length}):`)
745
+ for (const update of minorUpdates) {
746
+ logger.info(` ${update.name}: ${update.currentVersion} → ${update.newVersion}`)
747
+ }
748
+ }
749
+
750
+ if (patchUpdates.length > 0) {
751
+ logger.info(`\n🔧 Patch updates (${patchUpdates.length}):`)
752
+ for (const update of patchUpdates) {
753
+ logger.info(` ${update.name}: ${update.currentVersion} → ${update.newVersion}`)
754
+ }
755
+ }
756
+
757
+ if (scanResult.groups.length > 0) {
758
+ logger.info(`\n📋 Update groups (${scanResult.groups.length}):`)
759
+ for (const group of scanResult.groups) {
760
+ logger.info(` ${group.name}: ${group.updates.length} updates`)
761
+ }
762
+ }
763
+ }
764
+ catch (error) {
765
+ logger.error('Scan failed:', error)
766
+ process.exit(1)
767
+ }
768
+ })
769
+
770
+ cli
771
+ .command('dashboard', 'Create or update dependency dashboard issue')
772
+ .option('--verbose, -v', 'Enable verbose logging')
773
+ .option('--title <title>', 'Custom dashboard title')
774
+ .option('--issue-number <number>', 'Update specific issue number')
775
+ .option('--pin', 'Pin the dashboard issue to the top of the issue list')
776
+ .option('--no-pin', 'Unpin the dashboard issue')
777
+ .example('buddy dashboard')
778
+ .example('buddy dashboard --title "My Dependencies"')
779
+ .example('buddy dashboard --issue-number 42')
780
+ .example('buddy dashboard --pin')
781
+ .action(async (options: CLIOptions & { pin?: boolean, title?: string, issueNumber?: string }) => {
782
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
783
+ const config = await resolveConfig(options.config)
784
+
785
+ try {
786
+ logger.info('Creating or updating dependency dashboard...')
787
+
788
+ // Check if repository is configured
789
+ if (!config.repository) {
790
+ logger.error('❌ Repository configuration required for dashboard')
791
+ logger.info('Configure repository.provider, repository.owner, repository.name in buddy.config.ts')
792
+ process.exit(1)
793
+ }
794
+
795
+ // Override config with CLI options
796
+ const finalConfig: BuddyConfig = {
797
+ ...config,
798
+ verbose: options.verbose ?? config.verbose,
799
+ dashboard: {
800
+ ...config.dashboard,
801
+ enabled: true,
802
+ title: options.title ?? config.dashboard?.title,
803
+ issueNumber: options.issueNumber ? Number.parseInt(options.issueNumber, 10) : config.dashboard?.issueNumber,
804
+ pin: options.pin ?? config.dashboard?.pin,
805
+ },
806
+ }
807
+
808
+ const buddy = new Buddy(finalConfig)
809
+ const issue = await buddy.createOrUpdateDashboard()
810
+
811
+ logger.success(`✅ Dashboard updated: ${issue.url}`)
812
+ logger.info(`📊 Issue #${issue.number}: ${issue.title}`)
813
+ }
814
+ catch (error) {
815
+ logger.error('Dashboard creation failed:', error)
816
+ process.exit(1)
817
+ }
818
+ })
819
+
820
+ cli
821
+ .command('update', 'Update dependencies and create PRs')
822
+ .option('--verbose, -v', 'Enable verbose logging')
823
+ .option('--strategy <type>', 'Update strategy: major|minor|patch|all', { default: 'all' })
824
+ .option('--ignore <names>', 'Comma-separated list of packages to ignore')
825
+ .option('--dry-run', 'Preview changes without making them')
826
+ .option('--respect-latest', 'Respect "latest", "*", and other dynamic version indicators (default: true)')
827
+ .option('--no-respect-latest', 'Allow updating "latest", "*", and other dynamic version indicators')
828
+ .example('buddy update')
829
+ .example('buddy update --dry-run')
830
+ .example('buddy update --strategy patch')
831
+ .example('buddy update --verbose')
832
+ .example('buddy update --no-respect-latest')
833
+ .action(async (options: CLIOptions) => {
834
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
835
+ const config = await resolveConfig(options.config)
836
+
837
+ try {
838
+ logger.info('Starting dependency update process...')
839
+
840
+ // Parse ignore list from string if provided
841
+ let ignore: string[] | undefined
842
+ if (options.ignore) {
843
+ ignore = options.ignore.split(',').map(p => p.trim())
844
+ }
845
+
846
+ const finalConfig: BuddyConfig = {
847
+ ...config,
848
+ verbose: options.verbose ?? config.verbose,
849
+ packages: {
850
+ ...config.packages,
851
+ strategy: options.strategy ?? config.packages?.strategy ?? 'all',
852
+ ignore: ignore ?? config.packages?.ignore,
853
+ respectLatest: options.respectLatest ?? config.packages?.respectLatest ?? true,
854
+ },
855
+ }
856
+
857
+ const buddy = new Buddy(finalConfig)
858
+ const scanResult = await buddy.scanForUpdates()
859
+
860
+ if (scanResult.updates.length === 0) {
861
+ logger.success('All dependencies are up to date!')
862
+ return
863
+ }
864
+
865
+ if (options.dryRun) {
866
+ logger.info('🔍 Dry run mode - no changes will be made')
867
+ logger.info(`Would create ${scanResult.groups.length} pull request(s):`)
868
+ for (const group of scanResult.groups) {
869
+ logger.info(` 📝 ${group.title} (${group.updates.length} updates)`)
870
+ }
871
+ return
872
+ }
873
+
874
+ // Create pull requests
875
+ await buddy.createPullRequests(scanResult)
876
+ logger.success('Update process completed!')
877
+ }
878
+ catch (error) {
879
+ logger.error('Update failed:', error)
880
+ process.exit(1)
881
+ }
882
+ })
883
+
884
+ cli
885
+ .command('rebase <pr-number>', 'Rebase/retry a pull request by recreating it with latest updates')
886
+ .option('--verbose, -v', 'Enable verbose logging')
887
+ .option('--force', 'Force rebase even if PR appears to be up to date')
888
+ .example('buddy rebase 17')
889
+ .example('buddy rebase 17 --verbose')
890
+ .example('buddy rebase 17 --force')
891
+ .action(async (prNumber: string, options: CLIOptions & { force?: boolean }) => {
892
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
893
+ const config = await resolveConfig(options.config)
894
+
895
+ try {
896
+ logger.info(`🔄 Rebasing/retrying PR #${prNumber}...`)
897
+
898
+ // Check if repository is configured
899
+ if (!config.repository) {
900
+ logger.error('❌ Repository configuration required for PR operations')
901
+ logger.info('Configure repository.provider, repository.owner, repository.name in buddy.config.ts')
902
+ process.exit(1)
903
+ }
904
+
905
+ const gitProvider = await providerFor(config, 'PR operations', logger)
906
+
907
+ const prNum = Number.parseInt(prNumber, 10)
908
+ if (Number.isNaN(prNum)) {
909
+ logger.error('❌ Invalid PR number provided')
910
+ process.exit(1)
911
+ }
912
+
913
+ // Get the PR to rebase
914
+ const prs = await gitProvider.getPullRequests('open')
915
+ const pr = prs.find(p => p.number === prNum)
916
+
917
+ if (!pr) {
918
+ logger.error(`❌ Could not find open PR #${prNum}`)
919
+ process.exit(1)
920
+ }
921
+
922
+ if (!pr.head.startsWith('buddy/')) {
923
+ logger.error(`❌ PR #${prNum} is not a buddy PR (branch: ${pr.head})`)
924
+ process.exit(1)
925
+ }
926
+
927
+ logger.info(`📋 Found PR: ${pr.title}`)
928
+ logger.info(`🌿 Branch: ${pr.head}`)
929
+
930
+ // Extract package updates from PR body to determine what to update
931
+ const packageUpdates = await extractPackageUpdatesFromPRBody(pr.body)
932
+
933
+ if (packageUpdates.length === 0) {
934
+ logger.error('❌ Could not extract package updates from PR body')
935
+ process.exit(1)
936
+ }
937
+
938
+ logger.info(`📦 Found ${packageUpdates.length} packages to update`)
939
+
940
+ // Check if we need to rebase by scanning for current updates
941
+ if (!options.force) {
942
+ logger.info('🔍 Checking if rebase is needed...')
943
+ const buddy = new Buddy(config)
944
+ const scanResult = await buddy.scanForUpdates()
945
+
946
+ // Check if current scan matches PR content
947
+ const currentUpdates = scanResult.updates.filter(u =>
948
+ packageUpdates.some(pu => pu.name === u.name),
949
+ )
950
+
951
+ const upToDate = packageUpdates.every(pu =>
952
+ currentUpdates.some(cu =>
953
+ cu.name === pu.name
954
+ && cu.newVersion === pu.newVersion,
955
+ ),
956
+ )
957
+
958
+ if (upToDate) {
959
+ logger.success('✅ PR is already up to date, no rebase needed')
960
+ logger.info('💡 Use --force to rebase anyway')
961
+ return
962
+ }
963
+ }
964
+
965
+ // Update the existing PR with latest updates (true rebase)
966
+ logger.info('🔄 Updating PR with latest updates...')
967
+
968
+ // Get latest updates
969
+ const buddy = new Buddy({
970
+ ...config,
971
+ verbose: options.verbose ?? config.verbose,
972
+ })
973
+
974
+ const scanResult = await buddy.scanForUpdates()
975
+ if (scanResult.updates.length === 0) {
976
+ logger.success('✅ All dependencies are now up to date!')
977
+ return
978
+ }
979
+
980
+ // Find the matching update group - must match exactly
981
+ const group = scanResult.groups.find(g =>
982
+ g.updates.length === packageUpdates.length
983
+ && g.updates.every(u => packageUpdates.some(pu => pu.name === u.name))
984
+ && packageUpdates.every(pu => g.updates.some(u => u.name === pu.name)),
985
+ )
986
+
987
+ if (!group) {
988
+ logger.error('❌ Could not find matching update group. This likely means the package grouping has changed.')
989
+ logger.info(`📋 PR packages: ${packageUpdates.map(p => p.name).join(', ')}`)
990
+ logger.info(`📋 Available groups: ${scanResult.groups.map(g => `${g.name} (${g.updates.length} packages)`).join(', ')}`)
991
+ logger.info(`💡 Close this PR manually and let buddy create new ones with correct grouping`)
992
+ return
993
+ }
994
+
995
+ // Generate new file changes (package.json, dependency files, GitHub Actions)
996
+ const packageJsonUpdates = await buddy.generateAllFileUpdates(group.updates)
997
+
998
+ // (#1361) When the generator returns no file changes — common for
999
+ // pantry/pkgx-style deps that don't have a JS lock/yaml writer —
1000
+ // do NOT force-push an empty commit onto the PR branch. Same bug
1001
+ // pattern as #1360 but in the rebase code path. Just untick the
1002
+ // rebase checkbox in-place so the workflow doesn't loop on it.
1003
+ if (packageJsonUpdates.length === 0) {
1004
+ logger.info(`ℹ️ No file changes generated for PR #${prNum} — likely a pantry/pkgx-style dep with no JS writer. Skipping commit to avoid an empty force-push.`)
1005
+ const currentBody = pr.body || ''
1006
+ const untickedBody = currentBody.replace(
1007
+ /- \[x\] <!-- rebase-check -->/g,
1008
+ '- [ ] <!-- rebase-check -->',
1009
+ )
1010
+ if (untickedBody !== currentBody) {
1011
+ await gitProvider.updatePullRequest(prNum, { body: untickedBody })
1012
+ logger.info('✅ Unticked rebase checkbox to prevent the next update-check run from re-triggering this no-op rebase.')
1013
+ }
1014
+ return
1015
+ }
1016
+
1017
+ // Recreate branch from base with latest dependency changes (Renovate-style)
1018
+ const baseBranch = config.repository?.baseBranch || 'main'
1019
+ await gitProvider.commitChanges(pr.head, group.title, packageJsonUpdates, baseBranch)
1020
+ logger.info(`✅ Recreated branch ${pr.head} from ${baseBranch} with latest changes`)
1021
+
1022
+ // Generate new PR content
1023
+ const { PullRequestGenerator } = await import('../src/pr/pr-generator')
1024
+ const prGenerator = new PullRequestGenerator({ verbose: options.verbose })
1025
+ const newBody = await prGenerator.generateBody(group)
1026
+
1027
+ // Update the PR with new title/body (and uncheck the rebase box)
1028
+ const updatedBody = newBody.replace(
1029
+ /- \[x\] <!-- rebase-check -->/g,
1030
+ '- [ ] <!-- rebase-check -->',
1031
+ )
1032
+
1033
+ await gitProvider.updatePullRequest(prNum, {
1034
+ title: group.title,
1035
+ body: updatedBody,
1036
+ })
1037
+
1038
+ logger.success('🔄 PR rebase completed! Updated existing PR in place.')
1039
+ }
1040
+ catch (error) {
1041
+ logger.error('Rebase failed:', error)
1042
+ process.exit(1)
1043
+ }
1044
+ })
1045
+
1046
+ /**
1047
+ * Extract package updates from a PR body.
1048
+ *
1049
+ * Prefers the embedded manifest and falls back to scraping the rendered
1050
+ * tables for PRs opened before manifests existed. A manifest that had to drop
1051
+ * rows is rejected outright: rebase matches the PR against a scan result by
1052
+ * exact package set, so acting on a partial list would silently rebase the PR
1053
+ * into the wrong group.
1054
+ */
1055
+ async function extractPackageUpdatesFromPRBody(body: string): Promise<Array<{ name: string, currentVersion: string, newVersion: string }>> {
1056
+ const manifest = parseManifest(body)
1057
+ if (manifest?.truncated)
1058
+ return []
1059
+ if (manifest)
1060
+ return manifestUpdates(manifest)
1061
+
1062
+ const updates: Array<{ name: string, currentVersion: string, newVersion: string }> = []
1063
+
1064
+ // Match table rows with package updates - handles both npm and Composer formats
1065
+ // npm format: | [package] | [`version` -> `version`] |
1066
+ // Composer format: | [package](link) | `version` -> `version` | file | status |
1067
+ const tableRowRegex = /\|\s*\[([^\]]+)\][^|]*\|\s*\[?`\^?([^`]+)`\s*->\s*`\^?([^`]+)`\]?/g
1068
+
1069
+ let match
1070
+
1071
+ while ((match = tableRowRegex.exec(body)) !== null) {
1072
+ const [, packageName, currentVersion, newVersion] = match
1073
+ updates.push({
1074
+ name: packageName,
1075
+ currentVersion,
1076
+ newVersion,
1077
+ })
1078
+ }
1079
+
1080
+ return updates
1081
+ }
1082
+
1083
+ cli
1084
+ .command('update-check', 'Check all open buddy PRs for rebase checkbox and auto-rebase if checked')
1085
+ .option('--verbose, -v', 'Enable verbose logging')
1086
+ .option('--dry-run', 'Check but don\'t actually rebase')
1087
+ .example('buddy update-check')
1088
+ .example('buddy update-check --verbose')
1089
+ .example('buddy update-check --dry-run')
1090
+ .action(async (options: CLIOptions) => {
1091
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
1092
+ const config = await resolveConfig(options.config)
1093
+
1094
+ try {
1095
+ // Check if repository is configured
1096
+ if (!config.repository) {
1097
+ logger.error('❌ Repository configuration required for PR operations')
1098
+ logger.info('Configure repository.provider, repository.owner, repository.name in buddy.config.ts')
1099
+ process.exit(1)
1100
+ }
1101
+
1102
+ const gitProvider = await providerFor(config, 'PR operations', logger)
1103
+
1104
+ // Step 0: Read the dashboard issue's checkboxes. A maintainer ticking a
1105
+ // box there is the same request as ticking one in the PR itself, so the
1106
+ // two are resolved into a single set of branches before any rebasing.
1107
+ const dashboard = await findDashboardIssue(gitProvider, config, logger)
1108
+ const dashboardActions = parseDashboardActions(dashboard?.body)
1109
+
1110
+ if (hasDashboardActions(dashboardActions)) {
1111
+ logger.info(`📋 Dashboard requests: ${dashboardActions.rebaseBranches.length} branch(es)`
1112
+ + `${dashboardActions.rebaseAll ? ', rebase all' : ''}`
1113
+ + `${dashboardActions.manualRun ? ', manual run' : ''}`)
1114
+ }
1115
+
1116
+ const requestedBranches = new Set(dashboardActions.rebaseBranches)
1117
+
1118
+ // Step 1: Check for rebase checkboxes using GitHub API (proper body access)
1119
+ logger.info('🔍 Checking for PRs with rebase checkbox enabled...')
1120
+
1121
+ let rebasedCount = 0
1122
+ let checkedPRs = 0
1123
+
1124
+ try {
1125
+ // Get all open PRs via GitHub API to access the raw body
1126
+ const openPRs = await gitProvider.getPullRequests('open')
1127
+
1128
+ // Filter to buddy PRs (branches starting with buddy/)
1129
+ const buddyPRs = openPRs.filter(pr => pr.head.startsWith('buddy/'))
1130
+
1131
+ logger.info(`📋 Found ${buddyPRs.length} buddy PRs to check for rebase requests`)
1132
+
1133
+ for (const pr of buddyPRs) {
1134
+ checkedPRs++
1135
+ const requestedFromDashboard = dashboardActions.rebaseAll || requestedBranches.has(pr.head)
1136
+ const hasRebaseChecked = checkRebaseCheckbox(pr.body || '') || requestedFromDashboard
1137
+
1138
+ if (hasRebaseChecked) {
1139
+ logger.info(`🔄 PR #${pr.number} has rebase ${requestedFromDashboard ? 'requested from the dashboard' : 'checkbox checked'}`)
1140
+
1141
+ if (options.dryRun) {
1142
+ logger.info(`🔍 [DRY RUN] Would rebase PR #${pr.number}`)
1143
+ rebasedCount++
1144
+ }
1145
+ else {
1146
+ logger.info(`🔄 Rebasing PR #${pr.number} via rebase command...`)
1147
+
1148
+ try {
1149
+ // Use the existing rebase command logic
1150
+ const { spawn } = await import('node:child_process')
1151
+ const rebaseProcess = spawn('bunx', ['@buddysh/buddy', 'rebase', pr.number.toString()], {
1152
+ stdio: 'inherit',
1153
+ cwd: process.cwd(),
1154
+ })
1155
+
1156
+ await new Promise((resolve, reject) => {
1157
+ rebaseProcess.on('close', (code) => {
1158
+ if (code === 0) {
1159
+ rebasedCount++
1160
+ resolve(code)
1161
+ }
1162
+ else {
1163
+ reject(new Error(`Rebase failed with code ${code}`))
1164
+ }
1165
+ })
1166
+ })
1167
+
1168
+ logger.success(`✅ Successfully rebased PR #${pr.number}`)
1169
+ }
1170
+ catch (rebaseError) {
1171
+ logger.error(`❌ Failed to rebase PR #${pr.number}:`, rebaseError)
1172
+ }
1173
+ }
1174
+ }
1175
+ }
1176
+
1177
+ if (rebasedCount > 0) {
1178
+ logger.success(`✅ ${options.dryRun ? 'Would rebase' : 'Successfully rebased'} ${rebasedCount} PR(s)`)
1179
+ }
1180
+ else if (checkedPRs > 0) {
1181
+ logger.info('📋 No PRs have rebase checkbox enabled')
1182
+ }
1183
+ }
1184
+ catch (error) {
1185
+ logger.warn('⚠️ Could not check for rebase requests:', error)
1186
+ }
1187
+
1188
+ // Step 1b: Clear the dashboard checkboxes and honour a manual run
1189
+ // request. Unticking happens whether or not the rebases succeeded —
1190
+ // leaving a box ticked would replay the same request every run.
1191
+ if (hasDashboardActions(dashboardActions) && dashboard) {
1192
+ if (options.dryRun) {
1193
+ logger.info('🔍 [DRY RUN] Would clear dashboard checkboxes')
1194
+ }
1195
+ else {
1196
+ try {
1197
+ await gitProvider.updateIssue(dashboard.number, {
1198
+ body: uncheckDashboardActions(dashboard.body || ''),
1199
+ })
1200
+ logger.success('✅ Cleared dashboard checkboxes')
1201
+ }
1202
+ catch (error) {
1203
+ logger.warn('⚠️ Could not clear dashboard checkboxes:', error)
1204
+ }
1205
+ }
1206
+
1207
+ if (dashboardActions.manualRun) {
1208
+ logger.info('🔄 Dashboard requested a full update run...')
1209
+ if (options.dryRun) {
1210
+ logger.info('🔍 [DRY RUN] Would run a full scan and create PRs')
1211
+ }
1212
+ else {
1213
+ try {
1214
+ const buddy = new Buddy(config)
1215
+ const scanResult = await buddy.scanForUpdates()
1216
+ if (scanResult.updates.length > 0)
1217
+ await buddy.createPullRequests(scanResult)
1218
+ else
1219
+ logger.info('✅ No updates found during the requested run')
1220
+ }
1221
+ catch (error) {
1222
+ logger.error('❌ Requested update run failed:', error)
1223
+ }
1224
+ }
1225
+ }
1226
+ }
1227
+
1228
+ // Step 2: Check for satisfied PRs (dependencies already at target version)
1229
+ logger.info('\n✅ Checking for PRs with satisfied dependencies...')
1230
+ try {
1231
+ const { Buddy } = await import('../src/buddy')
1232
+ const buddy = new Buddy(config)
1233
+ await buddy.checkAndCloseSatisfiedPRs(gitProvider, !!options.dryRun)
1234
+ }
1235
+ catch (error) {
1236
+ logger.error('⚠️ Could not check for satisfied PRs:', error)
1237
+ }
1238
+
1239
+ // Step 3: Check for obsolete PRs (composer files removed, etc.)
1240
+ logger.info('\n🔍 Checking for obsolete PRs due to removed dependency files...')
1241
+ try {
1242
+ const { Buddy } = await import('../src/buddy')
1243
+ const buddy = new Buddy(config)
1244
+ await buddy.checkAndCloseObsoletePRs(gitProvider, !!options.dryRun)
1245
+ }
1246
+ catch (error) {
1247
+ logger.error('⚠️ Could not check for obsolete PRs:', error)
1248
+ }
1249
+
1250
+ // Step 4: Merge PRs that qualify for auto-merge and have green checks.
1251
+ // Repositories without required checks can't use GitHub's own queue, so
1252
+ // the decision is re-made here now that check results exist.
1253
+ let mergedCount = 0
1254
+ try {
1255
+ const buddy = new Buddy(config)
1256
+ const merged = await buddy.mergeEligiblePullRequests(!!options.dryRun)
1257
+ mergedCount = merged.length
1258
+
1259
+ if (mergedCount > 0)
1260
+ logger.success(`🔀 ${options.dryRun ? 'Would merge' : 'Merged'} ${mergedCount} PR(s)`)
1261
+ }
1262
+ catch (error) {
1263
+ logger.warn('⚠️ Could not process auto-merge:', error)
1264
+ }
1265
+
1266
+ // Step 5: Run branch cleanup (uses local git commands, no API calls)
1267
+ logger.info('\n🧹 Running branch cleanup...')
1268
+ assertSupports(gitProvider, 'branchHousekeeping', 'cleanupStaleBranches', 'branch cleanup')
1269
+ const result = await gitProvider.cleanupStaleBranches(2, !!options.dryRun)
1270
+
1271
+ if (options.dryRun) {
1272
+ logger.info(`🔍 [DRY RUN] Would delete ${result.deleted.length} stale branches`)
1273
+ }
1274
+ else {
1275
+ logger.success(`🎉 Cleanup complete: ${result.deleted.length} branches deleted, ${result.failed.length} failed`)
1276
+ }
1277
+
1278
+ // Summary
1279
+ if (rebasedCount > 0 || mergedCount > 0 || result.deleted.length > 0) {
1280
+ logger.success(`\n🎉 Update-check complete: ${rebasedCount} PR(s) rebased, ${mergedCount} merged, ${result.deleted.length} branches cleaned`)
1281
+ }
1282
+ }
1283
+ catch (error) {
1284
+ logger.error('update-check failed:', error)
1285
+ process.exit(1)
1286
+ }
1287
+ })
1288
+
1289
+ /**
1290
+ * Locate the dependency dashboard issue.
1291
+ *
1292
+ * Prefers the configured issue number and otherwise matches on the dashboard
1293
+ * title, which is how the dashboard command itself finds the issue it owns.
1294
+ *
1295
+ * @returns The dashboard issue, or `null` when the repository has none
1296
+ */
1297
+ async function findDashboardIssue(
1298
+ gitProvider: { getIssues: (state?: 'open' | 'closed' | 'all') => Promise<Array<{ number: number, title: string, body: string }>> },
1299
+ config: BuddyConfig,
1300
+ logger: Logger,
1301
+ ): Promise<{ number: number, title: string, body: string } | null> {
1302
+ try {
1303
+ const issues = await gitProvider.getIssues('open')
1304
+ const configured = config.dashboard?.issueNumber
1305
+
1306
+ if (configured)
1307
+ return issues.find(issue => issue.number === configured) ?? null
1308
+
1309
+ const title = config.dashboard?.title ?? 'Dependency Dashboard'
1310
+ return issues.find(issue => issue.title === title)
1311
+ ?? issues.find(issue => issue.title.includes('Dependency Dashboard'))
1312
+ ?? null
1313
+ }
1314
+ catch (error) {
1315
+ logger.warn('⚠️ Could not load the dependency dashboard:', error)
1316
+ return null
1317
+ }
1318
+ }
1319
+
1320
+ // Helper function to check if rebase checkbox is checked
1321
+ function checkRebaseCheckbox(body: string): boolean {
1322
+ // Look for the checked rebase checkbox pattern - handle both "rebase/retry" and "update/retry"
1323
+ // Note: The generated checkbox has a leading space (` - [x]`) so we use \s* to match optional whitespace
1324
+ const checkedPattern = /\s*-\s*\[x\]\s*<!--\s*rebase-check\s*-->.*(?:rebase|update)\/retry/i
1325
+ return checkedPattern.test(body)
1326
+ }
1327
+
1328
+ cli
1329
+ .command('fix-ci', 'Diagnose a failing workflow run and repair it when the fix is clear')
1330
+ .option('--verbose, -v', 'Enable verbose logging')
1331
+ .option('--run-id <id>', 'Workflow run to diagnose')
1332
+ .option('--pr <number>', 'Pull request to comment on')
1333
+ .option('--dry-run', 'Report the diagnosis without acting')
1334
+ .example('buddy fix-ci --run-id 12345')
1335
+ .action(async (options: CLIOptions & { runId?: string, pr?: string, dryRun?: boolean }) => {
1336
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
1337
+ const config = await resolveConfig(options.config)
1338
+
1339
+ try {
1340
+ const provider = await providerFor(config, 'this command', logger)
1341
+
1342
+ assertSupports(provider, 'ciLogs', 'getWorkflowRunLogs', 'reading CI logs')
1343
+ const runId = options.runId ? Number.parseInt(options.runId, 10) : undefined
1344
+ const log = runId ? await provider.getWorkflowRunLogs(runId) : null
1345
+
1346
+ if (!log) {
1347
+ logger.warn('⚠️ Could not read the run logs; nothing to diagnose')
1348
+ return
1349
+ }
1350
+
1351
+ const { attemptFix } = await import('../src/ci')
1352
+ const { createAiClient } = await import('../src/ai')
1353
+
1354
+ const outcome = await attemptFix({
1355
+ log,
1356
+ workspace: process.cwd(),
1357
+ baseBranch: config.repository?.baseBranch ?? 'main',
1358
+ ai: createAiClient(config, logger),
1359
+ logger,
1360
+ regenerateLockfile: async () => {
1361
+ const { regenerateLockFile, detectRequiredPackageManagers } = await import('../src/utils/lock-file')
1362
+
1363
+ // Detection keys off the manifests a lockfile is derived from, so a
1364
+ // repository with several ecosystems regenerates each of them.
1365
+ const managers = detectRequiredPackageManagers(['package.json', 'composer.json'])
1366
+ let regenerated = false
1367
+
1368
+ for (const manager of managers) {
1369
+ const result = await regenerateLockFile(manager, process.cwd())
1370
+ if (result.success)
1371
+ regenerated = true
1372
+ else
1373
+ logger.warn(`⚠️ ${result.message}`)
1374
+ }
1375
+
1376
+ return regenerated
1377
+ },
1378
+ })
1379
+
1380
+ logger.info(`\n${outcome.report}\n`)
1381
+
1382
+ const prNumber = options.pr ? Number.parseInt(options.pr, 10) : undefined
1383
+ if (prNumber && !options.dryRun)
1384
+ await provider.createComment(prNumber, outcome.report)
1385
+
1386
+ logger.success(`✅ ${outcome.action}${outcome.fixed ? ' (fixed)' : ''}`)
1387
+ }
1388
+ catch (error) {
1389
+ logger.error('fix-ci failed:', error)
1390
+ process.exit(1)
1391
+ }
1392
+ })
1393
+
1394
+ cli
1395
+ .command('handle-comment', 'Handle an @buddy command from a GitHub event payload')
1396
+ .option('--verbose, -v', 'Enable verbose logging')
1397
+ .option('--payload <path>', 'Path to the event payload (default: GITHUB_EVENT_PATH)')
1398
+ .option('--dry-run', 'Report what would run without acting')
1399
+ .example('buddy handle-comment')
1400
+ .action(async (options: CLIOptions & { payload?: string, dryRun?: boolean }) => {
1401
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
1402
+ const config = await resolveConfig(options.config)
1403
+
1404
+ try {
1405
+ const payloadPath = options.payload || process.env.GITHUB_EVENT_PATH
1406
+ if (!payloadPath) {
1407
+ logger.error('❌ No event payload. Pass --payload or run inside GitHub Actions.')
1408
+ process.exit(1)
1409
+ }
1410
+
1411
+ const event = await Bun.file(payloadPath).json()
1412
+ const comment = event.comment
1413
+ const target = event.issue ?? event.pull_request
1414
+
1415
+ if (!comment?.body || !target?.number) {
1416
+ logger.info('ℹ️ Event carries no comment; nothing to do')
1417
+ return
1418
+ }
1419
+
1420
+ const { mentionsBot, parseCommand } = await import('../src/commands')
1421
+ if (!mentionsBot(comment.body)) {
1422
+ logger.info('ℹ️ Comment does not mention buddy; nothing to do')
1423
+ return
1424
+ }
1425
+
1426
+ const command = parseCommand(comment.body)
1427
+ if (!command) {
1428
+ // The workflow guard is deliberately looser than the parser, so a
1429
+ // mention inside a code fence lands here and stops.
1430
+ logger.info('ℹ️ Mention is not a command (quoted or inside code); nothing to do')
1431
+ return
1432
+ }
1433
+
1434
+ const provider = await providerFor(config, 'this command', logger)
1435
+
1436
+ const login = comment.user?.login ?? ''
1437
+ const isBot = comment.user?.type === 'Bot' || login.endsWith('[bot]')
1438
+
1439
+ const actor = {
1440
+ login,
1441
+ isBot,
1442
+ // Resolved rather than assumed: public repositories accept comments
1443
+ // from anyone, and this is what separates a maintainer from a stranger.
1444
+ // A provider that cannot resolve permissions is treated as granting
1445
+ // none: assuming write access from a stranger's comment is the one
1446
+ // failure mode worth being paranoid about.
1447
+ canWrite: !isBot && supports(provider, 'permissionLookup', 'hasWriteAccess')
1448
+ ? await provider.hasWriteAccess(login)
1449
+ : false,
1450
+ }
1451
+
1452
+ const isPullRequest = Boolean(event.pull_request ?? event.issue?.pull_request)
1453
+
1454
+ logger.info(`🤖 Handling \`${command.name}\` from @${login} on #${target.number}`)
1455
+
1456
+ if (options.dryRun) {
1457
+ logger.info(`🔍 [DRY RUN] Would run ${command.name} (canWrite: ${actor.canWrite})`)
1458
+ return
1459
+ }
1460
+
1461
+ if (supports(provider, 'commentReactions', 'reactToComment'))
1462
+ await provider.reactToComment(comment.id, 'eyes')
1463
+
1464
+ const { createHandlers, dispatchCommand } = await import('../src/commands')
1465
+ const { runReviewForPR } = await import('../src/review/run')
1466
+
1467
+ const outcome = await dispatchCommand(
1468
+ {
1469
+ command,
1470
+ actor,
1471
+ number: target.number,
1472
+ isPullRequest,
1473
+ commentId: comment.id,
1474
+ logger,
1475
+ },
1476
+ createHandlers({
1477
+ config,
1478
+ provider,
1479
+ review: async (prNumber, reviewOptions) =>
1480
+ await runReviewForPR({ config, provider, prNumber, logger, ...reviewOptions }),
1481
+ rebase: async (prNumber) => {
1482
+ const { spawn } = await import('node:child_process')
1483
+ await new Promise<void>((resolve, reject) => {
1484
+ const child = spawn('bunx', ['@buddysh/buddy', 'rebase', String(prNumber)], { stdio: 'inherit' })
1485
+ child.on('close', code => (code === 0 ? resolve() : reject(new Error(`rebase exited ${code}`))))
1486
+ })
1487
+ return 'Rebased.'
1488
+ },
1489
+ merge: async () => await new Buddy(config).mergeEligiblePullRequests(false),
1490
+ remember: async (text, context) => {
1491
+ const { addLearning, createLearning, loadLearnings, serializeLearnings, DEFAULT_LEARNINGS_FILE }
1492
+ = await import('../src/ai')
1493
+
1494
+ const baseBranch = config.repository?.baseBranch ?? 'main'
1495
+ const existing = await loadLearnings(
1496
+ (path, ref) => provider.getFileContent(path, ref),
1497
+ baseBranch,
1498
+ DEFAULT_LEARNINGS_FILE,
1499
+ logger,
1500
+ )
1501
+
1502
+ const learning = createLearning(text, {
1503
+ source: context.isPullRequest ? { pr: context.number } : { issue: context.number },
1504
+ })
1505
+
1506
+ // Committed on a branch and opened as a PR rather than pushed to
1507
+ // the base: a learning changes how future reviews behave, so it
1508
+ // gets the same review a code change would.
1509
+ const branch = `buddy/learning-${learning.id}`
1510
+ await provider.commitChanges(
1511
+ branch,
1512
+ `chore(buddy): record a learning`,
1513
+ [{ path: DEFAULT_LEARNINGS_FILE, content: serializeLearnings(addLearning(existing, learning)), type: 'update' }],
1514
+ baseBranch,
1515
+ )
1516
+ await provider.createPullRequest({
1517
+ title: 'chore(buddy): record a learning',
1518
+ body: `Recorded from #${context.number}:\n\n> ${text}`,
1519
+ head: branch,
1520
+ base: baseBranch,
1521
+ draft: false,
1522
+ })
1523
+
1524
+ return `Noted. I opened a pull request adding it to \`${DEFAULT_LEARNINGS_FILE}\` so it gets reviewed like any other change.`
1525
+ },
1526
+ }),
1527
+ )
1528
+
1529
+ if (outcome.reply)
1530
+ await provider.createComment(target.number, outcome.reply)
1531
+
1532
+ if (supports(provider, 'commentReactions', 'reactToComment'))
1533
+ await provider.reactToComment(comment.id, outcome.handled ? 'rocket' : 'confused')
1534
+
1535
+ logger.success(outcome.handled ? `✅ Handled \`${command.name}\`` : `ℹ️ Did not run: ${outcome.refusal}`)
1536
+ }
1537
+ catch (error) {
1538
+ logger.error('handle-comment failed:', error)
1539
+ process.exit(1)
1540
+ }
1541
+ })
1542
+
1543
+ cli
1544
+ .command('review [pr-number]', 'Review a pull request, or local changes when no PR is given')
1545
+ .option('--verbose, -v', 'Enable verbose logging')
1546
+ .option('--base <branch>', 'Base branch to diff against for a local review')
1547
+ .option('--staged', 'Review staged changes only')
1548
+ .option('--branch', 'Review this branch against its base, rather than the working tree')
1549
+ .option('--light', 'Analyzers only — no AI call, fast enough for a pre-commit hook')
1550
+ .option('--format <name>', 'Output format: pretty|json|github|agent', { default: 'pretty' })
1551
+ .option('--fix', 'Apply committable suggestions to the working tree')
1552
+ .option('--yes', 'Apply fixes without confirming each one')
1553
+ .option('--fail-on <severity>', 'Exit non-zero when a finding at or above this severity is found')
1554
+ .option('--profile <name>', 'Review profile: chill|assertive')
1555
+ .option('--summary-only', 'Post only the summary, without inline findings')
1556
+ .option('--dry-run', 'Print the review instead of posting it')
1557
+ .example('buddy review 42')
1558
+ .example('buddy review --staged --light')
1559
+ .example('buddy review --format agent | claude')
1560
+ .action(async (prNumber: string | undefined, options: CLIOptions & {
1561
+ base?: string
1562
+ staged?: boolean
1563
+ branch?: boolean
1564
+ light?: boolean
1565
+ format?: string
1566
+ fix?: boolean
1567
+ yes?: boolean
1568
+ failOn?: string
1569
+ profile?: 'chill' | 'assertive'
1570
+ summaryOnly?: boolean
1571
+ dryRun?: boolean
1572
+ }) => {
1573
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
1574
+ const config = await resolveConfig(options.config)
1575
+
1576
+ const format = (options.format ?? 'pretty') as ReviewFormat
1577
+ if (!REVIEW_FORMATS.includes(format)) {
1578
+ logger.error(`❌ Unknown format '${format}'. Expected one of ${REVIEW_FORMATS.join(', ')}.`)
1579
+ process.exit(1)
1580
+ }
1581
+
1582
+ // Machine-readable formats own stdout: a log line in the middle of a JSON
1583
+ // document or an agent prompt breaks whatever is consuming it.
1584
+ const quiet = format !== 'pretty'
1585
+ const log = quiet ? Logger.silent() : logger
1586
+
1587
+ try {
1588
+ const { createAiClient } = await import('../src/ai')
1589
+ const ai = createAiClient(config, log)
1590
+
1591
+ // Local review runs without a key when only analyzers are wanted. A PR
1592
+ // review needs the model — analyzers alone cannot write a summary.
1593
+ if (!ai && (prNumber || !options.light)) {
1594
+ logger.error('❌ AI review needs an API key, or use --light for analyzers only. See https://buddy.sh/ai/providers')
1595
+ process.exit(1)
1596
+ }
1597
+
1598
+ const {
1599
+ composeInstructions,
1600
+ loadGuidelines,
1601
+ parseReviewState,
1602
+ prepareReview,
1603
+ reviewDiff,
1604
+ } = await import('../src/review')
1605
+ const { collectLocalDiff, formatReview, shouldFail } = await import('../src/review/local')
1606
+ const { runAnalyzers } = await import('../src/analysis')
1607
+
1608
+ let diff: string
1609
+ let headSha = ''
1610
+ let seenFingerprints: string[] = []
1611
+ let gitProvider: GitProvider | null = null
1612
+
1613
+ if (prNumber) {
1614
+ gitProvider = await providerFor(config, 'reviewing a pull request', log)
1615
+
1616
+ const number = Number.parseInt(prNumber, 10)
1617
+ diff = await gitProvider.getPullRequestDiff(number)
1618
+
1619
+ // Carry forward what earlier reviews already said, so a re-review
1620
+ // reports only what is new rather than repeating itself.
1621
+ const prs = await gitProvider.getPullRequests('open')
1622
+ const pr = prs.find(candidate => candidate.number === number)
1623
+ const state = parseReviewState(pr?.body)
1624
+ seenFingerprints = state?.fingerprints ?? []
1625
+ headSha = state?.reviewedSha ?? ''
1626
+ }
1627
+ else {
1628
+ const base = options.base || config.repository?.baseBranch || 'main'
1629
+ const mode = options.staged ? 'staged' : options.branch ? 'branch' : 'working'
1630
+ log.info(`🔍 Reviewing ${mode} changes${mode === 'branch' ? ` against ${base}` : ''}...`)
1631
+ diff = await collectLocalDiff(mode, base)
1632
+ }
1633
+
1634
+ if (!diff.trim()) {
1635
+ if (!quiet)
1636
+ logger.success('✅ No changes to review')
1637
+ return
1638
+ }
1639
+
1640
+ // Analyzers run locally against the working tree, so a local review gets
1641
+ // the same secret scanning and linting a CI review does — with no token.
1642
+ const { parseUnifiedDiff } = await import('../src/review/diff')
1643
+ const changedFiles = parseUnifiedDiff(diff).files.map(file => file.path)
1644
+ const analysis = config.analysis?.enabled === false || prNumber
1645
+ ? { findings: [], ran: [], skipped: [] }
1646
+ : await runAnalyzers({
1647
+ files: changedFiles,
1648
+ root: process.cwd(),
1649
+ ...(config.analysis?.tools ? { enabled: config.analysis.tools } : {}),
1650
+ logger: log,
1651
+ })
1652
+
1653
+ if (options.light) {
1654
+ const result = {
1655
+ summary: `Static analysis of ${changedFiles.length} changed file(s).`,
1656
+ walkthrough: [],
1657
+ findings: analysis.findings,
1658
+ effort: 1,
1659
+ omittedFiles: analysis.skipped.map(entry => `${entry.name} (${entry.reason})`),
1660
+ }
1661
+
1662
+ process.stdout.write(formatReview(result, format))
1663
+
1664
+ if (options.failOn && shouldFail(result.findings, options.failOn as 'critical'))
1665
+ process.exit(1)
1666
+ return
1667
+ }
1668
+
1669
+ // Guidelines are inlined into the prompt, so they are always read from
1670
+ // the base branch — reading them from the PR's own branch would let a
1671
+ // contributor rewrite the rules their code is reviewed against.
1672
+ const baseRef = config.repository?.baseBranch || options.base || 'main'
1673
+ const guidelines = gitProvider
1674
+ ? await loadGuidelines(
1675
+ (path, ref) => gitProvider!.getFileContent(path, ref),
1676
+ baseRef,
1677
+ config.ai?.review?.guidelineFiles,
1678
+ logger,
1679
+ )
1680
+ : ''
1681
+
1682
+ const reviewed = await reviewDiff(ai!, {
1683
+ diff,
1684
+ profile: options.profile ?? config.ai?.review?.profile,
1685
+ summaryOnly: options.summaryOnly ?? config.ai?.review?.summaryOnly,
1686
+ instructions: composeInstructions({
1687
+ global: config.ai?.review?.instructions,
1688
+ guidelines,
1689
+ }),
1690
+ pathFilters: config.ai?.review?.pathFilters,
1691
+ pathInstructions: config.ai?.review?.pathInstructions,
1692
+ seenFingerprints,
1693
+ logger: log,
1694
+ })
1695
+
1696
+ // Analyzer findings join the model's, so one review reports everything
1697
+ // rather than the user having to run two commands and merge them.
1698
+ const result = {
1699
+ ...reviewed,
1700
+ findings: [...analysis.findings, ...reviewed.findings],
1701
+ omittedFiles: [...reviewed.omittedFiles, ...analysis.skipped.map(entry => `${entry.name} (${entry.reason})`)],
1702
+ }
1703
+
1704
+ const prepared = prepareReview(result, {
1705
+ headSha,
1706
+ requestChangesOn: config.ai?.review?.requestChangesOn,
1707
+ seenFingerprints,
1708
+ })
1709
+
1710
+ if (!prNumber) {
1711
+ process.stdout.write(formatReview(result, format))
1712
+
1713
+ if (options.fix) {
1714
+ const applied = await applyFixes(result.findings, Boolean(options.yes), logger)
1715
+ logger.success(`🔧 Applied ${applied} suggestion(s)`)
1716
+ }
1717
+
1718
+ if (options.failOn && shouldFail(result.findings, options.failOn as 'critical'))
1719
+ process.exit(1)
1720
+ return
1721
+ }
1722
+
1723
+ if (options.dryRun) {
1724
+ logger.info(`\n${prepared.body}\n`)
1725
+ for (const comment of prepared.comments)
1726
+ logger.info(`${comment.path}:${comment.line}\n${comment.body}\n`)
1727
+ logger.success(`✅ Review complete: ${result.findings.length} finding(s)`)
1728
+ return
1729
+ }
1730
+
1731
+ assertSupports(gitProvider!, 'inlineReviewComments', 'createReview', 'posting a review')
1732
+ await gitProvider.createReview(Number.parseInt(prNumber, 10), prepared)
1733
+ logger.success(`✅ Reviewed PR #${prNumber}: ${result.findings.length} finding(s)`)
1734
+ }
1735
+ catch (error) {
1736
+ logger.error('Review failed:', error)
1737
+ process.exit(1)
1738
+ }
1739
+ })
1740
+
1741
+ cli
1742
+ .command('check <packages...>', 'Check specific packages for updates')
1743
+ .option('--verbose, -v', 'Enable verbose logging')
1744
+ .option('--strategy <type>', 'Update strategy: major|minor|patch|all', { default: 'all' })
1745
+ .example('buddy check react typescript')
1746
+ .example('buddy check react --verbose')
1747
+ .action(async (...args: any[]) => {
1748
+ // CAC passes individual arguments, then options as the last parameter
1749
+ const options: CLIOptions = args[args.length - 1]
1750
+ const packages: string[] = args.slice(0, -1)
1751
+
1752
+ const checkLogger = options.verbose ? Logger.verbose() : Logger.quiet()
1753
+ const config = await resolveConfig(options.config)
1754
+
1755
+ if (!packages.length) {
1756
+ checkLogger.error('No packages specified to check')
1757
+ process.exit(1)
1758
+ }
1759
+
1760
+ try {
1761
+ checkLogger.info(`Checking specific packages: ${packages.join(', ')}`)
1762
+
1763
+ const finalConfig: BuddyConfig = {
1764
+ ...config,
1765
+ verbose: options.verbose ?? config.verbose,
1766
+ packages: {
1767
+ ...config.packages,
1768
+ strategy: options.strategy ?? config.packages?.strategy ?? 'all',
1769
+ },
1770
+ }
1771
+
1772
+ const buddy = new Buddy(finalConfig)
1773
+ const updates = await buddy.checkPackages(packages)
1774
+
1775
+ if (updates.length === 0) {
1776
+ checkLogger.success('All specified packages are up to date!')
1777
+ }
1778
+ else {
1779
+ checkLogger.info(`Found ${updates.length} updates:`)
1780
+ for (const update of updates) {
1781
+ checkLogger.info(` ${update.name}: ${update.currentVersion} → ${update.newVersion} (${update.updateType})`)
1782
+ }
1783
+ }
1784
+ }
1785
+ catch (error) {
1786
+ checkLogger.error('Check failed:', error)
1787
+ process.exit(1)
1788
+ }
1789
+ })
1790
+
1791
+ cli
1792
+ .command('schedule', 'Run automated dependency updates on schedule')
1793
+ .option('--verbose, -v', 'Enable verbose logging')
1794
+ .option('--strategy <type>', 'Update strategy: major|minor|patch|all', { default: 'all' })
1795
+ .example('buddy schedule')
1796
+ .example('buddy schedule --verbose')
1797
+ .example('buddy schedule --strategy patch')
1798
+ .action(async (options: CLIOptions) => {
1799
+ const { Scheduler } = await import('../src/scheduler/scheduler')
1800
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
1801
+ const config = await resolveConfig(options.config)
1802
+
1803
+ try {
1804
+ logger.info('🕒 Starting Buddy Scheduler...')
1805
+
1806
+ // Parse ignore list from string if provided
1807
+ let ignore: string[] | undefined
1808
+ if (options.ignore) {
1809
+ ignore = options.ignore.split(',').map(p => p.trim())
1810
+ }
1811
+
1812
+ const finalConfig: BuddyConfig = {
1813
+ ...config,
1814
+ verbose: options.verbose ?? config.verbose,
1815
+ packages: {
1816
+ ...config.packages,
1817
+ strategy: options.strategy ?? config.packages?.strategy ?? 'all',
1818
+ ignore: ignore ?? config.packages?.ignore,
1819
+ },
1820
+ }
1821
+
1822
+ // Validate that repository is configured for scheduling
1823
+ if (!finalConfig.repository?.provider || !finalConfig.repository?.owner || !finalConfig.repository?.name) {
1824
+ logger.error('❌ Repository configuration required for scheduling. Please configure:')
1825
+ logger.info(' - repository.provider (github)')
1826
+ logger.info(' - repository.owner')
1827
+ logger.info(' - repository.name')
1828
+ logger.info(' - repository.token (via environment variable)')
1829
+ process.exit(1)
1830
+ }
1831
+
1832
+ const scheduler = new Scheduler(options.verbose)
1833
+ const job = Scheduler.createJobFromConfig(finalConfig, 'cli-schedule')
1834
+
1835
+ // Override cron if provided
1836
+ if (options.strategy) {
1837
+ switch (options.strategy) {
1838
+ case 'major':
1839
+ job.schedule.cron = Scheduler.PRESETS.WEEKLY
1840
+ break
1841
+ case 'minor':
1842
+ job.schedule.cron = Scheduler.PRESETS.TWICE_WEEKLY
1843
+ break
1844
+ case 'patch':
1845
+ job.schedule.cron = Scheduler.PRESETS.DAILY
1846
+ break
1847
+ default:
1848
+ job.schedule.cron = Scheduler.PRESETS.WEEKLY
1849
+ }
1850
+ }
1851
+
1852
+ scheduler.addJob(job)
1853
+ scheduler.start()
1854
+
1855
+ logger.success(`✅ Scheduler started with cron: ${job.schedule.cron}`)
1856
+ logger.info('📅 Next run:', job.nextRun?.toISOString() || 'Unknown')
1857
+ logger.info('🛑 Press Ctrl+C to stop the scheduler')
1858
+
1859
+ // Keep process alive
1860
+ process.stdin.resume()
1861
+ }
1862
+ catch (error) {
1863
+ logger.error('Scheduler failed:', error)
1864
+ process.exit(1)
1865
+ }
1866
+ })
1867
+
1868
+ cli
1869
+ .command('generate-workflows', 'Generate GitHub Actions workflow templates (deprecated - use "setup" instead)')
1870
+ .option('--verbose, -v', 'Enable verbose logging')
1871
+ .example('buddy generate-workflows')
1872
+ .example('buddy generate-workflows --verbose')
1873
+ .action(async (options: CLIOptions) => {
1874
+ const { GitHubActionsTemplate } = await import('../src/templates/github-actions')
1875
+ const { writeFileSync, mkdirSync } = await import('node:fs')
1876
+ const { resolve } = await import('node:path')
1877
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
1878
+ const config = await resolveConfig(options.config)
1879
+
1880
+ console.log('⚠️ The "generate-workflows" command is deprecated.')
1881
+ console.log('💡 Use "buddy setup" for a better interactive experience.\n')
1882
+
1883
+ try {
1884
+ const finalConfig: BuddyConfig = {
1885
+ ...config,
1886
+ verbose: options.verbose ?? config.verbose,
1887
+ }
1888
+
1889
+ const outputDir = finalConfig.workflows?.outputDir
1890
+ ? resolve(process.cwd(), finalConfig.workflows.outputDir)
1891
+ : resolve(process.cwd(), '.github', 'workflows')
1892
+
1893
+ logger.info('🚀 Generating GitHub Actions workflow templates...')
1894
+
1895
+ // Create output directory
1896
+ try {
1897
+ mkdirSync(outputDir, { recursive: true })
1898
+ }
1899
+ catch {
1900
+ // Directory already exists
1901
+ }
1902
+
1903
+ // Generate workflows based on configuration
1904
+ const templates = finalConfig.workflows?.templates || {
1905
+ comprehensive: true,
1906
+ daily: true,
1907
+ weekly: true,
1908
+ monthly: true,
1909
+ docker: true,
1910
+ monorepo: true,
1911
+ }
1912
+
1913
+ let generatedCount = 0
1914
+
1915
+ // Generate standard scheduled workflows
1916
+ if (templates.daily || templates.weekly || templates.monthly) {
1917
+ const workflows = GitHubActionsTemplate.generateScheduledWorkflows(finalConfig)
1918
+
1919
+ for (const [filename, content] of Object.entries(workflows)) {
1920
+ const shouldGenerate = (
1921
+ (filename.includes('daily') && templates.daily)
1922
+ || (filename.includes('weekly') && templates.weekly)
1923
+ || (filename.includes('monthly') && templates.monthly)
1924
+ )
1925
+
1926
+ if (shouldGenerate) {
1927
+ const filepath = resolve(outputDir, filename)
1928
+ writeFileSync(filepath, content)
1929
+ logger.success(`Generated: ${filename}`)
1930
+ generatedCount++
1931
+ }
1932
+ }
1933
+ }
1934
+
1935
+ // Generate comprehensive workflow
1936
+ if (templates.comprehensive) {
1937
+ const comprehensiveWorkflow = GitHubActionsTemplate.generateComprehensiveWorkflow(finalConfig)
1938
+ writeFileSync(resolve(outputDir, 'buddy-comprehensive.yml'), comprehensiveWorkflow)
1939
+ logger.success('Generated: buddy-comprehensive.yml')
1940
+ generatedCount++
1941
+ }
1942
+
1943
+ // Generate specialized workflows
1944
+ if (templates.docker) {
1945
+ const dockerWorkflow = GitHubActionsTemplate.generateDockerWorkflow(finalConfig)
1946
+ writeFileSync(resolve(outputDir, 'buddy-docker.yml'), dockerWorkflow)
1947
+ logger.success('Generated: buddy-docker.yml')
1948
+ generatedCount++
1949
+ }
1950
+
1951
+ if (templates.monorepo) {
1952
+ const monorepoWorkflow = GitHubActionsTemplate.generateMonorepoWorkflow(finalConfig)
1953
+ writeFileSync(resolve(outputDir, 'buddy-monorepo.yml'), monorepoWorkflow)
1954
+ logger.success('Generated: buddy-monorepo.yml')
1955
+ generatedCount++
1956
+ }
1957
+
1958
+ // Generate custom workflows
1959
+ if (finalConfig.workflows?.custom?.length) {
1960
+ for (const customWorkflow of finalConfig.workflows.custom) {
1961
+ const workflowContent = GitHubActionsTemplate.generateCustomWorkflow(customWorkflow, finalConfig)
1962
+ const filename = `buddy-${customWorkflow.name.toLowerCase().replace(/\s+/g, '-')}.yml`
1963
+ writeFileSync(resolve(outputDir, filename), workflowContent)
1964
+ logger.success(`Generated: ${filename}`)
1965
+ generatedCount++
1966
+ }
1967
+ }
1968
+
1969
+ if (generatedCount === 0) {
1970
+ logger.warn('No workflows were generated. Check your configuration in buddy.config.ts')
1971
+ logger.info('Set workflows.templates to enable specific templates or add custom workflows.')
1972
+ return
1973
+ }
1974
+
1975
+ logger.success(`\n🎉 ${generatedCount} GitHub Actions workflow(s) generated!`)
1976
+ logger.info(`📁 Location: ${outputDir}`)
1977
+ logger.info('\n💡 Next steps:')
1978
+ logger.info(' 1. Review and customize the workflows for your project')
1979
+ logger.info(' 2. Ensure GITHUB_TOKEN is available as a secret')
1980
+ logger.info(' 3. Configure buddy.config.ts with your repository settings')
1981
+ logger.info(' 4. Enable GitHub Actions in your repository settings')
1982
+ logger.info('\n🔗 Learn more: https://docs.github.com/en/actions')
1983
+ }
1984
+ catch (error) {
1985
+ logger.error('Failed to generate workflows:', error)
1986
+ process.exit(1)
1987
+ }
1988
+ })
1989
+
1990
+ cli
1991
+ .command('info <package>', 'Show detailed package information')
1992
+ .option('--verbose, -v', 'Enable verbose logging')
1993
+ .option('--json', 'Output in JSON format')
1994
+ .example('buddy info react')
1995
+ .example('buddy info react --json')
1996
+ .example('buddy info typescript@latest')
1997
+ .action(async (packageName: string, options: CLIOptions & { json?: boolean }) => {
1998
+ const { RegistryClient } = await import('../src/registry/registry-client')
1999
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2000
+
2001
+ try {
2002
+ const registryClient = new RegistryClient(process.cwd(), logger, undefined)
2003
+
2004
+ if (options.json) {
2005
+ // Output raw JSON from bun info
2006
+ const { spawn } = await import('node:child_process')
2007
+ const child = spawn('bun', ['info', packageName, '--json'], {
2008
+ stdio: 'inherit',
2009
+ })
2010
+
2011
+ child.on('close', (code) => {
2012
+ process.exit(code || 0)
2013
+ })
2014
+ return
2015
+ }
2016
+
2017
+ // Get package metadata and display in a nice format
2018
+ const metadata = await registryClient.getPackageMetadata(packageName)
2019
+
2020
+ if (!metadata) {
2021
+ logger.error(`Package "${packageName}" not found or failed to fetch metadata`)
2022
+ process.exit(1)
2023
+ }
2024
+
2025
+ console.log(`📦 ${metadata.name}@${metadata.latestVersion}`)
2026
+
2027
+ if (metadata.description) {
2028
+ console.log(`📝 ${metadata.description}`)
2029
+ }
2030
+
2031
+ if (metadata.homepage) {
2032
+ console.log(`🌐 ${metadata.homepage}`)
2033
+ }
2034
+
2035
+ if (metadata.repository) {
2036
+ console.log(`📁 ${metadata.repository}`)
2037
+ }
2038
+
2039
+ if (metadata.license) {
2040
+ console.log(`⚖️ License: ${metadata.license}`)
2041
+ }
2042
+
2043
+ if (metadata.author) {
2044
+ console.log(`👤 Author: ${metadata.author}`)
2045
+ }
2046
+
2047
+ if (metadata.keywords && metadata.keywords.length > 0) {
2048
+ console.log(`🏷️ Keywords: ${metadata.keywords.join(', ')}`)
2049
+ }
2050
+
2051
+ const depCounts = {
2052
+ deps: Object.keys(metadata.dependencies || {}).length,
2053
+ devDeps: Object.keys(metadata.devDependencies || {}).length,
2054
+ peerDeps: Object.keys(metadata.peerDependencies || {}).length,
2055
+ }
2056
+
2057
+ console.log(`📊 Dependencies: ${depCounts.deps} | Dev: ${depCounts.devDeps} | Peer: ${depCounts.peerDeps}`)
2058
+
2059
+ if (metadata.versions && metadata.versions.length > 1) {
2060
+ console.log(`📈 ${metadata.versions.length} versions available`)
2061
+
2062
+ if (options.verbose && metadata.versions.length <= 10) {
2063
+ console.log(` Latest versions: ${metadata.versions.slice(-5).join(', ')}`)
2064
+ }
2065
+ }
2066
+ }
2067
+ catch (error) {
2068
+ logger.error('Failed to get package info:', error)
2069
+ process.exit(1)
2070
+ }
2071
+ })
2072
+
2073
+ cli
2074
+ .command('versions <package>', 'Show all available versions of a package')
2075
+ .option('--verbose, -v', 'Enable verbose logging')
2076
+ .option('--latest <count>', 'Show only the latest N versions', { default: '10' })
2077
+ .example('buddy versions react')
2078
+ .example('buddy versions react --latest 5')
2079
+ .action(async (packageName: string, options: CLIOptions & { latest?: string }) => {
2080
+ const { RegistryClient } = await import('../src/registry/registry-client')
2081
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2082
+
2083
+ try {
2084
+ const registryClient = new RegistryClient(process.cwd(), logger, undefined)
2085
+ const metadata = await registryClient.getPackageMetadata(packageName)
2086
+
2087
+ if (!metadata) {
2088
+ logger.error(`Package "${packageName}" not found`)
2089
+ process.exit(1)
2090
+ }
2091
+
2092
+ const latestCount = Number.parseInt(options.latest || '10', 10)
2093
+
2094
+ console.log(`📦 ${metadata.name} - Available Versions`)
2095
+ console.log(`📈 Total: ${metadata.versions?.length || 0} versions`)
2096
+ console.log(`⭐ Latest: ${metadata.latestVersion}`)
2097
+
2098
+ if (metadata.versions && metadata.versions.length > 0) {
2099
+ console.log('\n📋 Recent versions:')
2100
+ const versionsToShow = metadata.versions.slice(-latestCount).reverse()
2101
+
2102
+ versionsToShow.forEach((version, _index) => {
2103
+ const isLatest = version === metadata.latestVersion
2104
+ const prefix = isLatest ? '⭐' : ' '
2105
+ console.log(`${prefix} ${version}`)
2106
+ })
2107
+
2108
+ if (metadata.versions.length > latestCount) {
2109
+ console.log(` ... and ${metadata.versions.length - latestCount} older versions`)
2110
+ }
2111
+ }
2112
+ }
2113
+ catch (error) {
2114
+ logger.error('Failed to get package versions:', error)
2115
+ process.exit(1)
2116
+ }
2117
+ })
2118
+
2119
+ cli
2120
+ .command('exists <package>', 'Check if a package exists in the registry')
2121
+ .option('--verbose, -v', 'Enable verbose logging')
2122
+ .example('buddy exists react')
2123
+ .example('buddy exists nonexistent-package-xyz')
2124
+ .action(async (packageName: string, options: CLIOptions) => {
2125
+ const { RegistryClient } = await import('../src/registry/registry-client')
2126
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2127
+
2128
+ try {
2129
+ const registryClient = new RegistryClient(process.cwd(), logger, undefined)
2130
+ const exists = await registryClient.packageExists(packageName)
2131
+
2132
+ if (exists) {
2133
+ console.log(`✅ Package "${packageName}" exists in the registry`)
2134
+ process.exit(0)
2135
+ }
2136
+ else {
2137
+ console.log(`❌ Package "${packageName}" does not exist in the registry`)
2138
+ process.exit(1)
2139
+ }
2140
+ }
2141
+ catch (error) {
2142
+ logger.error('Failed to check package existence:', error)
2143
+ process.exit(1)
2144
+ }
2145
+ })
2146
+
2147
+ cli
2148
+ .command('latest <package>', 'Get the latest version of a package')
2149
+ .option('--verbose, -v', 'Enable verbose logging')
2150
+ .example('buddy latest react')
2151
+ .example('buddy latest @types/node')
2152
+ .action(async (packageName: string, options: CLIOptions) => {
2153
+ const { RegistryClient } = await import('../src/registry/registry-client')
2154
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2155
+
2156
+ try {
2157
+ const registryClient = new RegistryClient(process.cwd(), logger, undefined)
2158
+ const latestVersion = await registryClient.getLatestVersion(packageName)
2159
+
2160
+ if (latestVersion) {
2161
+ console.log(`📦 ${packageName}@${latestVersion}`)
2162
+ }
2163
+ else {
2164
+ logger.error(`Package "${packageName}" not found`)
2165
+ process.exit(1)
2166
+ }
2167
+ }
2168
+ catch (error) {
2169
+ logger.error('Failed to get latest version:', error)
2170
+ process.exit(1)
2171
+ }
2172
+ })
2173
+
2174
+ cli
2175
+ .command('deps <package>', 'Show dependencies of a package')
2176
+ .option('--verbose, -v', 'Enable verbose logging')
2177
+ .option('--dev', 'Show dev dependencies')
2178
+ .option('--peer', 'Show peer dependencies')
2179
+ .option('--all', 'Show all dependency types')
2180
+ .example('buddy deps react')
2181
+ .example('buddy deps react --dev')
2182
+ .example('buddy deps react --all')
2183
+ .action(async (packageName: string, options: CLIOptions & { dev?: boolean, peer?: boolean, all?: boolean }) => {
2184
+ const { RegistryClient } = await import('../src/registry/registry-client')
2185
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2186
+
2187
+ try {
2188
+ const registryClient = new RegistryClient(process.cwd(), logger, undefined)
2189
+ const metadata = await registryClient.getPackageMetadata(packageName)
2190
+
2191
+ if (!metadata) {
2192
+ logger.error(`Package "${packageName}" not found`)
2193
+ process.exit(1)
2194
+ }
2195
+
2196
+ console.log(`📦 ${metadata.name}@${metadata.latestVersion} - Dependencies`)
2197
+
2198
+ const showProd = !options.dev && !options.peer
2199
+ const showDev = options.dev || options.all
2200
+ const showPeer = options.peer || options.all
2201
+
2202
+ if (showProd || options.all) {
2203
+ const deps = metadata.dependencies || {}
2204
+ const depCount = Object.keys(deps).length
2205
+
2206
+ console.log(`\n📋 Production Dependencies (${depCount}):`)
2207
+ if (depCount > 0) {
2208
+ Object.entries(deps).forEach(([name, version]) => {
2209
+ console.log(` ${name}: ${version}`)
2210
+ })
2211
+ }
2212
+ else {
2213
+ console.log(' No production dependencies')
2214
+ }
2215
+ }
2216
+
2217
+ if (showDev) {
2218
+ const devDeps = metadata.devDependencies || {}
2219
+ const devDepCount = Object.keys(devDeps).length
2220
+
2221
+ console.log(`\n🛠️ Dev Dependencies (${devDepCount}):`)
2222
+ if (devDepCount > 0) {
2223
+ Object.entries(devDeps).forEach(([name, version]) => {
2224
+ console.log(` ${name}: ${version}`)
2225
+ })
2226
+ }
2227
+ else {
2228
+ console.log(' No dev dependencies')
2229
+ }
2230
+ }
2231
+
2232
+ if (showPeer) {
2233
+ const peerDeps = metadata.peerDependencies || {}
2234
+ const peerDepCount = Object.keys(peerDeps).length
2235
+
2236
+ console.log(`\n🤝 Peer Dependencies (${peerDepCount}):`)
2237
+ if (peerDepCount > 0) {
2238
+ Object.entries(peerDeps).forEach(([name, version]) => {
2239
+ console.log(` ${name}: ${version}`)
2240
+ })
2241
+ }
2242
+ else {
2243
+ console.log(' No peer dependencies')
2244
+ }
2245
+ }
2246
+ }
2247
+ catch (error) {
2248
+ logger.error('Failed to get package dependencies:', error)
2249
+ process.exit(1)
2250
+ }
2251
+ })
2252
+
2253
+ cli
2254
+ .command('compare <package> <version1> <version2>', 'Compare two versions of a package')
2255
+ .option('--verbose, -v', 'Enable verbose logging')
2256
+ .example('buddy compare react 17.0.0 18.0.0')
2257
+ .example('buddy compare typescript 4.9.0 5.0.0')
2258
+ .action(async (packageName: string, version1: string, version2: string, options: CLIOptions) => {
2259
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2260
+
2261
+ try {
2262
+ console.log(`📊 Comparing ${packageName}: ${version1} vs ${version2}`)
2263
+
2264
+ // Get package metadata to validate versions exist
2265
+ const { RegistryClient } = await import('../src/registry/registry-client')
2266
+ const registryClient = new RegistryClient(process.cwd(), logger, undefined)
2267
+ const metadata = await registryClient.getPackageMetadata(packageName)
2268
+
2269
+ if (!metadata) {
2270
+ logger.error(`Package "${packageName}" not found`)
2271
+ process.exit(1)
2272
+ }
2273
+
2274
+ const availableVersions = metadata.versions || []
2275
+
2276
+ if (!availableVersions.includes(version1)) {
2277
+ console.log(`⚠️ Version ${version1} not found in available versions`)
2278
+ }
2279
+
2280
+ if (!availableVersions.includes(version2)) {
2281
+ console.log(`⚠️ Version ${version2} not found in available versions`)
2282
+ }
2283
+
2284
+ // Basic version comparison using semver-like logic
2285
+ const { getUpdateType } = await import('../src/utils/helpers')
2286
+ const updateType = getUpdateType(version1, version2)
2287
+
2288
+ console.log(`\n🔍 Version Analysis:`)
2289
+ console.log(` From: ${version1}`)
2290
+ console.log(` To: ${version2}`)
2291
+ console.log(` Type: ${updateType} update`)
2292
+
2293
+ // Show version position in the list
2294
+ const v1Index = availableVersions.indexOf(version1)
2295
+ const v2Index = availableVersions.indexOf(version2)
2296
+
2297
+ if (v1Index !== -1 && v2Index !== -1) {
2298
+ const versionsBetween = Math.abs(v2Index - v1Index) - 1
2299
+ console.log(` Gap: ${versionsBetween} versions between them`)
2300
+
2301
+ if (v2Index > v1Index) {
2302
+ console.log(` 📈 ${version2} is newer than ${version1}`)
2303
+ }
2304
+ else {
2305
+ console.log(` 📉 ${version2} is older than ${version1}`)
2306
+ }
2307
+ }
2308
+
2309
+ console.log(`\n💡 Use 'buddy versions ${packageName}' to see all available versions`)
2310
+ console.log(`💡 Use 'buddy info ${packageName}' for detailed package information`)
2311
+ }
2312
+ catch (error) {
2313
+ logger.error('Failed to compare versions:', error)
2314
+ process.exit(1)
2315
+ }
2316
+ })
2317
+
2318
+ cli
2319
+ .command('search <query>', 'Search for packages in the registry')
2320
+ .option('--verbose, -v', 'Enable verbose logging')
2321
+ .option('--limit <count>', 'Limit number of results', { default: '10' })
2322
+ .example('buddy search react')
2323
+ .example('buddy search "test framework" --limit 5')
2324
+ .action(async (query: string, options: CLIOptions & { limit?: string }) => {
2325
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2326
+
2327
+ try {
2328
+ const { spawn } = await import('node:child_process')
2329
+ const limit = Number.parseInt(options.limit || '10', 10)
2330
+
2331
+ console.log(`🔍 Searching for: "${query}"`)
2332
+ console.log(`📊 Showing top ${limit} results\n`)
2333
+
2334
+ // Check if npm is available first
2335
+ const checkNpm = spawn('which', ['npm'], { stdio: 'pipe' })
2336
+
2337
+ checkNpm.on('close', async (code) => {
2338
+ if (code !== 0) {
2339
+ // npm not available, use registry API search
2340
+ console.log('📡 Using npm registry API search...')
2341
+ try {
2342
+ const { RegistryClient } = await import('../src/registry/registry-client')
2343
+ const registryClient = new RegistryClient(process.cwd(), logger, undefined)
2344
+ const results = await registryClient.searchPackages(query, limit)
2345
+
2346
+ if (results.length === 0) {
2347
+ console.log(`❌ No packages found for "${query}"`)
2348
+ console.log('💡 Try different search terms or browse https://www.npmjs.com')
2349
+ return
2350
+ }
2351
+
2352
+ results.forEach((pkg, index) => {
2353
+ console.log(`${index + 1}. 📦 ${pkg.name}@${pkg.version}`)
2354
+ if (pkg.description) {
2355
+ console.log(` 📝 ${pkg.description}`)
2356
+ }
2357
+ if (pkg.keywords && pkg.keywords.length > 0) {
2358
+ console.log(` 🏷️ ${pkg.keywords.slice(0, 3).join(', ')}${pkg.keywords.length > 3 ? '...' : ''}`)
2359
+ }
2360
+ console.log()
2361
+ })
2362
+
2363
+ console.log(`✨ Use 'buddy info <package>' for detailed information`)
2364
+ }
2365
+ catch {
2366
+ console.log('❌ Registry API search failed')
2367
+ console.log('💡 Alternative search options:')
2368
+ console.log(` • Visit https://www.npmjs.com/search?q=${encodeURIComponent(query)}`)
2369
+ console.log(' • Use: bun add <package-name> to test if a package exists')
2370
+ console.log(' • Use: buddy exists <package-name> to check existence')
2371
+ }
2372
+ return
2373
+ }
2374
+
2375
+ // npm is available, proceed with search
2376
+ const child = spawn('npm', ['search', query, '--json'], {
2377
+ stdio: 'pipe',
2378
+ })
2379
+
2380
+ let output = ''
2381
+ child.stdout?.on('data', (data) => {
2382
+ output += data.toString()
2383
+ })
2384
+
2385
+ child.stderr?.on('data', (data) => {
2386
+ if (options.verbose) {
2387
+ logger.warn('npm search stderr:', data.toString())
2388
+ }
2389
+ })
2390
+
2391
+ child.on('close', (code) => {
2392
+ if (code === 0) {
2393
+ try {
2394
+ const results = JSON.parse(output)
2395
+ const limitedResults = results.slice(0, limit)
2396
+
2397
+ if (limitedResults.length === 0) {
2398
+ console.log(`❌ No packages found for "${query}"`)
2399
+ console.log('💡 Try different search terms or browse https://www.npmjs.com')
2400
+ return
2401
+ }
2402
+
2403
+ limitedResults.forEach((pkg: any, index: number) => {
2404
+ console.log(`${index + 1}. 📦 ${pkg.name}@${pkg.version}`)
2405
+ if (pkg.description) {
2406
+ console.log(` 📝 ${pkg.description}`)
2407
+ }
2408
+ if (pkg.keywords && pkg.keywords.length > 0) {
2409
+ console.log(` 🏷️ ${pkg.keywords.slice(0, 3).join(', ')}${pkg.keywords.length > 3 ? '...' : ''}`)
2410
+ }
2411
+ console.log()
2412
+ })
2413
+
2414
+ console.log(`✨ Use 'buddy info <package>' for detailed information`)
2415
+ }
2416
+ catch (error) {
2417
+ logger.error('Failed to parse search results:', error)
2418
+ console.log(`💡 Try searching at https://www.npmjs.com/search?q=${encodeURIComponent(query)}`)
2419
+ }
2420
+ }
2421
+ else {
2422
+ console.log('❌ Search failed')
2423
+ console.log(`💡 Try searching at https://www.npmjs.com/search?q=${encodeURIComponent(query)}`)
2424
+ }
2425
+ })
2426
+ })
2427
+ }
2428
+ catch (error) {
2429
+ logger.error('Failed to search packages:', error)
2430
+ console.log(`💡 Try searching at https://www.npmjs.com/search?q=${encodeURIComponent(query)}`)
2431
+ }
2432
+ })
2433
+
2434
+ cli
2435
+ .command('cleanup', 'Clean up stale buddy branches that don\'t have associated open PRs')
2436
+ .option('--verbose, -v', 'Enable verbose logging')
2437
+ .option('--dry-run', 'Show what would be deleted without actually deleting')
2438
+ .option('--days <number>', 'Delete branches older than N days (default: 7)', { default: '7' })
2439
+ .option('--force', 'Force cleanup without confirmation prompt')
2440
+ .example('buddy cleanup')
2441
+ .example('buddy cleanup --dry-run')
2442
+ .example('buddy cleanup --days 14')
2443
+ .example('buddy cleanup --force')
2444
+ .action(async (options: CLIOptions & { dryRun?: boolean, days?: string, force?: boolean }) => {
2445
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2446
+ const config = await resolveConfig(options.config)
2447
+
2448
+ try {
2449
+ logger.info('🧹 Starting buddy branch cleanup...')
2450
+
2451
+ // Check if repository is configured
2452
+ if (!config.repository) {
2453
+ logger.error('❌ Repository configuration required for branch cleanup')
2454
+ logger.info('Configure repository.provider, repository.owner, repository.name in buddy.config.ts')
2455
+ process.exit(1)
2456
+ }
2457
+
2458
+ const gitProvider = await providerFor(config, 'branch operations', logger)
2459
+
2460
+ const days = Number.parseInt(options.days || '7', 10)
2461
+ if (Number.isNaN(days) || days < 1) {
2462
+ logger.error('❌ Invalid days value. Must be a positive number.')
2463
+ process.exit(1)
2464
+ }
2465
+
2466
+ logger.info(`🔍 Looking for buddy branches older than ${days} days...`)
2467
+
2468
+ // Get all orphaned branches
2469
+ assertSupports(gitProvider, 'branchHousekeeping', 'getOrphanedBuddyBranches', 'branch cleanup')
2470
+ const orphanedBranches = await gitProvider.getOrphanedBuddyBranches()
2471
+ const cutoffDate = new Date()
2472
+ cutoffDate.setDate(cutoffDate.getDate() - days)
2473
+ const staleBranches = orphanedBranches.filter(branch => branch.lastCommitDate < cutoffDate)
2474
+
2475
+ if (staleBranches.length === 0) {
2476
+ logger.success('✅ No stale branches found!')
2477
+ logger.info(`📊 Total buddy branches: ${orphanedBranches.length}`)
2478
+ logger.info(`📊 Stale branches (>${days} days): 0`)
2479
+ return
2480
+ }
2481
+
2482
+ logger.info(`📊 Found ${staleBranches.length} stale branches to clean up:`)
2483
+ staleBranches.forEach((branch) => {
2484
+ const daysOld = Math.floor((Date.now() - branch.lastCommitDate.getTime()) / (1000 * 60 * 60 * 24))
2485
+ logger.info(` - ${branch.name} (${daysOld} days old)`)
2486
+ })
2487
+
2488
+ if (options.dryRun) {
2489
+ logger.info('\n🔍 [DRY RUN] These branches would be deleted')
2490
+ logger.info('💡 Run without --dry-run to actually delete them')
2491
+ return
2492
+ }
2493
+
2494
+ // Confirmation prompt (unless --force is used)
2495
+ if (!options.force) {
2496
+ const response = await prompts({
2497
+ type: 'confirm',
2498
+ name: 'confirmed',
2499
+ message: `Are you sure you want to delete ${staleBranches.length} stale branches?`,
2500
+ initial: false,
2501
+ })
2502
+
2503
+ if (!response.confirmed) {
2504
+ logger.info('❌ Cleanup cancelled')
2505
+ return
2506
+ }
2507
+ }
2508
+
2509
+ // Perform cleanup
2510
+ assertSupports(gitProvider, 'branchHousekeeping', 'cleanupStaleBranches', 'branch cleanup')
2511
+ const result = await gitProvider.cleanupStaleBranches(days, false)
2512
+
2513
+ if (result.deleted.length > 0) {
2514
+ logger.success(`✅ Successfully deleted ${result.deleted.length} stale branches`)
2515
+ }
2516
+
2517
+ if (result.failed.length > 0) {
2518
+ logger.warn(`⚠️ Failed to delete ${result.failed.length} branches`)
2519
+ result.failed.forEach(branch => logger.warn(` - ${branch}`))
2520
+ }
2521
+
2522
+ logger.info(`\n📊 Cleanup Summary:`)
2523
+ logger.info(` ✅ Deleted: ${result.deleted.length}`)
2524
+ logger.info(` ❌ Failed: ${result.failed.length}`)
2525
+ logger.info(` 📊 Total processed: ${staleBranches.length}`)
2526
+ }
2527
+ catch (error) {
2528
+ logger.error('Branch cleanup failed:', error)
2529
+ process.exit(1)
2530
+ }
2531
+ })
2532
+
2533
+ cli
2534
+ .command('list-branches', 'List all buddy branches and their status')
2535
+ .option('--verbose, -v', 'Enable verbose logging')
2536
+ .option('--orphaned-only', 'Show only branches without associated open PRs')
2537
+ .option('--stale-only', 'Show only stale branches (older than 7 days)')
2538
+ .option('--days <number>', 'Define stale threshold in days (default: 7)', { default: '7' })
2539
+ .example('buddy list-branches')
2540
+ .example('buddy list-branches --orphaned-only')
2541
+ .example('buddy list-branches --stale-only --days 14')
2542
+ .action(async (options: CLIOptions & { orphanedOnly?: boolean, staleOnly?: boolean, days?: string }) => {
2543
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2544
+ const config = await resolveConfig(options.config)
2545
+
2546
+ try {
2547
+ logger.info('📋 Listing buddy branches...')
2548
+
2549
+ // Check if repository is configured
2550
+ if (!config.repository) {
2551
+ logger.error('❌ Repository configuration required for branch listing')
2552
+ logger.info('Configure repository.provider, repository.owner, repository.name in buddy.config.ts')
2553
+ process.exit(1)
2554
+ }
2555
+
2556
+ const gitProvider = await providerFor(config, 'branch operations', logger)
2557
+
2558
+ const days = Number.parseInt(options.days || '7', 10)
2559
+ const cutoffDate = new Date()
2560
+ cutoffDate.setDate(cutoffDate.getDate() - days)
2561
+
2562
+ // Get all branches and PRs
2563
+ assertSupports(gitProvider, 'branchHousekeeping', 'getBuddyBranches', 'branch listing')
2564
+ const [allBuddyBranches, openPRs] = await Promise.all([
2565
+ gitProvider.getBuddyBranches(),
2566
+ gitProvider.getPullRequests('open'),
2567
+ ])
2568
+
2569
+ const prBranches = new Set(openPRs.map(pr => pr.head))
2570
+
2571
+ // Filter branches based on options
2572
+ let branches = allBuddyBranches
2573
+ if (options.orphanedOnly) {
2574
+ branches = branches.filter(branch => !prBranches.has(branch.name))
2575
+ }
2576
+ if (options.staleOnly) {
2577
+ branches = branches.filter(branch => branch.lastCommitDate < cutoffDate && !prBranches.has(branch.name))
2578
+ }
2579
+
2580
+ if (branches.length === 0) {
2581
+ if (options.orphanedOnly && options.staleOnly) {
2582
+ logger.success('✅ No stale orphaned branches found!')
2583
+ }
2584
+ else if (options.orphanedOnly) {
2585
+ logger.success('✅ No orphaned branches found!')
2586
+ }
2587
+ else if (options.staleOnly) {
2588
+ logger.success('✅ No stale branches found!')
2589
+ }
2590
+ else {
2591
+ logger.info('📋 No buddy branches found')
2592
+ }
2593
+ return
2594
+ }
2595
+
2596
+ console.log(`\n📊 Found ${branches.length} buddy branch${branches.length !== 1 ? 'es' : ''}:\n`)
2597
+
2598
+ // Sort by last commit date (newest first)
2599
+ branches.sort((a, b) => b.lastCommitDate.getTime() - a.lastCommitDate.getTime())
2600
+
2601
+ branches.forEach((branch) => {
2602
+ const hasOpenPR = prBranches.has(branch.name)
2603
+ const daysOld = Math.floor((Date.now() - branch.lastCommitDate.getTime()) / (1000 * 60 * 60 * 24))
2604
+ const isStale = branch.lastCommitDate < cutoffDate
2605
+
2606
+ const status = hasOpenPR ? '🔴 Open PR' : (isStale ? '🟡 Stale' : '🟢 Recent')
2607
+ const shortSha = branch.sha.substring(0, 7)
2608
+
2609
+ console.log(`${status} ${branch.name}`)
2610
+ console.log(` 📅 ${daysOld} days old | 📝 ${shortSha} | 🗓️ ${branch.lastCommitDate.toISOString().split('T')[0]}`)
2611
+ console.log()
2612
+ })
2613
+
2614
+ // Summary
2615
+ const orphanedCount = branches.filter(branch => !prBranches.has(branch.name)).length
2616
+ const staleCount = branches.filter(branch => branch.lastCommitDate < cutoffDate && !prBranches.has(branch.name)).length
2617
+
2618
+ console.log('📊 Summary:')
2619
+ console.log(` 📋 Total buddy branches: ${allBuddyBranches.length}`)
2620
+ console.log(` 🔴 With open PRs: ${allBuddyBranches.length - orphanedCount}`)
2621
+ console.log(` 🟡 Orphaned: ${orphanedCount}`)
2622
+ console.log(` 🗑️ Stale (>${days} days): ${staleCount}`)
2623
+
2624
+ if (staleCount > 0) {
2625
+ console.log(`\n💡 Run 'buddy cleanup' to clean up stale branches`)
2626
+ }
2627
+ }
2628
+ catch (error) {
2629
+ logger.error('Branch listing failed:', error)
2630
+ process.exit(1)
2631
+ }
2632
+ })
2633
+
2634
+ cli
2635
+ .command('open-settings', 'Open GitHub repository and organization settings pages')
2636
+ .option('--verbose, -v', 'Enable verbose logging')
2637
+ .example('buddy open-settings')
2638
+ .action(async (options: CLIOptions) => {
2639
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2640
+ const config = await resolveConfig(options.config)
2641
+
2642
+ try {
2643
+ const { exec } = await import('node:child_process')
2644
+ const { promisify } = await import('node:util')
2645
+ const execAsync = promisify(exec)
2646
+
2647
+ // Try to get repository info from config
2648
+ let owner = config.repository?.owner
2649
+ let name = config.repository?.name
2650
+
2651
+ // If not in config, try to detect from git remote
2652
+ if (!owner || !name) {
2653
+ try {
2654
+ const { stdout } = await execAsync('git remote get-url origin')
2655
+ const remoteUrl = stdout.trim()
2656
+
2657
+ // Parse GitHub URL (supports both HTTPS and SSH)
2658
+ const match = remoteUrl.match(/github\.com[/:]([\w-]+)\/([\w-]+)(?:\.git)?/)
2659
+ if (match) {
2660
+ owner = match[1]
2661
+ name = match[2]
2662
+ logger.info(`📡 Detected repository: ${owner}/${name}`)
2663
+ }
2664
+ }
2665
+ catch {
2666
+ // Ignore git errors
2667
+ }
2668
+ }
2669
+
2670
+ if (!owner || !name) {
2671
+ logger.warn('⚠️ Could not determine repository information.')
2672
+ logger.info('💡 Please configure repository settings in buddy.config.ts or run from a Git repository.')
2673
+ logger.info('\nFor manual setup, visit:')
2674
+ logger.info('🔗 Repository settings: https://github.com/YOUR_ORG/YOUR_REPO/settings/actions')
2675
+ logger.info('🔗 Organization settings: https://github.com/organizations/YOUR_ORG/settings/actions')
2676
+ return
2677
+ }
2678
+
2679
+ // Open repository settings page
2680
+ const repoUrl = `https://github.com/${owner}/${name}/settings/actions`
2681
+ const orgUrl = `https://github.com/organizations/${owner}/settings/actions`
2682
+
2683
+ logger.info('🔧 Opening GitHub Actions settings pages...')
2684
+ logger.info(`📦 Repository: ${owner}/${name}`)
2685
+
2686
+ // Function to open URL cross-platform
2687
+ const openUrl = async (url: string, description: string) => {
2688
+ try {
2689
+ let command: string
2690
+
2691
+ switch (process.platform) {
2692
+ case 'darwin': // macOS
2693
+ command = `open "${url}"`
2694
+ break
2695
+ case 'win32': // Windows
2696
+ command = `start "" "${url}"`
2697
+ break
2698
+ default: // Linux and others
2699
+ command = `xdg-open "${url}"`
2700
+ }
2701
+
2702
+ await execAsync(command)
2703
+ logger.success(`✅ Opened ${description}: ${url}`)
2704
+ }
2705
+ catch {
2706
+ logger.warn(`⚠️ Could not auto-open ${description}. Please visit manually:`)
2707
+ logger.info(`🔗 ${url}`)
2708
+ }
2709
+ }
2710
+
2711
+ // Open repository settings
2712
+ await openUrl(repoUrl, 'repository settings')
2713
+
2714
+ // Also try to open organization settings (may fail if not an org)
2715
+ setTimeout(async () => {
2716
+ logger.info('\n🏢 Attempting to open organization settings...')
2717
+ await openUrl(orgUrl, 'organization settings')
2718
+
2719
+ logger.info('\n📋 Required Settings:')
2720
+ logger.info(' 1. Under "Workflow permissions":')
2721
+ logger.info(' ✅ Select "Read and write permissions"')
2722
+ logger.info(' ✅ Check "Allow GitHub Actions to create and approve pull requests"')
2723
+ logger.info(' 2. Click "Save"')
2724
+ logger.info('\n💡 Note: Organization settings may override repository settings.')
2725
+ }, 1000) // Delay to avoid opening both simultaneously
2726
+ }
2727
+ catch (error) {
2728
+ logger.error('Failed to open settings:', error)
2729
+ logger.info('\n📋 Manual Setup:')
2730
+ logger.info('🔗 Repository: https://github.com/YOUR_ORG/YOUR_REPO/settings/actions')
2731
+ logger.info('🔗 Organization: https://github.com/organizations/YOUR_ORG/settings/actions')
2732
+ }
2733
+ })
2734
+
2735
+ cli
2736
+ .command('security [path]', '🛡 Static-analyse GitHub Actions workflows for supply-chain footguns')
2737
+ .option('-f, --format <format>', 'Reporter (pretty | json | github). Defaults to github on a runner, pretty otherwise.')
2738
+ .option('--ignore <ids>', 'Comma-separated rule ids to skip (e.g. missing-timeout,unpinned-action)')
2739
+ .option('--no-color', 'Disable ANSI colours in pretty output')
2740
+ .action(async (path: string | undefined, options: { format?: string, ignore?: string, color?: boolean }) => {
2741
+ const { audit } = await import('../src/security/engine')
2742
+ const { formatPretty } = await import('../src/security/reporters/pretty')
2743
+ const { formatJson } = await import('../src/security/reporters/json')
2744
+ const { formatGitHub } = await import('../src/security/reporters/github')
2745
+
2746
+ const ignore = options.ignore?.split(',').filter(Boolean) ?? []
2747
+ const result = await audit(path ?? '.', { ignore })
2748
+
2749
+ const format = options.format ?? (process.env.GITHUB_ACTIONS === 'true' ? 'github' : 'pretty')
2750
+ let output: string
2751
+ switch (format) {
2752
+ case 'json':
2753
+ output = formatJson(result)
2754
+ break
2755
+ case 'github':
2756
+ output = formatGitHub(result)
2757
+ break
2758
+ case 'pretty':
2759
+ output = formatPretty(result, { color: options.color !== false })
2760
+ break
2761
+ default:
2762
+ process.stderr.write(`Unknown --format ${format}. Use pretty | json | github.\n`)
2763
+ process.exit(2)
2764
+ return
2765
+ }
2766
+ if (output)
2767
+ process.stdout.write(`${output}\n`)
2768
+ process.exit(result.failed ? 1 : 0)
2769
+ })
2770
+
2771
+ cli
2772
+ .command('touch <pr-number>', 'Run a finishing touch ticked on a pull request, as a stacked PR')
2773
+ .option('--name <touch>', 'Run a specific touch rather than reading the checkboxes')
2774
+ .option('--test-command <command>', 'Command that verifies the change')
2775
+ .option('--dry-run', 'Report what would run without acting')
2776
+ .option('--verbose, -v', 'Enable verbose logging')
2777
+ .example('buddy touch 42')
2778
+ .example('buddy touch 42 --name unit-tests')
2779
+ .action(async (prNumber: string, options: CLIOptions & {
2780
+ name?: string
2781
+ testCommand?: string
2782
+ dryRun?: boolean
2783
+ }) => {
2784
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2785
+ const config = await resolveConfig(options.config)
2786
+
2787
+ try {
2788
+ const number = Number.parseInt(prNumber, 10)
2789
+ const provider = await providerFor(config, 'finishing touches', logger)
2790
+
2791
+ const prs = await provider.getPullRequests('open')
2792
+ const pullRequest = prs.find(candidate => candidate.number === number)
2793
+ if (!pullRequest) {
2794
+ logger.error(`❌ Pull request #${number} is not open`)
2795
+ process.exit(1)
2796
+ }
2797
+
2798
+ const { FINISHING_TOUCHES, getFinishingTouch, parseTouchSelections } = await import('../src/agent/tasks')
2799
+
2800
+ // The checkboxes are the request. A touch named on the command line is
2801
+ // the manual path, for a maintainer who did not want to tick a box.
2802
+ const selected = options.name
2803
+ ? [options.name]
2804
+ : parseTouchSelections(pullRequest.body)
2805
+
2806
+ if (selected.length === 0) {
2807
+ logger.info('ℹ️ No finishing touches are ticked on this pull request')
2808
+ return
2809
+ }
2810
+
2811
+ const { createAiClient } = await import('../src/ai')
2812
+ const ai = createAiClient(config, logger)
2813
+ if (!ai) {
2814
+ logger.error('❌ Finishing touches need an API key. See https://buddy.sh/ai/providers')
2815
+ process.exit(1)
2816
+ }
2817
+
2818
+ if (options.dryRun) {
2819
+ logger.info(`🔍 [DRY RUN] Would run: ${selected.join(', ')}`)
2820
+ return
2821
+ }
2822
+
2823
+ const { runStackedTouch } = await import('../src/agent/stacked')
2824
+
2825
+ for (const name of selected) {
2826
+ if (!FINISHING_TOUCHES[name]) {
2827
+ logger.warn(`⚠️ Unknown finishing touch '${name}', skipping`)
2828
+ continue
2829
+ }
2830
+
2831
+ const result = await runStackedTouch({
2832
+ provider,
2833
+ pullRequest,
2834
+ touch: getFinishingTouch(name),
2835
+ ai,
2836
+ workspace: process.cwd(),
2837
+ ...(options.testCommand ? { testCommand: options.testCommand.split(' ') } : {}),
2838
+ logger,
2839
+ })
2840
+
2841
+ await provider.createComment(number, result.comment)
2842
+ logger.success(`✅ ${name}: ${result.mode}`)
2843
+ }
2844
+
2845
+ // Cleared afterwards so the next poll does not run them again — the same
2846
+ // reason the dashboard unchecks its own boxes.
2847
+ const cleared = pullRequest.body.replace(
2848
+ /^(\s*-\s*)\[[xX]\](\s*<!--\s*buddy:touch=)/gm,
2849
+ '$1[ ]$2',
2850
+ )
2851
+
2852
+ if (cleared !== pullRequest.body)
2853
+ await provider.updatePullRequest(number, { body: cleared })
2854
+ }
2855
+ catch (error) {
2856
+ logger.error('Finishing touch failed:', error)
2857
+ process.exit(1)
2858
+ }
2859
+ })
2860
+
2861
+ cli
2862
+ .command('handle-issue', 'Post Buddy quick-links on a new issue, or run a ticked action')
2863
+ .option('--payload <path>', 'Path to the event payload (default: GITHUB_EVENT_PATH)')
2864
+ .option('--issue <number>', 'Act on an issue directly rather than reading an event')
2865
+ .option('--dry-run', 'Report what would happen without acting')
2866
+ .option('--verbose, -v', 'Enable verbose logging')
2867
+ .example('buddy handle-issue')
2868
+ .action(async (options: CLIOptions & {
2869
+ payload?: string
2870
+ issue?: string
2871
+ dryRun?: boolean
2872
+ }) => {
2873
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2874
+ const config = await resolveConfig(options.config)
2875
+
2876
+ if (config.issues?.quickLinks !== true) {
2877
+ logger.info('ℹ️ Issue quick-links are off (set issues.quickLinks to enable)')
2878
+ return
2879
+ }
2880
+
2881
+ try {
2882
+ let issueNumber = options.issue ? Number.parseInt(options.issue, 10) : Number.NaN
2883
+
2884
+ if (Number.isNaN(issueNumber)) {
2885
+ const payloadPath = options.payload || process.env.GITHUB_EVENT_PATH
2886
+ if (!payloadPath) {
2887
+ logger.error('❌ No event payload. Pass --issue or --payload, or run inside CI.')
2888
+ process.exit(1)
2889
+ }
2890
+
2891
+ const event = await Bun.file(payloadPath).json()
2892
+ issueNumber = Number(event?.issue?.number)
2893
+
2894
+ if (Number.isNaN(issueNumber)) {
2895
+ logger.info('ℹ️ Event carries no issue; nothing to do')
2896
+ return
2897
+ }
2898
+ }
2899
+
2900
+ const provider = await providerFor(config, 'issue quick-links', logger)
2901
+ const issues = await provider.getIssues('open')
2902
+ const issue = issues.find(candidate => candidate.number === issueNumber)
2903
+
2904
+ if (!issue) {
2905
+ logger.info(`ℹ️ Issue #${issueNumber} is not open`)
2906
+ return
2907
+ }
2908
+
2909
+ const {
2910
+ clearQuickSelection,
2911
+ parseQuickSelection,
2912
+ QUICK_LINKS_MARKER,
2913
+ renderQuickLinks,
2914
+ } = await import('../src/issues')
2915
+
2916
+ const selection = parseQuickSelection(issue.body)
2917
+
2918
+ // A ticked box is a request; an issue with no comment yet gets the offer.
2919
+ if (selection.actions.length > 0) {
2920
+ logger.info(`🤖 Requested: ${selection.actions.join(', ')}`)
2921
+
2922
+ if (options.dryRun)
2923
+ return
2924
+
2925
+ const { createAiClient } = await import('../src/ai')
2926
+ const ai = createAiClient(config, logger)
2927
+
2928
+ if (!ai) {
2929
+ await provider.createComment(issueNumber, 'Buddy needs an AI provider configured to act on this. See https://buddy.sh/ai/providers')
2930
+ return
2931
+ }
2932
+
2933
+ // Cleared first, so a long-running action cannot be triggered twice by
2934
+ // a second poll arriving before the first finishes.
2935
+ await provider.updateIssue(issueNumber, { body: clearQuickSelection(issue.body) })
2936
+
2937
+ for (const action of selection.actions) {
2938
+ const { getFinishingTouch, runAgent } = await import('../src/agent')
2939
+ const touch = getFinishingTouch(action === 'build' ? 'autofix' : 'plan')
2940
+
2941
+ const result = await runAgent(ai, {
2942
+ mode: touch.mode,
2943
+ task: `${touch.buildTask({ summary: issue.title, files: [] })}\n\nIssue:\n${issue.body}`,
2944
+ context: { workspace: process.cwd(), baseBranch: config.repository?.baseBranch ?? 'main' },
2945
+ logger,
2946
+ })
2947
+
2948
+ await provider.createComment(issueNumber, result.output)
2949
+ logger.success(`✅ Ran ${action}`)
2950
+ }
2951
+
2952
+ return
2953
+ }
2954
+
2955
+ if (issue.body.includes(QUICK_LINKS_MARKER)) {
2956
+ logger.debug('Quick-links already posted on this issue')
2957
+ return
2958
+ }
2959
+
2960
+ // Dependency context is added only when the issue names a package this
2961
+ // repository actually depends on.
2962
+ const packages = config.issues?.dependencyContext
2963
+ ? await collectPackageContext(config, logger)
2964
+ : []
2965
+
2966
+ const comment = renderQuickLinks({ body: issue.body, packages })
2967
+
2968
+ if (options.dryRun) {
2969
+ logger.info(comment)
2970
+ return
2971
+ }
2972
+
2973
+ await provider.createComment(issueNumber, comment)
2974
+ logger.success(`✅ Posted quick-links on #${issueNumber}`)
2975
+ }
2976
+ catch (error) {
2977
+ logger.error('handle-issue failed:', error)
2978
+ process.exit(1)
2979
+ }
2980
+ })
2981
+
2982
+ cli
2983
+ .command('gate <pr-number>', 'Run pre-merge gates on a pull request and publish the result')
2984
+ .option('--dry-run', 'Print the result instead of publishing a check run')
2985
+ .option('--verbose, -v', 'Enable verbose logging')
2986
+ .example('buddy gate 42')
2987
+ .action(async (prNumber: string, options: CLIOptions & { dryRun?: boolean }) => {
2988
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
2989
+ const config = await resolveConfig(options.config)
2990
+
2991
+ try {
2992
+ const number = Number.parseInt(prNumber, 10)
2993
+ if (Number.isNaN(number)) {
2994
+ logger.error('❌ Invalid PR number')
2995
+ process.exit(1)
2996
+ }
2997
+
2998
+ const provider = await providerFor(config, 'running gates', logger)
2999
+ const { findLinkedIssues, runAiGates, runGates, summarizeGates } = await import('../src/gates')
3000
+ const { parseManifest } = await import('../src/pr/pr-manifest')
3001
+
3002
+ const prs = await provider.getPullRequests('open')
3003
+ const pr = prs.find(candidate => candidate.number === number)
3004
+ if (!pr) {
3005
+ logger.error(`❌ Pull request #${number} is not open`)
3006
+ process.exit(1)
3007
+ }
3008
+
3009
+ const gates = config.gates ?? {}
3010
+ const manifest = parseManifest(pr.body)
3011
+
3012
+ // The manifest is what the dependency gate reads: without it the gate
3013
+ // evaluates an empty list and passes every pull request.
3014
+ const { manifestUpdates: readManifest } = await import('../src/pr/pr-manifest')
3015
+ const dependencies = manifest
3016
+ ? await Promise.all(readManifest(manifest).map(async (update) => {
3017
+ const base = { name: update.name, version: update.newVersion }
3018
+
3019
+ // Only base images have a support window to check, and only when
3020
+ // the gate would act on it.
3021
+ if (gates.dependencyGate?.blockEol === false)
3022
+ return base
3023
+
3024
+ const entry = manifest.updates.find(candidate => candidate.name === update.name)
3025
+ if (entry?.dependencyType !== 'docker-image')
3026
+ return base
3027
+
3028
+ const { checkEol, describeEol } = await import('../src/registry/eol')
3029
+ const status = await checkEol(update.name, update.newVersion, { logger })
3030
+ const note = describeEol(status)
3031
+
3032
+ return status?.eol && note ? { ...base, eol: note } : base
3033
+ }))
3034
+ : []
3035
+
3036
+ const deterministic = runGates(
3037
+ { title: pr.title, body: pr.body, manifest, dependencies },
3038
+ {
3039
+ ...(gates.titleFormat ? { titleFormat: gates.titleFormat } : {}),
3040
+ ...(gates.description ? { description: gates.description } : {}),
3041
+ ...(gates.dependencyGate ? { dependencyGate: gates.dependencyGate } : {}),
3042
+ },
3043
+ )
3044
+
3045
+ // The linked issues are fetched so the assessment reads what the issue
3046
+ // actually says rather than only its number.
3047
+ const linkedNumbers = findLinkedIssues(pr.body ?? '')
3048
+ const allIssues = linkedNumbers.length > 0 ? await provider.getIssues('all') : []
3049
+ const linkedIssues = linkedNumbers
3050
+ .map(issueNumber => allIssues.find(issue => issue.number === issueNumber))
3051
+ .filter((issue): issue is NonNullable<typeof issue> => Boolean(issue))
3052
+ .map(issue => ({ number: issue.number, title: issue.title, body: issue.body }))
3053
+
3054
+ const { createAiClient } = await import('../src/ai')
3055
+
3056
+ const aiResults = await runAiGates(
3057
+ createAiClient(config, logger),
3058
+ {
3059
+ title: pr.title,
3060
+ body: pr.body,
3061
+ diff: await provider.getPullRequestDiff(number),
3062
+ linkedIssues,
3063
+ },
3064
+ {
3065
+ ...(gates.linkedIssue ? { linkedIssue: gates.linkedIssue } : {}),
3066
+ ...(gates.custom ? { custom: gates.custom } : {}),
3067
+ },
3068
+ logger,
3069
+ )
3070
+
3071
+ const results = [...deterministic, ...aiResults]
3072
+ const summary = summarizeGates(results)
3073
+
3074
+ for (const result of results)
3075
+ logger.info(`${result.passed ? '✅' : result.mode === 'error' ? '❌' : '⚠️'} ${result.name}: ${result.summary}`)
3076
+
3077
+ const blocking = summary.conclusion === 'failure'
3078
+
3079
+ if (options.dryRun || !supports(provider, 'checkRuns', 'createCheckRun')) {
3080
+ logger.info(summary.summary)
3081
+ // Exit code carries the verdict when there is no check run to carry it.
3082
+ if (blocking)
3083
+ process.exit(1)
3084
+ return
3085
+ }
3086
+
3087
+ await provider.createCheckRun('buddy/gates', await provider.getPullRequestHeadSha(number), summary)
3088
+
3089
+ if (blocking)
3090
+ process.exit(1)
3091
+ }
3092
+ catch (error) {
3093
+ logger.error('Gate run failed:', error)
3094
+ process.exit(1)
3095
+ }
3096
+ })
3097
+
3098
+ cli
3099
+ .command('post-merge <pr-number>', 'Run post-merge actions for a merged pull request')
3100
+ .option('--verbose, -v', 'Enable verbose logging')
3101
+ .example('buddy post-merge 42')
3102
+ .action(async (prNumber: string, options: CLIOptions) => {
3103
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
3104
+ const config = await resolveConfig(options.config)
3105
+
3106
+ try {
3107
+ const number = Number.parseInt(prNumber, 10)
3108
+ const provider = await providerFor(config, 'post-merge actions', logger)
3109
+
3110
+ const prs = await provider.getPullRequests('all')
3111
+ const pr = prs.find(candidate => candidate.number === number)
3112
+ if (!pr) {
3113
+ logger.error(`❌ Pull request #${number} not found`)
3114
+ process.exit(1)
3115
+ }
3116
+
3117
+ // Guarded rather than assumed: `pull_request: [closed]` fires for
3118
+ // abandoned pull requests too, and these actions must not run for one.
3119
+ if (pr.state !== 'merged') {
3120
+ logger.info(`ℹ️ PR #${number} was closed without merging; nothing to do`)
3121
+ return
3122
+ }
3123
+
3124
+ const { runPostMerge } = await import('../src/gates')
3125
+ const outcome = await runPostMerge(provider, pr, config.gates?.postMerge ?? {}, {
3126
+ baseBranch: config.repository?.baseBranch ?? pr.base,
3127
+ logger,
3128
+ })
3129
+
3130
+ for (const action of outcome.performed)
3131
+ logger.success(`✅ ${action}`)
3132
+ for (const entry of outcome.skipped)
3133
+ logger.info(`⏭️ ${entry.action}: ${entry.reason}`)
3134
+ }
3135
+ catch (error) {
3136
+ logger.error('Post-merge actions failed:', error)
3137
+ process.exit(1)
3138
+ }
3139
+ })
3140
+
3141
+ cli
3142
+ .command('report', 'Generate a dependency-health and activity report')
3143
+ .option('--period <window>', 'Reporting window: 7d|30d|90d', { default: '30d' })
3144
+ .option('--format <name>', 'Output format: markdown|json', { default: 'markdown' })
3145
+ .option('--prompt <focus>', 'Focus for the AI narrative, when a provider is configured')
3146
+ .option('--publish', 'Publish to the repository\'s report issue')
3147
+ .option('--verbose, -v', 'Enable verbose logging')
3148
+ .example('buddy report --period 7d')
3149
+ .example('buddy report --prompt "focus on security posture" --publish')
3150
+ .action(async (options: CLIOptions & {
3151
+ period?: string
3152
+ format?: string
3153
+ prompt?: string
3154
+ publish?: boolean
3155
+ }) => {
3156
+ const quiet = options.format === 'json'
3157
+ const logger = options.verbose ? Logger.verbose() : quiet ? Logger.silent() : Logger.quiet()
3158
+ const config = await resolveConfig(options.config)
3159
+
3160
+ try {
3161
+ const {
3162
+ appendHistory,
3163
+ computeDeltas,
3164
+ computeMetrics,
3165
+ findPrevious,
3166
+ HISTORY_PATH,
3167
+ loadHistory,
3168
+ REPORT_MARKER,
3169
+ REPORT_PERIODS,
3170
+ renderReport,
3171
+ withNarrative,
3172
+ } = await import('../src/reports')
3173
+
3174
+ const period = (options.period ?? '30d') as '7d' | '30d' | '90d'
3175
+ if (!REPORT_PERIODS.includes(period)) {
3176
+ logger.error(`❌ Unknown period '${period}'. Expected one of ${REPORT_PERIODS.join(', ')}.`)
3177
+ process.exit(1)
3178
+ }
3179
+
3180
+ const provider = await providerFor(config, 'reporting', logger)
3181
+ const buddy = new Buddy(config, process.cwd())
3182
+
3183
+ const { PackageScanner } = await import('../src/scanner/package-scanner')
3184
+ const scanner = new PackageScanner(process.cwd(), logger, config.packages?.ignorePaths)
3185
+
3186
+ const [scan, pullRequests, packageFiles] = await Promise.all([
3187
+ buddy.scanForUpdates(),
3188
+ provider.getPullRequests('all'),
3189
+ scanner.scanProject(),
3190
+ ])
3191
+
3192
+ // Every declared dependency, not only the outdated ones — a health
3193
+ // percentage against the outdated set alone would always be 100%.
3194
+ const { ecosystemOf } = await import('../src/rules/engine')
3195
+ const byEcosystem: Record<string, number> = {}
3196
+ for (const file of packageFiles) {
3197
+ for (const dependency of file.dependencies) {
3198
+ const ecosystem = ecosystemOf({
3199
+ name: dependency.name,
3200
+ currentVersion: dependency.currentVersion,
3201
+ newVersion: dependency.currentVersion,
3202
+ updateType: 'patch',
3203
+ dependencyType: dependency.type,
3204
+ file: file.path,
3205
+ })
3206
+ byEcosystem[ecosystem] = (byEcosystem[ecosystem] ?? 0) + 1
3207
+ }
3208
+ }
3209
+
3210
+ const { DeprecatedDependenciesChecker } = await import('../src/services/deprecated-dependencies-checker')
3211
+ const deprecated = await new DeprecatedDependenciesChecker()
3212
+ .checkDeprecatedDependencies(packageFiles)
3213
+ .catch(() => [])
3214
+
3215
+ const metrics = computeMetrics({
3216
+ period,
3217
+ now: new Date(),
3218
+ pullRequests,
3219
+ updates: scan.updates,
3220
+ dependenciesByEcosystem: byEcosystem,
3221
+ deprecated: deprecated.length,
3222
+ })
3223
+
3224
+ const baseRef = config.repository?.baseBranch || 'main'
3225
+ const history = await loadHistory(provider, baseRef, logger)
3226
+ const deltas = computeDeltas(metrics, findPrevious(history, period))
3227
+
3228
+ if (options.format === 'json') {
3229
+ process.stdout.write(`${JSON.stringify({ metrics, deltas }, null, 2)}\n`)
3230
+ return
3231
+ }
3232
+
3233
+ const { createAiClient } = await import('../src/ai')
3234
+ const report = await withNarrative(
3235
+ renderReport(metrics, deltas),
3236
+ metrics,
3237
+ createAiClient(config, logger),
3238
+ options.prompt ?? config.reports?.prompt,
3239
+ logger,
3240
+ )
3241
+
3242
+ if (!options.publish) {
3243
+ process.stdout.write(`${report}\n`)
3244
+ return
3245
+ }
3246
+
3247
+ // Updated in place rather than opened fresh each period, so the issue is
3248
+ // one readable trend rather than a stream of near-identical issues.
3249
+ const issues = await provider.getIssues('open')
3250
+ const existing = issues.find(issue => issue.body.includes(REPORT_MARKER))
3251
+
3252
+ const title = config.reports?.title ?? 'Dependency Report'
3253
+ const labels = config.reports?.labels ?? ['dependencies', 'report']
3254
+
3255
+ const issue = existing
3256
+ ? await provider.updateIssue(existing.number, { title, body: report, labels })
3257
+ : await provider.createIssue({ title, body: report, labels })
3258
+
3259
+ logger.success(`✅ Report published: ${issue.url}`)
3260
+
3261
+ // History is committed so the next run has something to compare against.
3262
+ await provider.commitChanges(
3263
+ baseRef,
3264
+ 'chore(reports): record dependency metrics snapshot',
3265
+ [{ path: HISTORY_PATH, content: appendHistory(history, metrics), type: history.length > 0 ? 'update' : 'create' }],
3266
+ baseRef,
3267
+ )
3268
+ }
3269
+ catch (error) {
3270
+ logger.error('Report failed:', error)
3271
+ process.exit(1)
3272
+ }
3273
+ })
3274
+
3275
+ cli
3276
+ .command('doctor', 'Diagnose this environment: credentials, git state and analyzer tooling')
3277
+ .option('--verbose, -v', 'Enable verbose logging')
3278
+ .example('buddy doctor')
3279
+ .action(async (options: CLIOptions) => {
3280
+ const logger = options.verbose ? Logger.verbose() : Logger.quiet()
3281
+
3282
+ // A broken config is exactly what `doctor` exists to report, so loading it
3283
+ // must not be the thing that stops the diagnosis from running.
3284
+ const config = await resolveConfig(options.config).catch((error) => {
3285
+ logger.warn(`⚠️ Could not load configuration: ${formatError(error)}`)
3286
+ return {} as BuddyConfig
3287
+ })
3288
+
3289
+ const { diagnose, renderDoctorReport } = await import('../src/doctor')
3290
+ const report = await diagnose(config)
3291
+
3292
+ process.stdout.write(renderDoctorReport(report))
3293
+
3294
+ if (!report.healthy)
3295
+ process.exit(1)
3296
+ })
3297
+
3298
+ cli
3299
+ .command('run', 'Run a prompt headlessly, with optional schema-validated output')
3300
+ .option('--prompt <text>', 'The prompt to run')
3301
+ .option('--prompt-file <path>', 'Read the prompt from a file')
3302
+ .option('--output-schema <json>', 'JSON Schema the output must satisfy')
3303
+ .option('--output-schema-file <path>', 'Read the schema from a file')
3304
+ .option('--model <name>', 'Model override')
3305
+ .option('--retries <n>', 'Schema retries before failing', { default: '2' })
3306
+ .option('--verbose, -v', 'Enable verbose logging')
3307
+ .example('buddy run --prompt "Summarize this week\'s dependency updates"')
3308
+ .example('buddy run --prompt-file p.txt --output-schema \'{"type":"object"}\'')
3309
+ .action(async (options: CLIOptions & {
3310
+ prompt?: string
3311
+ promptFile?: string
3312
+ outputSchema?: string
3313
+ outputSchemaFile?: string
3314
+ model?: string
3315
+ retries?: string
3316
+ }) => {
3317
+ // stdout carries the result, which a pipeline step parses; diagnostics go
3318
+ // to stderr via the logger so they cannot corrupt it.
3319
+ const logger = options.verbose ? Logger.verbose() : Logger.silent()
3320
+ const config = await resolveConfig(options.config)
3321
+
3322
+ try {
3323
+ const prompt = options.promptFile
3324
+ ? await Bun.file(options.promptFile).text()
3325
+ : options.prompt
3326
+
3327
+ if (!prompt?.trim()) {
3328
+ process.stderr.write('❌ Provide --prompt or --prompt-file\n')
3329
+ process.exit(1)
3330
+ }
3331
+
3332
+ const schemaText = options.outputSchemaFile
3333
+ ? await Bun.file(options.outputSchemaFile).text()
3334
+ : options.outputSchema
3335
+
3336
+ let schema: Record<string, unknown> | undefined
3337
+ if (schemaText) {
3338
+ try {
3339
+ schema = JSON.parse(schemaText)
3340
+ }
3341
+ catch (error) {
3342
+ process.stderr.write(`❌ --output-schema is not valid JSON: ${formatError(error)}\n`)
3343
+ process.exit(1)
3344
+ }
3345
+ }
3346
+
3347
+ const { createAiClient } = await import('../src/ai')
3348
+ const ai = createAiClient(
3349
+ options.model ? { ...config, ai: { ...config.ai, model: options.model } } : config,
3350
+ logger,
3351
+ )
3352
+
3353
+ if (!ai) {
3354
+ process.stderr.write('❌ No AI provider configured. See https://buddy.sh/ai/providers\n')
3355
+ process.exit(1)
3356
+ }
3357
+
3358
+ const { publishOutput, runHeadless } = await import('../src/headless/run')
3359
+
3360
+ const outcome = await runHeadless({
3361
+ prompt,
3362
+ ai,
3363
+ ...(schema ? { schema } : {}),
3364
+ maxRetries: Number.parseInt(options.retries ?? '2', 10),
3365
+ logger,
3366
+ })
3367
+
3368
+ if (!outcome.valid) {
3369
+ // The contract a pipeline depends on: a nonconforming output fails the
3370
+ // step rather than emitting something shaped differently than promised.
3371
+ process.stderr.write(`❌ Output did not satisfy the schema after ${outcome.attempts} attempt(s):\n${outcome.error}\n`)
3372
+ process.exit(1)
3373
+ }
3374
+
3375
+ const wrote = await publishOutput(outcome.result, process.env.GITHUB_OUTPUT)
3376
+
3377
+ const serialized = typeof outcome.result === 'string'
3378
+ ? outcome.result
3379
+ : JSON.stringify(outcome.result, null, 2)
3380
+
3381
+ process.stdout.write(`${serialized}\n`)
3382
+
3383
+ if (wrote)
3384
+ logger.info('📤 Wrote `result` to $GITHUB_OUTPUT')
3385
+ }
3386
+ catch (error) {
3387
+ process.stderr.write(`❌ ${formatError(error)}\n`)
3388
+ process.exit(1)
3389
+ }
3390
+ })
3391
+
3392
+ cli.command('version', 'Show the version of Buddy').action(() => {
3393
+ console.log(version)
3394
+ })
3395
+
3396
+ // Available on every command: each action reads `options.config` and passes it
3397
+ // to resolveConfig, which bypasses discovery when a path is given.
3398
+ cli.option('--config <path>', 'Path to a buddy config file')
3399
+ cli.version(version)
3400
+ cli.help()
3401
+ cli.parse()