beta.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. #!/usr/bin/env bun
  2. import { $ } from "bun"
  3. import fs from "fs/promises"
  4. const model = "opencode/gpt-5.3-codex"
  5. interface PR {
  6. number: number
  7. title: string
  8. author: { login: string }
  9. labels: Array<{ name: string }>
  10. }
  11. interface FailedPR {
  12. number: number
  13. title: string
  14. reason: string
  15. }
  16. async function commentOnPR(prNumber: number, reason: string) {
  17. const body = `⚠️ **Blocking Beta Release**
  18. This PR cannot be merged into the beta branch due to: **${reason}**
  19. Please resolve this issue to include this PR in the next beta release.`
  20. try {
  21. await $`gh pr comment ${prNumber} --body ${body}`
  22. console.log(` Posted comment on PR #${prNumber}`)
  23. } catch (err) {
  24. console.log(` Failed to post comment on PR #${prNumber}: ${err}`)
  25. }
  26. }
  27. async function conflicts() {
  28. const out = await $`git diff --name-only --diff-filter=U`.text().catch(() => "")
  29. return out
  30. .split("\n")
  31. .map((x) => x.trim())
  32. .filter(Boolean)
  33. }
  34. async function cleanup() {
  35. try {
  36. await $`git merge --abort`
  37. } catch {}
  38. try {
  39. await $`git checkout -- .`
  40. } catch {}
  41. try {
  42. await $`git clean -fd`
  43. } catch {}
  44. }
  45. function lines(prs: PR[]) {
  46. return prs.map((x) => `- #${x.number}: ${x.title}`).join("\n") || "(none)"
  47. }
  48. async function typecheck() {
  49. console.log(" Running typecheck...")
  50. try {
  51. await $`bun typecheck`.cwd("packages/opencode")
  52. return true
  53. } catch (err) {
  54. console.log(`Typecheck failed: ${err}`)
  55. return false
  56. }
  57. }
  58. async function build() {
  59. console.log(" Running final build smoke check...")
  60. try {
  61. await $`./script/build.ts --single`.cwd("packages/opencode")
  62. return true
  63. } catch (err) {
  64. console.log(`Build failed: ${err}`)
  65. return false
  66. }
  67. }
  68. async function install() {
  69. console.log(" Regenerating bun.lock...")
  70. try {
  71. await fs.rm("bun.lock", { force: true })
  72. await $`bun install`
  73. await $`git add bun.lock`
  74. return true
  75. } catch (err) {
  76. console.log(`Install failed: ${err}`)
  77. return false
  78. }
  79. }
  80. async function fix(pr: PR, files: string[], prs: PR[], applied: number[], idx: number) {
  81. console.log(` Trying to auto-resolve ${files.length} conflict(s) with opencode...`)
  82. const done = lines(prs.filter((x) => applied.includes(x.number)))
  83. const next = lines(prs.slice(idx + 1))
  84. const prompt = [
  85. `Resolve the current git merge conflicts while merging PR #${pr.number} into the beta branch.`,
  86. `PR #${pr.number}: ${pr.title}`,
  87. `Start with these conflicted files: ${files.join(", ")}.`,
  88. `Merged PRs on HEAD:\n${done}`,
  89. `Pending PRs after this one (context only):\n${next}`,
  90. "IMPORTANT: The conflict resolution must be consistent with already-merged PRs.",
  91. "Pending PRs are context only; do not introduce their changes unless they are already present on HEAD.",
  92. "Prefer already-merged PRs over the base branch when resolving stacked conflicts.",
  93. "If bun.lock is conflicted, do not hand-merge it. Delete bun.lock and run bun install after the code conflicts are resolved.",
  94. "If a PR already deleted a file/directory, do not re-add it, instead apply changes in the new semantic location.",
  95. "If a PR already changed an import, keep that change.",
  96. "After resolving the conflicts, run `bun typecheck` in `packages/opencode`.",
  97. "If typecheck fails, you may also update any files reported by typecheck.",
  98. "Keep any non-conflict edits narrowly scoped to restoring a valid merged state for the current PR batch.",
  99. "Fix any merge-caused typecheck errors before finishing.",
  100. "Keep the merge in progress, do not abort the merge, and do not create a commit.",
  101. "When done, leave the working tree with no unmerged files and a passing typecheck.",
  102. ].join("\n")
  103. try {
  104. await $`opencode run -m ${model} ${prompt}`
  105. } catch (err) {
  106. console.log(` opencode failed: ${err}`)
  107. return false
  108. }
  109. const left = await conflicts()
  110. if (left.length > 0) {
  111. console.log(` Conflicts remain: ${left.join(", ")}`)
  112. return false
  113. }
  114. if (files.includes("bun.lock") && !(await install())) return false
  115. if (!(await typecheck())) return false
  116. console.log(" Conflicts resolved with opencode")
  117. return true
  118. }
  119. async function smoke(prs: PR[], applied: number[]) {
  120. console.log("\nRunning final smoke check with opencode...")
  121. const done = lines(prs.filter((x) => applied.includes(x.number)))
  122. const prompt = [
  123. "The beta merge batch is complete.",
  124. `Merged PRs on HEAD:\n${done}`,
  125. "Run `bun typecheck` in `packages/opencode`.",
  126. "Run `./script/build.ts --single` in `packages/opencode`.",
  127. "Fix any merge-caused issues until both commands pass.",
  128. "Do not create a commit.",
  129. ].join("\n")
  130. try {
  131. await $`opencode run -m ${model} ${prompt}`
  132. } catch (err) {
  133. console.log(`Smoke fix failed: ${err}`)
  134. return false
  135. }
  136. if (!(await typecheck())) {
  137. return false
  138. }
  139. if (!(await build())) {
  140. return false
  141. }
  142. const out = await $`git status --porcelain`.text()
  143. if (!out.trim()) {
  144. console.log("Smoke check passed")
  145. return true
  146. }
  147. try {
  148. await $`git add -A`
  149. await $`git commit -m "Fix beta integration"`
  150. } catch (err) {
  151. console.log(`Failed to commit smoke fixes: ${err}`)
  152. return false
  153. }
  154. if (!(await typecheck())) {
  155. return false
  156. }
  157. if (!(await build())) {
  158. return false
  159. }
  160. console.log("Smoke check passed")
  161. return true
  162. }
  163. async function main() {
  164. console.log("Fetching open PRs with beta label...")
  165. const stdout =
  166. await $`gh pr list --state open --draft=false --label beta --json number,title,author,labels --limit 100`.text()
  167. const prs: PR[] = JSON.parse(stdout).sort((a: PR, b: PR) => a.number - b.number)
  168. console.log(`Found ${prs.length} open PRs with beta label`)
  169. if (prs.length === 0) {
  170. console.log("No team PRs to merge")
  171. return
  172. }
  173. console.log("Fetching latest main branch...")
  174. await $`git fetch origin main`
  175. console.log("Checking out main branch...")
  176. await $`git checkout -B beta origin/main`
  177. const applied: number[] = []
  178. const failed: FailedPR[] = []
  179. for (const [idx, pr] of prs.entries()) {
  180. console.log(`\nProcessing PR ${idx + 1}/${prs.length} #${pr.number}: ${pr.title}`)
  181. console.log(" Fetching PR head...")
  182. try {
  183. await $`git fetch origin pull/${pr.number}/head:pr/${pr.number}`
  184. } catch (err) {
  185. console.log(` Failed to fetch: ${err}`)
  186. failed.push({ number: pr.number, title: pr.title, reason: "Fetch failed" })
  187. await commentOnPR(pr.number, "Fetch failed")
  188. continue
  189. }
  190. console.log(" Merging...")
  191. try {
  192. await $`git merge --no-commit --no-ff pr/${pr.number}`
  193. } catch {
  194. const files = await conflicts()
  195. if (files.length > 0) {
  196. console.log(" Failed to merge (conflicts)")
  197. if (!(await fix(pr, files, prs, applied, idx))) {
  198. await cleanup()
  199. failed.push({ number: pr.number, title: pr.title, reason: "Merge conflicts" })
  200. await commentOnPR(pr.number, "Merge conflicts with dev branch")
  201. continue
  202. }
  203. } else {
  204. console.log(" Failed to merge")
  205. await cleanup()
  206. failed.push({ number: pr.number, title: pr.title, reason: "Merge failed" })
  207. await commentOnPR(pr.number, "Merge failed")
  208. continue
  209. }
  210. }
  211. try {
  212. await $`git rev-parse -q --verify MERGE_HEAD`.text()
  213. } catch {
  214. console.log(" No changes, skipping")
  215. continue
  216. }
  217. try {
  218. await $`git add -A`
  219. } catch {
  220. console.log(" Failed to stage changes")
  221. failed.push({ number: pr.number, title: pr.title, reason: "Staging failed" })
  222. await commentOnPR(pr.number, "Failed to stage changes")
  223. continue
  224. }
  225. const commitMsg = `Apply PR #${pr.number}: ${pr.title}`
  226. try {
  227. await $`git commit -m ${commitMsg}`
  228. } catch (err) {
  229. console.log(` Failed to commit: ${err}`)
  230. failed.push({ number: pr.number, title: pr.title, reason: "Commit failed" })
  231. await commentOnPR(pr.number, "Failed to commit changes")
  232. continue
  233. }
  234. console.log(" Applied successfully")
  235. applied.push(pr.number)
  236. }
  237. console.log("\n--- Summary ---")
  238. console.log(`Applied: ${applied.length} PRs`)
  239. applied.forEach((num) => console.log(` - PR #${num}`))
  240. if (failed.length > 0) {
  241. console.log(`Failed: ${failed.length} PRs`)
  242. failed.forEach((f) => console.log(` - PR #${f.number}: ${f.reason}`))
  243. throw new Error(`${failed.length} PR(s) failed to merge`)
  244. }
  245. if (applied.length > 0) {
  246. const ok = await smoke(prs, applied)
  247. if (!ok) {
  248. throw new Error("Final smoke check failed")
  249. }
  250. }
  251. console.log("\nChecking if beta branch has changes...")
  252. await $`git fetch origin beta`
  253. const localTree = await $`git rev-parse beta^{tree}`.text()
  254. const remoteTrees = (await $`git log origin/main..origin/beta --format=%T`.text()).split("\n")
  255. const matchIdx = remoteTrees.indexOf(localTree.trim())
  256. if (matchIdx !== -1) {
  257. if (matchIdx !== 0) {
  258. console.log(`Beta branch contains this sync, but additional commits exist after it. Leaving beta branch as is.`)
  259. } else {
  260. console.log("Beta branch has identical contents, no push needed")
  261. }
  262. return
  263. }
  264. console.log("Force pushing beta branch...")
  265. await $`git push origin beta --force --no-verify`
  266. console.log("Successfully synced beta branch")
  267. }
  268. main().catch((err) => {
  269. console.error("Error:", err)
  270. process.exit(1)
  271. })