@preventive/triage 1.0.0-alpha.5 → 1.0.0-alpha.51

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 (368) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +357 -0
  14. package/common/bundle-compare-inputs.d.ts +2 -0
  15. package/common/bundle-compare-inputs.js +65 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +62 -0
  19. package/common/bundle-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +31 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/github-issue-labels.d.ts +1 -0
  41. package/common/github-issue-labels.js +11 -0
  42. package/common/github-pr.ts +56 -0
  43. package/common/gzip.js +59 -0
  44. package/common/line-diff.d.ts +8 -0
  45. package/common/line-diff.js +57 -0
  46. package/common/linked-workspace-groups.js +63 -0
  47. package/common/managed/agent-tasks.ts +292 -0
  48. package/common/managed/comments.ts +34 -0
  49. package/common/managed/finding-detail.d.ts +3 -0
  50. package/common/managed/finding-detail.js +66 -0
  51. package/common/managed/github-agents.ts +114 -0
  52. package/common/managed/github-logins.ts +49 -0
  53. package/common/managed/npm-packages.d.ts +7 -0
  54. package/common/managed/npm-packages.js +51 -0
  55. package/common/managed/permissions.ts +31 -0
  56. package/common/managed/report-content.ts +72 -0
  57. package/common/managed/report-filter.ts +109 -0
  58. package/common/managed/repository-alias.ts +65 -0
  59. package/common/managed/roles.ts +35 -0
  60. package/common/managed/routes.d.ts +2 -0
  61. package/common/managed/routes.js +359 -0
  62. package/common/managed/scan-models.ts +6 -0
  63. package/common/managed/team-app.d.ts +6 -0
  64. package/common/managed/team-app.js +47 -0
  65. package/common/managed/triage.ts +83 -0
  66. package/common/managed/upload-seal.ts +126 -0
  67. package/common/pretty-print.d.ts +5 -0
  68. package/common/pretty-print.js +24 -0
  69. package/common/revalidation-conflicts.js +48 -0
  70. package/common/revalidation-input-groups.js +56 -0
  71. package/common/save-error-reason.ts +20 -7
  72. package/common/scan-server.ts +13 -0
  73. package/common/security-links.d.ts +5 -0
  74. package/common/security-links.js +33 -0
  75. package/common/server-info.ts +46 -0
  76. package/common/utf8.d.ts +3 -0
  77. package/common/utf8.js +45 -0
  78. package/common/workspace-app.js +39 -0
  79. package/common/workspace-groups.js +176 -0
  80. package/out/activity.js +4 -0
  81. package/out/brotli-fallback.js +3 -3
  82. package/out/chunk-2K6UN3PC.js +3 -0
  83. package/out/chunk-2XUEZHIP.js +28 -0
  84. package/out/chunk-2ZDZWLFY.js +1 -0
  85. package/out/chunk-4HI2MSAV.js +17 -0
  86. package/out/chunk-6LNQTKAV.js +52 -0
  87. package/out/chunk-7BKKYVWR.js +7 -0
  88. package/out/chunk-7C7DWL7I.js +1 -0
  89. package/out/chunk-7JBSSRD7.js +3 -0
  90. package/out/chunk-7VAWINQF.js +6 -0
  91. package/out/chunk-C4Z6ZBXV.js +10 -0
  92. package/out/chunk-FMXWXDR4.js +36 -0
  93. package/out/chunk-GDPCLSOS.js +2 -0
  94. package/out/chunk-GO7FT4OD.js +1 -0
  95. package/out/chunk-HT2SSA3V.js +1 -0
  96. package/out/chunk-IPAH4LKF.js +232 -0
  97. package/out/chunk-IYPY47MC.js +1 -0
  98. package/out/chunk-IZ7POWI3.js +18 -0
  99. package/out/chunk-JCIIBLKR.js +1 -0
  100. package/out/chunk-KOGNQDSJ.js +1 -0
  101. package/out/chunk-NRPC74AM.js +1 -0
  102. package/out/chunk-OOJM4CTU.js +1 -0
  103. package/out/chunk-PBZPYIG7.js +1 -0
  104. package/out/chunk-PNHBZGDD.js +1 -0
  105. package/out/chunk-PWFUOLZK.js +17 -0
  106. package/out/chunk-PXK7EU4V.js +1 -0
  107. package/out/chunk-QB4CBOX2.js +1 -0
  108. package/out/chunk-R3NZFXVR.js +1 -0
  109. package/out/chunk-R5O6FAW4.js +2 -0
  110. package/out/chunk-SXV2T5C4.js +80 -0
  111. package/out/chunk-TQJDYHVE.js +2 -0
  112. package/out/chunk-TUII34K2.js +1 -0
  113. package/out/chunk-VDRXHIHN.js +3 -0
  114. package/out/chunk-VFWMQ3LG.js +2 -0
  115. package/out/chunk-VH4XMZIW.js +2 -0
  116. package/out/chunk-WCPJDAYA.js +10 -0
  117. package/out/chunk-WFYLMF6Z.js +10 -0
  118. package/out/chunk-WRAJVD35.js +1 -0
  119. package/out/chunk-WYLQWYLA.js +1 -0
  120. package/out/client-managed-import.js +4 -0
  121. package/out/client-managed.js +33 -0
  122. package/out/client-sync.js +11 -17
  123. package/out/compare.js +35 -0
  124. package/out/dialogs.js +55 -0
  125. package/out/github-issue-authorized.html +3 -0
  126. package/out/github-issue-authorized.js +1 -0
  127. package/out/graph.js +17 -4
  128. package/out/index.html +90 -8
  129. package/out/prism.js +14 -10
  130. package/out/scan.js +2 -0
  131. package/out/stasis.svg +20 -0
  132. package/out/terminal.js +366 -39
  133. package/out/view.css +1 -1
  134. package/out/view.js +19 -144
  135. package/package.json +364 -59
  136. package/risk/actions/findings.js +161 -0
  137. package/risk/actions/resolve.js +219 -0
  138. package/risk/actions/scripts/commands.js +182 -0
  139. package/risk/actions/scripts/grade.js +113 -0
  140. package/risk/actions/scripts/packages.js +123 -0
  141. package/risk/actions/scripts/shell.js +169 -0
  142. package/risk/actions/uses.js +76 -0
  143. package/risk/actions/workflow.js +110 -0
  144. package/risk/files/characters.js +196 -0
  145. package/risk/files/hosts.js +205 -0
  146. package/risk/files/readability.js +177 -0
  147. package/risk/files/runs-code.js +615 -0
  148. package/risk/files/script.js +118 -0
  149. package/risk/files/stamps.js +47 -0
  150. package/risk/index.d.ts +254 -0
  151. package/risk/index.js +11 -0
  152. package/risk/npm/assess.js +285 -0
  153. package/risk/npm/combined.js +68 -0
  154. package/risk/npm/compare.js +257 -0
  155. package/risk/npm/dependencies.js +172 -0
  156. package/risk/npm/diff.js +79 -0
  157. package/risk/npm/downloads.js +84 -0
  158. package/risk/npm/files.js +445 -0
  159. package/risk/npm/held.js +63 -0
  160. package/risk/npm/install-scripts.js +34 -0
  161. package/risk/npm/malware.js +36 -0
  162. package/risk/npm/manifest.js +65 -0
  163. package/risk/npm/new-dependency.js +60 -0
  164. package/risk/npm/old-version.js +108 -0
  165. package/risk/npm/registry.js +388 -0
  166. package/risk/npm/release.js +85 -0
  167. package/risk/npm/score.js +59 -0
  168. package/risk/npm/specs.js +124 -0
  169. package/risk/npm/tarball.js +96 -0
  170. package/server-common/database-config.ts +16 -0
  171. package/server-common/initialize.ts +18 -0
  172. package/server-common/npm-advisories.ts +101 -0
  173. package/{server → server-common}/origin.ts +5 -5
  174. package/server-common/reap.ts +48 -0
  175. package/server-common/scan-config.ts +19 -0
  176. package/server-common/standalone.ts +29 -0
  177. package/server-common/storage-crypto.ts +182 -0
  178. package/server-common/storage-log.ts +38 -0
  179. package/server-common/vercel-blob.ts +103 -0
  180. package/server-e2e/app.ts +487 -0
  181. package/{server → server-e2e}/bus-receiver.ts +2 -1
  182. package/{server → server-e2e}/cli.js +9 -4
  183. package/{server → server-e2e}/config.ts +50 -42
  184. package/{server → server-e2e}/db-neon.ts +2 -2
  185. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  186. package/{server → server-e2e}/db-stmt.ts +2 -2
  187. package/{server → server-e2e}/db.ts +7 -7
  188. package/{server → server-e2e}/http.ts +44 -13
  189. package/{server → server-e2e}/hub.ts +40 -9
  190. package/server-e2e/index.ts +17 -0
  191. package/server-e2e/lifecycle.ts +95 -0
  192. package/{server → server-e2e}/neon-driver.ts +2 -2
  193. package/{server → server-e2e}/npm-proxy.ts +12 -145
  194. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  195. package/{server → server-e2e}/objstore/blob.ts +1 -1
  196. package/server-e2e/objstore/fetch-mint-guard.ts +74 -0
  197. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  198. package/{server → server-e2e}/objstore/init.ts +19 -27
  199. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  200. package/server-e2e/objstore/rest-deny.ts +28 -0
  201. package/server-e2e/objstore/rest-mint.ts +224 -0
  202. package/{server → server-e2e}/objstore/rest.ts +3 -3
  203. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  204. package/{server → server-e2e}/objstore/store.ts +7 -7
  205. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  206. package/{server → server-e2e}/pubsub.ts +12 -9
  207. package/{server → server-e2e}/sign.ts +4 -4
  208. package/{server → server-e2e}/sse-server.ts +60 -33
  209. package/{server → server-e2e}/static.ts +31 -21
  210. package/{server → server-e2e}/sync-handlers.ts +64 -30
  211. package/{server → server-e2e}/ws-server.ts +20 -9
  212. package/server-managed/activity.ts +258 -0
  213. package/server-managed/agent-merges.ts +109 -0
  214. package/server-managed/app-agents.ts +23 -0
  215. package/server-managed/avatar-store.ts +13 -0
  216. package/server-managed/blob-store.ts +17 -0
  217. package/server-managed/brotli.ts +10 -0
  218. package/server-managed/bundle-advisories.ts +120 -0
  219. package/server-managed/bundle-advisory-inventory.ts +77 -0
  220. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  221. package/server-managed/bundle-build-diagnostics.js +23 -0
  222. package/server-managed/bundle-build-leases.ts +41 -0
  223. package/server-managed/bundle-build-worker.js +115 -0
  224. package/server-managed/bundle-build.ts +200 -0
  225. package/server-managed/bundle-cache.ts +211 -0
  226. package/server-managed/bundle-catalog.ts +29 -0
  227. package/server-managed/bundle-commits.ts +140 -0
  228. package/server-managed/bundle-store.ts +24 -0
  229. package/server-managed/bundle-summary-cache.ts +130 -0
  230. package/server-managed/bundle.ts +119 -0
  231. package/server-managed/cache-storage.ts +20 -0
  232. package/server-managed/cli.js +21 -0
  233. package/server-managed/combined.ts +47 -0
  234. package/server-managed/comments.ts +151 -0
  235. package/server-managed/commit-coauthors.ts +106 -0
  236. package/server-managed/commit-lockfiles.ts +76 -0
  237. package/server-managed/comparison.ts +52 -0
  238. package/server-managed/config.ts +164 -0
  239. package/server-managed/content-access.ts +15 -0
  240. package/server-managed/crypto.ts +25 -0
  241. package/server-managed/db-methods.ts +1923 -0
  242. package/server-managed/db-neon.ts +468 -0
  243. package/server-managed/db-schema.ts +238 -0
  244. package/server-managed/db-table-names.ts +22 -0
  245. package/server-managed/db.ts +143 -0
  246. package/server-managed/dependabot-access.ts +60 -0
  247. package/server-managed/dependabot-alerts.ts +185 -0
  248. package/server-managed/dependency-review-comments.ts +98 -0
  249. package/server-managed/dependency-reviews.ts +364 -0
  250. package/server-managed/github-accounts.ts +60 -0
  251. package/server-managed/github-actions.ts +71 -0
  252. package/server-managed/github-app.ts +376 -0
  253. package/server-managed/github-errors.ts +70 -0
  254. package/server-managed/github-graphql.ts +39 -0
  255. package/server-managed/github-issue-links.ts +140 -0
  256. package/server-managed/github-issue-oauth.ts +47 -0
  257. package/server-managed/github-issues.ts +152 -0
  258. package/server-managed/github-link-oauth.ts +69 -0
  259. package/server-managed/github-links.ts +204 -0
  260. package/server-managed/github-metadata.ts +213 -0
  261. package/server-managed/github-oauth.ts +238 -0
  262. package/server-managed/github-pulls.ts +227 -0
  263. package/server-managed/github-requests.ts +136 -0
  264. package/server-managed/github-users.ts +30 -0
  265. package/server-managed/http-response.ts +76 -0
  266. package/server-managed/http.ts +5503 -0
  267. package/server-managed/import-triage.ts +51 -0
  268. package/server-managed/index.ts +192 -0
  269. package/server-managed/kept-briefly.ts +37 -0
  270. package/server-managed/kept.ts +28 -0
  271. package/server-managed/link-reports.ts +162 -0
  272. package/server-managed/listed-activity.ts +39 -0
  273. package/server-managed/locked-packages.ts +152 -0
  274. package/server-managed/lockfile-scope.ts +49 -0
  275. package/server-managed/lru.ts +30 -0
  276. package/server-managed/managed-issues.ts +78 -0
  277. package/server-managed/management-catalog.ts +45 -0
  278. package/server-managed/management.ts +99 -0
  279. package/server-managed/npm-delta-worker.js +23 -0
  280. package/server-managed/npm-delta.ts +194 -0
  281. package/server-managed/npm-insights.ts +449 -0
  282. package/server-managed/npm-kept.ts +225 -0
  283. package/server-managed/npm-loads.ts +264 -0
  284. package/server-managed/npm-manifest.ts +115 -0
  285. package/server-managed/npm-packages.ts +454 -0
  286. package/server-managed/npm-patch.ts +325 -0
  287. package/server-managed/npm-provenance.ts +123 -0
  288. package/server-managed/npm-risk.ts +285 -0
  289. package/server-managed/object-storage-disk.ts +148 -0
  290. package/server-managed/object-storage-vercel.ts +67 -0
  291. package/server-managed/object-storage.ts +75 -0
  292. package/server-managed/package-entry-points.ts +51 -0
  293. package/server-managed/pretty-print.ts +434 -0
  294. package/server-managed/public-workspace.ts +238 -0
  295. package/server-managed/pull-comment-reviews.ts +161 -0
  296. package/server-managed/pull-dependencies.ts +351 -0
  297. package/server-managed/pull-dependency-reviews.ts +334 -0
  298. package/server-managed/pull-reviews.ts +205 -0
  299. package/server-managed/queue.ts +39 -0
  300. package/server-managed/release-commits.ts +84 -0
  301. package/server-managed/rename-diff-worker.js +26 -0
  302. package/server-managed/rename-diff.ts +279 -0
  303. package/server-managed/repo-path.ts +21 -0
  304. package/server-managed/report-migration.ts +35 -0
  305. package/server-managed/report-query.ts +10 -0
  306. package/server-managed/report-response.ts +16 -0
  307. package/server-managed/report-sources.ts +178 -0
  308. package/server-managed/report-store.ts +85 -0
  309. package/server-managed/repository-actions.ts +218 -0
  310. package/server-managed/repository-agents.ts +448 -0
  311. package/server-managed/repository-aliases.ts +91 -0
  312. package/server-managed/repository-browser.ts +294 -0
  313. package/server-managed/repository-changes.ts +284 -0
  314. package/server-managed/repository-code.ts +215 -0
  315. package/server-managed/repository-dependency-reviews.ts +166 -0
  316. package/server-managed/repository-discovery.ts +82 -0
  317. package/server-managed/repository-history.ts +432 -0
  318. package/server-managed/repository-issues.ts +195 -0
  319. package/server-managed/repository-policy.ts +27 -0
  320. package/server-managed/repository-pulls.ts +212 -0
  321. package/server-managed/repository-pulse.ts +460 -0
  322. package/server-managed/repository-risk-assess.ts +105 -0
  323. package/server-managed/repository-risk-audit.ts +79 -0
  324. package/server-managed/repository-risk-read.ts +170 -0
  325. package/server-managed/repository-risk.ts +491 -0
  326. package/server-managed/repository-squashes.ts +168 -0
  327. package/server-managed/request-timing.ts +63 -0
  328. package/server-managed/reviewed-dependencies.ts +149 -0
  329. package/server-managed/revisions.ts +35 -0
  330. package/server-managed/scan-downloads.ts +87 -0
  331. package/server-managed/session.ts +132 -0
  332. package/server-managed/slugs.ts +38 -0
  333. package/server-managed/solidity-entry-points.ts +71 -0
  334. package/server-managed/sql-postgres.ts +34 -0
  335. package/server-managed/sql.ts +88 -0
  336. package/server-managed/static.ts +28 -0
  337. package/server-managed/storage-command.ts +16 -0
  338. package/server-managed/storage-db.ts +183 -0
  339. package/server-managed/storage-encryption.ts +290 -0
  340. package/server-managed/storage-maintenance.ts +259 -0
  341. package/server-managed/storage-payload.ts +121 -0
  342. package/server-managed/storage-stores.ts +91 -0
  343. package/server-managed/storage.ts +82 -0
  344. package/server-managed/team-app.ts +134 -0
  345. package/server-managed/team-catalog.ts +7 -0
  346. package/server-managed/team-feed.ts +180 -0
  347. package/server-managed/team-npm-scopes.ts +106 -0
  348. package/server-managed/team-reports.ts +319 -0
  349. package/server-managed/triage-response.ts +16 -0
  350. package/server-managed/type-only-worker.js +19 -0
  351. package/server-managed/type-only.ts +105 -0
  352. package/server-managed/uploads.ts +106 -0
  353. package/server-managed/upstream-cache.ts +243 -0
  354. package/server-managed/view-as.ts +58 -0
  355. package/server-managed/workspace-shares.ts +169 -0
  356. package/server.ts +70 -0
  357. package/server/index.ts +0 -480
  358. package/server/lifecycle.ts +0 -208
  359. /package/{LICENSE → LICENSE-MIT} +0 -0
  360. /package/{server → server-e2e}/auth.ts +0 -0
  361. /package/{server → server-e2e}/config.example.json +0 -0
  362. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  363. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  364. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  365. /package/{server → server-e2e}/peer.ts +0 -0
  366. /package/{server → server-e2e}/sse-session.ts +0 -0
  367. /package/{server → server-e2e}/util.ts +0 -0
  368. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,334 @@
1
+ // What an open pull request's lockfiles' versions want of review, in a
2
+ // repository that reviews dependencies (repository-dependency-reviews.ts), as
3
+ // its tile and popup show it: each version it adds, whether it passes, by as
4
+ // many reviewers' reviews as the repository requires (`reviews`) or by the
5
+ // reviewed dependencies the host registers (`reviewed`,
6
+ // reviewed-dependencies.ts), or needs none, being among those the
7
+ // repository's lockfiles locked at the commit it is reviewed since
8
+ // (`baseline`); apart from them, the other versions its lockfiles lock that
9
+ // neither passes nor needs none (`unreviewed`); and those that can't be
10
+ // reviewed (`unsupported`), which fail its review, as a lockfile it changes
11
+ // that isn't read does. Without that commit, every version wants its
12
+ // reviews; registered reviewed dependencies replace it.
13
+ //
14
+ // A version is reviewed as npm's registry has it, by its name, version and
15
+ // integrity: one locked of npm's registry, by its name or its link to its
16
+ // tarball (locked-packages.ts), with an integrity. One from git, another
17
+ // tarball (a mirror's too), or with no integrity can't be; a file of the
18
+ // project's isn't. Its reviews are those of it, of an integrity it is locked
19
+ // with, either whole, or compared with a version of its package: for a
20
+ // version the pull request adds, one it was; for another, any. A patched
21
+ // one's (`patch`) are of it as patched, by its patch's hash, its patch read
22
+ // of the repository where its lockfile names the patch's file (npm-patch.ts):
23
+ // compared with the version it patches, where that is one it was, they review
24
+ // the patch alone. Locked so at that commit, its patch too, it needs none.
25
+ // Which versions the repository's lockfiles locked at that commit never
26
+ // changes: it is read once, every lockfile there of those read here
27
+ // (pull-dependencies.ts), and kept by the commit (`baselines` in this
28
+ // instance, `kept` beyond it), never stored as reviews.
29
+ import { lockedAt, lockedIn } from './commit-lockfiles.ts'
30
+ import { GithubApiError } from './github-app.ts'
31
+ import type { LockedPackage } from './locked-packages.ts'
32
+ import { EVERY_LOCKFILE, type LockfileScope, heldTo, isEvery, reviewedIn } from './lockfile-scope.ts'
33
+ import { type Lru, lru } from './lru.ts'
34
+ import { type DirectoryDependencies, type GithubAsked, type LockfileStore, MAX_ADDED, type PullDependencies, lockedAs, lockedWith } from './pull-dependencies.ts'
35
+ import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
36
+ import { type ReviewedDependencies, type ReviewedDependency, askReviewed } from './reviewed-dependencies.ts'
37
+
38
+ // The other versions told unreviewed, and those told unsupported, of each
39
+ // directory, those past them counted.
40
+ export const MAX_UNREVIEWED = 200
41
+
42
+ // The versions a commit's lockfiles lock, and the lockfiles there that
43
+ // couldn't be read (`unread`), whose versions want reviews all the same.
44
+ export interface Baseline { versions: Set<string>; unread: string[] }
45
+ export interface ReviewBaselineStore {
46
+ read(key: string): Promise<{ versions: string[]; unread: string[] } | null>
47
+ write(key: string, value: { versions: string[]; unread: string[] }): Promise<void>
48
+ }
49
+ const baselines: Lru<Baseline> = lru(500_000, baseline => baseline.versions.size + baseline.unread.length + 1)
50
+
51
+ // Why a version can't be reviewed: from git, of a tarball not npm's
52
+ // registry's of its version, or locked with no integrity.
53
+ export type Unsupported = 'git' | 'tarball' | 'integrity'
54
+ // How a version is reviewed: by its name, version and integrity
55
+ // (`version`), not at all (`skip`), or why it can't be.
56
+ function reviewedAs(pkg: LockedPackage): 'version' | 'skip' | Unsupported {
57
+ if (pkg.source === 'file') return 'skip'
58
+ if (pkg.source === 'git') return 'git'
59
+ if (pkg.source !== 'registry' || pkg.version === null) return 'tarball'
60
+ return pkg.integrity ? 'version' : 'integrity'
61
+ }
62
+ // The hashes an integrity names, each of which is npm's of it.
63
+ const hashesOf = (pkg: LockedPackage) => (pkg.integrity ?? '').split(/\s+/u).filter(Boolean)
64
+ // A version as a baseline holds it: its name and version with each hash,
65
+ // and its patch.
66
+ const baselineKeys = (pkg: LockedPackage) => hashesOf(pkg).map(hash => `${pkg.name}@${pkg.version ?? ''}\0${hash}\0${pkg.patchHash ?? ''}`)
67
+
68
+ // The versions the repository's lockfiles locked at commit `since` that are
69
+ // reviewed (reviewedAs), as kept, else read of GitHub (commit-lockfiles.ts,
70
+ // its lockfiles as `reads` keeps them) and kept; with the lockfiles there its
71
+ // reader refuses, isn't one of, or past those read (`unread`). GitHub having
72
+ // none of a lockfile it lists there is a failure of the whole, as of any
73
+ // file, never kept.
74
+ export async function reviewBaseline(fullName: string, token: string, repoId: number, since: string, kept: ReviewBaselineStore, reads: LockfileStore | null = null,
75
+ asked?: GithubAsked): Promise<Baseline> {
76
+ const key = `${repoId}\0${since}`
77
+ const known = baselines.get(key)
78
+ if (known) return known
79
+ const stored = await kept.read(key)
80
+ if (stored) { const baseline = { versions: new Set(stored.versions), unread: stored.unread }; baselines.set(key, baseline); return baseline }
81
+ const read = await lockedAt(fullName, token, since, reads, () => true, asked)
82
+ const { packages } = lockedIn(read), { unread } = read
83
+ const versions = new Set<string>()
84
+ for (const pkg of packages) if (reviewedAs(pkg) === 'version') for (const held of baselineKeys(pkg)) versions.add(held)
85
+ const baseline = { versions, unread }
86
+ baselines.set(key, baseline)
87
+ await kept.write(key, { versions: [...versions], unread: baseline.unread })
88
+ return baseline
89
+ }
90
+
91
+ // Passing reviews by the version they are of, its name and version.
92
+ type ReviewsOf = Map<string, PublishedReview[]>
93
+ function reviewsByVersion(reviews: PublishedReview[]): ReviewsOf {
94
+ const by: ReviewsOf = new Map()
95
+ for (const review of reviews) {
96
+ const key = `${review.package}@${review.version}`
97
+ const held = by.get(key)
98
+ if (held) held.push(review)
99
+ else by.set(key, [review])
100
+ }
101
+ return by
102
+ }
103
+
104
+ const ACCEPTING = new Set(['accept', 'accept-with-nits'])
105
+ // Where `pkg`'s reviewers stand on it among `reviews`, those of its version,
106
+ // of an integrity it is locked with, and of its patch: each one's latest
107
+ // telling it, any rejecting it holding it unreviewed (`rejected`); those
108
+ // accepting it passing it (`passing`), each once, by a full, accepting
109
+ // review of theirs, whole or compared with one of `bases` of its package
110
+ // (any, for `any`); and how many review it in its pull request's comments
111
+ // alone (`commented`), which count for it alone: whose reviews passing it,
112
+ // else whose latest, are its comments'. Each reviewer too (`reviewers`), by
113
+ // their login, their latest verdict, whether they pass it, and whether that
114
+ // verdict is its comments' (`comment`), which counts for it alone.
115
+ function stancesOf(pkg: LockedPackage, reviews: ReviewsOf, bases: string[] | 'any') {
116
+ const hashes = hashesOf(pkg)
117
+ const by = new Map<string, PublishedReview[]>()
118
+ for (const review of reviews.get(`${pkg.name}@${pkg.version}`) ?? []) {
119
+ if (!hashes.includes(review.integrity) || (review.patchHash ?? '') !== (pkg.patchHash ?? '')) continue
120
+ by.set(review.reviewer, [...by.get(review.reviewer) ?? [], review])
121
+ }
122
+ const qualifies = (review: PublishedReview) => review.full && ACCEPTING.has(review.status)
123
+ && (review.basePackage === null || (review.basePackage === pkg.name && (bases === 'any' || bases.includes(review.baseVersion ?? ''))))
124
+ let commented = 0, passing = 0, rejected = false
125
+ const reviewers: Reviewer[] = []
126
+ for (const theirs of by.values()) {
127
+ const latest = theirs.reduce((one, other) => other.time > one.time ? other : one)
128
+ const passes = ACCEPTING.has(latest.status) && theirs.some(qualifies)
129
+ // In its comments alone where those telling where they stand are: those
130
+ // passing it, where they pass it, else their latest.
131
+ const comment = (passes ? theirs.filter(qualifies) : [latest]).every(review => review.comment)
132
+ if (comment) commented++
133
+ if (latest.status === 'reject') rejected = true
134
+ else if (passes) passing++
135
+ reviewers.push({ login: latest.login, status: latest.status, ...passes ? { passes: true as const } : {}, ...latest.comment ? { comment: true as const } : {} })
136
+ }
137
+ return { passing, rejected, commented, reviewers }
138
+ }
139
+ type Reviewer = { login: string; status: PublishedReview['status']; passes?: true; comment?: true }
140
+
141
+ // A version as the client is told it: what its reviews are held to left
142
+ // out, but its patch, where it is patched (`patch`): its hash, which its
143
+ // reviews are held to, and its file, where its lockfile names one, from the
144
+ // repository's root, whence its reviews read it.
145
+ type Patch = { hash: string; path?: string }
146
+ function shown<T extends LockedPackage>(pkg: T): Omit<T, 'integrity' | 'shasum' | 'patchHash' | 'patchPath' | 'lockfile'> & { patch?: Patch } {
147
+ const copy = { ...pkg }
148
+ for (const field of ['integrity', 'shasum', 'patchHash', 'patchPath', 'lockfile'] as const) delete copy[field]
149
+ return { ...copy, ...pkg.patchHash ? { patch: { hash: pkg.patchHash, ...pkg.patchPath ? { path: pkg.patchPath } : {} } } : {} }
150
+ }
151
+
152
+ // A version as the registered reviewed dependencies are asked of it, by
153
+ // what it is asked.
154
+ function askedOf(pkg: LockedPackage): [string, ReviewedDependency] {
155
+ const dependency: ReviewedDependency = { ecosystem: 'npm', lockfile: pkg.lockfile ?? 'npm', name: pkg.name, version: pkg.version ?? '', integrity: pkg.integrity ?? '',
156
+ ...pkg.shasum ? { shasum: pkg.shasum } : {}, ...pkg.patchHash ? { patchHash: pkg.patchHash } : {} }
157
+ return [JSON.stringify(dependency), dependency]
158
+ }
159
+
160
+ // A version's review, and whether it wants one (`wants`), neither passing
161
+ // nor needing none, as only one that can be reviewed may.
162
+ type Review = { unsupported: Unsupported } | { baseline: true } | { reviewed: true } | { reviews: number; rejected?: true; commented?: number; reviewers?: Reviewer[] }
163
+ | Record<string, never>
164
+ interface Judged { review: Review; wants: boolean }
165
+ type Judge = (pkg: LockedPackage, bases: string[] | 'any') => Judged
166
+ interface Context { state: RepoReviewState; reviews: ReviewsOf; baseline: Set<string> | null }
167
+ function judge(pkg: LockedPackage, bases: string[] | 'any', { state, reviews, baseline }: Context): Judged {
168
+ const as = reviewedAs(pkg)
169
+ if (as === 'skip') return { review: {}, wants: false }
170
+ if (as !== 'version') return { review: { unsupported: as }, wants: false }
171
+ if (baselineKeys(pkg).some(key => baseline?.has(key))) return { review: { baseline: true }, wants: false }
172
+ const { passing, rejected, commented, reviewers } = stancesOf(pkg, reviews, bases)
173
+ const told = { reviews: passing, ...commented > 0 ? { commented } : {}, ...reviewers.length > 0 ? { reviewers } : {} }
174
+ if (rejected) return { review: { ...told, rejected: true }, wants: true }
175
+ return { review: told, wants: passing < state.required }
176
+ }
177
+
178
+ // A directory as the client is told it: what it adds, as many as MAX_ADDED,
179
+ // each version with its review (`review`, as judged), those past them judged
180
+ // as they are, against the versions they were, as is every one its lockfiles
181
+ // lock of them (another integrity of it, say), each told by the least passing
182
+ // of them, and those of all that want one (`toReview`); the others its lockfiles lock that want reviews, and every one
183
+ // that can't be reviewed (as many of each as MAX_UNREVIEWED, how many more,
184
+ // once `capped`); and how many it locks past those read (`moreLocked`), which
185
+ // aren't checked; without `review`, what it adds alone.
186
+ function reviewedDirectory(dir: DirectoryDependencies, review: Judge | null) {
187
+ if ('error' in dir) return dir
188
+ const { locked, moreLocked, added, ...told } = dir
189
+ if (!review) return { ...told, added: added.slice(0, MAX_ADDED).map(shown) }
190
+ const adds = new Map(added.map(pkg => [lockedAs(pkg), { pkg, variants: [pkg] }]))
191
+ for (const pkg of locked) {
192
+ const of = adds.get(lockedAs(pkg))
193
+ if (of && lockedWith(pkg) !== lockedWith(of.pkg)) of.variants.push(pkg)
194
+ }
195
+ const own = [...adds.values()].map(({ pkg, variants }) => {
196
+ const judged = variants.map(variant => ({ variant, ...review(variant, pkg.was ?? []) }))
197
+ const least = judged.find(one => 'unsupported' in one.review) ?? judged.find(one => one.wants) ?? judged[0]!
198
+ return { pkg, judged: least, wanting: judged.filter(one => one.wants).map(({ variant }) => variant) }
199
+ })
200
+ const others = locked.filter(pkg => !adds.has(lockedAs(pkg))).map(pkg => ({ pkg, judged: review(pkg, 'any') }))
201
+ const unsupported = locked.flatMap(pkg => { const as = reviewedAs(pkg); return as === 'version' || as === 'skip' ? [] : [{ ...shown(pkg), unsupported: as }] })
202
+ return { ...told, added: own.slice(0, MAX_ADDED).map(({ pkg, judged }) => ({ ...shown(pkg), ...judged.review })),
203
+ toReview: own.flatMap(({ wanting }) => wanting.map(shown)),
204
+ unreviewed: others.filter(({ judged }) => judged.wants).map(({ pkg, judged }) => ({ ...shown(pkg), ...judged.review })), unsupported, moreLocked }
205
+ }
206
+ function capped<T extends { toReview: unknown[]; unreviewed: unknown[]; unsupported: unknown[] }>({ toReview: _toReview, ...dir }: T) {
207
+ return { ...dir, unreviewed: dir.unreviewed.slice(0, MAX_UNREVIEWED), moreUnreviewed: Math.max(0, dir.unreviewed.length - MAX_UNREVIEWED),
208
+ unsupported: dir.unsupported.slice(0, MAX_UNREVIEWED), moreUnsupported: Math.max(0, dir.unsupported.length - MAX_UNREVIEWED) }
209
+ }
210
+ // How many versions of `lists` there are, each once across them, by `key`,
211
+ // as the client tells them once: one wanting reviews by its name and
212
+ // version, and its patch's hash, as each patch of it is reviewed apart; one
213
+ // that can't be reviewed by where it is from too.
214
+ type Shown = Pick<LockedPackage, 'name' | 'version' | 'source' | 'from'> & { patch?: Patch }
215
+ const distinct = (lists: Shown[][], key: (pkg: Shown) => string) => new Set(lists.flat().map(key)).size
216
+ const versionKey = (pkg: Shown) => `${pkg.name}@${pkg.version ?? ''}\0${pkg.patch?.hash ?? ''}`
217
+ const sourceKey = (pkg: Shown) => `${pkg.source}\0${pkg.name}@${pkg.version ?? ''}\0${pkg.from ?? ''}`
218
+
219
+ // The reviews an open pull request's comments make of `wanting`, the
220
+ // versions still wanting one (pull-comment-reviews.ts): those that count,
221
+ // and whether they couldn't be read.
222
+ export type CommentReviews = (wanting: ReviewedDependency[]) => Promise<{ reviews: PublishedReview[]; failed: boolean }>
223
+
224
+ // What a pull request's lockfiles lock, but in directories none of whose
225
+ // lockfiles `scope` holds to, as they aren't reviewed: left out, as lockfiles
226
+ // left unread are where it holds to none of them (`omitted`, told to none).
227
+ export function heldDependencies<T extends PullDependencies>(told: T, scope: LockfileScope): Omit<T, 'omitted'> {
228
+ const { omitted, ...answered } = told
229
+ if (isEvery(scope)) return answered
230
+ return { ...answered, cut: told.cut && !(omitted && !omitted.some(path => heldTo(scope, path))), lockfiles: told.lockfiles.filter(dir => reviewedIn(scope, dir.paths)) }
231
+ }
232
+
233
+ // A pull request's dependencies as the client is told them: without the
234
+ // versions its directories lock; with `state`, a repository's review in
235
+ // effect, each version's review (reviewedDirectory), those wanting one asked
236
+ // of the registered reviewed dependencies (`reviewed`), and those still
237
+ // wanting one of the reviews its comments make (`commentReviews`, where the
238
+ // host reads them), and the review's terms (`review`), with how many
239
+ // reviewers' its comments count (`commentReviews`), or that they couldn't be
240
+ // read (`commentsFailed`), and how many versions across its directories want
241
+ // reviews, of those it adds (`toReview`) and the rest (`unreviewed`), and
242
+ // can't be reviewed (`unsupported`), each once; how many the reviewed dependencies failed to
243
+ // answer (`unasked`), and whether they are registered (`reviewedDependencies`,
244
+ // the commit reviewed since then none); and where the baseline couldn't be
245
+ // read, why (`baselineError`), every version then wanting its reviews, or
246
+ // the lockfiles there left unread (`baselineUnread`), whose versions do. It
247
+ // fails where a version can't be reviewed, a directory's lockfiles couldn't
248
+ // be read or lock more than are checked, or the pull request changes more
249
+ // lockfiles than are read (`cut`). Those of directories none of whose
250
+ // lockfiles the review holds to (`lockfiles`, lockfile-scope.ts, told in its
251
+ // terms where not every one) are left out (heldDependencies).
252
+ export async function reviewedDependencies(told: PullDependencies, state: RepoReviewState | null,
253
+ { baseline = null, baselineUnread = [], baselineError = null, reviewed = null, commentReviews = null }: { baseline?: Set<string> | null; baselineUnread?: string[]
254
+ baselineError?: string | null; reviewed?: ReviewedDependencies | null; commentReviews?: CommentReviews | null } = {}) {
255
+ const scope = state?.lockfiles ?? EVERY_LOCKFILE
256
+ const answered = heldDependencies(told, scope)
257
+ if (!state) return { ...answered, lockfiles: answered.lockfiles.map(dir => reviewedDirectory(dir, null)) }
258
+ const { cut, lockfiles: held } = answered
259
+ let context = { state, reviews: reviewsByVersion(state.reviews), baseline: reviewed ? null : baseline }
260
+ // What wants a review, as `lookup` is asked of, each once.
261
+ const wanting = () => {
262
+ const asked = new Map<string, ReviewedDependency>()
263
+ const asking: Judge = (pkg, bases) => {
264
+ const judged = judge(pkg, bases, context)
265
+ if (judged.wants) asked.set(...askedOf(pkg))
266
+ return judged
267
+ }
268
+ for (const dir of held) reviewedDirectory(dir, asking)
269
+ return asked
270
+ }
271
+ const passed = new Set<string>()
272
+ let unasked = 0
273
+ const ask = async (asked: Map<string, ReviewedDependency>) => {
274
+ const answer = asked.size > 0 && reviewed ? await askReviewed(reviewed.lookup, asked) : { passed: new Set<string>(), unasked: 0 }
275
+ for (const key of answer.passed) passed.add(key)
276
+ unasked += answer.unasked
277
+ }
278
+ const asked = wanting()
279
+ await ask(asked)
280
+ // Of those still wanting one, and every other one the lockfiles it holds
281
+ // to add that its teams' reviews pass, telling other pull requests those
282
+ // it reviews (`commented`), but those `lookup` passes, reviewed, the
283
+ // reviews its comments make, an open one's alone (pull-comment-reviews.ts),
284
+ // which count as its teams' do; those their rejects hold asked of `lookup`
285
+ // too.
286
+ const parsing = new Map([...asked].filter(([key]) => !passed.has(key)))
287
+ if (commentReviews) {
288
+ const others = new Map<string, ReviewedDependency>()
289
+ for (const pkg of held.flatMap(dir => 'added' in dir ? dir.added : [])) {
290
+ const [key, dependency] = askedOf(pkg)
291
+ if (!asked.has(key) && 'reviews' in judge(pkg, pkg.was ?? [], context).review) others.set(key, dependency)
292
+ }
293
+ const vouched = others.size > 0 && reviewed ? (await askReviewed(reviewed.lookup, others)).passed : new Set<string>()
294
+ for (const [key, dependency] of others) if (!vouched.has(key)) parsing.set(key, dependency)
295
+ }
296
+ const comments = parsing.size > 0 && commentReviews ? await commentReviews([...parsing.values()]) : { reviews: [], failed: false }
297
+ if (comments.reviews.length > 0) {
298
+ context = { ...context, reviews: reviewsByVersion([...state.reviews, ...comments.reviews.map(review => ({ ...review, comment: true as const }))]) }
299
+ await ask(new Map([...wanting()].filter(([key]) => !asked.has(key))))
300
+ }
301
+ const dirs = held.map(dir => reviewedDirectory(dir, (pkg, bases) => {
302
+ const judged = judge(pkg, bases, context)
303
+ return judged.wants && passed.has(askedOf(pkg)[0]) ? { review: { reviewed: true }, wants: false } : judged
304
+ }))
305
+ const unread = baselineUnread.filter(path => heldTo(scope, path))
306
+ const listed = dirs.flatMap(dir => 'unreviewed' in dir ? [dir] : [])
307
+ return { ...answered, cut, lockfiles: dirs.map(dir => 'unreviewed' in dir ? capped(dir) : dir), review: { required: state.required,
308
+ since: reviewed ? null : state.since, canReview: state.canReview, ...reviewed ? { reviewedDependencies: true } : {},
309
+ toReview: distinct(listed.map(dir => dir.toReview), versionKey), unreviewed: distinct(listed.map(dir => dir.unreviewed), versionKey),
310
+ unsupported: distinct(listed.map(dir => dir.unsupported), sourceKey),
311
+ ...unasked > 0 ? { unasked } : {}, ...baselineError && !reviewed ? { baselineError } : {},
312
+ ...comments.reviews.length > 0 ? { commentReviews: new Set(comments.reviews.map(review => review.reviewer)).size } : {}, ...comments.failed ? { commentsFailed: true } : {},
313
+ ...unread.length > 0 && !reviewed ? { baselineUnread: unread.slice(0, MAX_UNREVIEWED) } : {}, ...isEvery(scope) ? {} : { lockfiles: scope } } }
314
+ }
315
+
316
+ // The package versions a pull request's lockfiles lock that its reviews here
317
+ // may pass, whose reviews are asked: those that can be reviewed.
318
+ export const reviewedPackages = (told: PullDependencies) => told.lockfiles
319
+ .flatMap(dir => 'error' in dir ? [] : dir.locked.filter(pkg => reviewedAs(pkg) === 'version').map(pkg => ({ name: pkg.name, version: pkg.version! })))
320
+
321
+ // A repository's baseline as read for a pull request: its versions and the
322
+ // lockfiles there left unread; none where it reviews since no commit; and
323
+ // where GitHub doesn't read it, none and why.
324
+ export async function baselineFor(fullName: string, token: string, repoId: number, state: RepoReviewState, kept: ReviewBaselineStore, reads: LockfileStore | null,
325
+ asked?: GithubAsked) {
326
+ if (!state.since) return { baseline: null, unread: [], error: null }
327
+ try {
328
+ const { versions, unread } = await reviewBaseline(fullName, token, repoId, state.since, kept, reads, asked)
329
+ return { baseline: versions, unread, error: null }
330
+ } catch (err) {
331
+ if (err instanceof GithubApiError && err.status !== 429 && err.status !== 401) return { baseline: null, unread: [], error: err.message }
332
+ throw err
333
+ }
334
+ }
@@ -0,0 +1,205 @@
1
+ // What an open pull request's reviews say, as the code viewer's Pull requests
2
+ // tab and a pull request's popup show it (repository-issues.ts): who
3
+ // reviewed it and how, each by their latest review and the commit it was on,
4
+ // its author's own aside (the replies GitHub makes reviews of in a thread);
5
+ // whose review is requested, and how many more than those read; its review
6
+ // threads open and resolved, the latest read (open ones are, mostly, those
7
+ // lately opened), the gravest open one by the P0–P3 badge Codex marks a
8
+ // finding with; and
9
+ // Codex's own, which it keeps in a comment of its own (its summary, edited in
10
+ // place) rather than in reviews, reviewing only where it finds something:
11
+ // the commit its code review and its security review were last on, either
12
+ // one still running, asked for again since, or failed since. A review an
13
+ // agentic workflow (gh-aw) posted, as GitHub Actions' bot, names its
14
+ // workflow by the marker gh-aw leaves (`<!-- gh-aw-workflow-id: NAME -->`), in
15
+ // the popup, which reads reviews' bodies.
16
+ import { githubAgent } from '../common/managed/github-agents.ts'
17
+ import { ACTOR, type GraphAccount, actorOf } from './github-accounts.ts'
18
+
19
+ const REVIEWERS = 20
20
+ const REQUESTS = 10
21
+ // The threads the Pull requests tab counts, and those a popup lists.
22
+ export const TILE_THREADS = 50
23
+ export const ITEM_THREADS = 100
24
+ // The comments read for Codex's: its summary among the first, posted as the
25
+ // pull request opens, or among the last, where it was first asked later;
26
+ // asking it again, and its failures, among the last.
27
+ const FIRST_COMMENTS = 5
28
+ const LAST_COMMENTS = 20
29
+ const MAX_TITLE = 200
30
+ const MAX_PATH = 1000
31
+ const COMMIT = /^[a-f\d]{40}$/u
32
+
33
+ // The fields a pull request's reviews are read by, its threads' places and
34
+ // links with them for its popup (`detail`). A team requested is no reviewer
35
+ // read, but one of those requested GitHub names no one for: reading a team
36
+ // needs its organization's Members permission, and a query reading one
37
+ // without it fails whole (as one naming an EnterpriseTeam, which GitHub's
38
+ // docs name and its API knows none of, does).
39
+ export const reviewFields = (threads: number, detail: boolean) => `headRefOid
40
+ latestReviews(first: ${REVIEWERS}) { totalCount nodes { author { ${ACTOR} } state submittedAt commit { oid }${detail ? ' body' : ''} } }
41
+ reviewRequests(first: ${REQUESTS}) { totalCount nodes { requestedReviewer { __typename ... on User { login databaseId } ... on Bot { login databaseId }
42
+ ... on Mannequin { login databaseId } } } }
43
+ reviewThreads(last: ${threads}) { totalCount nodes { isResolved isOutdated${detail ? ' path line originalLine' : ''}
44
+ comments(first: 1) { nodes { author { ${ACTOR} } body${detail ? ' url' : ''} } } } }
45
+ firstComments: comments(first: ${FIRST_COMMENTS}) { nodes { author { ${ACTOR} } body updatedAt } }
46
+ lastComments: comments(last: ${LAST_COMMENTS}) { nodes { author { ${ACTOR} } body createdAt updatedAt } }`
47
+
48
+ // The fields read for reviews that GitHub may refuse alone, as it refuses an
49
+ // App a pull request's checks: their pull request then shows no reviews.
50
+ const REVIEW_PATHS = new Set(['latestReviews', 'reviewRequests', 'reviewThreads', 'firstComments', 'lastComments'])
51
+ export const reviewsRefused = (error: { type?: unknown; path?: unknown } | null | undefined) => error?.type === 'FORBIDDEN' && Array.isArray(error.path)
52
+ && error.path.some(part => REVIEW_PATHS.has(part as string))
53
+
54
+ type Comment = { author?: GraphAccount; body?: unknown; updatedAt?: unknown; createdAt?: unknown } | null
55
+ type Thread = { isResolved?: unknown; isOutdated?: unknown; path?: unknown; line?: unknown; originalLine?: unknown
56
+ comments?: { nodes?: (Comment & { url?: unknown })[] } | null } | null
57
+ export type ReviewNode = {
58
+ headRefOid?: unknown
59
+ latestReviews?: { totalCount?: unknown; nodes?: ({ author?: GraphAccount; state?: unknown; submittedAt?: unknown; commit?: { oid?: unknown } | null; body?: unknown } | null)[] } | null
60
+ reviewRequests?: { totalCount?: unknown; nodes?: ({ requestedReviewer?: { __typename?: unknown; login?: unknown; databaseId?: unknown } | null } | null)[] } | null
61
+ reviewThreads?: { totalCount?: unknown; nodes?: Thread[] } | null
62
+ firstComments?: { nodes?: Comment[] } | null
63
+ lastComments?: { nodes?: Comment[] } | null
64
+ }
65
+
66
+ const STATES: Record<string, string> = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes', COMMENTED: 'commented', DISMISSED: 'dismissed' }
67
+ const CODEX_STATES: Record<string, string> = { completed: 'done', running: 'running', queued: 'running', pending: 'running', in_progress: 'running', failed: 'failed', error: 'failed' }
68
+ const SEVERITY = /!\[(P[0-3]) Badge\]/u
69
+ const SUMMARY = /<!--\s*codex-review-state:v1\s+(\{[^]*?\})\s*-->/u
70
+ // Asking it to review again reruns its code review alone, never its security review.
71
+ const ASKED = /^@codex\s+review\b/iu
72
+ const FAILED = /^Codex Review: Something went wrong/u
73
+ const WORKFLOW = /<!--\s*gh-aw-workflow-id:\s*([\w.-]{1,100})\s*-->/u
74
+
75
+ const timeOf = (value: unknown) => {
76
+ const at = typeof value === 'string' ? Date.parse(value) : Number.NaN
77
+ return Number.isSafeInteger(at) ? at : null
78
+ }
79
+ const commitOf = (value: unknown) => typeof value === 'string' && COMMIT.test(value.toLowerCase()) ? value.toLowerCase() : null
80
+ const textOf = (value: unknown) => typeof value === 'string' ? value : ''
81
+ const isCodex = (account: GraphAccount) => {
82
+ const { login, id } = actorOf(account)
83
+ return login !== null && githubAgent(login, id) === 'codex'
84
+ }
85
+
86
+ // A finding's gravity, by its badge, `p0` the gravest; null for none.
87
+ const severityOf = (body: string) => SEVERITY.exec(body.slice(0, 500))?.[1]?.toLowerCase() ?? null
88
+ // A thread's title: its first comment's first line with words, as written,
89
+ // but for Codex's badge and emphasis.
90
+ function titleOf(body: string) {
91
+ for (const line of body.split('\n', 6)) {
92
+ const words = line.replaceAll(/!\[[^\]]*\]\([^)]*\)|<\/?sub>|\*\*|__/gu, '').trim()
93
+ if (words) return words.slice(0, MAX_TITLE)
94
+ }
95
+ return ''
96
+ }
97
+
98
+ // Codex's review of one kind, as its summary names it: the commit it was
99
+ // last on and how it stands.
100
+ function codexReview(value: unknown) {
101
+ const review = value && typeof value === 'object' ? value as { commit_sha?: unknown; status?: unknown } : null
102
+ if (!review) return null
103
+ return { commit: commitOf(review.commit_sha), status: CODEX_STATES[String(review.status)] ?? null }
104
+ }
105
+
106
+ // What Codex's summary says of its reviews, else null.
107
+ function summaryState(body: string): { code_review?: unknown; security_review?: unknown } | null {
108
+ try {
109
+ const value: unknown = JSON.parse(SUMMARY.exec(body)?.[1] ?? 'null')
110
+ return value && typeof value === 'object' ? value : null
111
+ } catch { return null }
112
+ }
113
+
114
+ // Codex's reviews, from its summary, else none: its account, as the summary
115
+ // names it; whether it was asked again since the summary last changed
116
+ // (`@codex review`), and whether it failed since it was last asked.
117
+ function codexOf(node: ReviewNode) {
118
+ const summary = [...node.firstComments?.nodes ?? [], ...node.lastComments?.nodes ?? []]
119
+ .find(comment => comment && isCodex(comment.author) && SUMMARY.test(textOf(comment.body)))
120
+ if (!summary) return null
121
+ const state = summaryState(textOf(summary.body))
122
+ if (!state) return null
123
+ const since = timeOf(summary.updatedAt) ?? 0
124
+ const later = (node.lastComments?.nodes ?? []).filter(comment => comment && (timeOf(comment.createdAt) ?? 0) > since) as NonNullable<Comment>[]
125
+ const at = (comment: NonNullable<Comment> | undefined) => comment ? timeOf(comment.createdAt) ?? 0 : null
126
+ const asked = at(later.findLast(comment => !isCodex(comment.author) && ASKED.test(textOf(comment.body).trim())))
127
+ const failed = at(later.findLast(comment => isCodex(comment.author) && FAILED.test(textOf(comment.body).trim())))
128
+ const { login, id } = actorOf(summary.author)
129
+ return { login, id, code: codexReview(state.code_review), security: codexReview(state.security_review),
130
+ requested: asked !== null && !(failed !== null && failed > asked), failed: failed !== null && (asked === null || failed > asked) }
131
+ }
132
+
133
+ type Reviewer = { login: string | null; id: number | null; workflow?: string; state: string | null; requested: boolean; commit: string | null; at: number | null }
134
+
135
+ // The reviewers, each once: by their latest review, its state and commit;
136
+ // whose is requested (again, for one who reviewed), a user, a bot (Copilot's
137
+ // code review, asked for, is its bot's) or an imported account's mannequin.
138
+ // Codex's reviews are its summary's where it has one (`codex`). How many
139
+ // requested GitHub named no one for, a team among them, as `unnamed`,
140
+ // counted with those past the ones read.
141
+ function reviewersOf(node: ReviewNode, author: string | null, codex: boolean) {
142
+ const own = author?.toLowerCase()
143
+ const reviewers: Reviewer[] = (node.latestReviews?.nodes ?? []).flatMap(review => {
144
+ const { login, id } = actorOf(review?.author)
145
+ const state = STATES[String(review?.state)]
146
+ if (!state || (login !== null && login.toLowerCase() === own) || (codex && isCodex(review?.author))) return []
147
+ const workflow = WORKFLOW.exec(textOf(review?.body))?.[1]
148
+ return [{ login, id, ...workflow ? { workflow } : {}, state, requested: false, commit: commitOf(review?.commit?.oid), at: timeOf(review?.submittedAt) }]
149
+ })
150
+ let unnamed = 0
151
+ for (const request of node.reviewRequests?.nodes ?? []) {
152
+ const reviewer = request?.requestedReviewer
153
+ const { login, id } = actorOf(reviewer)
154
+ if (login === null) {
155
+ unnamed++
156
+ continue
157
+ }
158
+ // By their account where both name it, as GitHub may name one account
159
+ // otherwise on its reviews than on its requests (Copilot's code review's
160
+ // bot); else by their login.
161
+ const reviewed = reviewers.find(item => id !== null && item.id !== null ? item.id === id : item.login?.toLowerCase() === login.toLowerCase())
162
+ if (reviewed) reviewed.requested = true
163
+ else reviewers.push({ login, id, state: null, requested: true, commit: null, at: null })
164
+ }
165
+ return { reviewers, unnamed }
166
+ }
167
+
168
+ // Its review threads, the latest read: how many are open and resolved,
169
+ // whether more than those read are, the gravest open one; and, for its popup (`detail`), each
170
+ // open one: its gravity, title, file and line, whether its code changed
171
+ // since, who opened it and where it is on GitHub.
172
+ function threadsOf(node: ReviewNode, detail: boolean) {
173
+ const threads = (node.reviewThreads?.nodes ?? []).filter(Boolean) as NonNullable<Thread>[]
174
+ const open = threads.filter(thread => thread.isResolved !== true)
175
+ const severities = open.map(thread => severityOf(textOf(thread.comments?.nodes?.[0]?.body))).filter(Boolean) as string[]
176
+ const total = node.reviewThreads?.totalCount
177
+ const counted = { open: open.length, resolved: threads.length - open.length,
178
+ more: Number.isSafeInteger(total) && (total as number) > threads.length, severity: severities.toSorted()[0] ?? null }
179
+ if (!detail) return counted
180
+ return { ...counted, list: open.map(thread => {
181
+ const first = thread.comments?.nodes?.[0]
182
+ const body = textOf(first?.body)
183
+ const opener = actorOf(first?.author)
184
+ const line = Number.isSafeInteger(thread.line) ? thread.line : Number.isSafeInteger(thread.originalLine) ? thread.originalLine : null
185
+ const url = typeof first?.url === 'string' && first.url.startsWith('https://github.com/') ? first.url : null
186
+ return { severity: severityOf(body), title: titleOf(body), path: typeof thread.path === 'string' ? thread.path.slice(0, MAX_PATH) : null, line,
187
+ outdated: thread.isOutdated === true, author: opener.login, authorId: opener.id, url }
188
+ }) }
189
+ }
190
+
191
+ // A pull request's reviews (`author` its author's login), for its tile or,
192
+ // with its threads listed, its popup (`detail`); null where none was read, or
193
+ // GitHub refused its reviews, requests or threads (reviewsRefused), rather
194
+ // than none.
195
+ export function pullReviews(node: ReviewNode, author: string | null, detail = false) {
196
+ if (node.headRefOid === undefined || node.latestReviews === null || node.reviewRequests === null || node.reviewThreads === null) return null
197
+ const codex = codexOf(node)
198
+ // Those past the reviews and the requests read, as many as GitHub counts,
199
+ // apart: a review unread may be on the latest commit, a request never is.
200
+ const past = (connection: { totalCount?: unknown; nodes?: unknown[] } | null | undefined) => Number.isSafeInteger(connection?.totalCount)
201
+ ? Math.max(0, (connection!.totalCount as number) - (connection!.nodes?.length ?? 0)) : 0
202
+ const { reviewers, unnamed } = reviewersOf(node, author, codex !== null)
203
+ return { head: commitOf(node.headRefOid), reviewers, moreReviews: past(node.latestReviews), moreRequests: past(node.reviewRequests) + unnamed,
204
+ threads: threadsOf(node, detail), codex }
205
+ }
@@ -0,0 +1,39 @@
1
+ // Items in the order they are added, each taken once by whichever reader asks
2
+ // first: none once closed and all taken, or once `signal` aborts, but those
3
+ // added by then where `drain`, none waited for.
4
+ export interface Queue<T> { add(item: T): void; close(): void; take(): Promise<T | undefined> }
5
+ export function queue<T>(signal: AbortSignal, { drain = false } = {}): Queue<T> {
6
+ const items: T[] = []
7
+ const waiting: (() => void)[] = []
8
+ let closed = false
9
+ const wake = () => { for (const resolve of waiting.splice(0)) resolve() }
10
+ signal.addEventListener('abort', wake, { once: true })
11
+ return {
12
+ add(item) { items.push(item); wake() },
13
+ close() { closed = true; wake() },
14
+ async take() {
15
+ for (;;) {
16
+ if (signal.aborted && !drain) return undefined
17
+ const item = items.shift()
18
+ if (item !== undefined || closed || signal.aborted) return item
19
+ await new Promise<void>(resolve => { waiting.push(resolve) })
20
+ }
21
+ },
22
+ }
23
+ }
24
+
25
+ // Work done `count` at a time, in the order asked, the rest waiting their
26
+ // turn.
27
+ export function inTurns(count: number): <T>(work: () => Promise<T>) => Promise<T> {
28
+ let active = 0
29
+ const waiting: (() => void)[] = []
30
+ return async work => {
31
+ if (active < count) active++
32
+ else await new Promise<void>(resolve => { waiting.push(resolve) })
33
+ try { return await work() } finally {
34
+ const next = waiting.shift()
35
+ if (next) next()
36
+ else active--
37
+ }
38
+ }
39
+ }