@preventive/triage 1.0.0-alpha.67 → 1.0.0-alpha.69

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 (37) hide show
  1. package/common/managed/routes.js +19 -12
  2. package/out/activity.js +3 -3
  3. package/out/{chunk-LBJVV6UB.js → chunk-2F3CYNPZ.js} +1 -1
  4. package/out/{chunk-U5C2TNNQ.js → chunk-2HGKTQ5Q.js} +1 -1
  5. package/out/chunk-4RS3NDOG.js +1 -0
  6. package/out/{chunk-VR3NRE5V.js → chunk-DVIYJG3F.js} +1 -1
  7. package/out/{chunk-LDO42LAC.js → chunk-GZ46SSTF.js} +1 -1
  8. package/out/{chunk-R3WUYD4F.js → chunk-HETCVNO4.js} +1 -1
  9. package/out/{chunk-5F5FPI75.js → chunk-MPXVKVPF.js} +1 -1
  10. package/out/{chunk-FUHRMY7R.js → chunk-NA3BSFFM.js} +6 -6
  11. package/out/{chunk-6YGH7BJG.js → chunk-QPGM3DTI.js} +1 -1
  12. package/out/{chunk-A5A3LEMV.js → chunk-Y3MWMG7M.js} +1 -1
  13. package/out/client-managed-import.js +1 -1
  14. package/out/client-managed.js +2 -2
  15. package/out/compare.js +8 -8
  16. package/out/dialogs.js +38 -38
  17. package/out/graph.js +1 -1
  18. package/out/index.html +7 -7
  19. package/out/scan.js +1 -1
  20. package/out/view.css +1 -1
  21. package/out/view.js +15 -15
  22. package/package.json +1 -1
  23. package/server-managed/bundle-build-worker.js +59 -7
  24. package/server-managed/bundle-build.ts +9 -4
  25. package/server-managed/db-neon.ts +4 -1
  26. package/server-managed/dependency-review-comments.ts +18 -13
  27. package/server-managed/dependency-reviews.ts +17 -14
  28. package/server-managed/http.ts +93 -42
  29. package/server-managed/npm-patch.ts +101 -43
  30. package/server-managed/pull-dependencies.ts +30 -21
  31. package/server-managed/pull-dependency-reviews.ts +63 -26
  32. package/server-managed/repository-dependency-reviews.ts +4 -2
  33. package/server-managed/repository-issues.ts +3 -3
  34. package/server-managed/reviewed-dependencies.ts +44 -24
  35. package/server-managed/stasis-dependencies.ts +34 -16
  36. package/server.ts +1 -1
  37. package/out/chunk-6ATPGDDI.js +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.67",
3
+ "version": "1.0.0-alpha.69",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -1,6 +1,8 @@
1
1
  import { parentPort, workerData } from 'node:worker_threads'
2
2
  import { Buffer } from 'node:buffer'
3
- import { posix } from 'node:path'
3
+ import { createHash } from 'node:crypto'
4
+ import { mkdir, readFile, readdir, rename, rm, stat, statfs, writeFile } from 'node:fs/promises'
5
+ import { join, posix } from 'node:path'
4
6
  import { brotliCompressSync } from 'node:zlib'
5
7
  import { isEvidenceFile } from '@exodus/stasis/audit-corrections'
6
8
  import { buildGitHubBundle, setCacheDir } from '@exodus/stasis/vfs-bundle'
@@ -128,12 +130,13 @@ function buildClientOf(client, note) {
128
130
  // `note` is told what the build log keeps of a build beside its stages: the
129
131
  // directory Stasis builds from (`project`), and each tree it downloads of the
130
132
  // repo (`download`, buildClientOf).
131
- export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
133
+ export async function buildStasisBundle({ input, github, token, maxBytes, scopes, cacheDir = null, instanceDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
132
134
  const allowed = path => scopes.some(scope => !scope || path === scope || path.startsWith(scope + '/'))
133
135
  const buildClient = buildClientOf(client, note)
134
136
  // Upstream's disk cache keeps the npm tarballs and version documents, and
135
- // the repo's tree, in `cacheDir`; without one (Vercel), nothing is kept on
136
- // disk. This fresh worker inherits no application credentials but NPM_TOKEN.
137
+ // the repo's tree, in `cacheDir`; without one (Vercel), what it downloads
138
+ // of npm is kept in `instanceDir` (cacheOf), where one is given. This fresh
139
+ // worker inherits no application credentials but NPM_TOKEN.
137
140
  setCacheDir(cacheDir ?? false)
138
141
  progress('build')
139
142
  // Entries stasis.config.json lists are built from its directory, where
@@ -158,7 +161,7 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
158
161
  const { bundle } = await buildGitHubBundle({
159
162
  github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: project || undefined,
160
163
  entries: input.entries.map(entry => posix.relative(project || '.', entry)),
161
- ...options, ...(named && { packageManager }), client: buildClient, ...(cacheDir === null && { cache: false }),
164
+ ...options, ...(named && { packageManager }), client: buildClient, ...await cacheOf(cacheDir, instanceDir),
162
165
  })
163
166
  const directory = bundle.repo?.directory ?? ''
164
167
  progress('scope')
@@ -200,12 +203,61 @@ export function lockfileDependencies(lockfile) {
200
203
  return [...found].toSorted(([a], [b]) => a < b ? -1 : 1).map(([, one]) => one)
201
204
  }
202
205
 
206
+ // The npm tarballs and version documents a build downloads, kept as files in
207
+ // `dir` for the builds after it in this instance, where no cache directory
208
+ // is set (serverless, whose temporary directory lasts as long as its
209
+ // instance): a store Stasis reads and writes in place of its cache, so a
210
+ // bundle's build, a pull request's head and merge base, and the commits
211
+ // after them download each version once. As much as `budget` bytes: found
212
+ // past it, or with less than `spare` bytes left on its disk (Vercel's holds
213
+ // 500 MB), the directory is emptied, and nothing is written past it. A file
214
+ // is written whole or not at all, as what is read is held to its integrity,
215
+ // a mismatch failing the build; one a stopped build left half-written is
216
+ // removed.
217
+ const INSTANCE_KEPT = new Set(['npm/tarballs', 'npm/versions'])
218
+ const INSTANCE_BUDGET = 512 * 1024 * 1024
219
+ const INSTANCE_SPARE = 64 * 1024 * 1024
220
+ export async function instanceCache(dir, budget = INSTANCE_BUDGET, spare = INSTANCE_SPARE) {
221
+ let used = 0, written = 0
222
+ for (const name of await readdir(dir).catch(() => [])) {
223
+ if (name.endsWith('.tmp')) await rm(join(dir, name), { force: true }).catch(() => {})
224
+ else used += (await stat(join(dir, name)).catch(() => null))?.size ?? 0
225
+ }
226
+ const free = await statfs(dir).then(disk => disk.bavail * disk.bsize, () => Infinity)
227
+ if (used > budget || (used > 0 && free < spare)) {
228
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
229
+ used = 0
230
+ }
231
+ await mkdir(dir, { recursive: true }).catch(() => {})
232
+ const pathOf = (kind, name) => join(dir, createHash('sha256').update(`${kind}\0${name}`).digest('hex'))
233
+ return {
234
+ async read(kind, name) {
235
+ const bytes = INSTANCE_KEPT.has(kind) ? await readFile(pathOf(kind, name)).catch(() => null) : null
236
+ if (bytes === null || kind === 'npm/tarballs') return bytes
237
+ try { return JSON.parse(bytes.toString()) } catch { return null }
238
+ },
239
+ async write(kind, name, value) {
240
+ if (!INSTANCE_KEPT.has(kind)) return
241
+ const bytes = value instanceof Uint8Array ? value : Buffer.from(JSON.stringify(value))
242
+ if (used + bytes.length > budget) return
243
+ used += bytes.length
244
+ const path = pathOf(kind, name), tmp = `${path}.${++written}.tmp`
245
+ await writeFile(tmp, bytes).then(() => rename(tmp, path)).catch(() => rm(tmp, { force: true }).catch(() => {}))
246
+ },
247
+ }
248
+ }
249
+
250
+ // Stasis's `cache` option for a build: none with a cache directory set,
251
+ // which it reads and writes; else the instance's own (instanceCache), where
252
+ // it has a directory, and nothing kept where it has none.
253
+ const cacheOf = async (cacheDir, instanceDir) => cacheDir === null ? { cache: instanceDir === null ? false : await instanceCache(instanceDir) } : {}
254
+
203
255
  // What the stasis.config.json at `input.config` has Stasis reach at
204
256
  // `input.commit`, for the repository's dependency review
205
257
  // (stasis-dependencies.ts): the npm versions of the lockfile it builds in
206
258
  // its directory, as `stasis github-bundle --lockfile-only` does, no bundle
207
259
  // serialized; none of a commit with no file there.
208
- export async function buildStasisLockfile({ input, github, token, cacheDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
260
+ export async function buildStasisLockfile({ input, github, token, cacheDir = null, instanceDir = null }, client = createClient({ token }), progress = () => {}, note = () => {}) {
209
261
  const buildClient = buildClientOf(client, note)
210
262
  setCacheDir(cacheDir ?? false)
211
263
  progress('build')
@@ -216,7 +268,7 @@ export async function buildStasisLockfile({ input, github, token, cacheDir = nul
216
268
  await directoryConfig(configText, directory)
217
269
  note('project', { project: directory, configured: true })
218
270
  const { lockfile } = await buildGitHubBundle({ github, sha: input.commit, ...(input.branch !== undefined && { branch: input.branch }), directory: directory || undefined, lockfile: LOCK_FILE, client: buildClient,
219
- ...(cacheDir === null && { cache: false }) })
271
+ ...await cacheOf(cacheDir, instanceDir) })
220
272
  progress('lockfile')
221
273
  if (!lockfile) throw new Error('Stasis built no lockfile of these entries')
222
274
  return lockfileDependencies(lockfile)
@@ -1,7 +1,7 @@
1
1
  import { Buffer } from 'node:buffer'
2
2
  import { createHash, randomUUID } from 'node:crypto'
3
- import { totalmem } from 'node:os'
4
- import { posix } from 'node:path'
3
+ import { tmpdir, totalmem } from 'node:os'
4
+ import { join, posix } from 'node:path'
5
5
  import { Worker } from 'node:worker_threads'
6
6
  import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
7
7
  import { type BundleBuildDiagnostic, type BundleBuildStage, bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
@@ -144,6 +144,10 @@ const MAX_ACTIVE_BUILDS = 1
144
144
  let behind: { yield: () => void; gone: Promise<void> } | null = null
145
145
  // Who builds behind no request, as `active` and the shared lease name it.
146
146
  const LOCKFILE_BUILDER = 'dependency-review'
147
+ // Where builds keep what they download of npm for those after them in this
148
+ // instance, where no cache directory is set, as on Vercel
149
+ // (bundle-build-worker.js instanceCache).
150
+ const INSTANCE_DIR = join(tmpdir(), 'triage-stasis-cache')
147
151
  async function yielded(): Promise<void> {
148
152
  const running = behind
149
153
  if (!running) return
@@ -203,7 +207,8 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
203
207
  // credentials or mutable Stasis state between requests.
204
208
  export function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
205
209
  const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, directory: request.input.directory, entryCount: request.input.entries.length }
206
- return runBuild<BuiltBundle & { bytes: Uint8Array }, BuiltBundle>(userId, request, context, signal, message => {
210
+ const asked = { ...request, instanceDir: INSTANCE_DIR }
211
+ return runBuild<BuiltBundle & { bytes: Uint8Array }, BuiltBundle>(userId, asked, context, signal, message => {
207
212
  // A view of the bytes the worker handed over, not a copy of them.
208
213
  const { bytes } = message
209
214
  return { value: { bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename }, logged: { byteSize: bytes.length } }
@@ -218,7 +223,7 @@ export function buildRepositoryBundle(userId: string, request: BuildRequest, sig
218
223
  export async function buildRepositoryLockfile(db: BundleBuildLeaseStore, request: LockfileRequest, signal: AbortSignal): Promise<StasisDependency[]> {
219
224
  if (behind || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
220
225
  const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, config: request.input.config, branch: request.input.branch, lockfileOnly: true }
221
- const asked = { ...request, lockfileOnly: true }
226
+ const asked = { ...request, instanceDir: INSTANCE_DIR, lockfileOnly: true }
222
227
  const yielding = new AbortController()
223
228
  let gone = () => {}
224
229
  behind = { yield: () => yielding.abort(new BundleBuildError(429, 'build-yielded')), gone: new Promise(resolve => { gone = resolve }) }
@@ -40,7 +40,7 @@ const LOCK = 'SELECT pg_advisory_xact_lock(1937006964, 1835101793)'
40
40
  // Whether every version up to the latest is recorded, in one round trip at
41
41
  // a cold start: a database with no versions table yet (undefined_table) has
42
42
  // none. Outside a transaction, so the failed read aborts nothing.
43
- const SCHEMA_VERSIONS = 35
43
+ const SCHEMA_VERSIONS = 36
44
44
  async function currentSchema(db: PgConnection): Promise<boolean> {
45
45
  try {
46
46
  const { rows } = await db.query(`SELECT count(*) AS n FROM managed_schema_version WHERE version BETWEEN 1 AND ${SCHEMA_VERSIONS}`)
@@ -136,6 +136,9 @@ async function migrateFrom12(db: PgConnection): Promise<void> {
136
136
  // The issue a saved one was closed as a duplicate of, none known of those
137
137
  // checked before.
138
138
  await migration(db, 35, 'ALTER TABLE managed_finding_issue ADD COLUMN IF NOT EXISTS duplicate_of_url TEXT')
139
+ // The patch a dependency review's base is of, none of those written
140
+ // before; each author's one draft of a comparison held to it too.
141
+ await migration(db, 36, `ALTER TABLE managed_dependency_review ${addColumns(DEPENDENCY_REVIEW_COLUMNS)}`, DEPENDENCY_REVIEW_INDEXES)
139
142
  }
140
143
 
141
144
  async function initialize(db: PgConnection): Promise<void> {
@@ -11,10 +11,10 @@
11
11
  import type { DependencyReview, DependencyReviewStore } from './dependency-reviews.ts'
12
12
  import type { LockedPackage } from './locked-packages.ts'
13
13
  import type { PullDependencies } from './pull-dependencies.ts'
14
- import { askedOf, comparedWith, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
14
+ import { askedOf, basesOf, comparedWith, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
15
15
  import { eachOf } from './queue.ts'
16
16
  import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
17
- import { type DependencyReviewEntry, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
17
+ import { type DependencyReviewEntry, type ReviewedBase, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
18
18
 
19
19
  const FORMAT_AT_ONCE = 8
20
20
  // The longest comment told, past which none is.
@@ -24,11 +24,11 @@ const MAX_FORMATTED = 1_000_000
24
24
  const REVIEWS_AT_ONCE = 200
25
25
 
26
26
  // `review` as the hook is given it: each version with the integrity and
27
- // shasum the review keeps of the tarball it read, and the version it is of
28
- // with the patch it is of, where it is a patched one's.
27
+ // shasum the review keeps of the tarball it read, and the patch it is of,
28
+ // where it is a patched one's.
29
29
  function entryOf(review: DependencyReview): DependencyReviewEntry {
30
30
  return { ecosystem: 'npm', old: review.basePackage === null ? null : { name: review.basePackage, version: review.baseVersion ?? '', integrity: review.baseIntegrity ?? '',
31
- ...review.baseShasum ? { shasum: review.baseShasum } : {} },
31
+ ...review.baseShasum ? { shasum: review.baseShasum } : {}, ...review.basePatchHash ? { patchHash: review.basePatchHash } : {} },
32
32
  new: { name: review.package, version: review.version, integrity: review.integrity, ...review.shasum ? { shasum: review.shasum } : {},
33
33
  ...review.patchHash ? { patchHash: review.patchHash } : {} },
34
34
  status: review.status!, coverage: review.coverage === 'full' ? 'full' : 'partial', comment: review.comment,
@@ -68,18 +68,20 @@ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDepe
68
68
 
69
69
  // Those of `reviews` `user` published of the versions `told` adds, by their
70
70
  // ids, each with the versions it is of, as its lockfiles lock each: of its
71
- // version, of an integrity it is locked with and of its patch, whole or
72
- // compared with a version it was (pull-dependency-reviews.ts reviewsOf,
73
- // comparedWith).
71
+ // version, of an integrity it is locked with and of its patch, whole,
72
+ // compared with another package's version, or compared with a version it was
73
+ // or the base the host names it (`bases`; pull-dependency-reviews.ts reviewsOf,
74
+ // comparedWith, basesOf), or, `any`, with any version of its package.
74
75
  interface Own { review: PublishedReview; pkgs: LockedPackage[] }
75
- function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string): Map<string, Own> {
76
+ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean, bases: Map<string, ReviewedBase>): Map<string, Own> {
76
77
  // Theirs by the version they are of, each version probed once.
77
78
  const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
78
79
  const mine = new Map<string, Own>()
79
80
  if (theirs.size === 0) return mine
80
81
  for (const pkg of told.lockfiles.flatMap(dir => 'added' in dir ? dir.added : [])) {
82
+ const against = any ? 'any' : basesOf(pkg, bases.get(askedOf(pkg)[0]) ?? null)
81
83
  for (const review of reviewsOf(pkg, theirs)) {
82
- if (comparedWith(review, pkg, pkg.was ?? [])) (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
84
+ if (comparedWith(review, pkg, against)) (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
83
85
  }
84
86
  }
85
87
  return mine
@@ -94,11 +96,14 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
94
96
  // it with the same verdict, as copying it would but repeat them: by their
95
97
  // latest of it, which tells where they stand there (pull-dependency-
96
98
  // reviews.ts stancesOf), an older one of that verdict not counting. A
97
- // version `lookup` fails to answer of keeps its review.
99
+ // version `lookup` fails to answer of keeps its review. Where the host reads
100
+ // reviews of comments (`parseComments`), what a review was compared with is
101
+ // its to weigh, so one compared with any version is given.
98
102
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
99
- told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = []): Promise<string | null> {
103
+ told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = [],
104
+ bases: Map<string, ReviewedBase> = new Map()): Promise<string | null> {
100
105
  if (!reviewed?.formatDependencyReviews || !state) return null
101
- const mine = ownOfPull(told, state.reviews, user)
106
+ const mine = ownOfPull(told, state.reviews, user, reviewed.parseComments !== undefined, bases)
102
107
  if (mine.size === 0) return null
103
108
  const { passed } = await askReviewed(reviewed.lookup, new Map([...mine.values()].flatMap(({ pkgs }) => pkgs.map(askedOf))))
104
109
  const there = reviewsByVersion(commented.filter(review => review.reviewer === user))
@@ -6,10 +6,11 @@ import { REVIEW_VERDICTS, type ReviewSummary, type ReviewVerdict, allowedReviewV
6
6
 
7
7
  // A review is of a version, as npm's registry has it, by its integrity; of
8
8
  // it as pnpm patches it (`patchHash`, the patch's hash as a lockfile names
9
- // it), where it is patched; and compared with a version (its base), or none.
9
+ // it), where it is patched; and compared with a version (its base), or none,
10
+ // that as a patch changes it too (`basePatchHash`), where named so.
10
11
  export interface ReviewContext {
11
12
  ecosystem: 'npm'; package: string; version: string; integrity: string; patchHash: string | null
12
- basePackage: string | null; baseVersion: string | null; baseIntegrity: string | null
13
+ basePackage: string | null; baseVersion: string | null; baseIntegrity: string | null; basePatchHash: string | null
13
14
  }
14
15
  // The shasums (sha1s, in hex) of the tarballs a review reads, its version's
15
16
  // and its base's, where npm tells them: each held, with its integrity, to the
@@ -67,7 +68,8 @@ CREATE TABLE IF NOT EXISTS managed_dependency_review (
67
68
  base_package TEXT NOT NULL, base_version TEXT NOT NULL, base_integrity TEXT NOT NULL,
68
69
  time INTEGER NOT NULL, revision INTEGER NOT NULL, published_at INTEGER, revoked_at INTEGER, files TEXT,
69
70
  status TEXT CHECK (status IN ('accept', 'accept-with-nits', 'request-changes', 'reject')), comment TEXT NOT NULL DEFAULT '',
70
- shasum TEXT NOT NULL DEFAULT '', base_shasum TEXT NOT NULL DEFAULT '', patch_hash TEXT NOT NULL DEFAULT '', patch_source TEXT
71
+ shasum TEXT NOT NULL DEFAULT '', base_shasum TEXT NOT NULL DEFAULT '', patch_hash TEXT NOT NULL DEFAULT '', patch_source TEXT,
72
+ base_patch_hash TEXT NOT NULL DEFAULT ''
71
73
  ) STRICT;
72
74
  CREATE INDEX IF NOT EXISTS managed_dependency_review_context_idx
73
75
  ON managed_dependency_review(ecosystem, package, version, integrity, base_package, base_version, base_integrity, time);
@@ -87,22 +89,23 @@ CREATE INDEX IF NOT EXISTS managed_dependency_review_team_idx ON managed_depende
87
89
  `
88
90
  // The columns added since the table was, for a database that has it already.
89
91
  export const DEPENDENCY_REVIEW_COLUMNS = [['shasum', "TEXT NOT NULL DEFAULT ''"], ['base_shasum', "TEXT NOT NULL DEFAULT ''"],
90
- ['patch_hash', "TEXT NOT NULL DEFAULT ''"], ['patch_source', 'TEXT']] as const
91
- // Each author's one draft of a comparison, its patch's too, made once those
92
- // columns are: the index held to it before patches were reviewed gone.
92
+ ['patch_hash', "TEXT NOT NULL DEFAULT ''"], ['patch_source', 'TEXT'], ['base_patch_hash', "TEXT NOT NULL DEFAULT ''"]] as const
93
+ // Each author's one draft of a comparison, its patches' too, made once those
94
+ // columns are: those held to it before patches, then its base's, were reviewed gone.
93
95
  export const DEPENDENCY_REVIEW_INDEXES = `
94
96
  DROP INDEX IF EXISTS managed_dependency_review_unpublished_idx;
95
- CREATE UNIQUE INDEX IF NOT EXISTS managed_dependency_review_draft_idx
96
- ON managed_dependency_review(user_id, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity)
97
+ DROP INDEX IF EXISTS managed_dependency_review_draft_idx;
98
+ CREATE UNIQUE INDEX IF NOT EXISTS managed_dependency_review_drafts_idx
99
+ ON managed_dependency_review(user_id, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, base_patch_hash)
97
100
  WHERE published_at IS NULL;`
98
- const values = (c: ReviewContext) => [c.ecosystem, c.package, c.version, c.integrity, c.patchHash ?? '', c.basePackage ?? '', c.baseVersion ?? '', c.baseIntegrity ?? '']
101
+ const values = (c: ReviewContext) => [c.ecosystem, c.package, c.version, c.integrity, c.patchHash ?? '', c.basePackage ?? '', c.baseVersion ?? '', c.baseIntegrity ?? '', c.basePatchHash ?? '']
99
102
  const targetWhere = 'ecosystem = ? AND package = ? AND version = ? AND integrity = ? AND patch_hash = ?'
100
- const contextWhere = `${targetWhere} AND base_package = ? AND base_version = ? AND base_integrity = ?`
103
+ const contextWhere = `${targetWhere} AND base_package = ? AND base_version = ? AND base_integrity = ? AND base_patch_hash = ?`
101
104
  // Its author by the login they reviewed as, and by the name the app's user
102
105
  // has now (null once they are none, or have none), as the lists show them.
103
106
  const columns = `id, user_id AS user, user_login AS userLogin, (SELECT n.name FROM managed_user n WHERE n.id = user_id) AS userName, ecosystem, package, version, integrity,
104
107
  NULLIF(patch_hash, '') AS patchHash, NULLIF(base_package, '') AS basePackage, NULLIF(base_version, '') AS baseVersion, NULLIF(base_integrity, '') AS baseIntegrity,
105
- NULLIF(shasum, '') AS shasum, NULLIF(base_shasum, '') AS baseShasum, patch_source AS patchSource,
108
+ NULLIF(base_patch_hash, '') AS basePatchHash, NULLIF(shasum, '') AS shasum, NULLIF(base_shasum, '') AS baseShasum, patch_source AS patchSource,
106
109
  time, revision, published_at AS publishedAt, revoked_at AS revokedAt, files, status, comment`
107
110
  const conflict = () => { throw new ManagedMutationError(409, 'review-conflict') }
108
111
  // What a review keeps of the bytes it read: its tarballs' shasums, and where
@@ -225,7 +228,7 @@ async function listContext(db: ManagedSql, context: ReviewContext, user: string,
225
228
  AND (user_id = ? OR (published_at IS NOT NULL AND EXISTS (
226
229
  SELECT 1 FROM managed_dependency_review_team rt JOIN managed_team t ON t.id = rt.team_id JOIN managed_user u ON u.id = ?
227
230
  WHERE rt.review_id = r.id AND ${reviewsIn(false)})))
228
- ORDER BY time, id`).all(...values(context).slice(0, allBases ? 5 : 8), user, user)
231
+ ORDER BY time, id`).all(...values(context).slice(0, allBases ? 5 : 9), user, user)
229
232
  return expandReviews(db, rows, user)
230
233
  }
231
234
 
@@ -329,8 +332,8 @@ export function dependencyReviewMethods(db: ManagedSql): DependencyReviewStore {
329
332
  if (await unpublished()) return conflict()
330
333
  const next = randomUUID()
331
334
  await db.prepare(`INSERT INTO managed_dependency_review
332
- (id, user_id, user_login, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, shasum, base_shasum, patch_source, time, revision)
333
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`).run(next, user.id, user.login, ...values(context), ...shasums(tarballs), now)
335
+ (id, user_id, user_login, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, base_patch_hash, shasum, base_shasum, patch_source, time, revision)
336
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`).run(next, user.id, user.login, ...values(context), ...shasums(tarballs), now)
334
337
  return next
335
338
  }
336
339
  if (change.action === 'start') {