@oss-autopilot/core 3.39.0 → 3.39.2

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.
@@ -16,8 +16,10 @@
16
16
  * emoji-only reactions do not, except that a bare status request on a
17
17
  * claimed issue is addressed to the claimant and counts. Engaged issues
18
18
  * the comment search does not return (the user never commented, or not
19
- * within the window) are fetched directly, up to
20
- * {@link MAX_DIRECT_ENGAGED_FETCHES} per run.
19
+ * within the window) are looked up in batched GraphQL queries, and the
20
+ * ones still open and updated since the engagement have their comments
21
+ * read directly, up to {@link MAX_DIRECT_ENGAGED_FETCHES} per run, most
22
+ * recently updated first.
21
23
  */
22
24
  import { getOctokit } from './github.js';
23
25
  import { isBotAuthor, isAcknowledgmentComment, isReactionOnlyComment, isQuoteReplyTo, isStatusNudge, } from './comment-utils.js';
@@ -28,18 +30,22 @@ import { daysBetween } from './dates.js';
28
30
  import { splitRepo, extractOwnerRepo, isOwnRepo, parseGitHubUrl, issueRefKey } from './urls.js';
29
31
  import { runWorkerPool, DEFAULT_CONCURRENCY } from './concurrency.js';
30
32
  import { toIssueEngagement } from './engaged-issues.js';
33
+ import { lookupEngagedIssues, } from './engaged-issue-lookup.js';
31
34
  import { ConfigurationError, ValidationError, errorMessage, getHttpStatusCode, isRateLimitOrAuthError, } from './errors.js';
32
35
  import { debug, warn } from './logger.js';
33
36
  const MODULE = 'issue-conversation';
34
37
  const MAX_CONCURRENT_REQUESTS = DEFAULT_CONCURRENCY;
35
38
  /**
36
- * Most engaged issues fetched directly per run when the comment search
37
- * misses them (#1862). Each costs one issue lookup plus its comment pages,
38
- * all ETag-cached, so a quiet day is mostly 304s; the cap bounds a first run
39
- * for a user with many open claims. Strongest engagements come first, so
40
- * the open-PR and claim issues are the ones kept.
39
+ * Most engaged issues whose comments are read directly per run when the
40
+ * comment search misses them (#1862). Only issues the batched lookup found
41
+ * open and updated since the engagement count; each costs its comment pages,
42
+ * ETag-cached, so a quiet day is mostly 304s. The cap bounds a first run for
43
+ * a user with many active claims. Most recently updated issues come first,
44
+ * so an issue that gets a new comment moves to the front on the next run,
45
+ * but one that stays quiet behind a hundred busier ones is not read until
46
+ * the busier ones settle. That is why hitting the cap is a warning.
41
47
  */
42
- export const MAX_DIRECT_ENGAGED_FETCHES = 25;
48
+ export const MAX_DIRECT_ENGAGED_FETCHES = 100;
43
49
  /** Associations that indicate someone with repo-level permissions. */
44
50
  const MAINTAINER_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
45
51
  function parseMs(value) {
@@ -51,15 +57,15 @@ function parseMs(value) {
51
57
  function excerpt(body) {
52
58
  return body.slice(0, 200) + (body.length > 200 ? '...' : '');
53
59
  }
60
+ /** The label names on a looked-up issue node; GitHub may return null entries. */
61
+ function labelNames(node) {
62
+ const labelNodes = node.labels?.nodes ?? [];
63
+ return labelNodes.filter((label) => label !== null).map((label) => label.name);
64
+ }
54
65
  function describeError(error) {
55
66
  const status = getHttpStatusCode(error);
56
67
  return status === undefined ? errorMessage(error) : `HTTP ${status}: ${errorMessage(error)}`;
57
68
  }
58
- /** 404/410: the issue is gone (deleted, transferred, or now private). */
59
- function isGoneError(error) {
60
- const status = getHttpStatusCode(error);
61
- return status === 404 || status === 410;
62
- }
63
69
  /**
64
70
  * Whether a gone engaged issue is worth a warning: a claim or an open PR
65
71
  * still points at it and the user can release the claim or fix the PR's
@@ -117,7 +123,8 @@ export class IssueConversationMonitor {
117
123
  const cutoffDate = new Date();
118
124
  cutoffDate.setDate(cutoffDate.getDate() - maxDays);
119
125
  const since = cutoffDate.toISOString().split('T', 1)[0];
120
- const warnings = [];
126
+ const report = { warnings: [], failures: [] };
127
+ const { warnings, failures } = report;
121
128
  debug(MODULE, `Fetching commented issues for @${username} (last ${maxDays} days)...`);
122
129
  // Search for open issues the user has commented on, updated within window
123
130
  // Single page (100) is sufficient for most users; log if truncated.
@@ -134,6 +141,7 @@ export class IssueConversationMonitor {
134
141
  // Also parse repo info for each candidate to avoid re-parsing in analyzeIssueConversation.
135
142
  const candidates = [];
136
143
  const seenKeys = new Set();
144
+ const searchCandidates = new Map();
137
145
  for (const item of data.items) {
138
146
  // Defensive: skip pull requests in case type:issue qualifier is unreliable
139
147
  if (item.pull_request)
@@ -151,7 +159,9 @@ export class IssueConversationMonitor {
151
159
  continue;
152
160
  if (!this.isRepoAllowed(repoFullName, config))
153
161
  continue;
154
- candidates.push({ item, repoFullName, engagement: engaged.get(key), url: item.html_url, number: item.number });
162
+ const candidate = { item, repoFullName, engagement: engaged.get(key), url: item.html_url };
163
+ candidates.push(candidate);
164
+ searchCandidates.set(key, candidate);
155
165
  }
156
166
  // Live engaged issues the search did not return are looked up directly.
157
167
  const missing = [];
@@ -163,33 +173,17 @@ export class IssueConversationMonitor {
163
173
  continue;
164
174
  missing.push(entry);
165
175
  }
166
- // `engaged` iterates strongest reason first (open PR, claim, then closed
167
- // and merged links), so the cap drops finished-PR links before claims.
168
- const skipped = missing.slice(MAX_DIRECT_ENGAGED_FETCHES);
169
- if (skipped.length > 0) {
170
- warnings.push(`${skipped.length} engaged issue${skipped.length === 1 ? '' : 's'} missing from the comment search ${skipped.length === 1 ? 'was' : 'were'} not fetched this run (cap of ${MAX_DIRECT_ENGAGED_FETCHES} direct lookups; open-PR and claimed issues come first), so replies there may be missed: ${skipped.map((e) => e.url).join(', ')}`);
171
- }
172
- for (const entry of missing.slice(0, MAX_DIRECT_ENGAGED_FETCHES)) {
173
- const parsed = parseGitHubUrl(entry.url);
174
- if (!parsed)
175
- continue;
176
- candidates.push({
177
- url: entry.url,
178
- repoFullName: `${parsed.owner}/${parsed.repo}`,
179
- number: parsed.number,
180
- engagement: entry,
181
- });
182
- }
176
+ const context = { username, config, cutoffDate, seenKeys, searchCandidates, report };
177
+ candidates.push(...(await this.collectDirectCandidates(missing, context)));
178
+ // Lookup failures are already in `failures`; the analysis tallies below
179
+ // count only the candidates the pool analyzed.
180
+ const lookupFailures = failures.length;
183
181
  debug(MODULE, `Found ${candidates.length} commented issues to check`);
184
182
  // Fetch comments for each issue using worker pool.
185
183
  const results = [];
186
- const failures = [];
187
184
  await runWorkerPool(candidates, async (candidate) => {
188
185
  try {
189
- const item = candidate.item ?? (await this.fetchEngagedIssue(candidate, username, cutoffDate));
190
- if (!item)
191
- return;
192
- const issue = await this.analyzeIssueConversation(item, candidate.repoFullName, username, candidate.engagement, warnings);
186
+ const issue = await this.analyzeIssueConversation(candidate.item, candidate.repoFullName, username, candidate.engagement, warnings);
193
187
  if (issue) {
194
188
  results.push(issue);
195
189
  return;
@@ -211,27 +205,19 @@ export class IssueConversationMonitor {
211
205
  // aborting the run just like PRMonitor's 429s do.
212
206
  if (isRateLimitOrAuthError(error))
213
207
  throw error;
214
- if (candidate.item === undefined && isGoneError(error)) {
215
- // Only a direct fetch can see a 404/410: the issue was deleted,
216
- // transferred, or made private since the PR or claim linked it.
217
- // Worth telling the user only while something of theirs still
218
- // points at it (a claim to release, an open PR's closing link).
219
- const message = `${candidate.url}: issue no longer reachable (${describeError(error)}); dropped`;
220
- if (isActionableEngagement(candidate.engagement))
221
- warnings.push(message);
222
- else
223
- debug(MODULE, message);
224
- return;
225
- }
226
208
  const msg = describeError(error);
227
209
  failures.push({ issueUrl: candidate.url, error: msg });
228
210
  warn(MODULE, `Error analyzing issue ${candidate.url}: ${msg}`);
229
211
  }
230
212
  }, MAX_CONCURRENT_REQUESTS);
231
- if (failures.length > 0) {
232
- warn(MODULE, `${failures.length}/${candidates.length} issue analysis call(s) failed`);
213
+ const analysisFailures = failures.length - lookupFailures;
214
+ if (lookupFailures > 0) {
215
+ warn(MODULE, `${lookupFailures} engaged issue lookup(s) failed`);
216
+ }
217
+ if (analysisFailures > 0) {
218
+ warn(MODULE, `${analysisFailures}/${candidates.length} issue analysis call(s) failed`);
233
219
  }
234
- if (failures.length === candidates.length && candidates.length > 0) {
220
+ if (analysisFailures === candidates.length && candidates.length > 0) {
235
221
  warn(MODULE, `All ${candidates.length} issue analysis call(s) failed. Possible systemic issue (network, GitHub availability).`);
236
222
  }
237
223
  for (const message of warnings)
@@ -244,7 +230,7 @@ export class IssueConversationMonitor {
244
230
  };
245
231
  results.sort((a, b) => statusOrder[a.status] - statusOrder[b.status]);
246
232
  debug(MODULE, `Analyzed ${results.length} issue conversations (${results.filter((i) => i.status === 'new_response').length} with new responses)`);
247
- return { issues: results, failures, warnings };
233
+ return { failures, lookupFailures, warnings, issues: results };
248
234
  }
249
235
  /** Repo-level exclusions shared by the search results and the direct fetches. */
250
236
  isRepoAllowed(repoFullName, config) {
@@ -260,33 +246,129 @@ export class IssueConversationMonitor {
260
246
  return !blocklist.includes(repoFullName.toLowerCase());
261
247
  }
262
248
  /**
263
- * Look up an engaged issue the comment search did not return (#1862).
264
- * Returns undefined, with a debug line, when the number is a pull request,
265
- * the issue is closed, the user authored it, or nothing on it changed
266
- * since the later of the search window's start and the engagement step.
267
- * The window keeps this path consistent with the commenter search (a
268
- * reply older than `maxDays` is not surfaced either way); the engagement
269
- * step tightens it because only comments after that step can be replies
270
- * to the user, so an issue untouched since then has nothing to report.
271
- * ETag-cached like the comment pages. Errors propagate to the worker.
249
+ * Candidates for the engaged issues the comment search did not return
250
+ * (#1862): one batched GraphQL lookup for all of them, then the issues
251
+ * still open, not the user's own, and updated since the later of the
252
+ * search window's start and the engagement step, most recently updated
253
+ * first, up to {@link MAX_DIRECT_ENGAGED_FETCHES}. The window keeps this
254
+ * path consistent with the commenter search (a reply older than `maxDays`
255
+ * is not surfaced either way); the engagement step tightens it because
256
+ * only comments after that step can be replies to the user. The issues
257
+ * past the cap are named in a warning: the next run reorders by update
258
+ * time again, so one that is commented on moves to the front, but with a
259
+ * hundred busier issues ahead of it a quiet one can wait a long time.
260
+ *
261
+ * @throws The lookup's rate-limit or auth error; other lookup failures are
262
+ * recorded per issue in `report.failures`.
272
263
  */
273
- async fetchEngagedIssue(candidate, username, cutoffDate) {
274
- const { owner, repo } = splitRepo(candidate.repoFullName);
275
- const url = `/repos/${owner}/${repo}/issues/${candidate.number}`;
276
- const issue = await cachedRequest(getHttpCache(), url, (headers) => this.octokit.issues.get({ owner, repo, headers, issue_number: candidate.number }));
264
+ async collectDirectCandidates(missing, context) {
265
+ const refs = [];
266
+ for (const entry of missing) {
267
+ const parsed = parseGitHubUrl(entry.url);
268
+ if (parsed)
269
+ refs.push({ owner: parsed.owner, repo: parsed.repo, number: parsed.number, url: entry.url });
270
+ }
271
+ if (refs.length === 0)
272
+ return [];
273
+ const lookups = await lookupEngagedIssues(this.octokit, refs);
274
+ const active = [];
275
+ for (const entry of missing) {
276
+ const outcome = lookups.get(entry.url);
277
+ if (!outcome)
278
+ continue;
279
+ const direct = this.toDirectCandidate(entry, outcome, context);
280
+ if (direct)
281
+ active.push(direct);
282
+ }
283
+ active.sort((a, b) => b.updatedMs - a.updatedMs);
284
+ const deferred = active.slice(MAX_DIRECT_ENGAGED_FETCHES);
285
+ if (deferred.length > 0) {
286
+ const plural = deferred.length === 1 ? '' : 's';
287
+ context.report.warnings.push(`${deferred.length} engaged issue${plural} with new activity ${deferred.length === 1 ? 'was' : 'were'} not scanned this run (cap of ${MAX_DIRECT_ENGAGED_FETCHES} comment fetches per run, most recently updated first; replies there stay unseen until fewer issues are busier): ${deferred.map((d) => d.candidate.url).join(', ')}`);
288
+ }
289
+ return active.slice(0, MAX_DIRECT_ENGAGED_FETCHES).map((d) => d.candidate);
290
+ }
291
+ /**
292
+ * The direct candidate one lookup outcome yields, or undefined with the
293
+ * reason logged: a lookup failure (recorded), a gone issue (a warning only
294
+ * while a claim or an open PR still points at it), a pull request number,
295
+ * a closed issue, one the user authored, or one untouched since the
296
+ * engagement. The candidate's repo and number come from the node's URL,
297
+ * not the engagement's: GitHub follows a transferred issue to its new
298
+ * repo, and the comments live there. So the repo exclusions and the
299
+ * search dedupe run again on that URL: a transfer into an excluded repo
300
+ * is skipped, and one onto an issue the search already returned adds no
301
+ * second candidate but lends that one the engagement (the engaged reply
302
+ * rule applies there too) unless it has its own.
303
+ */
304
+ toDirectCandidate(entry, outcome, context) {
305
+ const { username, cutoffDate, report } = context;
306
+ if (outcome.kind === 'failed') {
307
+ report.failures.push({ issueUrl: entry.url, error: outcome.error });
308
+ warn(MODULE, `Error looking up engaged issue ${entry.url}: ${outcome.error}`);
309
+ return undefined;
310
+ }
311
+ if (outcome.kind === 'gone') {
312
+ // The issue was deleted, transferred, or made private since the PR or
313
+ // claim linked it. Worth telling the user only while something of
314
+ // theirs still points at it (a claim to release, an open PR's closing
315
+ // link); a finished PR's link is history.
316
+ const message = `${entry.url}: issue no longer reachable (${outcome.reason}); dropped`;
317
+ if (isActionableEngagement(entry))
318
+ report.warnings.push(message);
319
+ else
320
+ debug(MODULE, message);
321
+ return undefined;
322
+ }
277
323
  const skip = (reason) => {
278
- debug(MODULE, `Skipping engaged issue ${candidate.url}: ${reason}`);
324
+ debug(MODULE, `Skipping engaged issue ${entry.url}: ${reason}`);
279
325
  };
280
- if (issue.pull_request)
326
+ if (outcome.kind === 'pull_request')
281
327
  return skip('the number is a pull request');
282
- if (issue.state !== 'open')
283
- return skip(`issue is ${issue.state}`);
284
- if (issue.user?.login?.toLowerCase() === username.toLowerCase())
328
+ const { node } = outcome;
329
+ if (node.state !== 'OPEN')
330
+ return skip(`issue is ${node.state.toLowerCase()}`);
331
+ if (node.author?.login.toLowerCase() === username.toLowerCase())
285
332
  return skip('authored by the user');
286
- const activitySinceMs = Math.max(cutoffDate.getTime(), parseMs(candidate.engagement?.since));
287
- if (Date.parse(issue.updated_at) < activitySinceMs)
288
- return skip(`not updated since ${issue.updated_at}`);
289
- return { html_url: issue.html_url, number: issue.number, title: issue.title, labels: issue.labels };
333
+ const updatedMs = parseMs(node.updatedAt);
334
+ const activitySinceMs = Math.max(cutoffDate.getTime(), parseMs(entry.since));
335
+ if (updatedMs < activitySinceMs)
336
+ return skip(`not updated since ${node.updatedAt}`);
337
+ const parsed = extractOwnerRepo(node.url);
338
+ if (!parsed) {
339
+ report.warnings.push(`${entry.url}: skipped; GitHub returned it at an unparseable URL "${node.url}"`);
340
+ return undefined;
341
+ }
342
+ const repoFullName = `${parsed.owner}/${parsed.repo}`;
343
+ const covered = this.transferredIssueCoverage(entry, node.url, repoFullName, context);
344
+ if (covered)
345
+ return skip(covered);
346
+ const item = { html_url: node.url, number: node.number, title: node.title, labels: labelNames(node) };
347
+ const candidate = { item, repoFullName, url: node.url, engagement: entry };
348
+ return { candidate, updatedMs };
349
+ }
350
+ /**
351
+ * Why a looked-up issue needs no candidate at the URL GitHub returned it,
352
+ * or undefined when it does (and its key is then marked seen). Only a
353
+ * transferred issue can be covered: the engagement's own repo passed the
354
+ * exclusions before the lookup and its own key was not among the search
355
+ * results. A transfer into an excluded repo is skipped; one onto an
356
+ * issue the search returned lends that candidate the engagement unless
357
+ * it has its own, so the engaged reply rule applies there.
358
+ */
359
+ transferredIssueCoverage(entry, url, repoFullName, { config, seenKeys, searchCandidates }) {
360
+ if (!this.isRepoAllowed(repoFullName, config))
361
+ return `now at ${url}, a repo that is excluded`;
362
+ const key = issueRefKey(url) ?? url;
363
+ const found = searchCandidates.get(key);
364
+ if (found) {
365
+ found.engagement ??= entry;
366
+ return `now at ${url}, which the search already returned`;
367
+ }
368
+ if (seenKeys.has(key))
369
+ return `now at ${url}, which is already covered`;
370
+ seenKeys.add(key);
371
+ return undefined;
290
372
  }
291
373
  /**
292
374
  * Analyze a single issue's comment thread to determine conversation status.
@@ -223,6 +223,8 @@ type NormalizeOutcome = {
223
223
  * hit; `missing` — the node was absent, inaccessible, or lacked a database id).
224
224
  */
225
225
  export declare function normalizePRNode(node: GraphQLPullRequestNode | null | undefined): NormalizeOutcome;
226
+ /** Split an array into fixed-size chunks. Shared with the engaged-issue lookup. */
227
+ export declare function chunk<T>(items: T[], size: number): T[][];
226
228
  /**
227
229
  * Detect GitHub's primary GraphQL rate limit. Unlike a REST 429/403, an
228
230
  * exhausted GraphQL point budget arrives as an HTTP 200 with an
@@ -262,8 +262,8 @@ export function normalizePRNode(node) {
262
262
  },
263
263
  };
264
264
  }
265
- /** Split an array into fixed-size chunks. */
266
- function chunk(items, size) {
265
+ /** Split an array into fixed-size chunks. Shared with the engaged-issue lookup. */
266
+ export function chunk(items, size) {
267
267
  const out = [];
268
268
  for (let i = 0; i < items.length; i += size)
269
269
  out.push(items.slice(i, i + size));
@@ -229,6 +229,10 @@ export declare class StateManager {
229
229
  get refreshGeneration(): number;
230
230
  /** Gist mode: whether a saved mutation has not reached the Gist yet. */
231
231
  hasUnpushedChanges(): boolean;
232
+ /** Gist mode: treat the current un-pushed saves as disposable, so the next
233
+ * refresh replaces them without raising the lost-changes staleness marker.
234
+ * Only for re-derivable data (the dashboard's GitHub fetch caches). */
235
+ forgetUnpushedChanges(): void;
232
236
  /**
233
237
  * Re-fetch state from the backing Gist (if in Gist mode).
234
238
  * Throttled to once per 30 seconds by GistStateStore unless `force` is set.
@@ -554,6 +554,12 @@ export class StateManager {
554
554
  hasUnpushedChanges() {
555
555
  return this.unpushed;
556
556
  }
557
+ /** Gist mode: treat the current un-pushed saves as disposable, so the next
558
+ * refresh replaces them without raising the lost-changes staleness marker.
559
+ * Only for re-derivable data (the dashboard's GitHub fetch caches). */
560
+ forgetUnpushedChanges() {
561
+ this.unpushed = false;
562
+ }
557
563
  /**
558
564
  * Re-fetch state from the backing Gist (if in Gist mode).
559
565
  * Throttled to once per 30 seconds by GistStateStore unless `force` is set.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oss-autopilot/core",
3
- "version": "3.39.0",
3
+ "version": "3.39.2",
4
4
  "description": "CLI and core library for managing open source contributions",
5
5
  "type": "module",
6
6
  "bin": {