limn-review 0.1.123

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 (474) hide show
  1. package/LICENSE +110 -0
  2. package/README.md +133 -0
  3. package/dist/ai/runtime.js +535 -0
  4. package/dist/api/plugins/auth.js +169 -0
  5. package/dist/api/plugins/error-handler.js +114 -0
  6. package/dist/api/plugins/rate-limit.js +855 -0
  7. package/dist/api/plugins/security.js +321 -0
  8. package/dist/api/routes/activity.js +103 -0
  9. package/dist/api/routes/ai-runtime.js +67 -0
  10. package/dist/api/routes/auth.js +194 -0
  11. package/dist/api/routes/billing.js +209 -0
  12. package/dist/api/routes/bot-triage.js +1289 -0
  13. package/dist/api/routes/conflicts.js +730 -0
  14. package/dist/api/routes/contact.js +318 -0
  15. package/dist/api/routes/daily-brief.js +58 -0
  16. package/dist/api/routes/flow.js +71 -0
  17. package/dist/api/routes/health.js +7 -0
  18. package/dist/api/routes/insights.js +200 -0
  19. package/dist/api/routes/me.js +458 -0
  20. package/dist/api/routes/mentions.js +22 -0
  21. package/dist/api/routes/mergers.js +8 -0
  22. package/dist/api/routes/ml-labels.js +109 -0
  23. package/dist/api/routes/open-prs.js +35 -0
  24. package/dist/api/routes/prs.js +1633 -0
  25. package/dist/api/routes/reactions.js +217 -0
  26. package/dist/api/routes/repos.js +563 -0
  27. package/dist/api/routes/search.js +41 -0
  28. package/dist/api/routes/threads.js +118 -0
  29. package/dist/api/routes/timeline.js +150 -0
  30. package/dist/api/routes/users.js +67 -0
  31. package/dist/api/routes/webhooks.js +181 -0
  32. package/dist/api/routes/workspaces.js +322 -0
  33. package/dist/app.js +274 -0
  34. package/dist/ascii.js +19 -0
  35. package/dist/auth/account.js +482 -0
  36. package/dist/auth/crypto.js +46 -0
  37. package/dist/bot-triage/resolve.js +59 -0
  38. package/dist/cli.js +388 -0
  39. package/dist/coding/activity.js +80 -0
  40. package/dist/coding/agent.js +288 -0
  41. package/dist/coding/ai-fix/auto-fix.js +212 -0
  42. package/dist/coding/ai-fix/manager.js +370 -0
  43. package/dist/coding/ai-fix/persist.js +213 -0
  44. package/dist/coding/ai-fix/pr-context.js +58 -0
  45. package/dist/coding/ai-fix/prompts.js +138 -0
  46. package/dist/coding/ai-fix/review-seed.js +357 -0
  47. package/dist/coding/ai-fix/routes.js +425 -0
  48. package/dist/coding/git-ops.js +321 -0
  49. package/dist/coding/git.js +184 -0
  50. package/dist/coding/merge.js +262 -0
  51. package/dist/coding/safe-path.js +75 -0
  52. package/dist/coding/schema.js +43 -0
  53. package/dist/config.js +648 -0
  54. package/dist/conflict/diff.js +304 -0
  55. package/dist/conflict/git.js +118 -0
  56. package/dist/conflict/hash.js +73 -0
  57. package/dist/conflict/janitor.js +218 -0
  58. package/dist/conflict/land.js +675 -0
  59. package/dist/conflict/model-types.js +2 -0
  60. package/dist/conflict/model.js +1081 -0
  61. package/dist/conflict/parse.js +142 -0
  62. package/dist/conflict/seam.js +136 -0
  63. package/dist/conflict/session.js +532 -0
  64. package/dist/conflict/suggestion.js +398 -0
  65. package/dist/conflict/tokens.js +72 -0
  66. package/dist/data-dir.js +112 -0
  67. package/dist/db/actor-lanes.js +213 -0
  68. package/dist/db/automation-ids.js +97 -0
  69. package/dist/db/automation-output.js +349 -0
  70. package/dist/db/blast-radius-query.js +36 -0
  71. package/dist/db/blast-radius.js +226 -0
  72. package/dist/db/bot-dormancy.js +115 -0
  73. package/dist/db/bot-overlap.js +579 -0
  74. package/dist/db/bot-volume.js +722 -0
  75. package/dist/db/bot-window.js +35 -0
  76. package/dist/db/branch-queries.js +310 -0
  77. package/dist/db/change-shape.js +243 -0
  78. package/dist/db/changepoint.js +75 -0
  79. package/dist/db/cleanup.js +36 -0
  80. package/dist/db/client.js +102 -0
  81. package/dist/db/code-loc.js +388 -0
  82. package/dist/db/credits.js +79 -0
  83. package/dist/db/daily-brief.js +406 -0
  84. package/dist/db/dependency-cards.js +145 -0
  85. package/dist/db/erase-account.js +255 -0
  86. package/dist/db/export-account.js +189 -0
  87. package/dist/db/failing-checks.js +124 -0
  88. package/dist/db/file-coupling.js +197 -0
  89. package/dist/db/flow-detail.js +661 -0
  90. package/dist/db/flow-pointers.js +197 -0
  91. package/dist/db/flow-settings.js +67 -0
  92. package/dist/db/forecast.js +114 -0
  93. package/dist/db/line-overlap.js +81 -0
  94. package/dist/db/merge-queue.js +189 -0
  95. package/dist/db/migrate.js +17 -0
  96. package/dist/db/migrations/0000_purple_ben_grimm.sql +155 -0
  97. package/dist/db/migrations/0001_colorful_ozymandias.sql +31 -0
  98. package/dist/db/migrations/0002_famous_sersi.sql +9 -0
  99. package/dist/db/migrations/0003_clever_shinobi_shaw.sql +3 -0
  100. package/dist/db/migrations/0004_pale_scalphunter.sql +1 -0
  101. package/dist/db/migrations/0005_daffy_guardian.sql +2 -0
  102. package/dist/db/migrations/0006_cute_violations.sql +45 -0
  103. package/dist/db/migrations/0007_dark_anthem.sql +2 -0
  104. package/dist/db/migrations/0008_multitenant_accounts.sql +44 -0
  105. package/dist/db/migrations/0009_lean_bodies.sql +13 -0
  106. package/dist/db/migrations/0010_lean_bodies_nullable.sql +56 -0
  107. package/dist/db/migrations/0011_pr_diff_size.sql +10 -0
  108. package/dist/db/migrations/0012_findings_included_default.sql +7 -0
  109. package/dist/db/migrations/0013_review_routing.sql +9 -0
  110. package/dist/db/migrations/0014_account_last_active.sql +6 -0
  111. package/dist/db/migrations/0015_repos_inbox_watch.sql +9 -0
  112. package/dist/db/migrations/0016_repo_viewer_permission.sql +7 -0
  113. package/dist/db/migrations/0017_account_display_name.sql +7 -0
  114. package/dist/db/migrations/0018_finding_comment_kind.sql +7 -0
  115. package/dist/db/migrations/0019_finding_file_in_diff.sql +7 -0
  116. package/dist/db/migrations/0020_claude_review_cost_telemetry.sql +11 -0
  117. package/dist/db/migrations/0021_account_feed_last_seen.sql +7 -0
  118. package/dist/db/migrations/0022_ci_status_events.sql +21 -0
  119. package/dist/db/migrations/0023_ai_usage.sql +21 -0
  120. package/dist/db/migrations/0024_pr_head_ref_name.sql +6 -0
  121. package/dist/db/migrations/0025_account_billing.sql +7 -0
  122. package/dist/db/migrations/0026_ai_credit_allowance.sql +5 -0
  123. package/dist/db/migrations/0027_user_github_type.sql +6 -0
  124. package/dist/db/migrations/0028_bot_review_classification.sql +21 -0
  125. package/dist/db/migrations/0029_bot_mute_rules.sql +19 -0
  126. package/dist/db/migrations/0030_teams.sql +32 -0
  127. package/dist/db/migrations/0031_events_pr_idx.sql +7 -0
  128. package/dist/db/migrations/0032_benchmark_contributions.sql +29 -0
  129. package/dist/db/migrations/0033_thread_addressed_confidence.sql +9 -0
  130. package/dist/db/migrations/0034_thread_resolved_at.sql +6 -0
  131. package/dist/db/migrations/0035_pr_first_review_requested_at.sql +5 -0
  132. package/dist/db/migrations/0036_search_index.sql +25 -0
  133. package/dist/db/migrations/0037_author_indexes.sql +15 -0
  134. package/dist/db/migrations/0038_auto_merge_requests.sql +37 -0
  135. package/dist/db/migrations/0039_branch_status.sql +44 -0
  136. package/dist/db/migrations/0040_pr_review_decision.sql +10 -0
  137. package/dist/db/migrations/0041_branch_commit_detail.sql +38 -0
  138. package/dist/db/migrations/0042_repo_reviewers.sql +176 -0
  139. package/dist/db/migrations/0043_account_reviewers.sql +131 -0
  140. package/dist/db/migrations/0044_workspaces.sql +138 -0
  141. package/dist/db/migrations/0045_workspace_reviewers.sql +180 -0
  142. package/dist/db/migrations/0046_drop_inbox_watch.sql +25 -0
  143. package/dist/db/migrations/0047_ml_comment_labels.sql +40 -0
  144. package/dist/db/migrations/0048_ml_vendor_severity.sql +31 -0
  145. package/dist/db/migrations/0049_seat_pricing_repo_description.sql +21 -0
  146. package/dist/db/migrations/0050_users_app_slug.sql +12 -0
  147. package/dist/db/migrations/0051_auto_merge_queue.sql +17 -0
  148. package/dist/db/migrations/0052_trunk_ci_status_events.sql +43 -0
  149. package/dist/db/migrations/0053_automation_roles.sql +79 -0
  150. package/dist/db/migrations/0054_automation_vendor_kinds.sql +514 -0
  151. package/dist/db/migrations/0055_auto_merge_phase.sql +12 -0
  152. package/dist/db/migrations/0056_pr_mentions.sql +22 -0
  153. package/dist/db/migrations/0057_large_pr_threshold.sql +14 -0
  154. package/dist/db/migrations/0058_pending_mute.sql +53 -0
  155. package/dist/db/migrations/0059_merge_queue_state.sql +33 -0
  156. package/dist/db/migrations/0060_drop_my_turn_dismissals.sql +33 -0
  157. package/dist/db/migrations/0061_auto_merge_durable_anchors.sql +27 -0
  158. package/dist/db/migrations/0062_blast_radius_config.sql +21 -0
  159. package/dist/db/migrations/0063_repo_file_coupling.sql +33 -0
  160. package/dist/db/migrations/0064_pr_content_kind.sql +21 -0
  161. package/dist/db/migrations/0065_workspace_flow_settings.sql +13 -0
  162. package/dist/db/migrations/0066_review_request_events.sql +31 -0
  163. package/dist/db/migrations/0067_pr_security_signals.sql +86 -0
  164. package/dist/db/migrations/0068_my_turn_settings.sql +18 -0
  165. package/dist/db/migrations/0069_my_turn_dismissals.sql +41 -0
  166. package/dist/db/migrations/0070_claude_review_follow_up_ticket.sql +22 -0
  167. package/dist/db/migrations/0071_claude_review_trigger.sql +11 -0
  168. package/dist/db/migrations/0072_commit_message_headline.sql +13 -0
  169. package/dist/db/migrations/0073_claude_review_chat.sql +31 -0
  170. package/dist/db/migrations/0074_adopt_agentic_tables.sql +98 -0
  171. package/dist/db/migrations/0075_review_lens_drop_learnings.sql +15 -0
  172. package/dist/db/migrations/0076_claude_review_threads.sql +17 -0
  173. package/dist/db/migrations/0077_claude_review_ci_failures.sql +10 -0
  174. package/dist/db/migrations/0078_ai_fix_change_report.sql +17 -0
  175. package/dist/db/migrations/0079_claude_finding_story.sql +16 -0
  176. package/dist/db/migrations/meta/0000_snapshot.json +1116 -0
  177. package/dist/db/migrations/meta/0001_snapshot.json +1321 -0
  178. package/dist/db/migrations/meta/0002_snapshot.json +1375 -0
  179. package/dist/db/migrations/meta/0003_snapshot.json +1396 -0
  180. package/dist/db/migrations/meta/0004_snapshot.json +1416 -0
  181. package/dist/db/migrations/meta/0005_snapshot.json +1430 -0
  182. package/dist/db/migrations/meta/0006_snapshot.json +1745 -0
  183. package/dist/db/migrations/meta/0007_snapshot.json +1759 -0
  184. package/dist/db/migrations/meta/_journal.json +566 -0
  185. package/dist/db/migrations-pg/0000_tired_alex_power.sql +268 -0
  186. package/dist/db/migrations-pg/0001_dizzy_mockingbird.sql +3 -0
  187. package/dist/db/migrations-pg/0002_glorious_ikaris.sql +4 -0
  188. package/dist/db/migrations-pg/0003_melted_secret_warriors.sql +2 -0
  189. package/dist/db/migrations-pg/0004_numerous_triton.sql +1 -0
  190. package/dist/db/migrations-pg/0005_thick_blockbuster.sql +2 -0
  191. package/dist/db/migrations-pg/0006_majestic_dracula.sql +1 -0
  192. package/dist/db/migrations-pg/0007_same_human_torch.sql +2 -0
  193. package/dist/db/migrations-pg/0008_slimy_toxin.sql +1 -0
  194. package/dist/db/migrations-pg/0009_fuzzy_jubilee.sql +4 -0
  195. package/dist/db/migrations-pg/0010_late_hammerhead.sql +1 -0
  196. package/dist/db/migrations-pg/0011_happy_leech.sql +16 -0
  197. package/dist/db/migrations-pg/0012_woozy_captain_midlands.sql +16 -0
  198. package/dist/db/migrations-pg/0013_yielding_nicolaos.sql +1 -0
  199. package/dist/db/migrations-pg/0014_wakeful_bill_hollister.sql +2 -0
  200. package/dist/db/migrations-pg/0015_aspiring_black_tom.sql +1 -0
  201. package/dist/db/migrations-pg/0016_cute_ghost_rider.sql +30 -0
  202. package/dist/db/migrations-pg/0017_far_changeling.sql +24 -0
  203. package/dist/db/migrations-pg/0018_fancy_miss_america.sql +1 -0
  204. package/dist/db/migrations-pg/0019_benchmark_contributions.sql +22 -0
  205. package/dist/db/migrations-pg/0020_majestic_edwin_jarvis.sql +3 -0
  206. package/dist/db/migrations-pg/0021_green_salo.sql +1 -0
  207. package/dist/db/migrations-pg/0022_wise_baron_strucker.sql +1 -0
  208. package/dist/db/migrations-pg/0023_search_index.sql +19 -0
  209. package/dist/db/migrations-pg/0024_author_indexes.sql +9 -0
  210. package/dist/db/migrations-pg/0025_auto_merge_requests.sql +26 -0
  211. package/dist/db/migrations-pg/0026_branch_status.sql +32 -0
  212. package/dist/db/migrations-pg/0027_pr_review_decision.sql +5 -0
  213. package/dist/db/migrations-pg/0028_branch_commit_detail.sql +9 -0
  214. package/dist/db/migrations-pg/0029_repo_reviewers.sql +127 -0
  215. package/dist/db/migrations-pg/0030_account_reviewers.sql +77 -0
  216. package/dist/db/migrations-pg/0031_workspaces.sql +131 -0
  217. package/dist/db/migrations-pg/0032_workspace_reviewers.sql +165 -0
  218. package/dist/db/migrations-pg/0033_drop_inbox_watch.sql +14 -0
  219. package/dist/db/migrations-pg/0034_ml_comment_labels.sql +33 -0
  220. package/dist/db/migrations-pg/0035_ml_vendor_severity.sql +16 -0
  221. package/dist/db/migrations-pg/0036_seat_pricing_repo_description.sql +12 -0
  222. package/dist/db/migrations-pg/0037_users_app_slug.sql +9 -0
  223. package/dist/db/migrations-pg/0038_auto_merge_queue.sql +10 -0
  224. package/dist/db/migrations-pg/0039_trunk_ci_status_events.sql +27 -0
  225. package/dist/db/migrations-pg/0040_automation_roles.sql +63 -0
  226. package/dist/db/migrations-pg/0041_automation_vendor_kinds.sql +488 -0
  227. package/dist/db/migrations-pg/0042_auto_merge_phase.sql +8 -0
  228. package/dist/db/migrations-pg/0043_pr_mentions.sql +19 -0
  229. package/dist/db/migrations-pg/0044_large_pr_threshold.sql +6 -0
  230. package/dist/db/migrations-pg/0045_pending_mute.sql +26 -0
  231. package/dist/db/migrations-pg/0046_merge_queue_state.sql +18 -0
  232. package/dist/db/migrations-pg/0047_drop_my_turn_dismissals.sql +21 -0
  233. package/dist/db/migrations-pg/0048_auto_merge_durable_anchors.sql +27 -0
  234. package/dist/db/migrations-pg/0049_blast_radius_config.sql +8 -0
  235. package/dist/db/migrations-pg/0050_repo_file_coupling.sql +13 -0
  236. package/dist/db/migrations-pg/0051_pr_content_kind.sql +6 -0
  237. package/dist/db/migrations-pg/0052_workspace_flow_settings.sql +4 -0
  238. package/dist/db/migrations-pg/0053_review_request_events.sql +18 -0
  239. package/dist/db/migrations-pg/0054_pr_security_signals.sql +59 -0
  240. package/dist/db/migrations-pg/0055_my_turn_settings.sql +6 -0
  241. package/dist/db/migrations-pg/0056_my_turn_dismissals.sql +21 -0
  242. package/dist/db/migrations-pg/0057_claude_review_follow_up_ticket.sql +8 -0
  243. package/dist/db/migrations-pg/0058_claude_review_trigger.sql +4 -0
  244. package/dist/db/migrations-pg/0059_commit_message_headline.sql +3 -0
  245. package/dist/db/migrations-pg/0060_claude_review_chat.sql +24 -0
  246. package/dist/db/migrations-pg/0061_adopt_agentic_tables.sql +79 -0
  247. package/dist/db/migrations-pg/0062_review_lens_drop_learnings.sql +5 -0
  248. package/dist/db/migrations-pg/0063_claude_review_threads.sql +7 -0
  249. package/dist/db/migrations-pg/0064_claude_review_ci_failures.sql +4 -0
  250. package/dist/db/migrations-pg/0065_ai_fix_change_report.sql +9 -0
  251. package/dist/db/migrations-pg/0066_claude_finding_story.sql +7 -0
  252. package/dist/db/migrations-pg/meta/0000_snapshot.json +2137 -0
  253. package/dist/db/migrations-pg/meta/0001_snapshot.json +2143 -0
  254. package/dist/db/migrations-pg/meta/0002_snapshot.json +2170 -0
  255. package/dist/db/migrations-pg/meta/0003_snapshot.json +2182 -0
  256. package/dist/db/migrations-pg/meta/0004_snapshot.json +2188 -0
  257. package/dist/db/migrations-pg/meta/0005_snapshot.json +2201 -0
  258. package/dist/db/migrations-pg/meta/0006_snapshot.json +2207 -0
  259. package/dist/db/migrations-pg/meta/0007_snapshot.json +2219 -0
  260. package/dist/db/migrations-pg/meta/0008_snapshot.json +2226 -0
  261. package/dist/db/migrations-pg/meta/0009_snapshot.json +2250 -0
  262. package/dist/db/migrations-pg/meta/0010_snapshot.json +2256 -0
  263. package/dist/db/migrations-pg/meta/0011_snapshot.json +2412 -0
  264. package/dist/db/migrations-pg/meta/0012_snapshot.json +2528 -0
  265. package/dist/db/migrations-pg/meta/0013_snapshot.json +2534 -0
  266. package/dist/db/migrations-pg/meta/0014_snapshot.json +2547 -0
  267. package/dist/db/migrations-pg/meta/0015_snapshot.json +2553 -0
  268. package/dist/db/migrations-pg/meta/0016_snapshot.json +2774 -0
  269. package/dist/db/migrations-pg/meta/0017_snapshot.json +2999 -0
  270. package/dist/db/migrations-pg/meta/0018_snapshot.json +3020 -0
  271. package/dist/db/migrations-pg/meta/0020_snapshot.json +3228 -0
  272. package/dist/db/migrations-pg/meta/0021_snapshot.json +3234 -0
  273. package/dist/db/migrations-pg/meta/0022_snapshot.json +3240 -0
  274. package/dist/db/migrations-pg/meta/_journal.json +475 -0
  275. package/dist/db/ml-labels.js +1666 -0
  276. package/dist/db/my-turn-dismissals.js +343 -0
  277. package/dist/db/my-turn-settings.js +34 -0
  278. package/dist/db/pending-classify.js +46 -0
  279. package/dist/db/pending-mute.js +171 -0
  280. package/dist/db/pending-tabs.js +238 -0
  281. package/dist/db/period-metrics.js +820 -0
  282. package/dist/db/person-period.js +763 -0
  283. package/dist/db/pr-intervals.js +930 -0
  284. package/dist/db/pr-liveness.js +240 -0
  285. package/dist/db/pr-mentions.js +279 -0
  286. package/dist/db/pr-merge-queue-stamp.js +91 -0
  287. package/dist/db/queries.js +14631 -0
  288. package/dist/db/reaction-targets.js +94 -0
  289. package/dist/db/repo-activity.js +171 -0
  290. package/dist/db/retention.js +138 -0
  291. package/dist/db/review-threads-for-review.js +240 -0
  292. package/dist/db/run-migrations.js +24 -0
  293. package/dist/db/schema.pg.js +1220 -0
  294. package/dist/db/schema.sqlite.js +1801 -0
  295. package/dist/db/search.js +317 -0
  296. package/dist/db/security-alerts.js +218 -0
  297. package/dist/db/synthesis-input.js +565 -0
  298. package/dist/db/triage.js +320 -0
  299. package/dist/db/usage.js +63 -0
  300. package/dist/db/work-plan.js +1086 -0
  301. package/dist/db/working-hours.js +161 -0
  302. package/dist/feed/my-turn.js +122 -0
  303. package/dist/github/actions-logs.js +397 -0
  304. package/dist/github/auth.js +86 -0
  305. package/dist/github/branch-queries.js +229 -0
  306. package/dist/github/client.js +454 -0
  307. package/dist/github/codeowners.js +221 -0
  308. package/dist/github/commit-checks.js +105 -0
  309. package/dist/github/compare.js +110 -0
  310. package/dist/github/diff-anchor.js +227 -0
  311. package/dist/github/mutations.js +706 -0
  312. package/dist/github/pr-file-content.js +254 -0
  313. package/dist/github/pr-liveness.js +161 -0
  314. package/dist/github/queries.js +875 -0
  315. package/dist/github/rate-budget.js +129 -0
  316. package/dist/github/reactions.js +161 -0
  317. package/dist/github/reviewer-suggest.js +104 -0
  318. package/dist/github/team-reviewers.js +96 -0
  319. package/dist/index.js +184 -0
  320. package/dist/merge/auto-merge-runner.js +960 -0
  321. package/dist/ml/severity-client.js +218 -0
  322. package/dist/pr/detail-enricher.js +26 -0
  323. package/dist/pro/bind.js +302 -0
  324. package/dist/pro/contract.js +37 -0
  325. package/dist/pro/migrate.js +64 -0
  326. package/dist/review/agent-context.js +127 -0
  327. package/dist/review/agent.js +385 -0
  328. package/dist/review/agentic.js +59 -0
  329. package/dist/review/auth.js +94 -0
  330. package/dist/review/chat-agent.js +179 -0
  331. package/dist/review/claude-review/ai-ready.js +16 -0
  332. package/dist/review/claude-review/auto-settings.js +139 -0
  333. package/dist/review/claude-review/auto.js +244 -0
  334. package/dist/review/claude-review/chat.js +489 -0
  335. package/dist/review/claude-review/ci-failures.js +350 -0
  336. package/dist/review/claude-review/follow-up.js +310 -0
  337. package/dist/review/claude-review/manager.js +686 -0
  338. package/dist/review/claude-review/persist.js +996 -0
  339. package/dist/review/claude-review/prompts.js +357 -0
  340. package/dist/review/claude-review/routes.js +518 -0
  341. package/dist/review/claude-review/routing.js +61 -0
  342. package/dist/review/claude-review/specialists.js +190 -0
  343. package/dist/review/claude-review/threads.js +265 -0
  344. package/dist/review/claude-review/ticket.js +282 -0
  345. package/dist/review/clone-hygiene.js +380 -0
  346. package/dist/review/clone-manager.js +367 -0
  347. package/dist/review/llm.js +113 -0
  348. package/dist/review/model-options.js +48 -0
  349. package/dist/review/plugin-providers.js +12 -0
  350. package/dist/review/post-review.js +216 -0
  351. package/dist/review/post-seam.js +161 -0
  352. package/dist/review/prepare.js +168 -0
  353. package/dist/review/pricing.js +17 -0
  354. package/dist/review/schema.js +156 -0
  355. package/dist/review/submit-map.js +41 -0
  356. package/dist/review/usage.js +90 -0
  357. package/dist/shared/claude-review.js +335 -0
  358. package/dist/shared/conflict-fold.js +151 -0
  359. package/dist/shared/conflicts.js +30 -0
  360. package/dist/shared/flow-settings.js +191 -0
  361. package/dist/shared/index.js +8 -0
  362. package/dist/shared/my-turn-settings.js +238 -0
  363. package/dist/shared/pending-rules.js +281 -0
  364. package/dist/shared/product.js +54 -0
  365. package/dist/shared/types.js +896 -0
  366. package/dist/status.js +386 -0
  367. package/dist/sync/adaptive.js +185 -0
  368. package/dist/sync/app-attribution.js +66 -0
  369. package/dist/sync/auth-notices.js +36 -0
  370. package/dist/sync/backfill-ci-history.js +315 -0
  371. package/dist/sync/backfill-commit-headlines.js +136 -0
  372. package/dist/sync/backfill-pr-security.js +175 -0
  373. package/dist/sync/backfill-review-requests.js +97 -0
  374. package/dist/sync/benchmark-rollup.js +50 -0
  375. package/dist/sync/bot-detection.js +309 -0
  376. package/dist/sync/bot-resolution-markers.js +30 -0
  377. package/dist/sync/branch-status.js +634 -0
  378. package/dist/sync/classify-change-shape.js +150 -0
  379. package/dist/sync/commit-files.js +74 -0
  380. package/dist/sync/derive-thread-state.js +99 -0
  381. package/dist/sync/drain-review-threads.js +212 -0
  382. package/dist/sync/hydrate-detail.js +482 -0
  383. package/dist/sync/mention-scan.js +89 -0
  384. package/dist/sync/ml-enrichment.js +478 -0
  385. package/dist/sync/pr-change-signal.js +96 -0
  386. package/dist/sync/pr-liveness-sweep.js +139 -0
  387. package/dist/sync/pr-settle.js +381 -0
  388. package/dist/sync/refresh-pr.js +163 -0
  389. package/dist/sync/reparse-vendor-badges.js +495 -0
  390. package/dist/sync/resync-after-write.js +280 -0
  391. package/dist/sync/review-fingerprint.js +117 -0
  392. package/dist/sync/reviewer-behavior.js +103 -0
  393. package/dist/sync/reviewer-classify.js +503 -0
  394. package/dist/sync/routing-files.js +97 -0
  395. package/dist/sync/scheduled-jobs.js +12 -0
  396. package/dist/sync/scheduler.js +159 -0
  397. package/dist/sync/security-detect.js +521 -0
  398. package/dist/sync/sync-manager.js +750 -0
  399. package/dist/sync/sync-one-pr.js +205 -0
  400. package/dist/sync/sync-repo.js +400 -0
  401. package/dist/sync/unsettled-prs.js +506 -0
  402. package/dist/sync/upsert.js +1190 -0
  403. package/package.json +56 -0
  404. package/public/apple-touch-icon.png +0 -0
  405. package/public/assets/AiFixTab-CQP6PT5u.js +2 -0
  406. package/public/assets/ClaudeReviewTab-DQJ-58ZA.js +8 -0
  407. package/public/assets/PrBotBehaviourTab-CCnFrWbC.js +1 -0
  408. package/public/assets/archivo-latin-600-BN-JkNrl.woff2 +0 -0
  409. package/public/assets/highlight-BEHUn5zE.css +10 -0
  410. package/public/assets/highlight-CIIZLa6Z.js +12 -0
  411. package/public/assets/index-BDnYs6zg.js +73 -0
  412. package/public/assets/index-mCuI--RC.css +1 -0
  413. package/public/assets/markdown-I_JLLVAZ.js +32 -0
  414. package/public/assets/perfProbe-Da13EhTE.js +1 -0
  415. package/public/assets/tanstack-5qsxxaLe.js +17 -0
  416. package/public/assets/vis-C3BCkP5U.js +1280 -0
  417. package/public/assets/vis-ziCVehMy.css +1 -0
  418. package/public/favicon-16.png +0 -0
  419. package/public/favicon-32.png +0 -0
  420. package/public/favicon-48.png +0 -0
  421. package/public/favicon.svg +5 -0
  422. package/public/index.html +41 -0
  423. package/public-landing/apple-touch-icon.png +0 -0
  424. package/public-landing/assets/archivo-latin-500-BWmvx2Mg.woff2 +0 -0
  425. package/public-landing/assets/archivo-latin-600-BN-JkNrl.woff2 +0 -0
  426. package/public-landing/assets/index-CA3eEGXO.js +40 -0
  427. package/public-landing/assets/index-naQrQ6Fe.css +1 -0
  428. package/public-landing/assets/jetbrains-mono-latin-400-RruCX7RW.woff2 +0 -0
  429. package/public-landing/assets/newsreader-latin-400-DExrRRrN.woff2 +0 -0
  430. package/public-landing/assets/newsreader-latin-400-italic-b0I-AwbV.woff2 +0 -0
  431. package/public-landing/bots/index.html +156 -0
  432. package/public-landing/contact/index.html +156 -0
  433. package/public-landing/cookies/index.html +156 -0
  434. package/public-landing/demo/limn-walkthrough-poster.jpg +0 -0
  435. package/public-landing/demo/limn-walkthrough.cues.json +44 -0
  436. package/public-landing/demo/limn-walkthrough.mp4 +0 -0
  437. package/public-landing/favicon-16.png +0 -0
  438. package/public-landing/favicon-32.png +0 -0
  439. package/public-landing/favicon-48.png +0 -0
  440. package/public-landing/favicon.svg +5 -0
  441. package/public-landing/features/index.html +156 -0
  442. package/public-landing/for-developers/index.html +156 -0
  443. package/public-landing/for-managers/index.html +156 -0
  444. package/public-landing/how-it-works/index.html +156 -0
  445. package/public-landing/how-we-measure/index.html +156 -0
  446. package/public-landing/icon-192.png +0 -0
  447. package/public-landing/icon-512.png +0 -0
  448. package/public-landing/index.html +156 -0
  449. package/public-landing/insights/index.html +156 -0
  450. package/public-landing/og-image.png +0 -0
  451. package/public-landing/pricing/index.html +156 -0
  452. package/public-landing/privacy/index.html +156 -0
  453. package/public-landing/pro/index.html +156 -0
  454. package/public-landing/reviews/index.html +156 -0
  455. package/public-landing/robots.txt +8 -0
  456. package/public-landing/shots/benchmark.png +0 -0
  457. package/public-landing/shots/bot-roi.png +0 -0
  458. package/public-landing/shots/bot-settings.png +0 -0
  459. package/public-landing/shots/chronology.png +0 -0
  460. package/public-landing/shots/feed.png +0 -0
  461. package/public-landing/shots/flow-metrics.png +0 -0
  462. package/public-landing/shots/free-reports.png +0 -0
  463. package/public-landing/shots/pending-board.png +0 -0
  464. package/public-landing/shots/pending-card.png +0 -0
  465. package/public-landing/shots/period-report.png +0 -0
  466. package/public-landing/shots/pr-detail.png +0 -0
  467. package/public-landing/shots/pr-threads.png +0 -0
  468. package/public-landing/shots/reach.png +0 -0
  469. package/public-landing/shots/repo-rows.png +0 -0
  470. package/public-landing/shots/severity-findings.png +0 -0
  471. package/public-landing/shots/severity-strip.png +0 -0
  472. package/public-landing/site.webmanifest +14 -0
  473. package/public-landing/sitemap.xml +51 -0
  474. package/public-landing/terms/index.html +156 -0
@@ -0,0 +1,1633 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { REQUEST_CHANGES_DEFAULT_BODY } from '../../shared/index.js';
3
+ import { config } from '../../config.js';
4
+ import { stampPrMergeQueueStateNonFatal } from '../../db/pr-merge-queue-stamp.js';
5
+ import { getAccessToken, getAccountUserId } from '../../auth/account.js';
6
+ import { fetchActionsJobLog } from '../../github/actions-logs.js';
7
+ import { armAutoMerge, disarmAutoMerge, getAutoMergeRequest, getSyncedBaseRef, listAutoMergeRequests, getMentionCandidates, getPrDetail, getPrBotBehaviour, getPrFilesContext, getPrWriteContext, getReviewerLogins, getResolvableBotThreads, getSuggestedReviewersBasis, getUsersByLogins, clearOwnReviewRequest, markAllViewed, markPrClosedLocally, markPrMergedLocally, markPrReopenedLocally, markPrViewed, stampReviewRequests, upsertLocalPrComment, upsertLocalReview, } from '../../db/queries.js';
8
+ import { resolveArmedQueues, withArmedQueueFields } from '../../db/merge-queue.js';
9
+ // The watcher's live marks (yields + queue-disabled fallbacks). Read-only, and the reason this
10
+ // import is not a layering smell: every one of them is a LIVE observation of GitHub made inside
11
+ // the tick, so the runner is the only thing that can own them, and the route only reports them.
12
+ import { armedQueueMarks } from '../../merge/auto-merge-runner.js';
13
+ import { enrichReviewerSuggestions } from '../../github/reviewer-suggest.js';
14
+ import { buildFileAnchors, fallbackAnchor, isFindingAnchored, } from '../../github/diff-anchor.js';
15
+ import { addIssueComment, closePullRequest, dequeuePullRequestFromQueue, enqueuePullRequestOnQueue, fetchHeadShaFor, fetchMergeability, fetchMergeQueueState, fetchPrFilesWithPatch, fetchPrHeadInfo, fetchRepoMergeConfig, mergePullRequest, postInlineComment, reopenPullRequest, requestReviewers, rerunWorkflowRun, submitPrReview, updatePullRequestBranch, } from '../../github/mutations.js';
16
+ import { PR_FILES_MAX_PAGE, fetchFileAtRef, fetchPrFilesPage, findPrFileWithPatch, isSafeRepoPath, resolvePrDiffRefs, synthesizeUnifiedPatch, } from '../../github/pr-file-content.js';
17
+ import { hydratePrDetail } from '../../sync/hydrate-detail.js';
18
+ import { mergeQueueEntryStateFrom, reviewDecisionFrom } from '../../sync/upsert.js';
19
+ import { refreshPrFromGitHub } from '../../sync/refresh-pr.js';
20
+ import { asSyncLogger, confirmPostedReviewComment, resyncPrAfterWrite, settlePrAfterWrite, } from '../../sync/resync-after-write.js';
21
+ import { getPrSettleFacts, notePrChangedForPr, schedulePrSettle, } from '../../sync/pr-settle.js';
22
+ import { noteMergeLanded } from '../../sync/unsettled-prs.js';
23
+ import { resolveThreadsOnGitHub } from '../../bot-triage/resolve.js';
24
+ import { accountIdOf } from '../plugins/auth.js';
25
+ // GitHub anchors a file in the PR "Files changed" diff by the SHA-256 of its
26
+ // path (matches db/queries.ts + hydrate-detail.ts's diffAnchorId).
27
+ function diffAnchorId(path) {
28
+ return createHash('sha256').update(path, 'utf8').digest('hex');
29
+ }
30
+ // How long an armed auto-merge intent stays live before the watcher expires it. A hard stop
31
+ // so an intent can't linger for weeks against a PR the user has long forgotten — 72h covers
32
+ // "arm it on Friday, it lands when Monday's CI goes green".
33
+ const AUTO_MERGE_TTL_MS = 72 * 60 * 60 * 1000;
34
+ const PR_FILE_STATUSES = [
35
+ 'added',
36
+ 'modified',
37
+ 'removed',
38
+ 'renamed',
39
+ 'changed',
40
+ 'copied',
41
+ 'unchanged',
42
+ ];
43
+ // Pass GitHub's REST file status through verbatim when it's one we model, else
44
+ // fall back to 'changed' (the catch-all GitHub itself uses).
45
+ function normalizeStatus(status) {
46
+ return PR_FILE_STATUSES.includes(status)
47
+ ? status
48
+ : 'changed';
49
+ }
50
+ const idParamSchema = {
51
+ params: {
52
+ type: 'object',
53
+ required: ['id'],
54
+ properties: { id: { type: 'integer' } },
55
+ },
56
+ };
57
+ // GET /api/prs/:id/files — `?page=` is the "Load next 100 files" click (GitHub's 3,000-file
58
+ // listing ceiling is page 30).
59
+ const prFilesSchema = {
60
+ ...idParamSchema,
61
+ querystring: {
62
+ type: 'object',
63
+ properties: { page: { type: 'integer', minimum: 1, maximum: PR_FILES_MAX_PAGE } },
64
+ },
65
+ };
66
+ const prFileContentSchema = {
67
+ ...idParamSchema,
68
+ querystring: {
69
+ type: 'object',
70
+ required: ['path', 'side'],
71
+ properties: {
72
+ path: { type: 'string', minLength: 1, maxLength: 4096 },
73
+ side: { type: 'string', enum: ['head', 'base'] },
74
+ },
75
+ },
76
+ };
77
+ const prFileDiffSchema = {
78
+ ...idParamSchema,
79
+ querystring: {
80
+ type: 'object',
81
+ required: ['path'],
82
+ properties: {
83
+ path: { type: 'string', minLength: 1, maxLength: 4096 },
84
+ previousPath: { type: 'string', minLength: 1, maxLength: 4096 },
85
+ },
86
+ },
87
+ };
88
+ /** A file body as display lines: no phantom last line for the trailing newline, `\r` stripped. */
89
+ function splitFileLines(text) {
90
+ if (text === '')
91
+ return [];
92
+ const lines = text.split('\n');
93
+ if (lines[lines.length - 1] === '')
94
+ lines.pop();
95
+ return lines.map((l) => (l.endsWith('\r') ? l.slice(0, -1) : l));
96
+ }
97
+ const checkLogsSchema = {
98
+ params: {
99
+ type: 'object',
100
+ required: ['id', 'jobId'],
101
+ properties: {
102
+ id: { type: 'integer' },
103
+ jobId: { type: 'integer', minimum: 1 },
104
+ },
105
+ },
106
+ querystring: {
107
+ type: 'object',
108
+ properties: {
109
+ tail: { type: 'integer', minimum: 1, maximum: 1000 },
110
+ // Byte window for the scroll-up pager. startByte is inclusive, endByte
111
+ // EXCLUSIVE, both in SOURCE-byte space (the \r\n normalisation the fetcher
112
+ // applies is display-only), so feeding a response's startByte back as the
113
+ // next endByte abuts exactly. Absent ⇒ anchor at the tail.
114
+ startByte: { type: 'integer', minimum: 0 },
115
+ endByte: { type: 'integer', minimum: 0 },
116
+ },
117
+ },
118
+ };
119
+ const markViewedSchema = {
120
+ ...idParamSchema,
121
+ body: {
122
+ type: 'object',
123
+ additionalProperties: false,
124
+ properties: { sha: { type: 'string' } },
125
+ },
126
+ };
127
+ const refreshSchema = {
128
+ ...idParamSchema,
129
+ body: {
130
+ type: 'object',
131
+ additionalProperties: false,
132
+ properties: { wait: { type: 'boolean' } },
133
+ },
134
+ };
135
+ const ciRerunSchema = {
136
+ ...idParamSchema,
137
+ body: {
138
+ type: 'object',
139
+ required: ['runId', 'mode'],
140
+ additionalProperties: false,
141
+ properties: {
142
+ runId: { type: 'integer', minimum: 1 },
143
+ mode: { type: 'string', enum: ['failed', 'all'] },
144
+ },
145
+ },
146
+ };
147
+ const markAllViewedSchema = {
148
+ body: {
149
+ type: 'object',
150
+ additionalProperties: false,
151
+ properties: { repoIds: { type: 'array', items: { type: 'integer' } } },
152
+ },
153
+ };
154
+ const commentSchema = {
155
+ ...idParamSchema,
156
+ body: {
157
+ type: 'object',
158
+ required: ['body'],
159
+ additionalProperties: false,
160
+ properties: { body: { type: 'string' } },
161
+ },
162
+ };
163
+ const approveSchema = {
164
+ ...idParamSchema,
165
+ body: {
166
+ type: 'object',
167
+ additionalProperties: false,
168
+ properties: { body: { type: 'string' } },
169
+ },
170
+ };
171
+ const resolveBotThreadsSchema = {
172
+ ...idParamSchema,
173
+ body: {
174
+ type: 'object',
175
+ required: ['threadIds'],
176
+ additionalProperties: false,
177
+ properties: {
178
+ // minItems: 1 rejects `{threadIds: []}` with a 400 — a destructive endpoint should
179
+ // never be invoked with an empty selection (defence-in-depth with getResolvableBotThreads).
180
+ threadIds: { type: 'array', items: { type: 'integer' }, minItems: 1, maxItems: 200 },
181
+ },
182
+ },
183
+ };
184
+ const mergeSchema = {
185
+ ...idParamSchema,
186
+ body: {
187
+ type: 'object',
188
+ required: ['method'],
189
+ additionalProperties: false,
190
+ properties: { method: { type: 'string', enum: ['merge', 'squash', 'rebase'] } },
191
+ },
192
+ };
193
+ const updateBranchSchema = {
194
+ ...idParamSchema,
195
+ body: {
196
+ type: 'object',
197
+ additionalProperties: false,
198
+ properties: { strategy: { type: 'string', enum: ['rebase', 'merge'] } },
199
+ },
200
+ };
201
+ // Enqueue on GitHub's native merge queue. `method` is accepted (some repos allow a per-entry
202
+ // method) but GitHub's EnqueuePullRequestInput has no such field today, so it is ignored —
203
+ // declared here only so a client sending it isn't 400'd by additionalProperties:false.
204
+ const mergeQueueSchema = {
205
+ ...idParamSchema,
206
+ body: {
207
+ type: 'object',
208
+ additionalProperties: false,
209
+ properties: { method: { type: 'string', enum: ['merge', 'squash', 'rebase'] } },
210
+ },
211
+ };
212
+ const armMergeSchema = {
213
+ ...idParamSchema,
214
+ body: {
215
+ type: 'object',
216
+ required: ['mergeMethod'],
217
+ additionalProperties: false,
218
+ properties: {
219
+ mergeMethod: { type: 'string', enum: ['merge', 'squash', 'rebase'] },
220
+ updateStrategy: { type: 'string', enum: ['rebase', 'merge', 'none'] },
221
+ },
222
+ },
223
+ };
224
+ const reviewCommentSchema = {
225
+ ...idParamSchema,
226
+ body: {
227
+ type: 'object',
228
+ required: ['path', 'line', 'body'],
229
+ additionalProperties: false,
230
+ properties: {
231
+ path: { type: 'string' },
232
+ line: { type: 'integer' },
233
+ side: { type: 'string', enum: ['LEFT', 'RIGHT'] },
234
+ body: { type: 'string' },
235
+ },
236
+ },
237
+ };
238
+ const requestReviewersSchema = {
239
+ ...idParamSchema,
240
+ body: {
241
+ type: 'object',
242
+ additionalProperties: false,
243
+ // All three are optional; the handler 400s if the combined set is empty. `userIds`
244
+ // are resolved to logins; `logins` pass through (suggested reviewers we haven't synced);
245
+ // `teamSlugs` become team review requests (CODEOWNERS @org/team).
246
+ properties: {
247
+ userIds: { type: 'array', maxItems: 15, items: { type: 'integer' } },
248
+ logins: { type: 'array', maxItems: 15, items: { type: 'string' } },
249
+ teamSlugs: { type: 'array', maxItems: 15, items: { type: 'string' } },
250
+ },
251
+ },
252
+ };
253
+ // Build the CORE "Suggested reviewers" set for a PR — served as its OWN live query so it's
254
+ // never frozen inside the cached PR detail (it must empty the instant a reviewer is
255
+ // requested). Combines the history-USER basis (from synced data) with two best-effort,
256
+ // per-repo-cached network sources fetched in parallel:
257
+ // • CODEOWNERS — declared ownership for the touched paths (users + teams).
258
+ // • Team history — which team(s) are usually REQUESTED to review this repo (the behavioural
259
+ // fallback when CODEOWNERS declares no team; repo-level, so it runs even when the PR
260
+ // touches no owned path). See github/team-reviewers.ts.
261
+ // Returns empty when the PR doesn't warrant suggestions. Any network failure (no CODEOWNERS,
262
+ // org wall, a repo that doesn't use team requests) degrades to just the history-user set.
263
+ // Precedence: declared CODEOWNERS owners, then the inferred team(s), then history users, cap 5.
264
+ async function buildSuggestedReviewers(basis, accountId) {
265
+ if (!basis.wants)
266
+ return { suggestedReviewers: [], users: [] };
267
+ const { owner, name, authorLogin, paths, suggestions, users } = basis;
268
+ const { suggestions: merged, extraUsers } = await enrichReviewerSuggestions({
269
+ accountId,
270
+ owner,
271
+ name,
272
+ authorLogin,
273
+ paths,
274
+ userSuggestions: suggestions,
275
+ knownUserIds: new Set(users.map((u) => u.id)),
276
+ resolveUsers: getUsersByLogins,
277
+ });
278
+ return { suggestedReviewers: merged, users: [...users, ...extraUsers] };
279
+ }
280
+ export async function prRoutes(app) {
281
+ // Bulk "mark all seen": stamp every open PR (optionally scoped to repoIds) viewed
282
+ // at its head, clearing all new-since badges at once. Static path — no :id — so it
283
+ // doesn't collide with /api/prs/:id.
284
+ app.post('/api/prs/mark-all-viewed', { schema: markAllViewedSchema }, async (req) => {
285
+ const { repoIds } = (req.body ?? {});
286
+ const count = await markAllViewed(accountIdOf(req), repoIds && repoIds.length > 0 ? repoIds : null);
287
+ return { status: 'ok', count };
288
+ });
289
+ app.get('/api/prs/:id', { schema: idParamSchema }, async (req, reply) => {
290
+ const { id } = req.params;
291
+ const accountId = accountIdOf(req);
292
+ const pr = await getPrDetail(id, accountId);
293
+ if (!pr) {
294
+ reply.status(404);
295
+ return { error: 'NotFound', message: `PR ${id} not found` };
296
+ }
297
+ // Cloud lean mode: fill in bulky text from GitHub (no-op in local). The client
298
+ // caches the result in IndexedDB keyed by updatedAt so unchanged PRs don't refetch.
299
+ // (Suggested reviewers are NOT here — they're a separate live query, see below — so the
300
+ // cached detail never freezes a stale suggestion.)
301
+ return hydratePrDetail(pr, accountId);
302
+ });
303
+ // Live PR-detail freshness: the SPA polls this every ~5s while a PR is open AND visible,
304
+ // and the header Refresh button posts {wait:true}. Probe-gated server-side — a quiet
305
+ // tick is one free conditional REST 304; see sync/refresh-pr.ts for the cost model.
306
+ // POST deliberately (not GET) so the cross-origin guard applies in cloud; rate tier is
307
+ // `prDetail` (spelled into tierFor — same GitHub-cost profile as GET /api/prs/:id).
308
+ // A sync failure is a 200 {synced:false}, NEVER a 5xx — the stored PR is still valid.
309
+ app.post('/api/prs/:id/refresh', { schema: refreshSchema }, async (req, reply) => {
310
+ const { id } = req.params;
311
+ const { wait } = (req.body ?? {});
312
+ const result = await refreshPrFromGitHub({
313
+ prId: id,
314
+ accountId: accountIdOf(req),
315
+ wait: wait === true,
316
+ log: req.log,
317
+ });
318
+ if (!result) {
319
+ reply.status(404);
320
+ return { error: 'NotFound', message: `PR ${id} not found` };
321
+ }
322
+ const resp = result;
323
+ return resp;
324
+ });
325
+ // PR-scoped bot behaviour (EXPERIMENTAL, CORE, deterministic — no AI): each automated reviewer's
326
+ // touch timeline ON THIS PR + how it compares to that bot's OWN typical (an 84-day account-wide
327
+ // robust baseline). Powers the PrDetail "Bot activity" tab + the Overview chip warn badge.
328
+ // Account-scoped: 404 when the PR isn't the caller's; empty `bots` when no bot touched it.
329
+ app.get('/api/prs/:id/bot-behaviour', { schema: idParamSchema }, async (req, reply) => {
330
+ const { id } = req.params;
331
+ const resp = await getPrBotBehaviour(id, accountIdOf(req));
332
+ if (!resp) {
333
+ reply.status(404);
334
+ return { error: 'NotFound', message: `PR ${id} not found` };
335
+ }
336
+ return resp;
337
+ });
338
+ // Suggested reviewers — its OWN live query (not embedded in the cached PR detail) so it
339
+ // always reflects current state: it empties the instant a reviewer is requested (the assign
340
+ // route stamps review_requests locally), rather than staying frozen until the PR's updatedAt
341
+ // next bumps. Best-effort network enrichment (CODEOWNERS + inferred team) on top of the
342
+ // synced history basis. 404s when the PR isn't the caller's.
343
+ app.get('/api/prs/:id/suggested-reviewers', { schema: idParamSchema }, async (req, reply) => {
344
+ const { id } = req.params;
345
+ const accountId = accountIdOf(req);
346
+ const basis = await getSuggestedReviewersBasis(id, accountId);
347
+ if (!basis) {
348
+ reply.status(404);
349
+ return { error: 'NotFound', message: `PR ${id} not found` };
350
+ }
351
+ const result = await buildSuggestedReviewers(basis, accountId);
352
+ return result;
353
+ });
354
+ // Candidates for an @mention autocomplete, ranked by proximity to this PR
355
+ // (participants first, then repo people), self + bots excluded, each carrying
356
+ // `isMaintainer` (has merged a PR in THIS repo) for the picker's shield + sort.
357
+ // Account-scoped: 404 when the PR isn't the caller's.
358
+ app.get('/api/prs/:id/mention-candidates', { schema: idParamSchema }, async (req, reply) => {
359
+ const { id } = req.params;
360
+ const candidates = await getMentionCandidates(id, accountIdOf(req));
361
+ if (!candidates) {
362
+ reply.status(404);
363
+ return { error: 'NotFound', message: `PR ${id} not found` };
364
+ }
365
+ return candidates;
366
+ });
367
+ // Record that the local user has seen this PR up to `sha` (defaults to the
368
+ // current head). Clears "new since last viewed" badges.
369
+ app.post('/api/prs/:id/mark-viewed', { schema: markViewedSchema }, async (req, reply) => {
370
+ const { id } = req.params;
371
+ const { sha } = (req.body ?? {});
372
+ const ok = await markPrViewed(id, accountIdOf(req), sha);
373
+ if (!ok) {
374
+ reply.status(404);
375
+ return { error: 'NotFound', message: `PR ${id} not found` };
376
+ }
377
+ return { status: 'ok' };
378
+ });
379
+ // Explicit "I've seen this" without opening — same effect as mark-viewed.
380
+ app.post('/api/prs/:id/dismiss', { schema: idParamSchema }, async (req, reply) => {
381
+ const { id } = req.params;
382
+ const ok = await markPrViewed(id, accountIdOf(req));
383
+ if (!ok) {
384
+ reply.status(404);
385
+ return { error: 'NotFound', message: `PR ${id} not found` };
386
+ }
387
+ return { status: 'ok' };
388
+ });
389
+ // Bulk-resolve the review-BOT threads a later commit has likely addressed — Pierre's
390
+ // "clear the bot backlog in one click." NEVER automatic: the client sends the explicit
391
+ // reviewed list of thread ids; the server RE-DERIVES the eligible set (owned + bot-
392
+ // originated + `likely_addressed`), intersects it with that list, and resolves only that
393
+ // — so a stale client can never resolve a thread the server wouldn't itself offer. Each
394
+ // thread is resolved on GitHub + locally stamped; per-thread failures are reported, not fatal.
395
+ app.post('/api/prs/:id/resolve-bot-threads', { schema: resolveBotThreadsSchema }, async (req) => {
396
+ const { id } = req.params;
397
+ const { threadIds } = req.body;
398
+ const accountId = accountIdOf(req);
399
+ // Server RE-DERIVES the eligible set (owned + automated-reviewer-originated +
400
+ // `likely_addressed` + unresolved) ∩ the client's reviewed list, then resolves each via
401
+ // the shared helper (the SAME code path the scope-wide resolve uses). An empty
402
+ // eligible set — PR not owned / no such threads / a fully-stale client list — is a no-op,
403
+ // not an error (the helper short-circuits before any token fetch). Status stays 200 even
404
+ // on partial failure; the body carries per-thread outcomes.
405
+ const eligible = await getResolvableBotThreads(id, accountId, threadIds);
406
+ return resolveThreadsOnGitHub(accountId, eligible.map((t) => ({ ...t, prId: id })));
407
+ });
408
+ // Post a new issue-level (general) PR comment, then optimistically stamp it
409
+ // locally so it shows before the next sync.
410
+ app.post('/api/prs/:id/comment', { schema: commentSchema }, async (req, reply) => {
411
+ const { id } = req.params;
412
+ const { body } = req.body;
413
+ const accountId = accountIdOf(req);
414
+ const ctx = await getPrWriteContext(id, accountId);
415
+ if (!ctx) {
416
+ reply.status(404);
417
+ return { error: 'NotFound', message: `PR ${id} not found` };
418
+ }
419
+ try {
420
+ const token = await getAccessToken(accountId);
421
+ const gh = await addIssueComment(token, ctx.owner, ctx.name, ctx.number, body);
422
+ const authorId = await getAccountUserId(accountId);
423
+ const rowId = await upsertLocalPrComment(ctx.prId, authorId, gh);
424
+ // The stamp moves what the board reads (My Turn's ball rule reads your comments), and no
425
+ // walk reports a local stamp: raise the SPA change signal BEFORE replying, so the write's
426
+ // own ordered `['repos']` read already covers it (sync/pr-settle.ts). Never throws.
427
+ await notePrChangedForPr(accountId, ctx.prId);
428
+ const result = {
429
+ id: rowId,
430
+ authorId,
431
+ body: gh.body,
432
+ createdAt: new Date(gh.createdAt).toISOString(),
433
+ url: gh.url,
434
+ };
435
+ return result;
436
+ }
437
+ catch (err) {
438
+ reply.status(502);
439
+ return {
440
+ error: 'GitHubError',
441
+ message: err instanceof Error ? err.message : String(err),
442
+ };
443
+ }
444
+ });
445
+ // Approve the PR. Server re-checks (matching getPrDetail.viewerCanApprove) that
446
+ // the viewer has write+ permission and isn't the author; else 403. On success
447
+ // submits an APPROVE review and stamps it locally. A GitHub 422 (e.g. a
448
+ // self-approve race) bubbles to the 502 catch.
449
+ app.post('/api/prs/:id/approve', { schema: approveSchema }, async (req, reply) => {
450
+ const { id } = req.params;
451
+ const { body } = (req.body ?? {});
452
+ const accountId = accountIdOf(req);
453
+ const ctx = await getPrWriteContext(id, accountId);
454
+ if (!ctx) {
455
+ reply.status(404);
456
+ return { error: 'NotFound', message: `PR ${id} not found` };
457
+ }
458
+ const viewerUserId = await getAccountUserId(accountId);
459
+ const canApprove = viewerUserId != null &&
460
+ viewerUserId !== ctx.authorId &&
461
+ ['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '');
462
+ if (!canApprove) {
463
+ reply.status(403);
464
+ return {
465
+ error: 'NotPermitted',
466
+ message: 'You need write access to this repo and cannot approve your own PR.',
467
+ };
468
+ }
469
+ try {
470
+ const token = await getAccessToken(accountId);
471
+ const gh = await submitPrReview(token, ctx.owner, ctx.name, ctx.number, {
472
+ event: 'APPROVE',
473
+ body,
474
+ });
475
+ const rowId = await upsertLocalReview(ctx.prId, viewerUserId, gh);
476
+ // ── The approval's SECOND and THIRD stamps — "an approved PR should drop off Pending,
477
+ // and may become ready to merge" ────────────────────────────────────────────────────
478
+ //
479
+ // 1. CLEAR THE VIEWER'S REVIEW REQUEST. GitHub deletes it the moment the review lands;
480
+ // `computeTriage.reviewRequestedFromMe` reads that table and nothing else, so without
481
+ // this the board keeps asking for a review that has been given. Free, local, and
482
+ // reconciled by the next `persistPr` either way.
483
+ await clearOwnReviewRequest(ctx.prId, accountId, viewerUserId);
484
+ // 2. RE-READ THE PR FROM GITHUB. This is the only half that can deliver the "…and it now
485
+ // shows as Ready to merge" the request asked for: `mergeStateStatus` is GitHub's
486
+ // protection-aware verdict and there is NO local derivation of it — an approval that
487
+ // satisfies branch protection flips `blocked → clean` on GitHub's side, asynchronously,
488
+ // and we can only observe it.
489
+ //
490
+ // ⚠ THE EXISTING SINGLE-PR MACHINERY, NOT A SECOND PATH: `resyncPrAfterWrite` is the
491
+ // same hydration-bust → `syncOnePr(waitForInFlight)` composition the review-comment
492
+ // tail and the live refresh poll both descend from, and it never throws.
493
+ //
494
+ // ⚠ IT IS A PER-ROUTE LATENCY DECISION, NOT A BLANKET RULE. One extra GitHub round
495
+ // trip (~1 GraphQL point) is affordable HERE because an approval is a deliberate,
496
+ // low-frequency human click — the same trip on a per-card poll is the 150-calls-to-
497
+ // paint-a-board failure the Pending board is designed around. And it is best-effort:
498
+ // GitHub often has not recomputed the merge state by the time we ask, in which case the
499
+ // board's own focus/interval refetch picks the flip up later. Stamp 1 has already made
500
+ // the card honest, so nothing here is load-bearing for correctness.
501
+ await resyncPrAfterWrite({ prId: ctx.prId, accountId, log: req.log });
502
+ // 3. …AND KEEP LOOKING. "Often not recomputed by the time we ask" is the norm, and the
503
+ // flip is updatedAt-silent — no walk would ever re-read it. The settle ladder
504
+ // (sync/pr-settle.ts) re-reads at ~5/15/45/120s until the merge state is known AND no
505
+ // longer `blocked` (a stale BLOCKED is a known value, so without `mergeStateNot` the
506
+ // ladder would stop on it at its first read). An approval that does not satisfy
507
+ // protection stays blocked and simply costs the ladder's four reads. The change signal
508
+ // tells every OTHER screen that the local stamps above moved — AWAITED, so it is raised
509
+ // before the reply and the write's own ordered `['repos']` read covers it.
510
+ schedulePrSettle(accountId, ctx.prId, asSyncLogger(req.log), {
511
+ mergeStateNot: 'blocked',
512
+ });
513
+ await notePrChangedForPr(accountId, ctx.prId);
514
+ const result = {
515
+ id: rowId,
516
+ authorId: viewerUserId,
517
+ state: 'approved',
518
+ body: gh.body,
519
+ submittedAt: new Date(gh.submittedAt).toISOString(),
520
+ url: gh.url,
521
+ };
522
+ return result;
523
+ }
524
+ catch (err) {
525
+ reply.status(502);
526
+ return {
527
+ error: 'GitHubError',
528
+ message: err instanceof Error ? err.message : String(err),
529
+ };
530
+ }
531
+ });
532
+ // Request changes. The SAME permission re-check as approve (GitHub 422s an author who
533
+ // requests changes on their own PR, so the author exclusion is real, not cosmetic). GitHub
534
+ // also refuses a REQUEST_CHANGES review with no text, so a blank message is sent as
535
+ // REQUEST_CHANGES_DEFAULT_BODY — the SPA's placeholder says so.
536
+ //
537
+ // Post-write: stamp the review row with its real state, clear the viewer's review request
538
+ // (GitHub deletes it on any submitted review), re-read the PR once, then raise the change
539
+ // signal. NO settle ladder: a request-changes review cannot lift `blocked`, `reviewDecision`
540
+ // is written synchronously by GitHub (the one resync reads it), and pr-settle has no
541
+ // reviewDecision expectation — an expectation-free ladder would stop on its first read.
542
+ app.post('/api/prs/:id/request-changes', { schema: approveSchema }, async (req, reply) => {
543
+ const { id } = req.params;
544
+ const { body } = (req.body ?? {});
545
+ const accountId = accountIdOf(req);
546
+ const ctx = await getPrWriteContext(id, accountId);
547
+ if (!ctx) {
548
+ reply.status(404);
549
+ return { error: 'NotFound', message: `PR ${id} not found` };
550
+ }
551
+ const viewerUserId = await getAccountUserId(accountId);
552
+ const canReview = viewerUserId != null &&
553
+ viewerUserId !== ctx.authorId &&
554
+ ['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '');
555
+ if (!canReview) {
556
+ reply.status(403);
557
+ return {
558
+ error: 'NotPermitted',
559
+ message: 'You need write access to this repo and cannot request changes on your own PR.',
560
+ };
561
+ }
562
+ const text = body?.trim() ? body : REQUEST_CHANGES_DEFAULT_BODY;
563
+ try {
564
+ const token = await getAccessToken(accountId);
565
+ const gh = await submitPrReview(token, ctx.owner, ctx.name, ctx.number, {
566
+ event: 'REQUEST_CHANGES',
567
+ body: text,
568
+ });
569
+ const rowId = await upsertLocalReview(ctx.prId, viewerUserId, gh, 'changes_requested');
570
+ await clearOwnReviewRequest(ctx.prId, accountId, viewerUserId);
571
+ await resyncPrAfterWrite({ prId: ctx.prId, accountId, log: req.log });
572
+ await notePrChangedForPr(accountId, ctx.prId);
573
+ const result = {
574
+ id: rowId,
575
+ authorId: viewerUserId,
576
+ state: 'changes_requested',
577
+ body: gh.body,
578
+ submittedAt: new Date(gh.submittedAt).toISOString(),
579
+ url: gh.url,
580
+ };
581
+ return result;
582
+ }
583
+ catch (err) {
584
+ reply.status(502);
585
+ return {
586
+ error: 'GitHubError',
587
+ message: err instanceof Error ? err.message : String(err),
588
+ };
589
+ }
590
+ });
591
+ // ---- Merge (CORE / free tier) ----
592
+ // The merge control's options — the repo's enabled merge methods + GitHub's live mergeability.
593
+ // Fetched lazily (only when the control opens) so the hot PR-detail path isn't slowed by a
594
+ // live GitHub call. Ownership-scoped via getPrWriteContext (→ 404).
595
+ app.get('/api/prs/:id/merge-options', async (req, reply) => {
596
+ const { id } = req.params;
597
+ const accountId = accountIdOf(req);
598
+ const ctx = await getPrWriteContext(id, accountId);
599
+ if (!ctx) {
600
+ reply.status(404);
601
+ return { error: 'NotFound', message: `PR ${id} not found` };
602
+ }
603
+ try {
604
+ const token = await getAccessToken(accountId);
605
+ const [cfg, m, queue, armed, armedQueues] = await Promise.all([
606
+ fetchRepoMergeConfig(token, ctx.owner, ctx.name),
607
+ fetchMergeability(token, ctx.owner, ctx.name, ctx.number),
608
+ // Merge-queue state is BEST-EFFORT: a repo without a queue, an older GHES, or a token
609
+ // that can't run the query must not fail the whole merge control. null → render nothing.
610
+ fetchMergeQueueState(token, ctx.owner, ctx.name, ctx.number).catch(() => null),
611
+ // Pierre-side auto-merge intent — a pure DB read, never a GitHub call.
612
+ getAutoMergeRequest(accountId, id),
613
+ // …as is its place in the repo's landing queue, so the armed panel can say "2nd of 5"
614
+ // without a second request.
615
+ resolveArmedQueues(accountId, armedQueueMarks()),
616
+ ]);
617
+ // THE PROBE ANSWERED, SO THE ROW LEARNS IT. The merge control resolves membership from the
618
+ // NEWER of this answer and the synced columns; without the stamp, a PR queued or dequeued
619
+ // on GitHub would keep contradicting this answer on every other screen until the next walk.
620
+ // Only a non-null answer is a statement — the `.catch(() => null)` above is "we never
621
+ // asked", and it writes nothing. NON-FATAL: this route was read-only, and a failed local
622
+ // write must not turn the merge control into "Couldn't load merge status".
623
+ if (queue) {
624
+ await stampPrMergeQueueStateNonFatal(id, accountId, queue.inQueue, queue.state, req.log);
625
+ }
626
+ const allowedMethods = ['merge', 'squash', 'rebase'].filter((meth) => meth === 'merge'
627
+ ? cfg.allowMergeCommit
628
+ : meth === 'squash'
629
+ ? cfg.allowSquashMerge
630
+ : cfg.allowRebaseMerge);
631
+ const conflicts = m.mergeable === false || m.mergeableState === 'dirty';
632
+ const behind = m.mergeableState === 'behind' || m.behindBy > 0;
633
+ const canWrite = ['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '');
634
+ const result = {
635
+ allowedMethods: [...allowedMethods],
636
+ defaultMethod: allowedMethods[0] ?? 'merge',
637
+ mergeable: m.mergeable,
638
+ mergeStateStatus: m.mergeableState,
639
+ conflicts,
640
+ behind,
641
+ blocked: m.mergeableState === 'blocked',
642
+ behindBy: m.behindBy,
643
+ baseRef: m.baseRef,
644
+ canUpdateBranch: behind && !conflicts,
645
+ canRebaseUpdate: !config.isCloud,
646
+ // Only report a queue when the base branch actually has one — `enabled:false` would
647
+ // otherwise make the control render a "merge queue" section for every repo.
648
+ mergeQueue: queue && queue.enabled
649
+ ? {
650
+ enabled: true,
651
+ inQueue: queue.inQueue,
652
+ position: queue.position,
653
+ state: queue.state,
654
+ // The ONE normaliser's reading, so the client never re-spells the raw enum.
655
+ entryState: queue.inQueue ? mergeQueueEntryStateFrom(queue.state) : null,
656
+ estimatedTimeToMergeMs: queue.estimatedTimeToMergeMs,
657
+ }
658
+ : null,
659
+ autoMerge: {
660
+ // Arming is offerable to anyone who could merge by hand — the watcher merges with
661
+ // THIS account's token, so it can never do more than the user already can. Permission
662
+ // is re-checked at arm time AND again at land time.
663
+ allowedByRepo: canWrite && allowedMethods.length > 0,
664
+ armed: armed ? withArmedQueueFields(armed, armedQueues) : null,
665
+ },
666
+ // The live review decision the queue probe already carries. `blocked: true` above is a
667
+ // restatement of GitHub's word and explains nothing; this is the one field on the
668
+ // payload that can name WHICH HALF of branch protection is unmet, and it costs no extra
669
+ // call — fetchMergeQueueState selects it, and until now the route dropped it (and threw
670
+ // the whole probe away on any repo without a merge queue, which is most of them).
671
+ //
672
+ // ⚠ SPREAD, never assigned: `queue` is null when the probe FAILED, and "we never asked"
673
+ // must not arrive at the client wearing the same null GitHub uses for "this base branch
674
+ // requires no review". Absent → the merge control falls back to the synced PR row.
675
+ ...(queue ? { reviewDecision: reviewDecisionFrom(queue.reviewDecision) } : {}),
676
+ };
677
+ return result;
678
+ }
679
+ catch (err) {
680
+ reply.status(502);
681
+ return { error: 'GitHubError', message: err instanceof Error ? err.message : String(err) };
682
+ }
683
+ });
684
+ // Merge the PR (native GitHub merge; merge/squash/rebase). Re-checks write+ permission
685
+ // (author allowed — GitHub lets an author merge their own PR) and pre-checks conflicts, then
686
+ // pins the merge to the current head SHA (409 if it moved). Optimistically stamps merged.
687
+ app.post('/api/prs/:id/merge', { schema: mergeSchema }, async (req, reply) => {
688
+ const { id } = req.params;
689
+ const { method } = req.body;
690
+ const accountId = accountIdOf(req);
691
+ const ctx = await getPrWriteContext(id, accountId);
692
+ if (!ctx) {
693
+ reply.status(404);
694
+ return { error: 'NotFound', message: `PR ${id} not found` };
695
+ }
696
+ if (!['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '')) {
697
+ reply.status(403);
698
+ return { error: 'NotPermitted', message: 'You need write access to merge this PR.' };
699
+ }
700
+ try {
701
+ const token = await getAccessToken(accountId);
702
+ // Live conflict pre-check — never attempt a merge on a conflicting PR. GitHub would 405
703
+ // anyway; a 409 here is clearer.
704
+ //
705
+ // ⚠ THE SENTENCE NAMES NO TIER AND POINTS NOWHERE, for the same reason as the two on the
706
+ // update-branch route below: conflict resolution is CORE, free and in-app in local mode,
707
+ // and its button sits on the pane this error lands on. Telling the reader to go to GitHub
708
+ // is now false. The error CODE and the `conflicts: true` flag are unchanged; the SPA reads
709
+ // those, never the prose.
710
+ const m = await fetchMergeability(token, ctx.owner, ctx.name, ctx.number);
711
+ if (m.mergeable === false || m.mergeableState === 'dirty') {
712
+ reply.status(409);
713
+ return {
714
+ error: 'Conflicts',
715
+ conflicts: true,
716
+ message: 'This PR conflicts with the base branch. Resolve the conflicts first.',
717
+ };
718
+ }
719
+ const info = await fetchPrHeadInfo(token, ctx.owner, ctx.name, ctx.number);
720
+ const out = await mergePullRequest(token, ctx.owner, ctx.name, ctx.number, {
721
+ method,
722
+ expectedHeadSha: info.headSha,
723
+ });
724
+ if (!out.ok) {
725
+ const status = out.reason === 'method_disallowed' ? 422 : 409;
726
+ reply.status(status);
727
+ return {
728
+ error: out.reason === 'head_moved'
729
+ ? 'HeadMoved'
730
+ : out.reason === 'method_disallowed'
731
+ ? 'MethodNotAllowed'
732
+ : 'NotMergeable',
733
+ message: out.message,
734
+ };
735
+ }
736
+ const viewerUserId = await getAccountUserId(accountId);
737
+ await markPrMergedLocally(id, accountId, viewerUserId);
738
+ // The trunk just moved: every OTHER open PR's merge verdict is now about a base that no
739
+ // longer exists, and none of them bumped `updatedAt`. Re-read them at ~30s/~90s, and
740
+ // raise the change signal for the stamp above — awaited, so it is raised BEFORE the reply
741
+ // (the re-reads themselves stay in the background). Never throws.
742
+ await noteMergeLanded(accountId, id, asSyncLogger(req.log));
743
+ const result = { merged: true, sha: out.sha, state: 'merged' };
744
+ return result;
745
+ }
746
+ catch (err) {
747
+ reply.status(502);
748
+ return { error: 'GitHubError', message: err instanceof Error ? err.message : String(err) };
749
+ }
750
+ });
751
+ // ---- GitHub's native merge QUEUE ----
752
+ //
753
+ // When the base branch has a merge queue, "Merge" is not the offerable action — GitHub
754
+ // requires the PR to go through the queue — so the merge control swaps in "Add to merge
755
+ // queue". Both verbs are GraphQL-only (no REST equivalent); see github/mutations.ts.
756
+ // Enqueue. Re-checks write permission, then pins the enqueue to the LIVE head SHA so the
757
+ // queue can't pick up commits the user hasn't seen (the same consent anchor as a merge).
758
+ app.post('/api/prs/:id/merge-queue', { schema: mergeQueueSchema }, async (req, reply) => {
759
+ const { id } = req.params;
760
+ const accountId = accountIdOf(req);
761
+ const ctx = await getPrWriteContext(id, accountId);
762
+ if (!ctx) {
763
+ reply.status(404);
764
+ return { error: 'NotFound', message: `PR ${id} not found` };
765
+ }
766
+ if (!['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '')) {
767
+ reply.status(403);
768
+ return { error: 'NotPermitted', message: 'You need write access to queue this PR.' };
769
+ }
770
+ try {
771
+ const token = await getAccessToken(accountId);
772
+ const queue = await fetchMergeQueueState(token, ctx.owner, ctx.name, ctx.number);
773
+ // A non-null probe is a positive answer about membership whichever branch we take next —
774
+ // including the "no queue configured" 400 below, where `inQueue:false` is exactly the
775
+ // fact that clears a stale `true` off the row. `null` means the PR could not be read at
776
+ // all, so it stamps nothing.
777
+ if (queue) {
778
+ await stampPrMergeQueueStateNonFatal(id, accountId, queue.inQueue, queue.state, req.log);
779
+ }
780
+ if (!queue || !queue.enabled) {
781
+ // 400, not a silent no-op: enqueuing where there is no queue would otherwise fail
782
+ // deep inside GraphQL with an opaque message.
783
+ reply.status(400);
784
+ return {
785
+ error: 'NoMergeQueue',
786
+ message: 'This PR’s base branch has no merge queue configured.',
787
+ };
788
+ }
789
+ if (queue.inQueue) {
790
+ const already = {
791
+ inQueue: true,
792
+ position: queue.position,
793
+ state: queue.state,
794
+ };
795
+ return already;
796
+ }
797
+ const info = await fetchPrHeadInfo(token, ctx.owner, ctx.name, ctx.number);
798
+ const entry = await enqueuePullRequestOnQueue(token, ctx.prNodeId, info.headSha);
799
+ // GitHub has accepted the enqueue, so membership is true even when the mutation's
800
+ // nullable payload gave us no entry state (it can 200 with a null entry — see
801
+ // GqlEnqueueResponse). `null` there stores "queued, state unknown", never "not queued".
802
+ // ⚠ NON-FATAL: GitHub has ACCEPTED the enqueue, so this route may not fail from here on —
803
+ // a 502 would tell the reader it did not happen and invite a second enqueue.
804
+ await stampPrMergeQueueStateNonFatal(id, accountId, true, entry.state, req.log);
805
+ const result = {
806
+ inQueue: true,
807
+ position: entry.position,
808
+ state: entry.state,
809
+ };
810
+ return result;
811
+ }
812
+ catch (err) {
813
+ reply.status(502);
814
+ return { error: 'GitHubError', message: err instanceof Error ? err.message : String(err) };
815
+ }
816
+ });
817
+ // Dequeue. Idempotent: removing a PR that isn't queued reports the already-out state — and it
818
+ // ASKS FIRST rather than trusting GitHub's mutation to be a no-op on a PR it does not hold.
819
+ app.delete('/api/prs/:id/merge-queue', { schema: idParamSchema }, async (req, reply) => {
820
+ const { id } = req.params;
821
+ const accountId = accountIdOf(req);
822
+ const ctx = await getPrWriteContext(id, accountId);
823
+ if (!ctx) {
824
+ reply.status(404);
825
+ return { error: 'NotFound', message: `PR ${id} not found` };
826
+ }
827
+ if (!['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '')) {
828
+ reply.status(403);
829
+ return {
830
+ error: 'NotPermitted',
831
+ message: 'You need write access to remove this PR from the queue.',
832
+ };
833
+ }
834
+ try {
835
+ const token = await getAccessToken(accountId);
836
+ // ⚠ PROBE BEFORE THE MUTATION. "Remove from queue" now renders on the COLLAPSED merge row,
837
+ // decided from synced columns that can be minutes old, so the click can arrive for a PR
838
+ // GitHub has already landed, ejected or seen dequeued elsewhere. What
839
+ // `dequeuePullRequest` does with a PR that is not queued is GitHub's business and
840
+ // unverified here; asking first makes that case a plain success that also CORRECTS the
841
+ // stale row. A probe that fails or cannot read the PR (null) falls through to the
842
+ // mutation, which then speaks for itself — the old behaviour, never a new refusal.
843
+ const queue = await fetchMergeQueueState(token, ctx.owner, ctx.name, ctx.number).catch(() => null);
844
+ if (queue && !queue.inQueue) {
845
+ if (queue.prState === 'MERGED' && ctx.state === 'open') {
846
+ // ⚠ THE QUEUE ALREADY LANDED IT — the likeliest reason a queued row's "Remove from
847
+ // queue" meets a PR GitHub no longer holds. Stamping only "not queued" would leave an
848
+ // OPEN row out of the queue, and the refetch this answer triggers would offer "Merge ▾"
849
+ // for a PR that has merged. Record the landing instead (which also clears both queue
850
+ // columns), as the watcher does when it sees the same probe say MERGED. The merger is
851
+ // not known here (the queue merged it, on whoever's enqueue), so it stays null until
852
+ // the next walk reads it. Only over an OPEN row: one the sync has already marked merged
853
+ // carries the real merge time and merger, and must not be overwritten with guesses.
854
+ // Non-fatal: GitHub's answer stands whatever the DB does.
855
+ try {
856
+ await markPrMergedLocally(id, accountId, null);
857
+ await noteMergeLanded(accountId, id, asSyncLogger(req.log));
858
+ }
859
+ catch (err) {
860
+ req.log.warn({ err, prId: id }, 'merge queue: could not record the landing on the PR row');
861
+ }
862
+ }
863
+ else {
864
+ await stampPrMergeQueueStateNonFatal(id, accountId, false, null, req.log);
865
+ }
866
+ const out = { inQueue: false, position: null, state: null };
867
+ return out;
868
+ }
869
+ await dequeuePullRequestFromQueue(token, ctx.prNodeId);
870
+ // Stamped for the same reason the enqueue is, and it matters more here: without it the
871
+ // row keeps claiming `queued` until the next walk, so the SPA re-reads the PR it just
872
+ // removed and offers "Remove from queue" again. ⚠ NON-FATAL: GitHub has accepted the
873
+ // dequeue, so a failed local write may not turn this into a 502.
874
+ await stampPrMergeQueueStateNonFatal(id, accountId, false, null, req.log);
875
+ const result = { inQueue: false, position: null, state: null };
876
+ return result;
877
+ }
878
+ catch (err) {
879
+ reply.status(502);
880
+ return { error: 'GitHubError', message: err instanceof Error ? err.message : String(err) };
881
+ }
882
+ });
883
+ // ---- Auto-merge ("merge when ready") ----
884
+ //
885
+ // Pierre's OWN watcher, deliberately NOT GitHub's `enablePullRequestAutoMerge`: that
886
+ // mutation 422s unless the requirements are already met and needs repo settings we can't
887
+ // assume. `merge/auto-merge-runner.ts` re-evaluates each armed intent on a cron tick.
888
+ //
889
+ // Arming pins the CURRENT head SHA. A later push disarms the intent instead of merging —
890
+ // arming is consent to merge THIS code, not whatever lands next.
891
+ app.post('/api/prs/:id/auto-merge', { schema: armMergeSchema }, async (req, reply) => {
892
+ const { id } = req.params;
893
+ const { mergeMethod, updateStrategy } = req.body;
894
+ const accountId = accountIdOf(req);
895
+ const ctx = await getPrWriteContext(id, accountId);
896
+ if (!ctx) {
897
+ reply.status(404);
898
+ return { error: 'NotFound', message: `PR ${id} not found` };
899
+ }
900
+ // Permission is checked HERE and again at land time — a user can lose write access
901
+ // between arming and the merge, and the watcher must not act on a stale grant.
902
+ if (!['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '')) {
903
+ reply.status(403);
904
+ return {
905
+ error: 'NotPermitted',
906
+ message: 'You need write access to arm auto-merge on this PR.',
907
+ };
908
+ }
909
+ if (ctx.state !== 'open') {
910
+ reply.status(409);
911
+ return { error: 'NotOpen', message: `This PR is already ${ctx.state}.` };
912
+ }
913
+ try {
914
+ const token = await getAccessToken(accountId);
915
+ // The LIVE head, never the possibly-stale synced one: arming against a SHA that is
916
+ // already superseded would disarm itself on the very first tick.
917
+ const info = await fetchPrHeadInfo(token, ctx.owner, ctx.name, ctx.number);
918
+ // The head pin is blind to a RETARGET (PATCH pulls/{n} with a new `base` leaves head.sha
919
+ // untouched), so the watcher guards the target branch too — against the last SYNCED base
920
+ // ref, which is the branch the SPA was showing the user. That is only a valid consent
921
+ // record if it agrees with GitHub right now; if the PR was retargeted since the last
922
+ // sync, say so instead of arming an intent the watcher would immediately disarm.
923
+ const syncedBaseRef = await getSyncedBaseRef(accountId, id);
924
+ if (syncedBaseRef !== info.baseRef) {
925
+ reply.status(409);
926
+ return {
927
+ error: 'StaleBase',
928
+ message: `This PR now targets ${info.baseRef}; Limn last saw ${syncedBaseRef ?? 'no base branch'}. Sync the repository, then arm auto-merge again.`,
929
+ };
930
+ }
931
+ // Does the base branch have a merge queue? Stamped on the intent so the watcher
932
+ // enqueues instead of direct-merging (which GitHub refuses on a queue-protected
933
+ // branch). Best-effort like merge-options' read: an older GHES or a token that can't
934
+ // run the query arms a direct-merge intent, exactly what those repos need.
935
+ const queue = await fetchMergeQueueState(token, ctx.owner, ctx.name, ctx.number).catch(() => null);
936
+ // An answer is an answer, whichever way this route then goes — and the AlreadyQueued 409
937
+ // below is the case that matters: the reader pressed "Merge when ready" because their
938
+ // screen did not know the PR was queued, and the row is what every screen reads.
939
+ // NON-FATAL: a failed local copy of GitHub's answer must not refuse the arm.
940
+ if (queue) {
941
+ await stampPrMergeQueueStateNonFatal(id, accountId, queue.inQueue, queue.state, req.log);
942
+ }
943
+ if (queue?.inQueue) {
944
+ // Already in the queue ⇒ landing is already arranged; an armed intent could only
945
+ // duplicate or contradict it.
946
+ reply.status(409);
947
+ return {
948
+ error: 'AlreadyQueued',
949
+ message: 'This PR is already in the merge queue — it will land on its own.',
950
+ };
951
+ }
952
+ const armed = await armAutoMerge(accountId, id, {
953
+ mergeMethod,
954
+ updateStrategy: updateStrategy ?? 'none',
955
+ viaMergeQueue: queue?.enabled === true,
956
+ expectedHeadOid: info.headSha,
957
+ // ⚠ THE LIVE REF, PINNED — not `syncedBaseRef`, even though the guard above has just
958
+ // proven the two equal. They are equal AT THIS INSTANT; the synced column belongs to the
959
+ // sync and may be rewritten at any moment, and the watcher used to re-read it every tick
960
+ // and disarm on any disagreement. Recording GitHub's own answer here makes the consent a
961
+ // fact about the click rather than a lookup that can change underneath it.
962
+ expectedBaseRef: info.baseRef,
963
+ expiresAt: new Date(Date.now() + AUTO_MERGE_TTL_MS),
964
+ });
965
+ // The full row, identity and `phase: 'pending_first_check'` included — the SPA seeds its
966
+ // progress card from this response, so the surface appears on the click rather than on
967
+ // the next poll (and, before it, the watcher's next tick, up to two minutes away).
968
+ // The landing position is resolved AFTER the arm, so the fifth click already reads "5 of
969
+ // 5" instead of appearing to be next up until the first poll corrects it.
970
+ return withArmedQueueFields(armed, await resolveArmedQueues(accountId, armedQueueMarks()));
971
+ }
972
+ catch (err) {
973
+ reply.status(502);
974
+ return { error: 'GitHubError', message: err instanceof Error ? err.message : String(err) };
975
+ }
976
+ });
977
+ // Disarm. 204 whether or not anything was armed (idempotent). When the WATCHER had already
978
+ // added the PR to the merge queue (`enqueuedAt` set), cancelling must also remove that
979
+ // entry — otherwise "cancel" leaves the queue to land the PR anyway. The row is deleted
980
+ // FIRST so the cancel always wins (the watcher's compare-and-set sees the row gone even if
981
+ // the dequeue then fails); the dequeue itself is best-effort, since the entry may already
982
+ // be gone and a human queue entry is not ours to remove (enqueuedAt is null for those).
983
+ app.delete('/api/prs/:id/auto-merge', { schema: idParamSchema }, async (req, reply) => {
984
+ const { id } = req.params;
985
+ const accountId = accountIdOf(req);
986
+ const ctx = await getPrWriteContext(id, accountId);
987
+ if (!ctx) {
988
+ reply.status(404);
989
+ return { error: 'NotFound', message: `PR ${id} not found` };
990
+ }
991
+ const intent = await getAutoMergeRequest(accountId, id);
992
+ await disarmAutoMerge(accountId, id);
993
+ if (intent?.state === 'armed' && intent.enqueuedAt != null) {
994
+ let dequeued = false;
995
+ try {
996
+ const token = await getAccessToken(accountId);
997
+ await dequeuePullRequestFromQueue(token, ctx.prNodeId);
998
+ dequeued = true;
999
+ }
1000
+ catch (err) {
1001
+ req.log.warn({ err, prId: id }, 'auto-merge: disarmed, but could not remove the PR from the merge queue');
1002
+ }
1003
+ // A dequeue GitHub accepted is a positive "not queued" — stamp it like the queue verbs do,
1004
+ // or every screen keeps drawing the queue status line for a PR we just took out. Outside the
1005
+ // dequeue's try, so its log line only ever reports a dequeue that really failed.
1006
+ if (dequeued)
1007
+ await stampPrMergeQueueStateNonFatal(id, accountId, false, null, req.log);
1008
+ }
1009
+ reply.status(204);
1010
+ return null;
1011
+ });
1012
+ // Every armed (and recently-resolved) intent for the account. A pure DB read — this is what
1013
+ // the SPA polls to raise its "auto-merge landed" toast and to draw the cross-PR progress
1014
+ // stack, so it must never touch GitHub. Each row carries its own repo/PR identity and
1015
+ // `phase` precisely so that stack needs no second request per armed PR (a per-PR
1016
+ // merge-options fetch would be ~3 GitHub calls each); adding anything live here would also
1017
+ // break the `read` rate tier this route sits on. See api/plugins/rate-limit.ts.
1018
+ //
1019
+ // Registered here rather than in its own route file because it is the cross-PR view of the
1020
+ // per-PR routes directly above; keeping the pair together is what stops the two drifting.
1021
+ app.get('/api/auto-merge', async (req) => {
1022
+ const accountId = accountIdOf(req);
1023
+ // The per-repo landing order rides along (still a pure DB read — one tiny extra scan, no
1024
+ // GitHub). Computing it HERE rather than storing it on the row is deliberate: the order is
1025
+ // a fact about the whole set, it changes whenever anyone arms or cancels, and a stored
1026
+ // position would be wrong for every row but the one the watcher last touched.
1027
+ const [requests, queues] = await Promise.all([
1028
+ listAutoMergeRequests(accountId),
1029
+ resolveArmedQueues(accountId, armedQueueMarks()),
1030
+ ]);
1031
+ const result = {
1032
+ requests: requests.map((r) => withArmedQueueFields(r, queues)),
1033
+ };
1034
+ return result;
1035
+ });
1036
+ // Close a PR WITHOUT merging (CORE / free tier). Reversible on GitHub (reopen), so no
1037
+ // head-SHA pin. Permitted for anyone with WRITE+ OR the PR author (GitHub's own rule),
1038
+ // mirrored by viewerCanClose on the detail payload; re-checked here. Only an OPEN PR can be
1039
+ // closed (a merged/closed one → 409). Optimistically stamps state='closed'.
1040
+ app.post('/api/prs/:id/close', async (req, reply) => {
1041
+ const { id } = req.params;
1042
+ const accountId = accountIdOf(req);
1043
+ const ctx = await getPrWriteContext(id, accountId);
1044
+ if (!ctx) {
1045
+ reply.status(404);
1046
+ return { error: 'NotFound', message: `PR ${id} not found` };
1047
+ }
1048
+ const viewerUserId = await getAccountUserId(accountId);
1049
+ const canClose = ['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '') ||
1050
+ (viewerUserId != null && viewerUserId === ctx.authorId);
1051
+ if (!canClose) {
1052
+ reply.status(403);
1053
+ return {
1054
+ error: 'NotPermitted',
1055
+ message: 'You need write access or to be the PR author to close this PR.',
1056
+ };
1057
+ }
1058
+ if (ctx.state !== 'open') {
1059
+ reply.status(409);
1060
+ return {
1061
+ error: 'NotOpen',
1062
+ message: `This PR is already ${ctx.state}.`,
1063
+ };
1064
+ }
1065
+ try {
1066
+ const token = await getAccessToken(accountId);
1067
+ const out = await closePullRequest(token, ctx.owner, ctx.name, ctx.number);
1068
+ if (!out.ok) {
1069
+ reply.status(out.reason === 'not_found' ? 404 : 502);
1070
+ return {
1071
+ error: out.reason === 'not_found' ? 'NotFound' : 'GitHubError',
1072
+ message: out.message,
1073
+ };
1074
+ }
1075
+ await markPrClosedLocally(id, accountId);
1076
+ // A closed PR leaves every Pending tab: signal the stamp before replying. Never throws.
1077
+ await notePrChangedForPr(accountId, id);
1078
+ const result = { closed: true, state: 'closed' };
1079
+ return result;
1080
+ }
1081
+ catch (err) {
1082
+ reply.status(502);
1083
+ return { error: 'GitHubError', message: err instanceof Error ? err.message : String(err) };
1084
+ }
1085
+ });
1086
+ // Reopen a CLOSED PR (CORE / free tier) — the inverse of the close above and permitted by the
1087
+ // same rule: WRITE+ OR the PR author, mirrored by viewerCanReopen on the detail payload and
1088
+ // re-checked here. Only a CLOSED PR can be reopened; an open one and a MERGED one both 409
1089
+ // (GitHub cannot un-merge). Optimistically stamps state='open' + closedAt=null AND writes the
1090
+ // pr_reopened event, because that stamp is exactly what stops the next sync from writing it.
1091
+ app.post('/api/prs/:id/reopen', { schema: idParamSchema }, async (req, reply) => {
1092
+ const { id } = req.params;
1093
+ const accountId = accountIdOf(req);
1094
+ const ctx = await getPrWriteContext(id, accountId);
1095
+ if (!ctx) {
1096
+ reply.status(404);
1097
+ return { error: 'NotFound', message: `PR ${id} not found` };
1098
+ }
1099
+ const viewerUserId = await getAccountUserId(accountId);
1100
+ const canReopen = ['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '') ||
1101
+ (viewerUserId != null && viewerUserId === ctx.authorId);
1102
+ if (!canReopen) {
1103
+ reply.status(403);
1104
+ return {
1105
+ error: 'NotPermitted',
1106
+ message: 'You need write access or to be the PR author to reopen this PR.',
1107
+ };
1108
+ }
1109
+ // ⚠ TWO 409s, NOT ONE — 'merged' and 'open' are different facts and the merged one is
1110
+ // permanent, so they must not share a sentence.
1111
+ if (ctx.state !== 'closed') {
1112
+ reply.status(409);
1113
+ return {
1114
+ error: ctx.state === 'merged' ? 'AlreadyMerged' : 'NotClosed',
1115
+ message: ctx.state === 'merged'
1116
+ ? 'This PR was merged. A merged PR can’t be reopened.'
1117
+ : 'This PR is already open.',
1118
+ };
1119
+ }
1120
+ try {
1121
+ const token = await getAccessToken(accountId);
1122
+ const out = await reopenPullRequest(token, ctx.owner, ctx.name, ctx.number);
1123
+ if (!out.ok) {
1124
+ // ⚠ `not_reopenable` is a 409, not a 502. GitHub's usual refusal is the deleted head
1125
+ // branch — nothing is broken and no retry will help, so the answer is the conflict code
1126
+ // plus GitHub's own sentence, which the SPA prints verbatim (4xx bodies stay verbatim in
1127
+ // cloud; only 5xx are made generic — see docs/SECURITY.md).
1128
+ reply.status(out.reason === 'not_found' ? 404 : out.reason === 'not_reopenable' ? 409 : 502);
1129
+ return {
1130
+ error: out.reason === 'not_found'
1131
+ ? 'NotFound'
1132
+ : out.reason === 'not_reopenable'
1133
+ ? 'NotReopenable'
1134
+ : 'GitHubError',
1135
+ message: out.message,
1136
+ };
1137
+ }
1138
+ // ⚠ Takes the viewer id the permission check already resolved — no second lookup.
1139
+ await markPrReopenedLocally(id, accountId, viewerUserId);
1140
+ // The reopened PR re-enters the board: signal the stamp before replying. Never throws.
1141
+ await notePrChangedForPr(accountId, id);
1142
+ const result = { reopened: true, state: 'open' };
1143
+ return result;
1144
+ }
1145
+ catch (err) {
1146
+ reply.status(502);
1147
+ return { error: 'GitHubError', message: err instanceof Error ? err.message : String(err) };
1148
+ }
1149
+ });
1150
+ // Update the PR's branch from the base/trunk before merging. Local: clone-based rebase
1151
+ // (default) or merge, aborting on ANY conflict (no free-tier resolution → 409). Cloud: GitHub's
1152
+ // native update-branch (merge-only, clone-free). Gated on write+ permission.
1153
+ app.post('/api/prs/:id/update-branch', { schema: updateBranchSchema }, async (req, reply) => {
1154
+ const { id } = req.params;
1155
+ const { strategy } = (req.body ?? {});
1156
+ const accountId = accountIdOf(req);
1157
+ const ctx = await getPrWriteContext(id, accountId);
1158
+ if (!ctx) {
1159
+ reply.status(404);
1160
+ return { error: 'NotFound', message: `PR ${id} not found` };
1161
+ }
1162
+ if (!['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '')) {
1163
+ reply.status(403);
1164
+ return { error: 'NotPermitted', message: 'You need write access to update this branch.' };
1165
+ }
1166
+ try {
1167
+ const token = await getAccessToken(accountId);
1168
+ // Never attempt an update on a conflicting PR.
1169
+ //
1170
+ // ⚠ THE SENTENCE NAMES NO TIER AND POINTS NOWHERE. Conflict resolution is CORE and free,
1171
+ // in-app in local mode, and its button is on this same pane — a sentence telling the
1172
+ // reader to click a visible button is verbiage, and one telling them to go to GitHub is
1173
+ // now false. The error CODE and the `conflicts: true` flag are unchanged; the SPA reads
1174
+ // those, never the prose.
1175
+ const m = await fetchMergeability(token, ctx.owner, ctx.name, ctx.number);
1176
+ if (m.mergeable === false || m.mergeableState === 'dirty') {
1177
+ reply.status(409);
1178
+ return {
1179
+ error: 'Conflicts',
1180
+ conflicts: true,
1181
+ message: 'This PR conflicts with the base branch. Resolve the conflicts first.',
1182
+ };
1183
+ }
1184
+ const info = await fetchPrHeadInfo(token, ctx.owner, ctx.name, ctx.number);
1185
+ if (config.isCloud) {
1186
+ // Cloud: native update-branch (merge trunk in). No clone/git on the host.
1187
+ const out = await updatePullRequestBranch(token, ctx.owner, ctx.name, ctx.number, info.headSha);
1188
+ if (!out.ok) {
1189
+ reply.status(409);
1190
+ return out.reason === 'head_moved'
1191
+ ? { error: 'HeadMoved', headMoved: true, message: out.message }
1192
+ : { error: 'Conflicts', conflicts: true, message: out.message };
1193
+ }
1194
+ // ⚠ SETTLE, THEN ANSWER. This route used to stamp nothing and resync nothing, so the
1195
+ // SPA's board refetch re-read `behind` and the old head and the Update-branch card came
1196
+ // straight back. GitHub merges the base in ASYNCHRONOUSLY (202, no sha), so the only
1197
+ // expectation we can state is "the head moved off the one we updated from"; the inline
1198
+ // wait is deadline-bounded and the rest goes to the settle ladder. Never throws.
1199
+ await settlePrAfterWrite({
1200
+ accountId,
1201
+ prId: ctx.prId,
1202
+ log: asSyncLogger(req.log),
1203
+ expect: { headNot: info.headSha },
1204
+ });
1205
+ const result = { ok: true, headSha: null, strategy: 'merge' };
1206
+ return result;
1207
+ }
1208
+ // Local: clone-based rebase (default) or merge from trunk. Nothing on this path resolves a
1209
+ // conflict: any conflict aborts with CONFLICTS_UNRESOLVED (→ the 409 below). Dynamic
1210
+ // import so the clone/git machinery is only loaded on this path (never in cloud).
1211
+ const strat = strategy === 'merge' ? 'merge' : 'rebase';
1212
+ const { updatePrBranchFromTrunk } = await import('../../coding/merge.js');
1213
+ const out = await updatePrBranchFromTrunk({
1214
+ accountId,
1215
+ owner: ctx.owner,
1216
+ name: ctx.name,
1217
+ prNumber: ctx.number,
1218
+ headRef: info.headRef,
1219
+ headSha: info.headSha,
1220
+ trunk: info.baseRef,
1221
+ strategy: strat,
1222
+ });
1223
+ // The push LANDED — settle-and-verify against the exact sha it pushed (an already-current
1224
+ // branch returns its unchanged head, which is then trivially met). Never throws.
1225
+ await settlePrAfterWrite({
1226
+ accountId,
1227
+ prId: ctx.prId,
1228
+ log: asSyncLogger(req.log),
1229
+ expect: { headSha: out.headSha },
1230
+ });
1231
+ const result = { ok: true, headSha: out.headSha, strategy: out.strategy };
1232
+ return result;
1233
+ }
1234
+ catch (err) {
1235
+ const code = err?.code;
1236
+ if (code === 'CONFLICTS_UNRESOLVED') {
1237
+ reply.status(409);
1238
+ return {
1239
+ error: 'Conflicts',
1240
+ conflicts: true,
1241
+ message: 'Updating from the base branch hit conflicts. Resolve them first, then update.',
1242
+ };
1243
+ }
1244
+ if (code === 'HEAD_MOVED') {
1245
+ reply.status(409);
1246
+ return { error: 'HeadMoved', headMoved: true, message: err.message };
1247
+ }
1248
+ if (code === 'PUSH_DENIED') {
1249
+ reply.status(403);
1250
+ return { error: 'NotPermitted', message: err.message };
1251
+ }
1252
+ reply.status(502);
1253
+ return { error: 'GitHubError', message: err instanceof Error ? err.message : String(err) };
1254
+ }
1255
+ });
1256
+ // Add ONE inline review comment, posted immediately. Validates the requested
1257
+ // (path, line, side) lands on an addable diff line; if not, re-anchors to the
1258
+ // file's first changed line; if the file has no changes at all, returns a
1259
+ // not-anchored result without posting.
1260
+ //
1261
+ // After a successful post it also RESYNCS this PR (sync/resync-after-write.ts) and
1262
+ // VERIFIES the comment row landed locally, returning `visible`/`threadId` — this is the
1263
+ // one write with no optimistic local stamp (REST hands back no review-THREAD node id, so
1264
+ // a forged row would have no reply/resolve identity), so it re-reads GitHub instead. The
1265
+ // client can then render the real thread rather than promise a future sync.
1266
+ app.post('/api/prs/:id/review-comment', { schema: reviewCommentSchema }, async (req, reply) => {
1267
+ const { id } = req.params;
1268
+ const { path, line, body } = req.body;
1269
+ const side = req.body.side ?? 'RIGHT';
1270
+ const accountId = accountIdOf(req);
1271
+ const ctx = await getPrWriteContext(id, accountId);
1272
+ if (!ctx) {
1273
+ reply.status(404);
1274
+ return { error: 'NotFound', message: `PR ${id} not found` };
1275
+ }
1276
+ try {
1277
+ const token = await getAccessToken(accountId);
1278
+ // Resolve the LIVE head (not the possibly-stale DB head): commit_id must
1279
+ // pin to the same commit whose diff we validate the line against below,
1280
+ // or GitHub 422s the line as "not part of the diff".
1281
+ const head = await fetchHeadShaFor(token, ctx.owner, ctx.name, ctx.number);
1282
+ // Find the requested file's REST patch (header-less) to validate anchoring.
1283
+ const firstFiles = await fetchPrFilesWithPatch(token, ctx.owner, ctx.name, ctx.number);
1284
+ // The Changes tab pages past the first 100 files ("Load next 100 files"), so a reader can
1285
+ // comment on file 150: look further only when the first page did not hold it.
1286
+ const file = firstFiles.files.find((f) => f.filename === path) ??
1287
+ (firstFiles.truncated
1288
+ ? await findPrFileWithPatch(token, ctx.owner, ctx.name, ctx.number, path)
1289
+ : null) ??
1290
+ undefined;
1291
+ const anchors = buildFileAnchors(path, file?.patch ?? null);
1292
+ // A single-file AnchorIndex for the pure helpers.
1293
+ const index = new Map([[path, anchors]]);
1294
+ let finalLine = line;
1295
+ let finalSide = side;
1296
+ let anchored = true;
1297
+ if (!isFindingAnchored(index, path, line, side)) {
1298
+ const fb = fallbackAnchor(index, path);
1299
+ if (!fb) {
1300
+ // The file has no changes in the diff → can't post inline. Nothing was
1301
+ // posted, so there is nothing to make visible.
1302
+ const result = {
1303
+ commentId: null,
1304
+ url: null,
1305
+ line,
1306
+ side,
1307
+ anchored: false,
1308
+ visible: false,
1309
+ threadId: null,
1310
+ };
1311
+ return result;
1312
+ }
1313
+ finalLine = fb.line;
1314
+ finalSide = fb.side;
1315
+ anchored = false;
1316
+ }
1317
+ const gh = await postInlineComment(token, ctx.owner, ctx.name, ctx.number, { commitId: head, path, line: finalLine, side: finalSide, body });
1318
+ // THE COMMENT NOW EXISTS ON GITHUB. From here nothing may fail the request: the
1319
+ // catch below maps a 422 to "couldn't place" and everything else to a 502, either
1320
+ // of which would tell the user a live comment didn't post — and invite a retry that
1321
+ // would double-post. `confirmPostedReviewComment` never throws (its own guard), and
1322
+ // it is awaited outside nothing else, so the two guards are independent.
1323
+ const { visible, threadId } = await confirmPostedReviewComment({
1324
+ prId: ctx.prId,
1325
+ accountId,
1326
+ githubDatabaseId: String(gh.databaseId),
1327
+ githubNodeId: gh.nodeId,
1328
+ log: req.log,
1329
+ });
1330
+ // A new thread is a board-visible move whether or not the resync confirmed it (the resync
1331
+ // raises the signal itself only when it stored something). Before the reply, like every
1332
+ // other write route; never throws, so the "may not fail after the 201" rule holds.
1333
+ await notePrChangedForPr(accountId, ctx.prId);
1334
+ const result = {
1335
+ commentId: gh.databaseId,
1336
+ url: gh.url,
1337
+ line: finalLine,
1338
+ side: finalSide,
1339
+ anchored,
1340
+ visible,
1341
+ threadId,
1342
+ };
1343
+ return result;
1344
+ }
1345
+ catch (err) {
1346
+ const message = err instanceof Error ? err.message : String(err);
1347
+ // A 422 means GitHub rejected the line as not part of the diff (e.g. the
1348
+ // head shifted between our diff fetch and the post). Surface it as the
1349
+ // structured "couldn't place" result so the FE's recovery UX engages
1350
+ // (open on GitHub) instead of a generic error toast.
1351
+ if (/->\s*422\b/.test(message)) {
1352
+ // Nothing was posted (GitHub rejected the line), so nothing is visible.
1353
+ const result = {
1354
+ commentId: null,
1355
+ url: null,
1356
+ line,
1357
+ side,
1358
+ anchored: false,
1359
+ visible: false,
1360
+ threadId: null,
1361
+ };
1362
+ return result;
1363
+ }
1364
+ reply.status(502);
1365
+ return { error: 'GitHubError', message };
1366
+ }
1367
+ });
1368
+ // Changes tab: per-file diff patches, loaded on demand. Degrades to an empty
1369
+ // list on a GitHub fetch error (never 500s) so the tab fails gracefully.
1370
+ //
1371
+ // `headSha` is the STORED head at this read, so the SPA (which keeps the diff indefinitely)
1372
+ // can refetch it once a newer PR detail names another head. The empty fallback sends null, so
1373
+ // a failed read is retried on the next newer detail rather than kept as "no files" for good.
1374
+ //
1375
+ // `?page=` (1-30) is the "Load next 100 files" click: ONE REST page per request, `nextPage` says
1376
+ // whether another exists, `ceilingReached` that GitHub's 3,000-file listing ceiling was hit.
1377
+ app.get('/api/prs/:id/files', { schema: prFilesSchema }, async (req, reply) => {
1378
+ const { id } = req.params;
1379
+ const { page = 1 } = req.query;
1380
+ const accountId = accountIdOf(req);
1381
+ const ctx = await getPrFilesContext(id, accountId);
1382
+ if (!ctx) {
1383
+ reply.status(404);
1384
+ return { error: 'NotFound', message: `PR ${id} not found` };
1385
+ }
1386
+ try {
1387
+ const token = await getAccessToken(accountId);
1388
+ const { files, nextPage, ceilingReached } = await fetchPrFilesPage(token, ctx.owner, ctx.name, ctx.number, page);
1389
+ const mapped = files.map((f) => ({
1390
+ path: f.filename,
1391
+ previousPath: f.previous_filename ?? null,
1392
+ status: normalizeStatus(f.status),
1393
+ additions: f.additions,
1394
+ deletions: f.deletions,
1395
+ patch: f.patch ?? null,
1396
+ githubUrl: `${ctx.prUrl}/files#diff-${diffAnchorId(f.filename)}`,
1397
+ blobUrl: f.blob_url,
1398
+ }));
1399
+ const result = {
1400
+ files: mapped,
1401
+ truncated: nextPage != null || ceilingReached,
1402
+ headSha: ctx.headSha,
1403
+ nextPage,
1404
+ ceilingReached,
1405
+ };
1406
+ return result;
1407
+ }
1408
+ catch {
1409
+ // Graceful degrade — the Changes tab shows "no files" rather than 500ing.
1410
+ const result = { files: [], truncated: false, headSha: null };
1411
+ return result;
1412
+ }
1413
+ });
1414
+ // Changes tab, a gap marker's "Show N hidden lines": one file's raw text at the PR's stored
1415
+ // head (`side=head`) or at the merge base (`side=base`, for a deleted file's gaps). CLICK-GATED
1416
+ // in the SPA and never stored. Owner/name come from the account-scoped PR row, so `path` can
1417
+ // only ever name a file in this PR's own repo. Over ~1 MB, binary or absent → `refused`.
1418
+ app.get('/api/prs/:id/files/content', { schema: prFileContentSchema }, async (req, reply) => {
1419
+ const { id } = req.params;
1420
+ const { path, side } = req.query;
1421
+ const accountId = accountIdOf(req);
1422
+ if (!isSafeRepoPath(path)) {
1423
+ reply.status(400);
1424
+ return { error: 'BadRequest', message: 'That is not a file path in this repository.' };
1425
+ }
1426
+ const ctx = await getPrFilesContext(id, accountId);
1427
+ if (!ctx) {
1428
+ reply.status(404);
1429
+ return { error: 'NotFound', message: `PR ${id} not found` };
1430
+ }
1431
+ try {
1432
+ const token = await getAccessToken(accountId);
1433
+ const refs = await resolvePrDiffRefs(token, accountId, id, ctx.owner, ctx.name, ctx.number, ctx.headSha);
1434
+ const sha = side === 'base' ? refs.mergeBase : refs.headSha;
1435
+ const got = await fetchFileAtRef(token, ctx.owner, ctx.name, path, sha);
1436
+ const result = {
1437
+ path,
1438
+ side,
1439
+ sha,
1440
+ lines: got.kind === 'text' ? splitFileLines(got.text) : null,
1441
+ refused: got.kind === 'text' ? null : got.kind,
1442
+ };
1443
+ return result;
1444
+ }
1445
+ catch {
1446
+ reply.status(502);
1447
+ return { error: 'GitHubError', message: 'GitHub did not return this file.' };
1448
+ }
1449
+ });
1450
+ // Changes tab, "Load full diff" for a file GitHub sent NO patch for (its diff is too large for
1451
+ // the files listing). Both sides are fetched (`previousPath` for a rename's base) and diffed here
1452
+ // with the resolver's Myers engine into a header-less unified patch — the shape FileDiffView
1453
+ // already renders. A side that 404s is empty (an added or deleted file); both sides missing,
1454
+ // either side binary, or either side past ~1 MB → `refused`, and the GitHub link stays.
1455
+ app.get('/api/prs/:id/files/diff', { schema: prFileDiffSchema }, async (req, reply) => {
1456
+ const { id } = req.params;
1457
+ const { path, previousPath } = req.query;
1458
+ const accountId = accountIdOf(req);
1459
+ const basePath = previousPath ?? path;
1460
+ if (!isSafeRepoPath(path) || !isSafeRepoPath(basePath)) {
1461
+ reply.status(400);
1462
+ return { error: 'BadRequest', message: 'That is not a file path in this repository.' };
1463
+ }
1464
+ const ctx = await getPrFilesContext(id, accountId);
1465
+ if (!ctx) {
1466
+ reply.status(404);
1467
+ return { error: 'NotFound', message: `PR ${id} not found` };
1468
+ }
1469
+ try {
1470
+ const token = await getAccessToken(accountId);
1471
+ const refs = await resolvePrDiffRefs(token, accountId, id, ctx.owner, ctx.name, ctx.number, ctx.headSha);
1472
+ const [base, head] = await Promise.all([
1473
+ fetchFileAtRef(token, ctx.owner, ctx.name, basePath, refs.mergeBase),
1474
+ fetchFileAtRef(token, ctx.owner, ctx.name, path, refs.headSha),
1475
+ ]);
1476
+ const refusal = base.kind === 'too_large' || head.kind === 'too_large'
1477
+ ? 'too_large'
1478
+ : base.kind === 'binary' || head.kind === 'binary'
1479
+ ? 'binary'
1480
+ : base.kind === 'missing' && head.kind === 'missing'
1481
+ ? 'missing'
1482
+ : null;
1483
+ if (refusal != null) {
1484
+ const result = { path, patch: null, refused: refusal };
1485
+ return result;
1486
+ }
1487
+ const { patch } = synthesizeUnifiedPatch(base.kind === 'text' ? base.text : '', head.kind === 'text' ? head.text : '');
1488
+ const result = { path, patch, refused: null };
1489
+ return result;
1490
+ }
1491
+ catch {
1492
+ reply.status(502);
1493
+ return { error: 'GitHubError', message: 'GitHub did not return this file.' };
1494
+ }
1495
+ });
1496
+ // Failed-check logs: the tail of a GitHub Actions job's log, fetched live (never
1497
+ // stored). The jobId comes from CheckRun.jobId (parsed from the Actions detailsUrl);
1498
+ // only Actions checks have one, so the frontend offers this on failed Actions rows.
1499
+ // Degrades to {available:false, reason} on any GitHub error (expired logs, no
1500
+ // actions:read, network) instead of 500ing.
1501
+ app.get('/api/prs/:id/checks/:jobId/logs', { schema: checkLogsSchema }, async (req, reply) => {
1502
+ const { id, jobId } = req.params;
1503
+ const { tail, startByte, endByte } = req.query;
1504
+ const accountId = accountIdOf(req);
1505
+ const ctx = await getPrWriteContext(id, accountId);
1506
+ if (!ctx) {
1507
+ reply.status(404);
1508
+ return { error: 'NotFound', message: `PR ${id} not found` };
1509
+ }
1510
+ const token = await getAccessToken(accountId);
1511
+ // An explicit byte window wins; otherwise anchor at the tail. Forwarding the
1512
+ // window is what makes "load earlier" work at all — without it every page
1513
+ // re-serves the same tail and the pager spins forever.
1514
+ const window = startByte != null || endByte != null
1515
+ ? { startByte, endByte }
1516
+ : { tail: tail ?? 200 };
1517
+ const result = await fetchActionsJobLog(token, ctx.owner, ctx.name, jobId, window);
1518
+ return result;
1519
+ });
1520
+ // Re-trigger a GitHub Actions workflow run for this PR. The `runId` comes from
1521
+ // CheckRun.runId (Actions checks only). Server re-checks write access (WRITE/
1522
+ // MAINTAIN/ADMIN, matching viewerCanPush — no author exclusion, unlike approve),
1523
+ // then queues the rerun via the per-account token (local + cloud). GitHub runs it
1524
+ // asynchronously; the refreshed check states arrive on the next sync.
1525
+ app.post('/api/prs/:id/ci/rerun', { schema: ciRerunSchema }, async (req, reply) => {
1526
+ const { id } = req.params;
1527
+ const { runId, mode } = req.body;
1528
+ const accountId = accountIdOf(req);
1529
+ const ctx = await getPrWriteContext(id, accountId);
1530
+ if (!ctx) {
1531
+ reply.status(404);
1532
+ return { error: 'NotFound', message: `PR ${id} not found` };
1533
+ }
1534
+ const canRerun = ['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '');
1535
+ if (!canRerun) {
1536
+ reply.status(403);
1537
+ return {
1538
+ error: 'NotPermitted',
1539
+ message: 'You need write access to this repo to re-run CI.',
1540
+ };
1541
+ }
1542
+ try {
1543
+ // The stored CI verdict the rerun is meant to clear, read BEFORE asking GitHub so a sync
1544
+ // racing the rerun cannot hand us the post-rerun value as the "before". Advisory: a failed
1545
+ // read just means the ladder gets no CI expectation.
1546
+ const ciBefore = await getPrSettleFacts(ctx.prId, accountId).then((f) => f?.ciStatus ?? null, () => null);
1547
+ const token = await getAccessToken(accountId);
1548
+ await rerunWorkflowRun(token, ctx.owner, ctx.name, runId, mode);
1549
+ // CI moves asynchronously and never bumps the PR's `updatedAt`, so without this nothing
1550
+ // re-reads the PR until a walk happens to — the red card stays up after the rerun began.
1551
+ // ⚠ `ciNot`: a stale FAILURE is a KNOWN value, so a ladder with no expectation would stop
1552
+ // on it at its first read (~5s) if GitHub had not queued the new attempt yet. With it the
1553
+ // ladder keeps reading (≤4 reads, to ~120s) until the red status moves. It does NOT follow
1554
+ // the rerun to its finish — a run takes minutes; the stale-CI backstop and the open PR
1555
+ // pane's live poll read that. Fire-and-forget.
1556
+ schedulePrSettle(accountId, ctx.prId, asSyncLogger(req.log), ciBefore === 'failure' || ciBefore === 'error' ? { ciNot: ciBefore } : {});
1557
+ const result = { status: 'queued', runId, mode };
1558
+ return result;
1559
+ }
1560
+ catch (err) {
1561
+ reply.status(502);
1562
+ return {
1563
+ error: 'GitHubError',
1564
+ message: err instanceof Error ? err.message : String(err),
1565
+ };
1566
+ }
1567
+ });
1568
+ // Request reviewers on a PR (powers each Pending routing card's per-suggestion "Assign"
1569
+ // button, one reviewer per request — contract row in docs/API.md). Server
1570
+ // re-checks write access (WRITE/MAINTAIN/ADMIN — push-style, no author exclusion:
1571
+ // an author may request reviewers on their own PR). The given user ids are resolved
1572
+ // to GitHub logins (the PR author + bots + unknown ids dropped); GitHub itself gates
1573
+ // that each login is a repo collaborator. The refreshed request state arrives on the
1574
+ // next sync (reviewRequests are re-derived each pass).
1575
+ app.post('/api/prs/:id/request-reviewers', { schema: requestReviewersSchema }, async (req, reply) => {
1576
+ const { id } = req.params;
1577
+ const { userIds = [], logins: directLogins = [], teamSlugs = [], } = req.body;
1578
+ const accountId = accountIdOf(req);
1579
+ const ctx = await getPrWriteContext(id, accountId);
1580
+ if (!ctx) {
1581
+ reply.status(404);
1582
+ return { error: 'NotFound', message: `PR ${id} not found` };
1583
+ }
1584
+ const canRequest = ['WRITE', 'MAINTAIN', 'ADMIN'].includes(ctx.viewerPermission ?? '');
1585
+ if (!canRequest) {
1586
+ reply.status(403);
1587
+ return {
1588
+ error: 'NotPermitted',
1589
+ message: 'You need write access to this repo to request reviewers.',
1590
+ };
1591
+ }
1592
+ // Drop the PR author from the id set (GitHub rejects self-review requests), then
1593
+ // resolve to logins (also drops bots + unknown ids). Union with any direct logins
1594
+ // (suggested reviewers we haven't synced as users), deduped.
1595
+ const wanted = userIds.filter((uid) => uid !== ctx.authorId);
1596
+ const resolved = await getReviewerLogins(wanted); // [{ userId, login }]
1597
+ const resolvedLogins = resolved.map((r) => r.login);
1598
+ const logins = [...new Set([...resolvedLogins, ...directLogins])];
1599
+ const teams = [...new Set(teamSlugs)];
1600
+ if (logins.length === 0 && teams.length === 0) {
1601
+ reply.status(400);
1602
+ return {
1603
+ error: 'NoReviewers',
1604
+ message: 'None of the selected users or teams can be requested as reviewers.',
1605
+ };
1606
+ }
1607
+ try {
1608
+ const token = await getAccessToken(accountId);
1609
+ await requestReviewers(token, ctx.owner, ctx.name, ctx.number, logins, teams);
1610
+ // Optimistically stamp the request locally (mirrors approve/comment/merge) so the
1611
+ // "Requested" row + the suggestion gate reflect it immediately; the next sync
1612
+ // re-derives review_requests idempotently. Team handle = `owner/slug` (matches how a
1613
+ // CODEOWNERS team + the suggestion render). Only the synced-user ids are stamped;
1614
+ // unsynced direct logins land on the next sync.
1615
+ await stampReviewRequests(ctx.prId, resolved.map((r) => r.userId), teams.map((slug) => `${ctx.owner}/${slug}`));
1616
+ // The stamp moves the routing card; signal it before replying. Never throws.
1617
+ await notePrChangedForPr(accountId, ctx.prId);
1618
+ const result = {
1619
+ status: 'ok',
1620
+ requestedLogins: logins,
1621
+ };
1622
+ return result;
1623
+ }
1624
+ catch (err) {
1625
+ reply.status(502);
1626
+ return {
1627
+ error: 'GitHubError',
1628
+ message: err instanceof Error ? err.message : String(err),
1629
+ };
1630
+ }
1631
+ });
1632
+ }
1633
+ //# sourceMappingURL=prs.js.map