@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.60

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 (406) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +376 -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-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +35 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +34 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2SY4PYUQ.js +4 -0
  92. package/out/chunk-2XUEZHIP.js +28 -0
  93. package/out/chunk-4EMM6UCD.js +1 -0
  94. package/out/chunk-4HI2MSAV.js +17 -0
  95. package/out/chunk-4ISO5F7Y.js +7 -0
  96. package/out/chunk-4TQKM3JC.js +42 -0
  97. package/out/chunk-4XIH7YTX.js +1 -0
  98. package/out/chunk-6VDDCFHT.js +3 -0
  99. package/out/chunk-74AEKRES.js +10 -0
  100. package/out/chunk-7BKKYVWR.js +7 -0
  101. package/out/chunk-7C7DWL7I.js +1 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-EEQHVKR3.js +1 -0
  106. package/out/chunk-G3LY2FV4.js +1 -0
  107. package/out/chunk-GO7FT4OD.js +1 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HNQNDNIE.js +12 -0
  110. package/out/chunk-HOB3YPS5.js +1 -0
  111. package/out/chunk-IYPY47MC.js +1 -0
  112. package/out/chunk-IZ6MYRYB.js +3 -0
  113. package/out/chunk-J2FWBXFV.js +1 -0
  114. package/out/chunk-JCIIBLKR.js +1 -0
  115. package/out/chunk-JFL7WLRV.js +1 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFPDMZJF.js +244 -0
  123. package/out/chunk-OOJM4CTU.js +1 -0
  124. package/out/chunk-OQRSIBSC.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QMVOEBWC.js +13 -0
  131. package/out/chunk-QRKFPLA4.js +80 -0
  132. package/out/chunk-R3NZFXVR.js +1 -0
  133. package/out/chunk-R5O6FAW4.js +2 -0
  134. package/out/chunk-RRBIJL2B.js +1 -0
  135. package/out/chunk-SYXT3SFP.js +2 -0
  136. package/out/chunk-TOXMUOIW.js +5 -0
  137. package/out/chunk-TUII34K2.js +1 -0
  138. package/out/chunk-TZS7KERJ.js +52 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-VZJIHHTQ.js +1 -0
  143. package/out/chunk-WCPJDAYA.js +10 -0
  144. package/out/chunk-WMFDQS2L.js +11 -0
  145. package/out/chunk-WREU7JAG.js +1 -0
  146. package/out/chunk-Y5ZHFNBD.js +2 -0
  147. package/out/chunk-YF4M5OCI.js +1 -0
  148. package/out/chunk-YGRRXC2L.js +1 -0
  149. package/out/chunk-YTO6AQZM.js +2 -0
  150. package/out/chunk-Z667U2UJ.js +1 -0
  151. package/out/chunk-ZQHLECTI.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +35 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +379 -62
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +258 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +17 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +102 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +203 -0
  256. package/server-managed/bundle-build.ts +232 -0
  257. package/server-managed/bundle-cache.ts +211 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +140 -0
  260. package/server-managed/bundle-dependency-reviews.ts +74 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +130 -0
  263. package/server-managed/bundle-validation.ts +32 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +47 -0
  268. package/server-managed/comments.ts +151 -0
  269. package/server-managed/commit-coauthors.ts +106 -0
  270. package/server-managed/commit-lockfiles.ts +76 -0
  271. package/server-managed/comparison.ts +52 -0
  272. package/server-managed/config.ts +164 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1958 -0
  276. package/server-managed/db-neon.ts +484 -0
  277. package/server-managed/db-schema.ts +238 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +152 -0
  280. package/server-managed/dependabot-access.ts +60 -0
  281. package/server-managed/dependabot-alerts.ts +185 -0
  282. package/server-managed/dependency-review-comments.ts +98 -0
  283. package/server-managed/dependency-reviews.ts +364 -0
  284. package/server-managed/github-accounts.ts +60 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +376 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +39 -0
  289. package/server-managed/github-issue-links.ts +244 -0
  290. package/server-managed/github-issue-oauth.ts +47 -0
  291. package/server-managed/github-issues.ts +155 -0
  292. package/server-managed/github-link-oauth.ts +69 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +238 -0
  296. package/server-managed/github-pulls.ts +246 -0
  297. package/server-managed/github-requests.ts +166 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/history-windows.ts +172 -0
  300. package/server-managed/http-response.ts +76 -0
  301. package/server-managed/http.ts +5855 -0
  302. package/server-managed/import-triage.ts +51 -0
  303. package/server-managed/index.ts +204 -0
  304. package/server-managed/kept-briefly.ts +37 -0
  305. package/server-managed/kept.ts +28 -0
  306. package/server-managed/link-reports.ts +162 -0
  307. package/server-managed/listed-activity.ts +39 -0
  308. package/server-managed/locked-packages.ts +152 -0
  309. package/server-managed/lockfile-scope.ts +49 -0
  310. package/server-managed/lru.ts +30 -0
  311. package/server-managed/managed-issues.ts +92 -0
  312. package/server-managed/management-catalog.ts +45 -0
  313. package/server-managed/management.ts +99 -0
  314. package/server-managed/npm-delta-worker.js +23 -0
  315. package/server-managed/npm-delta.ts +194 -0
  316. package/server-managed/npm-insights.ts +450 -0
  317. package/server-managed/npm-kept.ts +233 -0
  318. package/server-managed/npm-loads.ts +264 -0
  319. package/server-managed/npm-manifest.ts +115 -0
  320. package/server-managed/npm-packages.ts +454 -0
  321. package/server-managed/npm-patch.ts +325 -0
  322. package/server-managed/npm-provenance.ts +123 -0
  323. package/server-managed/npm-risk.ts +285 -0
  324. package/server-managed/object-storage-disk.ts +148 -0
  325. package/server-managed/object-storage-vercel.ts +67 -0
  326. package/server-managed/object-storage.ts +75 -0
  327. package/server-managed/package-entry-points.ts +79 -0
  328. package/server-managed/pretty-print.ts +436 -0
  329. package/server-managed/public-workspace.ts +238 -0
  330. package/server-managed/pull-comment-reviews.ts +161 -0
  331. package/server-managed/pull-dependencies.ts +351 -0
  332. package/server-managed/pull-dependency-reviews.ts +334 -0
  333. package/server-managed/pull-reviews.ts +205 -0
  334. package/server-managed/queue.ts +39 -0
  335. package/server-managed/release-commits.ts +84 -0
  336. package/server-managed/rename-diff-worker.js +26 -0
  337. package/server-managed/rename-diff.ts +279 -0
  338. package/server-managed/repo-path.ts +21 -0
  339. package/server-managed/report-migration.ts +35 -0
  340. package/server-managed/report-query.ts +10 -0
  341. package/server-managed/report-response.ts +16 -0
  342. package/server-managed/report-sources.ts +185 -0
  343. package/server-managed/report-store.ts +85 -0
  344. package/server-managed/repository-actions.ts +221 -0
  345. package/server-managed/repository-agents.ts +448 -0
  346. package/server-managed/repository-aliases.ts +91 -0
  347. package/server-managed/repository-browser.ts +301 -0
  348. package/server-managed/repository-changes.ts +284 -0
  349. package/server-managed/repository-code.ts +215 -0
  350. package/server-managed/repository-dependency-reviews.ts +166 -0
  351. package/server-managed/repository-discovery.ts +82 -0
  352. package/server-managed/repository-history.ts +432 -0
  353. package/server-managed/repository-issues.ts +195 -0
  354. package/server-managed/repository-policy.ts +27 -0
  355. package/server-managed/repository-pulls.ts +212 -0
  356. package/server-managed/repository-pulse.ts +471 -0
  357. package/server-managed/repository-risk-assess.ts +105 -0
  358. package/server-managed/repository-risk-audit.ts +78 -0
  359. package/server-managed/repository-risk-read.ts +170 -0
  360. package/server-managed/repository-risk.ts +491 -0
  361. package/server-managed/repository-squashes.ts +168 -0
  362. package/server-managed/repository-stamp.ts +41 -0
  363. package/server-managed/request-timing.ts +63 -0
  364. package/server-managed/reviewed-dependencies.ts +149 -0
  365. package/server-managed/revisions.ts +35 -0
  366. package/server-managed/scan-downloads.ts +87 -0
  367. package/server-managed/session.ts +132 -0
  368. package/server-managed/slugs.ts +38 -0
  369. package/server-managed/solidity-entry-points.ts +71 -0
  370. package/server-managed/sql-postgres.ts +34 -0
  371. package/server-managed/sql.ts +89 -0
  372. package/server-managed/stasis-config.ts +55 -0
  373. package/server-managed/static.ts +28 -0
  374. package/server-managed/storage-command.ts +16 -0
  375. package/server-managed/storage-db.ts +183 -0
  376. package/server-managed/storage-encryption.ts +290 -0
  377. package/server-managed/storage-maintenance.ts +259 -0
  378. package/server-managed/storage-payload.ts +121 -0
  379. package/server-managed/storage-stores.ts +91 -0
  380. package/server-managed/storage.ts +82 -0
  381. package/server-managed/team-app-summaries.ts +54 -0
  382. package/server-managed/team-app.ts +157 -0
  383. package/server-managed/team-catalog.ts +7 -0
  384. package/server-managed/team-feed.ts +180 -0
  385. package/server-managed/team-npm-scopes.ts +106 -0
  386. package/server-managed/team-reports.ts +351 -0
  387. package/server-managed/triage-response.ts +16 -0
  388. package/server-managed/type-only-worker.js +19 -0
  389. package/server-managed/type-only.ts +105 -0
  390. package/server-managed/uploads.ts +106 -0
  391. package/server-managed/upstream-cache.ts +252 -0
  392. package/server-managed/view-as.ts +58 -0
  393. package/server-managed/workspace-shares.ts +171 -0
  394. package/server.ts +70 -0
  395. package/server/index.ts +0 -480
  396. package/server/lifecycle.ts +0 -208
  397. /package/{LICENSE → LICENSE-MIT} +0 -0
  398. /package/{server → server-e2e}/auth.ts +0 -0
  399. /package/{server → server-e2e}/config.example.json +0 -0
  400. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  401. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  402. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  403. /package/{server → server-e2e}/peer.ts +0 -0
  404. /package/{server → server-e2e}/sse-session.ts +0 -0
  405. /package/{server → server-e2e}/util.ts +0 -0
  406. /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,258 @@
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 } from './sql.ts'
7
+
8
+ export interface ActivityInput {
9
+ kind: 'access' | 'repository' | 'visibility' | 'delete'
10
+ actor: string
11
+ actorId?: string | null
12
+ action: string
13
+ repo?: string | null
14
+ reportId?: string | null
15
+ bundleId?: string | null
16
+ repoId?: number | null
17
+ repoDirectory?: string | null
18
+ report?: string | null
19
+ }
20
+
21
+ export interface ActivityContext {
22
+ finding: string
23
+ reportId: string
24
+ report: string
25
+ repo: string | null
26
+ }
27
+
28
+ export type ActivityEntry = {
29
+ id: string; kind: string; actor: string | null; action: string
30
+ repo: string | null; reportId: string | null; report: string | null
31
+ finding: string | null; at: number
32
+ }
33
+
34
+ export interface ActivityQuery {
35
+ page: number
36
+ limit: number
37
+ kind: string
38
+ query: string
39
+ repo?: string
40
+ actor?: string
41
+ // null = admin; [] = no accessible findings. Context is supplied by the
42
+ // server, never by the client. It also replaces potentially private context
43
+ // from an old report carrying the same globally shared finding.
44
+ contexts: ActivityContext[] | null
45
+ userId?: string
46
+ }
47
+
48
+ export interface ActivityFilters {
49
+ repos: string[]
50
+ users: { id: string; login: string; detail: string | null }[]
51
+ }
52
+
53
+ export interface ActivityStore {
54
+ recordActivity(entry: ActivityInput, at: number): Promise<void>
55
+ listActivityReports(userId: string): Promise<Omit<ActivityContext, 'finding'>[]>
56
+ listActivity(query: ActivityQuery): Promise<{ history: ActivityEntry[]; total: number; page: number; limit: number; filters: ActivityFilters }>
57
+ }
58
+
59
+ const triageFields = `'triage:' || e.seq AS id, 'triage' AS kind,
60
+ COALESCE(u.login, e.actor_login) AS actor, e.actor_id AS actorId,
61
+ 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
62
+ THEN 'cleared triage' ELSE 'updated triage' END AS action`
63
+ const triage = `SELECT ${triageFields}, e.repo, e.report_id AS reportId, e.report, e.finding_id AS finding, e.at
64
+ FROM managed_finding_triage_event e LEFT JOIN managed_user u ON u.id = e.actor_id`
65
+ const commentFields = `'comment:' || e.seq AS id, 'triage' AS kind,
66
+ COALESCE(u.login, e.actor_login) AS actor, e.actor_id AS actorId, e.action`
67
+ const comments = `SELECT ${commentFields}, e.repo, e.report_id AS reportId, e.report, e.finding_id AS finding, e.at
68
+ FROM managed_finding_comment_event e LEFT JOIN managed_user u ON u.id = e.actor_id`
69
+ const adminSource = `${triage} UNION ALL ${comments} UNION ALL
70
+ SELECT id, kind, actor, actor_id AS actorId, action, repo, report_id AS reportId, report, NULL AS finding, at FROM managed_activity`
71
+ // Keep the finite set of accessible findings outside the indexed event
72
+ // lookup. Scanning all events against json_each for every row is quadratic.
73
+ const managerSource = `SELECT ${triageFields},
74
+ json_extract(c.value, '$.repo') AS repo, json_extract(c.value, '$.reportId') AS reportId,
75
+ json_extract(c.value, '$.report') AS report, e.finding_id AS finding, e.at
76
+ FROM json_each(:contexts) c
77
+ CROSS JOIN managed_finding_triage_event e ON e.finding_id = json_extract(c.value, '$.finding')
78
+ LEFT JOIN managed_user u ON u.id = e.actor_id
79
+ UNION ALL SELECT ${commentFields},
80
+ json_extract(c.value, '$.repo') AS repo, json_extract(c.value, '$.reportId') AS reportId,
81
+ json_extract(c.value, '$.report') AS report, e.finding_id AS finding, e.at
82
+ FROM json_each(:contexts) c
83
+ CROSS JOIN managed_finding_comment_event e ON e.finding_id = json_extract(c.value, '$.finding')
84
+ LEFT JOIN managed_user u ON u.id = e.actor_id
85
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId,
86
+ CASE WHEN a.kind = 'repository' THEN 'changed a report repository assignment' ELSE a.action END AS action,
87
+ p.full_name AS repo, r.id AS reportId, r.filename AS report, NULL AS finding, a.at
88
+ FROM managed_activity a JOIN managed_report r ON r.id = a.report_id
89
+ LEFT JOIN managed_selected_repo p ON p.repo_id = r.repo_id
90
+ WHERE EXISTS (
91
+ SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
92
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
93
+ WHERE tu.user_id = :userId AND tr.repo_id = r.repo_id AND ${withinTeamPath('r.repo_directory')}
94
+ )
95
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId,
96
+ CASE WHEN a.kind = 'repository' THEN 'changed a bundle repository assignment' ELSE a.action END AS action,
97
+ p.full_name AS repo, NULL AS reportId, b.filename AS report, NULL AS finding, a.at
98
+ FROM managed_activity a JOIN managed_bundle b ON b.id = a.bundle_id
99
+ LEFT JOIN managed_selected_repo p ON p.repo_id = b.repo_id
100
+ WHERE a.report_id IS NULL AND EXISTS (
101
+ SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
102
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
103
+ WHERE tu.user_id = :userId AND tr.repo_id = b.repo_id AND ${withinTeamPath('b.repo_directory')}
104
+ )
105
+ UNION ALL SELECT a.id, a.kind, a.actor, a.actor_id AS actorId, a.action, a.repo, a.report_id AS reportId,
106
+ a.report, NULL AS finding, a.at FROM managed_activity a
107
+ WHERE a.kind = 'delete' AND (a.report_id IS NOT NULL OR a.bundle_id IS NOT NULL)
108
+ AND NOT EXISTS (SELECT 1 FROM managed_report WHERE id = a.report_id)
109
+ AND NOT EXISTS (SELECT 1 FROM managed_bundle WHERE id = a.bundle_id)
110
+ AND EXISTS (SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
111
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
112
+ WHERE tu.user_id = :userId AND tr.repo_id = a.repo_id
113
+ AND ${withinTeamPath('a.repo_directory')})`
114
+
115
+ export const ACTIVITY_SCHEMA = `
116
+ CREATE TABLE IF NOT EXISTS managed_activity (
117
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, actor TEXT, action TEXT NOT NULL,
118
+ repo TEXT, report_id TEXT, report TEXT, at INTEGER NOT NULL,
119
+ bundle_id TEXT, repo_id INTEGER, repo_directory TEXT, actor_id TEXT
120
+ ) STRICT;
121
+ CREATE INDEX IF NOT EXISTS managed_activity_at_idx ON managed_activity(at, id);
122
+ CREATE INDEX IF NOT EXISTS finding_triage_event_at_idx ON managed_finding_triage_event(at, seq);
123
+ `
124
+
125
+ export function initActivityMethods(db: DatabaseSync): void {
126
+ db.exec(ACTIVITY_SCHEMA)
127
+ migrateActivityScope(db)
128
+ db.exec('CREATE INDEX IF NOT EXISTS managed_activity_actor_at_idx ON managed_activity(actor_id, at)')
129
+ // Stable upload IDs make backfill idempotent, including after restarts.
130
+ // Snapshots deliberately have no cascading FKs: deletion is itself activity.
131
+ // CREATE TRIGGER IF NOT EXISTS keeps an older body; replace the one that
132
+ // predates server-built bundles so builds are not recorded as uploads.
133
+ const bundleTrigger = db.prepare("SELECT sql FROM sqlite_schema WHERE type = 'trigger' AND name = 'managed_bundle_activity'").get() as { sql: string } | undefined
134
+ if (bundleTrigger && !bundleTrigger.sql.includes('provenance')) db.exec('DROP TRIGGER managed_bundle_activity')
135
+ for (const type of ['report', 'bundle']) {
136
+ const columns = `id, kind, actor, action, repo, report_id, report, at, bundle_id, actor_id`
137
+ const values = (alias: string) => `'${type}-upload:' || ${alias}.id, 'upload',
138
+ COALESCE(${alias}.uploaded_by_login, (SELECT login FROM managed_user WHERE id = ${alias}.uploaded_by)), ${uploadAction(type, alias)},
139
+ (SELECT full_name FROM managed_selected_repo WHERE repo_id = ${alias}.repo_id),
140
+ ${type === 'report' ? `${alias}.id` : 'NULL'}, ${alias}.filename, ${alias}.uploaded_at,
141
+ ${type === 'bundle' ? `${alias}.id` : 'NULL'}, ${alias}.uploaded_by`
142
+ db.exec(`
143
+ CREATE TRIGGER IF NOT EXISTS managed_${type}_activity AFTER INSERT ON managed_${type}
144
+ BEGIN INSERT INTO managed_activity (${columns}) SELECT ${values('NEW')}; END;
145
+ INSERT OR IGNORE INTO managed_activity (${columns}) SELECT ${values('source')} FROM managed_${type} source;
146
+ `)
147
+ }
148
+ }
149
+
150
+ // The creation entry for a stored report or bundle. Shared with the Postgres
151
+ // trigger function; `alias` is the trigger row (NEW) or a backfill alias.
152
+ export function uploadAction(type: string, alias: string): string {
153
+ return type === 'bundle' ? `CASE WHEN ${alias}.provenance = 'build' THEN 'built a bundle' ELSE 'uploaded a bundle' END` : `'uploaded a ${type}'`
154
+ }
155
+
156
+ export function activityMethods(db: ManagedSql): ActivityStore {
157
+ 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)
158
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
159
+ const admin = activityStatements(db, adminSource)
160
+ const manager = activityStatements(db, managerSource)
161
+ const reports = db.prepare(`SELECT r.id AS reportId, r.filename AS report, p.full_name AS repo
162
+ FROM managed_report r JOIN managed_selected_repo p ON p.repo_id = r.repo_id
163
+ WHERE EXISTS (SELECT 1 FROM managed_team_repo tr JOIN managed_team_user tu ON tu.team_id = tr.team_id
164
+ JOIN managed_team t ON t.id = tu.team_id AND t.hidden = 0
165
+ WHERE tu.user_id = ? AND tr.repo_id = r.repo_id AND ${withinTeamPath('r.repo_directory')})
166
+ ORDER BY r.uploaded_at DESC, r.id`)
167
+ return {
168
+ async recordActivity(entry, at) {
169
+ await insert.run(randomUUID(), entry.kind, entry.actor, entry.action, entry.repo ?? null, entry.reportId ?? null, entry.report ?? null, at,
170
+ entry.bundleId ?? null, entry.repoId ?? null, entry.repoDirectory ?? null, entry.actorId ?? null)
171
+ },
172
+ async listActivityReports(userId) {
173
+ return (await reports.all(userId)) as Omit<ActivityContext, 'finding'>[]
174
+ },
175
+ async listActivity({ page, limit, kind, query, repo = '', actor = '', contexts, userId }) {
176
+ const stmts = contexts == null ? admin : manager
177
+ const scope = contexts == null ? {} : { contexts: JSON.stringify(contexts), userId: userId ?? '' }
178
+ const params = { ...scope, kind, query, repo, actor }
179
+ const read = async (at: number) => (await stmts.rows.all({ ...params, limit, offset: (at - 1) * limit })) as (ActivityEntry & { total: number | string })[]
180
+ // A page's rows carry the total. Only a page past the last has none to
181
+ // carry it: it is counted, and the last page read in its place.
182
+ let currentPage = page, rows = await read(page)
183
+ let total = rows.length > 0 ? Number(rows[0]!.total) : 0
184
+ if (rows.length === 0 && page > 1) {
185
+ total = Number(((await stmts.count.get(params)) as { total: number | string }).total)
186
+ currentPage = Math.min(page, Math.max(1, Math.ceil(total / limit)))
187
+ if (currentPage !== page) rows = total === 0 ? [] : await read(currentPage)
188
+ }
189
+ const history = rows.map(({ total: _total, ...entry }) => entry)
190
+ const filters: ActivityFilters = { repos: [], users: [] }
191
+ for (const row of (await stmts.filters.all(scope)) as { facet: string; id: string; login: string; detail: string | null }[]) {
192
+ if (row.facet === 'repo') filters.repos.push(row.id)
193
+ else filters.users.push({ id: row.id, login: row.login, detail: row.detail })
194
+ }
195
+ return { history, total, page: currentPage, limit, filters }
196
+ },
197
+ }
198
+ }
199
+
200
+ // Both rows and selector choices come from the authorized source. Keep legacy
201
+ // login-only actors separate: a historical login is not proof of user identity.
202
+ function activityStatements(db: ManagedSql, source: string) {
203
+ const activity = `WITH events AS (${source}), activity AS (
204
+ SELECT events.*, COALESCE('user:' || actorId, 'legacy:' || actor) AS actorKey FROM events
205
+ )`
206
+ const filtered = `${activity} SELECT id, kind, actor, action, repo, reportId, report, finding, at FROM activity
207
+ WHERE (:kind = 'all' OR kind = :kind)
208
+ AND (:repo = '' OR repo = :repo) AND (:actor = '' OR actorKey = :actor)
209
+ AND (:query = '' OR instr(lower(coalesce(actor, '') || ' ' || action || ' ' ||
210
+ coalesce(repo, '') || ' ' || coalesce(report, '') || ' ' || coalesce(finding, '')), lower(:query)) > 0)`
211
+ // A page's rows each carry the total, so the source is read once for both;
212
+ // the selector choices, repositories then users, once between them.
213
+ return {
214
+ count: db.prepare(`SELECT count(*) AS total FROM (${filtered}) AS filtered`),
215
+ rows: db.prepare(`SELECT filtered.*, count(*) OVER () AS total FROM (${filtered}) AS filtered ORDER BY at DESC,
216
+ CASE WHEN kind = 'triage' THEN CAST(substr(id, instr(id, ':') + 1) AS INTEGER) ELSE 0 END DESC,
217
+ id DESC LIMIT :limit OFFSET :offset`),
218
+ filters: db.prepare(`${activity} SELECT 'repo' AS facet, repo AS id, repo AS login, NULL AS detail, repo AS sort, '' AS tiebreak
219
+ FROM (SELECT DISTINCT repo FROM activity WHERE repo IS NOT NULL AND repo <> '') AS repos
220
+ UNION ALL SELECT 'user' AS facet, a.actorKey AS id, COALESCE(u.login, a.actor, a.actorId) AS login,
221
+ CASE WHEN a.actorId IS NULL THEN 'Legacy actor' ELSE NULL END AS detail, COALESCE(u.login, a.actor, a.actorId) AS sort, a.actorKey AS tiebreak FROM (
222
+ SELECT actorKey, actorId, actor, ROW_NUMBER() OVER (PARTITION BY actorKey ORDER BY at DESC, id DESC) AS position
223
+ FROM activity WHERE actorKey IS NOT NULL AND actorKey <> 'legacy:'
224
+ ) a LEFT JOIN managed_user u ON u.id = a.actorId WHERE a.position = 1
225
+ ORDER BY facet, sort, tiebreak`),
226
+ }
227
+ }
228
+
229
+ // Literal path comparison preserves separators, case and SQL wildcard chars.
230
+ function withinTeamPath(path: string): string {
231
+ return `(tr.path IS NULL OR tr.path = '' OR ${path} = tr.path OR substr(${path}, 1, length(tr.path) + 1) = tr.path || '/')`
232
+ }
233
+
234
+ function migrateActivityScope(db: DatabaseSync): void {
235
+ const columns = new Set((db.prepare('PRAGMA table_info(managed_activity)').all() as { name: string }[]).map(column => column.name))
236
+ const missing = [['bundle_id', 'TEXT'], ['repo_id', 'INTEGER'], ['repo_directory', 'TEXT'], ['actor_id', 'TEXT']].filter(([name]) => !columns.has(name!))
237
+ if (missing.length === 0) return
238
+ db.exec('BEGIN')
239
+ try {
240
+ for (const [name, type] of missing) db.exec(`ALTER TABLE managed_activity ADD COLUMN ${name} ${type}`)
241
+ if (!columns.has('bundle_id') || !columns.has('actor_id')) {
242
+ db.exec('DROP TRIGGER IF EXISTS managed_report_activity; DROP TRIGGER IF EXISTS managed_bundle_activity;')
243
+ }
244
+ if (!columns.has('bundle_id')) db.exec("UPDATE managed_activity SET bundle_id = substr(id, 15) WHERE id LIKE 'bundle-upload:%'")
245
+ if (!columns.has('actor_id')) {
246
+ // Existing upload targets retain a reliable uploader identity. Do not
247
+ // guess identities from historical logins: names can change or be reused.
248
+ for (const type of ['report', 'bundle']) {
249
+ db.exec(`UPDATE managed_activity SET actor_id = (
250
+ SELECT uploaded_by FROM managed_${type} WHERE id = substr(managed_activity.id, 15)
251
+ ) WHERE id LIKE '${type}-upload:%'`)
252
+ }
253
+ }
254
+ // Legacy deletions/assignments without a durable target/scope remain
255
+ // admin-only; neither filenames nor repository names authorize access.
256
+ db.exec('COMMIT')
257
+ } catch (err) { db.exec('ROLLBACK'); throw err }
258
+ }
@@ -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 { merges: [string, number][]; rebases: Rebase[]; through: number | null; reach?: number
23
+ next: { after: string; from: number; stop: number; read: number; to?: number } | null; 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
+ }