@preventive/triage 1.0.0-alpha.8 → 1.0.0-alpha.80

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 (442) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  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 +6 -0
  13. package/common/bundle-compare-diff.js +377 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -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 +69 -0
  19. package/common/bundle-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-5AVGKFMR.js +1 -0
  111. package/out/chunk-5CJKUV53.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-6CCSTJWB.js +1 -0
  116. package/out/chunk-6VOB5WXX.js +2 -0
  117. package/out/chunk-6Y6PZ2BU.js +9 -0
  118. package/out/chunk-74JZTGTO.js +11 -0
  119. package/out/chunk-7BKKYVWR.js +7 -0
  120. package/out/chunk-7C7DWL7I.js +1 -0
  121. package/out/chunk-7HP2VYIC.js +2 -0
  122. package/out/chunk-7YFJUT2P.js +1 -0
  123. package/out/chunk-7YO4QV5P.js +1 -0
  124. package/out/chunk-A4BBBHQU.js +1 -0
  125. package/out/chunk-B64CTMVU.js +4 -0
  126. package/out/chunk-BEKYZCPX.js +14 -0
  127. package/out/chunk-C4Z6ZBXV.js +10 -0
  128. package/out/chunk-CU3FPB3P.js +1 -0
  129. package/out/chunk-DEVAORP2.js +1 -0
  130. package/out/chunk-DUASGS2O.js +8 -0
  131. package/out/chunk-DUS5ARE2.js +53 -0
  132. package/out/chunk-EEJA7JBI.js +13 -0
  133. package/out/chunk-FSU2PLJL.js +1 -0
  134. package/out/chunk-GBMAXAYK.js +3 -0
  135. package/out/chunk-GO7FT4OD.js +1 -0
  136. package/out/chunk-GX5UXWT4.js +1 -0
  137. package/out/chunk-ITUKKCCK.js +10 -0
  138. package/out/chunk-IYPY47MC.js +1 -0
  139. package/out/chunk-JXBRWLMA.js +4 -0
  140. package/out/chunk-K4XJHM2T.js +1 -0
  141. package/out/chunk-LBD3M3J6.js +1 -0
  142. package/out/chunk-LVSLM7HB.js +1 -0
  143. package/out/chunk-LVW7WWV4.js +1 -0
  144. package/out/chunk-MV66NL3G.js +3 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OOJM4CTU.js +1 -0
  148. package/out/chunk-OWSEQOL5.js +1 -0
  149. package/out/chunk-PKLVXUEI.js +11 -0
  150. package/out/chunk-PLGH63UC.js +2 -0
  151. package/out/chunk-PNHBZGDD.js +1 -0
  152. package/out/chunk-PTFYDJUP.js +1 -0
  153. package/out/chunk-PWFUOLZK.js +17 -0
  154. package/out/chunk-PXK7EU4V.js +1 -0
  155. package/out/chunk-QD3IBSF4.js +7 -0
  156. package/out/chunk-QI66YA4F.js +1 -0
  157. package/out/chunk-QRKFPLA4.js +80 -0
  158. package/out/chunk-R3NZFXVR.js +1 -0
  159. package/out/chunk-R5O6FAW4.js +2 -0
  160. package/out/chunk-RPNO56H2.js +1 -0
  161. package/out/chunk-SSPDMA6D.js +1 -0
  162. package/out/chunk-SZWPYLPC.js +1 -0
  163. package/out/chunk-TUII34K2.js +1 -0
  164. package/out/chunk-UJP4PQJA.js +1 -0
  165. package/out/chunk-UJSJMXEG.js +1 -0
  166. package/out/chunk-UR4WYMIP.js +1 -0
  167. package/out/chunk-VHEXSGGP.js +1 -0
  168. package/out/chunk-VYYUMYVW.js +9 -0
  169. package/out/chunk-VZPPX6MV.js +1 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-XM4RLC4A.js +2 -0
  172. package/out/chunk-YKCRCNYZ.js +266 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +341 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +563 -0
  202. package/risk/files/script.js +402 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +247 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1914 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +143 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6324 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,422 @@
1
+ // What the code viewer's Agents tab reconstructs agents' sessions
2
+ // from (GET /api/admin/repositories/agents, common/managed/agent-tasks.ts):
3
+ // a page of the repository's pull requests, the most recently updated first,
4
+ // as kept for the Pulse too (repository-pulls.ts readPulls), those past
5
+ // them searched for, and of its default branch's commits, the newest first,
6
+ // those no pull request merged, read from its history as the Commits tab
7
+ // keeps it, the
8
+ // marks an agent left kept with each (repository-history.ts commitMarks),
9
+ // whether a pull request brought one looked up for those marked alone, and
10
+ // kept by the commit; on the first page, its latest issues and the newest of
11
+ // its agents' branches (GitHub lists branches by name alone, so every one an
12
+ // agent's prefix names is read, as many as fifty pages of each, and the newest
13
+ // kept). Each artifact's own texts (never comments: an agent links its
14
+ // session in a pull request's body and its commits' messages) are read here
15
+ // for the marks an agent leaves, and a pull request's labels for one naming
16
+ // an agent, and those alone are answered, never the texts. GraphQL alone
17
+ // gives them, so it needs a token.
18
+ import { type AgentAuthor, type AgentBranch, type AgentCommit, type AgentIssue, type AgentPull, type AgentSignals, type AppAgent, agentSignals } from '../common/managed/agent-tasks.ts'
19
+ import { GITHUB_AGENTS, type GithubAgentAccount, type GithubAgentId, githubAgent } from '../common/managed/github-agents.ts'
20
+ import { AGENT_BRANCH_PREFIXES, APP_AGENTS } from './app-agents.ts'
21
+ import { ACTOR, type GraphAccount, type GraphActor, type NamedAccount, actorOf, commitAccount, linkNoreplyUsers } from './github-accounts.ts'
22
+ import { githubGraphql, notFound } from './github-graphql.ts'
23
+ import { SHA, count, nameOf, timeOf } from './github-values.ts'
24
+ import { ALL_BRANCHES, type Connection, type HistoryCommit, type HistoryPages, commitIds, commitMarks, commitsQuery, historyFrom, historyMarks, inBatches, messageMarks,
25
+ nextCursor } from './repository-history.ts'
26
+ import type { IssueList, PullList } from './repository-pulls.ts'
27
+
28
+ const AGENT_PULLS_PAGE = 50
29
+ const AGENT_COMMITS_PAGE = 100
30
+ const AGENT_ISSUES = 100
31
+ const AGENT_BRANCHES = 500
32
+ const CLOSES = 5
33
+ // A pull request's labels read, for one naming an agent: GitHub's most a
34
+ // page.
35
+ const LABELS = 100
36
+ const MAX_TITLE = 1000
37
+ // Commits whether a pull request brought each is looked up of, in a query,
38
+ // and queries at once.
39
+ const PULLED_COMMITS = 100
40
+ const PULLED_PARALLEL = 4
41
+
42
+ // The app agents' accounts' no-reply addresses, by each login of theirs.
43
+ const AGENT_EMAILS = APP_AGENTS.flatMap(({ id }) => GITHUB_AGENTS[id as GithubAgentId].accounts
44
+ .flatMap(({ id: account, logins }: GithubAgentAccount) => account === undefined ? [] : logins.map(login => `${account}+${login}@users.noreply.github.com`)))
45
+
46
+ // Branches' tip commits, `c<n>` the `n`th's: each's message and author.
47
+ const tipsQuery = (size: number) => commitsQuery(size, 'c', 'message author { email user { login databaseId } }')
48
+ // Tips looked up a query, and queries at once.
49
+ const TIPS = 100
50
+ const TIPS_PARALLEL = 4
51
+ // An agent's branches, a page at a time, as GitHub lists them by name, where
52
+ // the repository's branches as kept stop short of them (`cut`): each its tip
53
+ // and when that was committed; as many pages of each as MAX_BRANCH_PAGES.
54
+ const BRANCHES_QUERY = `query($owner: String!, $name: String!, $prefix: String!, $after: String) {
55
+ repository(owner: $owner, name: $name) {
56
+ refs(refPrefix: $prefix, first: 100, after: $after) {
57
+ pageInfo { hasNextPage endCursor }
58
+ nodes { prefix name target { oid ... on Commit { committedDate } } }
59
+ }
60
+ }
61
+ }`
62
+ const MAX_BRANCH_PAGES = 50
63
+ // What a commit of the default branch is read by.
64
+ const COMMIT_FIELDS = 'oid messageHeadline message committedDate additions deletions author { email user { login databaseId } } associatedPullRequests(first: 1) { totalCount }'
65
+ // The newest of the commits from the default branch's head the app agents'
66
+ // accounts authored, by their GitHub no-reply addresses, however far back: a
67
+ // bot's commits pushed with no pull request here (as before a repository
68
+ // moved) may lie deeper than pages are read on to.
69
+ const AUTHORED_QUERY = `query($owner: String!, $name: String!, $head: GitObjectID!, $emails: [String!]!) {
70
+ repository(owner: $owner, name: $name) {
71
+ object(oid: $head) { ... on Commit { history(first: ${AGENT_COMMITS_PAGE}, author: { emails: $emails }) { nodes { ${COMMIT_FIELDS} } } } }
72
+ }
73
+ }`
74
+ // What a pull request is read by, for its row (pull): its texts for the
75
+ // marks an agent leaves in them (its body, its last commit's message, its
76
+ // merge commit's), never answered; its commits counted beside (`commits {
77
+ // totalCount }`, as the reads of it ask theirs).
78
+ export const AGENT_PULL_FIELDS = `number title state isDraft createdAt updatedAt author { __typename ${ACTOR} } body headRefName isCrossRepository
79
+ headRepositoryOwner { login } additions deletions last: commits(last: 1) { nodes { commit { message } } } mergeCommit { message }
80
+ closingIssuesReferences(first: ${CLOSES}) { nodes { number } } labels(first: ${LABELS}) { nodes { name } }`
81
+ // What an issue is read by, for its row (issue).
82
+ export const AGENT_ISSUE_FIELDS = `number title state createdAt updatedAt author { __typename ${ACTOR} }`
83
+ // The latest issues, however long ago they were updated.
84
+ const ISSUES_QUERY = `query($owner: String!, $name: String!) {
85
+ repository(owner: $owner, name: $name) {
86
+ issues(first: ${AGENT_ISSUES}, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { ${AGENT_ISSUE_FIELDS} } }
87
+ }
88
+ }`
89
+ // A page of the pull requests a search finds, as GitHub sorts them, on from
90
+ // where `after` says its page before ended.
91
+ const SEARCH_QUERY = `query($query: String!, $after: String) {
92
+ search(type: ISSUE, query: $query, first: ${AGENT_PULLS_PAGE}, after: $after) {
93
+ pageInfo { endCursor } nodes { ... on PullRequest { ${AGENT_PULL_FIELDS} commits { totalCount } } }
94
+ }
95
+ }`
96
+
97
+ export type PullNode = { number?: unknown; title?: unknown; state?: unknown; isDraft?: unknown; createdAt?: unknown; updatedAt?: unknown; author?: GraphAccount; body?: unknown
98
+ headRefName?: unknown; isCrossRepository?: unknown; headRepositoryOwner?: GraphAccount; additions?: unknown; deletions?: unknown; commits?: { totalCount?: unknown } | null
99
+ last?: { nodes?: ({ commit?: { message?: unknown } | null } | null)[] } | null; mergeCommit?: { message?: unknown } | null
100
+ closingIssuesReferences?: { nodes?: ({ number?: unknown } | null)[] }; labels?: { nodes?: ({ name?: unknown } | null)[] } }
101
+ type CommitNode = { oid?: unknown; messageHeadline?: unknown; message?: unknown; committedDate?: unknown; additions?: unknown; deletions?: unknown
102
+ author?: GraphActor | null; associatedPullRequests?: { totalCount?: unknown } }
103
+ export type IssueNode = { number?: unknown; title?: unknown; state?: unknown; createdAt?: unknown; updatedAt?: unknown; author?: GraphAccount }
104
+ // Whether a pull request brought each commit, `c<n>` the `n`th's.
105
+ const pulledQuery = (size: number) => commitsQuery(size, 'c', 'associatedPullRequests(first: 1) { totalCount }')
106
+ type Pulled = { repository?: Record<string, { associatedPullRequests?: { totalCount?: unknown } } | null> | null }
107
+ type Authored = { repository?: { object?: { history?: Connection<CommitNode> } | null } | null }
108
+ type Issues = { repository?: { issues?: Connection<IssueNode> } | null }
109
+ type Tips = { repository?: Record<string, { message?: unknown; author?: GraphActor | null } | null> | null }
110
+ type RefNode = { prefix?: unknown; name?: unknown; target?: { oid?: unknown; committedDate?: unknown } | null }
111
+ type RefsPage = { repository?: { refs?: Connection<RefNode> } | null }
112
+ type Found = { search?: { pageInfo?: { endCursor?: unknown }; nodes?: (PullNode | null)[] } | null } | null
113
+
114
+ const number = (value: unknown) => Number.isSafeInteger(value) && (value as number) > 0 ? value as number : null
115
+ const PULL_STATES: Record<string, AgentPull['state']> = { OPEN: 'open', MERGED: 'merged', CLOSED: 'closed' }
116
+
117
+ // A pull request's row: what it is, and the marks an agent left on it.
118
+ export function pull(node: PullNode | null): AgentPull | null {
119
+ const at = number(node?.number)
120
+ if (!node || !at) return null
121
+ const author = actorOf(node.author)
122
+ return { number: at, title: nameOf(node.title, MAX_TITLE) ?? '', state: PULL_STATES[String(node.state)] ?? 'closed', draft: node.isDraft === true,
123
+ author: author.login, authorId: author.id, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt), head: nameOf(node.headRefName),
124
+ // A fork's, its owner; one GitHub no longer names, a fork of its own.
125
+ fork: node.isCrossRepository === true ? actorOf(node.headRepositoryOwner).login ?? `pull-${at}` : null,
126
+ additions: count(node.additions), deletions: count(node.deletions), commits: count(node.commits?.totalCount),
127
+ closes: (node.closingIssuesReferences?.nodes ?? []).flatMap(closed => number(closed?.number) ?? []),
128
+ signals: agentSignals([node.body, node.last?.nodes?.[0]?.commit?.message, node.mergeCommit?.message], APP_AGENTS, nameOf(node.headRefName),
129
+ both(author), (node.labels?.nodes ?? []).map(label => label?.name)) }
130
+ }
131
+
132
+ // An account as GitHub names it, by its login and id, both.
133
+ const both = ({ login, id }: NamedAccount): AgentAuthor | null => login !== null && id !== null ? { login, id } : null
134
+ // A commit's author: the account GitHub knows by its address, else the one
135
+ // its no-reply address names by id and login, as a bot's, Copilot's or
136
+ // Dependabot's, is told by that alone (repository-history.ts commitAccount).
137
+ const authorOf = (actor: GraphActor | null | undefined) => both(commitAccount(actor))
138
+
139
+ // A commit the app agents' accounts authored, as kept: as read, its
140
+ // message's marks (messageMarks) in its place, never the message.
141
+ export type AuthoredCommit = Omit<CommitNode, 'message'> & { marks: AgentSignals | null }
142
+ const authoredOf = ({ message, ...node }: CommitNode): AuthoredCommit => ({ ...node, marks: messageMarks(message) })
143
+
144
+ // A commit to the default branch no pull request merged, where an agent left
145
+ // its marks on it, or Claude authored it (commitMarks).
146
+ function directCommit(node: AuthoredCommit | null): AgentCommit | null {
147
+ if (!node || typeof node.oid !== 'string' || !SHA.test(node.oid) || count(node.associatedPullRequests?.totalCount) > 0) return null
148
+ const author = authorOf(node.author)
149
+ const signals = commitMarks(node.marks, { name: null, email: node.author?.email, account: commitAccount(node.author) })
150
+ if (!signals) return null
151
+ return { oid: node.oid, title: nameOf(node.messageHeadline, MAX_TITLE) ?? '', at: timeOf(node.committedDate),
152
+ author: author?.login ?? actorOf(node.author?.user).login, authorId: author?.id ?? null,
153
+ additions: count(node.additions), deletions: count(node.deletions), signals }
154
+ }
155
+
156
+ // A commit of the history kept an agent marked (`signals`,
157
+ // repository-history.ts historyMarks), as one of the default branch's.
158
+ const keptCommit = (commit: HistoryCommit, signals: AgentSignals): AgentCommit => ({ oid: commit.sha, title: commit.subject, at: commit.committedAt,
159
+ author: commit.authorLogin, authorId: commit.authorId ?? null, additions: commit.additions ?? 0, deletions: commit.deletions ?? 0, signals })
160
+
161
+ // Whether a pull request brought each commit, kept by the commit.
162
+ export interface CommitPulls {
163
+ read(shas: string[]): Promise<Map<string, boolean>>
164
+ write(sha: string, pulled: boolean): Promise<void>
165
+ }
166
+
167
+ // Those of `shas` a pull request brought: as kept (`kept`), the rest looked
168
+ // up, PULLED_COMMITS a query, and kept; one GitHub has none of, none.
169
+ async function pulledCommits(fullName: string, token: string, shas: string[], kept: CommitPulls, fetchImpl: typeof fetch) {
170
+ const [owner, name] = fullName.split('/') as [string, string]
171
+ const known = await kept.read(shas)
172
+ await inBatches(shas.filter(sha => !known.has(sha)), PULLED_COMMITS, PULLED_PARALLEL, async batch => {
173
+ const data = await githubGraphql(pulledQuery(batch.length), { owner, name, ...commitIds(batch) }, token, fetchImpl, notFound) as Pulled
174
+ await Promise.all(batch.map((sha, at) => {
175
+ const node = data?.repository?.[`c${at}`]
176
+ if (!node) return Promise.resolve()
177
+ known.set(sha, count(node.associatedPullRequests?.totalCount) > 0)
178
+ return kept.write(sha, known.get(sha)!)
179
+ }))
180
+ })
181
+ return new Set(shas.filter(sha => known.get(sha) === true))
182
+ }
183
+
184
+ // Where commits listed stop: those the cursor named but left unread still
185
+ // unlisted (`left`, newer than those below the commits read from the rest),
186
+ // then the parents of those listed not listed, the newest first (each by its
187
+ // child's time), as the Commits tab reads on from (repository-history.js):
188
+ // each read in its turn, as many as ALL_BRANCHES an answer, none dropped
189
+ // till MAX_FRONTIER are left (a cursor's length bounded, a URL's); null
190
+ // where none are.
191
+ function frontier(commits: HistoryCommit[], left: string[]) {
192
+ const listed = new Set(commits.map(commit => commit.sha))
193
+ const at = new Map<string, number>()
194
+ for (const commit of commits) {
195
+ for (const parent of commit.parents) if (!listed.has(parent)) at.set(parent, Math.max(at.get(parent) ?? Number.NEGATIVE_INFINITY, commit.committedAt ?? 0))
196
+ }
197
+ const below = [...at].toSorted((a, b) => b[1] - a[1]).map(([sha]) => sha)
198
+ const starts = [...new Set([...left.filter(sha => !listed.has(sha)), ...below])].slice(0, MAX_FRONTIER)
199
+ return starts.length > 0 ? starts.join(',') : null
200
+ }
201
+
202
+ // An issue's row: what it is, and who opened it.
203
+ export function issue(node: IssueNode | null): AgentIssue | null {
204
+ const at = number(node?.number)
205
+ if (!node || !at) return null
206
+ const author = actorOf(node.author)
207
+ return { number: at, title: nameOf(node.title, MAX_TITLE) ?? '', state: node.state === 'OPEN' ? 'open' : 'closed', author: author.login,
208
+ authorId: author.id, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt) }
209
+ }
210
+
211
+ // A branch's tip, as kept: its message's marks (messageMarks), never the
212
+ // message, and its author as read.
213
+ export interface BranchTip { marks: AgentSignals | null; author: GraphActor | null }
214
+ // The tips of branches, kept by their commits, which never change.
215
+ export interface BranchTips {
216
+ read(shas: string[]): Promise<Map<string, BranchTip>>
217
+ write(sha: string, tip: BranchTip): Promise<void>
218
+ }
219
+
220
+ // A branch an agent's prefix names (`name`), its tip (`sha`) committed `at`,
221
+ // as the Agents tab shows it: its tip's author, and the marks an agent left
222
+ // on it, its tip's message's, its author's account an agent's, or its name
223
+ // under an agent's prefix, as agent-tasks.ts agentSignals tells them.
224
+ function agentBranch({ name, at }: { name: string; at: number | null }, tip: BranchTip | undefined): AgentBranch {
225
+ const author = authorOf(tip?.author)
226
+ const authored = author ? githubAgent(author.login, author.id) : null
227
+ const marks = tip?.marks
228
+ return { name, at, author: author?.login ?? actorOf(tip?.author?.user).login, authorId: author?.id ?? null, signals: { sessions: marks?.sessions ?? [],
229
+ tasks: marks?.tasks ?? [], claude: marks?.claude ?? false, codex: marks?.codex ?? false,
230
+ agents: APP_AGENTS.flatMap(({ id, prefix }) => marks?.agents.includes(id) || authored === id || name.startsWith(prefix) ? [id] : []) } }
231
+ }
232
+
233
+ // The branches under `prefix`, every one, as many as MAX_BRANCH_PAGES of
234
+ // them list, named in full however GitHub splits its name from the prefix.
235
+ async function prefixHeads(owner: string, name: string, prefix: string, token: string, fetchImpl: typeof fetch) {
236
+ const found: Head[] = []
237
+ let after: string | null = null
238
+ for (let page = 0; page < MAX_BRANCH_PAGES; page++) {
239
+ const refs = (await githubGraphql(BRANCHES_QUERY, { owner, name, prefix: `refs/heads/${prefix}`, after }, token, fetchImpl) as RefsPage)?.repository?.refs
240
+ for (const node of refs?.nodes ?? []) {
241
+ const ref = typeof node?.prefix === 'string' && typeof node.name === 'string' ? `${node.prefix}${node.name}` : null
242
+ const branch = ref?.startsWith('refs/heads/') ? nameOf(ref.slice('refs/heads/'.length)) : null
243
+ const sha = node?.target?.oid
244
+ if (branch?.startsWith(prefix) && typeof sha === 'string' && SHA.test(sha)) found.push({ name: branch, sha, at: timeOf(node!.target!.committedDate) })
245
+ }
246
+ after = nextCursor(refs?.pageInfo)
247
+ if (after === null) break
248
+ }
249
+ return found
250
+ }
251
+
252
+ // The newest of the agents' branches, those each prefix names, as many as
253
+ // AGENT_BRANCHES of each, of the repository's branches as kept (`heads`, as
254
+ // the Commits tab reads them; those it stops short of, `cut`, listed by each
255
+ // prefix), their tips as kept (`tips`), those not looked up, TIPS a query,
256
+ // and kept.
257
+ async function agentBranches(fullName: string, token: string, { heads, cut }: { heads: Head[]; cut: boolean }, tips: BranchTips, fetchImpl: typeof fetch) {
258
+ const [owner, name] = fullName.split('/') as [string, string]
259
+ const all = cut ? (await Promise.all(AGENT_BRANCH_PREFIXES.map(prefix => prefixHeads(owner, name, prefix, token, fetchImpl)))).flat() : heads
260
+ const named = AGENT_BRANCH_PREFIXES.flatMap(prefix => all.filter(head => head.name.startsWith(prefix))
261
+ .toSorted((a, b) => (b.at ?? 0) - (a.at ?? 0)).slice(0, AGENT_BRANCHES))
262
+ const shown = named.filter((head, index) => named.findIndex(other => other.name === head.name) === index)
263
+ const shas = [...new Set(shown.map(head => head.sha))]
264
+ const known = await tips.read(shas)
265
+ await inBatches(shas.filter(sha => !known.has(sha)), TIPS, TIPS_PARALLEL, async batch => {
266
+ const data = await githubGraphql(tipsQuery(batch.length), { owner, name, ...commitIds(batch) }, token, fetchImpl, notFound) as Tips
267
+ await linkNoreplyUsers(batch.map((_, at) => data?.repository?.[`c${at}`]?.author), token, fetchImpl)
268
+ await Promise.all(batch.map((sha, at) => {
269
+ const node = data?.repository?.[`c${at}`]
270
+ if (!node) return Promise.resolve()
271
+ known.set(sha, { marks: messageMarks(node.message), author: node.author ?? null })
272
+ return tips.write(sha, known.get(sha)!)
273
+ }))
274
+ })
275
+ return shown.map(head => agentBranch(head, known.get(head.sha)))
276
+ }
277
+
278
+ // The commits from `head` the app agents' accounts authored (AUTHORED_QUERY),
279
+ // as kept by it (`kept`), else read and kept.
280
+ async function authoredCommits(fullName: string, token: string, head: string, kept: AuthoredCommits, fetchImpl: typeof fetch) {
281
+ const [owner, name] = fullName.split('/') as [string, string]
282
+ const key = `${head}\0${AGENT_EMAILS.join(',')}`
283
+ const known = await kept.read(key)
284
+ if (known) return known
285
+ const data = await githubGraphql(AUTHORED_QUERY, { owner, name, head, emails: AGENT_EMAILS }, token, fetchImpl) as Authored
286
+ const nodes = (data?.repository?.object?.history?.nodes ?? []).flatMap(node => node ? [authoredOf(node)] : [])
287
+ await linkNoreplyUsers(nodes.map(node => node.author), token, fetchImpl)
288
+ await kept.write(key, nodes)
289
+ return nodes
290
+ }
291
+
292
+ // What its answers are kept by, with their cursors (http.ts
293
+ // handleRepositoryAgents): bumped as what a page reads, or how it tells an
294
+ // agent, changes (with AGENT_MARKS_READ, app-agents.ts, where commits' marks
295
+ // do), so that no answer an older server kept is sent for a day.
296
+ export const AGENTS_READ_VERSION = 9
297
+
298
+ // A cursor of the default branch's commits: those the pages before stopped
299
+ // at (frontier), as many as MAX_FRONTIER, commas between, the first
300
+ // ALL_BRANCHES of them read next; one an older server gave, GitHub's,
301
+ // `<oid> <offset>`, read on from its commit.
302
+ const MAX_FRONTIER = 4 * ALL_BRANCHES
303
+ export const COMMITS_CURSOR = new RegExp(`^(?:[\\da-f]{40}(?:,[\\da-f]{40}){0,${MAX_FRONTIER - 1}}|[\\da-f]{40} \\d{1,9})$`, 'u')
304
+ const startsOf = (cursor: string) => cursor.split(/[ ,]/u).filter(part => SHA.test(part))
305
+
306
+ // A cursor of the pull requests: the last listed, by when it was updated and
307
+ // its number (`<ms>.<number>`), those below it read next; of a search's page
308
+ // all updated together, the time it searched by and where its page ended too
309
+ // (`~<ms>~<cursor>`), those updated with them read on through the same
310
+ // search; any other, as an older server gave (GitHub's), read from the
311
+ // newest again.
312
+ const POSITION = /^(\d{1,15})\.(\d{1,10})(?:~(\d{1,15})~([\w+/=-]{1,200}))?$/u
313
+ const positionOf = (item: AgentPull) => `${item.updatedAt ?? 0}.${item.number}`
314
+ // Those updated by a time, as GitHub's search takes it, to the second; any
315
+ // where it names none.
316
+ const updatedBy = (at: number) => Number.isFinite(at) ? ` updated:<=${new Date(at).toISOString().replace(/\.\d{3}Z$/u, '+00:00')}` : ''
317
+
318
+ // A branch: its name, its tip, and when that was committed.
319
+ type Head = { name: string; sha: string; at: number | null }
320
+ // The commits the app agents' accounts authored from a head (AUTHORED_QUERY),
321
+ // kept by it and the addresses they were asked by (`key`).
322
+ interface AuthoredCommits {
323
+ read(key: string): Promise<AuthoredCommit[] | null>
324
+ write(key: string, commits: AuthoredCommit[]): Promise<void>
325
+ }
326
+ // What the repository's tabs read and keep together (http.ts): its pull
327
+ // requests and its issues (repository-pulls.ts PullList, IssueList), each
328
+ // read as far back as their first page where none are, and those updated
329
+ // since read as they are (keptList), its default branch's head (defaultTip),
330
+ // its branches, as the Commits tab reads them (`heads`, whether they stop
331
+ // short of some, `cut`), their tips (`tips`), and the commits its app
332
+ // agents' accounts authored (`authored`).
333
+ export interface Kept { pulls(): Promise<PullList>; issues(): Promise<IssueList>; head(): Promise<string | null>; heads(): Promise<{ heads: Head[]; cut: boolean }>
334
+ tips: BranchTips
335
+ authored: AuthoredCommits }
336
+
337
+ // A page of the repository's pull requests, the most recently updated
338
+ // first, below the one `cursor` names (none: from the newest): of those kept
339
+ // (`kept`), as far back as every one is read; past them, as GitHub's search
340
+ // finds those updated before, a page a query. With where it reads on from,
341
+ // null where none are left: past every one kept where all are.
342
+ async function agentPulls(fullName: string, token: string, cursor: string | null, kept: Kept['pulls'], fetchImpl: typeof fetch) {
343
+ const at = cursor === null ? null : POSITION.exec(cursor)
344
+ const [time, past] = at ? [Number(at[1]), Number(at[2])] : [Number.POSITIVE_INFINITY, 0]
345
+ const below = (item: AgentPull) => (item.updatedAt ?? 0) < time || ((item.updatedAt ?? 0) === time && item.number < past)
346
+ const list = await kept()
347
+ // Since when every one updated is read (as repository-pulls.ts pullsReadTo
348
+ // tells, which reads its pages by these fields): all since the year's
349
+ // start, -∞.
350
+ const read = list.next ? list.next.to ?? Number.POSITIVE_INFINITY : list.reach ?? Number.NEGATIVE_INFINITY
351
+ // As far back as every one is read: the year's start, where all since are.
352
+ const bottom = Math.max(read, list.since)
353
+ const listed = list.rows.filter(item => below(item) && (item.updatedAt ?? 0) >= bottom)
354
+ const whole = list.all === true && read === Number.NEGATIVE_INFINITY
355
+ if (listed.length > 0) {
356
+ const page = listed.slice(0, AGENT_PULLS_PAGE)
357
+ return { pulls: page, after: listed.length > page.length || !whole ? positionOf(page.at(-1)!) : null }
358
+ }
359
+ if (whole) return { pulls: [], after: null }
360
+ // Those updated by when the last was, those updated with it again among
361
+ // them (GitHub orders those by no number), the last itself left out; a
362
+ // page all updated together read on through the same search, past them.
363
+ const [by, through] = at?.[3] === undefined ? [Math.min(time, bottom), null] : [Number(at[3]), at[4]!]
364
+ const found = await githubGraphql(SEARCH_QUERY, { query: `repo:${fullName} is:pr sort:updated-desc${updatedBy(by)}`, after: through }, token, fetchImpl) as Found
365
+ const nodes = found?.search?.nodes ?? []
366
+ const rows = nodes.flatMap(node => pull(node) ?? [])
367
+ const last = rows.at(-1)
368
+ const ended = found?.search?.pageInfo?.endCursor
369
+ const together = Number.isFinite(by) && rows.every(item => item.updatedAt === last?.updatedAt) && typeof ended === 'string' && /^[\w+/=-]{1,200}$/u.test(ended)
370
+ const after = nodes.length >= AGENT_PULLS_PAGE && last ? `${positionOf(last)}${together ? `~${by}~${ended}` : ''}` : null
371
+ return { pulls: rows.filter(item => item.updatedAt !== time || item.number !== past), after: after === cursor ? null : after }
372
+ }
373
+
374
+ // The repository's latest issues, as many as AGENT_ISSUES: of those kept
375
+ // (`kept`), where they hold as many, or every one the repository has; else
376
+ // read, as those kept hold none updated before the year they are read for.
377
+ async function latestIssues(fullName: string, token: string, kept: Kept['issues'], fetchImpl: typeof fetch): Promise<AgentIssue[]> {
378
+ const list = await kept()
379
+ if (list.rows.length >= AGENT_ISSUES || list.all) return list.rows.slice(0, AGENT_ISSUES).map(({ bot: _bot, closedAt: _closedAt, reason: _reason, ...row }) => row)
380
+ const [owner, name] = fullName.split('/') as [string, string]
381
+ const data = await githubGraphql(ISSUES_QUERY, { owner, name }, token, fetchImpl) as Issues
382
+ return (data?.repository?.issues?.nodes ?? []).flatMap(node => issue(node) ?? [])
383
+ }
384
+
385
+ // A page of what the repository's agents left: its pull requests below the
386
+ // one the cursor `pulls` names, as kept (`kept`, agentPulls), its default
387
+ // branch's commits on from those `commits` names, as its history is kept
388
+ // (`pages`, historyFrom: the first page from its head, as kept), whether a
389
+ // pull request brought those marked kept (`pulled`) (the first page where
390
+ // neither is named, with its latest issues, as kept, its agents' branches
391
+ // and the commits the app agents' accounts authored, and the app agents it
392
+ // may name), and the cursors reading on from each, null where either is
393
+ // read whole.
394
+ export async function repositoryAgents(fullName: string, token: string, cursors: { pulls: string | null; commits: string | null }, pages: HistoryPages,
395
+ pulled: CommitPulls, kept: Kept, fetchImpl: typeof fetch = globalThis.fetch) {
396
+ const first = cursors.pulls === null && cursors.commits === null
397
+ const tip = first ? kept.head() : Promise.resolve(null)
398
+ const [head, issues, branches, nodes, pulls] = await Promise.all([
399
+ tip,
400
+ first ? latestIssues(fullName, token, kept.issues, fetchImpl) : [],
401
+ first ? kept.heads().then(heads => agentBranches(fullName, token, heads, kept.tips, fetchImpl)) : [],
402
+ tip.then(sha => typeof sha === 'string' && SHA.test(sha) ? authoredCommits(fullName, token, sha, kept.authored, fetchImpl) : []),
403
+ first || cursors.pulls !== null ? agentPulls(fullName, token, cursors.pulls, kept.pulls, fetchImpl) : { pulls: [], after: null },
404
+ ])
405
+ const named = cursors.commits === null ? first && typeof head === 'string' && SHA.test(head) ? [head] : [] : startsOf(cursors.commits)
406
+ const starts = named.slice(0, ALL_BRANCHES)
407
+ const history = starts.length > 0 ? (await historyFrom(fullName, token, starts, pages, fetchImpl)).commits : []
408
+ const marked = history.flatMap(commit => { const signals = historyMarks(commit); return signals ? [{ commit, signals }] : [] })
409
+ const brought = await pulledCommits(fullName, token, marked.map(({ commit }) => commit.sha), pulled, fetchImpl)
410
+ const commits = [...marked.flatMap(({ commit, signals }) => brought.has(commit.sha) ? [] : [keptCommit(commit, signals)]), ...nodes.flatMap(node => directCommit(node) ?? [])]
411
+ const after = { pulls: pulls.after, commits: frontier(history, named.slice(ALL_BRANCHES)) }
412
+ return {
413
+ pulls: pulls.pulls.map(({ bot: _bot, merged: _merged, ...row }: AgentPull & { bot?: unknown; merged?: unknown }) => row),
414
+ commits: commits.filter((commit, index) => commits.findIndex(other => other.oid === commit.oid) === index),
415
+ ...first ? {
416
+ issues,
417
+ branches,
418
+ agents: APP_AGENTS.map(({ id, name: agent, avatar }): AppAgent => ({ id, name: agent, ...avatar ? { avatar } : {} })),
419
+ } : {},
420
+ more: after.pulls !== null || after.commits !== null, after,
421
+ }
422
+ }
@@ -0,0 +1,119 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { reportRepoGithub } from '@preventive/report'
3
+ import { type RepositoryAliasInput, matchRepositoryAlias, repositoryAliasNeedsFilePrefix } from '../common/managed/repository-alias.ts'
4
+ import type { ManagedDb } from './db.ts'
5
+ import { ManagedMutationError, sessionAdmin } from './management.ts'
6
+ import { normalizeTeamPath } from './repo-path.ts'
7
+ import type { ManagedSql } from './sql.ts'
8
+
9
+ export const REPOSITORY_ALIAS_SCHEMA = `
10
+ CREATE TABLE IF NOT EXISTS managed_repository_alias (
11
+ id TEXT PRIMARY KEY,
12
+ old_repo TEXT NOT NULL,
13
+ old_path TEXT NOT NULL DEFAULT '',
14
+ repo_id INTEGER NOT NULL REFERENCES managed_selected_repo(repo_id) ON DELETE CASCADE,
15
+ new_path TEXT NOT NULL DEFAULT '',
16
+ UNIQUE(old_repo, old_path)
17
+ ) STRICT;
18
+ `
19
+ export interface RepositoryAlias extends RepositoryAliasInput { id: string }
20
+ export interface RepositoryAliasStore {
21
+ listRepositoryAliases(): Promise<RepositoryAlias[]>
22
+ saveRepositoryAlias(sessionId: string, id: string | null, input: unknown): Promise<RepositoryAlias>
23
+ deleteRepositoryAlias(sessionId: string, id: string): Promise<void>
24
+ getRepositoryImportLocation(github: string, directory: string, filePrefix?: string): Promise<{ repoId: number | null; directory: string }>
25
+ // Connected repository `repo.repoId`, which GitHub renamed or transferred
26
+ // since it was named `from`, named as GitHub names it now (`fullName`,
27
+ // `htmlUrl`), and `from` an alias of the whole of it, as reports and
28
+ // bundles made before name it: where GitHub still sends `from` to it
29
+ // (`redirected`) and nothing here has that name, no repository connected
30
+ // (active or not) nor an alias of a whole repository. Resolves whether it
31
+ // was renamed here: false where it is no longer named `from`, as where
32
+ // another request renamed it first.
33
+ renameRepository(repo: { repoId: number; fullName: string; htmlUrl: string }, from: string, redirected: boolean): Promise<boolean>
34
+ }
35
+
36
+ // Keep expensive inventory reads outside database transactions and skip them
37
+ // unless a currently connected alias can use the bundle's existing paths.
38
+ export async function resolveRepositoryImportLocation(db: ManagedDb, github: string, directory: string, loadFilePrefix: () => Promise<string>) {
39
+ const aliases = await db.listRepositoryAliases()
40
+ let filePrefix = ''
41
+ if (repositoryAliasNeedsFilePrefix(github, directory, aliases)) {
42
+ const active = new Set((await db.listSelectedRepos()).map(repo => repo.repoId))
43
+ if (repositoryAliasNeedsFilePrefix(github, directory, aliases.filter(alias => active.has(alias.repoId)))) filePrefix = await loadFilePrefix()
44
+ }
45
+ return db.getRepositoryImportLocation(github, directory, filePrefix)
46
+ }
47
+
48
+ // The names our repositories go by: each active one's as connected, and each
49
+ // alias's of one of them, as reports from before a rename name it
50
+ // (renameRepository). For a finding's `repo` to tell ours by
51
+ // (common/finding-repo.js ourRepoSlugs).
52
+ export async function ourRepositoryNames(db: Pick<ManagedDb, 'listSelectedRepos' | 'listRepositoryAliases'>): Promise<string[]> {
53
+ const [repos, aliases] = await Promise.all([db.listSelectedRepos(), db.listRepositoryAliases()])
54
+ const active = new Set(repos.map(repo => repo.repoId))
55
+ return [...repos.map(repo => repo.fullName), ...aliases.filter(alias => active.has(alias.repoId)).map(alias => alias.oldRepo)]
56
+ }
57
+
58
+ function parseAlias(input: unknown): RepositoryAliasInput {
59
+ if (!input || typeof input !== 'object') throw new ManagedMutationError(400, 'bad-alias')
60
+ const { oldRepo, oldPath, repoId, newPath } = input as RepositoryAliasInput
61
+ const github = typeof oldRepo === 'string' ? reportRepoGithub({ repo: { github: oldRepo.trim() } }) : null
62
+ if (!github) throw new ManagedMutationError(400, 'bad-old-repo')
63
+ if (typeof oldPath !== 'string' || typeof newPath !== 'string') throw new ManagedMutationError(400, 'bad-directory')
64
+ const old = normalizeTeamPath(oldPath), target = normalizeTeamPath(newPath)
65
+ if (!old.ok || !target.ok) throw new ManagedMutationError(400, 'bad-directory')
66
+ if (!Number.isSafeInteger(repoId) || repoId <= 0) throw new ManagedMutationError(400, 'bad-repo')
67
+ return { oldRepo: github.toLowerCase(), oldPath: old.path ?? '', repoId, newPath: target.path ?? '' }
68
+ }
69
+
70
+ export function repositoryAliasMethods(db: ManagedSql): RepositoryAliasStore {
71
+ async function listRepositoryAliases() {
72
+ return await db.prepare(`SELECT id, old_repo AS oldRepo, old_path AS oldPath, repo_id AS repoId, new_path AS newPath
73
+ FROM managed_repository_alias ORDER BY old_repo, old_path, id`).all() as RepositoryAlias[]
74
+ }
75
+ return {
76
+ listRepositoryAliases,
77
+ async saveRepositoryAlias(sessionId, id, input) {
78
+ await sessionAdmin(db, sessionId)
79
+ const alias = parseAlias(input)
80
+ if (!await db.prepare('SELECT repo_id FROM managed_selected_repo WHERE repo_id = ? AND active = 1').get(alias.repoId)) throw new ManagedMutationError(400, 'bad-repo')
81
+ if (id && !await db.prepare('SELECT id FROM managed_repository_alias WHERE id = ?').get(id)) throw new ManagedMutationError(404, 'no-alias')
82
+ const duplicate = await db.prepare('SELECT id FROM managed_repository_alias WHERE old_repo = ? AND old_path = ?').get(alias.oldRepo, alias.oldPath) as { id: string } | undefined
83
+ if (duplicate && duplicate.id !== id) throw new ManagedMutationError(409, 'alias-exists')
84
+ const key = id ?? randomUUID()
85
+ await db.prepare(`INSERT INTO managed_repository_alias (id, old_repo, old_path, repo_id, new_path) VALUES (?, ?, ?, ?, ?)
86
+ ON CONFLICT(id) DO UPDATE SET old_repo = excluded.old_repo, old_path = excluded.old_path, repo_id = excluded.repo_id, new_path = excluded.new_path`)
87
+ .run(key, alias.oldRepo, alias.oldPath, alias.repoId, alias.newPath)
88
+ return { id: key, ...alias }
89
+ },
90
+ async deleteRepositoryAlias(sessionId, id) {
91
+ await sessionAdmin(db, sessionId)
92
+ if (!(await db.prepare('DELETE FROM managed_repository_alias WHERE id = ?').run(id)).changes) throw new ManagedMutationError(404, 'no-alias')
93
+ },
94
+ async renameRepository(repo, from, redirected) {
95
+ if (!Number((await db.prepare('UPDATE managed_selected_repo SET full_name = ?, html_url = ?, updated_at = ? WHERE repo_id = ? AND full_name = ?')
96
+ .run(repo.fullName, repo.htmlUrl, Date.now(), repo.repoId, from)).changes)) return false
97
+ // Normalized as an administrator's is (parseAlias); none where only the
98
+ // name's case changed, which aliases never tell apart.
99
+ const old = reportRepoGithub({ repo: { github: from } })?.toLowerCase()
100
+ if (!redirected || !old || old === repo.fullName.toLowerCase()) return true
101
+ const taken = await db.prepare(`SELECT 1 AS taken FROM managed_selected_repo WHERE LOWER(full_name) = ?
102
+ UNION ALL SELECT 1 AS taken FROM managed_repository_alias WHERE old_repo = ? AND old_path = ''`).get(old, old)
103
+ if (!taken) {
104
+ await db.prepare(`INSERT INTO managed_repository_alias (id, old_repo, old_path, repo_id, new_path) VALUES (?, ?, '', ?, '')`)
105
+ .run(randomUUID(), old, repo.repoId)
106
+ }
107
+ return true
108
+ },
109
+ async getRepositoryImportLocation(github, directory, filePrefix = '') {
110
+ const alias = matchRepositoryAlias(github, directory, await listRepositoryAliases(), filePrefix)
111
+ const normalized = normalizeTeamPath(alias?.directory ?? directory)
112
+ if (!normalized.ok) throw new ManagedMutationError(400, 'bad-directory')
113
+ const repo = await (alias
114
+ ? db.prepare('SELECT repo_id AS repoId FROM managed_selected_repo WHERE active = 1 AND repo_id = ?').get(alias.repoId)
115
+ : db.prepare('SELECT repo_id AS repoId FROM managed_selected_repo WHERE active = 1 AND LOWER(full_name) = ?').get(github.toLowerCase())) as { repoId: number } | undefined
116
+ return { repoId: repo?.repoId ?? null, directory: normalized.path ?? '' }
117
+ },
118
+ }
119
+ }