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

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-563V5VVT.js +266 -0
  111. package/out/chunk-5AVGKFMR.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-5UJHJWFU.js +4 -0
  116. package/out/chunk-6CCSTJWB.js +1 -0
  117. package/out/chunk-6VOB5WXX.js +2 -0
  118. package/out/chunk-6WMQVUT2.js +3 -0
  119. package/out/chunk-6Y6PZ2BU.js +9 -0
  120. package/out/chunk-74JZTGTO.js +11 -0
  121. package/out/chunk-7BKKYVWR.js +7 -0
  122. package/out/chunk-7C7DWL7I.js +1 -0
  123. package/out/chunk-7HP2VYIC.js +2 -0
  124. package/out/chunk-7YFJUT2P.js +1 -0
  125. package/out/chunk-7YO4QV5P.js +1 -0
  126. package/out/chunk-A4BBBHQU.js +1 -0
  127. package/out/chunk-B64CTMVU.js +4 -0
  128. package/out/chunk-BEKYZCPX.js +14 -0
  129. package/out/chunk-C4Z6ZBXV.js +10 -0
  130. package/out/chunk-CU3FPB3P.js +1 -0
  131. package/out/chunk-DEVAORP2.js +1 -0
  132. package/out/chunk-DOYTKRIR.js +53 -0
  133. package/out/chunk-DUASGS2O.js +8 -0
  134. package/out/chunk-EEJA7JBI.js +13 -0
  135. package/out/chunk-FSU2PLJL.js +1 -0
  136. package/out/chunk-GO7FT4OD.js +1 -0
  137. package/out/chunk-GX5UXWT4.js +1 -0
  138. package/out/chunk-H4FEC57K.js +1 -0
  139. package/out/chunk-ITUKKCCK.js +10 -0
  140. package/out/chunk-IYPY47MC.js +1 -0
  141. package/out/chunk-K4XJHM2T.js +1 -0
  142. package/out/chunk-LBD3M3J6.js +1 -0
  143. package/out/chunk-LVSLM7HB.js +1 -0
  144. package/out/chunk-LVW7WWV4.js +1 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OAWQNDAO.js +3 -0
  148. package/out/chunk-OOJM4CTU.js +1 -0
  149. package/out/chunk-PEE47ANR.js +1 -0
  150. package/out/chunk-PKLVXUEI.js +11 -0
  151. package/out/chunk-PLGH63UC.js +2 -0
  152. package/out/chunk-PNHBZGDD.js +1 -0
  153. package/out/chunk-PTFYDJUP.js +1 -0
  154. package/out/chunk-PWFUOLZK.js +17 -0
  155. package/out/chunk-PXK7EU4V.js +1 -0
  156. package/out/chunk-QD3IBSF4.js +7 -0
  157. package/out/chunk-QI66YA4F.js +1 -0
  158. package/out/chunk-QRKFPLA4.js +80 -0
  159. package/out/chunk-R3NZFXVR.js +1 -0
  160. package/out/chunk-R5O6FAW4.js +2 -0
  161. package/out/chunk-RPNO56H2.js +1 -0
  162. package/out/chunk-SSPDMA6D.js +1 -0
  163. package/out/chunk-SZWPYLPC.js +1 -0
  164. package/out/chunk-TUII34K2.js +1 -0
  165. package/out/chunk-UJP4PQJA.js +1 -0
  166. package/out/chunk-UJSJMXEG.js +1 -0
  167. package/out/chunk-UR4WYMIP.js +1 -0
  168. package/out/chunk-VHEXSGGP.js +1 -0
  169. package/out/chunk-VYYUMYVW.js +9 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-WFBVS4QI.js +1 -0
  172. package/out/chunk-XM4RLC4A.js +2 -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 +354 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +568 -0
  202. package/risk/files/script.js +410 -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 +269 -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 +1915 -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 +158 -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 +6327 -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
@@ -26,6 +26,8 @@ type WireRevision = {
26
26
  signature: string
27
27
  }
28
28
 
29
+ type SubscriptionLookup = { resume: () => void }
30
+
29
31
  // Structured result of the shared save pipeline (`commitSave`), rendered
30
32
  // per transport: WS → protocol frames; REST → JSON + HTTP status.
31
33
  type SaveOutcome =
@@ -79,6 +81,7 @@ export type SyncHandlersDeps = {
79
81
  // payload budget. Optional: a SQLite deployment passes a no-op.
80
82
  publishRevision: (tag: string, revisionId: string) => void
81
83
  subscribe: (socket: WebSocket, tag: string) => void
84
+ pauseBroadcasts: (socket: WebSocket) => () => void
82
85
  getNonce: (socket: WebSocket) => string | undefined
83
86
  requiresAuth: (socket: WebSocket) => boolean
84
87
  // Whether an operator password is configured. The REST save plane's
@@ -101,7 +104,7 @@ export type SyncHandlersDeps = {
101
104
  export type SyncHandlers = {
102
105
  handleSave: (socket: WebSocket, msg: SaveMsg) => Promise<void>
103
106
  // Session-independent REST save plane (`POST /api/sync/save`), wired into
104
- // the HTTP dispatcher in server/http.ts. Runs the same pipeline as
107
+ // the HTTP dispatcher in server-e2e/http.ts. Runs the same pipeline as
105
108
  // `handleSave` and renders the outcome as a JSON response.
106
109
  handleSaveRest: (req: IncomingMessage, res: ServerResponse) => Promise<void>
107
110
  handleSubscribe: (socket: WebSocket, msg: SubscribeMsg) => Promise<void>
@@ -112,6 +115,9 @@ export type SyncHandlers = {
112
115
 
113
116
  export function createSyncHandlers(deps: SyncHandlersDeps): SyncHandlers {
114
117
  const { handle, send, broadcast, publishRevision, subscribe, getNonce, requiresAuth, passwordConfigured, sendUnauthorized, workspaceExists, objstoreResources, debug } = deps
118
+ // Only the newest lookup for a socket/tag may publish a snapshot.
119
+ // Versions cannot order different object incarnations (or deletions).
120
+ const subscriptionLookups = new WeakMap<WebSocket, Map<string, SubscriptionLookup>>()
115
121
 
116
122
  // Typed wrapper for the three `workspace-save-error` emit sites
117
123
  // (too-large at handleSave, stale-base after the catch-up, busy at
@@ -238,6 +244,14 @@ export function createSyncHandlers(deps: SyncHandlersDeps): SyncHandlers {
238
244
  // chain in the 409 body. Either way the catch-up clears the client's
239
245
  // pending and the error is a no-op on the now-missing pending (a
240
246
  // recoverable race — client rebases + re-saves).
247
+ //
248
+ // The catch-up CAN be empty: a client holding a base from a chain
249
+ // this deployment no longer has (wiped / moved DB, SQLite→Neon
250
+ // migration — head=null, no keyframe, no rows) gets `revisions: []`.
251
+ // The client detects that shape (pending survives the catch-up) and
252
+ // answers with a full-state push re-anchored at base=null, which
253
+ // commits as the new chain root — see the client's
254
+ // `handleSaveError` stale-base branch.
241
255
  const revisions = chainForWire(await chainFrom(handle, tag, baseNorm))
242
256
  if (debug) console.log(`save (stale base ${baseNorm} vs head ${commit.head}) → chain ${revisions.length}`)
243
257
  return { kind: 'stale-base', base: baseNorm, revisions }
@@ -291,7 +305,7 @@ export function createSyncHandlers(deps: SyncHandlersDeps): SyncHandlers {
291
305
  // maps the outcome to a JSON + HTTP status the client switches on. SSE-mode
292
306
  // clients POST here so a save doesn't take over their event-stream; a 401
293
307
  // routes them to the in-band frame (which runs the operator auth flow).
294
- // Mounted + gated (same-origin, shutdown, idle-timeout) in server/http.ts.
308
+ // Mounted + gated (same-origin, shutdown, idle-timeout) in server-e2e/http.ts.
295
309
  async function handleSaveRest(req: IncomingMessage, res: ServerResponse): Promise<void> {
296
310
  const body = await readSaveBody(req)
297
311
  if (!body || typeof body !== 'object') { respondJson(res, 400, { reason: 'bad-request' }); return }
@@ -340,34 +354,54 @@ export function createSyncHandlers(deps: SyncHandlersDeps): SyncHandlers {
340
354
  return
341
355
  }
342
356
  const tag = msg.workspaceTag
343
- subscribe(socket, tag)
344
- // Explicit ack — distinguishes "the server processed my subscribe
345
- // and registered me as a peer" from "the WebSocket is open". A
346
- // client that sent a malformed / bad-sig subscribe never gets this;
347
- // a client that did gets one before the chain arrives. Lets the UI
348
- // surface a `connecting → online` transition based on real handshake
349
- // completion, not just socket state.
350
- //
351
- // The ack also carries the objstore inventory snapshot: the same
352
- // subscribe that registers this socket for objstore-put / -deleted
353
- // broadcasts seeds the client's initial inventory in one handshake.
354
- // The client keeps it live thereafter from those broadcasts.
355
- // Returns [] for a triage-only workspace. A failing inventory
356
- // lookup must NOT sink the subscribe — degrade to an empty snapshot
357
- // (broadcasts will fill it in) so the ack + chain still go out.
358
- let resources: object[] = []
359
- try { resources = await objstoreResources(tag) }
360
- catch (err) { if (debug) console.warn('subscribe: objstore inventory lookup failed', debugTag(tag), err) }
361
- send(socket, { type: 'workspace-subscribed', workspaceTag: tag, resources })
362
- // `from` is the last revision id the client claims to have applied —
363
- // now a base64url string, not an integer. We send only revisions
364
- // after that. Client lying about `from` just means they get a
365
- // smaller catch-up — their subsequent saves will reveal stale state
366
- // on the usual base-mismatch path. Null / missing → full chain.
367
- const fromId = typeof msg.from === 'string' ? msg.from : null
368
- const revisions = chainForWire(await chainFrom(handle, tag, fromId))
369
- if (debug) console.log(`subscribe ${debugTag(tag)} from=${fromId?.slice(0, 8) ?? 'null'} → chain ${revisions.length}`)
370
- send(socket, { type: 'workspace-state', workspaceTag: tag, revisions })
357
+ const lookups = subscriptionLookups.get(socket) ?? new Map<string, SubscriptionLookup>()
358
+ subscriptionLookups.set(socket, lookups)
359
+ const previous = lookups.get(tag)
360
+ const resume = deps.pauseBroadcasts(socket)
361
+ const lookup = { resume }
362
+ lookups.set(tag, lookup)
363
+ // Acquire the replacement's pause before releasing its predecessor so
364
+ // buffered broadcasts cannot overtake the replacement snapshot. A hung
365
+ // obsolete read must not keep the whole socket paused. The hub's release
366
+ // is idempotent, so the old finally can still call it when the read ends.
367
+ previous?.resume()
368
+ try {
369
+ subscribe(socket, tag)
370
+ // Explicit ack — distinguishes "the server processed my subscribe
371
+ // and registered me as a peer" from "the WebSocket is open". A
372
+ // client that sent a malformed / bad-sig subscribe never gets this;
373
+ // a client that did gets one before the chain arrives. Lets the UI
374
+ // surface a `connecting → online` transition based on real handshake
375
+ // completion, not just socket state.
376
+ //
377
+ // The ack also carries the objstore inventory snapshot: the same
378
+ // subscribe that registers this socket for objstore-put / -deleted
379
+ // broadcasts seeds the client's initial inventory in one handshake.
380
+ // The client keeps it live thereafter from those broadcasts.
381
+ // Returns [] for a triage-only workspace. A lookup failure is NOT an
382
+ // empty inventory: clients interpret absent resources as deletions.
383
+ // Reconnect to retry the complete handshake on either transport.
384
+ const resources = await objstoreResources(tag)
385
+ if (socket.readyState !== socket.OPEN || lookups.get(tag) !== lookup) return
386
+ // `from` is the last revision id the client claims to have applied —
387
+ // now a base64url string, not an integer. We send only revisions
388
+ // after that. Client lying about `from` just means they get a
389
+ // smaller catch-up — their subsequent saves will reveal stale state
390
+ // on the usual base-mismatch path. Null / missing → full chain.
391
+ const fromId = typeof msg.from === 'string' ? msg.from : null
392
+ const revisions = chainForWire(await chainFrom(handle, tag, fromId))
393
+ if (socket.readyState !== socket.OPEN || lookups.get(tag) !== lookup) return
394
+ if (debug) console.log(`subscribe ${debugTag(tag)} from=${fromId?.slice(0, 8) ?? 'null'} → chain ${revisions.length}`)
395
+ send(socket, { type: 'workspace-subscribed', workspaceTag: tag, resources })
396
+ send(socket, { type: 'workspace-state', workspaceTag: tag, revisions })
397
+ } catch (err) {
398
+ if (lookups.get(tag) !== lookup) return
399
+ if (debug) console.warn('subscribe: snapshot lookup failed', debugTag(tag), err)
400
+ socket.close(1011, 'subscription unavailable')
401
+ } finally {
402
+ if (lookups.get(tag) === lookup) lookups.delete(tag)
403
+ resume()
404
+ }
371
405
  }
372
406
 
373
407
  return { handleSave, handleSaveRest, handleSubscribe, sendSaveError }
@@ -16,6 +16,7 @@ import { Buffer } from 'node:buffer'
16
16
  import type { IncomingMessage as HttpRequest } from 'node:http'
17
17
  import { decodeUtf8 } from '../common/utf8.js'
18
18
  import type { SaveErrorReason } from '../common/save-error-reason.ts'
19
+ import type { ServerInfo } from '../common/server-info.ts'
19
20
  import { Peer, type PeerRegistry } from './peer.ts'
20
21
  import { errMsg, errStack, randomId } from './util.ts'
21
22
  import type { SaveMsg, SubscribeMsg } from './sign.ts'
@@ -36,6 +37,9 @@ type IncomingMessage = {
36
37
  // SSE path doesn't need them.
37
38
  export type PeerConnectionDeps = {
38
39
  peers: PeerRegistry
40
+ // The mode this server advertises, emitted as the first `server-info`
41
+ // frame on every connection (see setupPeerConnection).
42
+ serverInfo: ServerInfo
39
43
  send: (socket: WebSocket, msg: object) => void
40
44
  unsubscribeAll: (socket: WebSocket) => void
41
45
  handleSave: (socket: WebSocket, msg: SaveMsg) => Promise<void>
@@ -60,7 +64,7 @@ export type WsServerDeps = PeerConnectionDeps & {
60
64
  // `as unknown as WebSocket`; only the subset both expose is used.
61
65
  export function setupPeerConnection(socket: WebSocket, req: HttpRequest, deps: PeerConnectionDeps): void {
62
66
  const {
63
- peers, send, unsubscribeAll, handleSave, handleSubscribe, handleAuthenticate,
67
+ peers, serverInfo, send, unsubscribeAll, handleSave, handleSubscribe, handleAuthenticate,
64
68
  sendSaveError, objstore, track, isShuttingDown, maxInflightPerSocket, debug,
65
69
  } = deps
66
70
  if (debug) console.log(`connect from ${req.socket.remoteAddress}`)
@@ -71,13 +75,20 @@ export function setupPeerConnection(socket: WebSocket, req: HttpRequest, deps: P
71
75
  const peer = new Peer(randomId())
72
76
  peers.set(socket, peer)
73
77
  socket.on('pong', () => { peer.alive = true })
74
- // Issue the per-connection challenge nonce BEFORE the client can
75
- // send anything that needs it. The client signs it into every
76
- // `workspace-subscribe` (see canonicalSubscribe in server/sign.ts);
77
- // a captured subscribe frame can't be replayed from a different
78
- // connection because that connection's nonce differs and the
78
+ // Issue the per-connection challenge nonce FIRST — before the client can
79
+ // send anything that needs it, AND as frame #0 so clients/tests that
80
+ // positionally read the first frame as the challenge keep working. The
81
+ // client signs it into every `workspace-subscribe` (see canonicalSubscribe
82
+ // in server-e2e/sign.ts); a captured subscribe frame can't be replayed from
83
+ // a different connection because that connection's nonce differs and the
79
84
  // signature won't verify against the new canonical bytes. Round-9 H2.
80
85
  send(socket, { type: 'challenge', nonce: peer.challenge })
86
+ // Then advertise the sync protocol (the mode probe), right after the
87
+ // challenge — the WS plane and the SSE fallback share this path. A client
88
+ // uses it to detect the mode, cache it, and refuse a cross-mode switch.
89
+ // Unauthenticated + mode-agnostic; an older client ignores it (predicate
90
+ // readers skip it; the workspaceTag demux drops it).
91
+ send(socket, { type: 'server-info', ...serverInfo })
81
92
  // Per-socket handlers are DELIBERATELY NOT serialized (vs the
82
93
  // client-side `messageQueue = messageQueue.then(...)` Promise
83
94
  // chain inside `client/triage-sync.ts:onTransportMessage`).
@@ -86,10 +97,10 @@ export function setupPeerConnection(socket: WebSocket, req: HttpRequest, deps: P
86
97
  // boundaries inside the handlers. Per-resource correctness needs
87
98
  // no in-process lock: `commitRevision` resolves concurrent saves
88
99
  // via its single gated INSERT (one snapshot + the
89
- // `UNIQUE(workspace_tag, seq)` PK — see `server/db.ts`), and the
100
+ // `UNIQUE(workspace_tag, seq)` PK — see `server-e2e/db.ts`), and the
90
101
  // objstore handlers (`commitPut` / `beginPut` / `deleteObject`)
91
102
  // via the version compare-and-set + content-addressing (see
92
- // `server/objstore/store.ts`), backed by post-await
103
+ // `server-e2e/objstore/store.ts`), backed by post-await
93
104
  // `readyState === OPEN` rechecks in every objstore handler. The
94
105
  // unbounded fan-out is capped by `maxInflightPerSocket` (see
95
106
  // also the `'busy'` NACK at the cap below). Concurrent dispatch
@@ -129,7 +140,7 @@ export function setupPeerConnection(socket: WebSocket, req: HttpRequest, deps: P
129
140
  // shedding load. Pings go through a fast inline `send(pong)`
130
141
  // path BELOW that doesn't bump the per-socket inflight counter,
131
142
  // so a ping-spam at the cap can't outrun the gate. Transport
132
- // audit `server/index.ts:590` + post-#58 audit follow-up.
143
+ // audit `server-e2e/index.ts:590` + post-#58 audit follow-up.
133
144
  if (parsed.type === 'ping') {
134
145
  send(socket, { type: 'pong' })
135
146
  return
@@ -0,0 +1,269 @@
1
+ // Persistent workspace activity. Uploads are recorded in the same transaction
2
+ // as their metadata; triage reuses its existing immutable trail, including
3
+ // legacy entries. Never copy annotation bodies or credentials into this feed.
4
+ import { randomUUID } from 'node:crypto'
5
+ import type { DatabaseSync } from 'node:sqlite'
6
+ import { type ManagedSql, sqliteTransaction } from './sql.ts'
7
+ import { inUserTeamScope } from './db-schema.ts'
8
+ import { reviewsIn } from './dependency-reviews.ts'
9
+ import { REVIEW_VERDICTS } from '../common/dependency-reviews.js'
10
+
11
+ export interface ActivityInput {
12
+ kind: 'access' | 'repository' | 'visibility' | 'delete'
13
+ actor: string
14
+ actorId?: string | null
15
+ action: string
16
+ repo?: string | null
17
+ reportId?: string | null
18
+ bundleId?: string | null
19
+ repoId?: number | null
20
+ repoDirectory?: string | null
21
+ report?: string | null
22
+ }
23
+
24
+ export interface ActivityContext {
25
+ finding: string
26
+ reportId: string
27
+ report: string
28
+ repo: string | null
29
+ }
30
+
31
+ // `actor` is the login of who acted as it is now, else the one recorded;
32
+ // `actorId` the user they are (null for a legacy login), and `actorName` the
33
+ // name they chose to show, as it is now.
34
+ export type ActivityEntry = {
35
+ id: string; kind: string; actor: string | null; actorId: string | null; actorName: string | null; action: string
36
+ repo: string | null; reportId: string | null; report: string | null
37
+ finding: string | null; at: number
38
+ }
39
+
40
+ export interface ActivityQuery {
41
+ page: number
42
+ limit: number
43
+ kind: string
44
+ query: string
45
+ repo?: string
46
+ actor?: string
47
+ // null = admin; [] = no accessible findings. Context is supplied by the
48
+ // server, never by the client. It also replaces potentially private context
49
+ // from an old report carrying the same globally shared finding.
50
+ contexts: ActivityContext[] | null
51
+ userId?: string
52
+ }
53
+
54
+ export interface ActivityFilters {
55
+ repos: string[]
56
+ // `id` is the actor's filter key; `userId` the user, null for a legacy login.
57
+ users: { id: string; userId: string | null; login: string; name: string | null; detail: string | null }[]
58
+ }
59
+
60
+ export interface ActivityStore {
61
+ recordActivity(entry: ActivityInput, at: number): Promise<void>
62
+ listActivityReports(userId: string): Promise<Omit<ActivityContext, 'finding'>[]>
63
+ listActivity(query: ActivityQuery): Promise<{ history: ActivityEntry[]; total: number; page: number; limit: number; filters: ActivityFilters }>
64
+ }
65
+
66
+ const triageFields = `'triage:' || e.seq AS id, 'triage' AS kind,
67
+ COALESCE(u.login, e.actor_login) AS actor, e.actor_id AS actorId,
68
+ CASE WHEN e.color IS NULL AND e.triage IS NULL AND e.comment IS NULL AND e.fix IS NULL AND e.flagged IS NULL
69
+ THEN 'cleared triage' ELSE 'updated triage' END AS action`
70
+ const commentFields = `'comment:' || e.seq AS id, 'triage' AS kind,
71
+ COALESCE(u.login, e.actor_login) AS actor, e.actor_id AS actorId, e.action`
72
+ // The events of a finding trail (`table`), with `fields` and the context each
73
+ // recorded.
74
+ const recordedEvents = (fields: string, table: string) => `SELECT ${fields}, e.repo, e.report_id AS reportId, e.report, e.finding_id AS finding, e.at
75
+ FROM ${table} e LEFT JOIN managed_user u ON u.id = e.actor_id`
76
+ // Package reviews as published, read of the reviews themselves, never copied
77
+ // into managed_activity: each once, when it was first published, by its author
78
+ // (their login as they reviewed, and who they are), with its final verdict and
79
+ // what it reviewed as its target; never its comments. Publishing it to more
80
+ // teams, or revoking it, adds no entry. `where` narrows them.
81
+ const reviewVerdict = `CASE r.status ${Object.entries(REVIEW_VERDICTS)
82
+ .map(([status, label]) => `WHEN '${status}' THEN '${label.replace(/ \(.*\)$/u, '')}'`).join(' ')} END`
83
+ const reviewedVersion = (name: string, version: string, patch: string) => `${name} || '@' || ${version} || CASE WHEN ${patch} <> '' THEN ' (patched)' ELSE '' END`
84
+ const reviewEvents = (where = '') => `SELECT 'review:' || r.id AS id, 'review' AS kind, r.user_login AS actor, r.user_id AS actorId,
85
+ 'published a review' || COALESCE(' (' || ${reviewVerdict} || ')', '') AS action,
86
+ NULL AS repo, NULL AS reportId,
87
+ ${reviewedVersion('r.package', 'r.version', 'r.patch_hash')} || CASE WHEN r.base_package = '' THEN ''
88
+ WHEN r.base_package = r.package THEN ' compared with ' || r.base_version || CASE WHEN r.base_patch_hash <> '' THEN ' (patched)' ELSE '' END
89
+ ELSE ' compared with ' || ${reviewedVersion('r.base_package', 'r.base_version', 'r.base_patch_hash')} END AS report,
90
+ NULL AS finding, r.published_at AS at
91
+ FROM managed_dependency_review r WHERE r.published_at IS NOT NULL${where}`
92
+ const adminSource = `${recordedEvents(triageFields, 'managed_finding_triage_event')}
93
+ UNION ALL ${recordedEvents(commentFields, 'managed_finding_comment_event')} UNION ALL
94
+ SELECT id, kind, actor, actor_id AS actorId, action, repo, report_id AS reportId, report, NULL AS finding, at FROM managed_activity
95
+ UNION ALL ${reviewEvents()}`
96
+ // The events of the accessible findings in a finding trail (`table`), with
97
+ // `fields` and the context the server gives each finding. Keep the finite
98
+ // set of accessible findings outside the indexed event lookup. Scanning all
99
+ // events against json_each for every row is quadratic.
100
+ const contextEvents = (fields: string, table: string) => `SELECT ${fields},
101
+ json_extract(c.value, '$.repo') AS repo, json_extract(c.value, '$.reportId') AS reportId,
102
+ json_extract(c.value, '$.report') AS report, e.finding_id AS finding, e.at
103
+ FROM json_each(:contexts) c
104
+ CROSS JOIN ${table} e ON e.finding_id = json_extract(c.value, '$.finding')
105
+ LEFT JOIN managed_user u ON u.id = e.actor_id`
106
+ const managerSource = `${contextEvents(triageFields, 'managed_finding_triage_event')}
107
+ UNION ALL ${contextEvents(commentFields, 'managed_finding_comment_event')}
108
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId,
109
+ CASE WHEN a.kind = 'repository' THEN 'changed a report repository assignment' ELSE a.action END AS action,
110
+ p.full_name AS repo, r.id AS reportId, r.filename AS report, NULL AS finding, a.at
111
+ FROM managed_activity a JOIN managed_report r ON r.id = a.report_id
112
+ LEFT JOIN managed_selected_repo p ON p.repo_id = r.repo_id
113
+ WHERE ${inUserTeamScope(':userId', 'r')}
114
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId,
115
+ CASE WHEN a.kind = 'repository' THEN 'changed a bundle repository assignment' ELSE a.action END AS action,
116
+ p.full_name AS repo, NULL AS reportId, b.filename AS report, NULL AS finding, a.at
117
+ FROM managed_activity a JOIN managed_bundle b ON b.id = a.bundle_id
118
+ LEFT JOIN managed_selected_repo p ON p.repo_id = b.repo_id
119
+ WHERE a.report_id IS NULL AND ${inUserTeamScope(':userId', 'b')}
120
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId, a.action, a.repo, a.report_id AS reportId,
121
+ a.report, NULL AS finding, a.at FROM managed_activity a
122
+ WHERE a.kind = 'delete' AND (a.report_id IS NOT NULL OR a.bundle_id IS NOT NULL)
123
+ AND NOT EXISTS (SELECT 1 FROM managed_report WHERE id = a.report_id)
124
+ AND NOT EXISTS (SELECT 1 FROM managed_bundle WHERE id = a.bundle_id)
125
+ AND ${inUserTeamScope(':userId', 'a')}
126
+ UNION ALL ${reviewEvents(` AND (r.user_id = :userId OR EXISTS (SELECT 1 FROM managed_dependency_review_team rt
127
+ JOIN managed_team t ON t.id = rt.team_id JOIN managed_user u ON u.id = :userId
128
+ WHERE rt.review_id = r.id AND ${reviewsIn(false)}))`)}`
129
+
130
+ export const ACTIVITY_SCHEMA = `
131
+ CREATE TABLE IF NOT EXISTS managed_activity (
132
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, actor TEXT, action TEXT NOT NULL,
133
+ repo TEXT, report_id TEXT, report TEXT, at INTEGER NOT NULL,
134
+ bundle_id TEXT, repo_id INTEGER, repo_directory TEXT, actor_id TEXT
135
+ ) STRICT;
136
+ CREATE INDEX IF NOT EXISTS managed_activity_at_idx ON managed_activity(at, id);
137
+ CREATE INDEX IF NOT EXISTS finding_triage_event_at_idx ON managed_finding_triage_event(at, seq);
138
+ `
139
+
140
+ export function initActivityMethods(db: DatabaseSync): void {
141
+ db.exec(ACTIVITY_SCHEMA)
142
+ migrateActivityScope(db)
143
+ db.exec('CREATE INDEX IF NOT EXISTS managed_activity_actor_at_idx ON managed_activity(actor_id, at)')
144
+ // Stable upload IDs make backfill idempotent, including after restarts.
145
+ // Snapshots deliberately have no cascading FKs: deletion is itself activity.
146
+ // CREATE TRIGGER IF NOT EXISTS keeps an older body; replace the one that
147
+ // predates server-built bundles so builds are not recorded as uploads.
148
+ const bundleTrigger = db.prepare("SELECT sql FROM sqlite_schema WHERE type = 'trigger' AND name = 'managed_bundle_activity'").get() as { sql: string } | undefined
149
+ if (bundleTrigger && !bundleTrigger.sql.includes('provenance')) db.exec('DROP TRIGGER managed_bundle_activity')
150
+ for (const type of ['report', 'bundle']) {
151
+ const columns = `id, kind, actor, action, repo, report_id, report, at, bundle_id, actor_id`
152
+ const values = (alias: string) => `'${type}-upload:' || ${alias}.id, 'upload',
153
+ COALESCE(${alias}.uploaded_by_login, (SELECT login FROM managed_user WHERE id = ${alias}.uploaded_by)), ${uploadAction(type, alias)},
154
+ (SELECT full_name FROM managed_selected_repo WHERE repo_id = ${alias}.repo_id),
155
+ ${type === 'report' ? `${alias}.id` : 'NULL'}, ${alias}.filename, ${alias}.uploaded_at,
156
+ ${type === 'bundle' ? `${alias}.id` : 'NULL'}, ${alias}.uploaded_by`
157
+ db.exec(`
158
+ CREATE TRIGGER IF NOT EXISTS managed_${type}_activity AFTER INSERT ON managed_${type}
159
+ BEGIN INSERT INTO managed_activity (${columns}) SELECT ${values('NEW')}; END;
160
+ INSERT OR IGNORE INTO managed_activity (${columns}) SELECT ${values('source')} FROM managed_${type} source;
161
+ `)
162
+ }
163
+ }
164
+
165
+ // The creation entry for a stored report or bundle. Shared with the Postgres
166
+ // trigger function; `alias` is the trigger row (NEW) or a backfill alias.
167
+ export function uploadAction(type: string, alias: string): string {
168
+ return type === 'bundle' ? `CASE WHEN ${alias}.provenance = 'build' THEN 'built a bundle' ELSE 'uploaded a bundle' END` : `'uploaded a ${type}'`
169
+ }
170
+
171
+ export function activityMethods(db: ManagedSql): ActivityStore {
172
+ const insert = db.prepare(`INSERT INTO managed_activity (id, kind, actor, action, repo, report_id, report, at, bundle_id, repo_id, repo_directory, actor_id)
173
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
174
+ const admin = activityStatements(db, adminSource)
175
+ const manager = activityStatements(db, managerSource)
176
+ const reports = db.prepare(`SELECT r.id AS reportId, r.filename AS report, p.full_name AS repo
177
+ FROM managed_report r JOIN managed_selected_repo p ON p.repo_id = r.repo_id
178
+ WHERE ${inUserTeamScope('?', 'r')}
179
+ ORDER BY r.uploaded_at DESC, r.id`)
180
+ return {
181
+ async recordActivity(entry, at) {
182
+ await insert.run(randomUUID(), entry.kind, entry.actor, entry.action, entry.repo ?? null, entry.reportId ?? null, entry.report ?? null, at,
183
+ entry.bundleId ?? null, entry.repoId ?? null, entry.repoDirectory ?? null, entry.actorId ?? null)
184
+ },
185
+ async listActivityReports(userId) {
186
+ return (await reports.all(userId)) as Omit<ActivityContext, 'finding'>[]
187
+ },
188
+ async listActivity({ page, limit, kind, query, repo = '', actor = '', contexts, userId }) {
189
+ const stmts = contexts == null ? admin : manager
190
+ const scope = contexts == null ? {} : { contexts: JSON.stringify(contexts), userId: userId ?? '' }
191
+ const params = { ...scope, kind, query, repo, actor }
192
+ const read = async (at: number) => (await stmts.rows.all({ ...params, limit, offset: (at - 1) * limit })) as (ActivityEntry & { total: number | string })[]
193
+ // A page's rows carry the total. Only a page past the last has none to
194
+ // carry it: it is counted, and the last page read in its place.
195
+ let currentPage = page, rows = await read(page)
196
+ let total = rows.length > 0 ? Number(rows[0]!.total) : 0
197
+ if (rows.length === 0 && page > 1) {
198
+ total = Number(((await stmts.count.get(params)) as { total: number | string }).total)
199
+ currentPage = Math.min(page, Math.max(1, Math.ceil(total / limit)))
200
+ if (currentPage !== page) rows = total === 0 ? [] : await read(currentPage)
201
+ }
202
+ const history = rows.map(({ total: _total, ...entry }) => entry)
203
+ const filters: ActivityFilters = { repos: [], users: [] }
204
+ type FacetRow = { facet: string; id: string; userId: string | null; login: string; name: string | null; detail: string | null }
205
+ for (const row of (await stmts.filters.all(scope)) as FacetRow[]) {
206
+ if (row.facet === 'repo') filters.repos.push(row.id)
207
+ else filters.users.push({ id: row.id, userId: row.userId, login: row.login, name: row.name, detail: row.detail })
208
+ }
209
+ return { history, total, page: currentPage, limit, filters }
210
+ },
211
+ }
212
+ }
213
+
214
+ // Both rows and selector choices come from the authorized source. Keep legacy
215
+ // login-only actors separate: a historical login is not proof of user identity.
216
+ // A user shows by their login and name as they are now, as in the selector.
217
+ function activityStatements(db: ManagedSql, source: string) {
218
+ const activity = `WITH events AS (${source}), activity AS (
219
+ SELECT e.id, e.kind, COALESCE(u.login, e.actor) AS actor, e.actorId, u.name AS actorName, e.action,
220
+ e.repo, e.reportId, e.report, e.finding, e.at, COALESCE('user:' || e.actorId, 'legacy:' || e.actor) AS actorKey
221
+ FROM events e LEFT JOIN managed_user u ON u.id = e.actorId
222
+ )`
223
+ const filtered = `${activity} SELECT id, kind, actor, actorId, actorName, action, repo, reportId, report, finding, at FROM activity
224
+ WHERE (:kind = 'all' OR kind = :kind)
225
+ AND (:repo = '' OR repo = :repo) AND (:actor = '' OR actorKey = :actor)
226
+ AND (:query = '' OR instr(lower(coalesce(actor, '') || ' ' || coalesce(actorName, '') || ' ' || action || ' ' ||
227
+ coalesce(repo, '') || ' ' || coalesce(report, '') || ' ' || coalesce(finding, '')), lower(:query)) > 0)`
228
+ // A page's rows each carry the total, so the source is read once for both;
229
+ // the selector choices, repositories then users, once between them.
230
+ return {
231
+ count: db.prepare(`SELECT count(*) AS total FROM (${filtered}) AS filtered`),
232
+ rows: db.prepare(`SELECT filtered.*, count(*) OVER () AS total FROM (${filtered}) AS filtered ORDER BY at DESC,
233
+ CASE WHEN kind = 'triage' THEN CAST(substr(id, instr(id, ':') + 1) AS INTEGER) ELSE 0 END DESC,
234
+ id DESC LIMIT :limit OFFSET :offset`),
235
+ filters: db.prepare(`${activity} SELECT 'repo' AS facet, repo AS id, NULL AS userId, repo AS login, NULL AS name, NULL AS detail,
236
+ repo AS sort, '' AS tiebreak
237
+ FROM (SELECT DISTINCT repo FROM activity WHERE repo IS NOT NULL AND repo <> '') AS repos
238
+ UNION ALL SELECT 'user' AS facet, a.actorKey AS id, a.actorId AS userId, COALESCE(a.actor, a.actorId) AS login, a.actorName AS name,
239
+ CASE WHEN a.actorId IS NULL THEN 'Legacy actor' ELSE NULL END AS detail, COALESCE(a.actor, a.actorId) AS sort, a.actorKey AS tiebreak FROM (
240
+ SELECT actorKey, actorId, actor, actorName, ROW_NUMBER() OVER (PARTITION BY actorKey ORDER BY at DESC, id DESC) AS position
241
+ FROM activity WHERE actorKey IS NOT NULL AND actorKey <> 'legacy:'
242
+ ) a WHERE a.position = 1
243
+ ORDER BY facet, sort, tiebreak`),
244
+ }
245
+ }
246
+
247
+ function migrateActivityScope(db: DatabaseSync): void {
248
+ const columns = new Set((db.prepare('PRAGMA table_info(managed_activity)').all() as { name: string }[]).map(column => column.name))
249
+ const missing = [['bundle_id', 'TEXT'], ['repo_id', 'INTEGER'], ['repo_directory', 'TEXT'], ['actor_id', 'TEXT']].filter(([name]) => !columns.has(name!))
250
+ if (missing.length === 0) return
251
+ sqliteTransaction(db, 'BEGIN', () => {
252
+ for (const [name, type] of missing) db.exec(`ALTER TABLE managed_activity ADD COLUMN ${name} ${type}`)
253
+ if (!columns.has('bundle_id') || !columns.has('actor_id')) {
254
+ db.exec('DROP TRIGGER IF EXISTS managed_report_activity; DROP TRIGGER IF EXISTS managed_bundle_activity;')
255
+ }
256
+ if (!columns.has('bundle_id')) db.exec("UPDATE managed_activity SET bundle_id = substr(id, 15) WHERE id LIKE 'bundle-upload:%'")
257
+ if (!columns.has('actor_id')) {
258
+ // Existing upload targets retain a reliable uploader identity. Do not
259
+ // guess identities from historical logins: names can change or be reused.
260
+ for (const type of ['report', 'bundle']) {
261
+ db.exec(`UPDATE managed_activity SET actor_id = (
262
+ SELECT uploaded_by FROM managed_${type} WHERE id = substr(managed_activity.id, 15)
263
+ ) WHERE id LIKE '${type}-upload:%'`)
264
+ }
265
+ }
266
+ // Legacy deletions/assignments without a durable target/scope remain
267
+ // admin-only; neither filenames nor repository names authorize access.
268
+ })
269
+ }
@@ -0,0 +1,109 @@
1
+ // The commits agents' pull requests brought to a repository's default
2
+ // branch, for its Pulse (repository-pulse.ts commitStats), as the pull
3
+ // requests kept tell them (repository-pulls.ts readPulls: whose each is,
4
+ // and what one merged brought).
5
+ import type { PullList } from './repository-pulls.ts'
6
+ import type { HistoryCommit } from './repository-history.ts'
7
+
8
+ // How long before or after a pull request rebased onto the branch was merged
9
+ // its copies are committed.
10
+ const REBASE_SKEW_MS = 10 * 60_000
11
+
12
+ // The agents' pull requests merged since a year's start, as read so far
13
+ // (agentMerges): the commits each brought, and when it was merged; those
14
+ // rebased onto the branch by their last commit there, when merged, and
15
+ // their commits' subjects, the oldest first (agentCommits); and how far the
16
+ // pull requests are read, as the list tells (repository-pulls.ts PullList:
17
+ // `through`, `reach`, `next`). And of every pull request merged, an agent's
18
+ // or not, its merge commit, when and its number (`pulls`, by which the
19
+ // Commits tab tells those squashed too, http.ts pulseMerges; none of one
20
+ // kept before numbers were), and one rebased so (`pullRebases`), for the
21
+ // commits pushed to the branch directly to be told (directCommits).
22
+ export interface AgentMerges extends Pick<PullList, 'through' | 'reach' | 'next'> { merges: [string, number][]; rebases: Rebase[]
23
+ pulls?: [sha: string, at: number, number?: number][]; pullRebases?: Rebase[] }
24
+ // A pull request rebased onto the branch: its last commit there, when it was
25
+ // merged, its latest commits' subjects, the oldest first, and how many more
26
+ // it had than those read (`more`).
27
+ type Rebase = [sha: string, at: number, subjects: string[], more?: number]
28
+
29
+ // What the pull requests merged since `since` of those read (`list`) brought:
30
+ // an agent's, its merge commit, a squash merge's one commit, and one merged
31
+ // with a merge commit, its own commits too; and every one's merge commit,
32
+ // those rebased by their commits' subjects.
33
+ export function agentMerges(list: PullList, since: number): AgentMerges {
34
+ const merges = new Map<string, number>()
35
+ const [rebases, pulls, pullRebases]: [Rebase[], [string, number, number][], Rebase[]] = [[], [], []]
36
+ for (const { number, merged } of list.rows) {
37
+ if (!merged || merged.at < since) continue
38
+ const { sha, at, subjects, more = 0 } = merged
39
+ const rebase: Rebase | null = subjects ? more > 0 ? [sha, at, subjects, more] : [sha, at, subjects] : null
40
+ pulls.push([sha, at, number])
41
+ if (rebase) pullRebases.push(rebase)
42
+ if (!merged.agent) continue
43
+ for (const oid of [sha, ...merged.own ?? []]) merges.set(oid, at)
44
+ if (rebase) rebases.push(rebase)
45
+ }
46
+ return { merges: [...merges], rebases, through: list.through, ...list.reach === undefined ? {} : { reach: list.reach }, next: list.next, pulls, pullRebases }
47
+ }
48
+
49
+ // Whether two reads of the pull requests merged (agentMerges) bring the
50
+ // same commits, the agents' and every one's (`pulls`, `pullRebases`, which
51
+ // tell those pushed directly), whatever order each read them in.
52
+ export function sameMerges(a: AgentMerges, b: AgentMerges) {
53
+ const sorted = (entries: unknown[] = []) => entries.map(entry => JSON.stringify(entry)).toSorted()
54
+ const brought = (read: AgentMerges) => JSON.stringify([read.merges, read.rebases, read.pulls, read.pullRebases].map(sorted))
55
+ return brought(a) === brought(b)
56
+ }
57
+
58
+ // A commit's subject as GitHub heads its message: whole, or, past what it
59
+ // shows, cut short before an ellipsis.
60
+ const headed = (subject: string, headline: string) => headline.endsWith('…') ? subject.startsWith(headline.slice(0, -1)) : subject === headline
61
+
62
+ // The commits of `commits` (a year's) the agents' pull requests brought
63
+ // (`read`, agentMerges): those it names, and of one rebased, its commits'
64
+ // copies, the last and those below it on their first parents, as long as
65
+ // each one's subject is that of one of its commits older than the last
66
+ // matched, as Commits tells a rebase (repository-squashes.ts squashedPulls),
67
+ // past those of its commits the rebase left none of (an empty one GitHub
68
+ // counted no files of), and, past them all, as many more as it had before
69
+ // its latest read; a squash merge's one commit alone, its subject the pull
70
+ // request's own.
71
+ export function agentCommits(read: AgentMerges, commits: HistoryCommit[]): Set<string> {
72
+ const shas = new Set(read.merges.map(([sha]) => sha))
73
+ const bySha = new Map(commits.map(commit => [commit.sha, commit]))
74
+ for (const [last, merged, subjects, more = 0] of read.rebases) {
75
+ let commit = bySha.get(last)
76
+ let at = subjects.length - 1
77
+ for (; commit && at >= 0; commit = bySha.get(commit.parents[0] ?? '')) {
78
+ const [copied, upTo] = [commit, at]
79
+ const found = subjects.findLastIndex((subject, index) => index <= upTo && headed(copied.subject, subject))
80
+ if (found < 0) break
81
+ shas.add(commit.sha)
82
+ at = found - 1
83
+ }
84
+ // Each of its latest commits read copied, as many as it had before them
85
+ // the commits below, on their first parents, as long as each was
86
+ // committed as it was merged, as a rebase commits its copies: not past
87
+ // its first, its empty ones, which a rebase leaves out, counted too.
88
+ const copiedAsMerged = (when: number | null) => when !== null && Math.abs(when - merged) <= REBASE_SKEW_MS
89
+ for (let rest = at < 0 ? more : 0; commit && rest > 0 && copiedAsMerged(commit.committedAt); rest--, commit = bySha.get(commit.parents[0] ?? '')) {
90
+ shas.add(commit.sha)
91
+ }
92
+ }
93
+ return shas
94
+ }
95
+
96
+ // The commits of `commits` (a year's, from the branch's `head`) pushed to
97
+ // it directly: on its first parents from the head, none a merge, none a
98
+ // pull request brought (`read.pulls`: its merge commit, a squash's one
99
+ // commit, or the copies of one rebased onto it, as agentCommits tells
100
+ // them); those a merge brought from its other parents, not.
101
+ export function directCommits(read: AgentMerges, commits: HistoryCommit[], head: string): Set<string> {
102
+ const pulled = agentCommits({ ...read, merges: (read.pulls ?? []).map(([sha, at]) => [sha, at]), rebases: read.pullRebases ?? [] }, commits)
103
+ const bySha = new Map(commits.map(commit => [commit.sha, commit]))
104
+ const direct = new Set<string>()
105
+ for (let commit = bySha.get(head); commit; commit = bySha.get(commit.parents[0] ?? '')) {
106
+ if (commit.parents.length <= 1 && !pulled.has(commit.sha)) direct.add(commit.sha)
107
+ }
108
+ return direct
109
+ }
@@ -0,0 +1,23 @@
1
+ // The agents the server knows by their GitHub Apps or accounts (the Agents
2
+ // tab's, server-managed/repository-agents.ts, whose marks the Commits tab
3
+ // reads on commits too, repository-history.ts).
4
+ import type { AppAgent, AppAgentMarks } from '../common/managed/agent-tasks.ts'
5
+ import { GITHUB_AGENTS, type GithubAgent } from '../common/managed/github-agents.ts'
6
+
7
+ // The agents known by their GitHub Apps or accounts, beside Claude and
8
+ // Codex: those of GITHUB_AGENTS with branches of their own, in its order
9
+ // (common/managed/github-agents.ts, where each is told, its accounts among
10
+ // it), each its id and name, its avatar (its mark, served by
11
+ // /api/avatar/<avatar>, a GitHub App's, `app-<id>`), the fingerprint it
12
+ // leaves, and its branches' prefix.
13
+ export const APP_AGENTS: readonly (AppAgent & AppAgentMarks)[] = Object.entries<GithubAgent>(GITHUB_AGENTS)
14
+ .flatMap(([id, { name, avatar, prefix, fingerprint }]) => prefix ? [{ id, name, prefix, ...avatar ? { avatar } : {}, ...fingerprint ? { fingerprint } : {} }] : [])
15
+ // The prefixes of the branches agents work on: Claude Code's and Codex's,
16
+ // and the app agents'.
17
+ export const AGENT_BRANCH_PREFIXES = ['claude/', 'codex/', ...APP_AGENTS.map(agent => agent.prefix)]
18
+ // What the marks agents leave on commits are read by, as the history keeps
19
+ // them (repository-history.ts commitMarks), and branches' tips and the
20
+ // commits the app agents' accounts authored (repository-agents.ts): bumped
21
+ // as how they are told changes, so that the Agents tab reads again those
22
+ // kept by older rules.
23
+ export const AGENT_MARKS_READ = 1
@@ -0,0 +1,13 @@
1
+ // Shared avatar cache interface, implemented by storage-stores.ts.
2
+ import type { Buffer } from 'node:buffer'
3
+
4
+ export interface CachedAvatar {
5
+ contentType: string
6
+ bytes: Buffer
7
+ }
8
+
9
+ export interface AvatarStore {
10
+ put(id: string, contentType: string, bytes: Buffer): Promise<void>
11
+ get(id: string): Promise<CachedAvatar | null>
12
+ delete(id: string): Promise<void>
13
+ }