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

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 (150) hide show
  1. package/common/default-scan-models.ts +6 -5
  2. package/common/managed/comments.ts +9 -0
  3. package/out/activity.js +3 -3
  4. package/out/brotli-fallback.js +1 -1
  5. package/out/chunk-4ISO5F7Y.js +1 -1
  6. package/out/chunk-65PLAG3I.js +12 -0
  7. package/out/chunk-6CCSTJWB.js +1 -0
  8. package/out/chunk-7GJNLCXF.js +15 -0
  9. package/out/chunk-BZP3CT2V.js +244 -0
  10. package/out/{chunk-TZS7KERJ.js → chunk-DCBXCBLL.js} +2 -2
  11. package/out/chunk-E3LFSUDJ.js +1 -1
  12. package/out/chunk-EQ5EQXV5.js +1 -0
  13. package/out/chunk-F3UI65ZI.js +42 -0
  14. package/out/chunk-FAG6E5RC.js +3 -0
  15. package/out/chunk-HAZKDK4M.js +1 -1
  16. package/out/chunk-IZ6MYRYB.js +1 -1
  17. package/out/{chunk-VZJIHHTQ.js → chunk-K2QJLP3E.js} +1 -1
  18. package/out/chunk-NXATZJQ2.js +1 -1
  19. package/out/chunk-OBNHCORJ.js +2 -0
  20. package/out/chunk-OGNTXZYM.js +4 -0
  21. package/out/chunk-QRKFPLA4.js +2 -2
  22. package/out/chunk-QVKFY4FA.js +1 -0
  23. package/out/chunk-TOXMUOIW.js +2 -2
  24. package/out/chunk-WMFDQS2L.js +2 -2
  25. package/out/chunk-Y5ZHFNBD.js +1 -1
  26. package/out/client-managed-import.js +1 -1
  27. package/out/client-managed.js +7 -7
  28. package/out/client-sync.js +3 -3
  29. package/out/compare.js +19 -14
  30. package/out/dialogs.js +38 -38
  31. package/out/graph.js +12 -12
  32. package/out/index.html +5 -5
  33. package/out/prism.js +2 -2
  34. package/out/scan.js +2 -2
  35. package/out/terminal.js +150 -148
  36. package/out/view.css +1 -1
  37. package/out/view.js +5 -5
  38. package/package.json +21 -18
  39. package/risk/files/runs-code.js +2 -2
  40. package/server-e2e/static.ts +1 -1
  41. package/server-managed/activity.ts +23 -43
  42. package/server-managed/agent-merges.ts +2 -2
  43. package/server-managed/blob-store.ts +10 -1
  44. package/server-managed/bundle-advisories.ts +3 -2
  45. package/server-managed/bundle-advisory-inventory.ts +1 -1
  46. package/server-managed/bundle-build-worker.js +41 -6
  47. package/server-managed/bundle-build.ts +26 -14
  48. package/server-managed/bundle-cache.ts +29 -41
  49. package/server-managed/bundle-catalog.ts +11 -11
  50. package/server-managed/bundle-commits.ts +9 -16
  51. package/server-managed/bundle-dependency-reviews.ts +5 -11
  52. package/server-managed/bundle-summary-cache.ts +23 -14
  53. package/server-managed/bundle-validation.ts +2 -1
  54. package/server-managed/combined.ts +1 -5
  55. package/server-managed/comments.ts +15 -28
  56. package/server-managed/commit-coauthors.ts +4 -5
  57. package/server-managed/commit-lockfiles.ts +6 -5
  58. package/server-managed/comparison.ts +3 -5
  59. package/server-managed/config.ts +1 -2
  60. package/server-managed/db-methods.ts +163 -244
  61. package/server-managed/db-neon.ts +82 -178
  62. package/server-managed/db-schema.ts +15 -0
  63. package/server-managed/db.ts +5 -11
  64. package/server-managed/dependabot-access.ts +2 -1
  65. package/server-managed/dependabot-alerts.ts +7 -12
  66. package/server-managed/dependency-review-comments.ts +7 -13
  67. package/server-managed/dependency-reviews.ts +14 -15
  68. package/server-managed/github-accounts.ts +4 -5
  69. package/server-managed/github-actions.ts +6 -6
  70. package/server-managed/github-app.ts +19 -48
  71. package/server-managed/github-graphql.ts +5 -2
  72. package/server-managed/github-issue-links.ts +62 -42
  73. package/server-managed/github-issue-oauth.ts +7 -24
  74. package/server-managed/github-issues.ts +9 -7
  75. package/server-managed/github-link-oauth.ts +7 -20
  76. package/server-managed/github-oauth.ts +38 -12
  77. package/server-managed/github-pulls.ts +37 -26
  78. package/server-managed/github-requests.ts +21 -8
  79. package/server-managed/github-values.ts +26 -0
  80. package/server-managed/history-windows.ts +7 -7
  81. package/server-managed/http.ts +495 -554
  82. package/server-managed/index.ts +6 -6
  83. package/server-managed/link-reports.ts +6 -19
  84. package/server-managed/lockfile-scope.ts +1 -1
  85. package/server-managed/management.ts +14 -3
  86. package/server-managed/npm-delta.ts +22 -57
  87. package/server-managed/npm-insights.ts +31 -26
  88. package/server-managed/npm-kept.ts +9 -8
  89. package/server-managed/npm-loads.ts +2 -7
  90. package/server-managed/npm-manifest.ts +6 -4
  91. package/server-managed/npm-packages.ts +17 -9
  92. package/server-managed/npm-patch.ts +8 -16
  93. package/server-managed/npm-provenance.ts +12 -8
  94. package/server-managed/npm-risk.ts +9 -7
  95. package/server-managed/object-storage-disk.ts +2 -3
  96. package/server-managed/object-storage-vercel.ts +15 -11
  97. package/server-managed/object-storage.ts +7 -0
  98. package/server-managed/pretty-print.ts +8 -19
  99. package/server-managed/public-workspace.ts +50 -46
  100. package/server-managed/pull-comment-reviews.ts +2 -2
  101. package/server-managed/pull-dependencies.ts +20 -31
  102. package/server-managed/pull-dependency-reviews.ts +17 -24
  103. package/server-managed/pull-reviews.ts +4 -7
  104. package/server-managed/queue.ts +14 -0
  105. package/server-managed/release-commits.ts +9 -8
  106. package/server-managed/rename-diff.ts +17 -60
  107. package/server-managed/report-migration.ts +5 -8
  108. package/server-managed/report-sources.ts +6 -10
  109. package/server-managed/report-store.ts +2 -10
  110. package/server-managed/repository-actions.ts +7 -8
  111. package/server-managed/repository-agents.ts +31 -57
  112. package/server-managed/repository-aliases.ts +3 -9
  113. package/server-managed/repository-browser.ts +18 -16
  114. package/server-managed/repository-changes.ts +33 -37
  115. package/server-managed/repository-code.ts +5 -5
  116. package/server-managed/repository-dependency-reviews.ts +6 -13
  117. package/server-managed/repository-discovery.ts +2 -1
  118. package/server-managed/repository-history.ts +47 -51
  119. package/server-managed/repository-issues.ts +59 -30
  120. package/server-managed/repository-pulls.ts +7 -12
  121. package/server-managed/repository-pulse.ts +51 -45
  122. package/server-managed/repository-risk-assess.ts +5 -2
  123. package/server-managed/repository-risk-audit.ts +1 -1
  124. package/server-managed/repository-risk-read.ts +6 -6
  125. package/server-managed/repository-risk.ts +32 -40
  126. package/server-managed/repository-squashes.ts +7 -15
  127. package/server-managed/request-timing.ts +1 -1
  128. package/server-managed/sql.ts +18 -0
  129. package/server-managed/storage-encryption.ts +5 -7
  130. package/server-managed/team-app.ts +4 -7
  131. package/server-managed/team-npm-scopes.ts +5 -8
  132. package/server-managed/team-reports.ts +15 -15
  133. package/server-managed/type-only-proof.js +108 -0
  134. package/server-managed/type-only-worker.js +26 -14
  135. package/server-managed/type-only.ts +90 -60
  136. package/server-managed/uploads.ts +3 -3
  137. package/server-managed/upstream-cache.ts +5 -7
  138. package/server-managed/worker-turns.ts +76 -0
  139. package/server-managed/workspace-shares.ts +1 -2
  140. package/strip-types-loader.js +13 -10
  141. package/out/chunk-2SY4PYUQ.js +0 -4
  142. package/out/chunk-4HI2MSAV.js +0 -17
  143. package/out/chunk-4TQKM3JC.js +0 -42
  144. package/out/chunk-6VDDCFHT.js +0 -3
  145. package/out/chunk-EEQHVKR3.js +0 -1
  146. package/out/chunk-HNQNDNIE.js +0 -12
  147. package/out/chunk-OFPDMZJF.js +0 -244
  148. package/out/chunk-OQRSIBSC.js +0 -1
  149. package/out/chunk-YGRRXC2L.js +0 -1
  150. package/out/chunk-YTO6AQZM.js +0 -2
@@ -9,12 +9,12 @@ import { bundleReasons } from '../common/bundle-reasons.js'
9
9
  import { sourcemapEdges } from '../common/bundle-sourcemap.js'
10
10
  import { type BundleAdvisoryInventory, bundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
11
11
  import { decodeUtf8 } from '../common/utf8.js'
12
- import type { OpenedBlob } from './blob-store.ts'
12
+ import { type OpenedBlob, readBytes } from './blob-store.ts'
13
13
  import type { BundleStore } from './bundle-store.ts'
14
14
  import { encodeBrotli } from './brotli.ts'
15
15
  import type { ManagedBundle, ManagedDb } from './db.ts'
16
16
  import { CacheMissError } from './cache-storage.ts'
17
- import { SUMMARY_FILENAME, createBundleSummaryCache } from './bundle-summary-cache.ts'
17
+ import { SUMMARY_FILENAME, createBundleSummaryCache, readCachedBytes } from './bundle-summary-cache.ts'
18
18
 
19
19
  const decompress = promisify(brotliDecompress)
20
20
  const MAX_DECODED_BYTES = 512 * 1024 * 1024
@@ -60,28 +60,25 @@ function encodePackageInventory(details: BundleDetails): Buffer {
60
60
  parts.push(part)
61
61
  return true
62
62
  }
63
- function entries(rows: unknown[]) {
64
- if (!append('[')) return false
63
+ // `items` as `write` writes each, a comma apart, between `open` and
64
+ // `close`: false once past the budget, as `append` is.
65
+ function list<T>(open: string, items: Iterable<T>, write: (item: T) => boolean, close: string) {
66
+ if (!append(open)) return false
65
67
  let first = true
66
- for (const row of rows) {
67
- if (!append(`${first ? '' : ','}${JSON.stringify(row)}`)) return false
68
+ for (const item of items) {
69
+ if (!append(first ? '' : ',') || !write(item)) return false
68
70
  first = false
69
71
  }
70
- return append(']')
72
+ return append(close)
71
73
  }
74
+ const rows = (items: unknown[]) => list('[', items, row => append(JSON.stringify(row)), ']')
72
75
  function inventory(paths: Set<string> | null) {
73
76
  const { packages, skipped } = bundleAdvisoryInventory(details, paths)
74
- return append('{"packages":') && entries(packages) && append(',"skipped":') && entries(skipped) && append('}')
77
+ return append('{"packages":') && rows(packages) && append(',"skipped":') && rows(skipped) && append('}')
75
78
  }
76
- append('{"all":')
77
- if (!inventory(null) || !append(',"reasons":{')) return Buffer.from('null')
78
- let first = true
79
- for (const [reason, paths] of bundleReasons(details)) {
80
- if (!append(`${first ? '' : ','}${JSON.stringify(reason)}:`) || !inventory(paths)) return Buffer.from('null')
81
- first = false
82
- }
83
- if (!append('}}')) return Buffer.from('null')
84
- return Buffer.from(parts.join(''))
79
+ const whole = append('{"all":') && inventory(null)
80
+ && list(',"reasons":{', bundleReasons(details), ([reason, paths]) => append(`${JSON.stringify(reason)}:`) && inventory(paths), '}}')
81
+ return Buffer.from(whole ? parts.join('') : 'null')
85
82
  }
86
83
 
87
84
  // What a catalog sends of a bundle before it opens. A Stasis bundle's
@@ -104,9 +101,15 @@ function readSourcemapEdges(details: BundleDetails) {
104
101
  catch (err) { console.warn('managed: sourcemap edges failed:', err) }
105
102
  }
106
103
 
107
- async function build(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
104
+ // As readBundleDetails, thrown where the bundle's bytes are gone.
105
+ async function storedDetails(record: BundleCacheRecord, store: BundleStore) {
108
106
  const details = await readBundleDetails(record, store)
109
107
  if (!details) throw new Error('Bundle bytes unavailable')
108
+ return details
109
+ }
110
+
111
+ async function build(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
112
+ const details = await storedDetails(record, store)
110
113
  readSourcemapEdges(details)
111
114
  const metadata = { ...await createBundleMetadata(details), id: record.id, filename: record.filename }
112
115
  const body = await encodeBrotli(Buffer.from(JSON.stringify(metadata)))
@@ -134,11 +137,7 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
134
137
  const pending = new Map<string, Promise<void>>()
135
138
  // The database deduplicates by integrity, so each hash has one persistent
136
139
  // bundle/cache directory, shared across teams and repeated uploads.
137
- const summaries = createBundleSummaryCache(storage, async record => {
138
- const details = await readBundleDetails(record, store)
139
- if (!details) throw new Error('Bundle bytes unavailable')
140
- return bundleSummary(details)
141
- }, id => db.getBundle(id))
140
+ const summaries = createBundleSummaryCache(storage, async record => bundleSummary(await storedDetails(record, store)), id => db.getBundle(id))
142
141
  let queue = Promise.resolve()
143
142
  async function ensure(record: BundleCacheRecord): Promise<void> {
144
143
  const existing = pending.get(record.id)
@@ -175,29 +174,18 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
175
174
  // A sourcemap's edges as its metadata keeps them, read with the parser
176
175
  // once, for a derivative that reads the bundle itself (report previews).
177
176
  async sourcemapEdges(record: ManagedBundle): Promise<BundleDetails['edges']> {
178
- const cached = await openCached(record, filename)
179
- const chunks: Buffer[] = []
180
- try { for await (const chunk of cached.stream) chunks.push(Buffer.from(chunk)) }
181
- finally { cached.stream.destroy() }
182
- const decoded = await decompress(Buffer.concat(chunks), { maxOutputLength: MAX_DECODED_BYTES })
177
+ const decoded = await decompress(await readBytes(await openCached(record, filename)), { maxOutputLength: MAX_DECODED_BYTES })
183
178
  return parseBundleMetadata(JSON.parse(decodeUtf8(decoded)), record.integrity).edges
184
179
  },
185
180
  async advisoryInventory(record: ManagedBundle, reason = ''): Promise<BundleAdvisoryInventory | null | undefined> {
186
181
  if (record.kind !== 'stasis') return { packages: [], skipped: [] }
187
182
  const cached = await openCached(record, packagesFilename)
188
- try {
189
- if (cached.size != null && cached.size > MAX_PACKAGE_INVENTORY_BYTES) return null
190
- const chunks: Buffer[] = []
191
- let size = 0
192
- for await (const chunk of cached.stream) {
193
- size += chunk.length
194
- if (size > MAX_PACKAGE_INVENTORY_BYTES) return null
195
- chunks.push(Buffer.from(chunk))
196
- }
197
- const inventory = JSON.parse(decodeUtf8(Buffer.concat(chunks)))
198
- if (inventory === null) return null
199
- return reason ? (Object.hasOwn(inventory.reasons, reason) ? inventory.reasons[reason] : undefined) : inventory.all
200
- } finally { cached.stream.destroy() }
183
+ if (cached.size != null && cached.size > MAX_PACKAGE_INVENTORY_BYTES) { cached.stream.destroy(); return null }
184
+ const bytes = await readCachedBytes(cached, MAX_PACKAGE_INVENTORY_BYTES)
185
+ if (!bytes) return null
186
+ const inventory = JSON.parse(decodeUtf8(bytes))
187
+ if (inventory === null) return null
188
+ return reason ? (Object.hasOwn(inventory.reasons, reason) ? inventory.reasons[reason] : undefined) : inventory.all
201
189
  },
202
190
  async delete(id: string) {
203
191
  // Call after deleting the row. Waiting prevents an in-flight builder
@@ -1,29 +1,29 @@
1
1
  import type { BundleCache, BundleSummary } from './bundle-cache.ts'
2
2
  import type { AdminBundle, UserTeamBundle } from './db.ts'
3
+ import { eachOf } from './queue.ts'
3
4
 
4
5
  const SUMMARY_READ_CONCURRENCY = 8
6
+ type ListedBundle = AdminBundle | UserTeamBundle
7
+
8
+ // The bundles, one of each content hash.
9
+ const byIntegrity = (bundles: readonly ListedBundle[]) => [...new Map(bundles.map(bundle => [bundle.integrity, bundle])).values()]
5
10
 
6
11
  // Read only existing summaries: cold/malformed bundles must never trigger
7
12
  // parsing or wait for metadata builds before the catalog response is sent.
8
- export async function bundleSummaries(bundles: readonly (AdminBundle | UserTeamBundle)[], cache?: BundleCache) {
13
+ export async function bundleSummaries(bundles: readonly ListedBundle[], cache?: BundleCache) {
9
14
  const summaries = new Map<string, { summary: BundleSummary | null; summaryRetryAt: number | null }>()
10
15
  if (cache) {
11
- const unique = [...new Map(bundles.map(bundle => [bundle.integrity, bundle])).values()]
12
- let next = 0
13
16
  // Cold reads may each access remote storage. Bound those requests as well
14
17
  // as the subsequent backfill, without dropping entries from large catalogs.
15
- await Promise.all(Array.from({ length: Math.min(SUMMARY_READ_CONCURRENCY, unique.length) }, async () => {
16
- while (next < unique.length) {
17
- const bundle = unique[next++]!
18
- summaries.set(bundle.integrity, await cache.summaryStatus(bundle).catch(() => ({ summary: null, summaryRetryAt: null })))
19
- }
20
- }))
18
+ await eachOf(byIntegrity(bundles), SUMMARY_READ_CONCURRENCY, async bundle => {
19
+ summaries.set(bundle.integrity, await cache.summaryStatus(bundle).catch(() => ({ summary: null, summaryRetryAt: null })))
20
+ })
21
21
  }
22
22
  return summaries
23
23
  }
24
24
 
25
25
  // Called after sending the response. Each cache permits one small batch at a
26
26
  // time, deduplicated by content hash, and skips persisted retry-backoff markers.
27
- export async function backfillBundleSummaries(bundles: readonly (AdminBundle | UserTeamBundle)[], cache?: BundleCache) {
28
- await cache?.backfillSummaries([...new Map(bundles.map(bundle => [bundle.integrity, bundle])).values()])
27
+ export async function backfillBundleSummaries(bundles: readonly ListedBundle[], cache?: BundleCache) {
28
+ await cache?.backfillSummaries(byIntegrity(bundles))
29
29
  }
@@ -3,25 +3,23 @@ import { bundleCommitHash } from '../common/bundle-commit.js'
3
3
  import type { BundleSummary } from './bundle-cache.ts'
4
4
  import type { ManagedDb } from './db.ts'
5
5
  import { type GithubCommit, githubCommitKey } from './github-metadata.ts'
6
+ import { LOGIN, MAX_NAME, timeOf } from './github-values.ts'
6
7
 
7
8
  const MAX_MESSAGE_LENGTH = 65_536
8
- const MAX_NAME_LENGTH = 256
9
- // GitHub logins, and the `[bot]` accounts apps commit as.
10
- const GITHUB_LOGIN = /^[A-Za-z\d][A-Za-z\d-]{0,38}(?:\[bot\])?$/u
11
9
  const BACKFILL_LIMIT = 4
12
10
  const RETRY_MS = 5 * 60_000
13
11
 
14
- export type CommitDetails = Omit<GithubCommit, 'key' | 'fetchedAt'>
12
+ type CommitDetails = Omit<GithubCommit, 'key' | 'fetchedAt'>
15
13
  // What viewers see of a cached commit: its subject in place of the message.
16
- export type CatalogCommitDetails = Omit<CommitDetails, 'message'> & { subject: string }
14
+ type CatalogCommitDetails = Omit<CommitDetails, 'message'> & { subject: string }
17
15
  // What a catalog sends with a bundle whose summary records a commit, when
18
16
  // the cache holds its details, tags pointing to it, or both. `github` is the
19
17
  // repository they were cached for: the one the bundle is stored at.
20
- export interface BundleCommitInfo { sha: string; github: string; tags: string[]; details: CatalogCommitDetails | null }
18
+ interface BundleCommitInfo { sha: string; github: string; tags: string[]; details: CatalogCommitDetails | null }
21
19
  interface CatalogBundle { integrity: string; repoId: number | null; repoFullName: string | null }
22
20
  type Summaries = ReadonlyMap<string, { summary: BundleSummary | null }>
23
21
  export interface CatalogCommit { repoId: number; sha: string; key: string }
24
- export interface CommitReader { commitDetails(sha: string): Promise<CommitDetails | null> }
22
+ interface CommitReader { commitDetails(sha: string): Promise<CommitDetails | null> }
25
23
 
26
24
  function truncate(value: string, max: number): string {
27
25
  if (value.length <= max) return value
@@ -30,12 +28,7 @@ function truncate(value: string, max: number): string {
30
28
  }
31
29
 
32
30
  function name(value: unknown): string | null {
33
- return typeof value === 'string' && value.trim() ? truncate(value.trim(), MAX_NAME_LENGTH) : null
34
- }
35
-
36
- function date(value: unknown): number | null {
37
- const time = typeof value === 'string' ? Date.parse(value) : NaN
38
- return Number.isSafeInteger(time) ? time : null
31
+ return typeof value === 'string' && value.trim() ? truncate(value.trim(), MAX_NAME) : null
39
32
  }
40
33
 
41
34
  // `body` is a GitHub list-commits page that starts at `sha`, so its first
@@ -50,9 +43,9 @@ export function parseGithubCommit(sha: string, body: unknown): CommitDetails | n
50
43
  return {
51
44
  message: truncate(item.commit.message, MAX_MESSAGE_LENGTH),
52
45
  authorName: name(item.commit.author?.name),
53
- authorLogin: typeof login === 'string' && GITHUB_LOGIN.test(login) ? login : null,
54
- authoredAt: date(item.commit.author?.date),
55
- committedAt: date(item.commit.committer?.date),
46
+ authorLogin: typeof login === 'string' && LOGIN.test(login) ? login : null,
47
+ authoredAt: timeOf(item.commit.author?.date),
48
+ committedAt: timeOf(item.commit.committer?.date),
56
49
  }
57
50
  }
58
51
 
@@ -47,21 +47,15 @@ export function installsBundle(path: string, directory: string): boolean {
47
47
  // how many versions it bundles (`versions`), each once.
48
48
  export function bundleDependencies(bundled: BundledVersion[], read: CommitLockfiles, commit: string) {
49
49
  const versions = [...new Map(bundled.map(one => [`${one.name}@${one.version}`, one])).values()]
50
- const byDirectory = new Map<string, string[]>()
51
- for (const { path } of read.lockfiles) byDirectory.set(directoryOf(path), [...byDirectory.get(directoryOf(path)) ?? [], path])
50
+ const byDirectory = Map.groupBy(read.lockfiles.map(({ path }) => path), directoryOf)
52
51
  // Each directory's versions by their name and version, the nearest first.
53
- const nearest = [...byDirectory].toSorted(([a], [b]) => depth(b) - depth(a)).map(([dir, paths]) => {
54
- const locked = new Map<string, LockedPackage[]>()
55
- for (const pkg of lockedIn(read, path => directoryOf(path) === dir).packages) {
56
- const key = `${pkg.name}@${pkg.version ?? ''}`
57
- locked.set(key, [...locked.get(key) ?? [], pkg])
58
- }
59
- return { paths, locked }
60
- })
52
+ const nearest = [...byDirectory].toSorted(([a], [b]) => depth(b) - depth(a)).map(([dir, paths]) =>
53
+ ({ paths, locked: Map.groupBy(lockedIn(read, path => directoryOf(path) === dir).packages, pkg => `${pkg.name}@${pkg.version ?? ''}`) }))
61
54
  const found = new Map<string, LockedPackage>()
62
55
  const unlocked: BundledVersion[] = []
63
56
  for (const one of versions) {
64
- const variants = nearest.find(({ locked }) => locked.has(`${one.name}@${one.version}`))?.locked.get(`${one.name}@${one.version}`)
57
+ const key = `${one.name}@${one.version}`
58
+ const variants = nearest.find(({ locked }) => locked.has(key))?.locked.get(key)
65
59
  if (!variants) { unlocked.push(one); continue }
66
60
  for (const pkg of variants) if (!found.has(lockedWith(pkg))) found.set(lockedWith(pkg), pkg)
67
61
  }
@@ -3,6 +3,7 @@ import { setImmediate } from 'node:timers/promises'
3
3
  import { CacheMissError } from './cache-storage.ts'
4
4
  import { decodeUtf8 } from '../common/utf8.js'
5
5
  import { bundleCommitHash } from '../common/bundle-commit.js'
6
+ import type { OpenedBlob } from './blob-store.ts'
6
7
  import type { BundleCacheRecord, BundleCacheStorage, BundleSummary } from './bundle-cache.ts'
7
8
 
8
9
  // Version 3 adds the optional source commit; version 4 counts lines of code
@@ -14,6 +15,8 @@ const PREVIOUS_SUMMARY_FILENAME = 'v4-summary.json'
14
15
  const RETRY_MS = 5 * 60_000
15
16
  const BACKFILL_LIMIT = 4
16
17
  type CachedSummary = BundleSummary | { retryAt: number } | { previous: BundleSummary }
18
+ // Whether a summary is kept of a bundle: a Stasis bundle's or a sourcemap's.
19
+ const summarized = (record: BundleCacheRecord) => record.kind === 'stasis' || record.kind === 'sourcemap'
17
20
 
18
21
  async function readCurrentSummary(storage: BundleCacheStorage, id: string): Promise<CachedSummary> {
19
22
  try { return await readSummary(storage, id, SUMMARY_FILENAME) }
@@ -24,26 +27,32 @@ async function readCurrentSummary(storage: BundleCacheStorage, id: string): Prom
24
27
  }
25
28
  }
26
29
 
27
- async function readSummary(storage: BundleCacheStorage, id: string, file: string): Promise<BundleSummary | { retryAt: number }> {
28
- const cached = await storage.open(id, file)
30
+ // A cached file's bytes, read whole and its stream destroyed; null past `max`.
31
+ export async function readCachedBytes(cached: OpenedBlob, max: number): Promise<Buffer | null> {
29
32
  try {
30
33
  const chunks: Buffer[] = []
31
34
  let size = 0
32
35
  for await (const chunk of cached.stream) {
33
36
  size += chunk.length
34
- if (size > 1024) throw new Error('Invalid bundle summary')
37
+ if (size > max) return null
35
38
  chunks.push(Buffer.from(chunk))
36
39
  }
37
- const summary = JSON.parse(decodeUtf8(Buffer.concat(chunks))) as BundleSummary | { retryAt: number }
38
- if (summary && 'retryAt' in summary && Number.isSafeInteger(summary.retryAt) && summary.retryAt > 0) return summary
39
- const counts = summary as BundleSummary
40
- if (!counts || ![counts.files, counts.codeFiles, counts.lines].every(value => Number.isSafeInteger(value) && value >= 0)
41
- || counts.codeFiles > counts.files || (counts.commit !== undefined && !bundleCommitHash(counts.commit))
42
- || [counts.stasisVersion, counts.versionedPackages].some(value => value !== undefined && !(Number.isSafeInteger(value) && value >= 0))) throw new Error('Invalid bundle summary')
43
- return counts
40
+ return Buffer.concat(chunks)
44
41
  } finally { cached.stream.destroy() }
45
42
  }
46
43
 
44
+ async function readSummary(storage: BundleCacheStorage, id: string, file: string): Promise<BundleSummary | { retryAt: number }> {
45
+ const bytes = await readCachedBytes(await storage.open(id, file), 1024)
46
+ if (!bytes) throw new Error('Invalid bundle summary')
47
+ const summary = JSON.parse(decodeUtf8(bytes)) as BundleSummary | { retryAt: number }
48
+ if (summary && 'retryAt' in summary && Number.isSafeInteger(summary.retryAt) && summary.retryAt > 0) return summary
49
+ const counts = summary as BundleSummary
50
+ if (!counts || ![counts.files, counts.codeFiles, counts.lines].every(value => Number.isSafeInteger(value) && value >= 0)
51
+ || counts.codeFiles > counts.files || (counts.commit !== undefined && !bundleCommitHash(counts.commit))
52
+ || [counts.stasisVersion, counts.versionedPackages].some(value => value !== undefined && !(Number.isSafeInteger(value) && value >= 0))) throw new Error('Invalid bundle summary')
53
+ return counts
54
+ }
55
+
47
56
  export function createBundleSummaryCache(storage: BundleCacheStorage, build: (record: BundleCacheRecord) => Promise<BundleSummary>, exists: (id: string) => Promise<unknown>) {
48
57
  const entries = new Map<string, { id: string; value: CachedSummary }>()
49
58
  const reads = new Map<string, { id: string; job: Promise<CachedSummary | null> }>()
@@ -85,9 +94,9 @@ export function createBundleSummaryCache(storage: BundleCacheStorage, build: (re
85
94
  catch { await publish(record, { retryAt: Date.now() + RETRY_MS }).catch(() => {}) }
86
95
  }
87
96
  async function summaryStatus(record: BundleCacheRecord) {
88
- const value = ['stasis', 'sourcemap'].includes(record.kind ?? '') ? await read(record) : null
89
- return { summary: !value || 'retryAt' in value ? null : 'previous' in value ? value.previous : value,
90
- summaryRetryAt: value && 'retryAt' in value ? value.retryAt : null }
97
+ const value = summarized(record) ? await read(record) : null
98
+ if (!value || 'retryAt' in value) return { summary: null, summaryRetryAt: value?.retryAt ?? null }
99
+ return { summary: 'previous' in value ? value.previous : value, summaryRetryAt: null }
91
100
  }
92
101
  async function backfill(records: readonly BundleCacheRecord[]) {
93
102
  // Start after the catalog has been sent. Keep this work awaited by the
@@ -95,7 +104,7 @@ export function createBundleSummaryCache(storage: BundleCacheStorage, build: (re
95
104
  await setImmediate()
96
105
  let attempts = 0
97
106
  for (const record of records) {
98
- if (!['stasis', 'sourcemap'].includes(record.kind ?? '')) continue
107
+ if (!summarized(record)) continue
99
108
  const cached = await read(record).catch(() => null)
100
109
  if (cached && !('previous' in cached) && (!('retryAt' in cached) || cached.retryAt > Date.now())) continue
101
110
  if (!await exists(record.id)) continue
@@ -5,6 +5,7 @@
5
5
  import { type BundleValidation, type ValidationPlan, followingMoves, validateBundle, validateRepository } from '@exodus/stasis/validate'
6
6
  import { createClient } from '@preventive/upstream/github.js'
7
7
  import { upstreamGithub } from './github-errors.ts'
8
+ import { USER_AGENT } from './github-requests.ts'
8
9
 
9
10
  export { type BundleValidation, type PlannedBundle, validationPlan } from '@exodus/stasis/validate'
10
11
 
@@ -25,7 +26,7 @@ export const validateDependencies = (plan: ValidationPlan, reason: string, optio
25
26
  // `lockfileError`), not thrown.
26
27
  export function validateAtCommit(plan: ValidationPlan, { fullName, token, commit, directory }: { fullName: string; token: string; commit: string; directory: string },
27
28
  options: Options = {}): Promise<BundleValidation> {
28
- const client = createClient({ token, userAgent: 'deepview-triage' })
29
+ const client = createClient({ token, userAgent: USER_AGENT })
29
30
  const repository = followingMoves(client, fullName)
30
31
  return upstreamGithub(() => validateRepository(plan, { repository, commit, directory },
31
32
  { ...options, strict: false, listTree: paths => client.listRepoTree({ repo: repository.name(), sha: commit, paths }) }))
@@ -38,10 +38,6 @@ export async function init(mode: 'managed+e2e' | 'e2e+managed', { ui = true }: {
38
38
  e2e.httpServer.removeListener('request', next)
39
39
  e2e.httpServer.on('request', withReap(managed.handleRequest,
40
40
  { e2e: e2e.reap, managed: managed.reap }, { isShuttingDown: e2e.isShuttingDown }))
41
- e2e.httpServer.once('listening', () => {
42
- const address = e2e.httpServer.address()
43
- const port = typeof address === 'object' && address ? address.port : config.port
44
- logManagedStartup(config, port, mode)
45
- })
41
+ e2e.httpServer.once('listening', () => { logManagedStartup(config, e2e.httpServer, mode) })
46
42
  return e2e.httpServer
47
43
  }
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import type { DatabaseSync } from 'node:sqlite'
3
3
  import { type ManagedComment, canDeleteComment } from '../common/managed/comments.ts'
4
- import type { ManagedSql } from './sql.ts'
4
+ import { type ManagedSql, sqliteTransaction } from './sql.ts'
5
5
 
6
6
  export interface CommentInput {
7
7
  findingId: string
@@ -54,22 +54,17 @@ export function initCommentMethods(db: DatabaseSync): void {
54
54
  // Preserve legacy text without guessing an author. Clearing the old column
55
55
  // in the same transaction makes the migration safe to restart. Use a fresh
56
56
  // ID so a later legacy-server write cannot collide with an earlier import.
57
- db.exec('BEGIN')
58
- try {
59
- db.exec(`INSERT INTO managed_finding_comment (id, finding_id, body, created_at, updated_at)
57
+ sqliteTransaction(db, 'BEGIN', () => db.exec(`INSERT INTO managed_finding_comment (id, finding_id, body, created_at, updated_at)
60
58
  SELECT 'legacy:' || lower(hex(randomblob(16))), finding_id, comment, updated_at, updated_at
61
59
  FROM managed_finding_triage WHERE comment IS NOT NULL AND comment != '';
62
- UPDATE managed_finding_triage SET comment = NULL WHERE comment IS NOT NULL;`)
63
- db.exec('COMMIT')
64
- } catch (err) {
65
- db.exec('ROLLBACK')
66
- throw err
67
- }
60
+ UPDATE managed_finding_triage SET comment = NULL WHERE comment IS NOT NULL;`))
68
61
  }
69
62
 
70
63
  export function commentMethods(db: ManagedSql): CommentStore {
64
+ // The author's login and name as they are now; one no longer a user keeps
65
+ // the login they wrote it under, and has no name.
71
66
  const fields = `c.id, c.finding_id AS findingId, c.body, c.author_id AS authorId,
72
- COALESCE(u.login, c.author_login) AS authorLogin,
67
+ COALESCE(u.login, c.author_login) AS authorLogin, u.name AS authorName,
73
68
  c.created_at AS createdAt, c.updated_at AS updatedAt, c.version`
74
69
  const select = db.prepare(`SELECT ${fields} FROM managed_finding_comment c
75
70
  LEFT JOIN managed_user u ON u.id = c.author_id WHERE c.id = ?`)
@@ -110,12 +105,10 @@ export function commentMethods(db: ManagedSql): CommentStore {
110
105
  async editComment(id, authorId, authorLogin, body, version, reportId, now) {
111
106
  // Identity/version checks and the event share the operation transaction.
112
107
  const current = await read(id)
113
- if (!current || current.authorId !== authorId || current.version !== version || current.body === body) {
114
- if (!current) return null
115
- if (current.authorId !== authorId) return 'forbidden'
116
- if (current.version !== version) return 'conflict'
117
- return current
118
- }
108
+ if (!current) return null
109
+ if (current.authorId !== authorId) return 'forbidden'
110
+ if (current.version !== version) return 'conflict'
111
+ if (current.body === body) return current
119
112
  await update.run(body, now, id, authorId, version)
120
113
  await event.run(id, current.findingId, authorId, authorLogin, 'edited a comment', now, reportId, reportId, reportId)
121
114
  return (await read(id))!
@@ -123,11 +116,9 @@ export function commentMethods(db: ManagedSql): CommentStore {
123
116
  async deleteComment(id, actorId, actorLogin, version, reportId, now) {
124
117
  const current = await read(id)
125
118
  const role = (await userRole.get(actorId) as { role: string } | undefined)?.role ?? 'none'
126
- const allowed = current != null && canDeleteComment(current, { id: actorId, role })
127
- if (!current || !allowed || current.version !== version) {
128
- if (!current) return null
129
- return allowed ? 'conflict' : 'forbidden'
130
- }
119
+ if (!current) return null
120
+ if (!canDeleteComment(current, { id: actorId, role })) return 'forbidden'
121
+ if (current.version !== version) return 'conflict'
131
122
  await remove.run(id, current.authorId, current.authorId, version)
132
123
  await event.run(id, current.findingId, actorId, actorLogin, 'deleted a comment', now, reportId, reportId, reportId)
133
124
  return 'deleted'
@@ -138,14 +129,10 @@ export function commentMethods(db: ManagedSql): CommentStore {
138
129
  function migrateCommentDates(db: DatabaseSync): void {
139
130
  const columns = db.prepare('PRAGMA table_info(managed_finding_comment)').all() as { name: string; notnull: number }[]
140
131
  if (!columns.some(column => ['created_at', 'updated_at'].includes(column.name) && column.notnull)) return
141
- db.exec('BEGIN')
142
- try {
143
- db.exec(`CREATE TABLE managed_finding_comment_nullable_dates (${COMMENT_COLUMNS}) STRICT;
132
+ sqliteTransaction(db, 'BEGIN', () => db.exec(`CREATE TABLE managed_finding_comment_nullable_dates (${COMMENT_COLUMNS}) STRICT;
144
133
  INSERT INTO managed_finding_comment_nullable_dates (id, finding_id, body, author_id, author_login, created_at, updated_at, version)
145
134
  SELECT id, finding_id, body, author_id, author_login, created_at, updated_at, version FROM managed_finding_comment;
146
135
  DROP TABLE managed_finding_comment;
147
136
  ALTER TABLE managed_finding_comment_nullable_dates RENAME TO managed_finding_comment;
148
- CREATE INDEX finding_comment_finding_idx ON managed_finding_comment(finding_id, created_at, id);`)
149
- db.exec('COMMIT')
150
- } catch (err) { db.exec('ROLLBACK'); throw err }
137
+ CREATE INDEX finding_comment_finding_idx ON managed_finding_comment(finding_id, created_at, id);`))
151
138
  }
@@ -5,6 +5,7 @@ import { agentSignals, trailerBlock } from '../common/managed/agent-tasks.ts'
5
5
  import { GITHUB_AGENTS, type GithubAgentId, emailAgent, githubAgent } from '../common/managed/github-agents.ts'
6
6
  import { APP_AGENTS } from './app-agents.ts'
7
7
  import { type NamedAccount, commitAccount } from './github-accounts.ts'
8
+ import { nameOf } from './github-values.ts'
8
9
 
9
10
  export const MAX_COAUTHORS = 3
10
11
  // The rules who a commit names beside its author is read by (coauthorFacts),
@@ -12,13 +13,11 @@ export const MAX_COAUTHORS = 3
12
13
  // squashed pull requests) read again by these, once raised. The agents'
13
14
  // accounts, addresses and names are none of them (coauthorsOf).
14
15
  export const COAUTHORS_READ = 5
15
- const MAX_NAME = 256
16
- const textOf = (value: unknown, max: number) => typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : null
17
16
 
18
17
  // One who made a commit beside its author: by name and account, as its
19
18
  // author is, and the agent it is where known (common/managed/github-agents.ts),
20
19
  // by its account, its commits' address or name, or the marks it leaves.
21
- export interface Coauthor { name: string | null; login: string | null; id: number | null; agent?: string }
20
+ interface Coauthor { name: string | null; login: string | null; id: number | null; agent?: string }
22
21
 
23
22
  // `Co-authored-by: <name> <address>` trailers, GitHub matching the key
24
23
  // regardless of case; Cursor's agents' links, as their work carries them;
@@ -62,7 +61,7 @@ export function coauthorFacts(message: unknown, listed: Maker[] | null = null):
62
61
  const makers = listed ?? coauthorTrailers(text).map(({ name, email }) => ({ name, email, account: commitAccount({ email }) }))
63
62
  const signals = agentSignals([text], FINGERPRINTED)
64
63
  return {
65
- named: makers.slice(0, MAX_NAMED).map(({ name, email, account }) => ({ name: textOf(name, MAX_NAME), email: textOf(email, MAX_NAME), login: account.login, id: account.id })),
64
+ named: makers.slice(0, MAX_NAMED).map(({ name, email, account }) => ({ name: nameOf(name), email: nameOf(email), login: account.login, id: account.id })),
66
65
  markedBy: [...signals.claude || signals.sessions.length > 0 ? ['claude'] : [], ...signals.tasks.length > 0 || signals.codex ? ['codex'] : [],
67
66
  ...CURSOR_AGENT.test(text) ? ['cursor'] : [], ...signals.agents],
68
67
  }
@@ -86,7 +85,7 @@ export function coauthorsOf({ authorName, authorEmail = null, authorLogin, autho
86
85
  const same = (a: Identity, b: Identity) => a.agent && b.agent ? a.agent === b.agent : a.login && b.login ? a.login === b.login
87
86
  : a.email && b.email ? a.email === b.email : a.name !== null && a.name === b.name
88
87
  const author: Maker = { name: authorName, email: authorEmail, account: { login: authorLogin, id: authorId } }
89
- const seen = [identity(makerAgent(author), authorLogin, textOf(authorName, MAX_NAME), authorEmail)]
88
+ const seen = [identity(makerAgent(author), authorLogin, nameOf(authorName), authorEmail)]
90
89
  const coauthors: Coauthor[] = []
91
90
  const add = (coauthor: Coauthor, email: unknown = null) => {
92
91
  const who = identity(coauthor.agent ?? null, coauthor.login, coauthor.name, email)
@@ -10,13 +10,14 @@
10
10
  // is locked. GitHub having none of a lockfile it lists there fails the
11
11
  // whole, as it would for any file.
12
12
  import { createClient } from '@preventive/upstream/github.js'
13
- import { upstreamGithub } from './github-errors.ts'
14
- import { GithubApiError } from './github-app.ts'
13
+ import { GithubApiError, upstreamGithub } from './github-errors.ts'
14
+ import { USER_AGENT } from './github-requests.ts'
15
15
  import { type LockedPackage, patchedIn } from './locked-packages.ts'
16
16
  import { type Lru, lru } from './lru.ts'
17
- import { type GithubAsked, type ListedLockfile, type LockfileStore, eachOf, lockedWith, lockfileFormat, readLockfile } from './pull-dependencies.ts'
17
+ import { eachOf } from './queue.ts'
18
+ import { type GithubAsked, type ListedLockfile, type LockfileStore, lockedWith, lockfileFormat, readLockfile } from './pull-dependencies.ts'
18
19
 
19
- export const MAX_LOCKFILES = 100
20
+ const MAX_LOCKFILES = 100
20
21
  const READ_AT_ONCE = 4
21
22
 
22
23
  export interface CommitLockfiles { lockfiles: { path: string; packages: LockedPackage[] }[]; unread: string[] }
@@ -33,7 +34,7 @@ export async function lockfilesAt(fullName: string, token: string, sha: string,
33
34
  const stored = await kept?.listings.read(sha)
34
35
  if (stored) { listings.set(key, stored); return stored }
35
36
  if (asked) asked.github = true
36
- const { lockfiles } = await upstreamGithub(() => createClient({ token, userAgent: 'deepview-triage' }).findRepoLockfiles({ repo: fullName, sha }))
37
+ const { lockfiles } = await upstreamGithub(() => createClient({ token, userAgent: USER_AGENT }).findRepoLockfiles({ repo: fullName, sha }))
37
38
  const listed = lockfiles.flatMap(({ path, sha: blob }) => { const format = lockfileFormat(path); return format ? [{ path, format, sha: blob }] : [] })
38
39
  listings.set(key, listed)
39
40
  await kept?.listings.write(sha, listed)
@@ -10,13 +10,13 @@
10
10
  // sides' roots differ and none else, as the viewer reads none then. Access is
11
11
  // the caller's to check.
12
12
  import { Buffer } from 'node:buffer'
13
- import { Readable } from 'node:stream'
14
13
  import { prepareComparison } from '../common/bundle-comparison.js'
15
14
  import type { BundleDetails } from '../common/bundle-metadata.js'
16
15
  import type { OpenedBlob } from './blob-store.ts'
17
16
  import { encodeBrotli } from './brotli.ts'
18
17
  import { type NpmPackageFile, type NpmVersionDocument, npmFileRows } from './npm-packages.ts'
19
18
  import type { NpmPatch } from './npm-patch.ts'
19
+ import { opened } from './pretty-print.ts'
20
20
 
21
21
  // A side with no files, as Review compares a package's first version with:
22
22
  // one for each comparison, as working one out keeps its line counts on it.
@@ -38,8 +38,7 @@ export async function comparisonBody(base: BundleDetails, other: BundleDetails,
38
38
  const comparison = prepareComparison(base, other, scope)
39
39
  const { files } = comparison
40
40
  const json = JSON.stringify({ ...comparison, files: { ...files, basePaths: files.root ? [...files.basePaths] : [] } })
41
- const body = await encodeBrotli(Buffer.from(json))
42
- return { size: body.byteLength, stream: Readable.from([body]) }
41
+ return opened(await encodeBrotli(Buffer.from(json)))
43
42
  }
44
43
 
45
44
  // A version's `files` as `patch` changes them (npm-patch.ts patchedFiles), as
@@ -47,6 +46,5 @@ export async function comparisonBody(base: BundleDetails, other: BundleDetails,
47
46
  // patch, as sent: `{ name, version, private, integrity, patch, files }`.
48
47
  export async function patchedVersionBody(doc: NpmVersionDocument, patch: NpmPatch, files: NpmPackageFile[]): Promise<OpenedBlob> {
49
48
  const json = JSON.stringify({ name: doc.name, version: doc.version, private: doc.private, integrity: doc.dist.integrity, patch, files: npmFileRows(files) })
50
- const body = await encodeBrotli(Buffer.from(json))
51
- return { size: body.byteLength, stream: Readable.from([body]) }
49
+ return opened(await encodeBrotli(Buffer.from(json)))
52
50
  }
@@ -7,8 +7,7 @@ import { MAX_UPLOAD_BYTES } from './uploads.ts'
7
7
  import { parseStorageKey } from '../server-common/storage-crypto.ts'
8
8
  import { defaultCacheDir } from '@preventive/upstream/npm.js'
9
9
  import { RESERVED_COOKIES } from './session.ts'
10
-
11
- const LOOPBACK_HOSTS = new Set(['127.0.0.1', '::1', 'localhost'])
10
+ import { LOOPBACK_HOSTS } from '../server-common/origin.ts'
12
11
 
13
12
  export interface ManagedConfig {
14
13
  port: number