beta.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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`
  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 validate() {
  69. if (!(await typecheck())) return false
  70. if (!(await build())) return false
  71. return true
  72. }
  73. async function commitSmokeChanges() {
  74. const out = await $`git status --porcelain`.text()
  75. if (!out.trim()) {
  76. console.log("Smoke check passed")
  77. return true
  78. }
  79. try {
  80. await $`git add -A`
  81. await $`git commit -m "Fix beta integration"`
  82. } catch (err) {
  83. console.log(`Failed to commit smoke fixes: ${err}`)
  84. return false
  85. }
  86. if (!(await validate())) return false
  87. const left = await $`git status --porcelain`.text()
  88. if (!left.trim()) {
  89. console.log("Smoke check passed")
  90. return true
  91. }
  92. console.log(`Smoke check left uncommitted changes:\n${left}`)
  93. return false
  94. }
  95. async function install() {
  96. console.log(" Regenerating bun.lock...")
  97. try {
  98. await fs.rm("bun.lock", { force: true })
  99. await $`bun install`
  100. await $`git add bun.lock`
  101. return true
  102. } catch (err) {
  103. console.log(`Install failed: ${err}`)
  104. return false
  105. }
  106. }
  107. async function fix(pr: PR, files: string[], prs: PR[], applied: number[], idx: number) {
  108. console.log(` Trying to auto-resolve ${files.length} conflict(s) with opencode...`)
  109. const done = lines(prs.filter((x) => applied.includes(x.number)))
  110. const next = lines(prs.slice(idx + 1))
  111. const prompt = [
  112. `Resolve the current git merge conflicts while merging PR #${pr.number} into the beta branch.`,
  113. `PR #${pr.number}: ${pr.title}`,
  114. `Start with these conflicted files: ${files.join(", ")}.`,
  115. `Merged PRs on HEAD:\n${done}`,
  116. `Pending PRs after this one (context only):\n${next}`,
  117. "IMPORTANT: The conflict resolution must be consistent with already-merged PRs.",
  118. "Pending PRs are context only; do not introduce their changes unless they are already present on HEAD.",
  119. "Prefer already-merged PRs over the base branch when resolving stacked conflicts.",
  120. "If bun.lock is conflicted, do not hand-merge it. Delete bun.lock and run bun install after the code conflicts are resolved.",
  121. "If a PR already deleted a file/directory, do not re-add it, instead apply changes in the new semantic location.",
  122. "If a PR already changed an import, keep that change.",
  123. "After resolving the conflicts, run `bun typecheck` at the repo root.",
  124. "If typecheck fails, you may also update any files reported by typecheck.",
  125. "Keep any non-conflict edits narrowly scoped to restoring a valid merged state for the current PR batch.",
  126. "Fix any merge-caused typecheck errors before finishing.",
  127. "Keep the merge in progress, do not abort the merge, and do not create a commit.",
  128. "When done, leave the working tree with no unmerged files and a passing typecheck.",
  129. ].join("\n")
  130. try {
  131. await $`opencode run -m ${model} ${prompt}`
  132. } catch (err) {
  133. console.log(` opencode failed: ${err}`)
  134. return false
  135. }
  136. const left = await conflicts()
  137. if (left.length > 0) {
  138. console.log(` Conflicts remain: ${left.join(", ")}`)
  139. return false
  140. }
  141. if (files.includes("bun.lock") && !(await install())) return false
  142. if (!(await typecheck())) return false
  143. console.log(" Conflicts resolved with opencode")
  144. return true
  145. }
  146. async function smoke(prs: PR[], applied: number[]) {
  147. console.log("\nRunning final smoke check...")
  148. if (await validate()) return commitSmokeChanges()
  149. console.log("\nTrying to fix final smoke check with opencode...")
  150. const done = lines(prs.filter((x) => applied.includes(x.number)))
  151. const prompt = [
  152. "The beta merge batch is complete, but the deterministic final smoke check failed.",
  153. `Merged PRs on HEAD:\n${done}`,
  154. "Run `bun typecheck` at the repo root.",
  155. "Run `./script/build.ts --single` in `packages/opencode`.",
  156. "Fix any merge-caused issues until both commands pass.",
  157. "Do not create a commit.",
  158. ].join("\n")
  159. try {
  160. await $`opencode run -m ${model} ${prompt}`
  161. } catch (err) {
  162. console.log(`Smoke fix failed: ${err}`)
  163. return false
  164. }
  165. if (!(await validate())) return false
  166. return commitSmokeChanges()
  167. }
  168. async function main() {
  169. console.log("Fetching open PRs with beta label...")
  170. const stdout =
  171. await $`gh pr list --state open --draft=false --label beta --json number,title,author,labels --limit 100`.text()
  172. const prs: PR[] = JSON.parse(stdout).sort((a: PR, b: PR) => a.number - b.number)
  173. console.log(`Found ${prs.length} open PRs with beta label`)
  174. if (prs.length === 0) {
  175. console.log("No team PRs to merge")
  176. return
  177. }
  178. console.log("Fetching latest dev branch...")
  179. await $`git fetch origin dev`
  180. console.log("Checking out beta branch...")
  181. await $`git checkout -B beta origin/dev`
  182. const applied: number[] = []
  183. const failed: FailedPR[] = []
  184. for (const [idx, pr] of prs.entries()) {
  185. console.log(`\nProcessing PR ${idx + 1}/${prs.length} #${pr.number}: ${pr.title}`)
  186. console.log(" Fetching PR head...")
  187. try {
  188. await $`git fetch origin pull/${pr.number}/head:pr/${pr.number}`
  189. } catch (err) {
  190. console.log(` Failed to fetch: ${err}`)
  191. failed.push({ number: pr.number, title: pr.title, reason: "Fetch failed" })
  192. await commentOnPR(pr.number, "Fetch failed")
  193. continue
  194. }
  195. console.log(" Merging...")
  196. try {
  197. await $`git merge --no-commit --no-ff pr/${pr.number}`
  198. } catch {
  199. const files = await conflicts()
  200. if (files.length > 0) {
  201. console.log(" Failed to merge (conflicts)")
  202. if (!(await fix(pr, files, prs, applied, idx))) {
  203. await cleanup()
  204. failed.push({ number: pr.number, title: pr.title, reason: "Merge conflicts" })
  205. await commentOnPR(pr.number, "Merge conflicts with dev branch")
  206. continue
  207. }
  208. } else {
  209. console.log(" Failed to merge")
  210. await cleanup()
  211. failed.push({ number: pr.number, title: pr.title, reason: "Merge failed" })
  212. await commentOnPR(pr.number, "Merge failed")
  213. continue
  214. }
  215. }
  216. try {
  217. await $`git rev-parse -q --verify MERGE_HEAD`.text()
  218. } catch {
  219. console.log(" No changes, skipping")
  220. continue
  221. }
  222. try {
  223. await $`git add -A`
  224. } catch {
  225. console.log(" Failed to stage changes")
  226. failed.push({ number: pr.number, title: pr.title, reason: "Staging failed" })
  227. await commentOnPR(pr.number, "Failed to stage changes")
  228. continue
  229. }
  230. const commitMsg = `Apply PR #${pr.number}: ${pr.title}`
  231. try {
  232. await $`git commit -m ${commitMsg}`
  233. } catch (err) {
  234. console.log(` Failed to commit: ${err}`)
  235. failed.push({ number: pr.number, title: pr.title, reason: "Commit failed" })
  236. await commentOnPR(pr.number, "Failed to commit changes")
  237. continue
  238. }
  239. console.log(" Applied successfully")
  240. applied.push(pr.number)
  241. }
  242. console.log("\n--- Summary ---")
  243. console.log(`Applied: ${applied.length} PRs`)
  244. applied.forEach((num) => console.log(` - PR #${num}`))
  245. if (failed.length > 0) {
  246. console.log(`Failed: ${failed.length} PRs`)
  247. failed.forEach((f) => console.log(` - PR #${f.number}: ${f.reason}`))
  248. throw new Error(`${failed.length} PR(s) failed to merge`)
  249. }
  250. console.log("\nChecking if beta branch has changes...")
  251. await $`git fetch origin beta`
  252. const localTree = (await $`git rev-parse beta^{tree}`.text()).trim()
  253. const remoteTrees = (await $`git log origin/dev..origin/beta --format=%T`.text()).split("\n")
  254. const matchIdx = remoteTrees.indexOf(localTree)
  255. if (matchIdx !== -1) {
  256. if (matchIdx !== 0) {
  257. console.log(`Beta branch contains this sync, but additional commits exist after it. Leaving beta branch as is.`)
  258. } else {
  259. console.log("Beta branch has identical contents, no push needed")
  260. }
  261. return
  262. }
  263. if (!(await smoke(prs, applied))) throw new Error("Final smoke check failed")
  264. await $`git fetch origin beta`
  265. const validatedTree = (await $`git rev-parse beta^{tree}`.text()).trim()
  266. const remoteTreesAfterSmoke = (await $`git log origin/dev..origin/beta --format=%T`.text()).split("\n")
  267. const matchIdxAfterSmoke = remoteTreesAfterSmoke.indexOf(validatedTree)
  268. if (matchIdxAfterSmoke !== -1) {
  269. if (matchIdxAfterSmoke !== 0) {
  270. console.log(`Beta branch contains this validated sync, but additional commits exist after it. Leaving beta branch as is.`)
  271. } else {
  272. console.log("Validated beta branch now matches remote contents, no push needed")
  273. }
  274. return
  275. }
  276. console.log("Force pushing validated beta branch...")
  277. await $`git push origin beta --force --no-verify`
  278. console.log("Successfully synced beta branch")
  279. }
  280. main().catch((err) => {
  281. console.error("Error:", err)
  282. process.exit(1)
  283. })