@preventive/triage 1.0.0-alpha.53 → 1.0.0-alpha.55

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 (114) hide show
  1. package/common/bundle-compare-diff.js +28 -9
  2. package/common/bundle-compare-inputs.d.ts +1 -0
  3. package/common/bundle-compare-inputs.js +91 -15
  4. package/common/bundle-comparison.js +14 -7
  5. package/common/default-scan-models.ts +3 -0
  6. package/common/dependency-reviews.d.ts +1 -1
  7. package/common/dependency-reviews.js +1 -1
  8. package/common/managed/finding-detail.d.ts +1 -1
  9. package/common/managed/finding-detail.js +7 -7
  10. package/common/managed/routes.js +6 -2
  11. package/common/managed/team-app.d.ts +7 -0
  12. package/common/managed/team-app.js +31 -7
  13. package/common/managed/team-filters.js +26 -0
  14. package/common/workspace-app.js +19 -7
  15. package/out/activity.js +4 -4
  16. package/out/{chunk-NE2UGKRJ.js → chunk-3TFOB75M.js} +4 -3
  17. package/out/chunk-4EMM6UCD.js +1 -0
  18. package/out/chunk-4ISO5F7Y.js +7 -0
  19. package/out/chunk-4XIH7YTX.js +1 -0
  20. package/out/chunk-5PKS6FVK.js +2 -0
  21. package/out/chunk-6GAPL5ZA.js +42 -0
  22. package/out/chunk-6W5BMATD.js +1 -0
  23. package/out/{chunk-WFYLMF6Z.js → chunk-74AEKRES.js} +1 -1
  24. package/out/{chunk-YA4ETCFU.js → chunk-ATTKQVZH.js} +1 -1
  25. package/out/chunk-CGKPGHST.js +6 -0
  26. package/out/chunk-DEVAORP2.js +1 -0
  27. package/out/chunk-E3LFSUDJ.js +9 -0
  28. package/out/chunk-G3LY2FV4.js +1 -0
  29. package/out/chunk-HAZKDK4M.js +4 -0
  30. package/out/chunk-HOB3YPS5.js +1 -0
  31. package/out/{chunk-2K6UN3PC.js → chunk-IZ6MYRYB.js} +1 -1
  32. package/out/{chunk-KOGNQDSJ.js → chunk-J2FWBXFV.js} +1 -1
  33. package/out/{chunk-MYGJBYYJ.js → chunk-J4CLTPOR.js} +1 -1
  34. package/out/chunk-JFL7WLRV.js +1 -0
  35. package/out/chunk-JMG5DXII.js +2 -0
  36. package/out/chunk-JOXLZXMI.js +1 -0
  37. package/out/chunk-M37X4LCF.js +14 -0
  38. package/out/chunk-M3Y6SLC4.js +1 -0
  39. package/out/chunk-NXATZJQ2.js +1 -0
  40. package/out/chunk-PAD2JHZT.js +1 -0
  41. package/out/chunk-PKQBEPZU.js +244 -0
  42. package/out/chunk-PTFQKLKO.js +1 -0
  43. package/out/chunk-QMVOEBWC.js +13 -0
  44. package/out/{chunk-SXV2T5C4.js → chunk-QRKFPLA4.js} +1 -1
  45. package/out/chunk-RRBIJL2B.js +1 -0
  46. package/out/{chunk-GDPCLSOS.js → chunk-SYXT3SFP.js} +1 -1
  47. package/out/chunk-TOXMUOIW.js +5 -0
  48. package/out/chunk-UCP3JRE2.js +1 -0
  49. package/out/chunk-VRX2APNA.js +9 -0
  50. package/out/chunk-WMFDQS2L.js +11 -0
  51. package/out/chunk-WREU7JAG.js +1 -0
  52. package/out/chunk-WST3LUUL.js +1 -0
  53. package/out/{chunk-JEFZTVNX.js → chunk-X655SAHV.js} +1 -1
  54. package/out/chunk-Y5ZHFNBD.js +2 -0
  55. package/out/chunk-YF4M5OCI.js +1 -0
  56. package/out/chunk-Z667U2UJ.js +1 -0
  57. package/out/chunk-ZFXCWNXC.js +52 -0
  58. package/out/chunk-ZQHLECTI.js +1 -0
  59. package/out/client-managed-import.js +1 -1
  60. package/out/client-managed.js +27 -26
  61. package/out/compare.js +14 -14
  62. package/out/dialogs.js +36 -51
  63. package/out/graph.js +17 -15
  64. package/out/index.html +28 -12
  65. package/out/prism.js +1 -1
  66. package/out/scan.js +2 -2
  67. package/out/terminal.js +232 -232
  68. package/out/view.css +1 -1
  69. package/out/view.js +15 -15
  70. package/package.json +12 -7
  71. package/risk/actions/resolve.js +36 -5
  72. package/risk/index.d.ts +20 -2
  73. package/risk/npm/malware.js +6 -4
  74. package/risk/npm/registry.js +8 -6
  75. package/server-managed/bundle-advisories.ts +56 -74
  76. package/server-managed/bundle-build-worker.js +85 -21
  77. package/server-managed/bundle-build.ts +13 -4
  78. package/server-managed/bundle-dependency-reviews.ts +74 -0
  79. package/server-managed/bundle-validation.ts +32 -0
  80. package/server-managed/db-methods.ts +51 -16
  81. package/server-managed/db-neon.ts +18 -2
  82. package/server-managed/db.ts +11 -2
  83. package/server-managed/github-issue-links.ts +151 -47
  84. package/server-managed/github-pulls.ts +34 -15
  85. package/server-managed/http.ts +227 -12
  86. package/server-managed/index.ts +13 -1
  87. package/server-managed/managed-issues.ts +29 -15
  88. package/server-managed/npm-insights.ts +4 -3
  89. package/server-managed/npm-kept.ts +4 -0
  90. package/server-managed/package-entry-points.ts +37 -9
  91. package/server-managed/pretty-print.ts +7 -5
  92. package/server-managed/public-workspace.ts +2 -2
  93. package/server-managed/repository-actions.ts +7 -4
  94. package/server-managed/repository-browser.ts +11 -4
  95. package/server-managed/repository-risk-audit.ts +4 -5
  96. package/server-managed/repository-risk.ts +4 -4
  97. package/server-managed/sql.ts +2 -1
  98. package/server-managed/stasis-config.ts +55 -0
  99. package/server-managed/team-app-summaries.ts +54 -0
  100. package/server-managed/team-app.ts +52 -31
  101. package/server-managed/team-reports.ts +27 -7
  102. package/server-managed/upstream-cache.ts +41 -32
  103. package/server-managed/workspace-shares.ts +3 -1
  104. package/out/chunk-2ZDZWLFY.js +0 -1
  105. package/out/chunk-7VAWINQF.js +0 -6
  106. package/out/chunk-FMXWXDR4.js +0 -36
  107. package/out/chunk-HT2SSA3V.js +0 -1
  108. package/out/chunk-IZ7POWI3.js +0 -18
  109. package/out/chunk-LJ7XRXFU.js +0 -52
  110. package/out/chunk-QB4CBOX2.js +0 -1
  111. package/out/chunk-TQJDYHVE.js +0 -2
  112. package/out/chunk-TSIFIFBX.js +0 -232
  113. package/out/chunk-VH4XMZIW.js +0 -2
  114. package/out/chunk-WYLQWYLA.js +0 -1
@@ -1,26 +1,52 @@
1
- import { type GithubFixResult, githubIssueClosedReason, isGithubRepoName, parseGithubFixUrl } from '../common/github-pr.ts'
1
+ import { type GithubFixResult, githubIssueClosedReason, isGithubRepoName, parseGithubFixUrl, parseGithubIssueUrl } from '../common/github-pr.ts'
2
2
  import type { ManagedConfig } from './config.ts'
3
3
  import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
4
- import type { ManagedIssue } from './managed-issues.ts'
4
+ import type { IssueTracking, ManagedIssue } from './managed-issues.ts'
5
5
  import { ensureUserAccessToken } from './github-oauth.ts'
6
6
  import { lookupFixes } from './github-pulls.ts'
7
7
 
8
- export type IssueFixUpdate = { findingId: string; issueUrl: string; previous: string | null; next: string | null; checkedAt: number }
8
+ export type IssueFixUpdate = { findingId: string; issueUrl: string; previous: IssueTracking; next: IssueTracking; checkedAt: number }
9
9
  type Pull = { number: number; title: string; body: string | null; state: string; isDraft: boolean; createdAt: string;
10
10
  repository: { databaseId: number; nameWithOwner: string } }
11
11
  type Connection = { nodes: Pull[]; pageInfo: { hasNextPage: boolean; endCursor: string | null } }
12
- type Issue = { number: number; title: string; body: string | null; state: string; stateReason: string | null; closedByPullRequestsReferences?: Connection }
12
+ type RepositoryReference = { databaseId?: unknown; nameWithOwner?: unknown } | null | undefined
13
+ type IssueReference = { number?: unknown; repository?: RepositoryReference }
14
+ type Issue = { number: number; title: string; body: string | null; state: string; stateReason: string | null; closedByPullRequestsReferences?: Connection
15
+ duplicateOf?: IssueReference | null }
13
16
  type Repository = TeamReportAccessSnapshot['repositories'][number]
17
+ // The issue a linked one was closed as a duplicate of, in a workspace
18
+ // repository: null for none (or one outside them, never followed or
19
+ // disclosed, as a pull request outside them isn't).
20
+ type Duplicate = { repo: Repository; number: number } | null
21
+ // `duplicateOf` is a linked issue's, from its last page read: undefined while
22
+ // none is, or where GitHub refused the reference.
14
23
  type Job = { repo: Repository; kind: 'pull' | 'issue'; number: number; aliases: string[];
15
- linked: boolean; cursor: string | null; pulls: Pull[]; complete: boolean }
24
+ linked: boolean; cursor: string | null; pulls: Pull[]; complete: boolean; duplicateOf?: Duplicate | undefined }
16
25
  type Metadata = Exclude<GithubFixResult, { error: string }>
17
26
  const pullFields = 'number title body state isDraft createdAt repository { databaseId nameWithOwner }'
27
+ // A linked issue's: the issue it was closed as a duplicate of, and a page of
28
+ // the pull requests linked to it.
29
+ const linkedFields = (cursor: string | null) => 'duplicateOf { number repository { databaseId nameWithOwner } } '
30
+ + `closedByPullRequestsReferences(first: 100, includeClosedPrs: true, after: ${JSON.stringify(cursor)}) { nodes { ${pullFields} } pageInfo { hasNextPage endCursor } }`
31
+ // How many issues a saved one is followed through, each closed as a
32
+ // duplicate of the next: each is another request after the last.
33
+ const MAX_DUPLICATE_HOPS = 5
34
+ const jobKey = (repoId: number, kind: Job['kind'], number: number) => `${repoId}:${kind}:${number}`
35
+ const issueUrlOf = (repo: Repository, number: number) => `https://github.com/${repo.github}/issues/${number}`
36
+ // Whether GitHub named a repository as one is: by its stable ID and a name.
37
+ const isRepositoryReference = (ref: RepositoryReference): ref is { databaseId: number; nameWithOwner: string } =>
38
+ Number.isSafeInteger(ref?.databaseId) && typeof ref?.nameWithOwner === 'string' && isGithubRepoName(ref.nameWithOwner)
39
+ // The workspace repository GitHub named, matching its name and stable ID
40
+ // both; none for one outside the workspace repository grants.
41
+ const workspaceRepository = (ref: { databaseId: number; nameWithOwner: string }, allowed: Map<string, Repository>) => {
42
+ const repo = allowed.get(ref.nameWithOwner.toLowerCase())
43
+ return repo?.repoId === ref.databaseId ? repo : null
44
+ }
18
45
 
19
46
  function metadataQuery(jobs: Job[]) {
20
47
  return `{ ${jobs.map((job, index) => {
21
48
  const [owner, name] = job.repo.github.split('/')
22
- const fields = job.kind === 'pull' ? pullFields : `number title body state stateReason ${job.linked
23
- ? `closedByPullRequestsReferences(first: 100, includeClosedPrs: true, after: ${JSON.stringify(job.cursor)}) { nodes { ${pullFields} } pageInfo { hasNextPage endCursor } }` : ''}`
49
+ const fields = job.kind === 'pull' ? pullFields : `number title body state stateReason ${job.linked ? linkedFields(job.cursor) : ''}`
24
50
  return `r${index}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { databaseId nameWithOwner item: ${job.kind === 'pull' ? 'pullRequest' : 'issue'}(number: ${job.number}) { ${fields} } }`
25
51
  }).join('\n')} }`
26
52
  }
@@ -33,16 +59,32 @@ function itemMetadata(item: Issue | Pull, kind: Job['kind']): Omit<Metadata, 'ur
33
59
  return { title: item.title, description: item.body ?? null, status, stateReason }
34
60
  }
35
61
 
36
- function readPage(job: Job, item: Issue | Pull, metadata: Map<string, Metadata>): boolean {
62
+ // The issue `issue` was closed as a duplicate of, where GitHub names one
63
+ // (Duplicate); undefined for a reference it gave malformed.
64
+ function duplicateOf(issue: Issue, allowed: Map<string, Repository>): Duplicate | undefined {
65
+ if (issue.state !== 'CLOSED' || issue.stateReason !== 'DUPLICATE' || issue.duplicateOf == null) return null
66
+ const { number, repository } = issue.duplicateOf
67
+ if (!Number.isSafeInteger(number) || (number as number) <= 0 || !isRepositoryReference(repository)) return undefined
68
+ const repo = workspaceRepository(repository, allowed)
69
+ return repo ? { repo, number: number as number } : null
70
+ }
71
+
72
+ // `refused`: GitHub answered with an error on the issue's duplicate alone,
73
+ // which, like a malformed one, leaves it shown but what it redirects to
74
+ // unknown.
75
+ function readPage(job: Job, item: Issue | Pull, metadata: Map<string, Metadata>, allowed: Map<string, Repository>, refused: boolean): boolean {
37
76
  const details = itemMetadata(item, job.kind)
38
77
  if (!details || item.number !== job.number) return false
39
78
  for (const url of job.aliases) metadata.set(url, { url, ...details })
40
79
  if (!job.linked) return false
80
+ const duplicate = refused ? undefined : duplicateOf(item as Issue, allowed)
81
+ if (duplicate === undefined) return false
41
82
  const connection = (item as Issue).closedByPullRequestsReferences
42
83
  if (!connection || !Array.isArray(connection.nodes) || typeof connection.pageInfo?.hasNextPage !== 'boolean'
43
84
  || connection.nodes.some(pr => !pr || !Number.isSafeInteger(pr.number) || pr.number <= 0 || typeof pr.createdAt !== 'string'
44
85
  || !Number.isFinite(Date.parse(pr.createdAt)) || !itemMetadata(pr, 'pull') || typeof pr.isDraft !== 'boolean'
45
- || !Number.isSafeInteger(pr.repository?.databaseId) || typeof pr.repository?.nameWithOwner !== 'string' || !isGithubRepoName(pr.repository.nameWithOwner))) return false
86
+ || !isRepositoryReference(pr.repository))) return false
87
+ job.duplicateOf = duplicate
46
88
  job.pulls.push(...connection.nodes)
47
89
  if (!connection.pageInfo.hasNextPage) { job.complete = true; return false }
48
90
  if (typeof connection.pageInfo.endCursor !== 'string' || !connection.pageInfo.endCursor || connection.pageInfo.endCursor === job.cursor) return false
@@ -50,43 +92,89 @@ function readPage(job: Job, item: Issue | Pull, metadata: Map<string, Metadata>)
50
92
  return true
51
93
  }
52
94
 
53
- function issueUpdates(jobs: Job[], issues: ManagedIssue[], allowed: Map<string, Repository>, checkedAt: number, metadata: Map<string, Metadata>) {
54
- const updates: IssueFixUpdate[] = []
55
- // The issues each job's issue is, by repository and number, read once.
56
- const byIssue = new Map<string, ManagedIssue[]>()
57
- for (const issue of issues) {
58
- const ref = parseGithubFixUrl(issue.issueUrl)
59
- if (ref?.kind !== 'issue') continue
60
- const key = `${issue.repoId}:${ref.number}`, same = byIssue.get(key)
61
- if (same) same.push(issue)
62
- else byIssue.set(key, [issue])
95
+ // A saved issue's job, then those of the issues it was closed as a duplicate
96
+ // of in turn, as far as this lookup has read them, a redirect followed rather
97
+ // than the saved issue replaced. `next` is null where the last names none
98
+ // further to follow (or one already in the chain, or past
99
+ // MAX_DUPLICATE_HOPS); the one it names where this lookup has no linked job
100
+ // for it; undefined where one is yet unread, or what it names unknown.
101
+ function duplicateChain(root: Job, jobs: Map<string, Job>): { chain: Job[]; next: Duplicate | undefined } {
102
+ const chain = [root]
103
+ for (let job = root; ;) {
104
+ const target = job.duplicateOf
105
+ if (!target || chain.length > MAX_DUPLICATE_HOPS) return { chain, next: target && null }
106
+ const next = jobs.get(jobKey(target.repo.repoId, 'issue', target.number))
107
+ if (next && chain.includes(next)) return { chain, next: null }
108
+ if (!next?.linked) return { chain, next: target }
109
+ chain.push(job = next)
63
110
  }
64
- for (const job of jobs) {
65
- if (!job.linked || !job.complete) continue
111
+ }
112
+
113
+ // The issues saved ones were closed as duplicates of, which this lookup has
114
+ // yet to read with their linked pull requests: each made a linked job, as a
115
+ // saved issue's own is (one read without them never read further).
116
+ function duplicateJobs(jobs: Map<string, Job>, roots: Iterable<string>): Job[] {
117
+ const found: Job[] = []
118
+ for (const key of roots) {
119
+ const root = jobs.get(key)
120
+ const next = root && duplicateChain(root, jobs).next
121
+ if (!next) continue
122
+ const nextKey = jobKey(next.repo.repoId, 'issue', next.number), url = issueUrlOf(next.repo, next.number)
123
+ let job = jobs.get(nextKey)
124
+ if (!job) jobs.set(nextKey, job = { repo: next.repo, kind: 'issue', number: next.number, aliases: [], linked: true, cursor: null, pulls: [], complete: false })
125
+ job.linked = true
126
+ if (!job.aliases.includes(url)) job.aliases.push(url)
127
+ found.push(job)
128
+ }
129
+ return found
130
+ }
131
+
132
+ // `byIssue`: the saved issues each job's issue is, by its key.
133
+ function issueUpdates(jobs: Map<string, Job>, byIssue: Map<string, ManagedIssue[]>, allowed: Map<string, Repository>, checkedAt: number, metadata: Map<string, Metadata>) {
134
+ const updates: IssueFixUpdate[] = []
135
+ for (const [key, saved] of byIssue) {
136
+ const root = jobs.get(key)
137
+ if (!root?.linked) continue
138
+ // The saved issue and every one it was closed as a duplicate of in turn,
139
+ // each read whole: the last is tracked, and the pull requests of all.
140
+ const { chain, next } = duplicateChain(root, jobs)
141
+ if (next !== null || !chain.every(job => job.complete)) continue
66
142
  // "Last" means the newest PR by creation time, never its latest comment.
67
- const latest = job.pulls.filter(pr => pr.state !== 'CLOSED').toSorted((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt) || b.number - a.number)[0]
68
- const repo = latest && allowed.get(latest.repository.nameWithOwner.toLowerCase())
143
+ const latest = chain.flatMap(job => job.pulls).filter(pr => pr.state !== 'CLOSED')
144
+ .toSorted((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt) || b.number - a.number)[0]
145
+ const repo = latest && workspaceRepository(latest.repository, allowed)
69
146
  // The viewer's token can have broader access than this workspace. Never
70
- // persist or disclose a PR from outside the workspace repository grants.
71
- if (latest && (!repo || repo.repoId !== latest.repository.databaseId)) continue
72
- const next = latest ? `https://github.com/${repo!.github}/pull/${latest.number}` : null
73
- if (latest && next) metadata.set(next, { url: next, ...itemMetadata(latest, 'pull')! })
74
- // Only a changed derived Fix is written: an unchanged one's check time
75
- // alone would bump the annotations revision that every open team feed
76
- // polls, for nothing they show. Changes still stamp it, so an older lookup
77
- // never replaces a newer change (managed-issues.ts). An older lookup that
78
- // differs can now land after a newer unchanged one, as it could already
79
- // land before it (whose compare-and-set then fails); either way the next
80
- // lookup finds the stored Fix differs, and writes the current one.
81
- for (const issue of byIssue.get(`${job.repo.repoId}:${job.number}`) ?? []) {
82
- if (issue.autoFixUrl !== next) updates.push({ findingId: issue.findingId, issueUrl: issue.issueUrl!, previous: issue.autoFixUrl, next, checkedAt })
147
+ // persist or disclose a PR from outside the workspace repository grants:
148
+ // where the newest is one, the saved Fix stays. The duplicate, checked
149
+ // against the grants itself, is saved all the same.
150
+ const foreign = Boolean(latest && !repo)
151
+ const autoFix = latest && repo ? `https://github.com/${repo.github}/pull/${latest.number}` : null
152
+ if (latest && autoFix) metadata.set(autoFix, { url: autoFix, ...itemMetadata(latest, 'pull')! })
153
+ const last = chain.at(-1)!
154
+ const duplicate = chain.length > 1 ? issueUrlOf(last.repo, last.number) : null
155
+ // Only a changed derived Fix or duplicate is written: an unchanged one's
156
+ // check time alone would bump the annotations revision that every open
157
+ // team feed polls, for nothing they show. Changes still stamp it, so an
158
+ // older lookup never replaces a newer change (managed-issues.ts). An older
159
+ // lookup that differs can now land after a newer unchanged one, as it
160
+ // could already land before it (whose compare-and-set then fails); either
161
+ // way the next lookup finds the stored values differ, and writes the
162
+ // current ones.
163
+ for (const issue of saved) {
164
+ const tracking = { autoFix: foreign ? issue.autoFixUrl : autoFix, duplicateOf: duplicate }
165
+ if (issue.autoFixUrl !== tracking.autoFix || issue.duplicateOfUrl !== tracking.duplicateOf) {
166
+ updates.push({ findingId: issue.findingId, issueUrl: issue.issueUrl!, checkedAt,
167
+ previous: { autoFix: issue.autoFixUrl, duplicateOf: issue.duplicateOfUrl }, next: tracking })
168
+ }
83
169
  }
84
170
  }
85
171
  return updates
86
172
  }
87
173
 
88
174
  // Fetch issue details, linked PR states and manual Fix metadata in one batch.
89
- // Pagination and workspaces with over 200 distinct links need further batches.
175
+ // Pagination, workspaces with over 200 distinct links, and issues closed as a
176
+ // duplicate of one not yet read need further batches. A duplicate saved last
177
+ // time is read in the first, as a redirect kept is: its URL among `urls`.
90
178
  // Live GraphQL results prove this viewer's access; never publish them into the
91
179
  // REST shared cache under an older public-visibility grant.
92
180
  export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, snapshot: TeamReportAccessSnapshot,
@@ -94,14 +182,22 @@ export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, sna
94
182
  const checkedAt = Date.now(), signal = AbortSignal.timeout(10_000)
95
183
  const allowed = new Map(snapshot.repositories.filter(repo => isGithubRepoName(repo.github)).map(repo => [repo.github.toLowerCase(), repo]))
96
184
  const jobs = new Map<string, Job>()
97
- const linked = new Set(issues.filter(issue => issue.issueUrl).map(issue => {
98
- const ref = parseGithubFixUrl(issue.issueUrl)
99
- return ref?.kind === 'issue' ? `${issue.repoId}:issue:${ref.number}` : ''
100
- }))
185
+ // The saved issues by their issue's key, and the issues read with their
186
+ // linked pull requests: theirs, and the duplicates they were saved with.
187
+ const byIssue = new Map<string, ManagedIssue[]>(), linked = new Set<string>()
188
+ for (const issue of issues) {
189
+ const ref = parseGithubIssueUrl(issue.issueUrl)
190
+ if (!ref) continue
191
+ const key = jobKey(issue.repoId, 'issue', ref.number)
192
+ byIssue.set(key, [...byIssue.get(key) ?? [], issue])
193
+ linked.add(key)
194
+ const duplicate = parseGithubIssueUrl(issue.duplicateOfUrl), repo = duplicate && allowed.get(duplicate.repo.toLowerCase())
195
+ if (duplicate && repo) linked.add(jobKey(repo.repoId, 'issue', duplicate.number))
196
+ }
101
197
  for (const url of urls) {
102
198
  const ref = parseGithubFixUrl(url), repo = ref && allowed.get(ref.repo.toLowerCase())
103
199
  if (!ref || !repo) continue
104
- const key = `${repo.repoId}:${ref.kind}:${ref.number}`, previous = jobs.get(key)
200
+ const key = jobKey(repo.repoId, ref.kind, ref.number), previous = jobs.get(key)
105
201
  if (previous) { previous.aliases.push(url); continue }
106
202
  jobs.set(key, { repo, kind: ref.kind, number: ref.number, aliases: [url], linked: linked.has(key), cursor: null, pulls: [], complete: false })
107
203
  }
@@ -109,11 +205,12 @@ export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, sna
109
205
  const withinDeadline: typeof fetch = (input, init) => { signal.throwIfAborted(); return fetchImpl(input, { ...init, signal }) }
110
206
  const token = await ensureUserAccessToken(config, db, snapshot.user.id, checkedAt, withinDeadline)
111
207
  if (!token) return { fixes: await lookupFixes(config, db, snapshot, urls, withinDeadline), updates: [] }
112
- const metadata = new Map<string, Metadata>(), selected = [...jobs.values()]
113
- let pending = selected
208
+ const metadata = new Map<string, Metadata>()
209
+ let pending = [...jobs.values()]
114
210
  for (let page = 0; pending.length > 0 && page < 100 && !signal.aborted; page++) {
115
211
  const batch = pending.slice(0, 200), query = metadataQuery(batch)
116
212
  let data: Record<string, { databaseId: number; nameWithOwner: string; item: Issue | Pull } | null>
213
+ const refused = new Set<string>()
117
214
  try {
118
215
  const response = await withinDeadline('https://api.github.com/graphql', {
119
216
  method: 'POST', redirect: 'error',
@@ -123,18 +220,25 @@ export async function lookupIssueLinks(config: ManagedConfig, db: ManagedDb, sna
123
220
  const body = await response.json() as { data?: typeof data; errors?: { path?: unknown[] }[] }
124
221
  // Errors attached to an alias invalidate that whole job, including its
125
222
  // connection. Other aliases can succeed even if one issue was deleted.
223
+ // One on the issue it duplicates alone, which the viewer may be unable
224
+ // to read, leaves its status, and only what it redirects to unknown.
126
225
  if (!body?.data || body.errors != null && (!Array.isArray(body.errors)
127
226
  || body.errors.some(error => typeof error?.path?.[0] !== 'string' || !/^r\d+$/u.test(error.path[0])))) break
128
227
  data = body.data
129
- for (const error of body.errors ?? []) data[error.path![0] as string] = null
228
+ for (const error of body.errors ?? []) {
229
+ const [alias, field, reference] = error.path! as string[]
230
+ if (field === 'item' && reference === 'duplicateOf') refused.add(alias!)
231
+ else data[alias!] = null
232
+ }
130
233
  } catch { break }
131
234
  pending = pending.slice(batch.length)
132
235
  for (const [index, job] of batch.entries()) {
133
236
  const repository = data[`r${index}`]
134
237
  if (repository?.databaseId !== job.repo.repoId || typeof repository.nameWithOwner !== 'string' || repository.nameWithOwner.toLowerCase() !== job.repo.github.toLowerCase()) continue
135
- if (readPage(job, repository.item, metadata)) pending.push(job)
238
+ if (readPage(job, repository.item, metadata, allowed, refused.has(`r${index}`))) pending.push(job)
136
239
  }
240
+ for (const job of duplicateJobs(jobs, byIssue.keys())) if (!pending.includes(job)) pending.push(job)
137
241
  }
138
- const updates = issueUpdates(selected, issues, allowed, checkedAt, metadata)
242
+ const updates = issueUpdates(jobs, byIssue, allowed, checkedAt, metadata)
139
243
  return { fixes: [...metadata.values()], updates }
140
244
  }
@@ -6,6 +6,9 @@ import { ensureUserAccessToken } from './github-oauth.ts'
6
6
 
7
7
  type Metadata = Pick<GithubMetadata, 'title' | 'description' | 'status' | 'stateReason'>
8
8
  const MAX_GITHUB_LOOKUPS = 200
9
+ // A load reading this many open or unknown items anew also rechecks one closed
10
+ // item, rounded up (lookupFixes).
11
+ const CLOSED_RECHECK_EVERY = 10
9
12
  const GITHUB_LOOKUP_TIMEOUT_MS = 10_000
10
13
  const GITHUB_METADATA_TTL_MS = 60_000
11
14
  const GITHUB_PUBLIC_VISIBILITY_TTL_MS = 60_000
@@ -132,6 +135,32 @@ async function fetchMetadata(ref: GithubFixRef, token: string | null, fetchImpl:
132
135
  } catch { return null }
133
136
  }
134
137
 
138
+ // What a load reads of its `entries`, by what is cached of them at `now`:
139
+ // those missing or stale, the least recently checked first, as many as
140
+ // MAX_GITHUB_LOOKUPS. Closed items are kept once fetched, but GitHub can
141
+ // reopen them (merged ones are final): a load reading open or unknown items
142
+ // anew also rechecks a tenth as many closed ones, the least recently checked
143
+ // first, after them. None where every item is closed or fresh, and a busy
144
+ // workspace cycles through its closed items, a recheck rotating its item
145
+ // behind the others whether or not GitHub answers.
146
+ function readsOf<Entry extends [string, GithubFixRef]>(entries: Entry[], metadata: Map<string, GithubMetadata>, now: number): Entry[] {
147
+ const lastCheckedAt = ([key]: Entry) => Math.max(metadata.get(key)?.fetchedAt ?? 0, metadata.get(key)?.attemptedAt ?? 0)
148
+ const oldestFirst = (a: Entry, b: Entry) => lastCheckedAt(a) - lastCheckedAt(b)
149
+ const stale = ([key, ref]: Entry) => {
150
+ const cached = metadata.get(key)
151
+ // Backfill closed issues cached before closure reasons existed, within the
152
+ // same authorized/capped queue. Even an unknown reason completes backfill.
153
+ return !cached || (ref.kind === 'issue' && cached.status === 'closed' && cached.stateReason == null)
154
+ || (['open', 'draft'].includes(cached.status) && cached.fetchedAt + GITHUB_METADATA_TTL_MS <= now)
155
+ }
156
+ const pending = entries.filter(stale).toSorted(oldestFirst).slice(0, MAX_GITHUB_LOOKUPS)
157
+ // Stale ones are missing, open, draft, or closed issues awaiting backfill.
158
+ const reread = pending.filter(([key]) => metadata.get(key)?.status !== 'closed').length
159
+ const rechecks = entries.filter(entry => metadata.get(entry[0])?.status === 'closed' && !stale(entry))
160
+ .toSorted(oldestFirst).slice(0, Math.ceil(reread / CLOSED_RECHECK_EVERY))
161
+ return [...pending, ...rechecks]
162
+ }
163
+
135
164
  // The workspace handler checks user -> team membership and finding visibility.
136
165
  // Shared private metadata also requires this viewer's live GitHub access,
137
166
  // including for admins. Only recently verified public repos skip that check.
@@ -169,27 +198,17 @@ export async function lookupFixes(config: ManagedConfig, db: ManagedDb, snapshot
169
198
  const readable = await readableRepositories(repositories, context)
170
199
  const authorized = [...jobs.entries()].filter(([, ref]) => readable.has(ref.repo))
171
200
  const metadata = new Map((await db.listGithubMetadata(authorized.map(([key]) => key))).map(entry => [entry.key, entry]))
172
- const lastCheckedAt = (key: string) => {
173
- const cached = metadata.get(key)
174
- return Math.max(cached?.fetchedAt ?? 0, cached?.attemptedAt ?? 0)
175
- }
176
- const pending = authorized.filter(([key, ref]) => {
177
- const cached = metadata.get(key)
178
- // Backfill closed issues cached before closure reasons existed, within the
179
- // same authorized/capped queue. Even an unknown reason completes backfill.
180
- return !cached || (ref.kind === 'issue' && cached.status === 'closed' && cached.stateReason == null)
181
- || (['open', 'draft'].includes(cached.status) && cached.fetchedAt + GITHUB_METADATA_TTL_MS <= now)
182
- }).toSorted(([a], [b]) => lastCheckedAt(a) - lastCheckedAt(b)).slice(0, MAX_GITHUB_LOOKUPS)
201
+ const reads = readsOf(authorized, metadata, now)
183
202
  // Only stale/missing, distinct, authorized entries consume the request budget.
184
203
  // Prioritize missing/oldest entries so a large workspace makes progress.
185
- if (pending.length > 0) {
186
- const publicRefreshes = new Set(pending.filter(([, ref]) => publicRepos.has(ref.repo) && !checks.verified.has(ref.repo)).map(([, ref]) => ref.repo))
204
+ if (reads.length > 0) {
205
+ const publicRefreshes = new Set(reads.filter(([, ref]) => publicRepos.has(ref.repo) && !checks.verified.has(ref.repo)).map(([, ref]) => ref.repo))
187
206
  if (publicRefreshes.size > 0) token = await verifyPublicRefreshes(config, snapshot.user.id, repositories.filter(repo => publicRefreshes.has(repo.github)), context)
188
207
  const fresh: Omit<GithubMetadata, 'attemptedAt'>[] = []
189
208
  const attempted: string[] = []
190
209
  // All waves and access checks share one deadline and four-call limit.
191
- for (let i = 0; i < pending.length && !signal.aborted; i += 4) {
192
- await Promise.all(pending.slice(i, i + 4).map(async ([key, ref]) => {
210
+ for (let i = 0; i < reads.length && !signal.aborted; i += 4) {
211
+ await Promise.all(reads.slice(i, i + 4).map(async ([key, ref]) => {
193
212
  if (signal.aborted) return
194
213
  if (metadata.has(key)) attempted.push(key)
195
214
  const result = await fetchMetadata(ref, publicRepos.has(ref.repo) && !checks.verified.has(ref.repo) ? null : token, fetchWithinDeadline)