@oss-scout/core 0.1.0

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 (66) hide show
  1. package/dist/cli.bundle.cjs +114 -0
  2. package/dist/cli.d.ts +5 -0
  3. package/dist/cli.js +341 -0
  4. package/dist/commands/config.d.ts +22 -0
  5. package/dist/commands/config.js +169 -0
  6. package/dist/commands/results.d.ts +8 -0
  7. package/dist/commands/results.js +13 -0
  8. package/dist/commands/search.d.ts +39 -0
  9. package/dist/commands/search.js +50 -0
  10. package/dist/commands/setup.d.ts +17 -0
  11. package/dist/commands/setup.js +104 -0
  12. package/dist/commands/validation.d.ts +6 -0
  13. package/dist/commands/validation.js +17 -0
  14. package/dist/commands/vet-list.d.ts +9 -0
  15. package/dist/commands/vet-list.js +16 -0
  16. package/dist/commands/vet.d.ts +25 -0
  17. package/dist/commands/vet.js +29 -0
  18. package/dist/core/bootstrap.d.ts +14 -0
  19. package/dist/core/bootstrap.js +122 -0
  20. package/dist/core/category-mapping.d.ts +19 -0
  21. package/dist/core/category-mapping.js +58 -0
  22. package/dist/core/concurrency.d.ts +6 -0
  23. package/dist/core/concurrency.js +25 -0
  24. package/dist/core/errors.d.ts +22 -0
  25. package/dist/core/errors.js +69 -0
  26. package/dist/core/gist-state-store.d.ts +96 -0
  27. package/dist/core/gist-state-store.js +302 -0
  28. package/dist/core/github.d.ts +16 -0
  29. package/dist/core/github.js +58 -0
  30. package/dist/core/http-cache.d.ts +108 -0
  31. package/dist/core/http-cache.js +314 -0
  32. package/dist/core/issue-discovery.d.ts +93 -0
  33. package/dist/core/issue-discovery.js +475 -0
  34. package/dist/core/issue-eligibility.d.ts +33 -0
  35. package/dist/core/issue-eligibility.js +151 -0
  36. package/dist/core/issue-filtering.d.ts +51 -0
  37. package/dist/core/issue-filtering.js +103 -0
  38. package/dist/core/issue-scoring.d.ts +43 -0
  39. package/dist/core/issue-scoring.js +97 -0
  40. package/dist/core/issue-vetting.d.ts +44 -0
  41. package/dist/core/issue-vetting.js +270 -0
  42. package/dist/core/local-state.d.ts +16 -0
  43. package/dist/core/local-state.js +56 -0
  44. package/dist/core/logger.d.ts +11 -0
  45. package/dist/core/logger.js +25 -0
  46. package/dist/core/pagination.d.ts +7 -0
  47. package/dist/core/pagination.js +16 -0
  48. package/dist/core/repo-health.d.ts +19 -0
  49. package/dist/core/repo-health.js +179 -0
  50. package/dist/core/schemas.d.ts +315 -0
  51. package/dist/core/schemas.js +137 -0
  52. package/dist/core/search-budget.d.ts +62 -0
  53. package/dist/core/search-budget.js +129 -0
  54. package/dist/core/search-phases.d.ts +69 -0
  55. package/dist/core/search-phases.js +238 -0
  56. package/dist/core/types.d.ts +124 -0
  57. package/dist/core/types.js +9 -0
  58. package/dist/core/utils.d.ts +18 -0
  59. package/dist/core/utils.js +106 -0
  60. package/dist/formatters/json.d.ts +6 -0
  61. package/dist/formatters/json.js +20 -0
  62. package/dist/index.d.ts +23 -0
  63. package/dist/index.js +25 -0
  64. package/dist/scout.d.ts +125 -0
  65. package/dist/scout.js +391 -0
  66. package/package.json +70 -0
@@ -0,0 +1,475 @@
1
+ /**
2
+ * Issue Discovery — orchestrates multi-phase issue search across GitHub.
3
+ *
4
+ * Delegates filtering, scoring, vetting, and search infrastructure to focused modules:
5
+ * - issue-filtering.ts — spam detection, doc-only filtering, per-repo caps
6
+ * - issue-scoring.ts — viability scores, repo quality bonuses
7
+ * - issue-vetting.ts — vetting orchestration, recommendation + viability scoring
8
+ * - issue-eligibility.ts — PR existence, claim detection, requirements analysis
9
+ * - repo-health.ts — project health checks, contribution guidelines
10
+ * - search-phases.ts — search helpers, caching, batched repo search
11
+ *
12
+ * All state is injected via constructor parameters (ScoutStateReader + ScoutPreferences).
13
+ */
14
+ import { getOctokit, checkRateLimit } from './github.js';
15
+ import { getSearchBudgetTracker } from './search-budget.js';
16
+ import { daysBetween, sleep } from './utils.js';
17
+ import { SCOPE_LABELS } from './types.js';
18
+ import { CONCRETE_STRATEGIES } from './schemas.js';
19
+ import { ValidationError, errorMessage, getHttpStatusCode, isRateLimitError } from './errors.js';
20
+ import { debug, info, warn } from './logger.js';
21
+ import { isDocOnlyIssue, applyPerRepoCap } from './issue-filtering.js';
22
+ import { IssueVetter } from './issue-vetting.js';
23
+ import { getTopicsForCategories } from './category-mapping.js';
24
+ import { buildEffectiveLabels, interleaveArrays, cachedSearchIssues, filterVetAndScore, searchInRepos, searchWithChunkedLabels, } from './search-phases.js';
25
+ const MODULE = 'issue-discovery';
26
+ /** Delay between major search phases to let GitHub's rate limit window cool down. */
27
+ const INTER_PHASE_DELAY_MS = 2000;
28
+ /** If remaining search quota is below this, skip heavy phases (2, 3). */
29
+ const LOW_BUDGET_THRESHOLD = 20;
30
+ /** If remaining search quota is below this, only run Phase 0. */
31
+ const CRITICAL_BUDGET_THRESHOLD = 10;
32
+ /**
33
+ * Multi-phase issue discovery engine that searches GitHub for contributable issues.
34
+ *
35
+ * Search phases (in priority order):
36
+ * 0. Repos where user has merged PRs (highest merge probability)
37
+ * 0.5. Preferred organizations
38
+ * 1. Starred repos
39
+ * 2. General label-filtered search
40
+ * 3. Actively maintained repos
41
+ *
42
+ * Each candidate is vetted for claimability and scored 0-100 for viability.
43
+ */
44
+ export class IssueDiscovery {
45
+ preferences;
46
+ stateReader;
47
+ octokit;
48
+ githubToken;
49
+ vetter;
50
+ /** Set after searchIssues() runs if rate limits affected the search (low pre-flight quota or mid-search rate limit hits). */
51
+ rateLimitWarning = null;
52
+ /**
53
+ * @param githubToken - GitHub personal access token or token from `gh auth token`
54
+ * @param preferences - User's search preferences (languages, labels, scopes, etc.)
55
+ * @param stateReader - Read-only interface for accessing scout state (merged PRs, starred repos, etc.)
56
+ */
57
+ constructor(githubToken, preferences, stateReader) {
58
+ this.preferences = preferences;
59
+ this.stateReader = stateReader;
60
+ this.githubToken = githubToken;
61
+ this.octokit = getOctokit(githubToken);
62
+ this.vetter = new IssueVetter(this.octokit, this.stateReader);
63
+ }
64
+ /**
65
+ * Get starred repos from the state reader.
66
+ * @returns Array of starred repo names in "owner/repo" format
67
+ */
68
+ getStarredRepos() {
69
+ return this.stateReader.getStarredRepos();
70
+ }
71
+ /**
72
+ * Search for issues matching our criteria.
73
+ * Searches in priority order: merged-PR repos first (no label filter), then preferred
74
+ * organizations, then starred repos, then general search, then actively maintained repos.
75
+ * Filters out issues from low-scoring and excluded repos.
76
+ *
77
+ * @param options - Search configuration
78
+ * @param options.languages - Programming languages to filter by
79
+ * @param options.labels - Issue labels to search for
80
+ * @param options.maxResults - Maximum candidates to return (default: 10)
81
+ * @returns Scored and sorted issue candidates
82
+ * @throws {ValidationError} If no candidates found and no rate limits prevented the search
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * import { IssueDiscovery } from '@oss-scout/core';
87
+ *
88
+ * const discovery = new IssueDiscovery(token, preferences, stateReader);
89
+ * const candidates = await discovery.searchIssues({ maxResults: 5 });
90
+ * for (const c of candidates) {
91
+ * console.log(`${c.issue.repo}#${c.issue.number}: ${c.viabilityScore}/100`);
92
+ * }
93
+ * ```
94
+ */
95
+ async searchIssues(options = {}) {
96
+ const config = this.preferences;
97
+ const languages = options.languages || config.languages;
98
+ const scopes = config.scope; // undefined = legacy mode
99
+ const labels = options.labels || (scopes ? buildEffectiveLabels(scopes, config.labels) : config.labels);
100
+ const maxResults = options.maxResults || 10;
101
+ const minStars = config.minStars ?? 50;
102
+ // Strategy selection: resolve which phases to run
103
+ const ALL_STRATEGIES = CONCRETE_STRATEGIES;
104
+ const rawStrategies = options.strategies ?? config.defaultStrategy ?? ['all'];
105
+ const enabledStrategies = new Set(rawStrategies.includes('all') ? ALL_STRATEGIES : rawStrategies);
106
+ const strategiesUsed = [];
107
+ const allCandidates = [];
108
+ let phase0Error = null;
109
+ let phase1Error = null;
110
+ let rateLimitHitDuringSearch = false;
111
+ // Pre-flight rate limit check — also determines adaptive phase budget
112
+ this.rateLimitWarning = null;
113
+ const tracker = getSearchBudgetTracker();
114
+ let searchBudget = LOW_BUDGET_THRESHOLD - 1; // conservative: below threshold to skip heavy phases
115
+ try {
116
+ const rateLimit = await checkRateLimit(this.githubToken);
117
+ searchBudget = rateLimit.remaining;
118
+ tracker.init(rateLimit.remaining, rateLimit.resetAt);
119
+ if (rateLimit.remaining < 5) {
120
+ const resetTime = new Date(rateLimit.resetAt).toLocaleTimeString('en-US', { hour12: false });
121
+ this.rateLimitWarning = `GitHub search API quota low (${rateLimit.remaining}/${rateLimit.limit} remaining, resets at ${resetTime}). Search may be slow.`;
122
+ warn(MODULE, this.rateLimitWarning);
123
+ }
124
+ if (searchBudget < CRITICAL_BUDGET_THRESHOLD) {
125
+ info(MODULE, `Search budget critical (${searchBudget} remaining) — running only Phase 0`);
126
+ }
127
+ else if (searchBudget < LOW_BUDGET_THRESHOLD) {
128
+ info(MODULE, `Search budget low (${searchBudget} remaining) — skipping heavy phases (2, 3)`);
129
+ }
130
+ }
131
+ catch (error) {
132
+ // Fail fast on auth errors — no point searching with a bad token
133
+ if (getHttpStatusCode(error) === 401) {
134
+ throw error;
135
+ }
136
+ // Non-fatal: proceed with conservative budget for transient/network errors.
137
+ // Initialize tracker with conservative defaults so it doesn't fly blind.
138
+ tracker.init(CRITICAL_BUDGET_THRESHOLD, new Date(Date.now() + 60000).toISOString());
139
+ warn(MODULE, 'Could not check rate limit — using conservative budget, skipping heavy phases:', errorMessage(error));
140
+ }
141
+ // Get merged-PR repos (highest merge probability)
142
+ const mergedPRRepos = this.stateReader.getReposWithMergedPRs();
143
+ // Get starred repos (from local cache or state reader)
144
+ const starredRepos = this.getStarredRepos();
145
+ const starredRepoSet = new Set(starredRepos);
146
+ // Get low-scoring repos from state reader
147
+ const minRepoScoreThreshold = config.minRepoScoreThreshold;
148
+ const lowScoringRepos = new Set(this.deriveLowScoringRepos(minRepoScoreThreshold));
149
+ // Common filters
150
+ const excludedRepos = new Set(config.excludeRepos);
151
+ const maxAgeDays = config.maxIssueAgeDays || 90;
152
+ const now = new Date();
153
+ // Build query parts
154
+ // When languages includes 'any', omit the language filter entirely
155
+ const isAnyLanguage = languages.some((l) => l.toLowerCase() === 'any');
156
+ const langQuery = isAnyLanguage ? '' : languages.map((l) => `language:${l}`).join(' ');
157
+ // Phase 0 uses a broader query — established contributors don't need beginner labels
158
+ // Phases 1+ pass labels separately to searchInRepos/searchWithChunkedLabels
159
+ const baseQualifiers = `is:issue is:open ${langQuery} no:assignee`.replace(/ +/g, ' ').trim();
160
+ // Helper to filter issues
161
+ const includeDocIssues = config.includeDocIssues ?? true;
162
+ const aiBlocklisted = new Set(config.aiPolicyBlocklist);
163
+ if (aiBlocklisted.size > 0) {
164
+ debug(MODULE, `[AI_POLICY_FILTER] Filtering issues from ${aiBlocklisted.size} blocklisted repo(s): ${[...aiBlocklisted].join(', ')}`);
165
+ }
166
+ const filterIssues = (items) => {
167
+ return items.filter((item) => {
168
+ const repoFullName = item.repository_url.split('/').slice(-2).join('/');
169
+ if (excludedRepos.has(repoFullName))
170
+ return false;
171
+ // Filter repos with known anti-AI contribution policies
172
+ if (aiBlocklisted.has(repoFullName))
173
+ return false;
174
+ // Filter OUT low-scoring repos
175
+ if (lowScoringRepos.has(repoFullName))
176
+ return false;
177
+ // Filter by issue age based on updated_at
178
+ const updatedAt = new Date(item.updated_at);
179
+ const ageDays = daysBetween(updatedAt, now);
180
+ if (ageDays > maxAgeDays)
181
+ return false;
182
+ // Filter out doc-only issues unless opted in
183
+ if (!includeDocIssues && isDocOnlyIssue(item))
184
+ return false;
185
+ return true;
186
+ });
187
+ };
188
+ // Phase 0: Search repos where user has merged PRs (highest merge probability)
189
+ const phase0Repos = mergedPRRepos.slice(0, 10);
190
+ const phase0RepoSet = new Set(phase0Repos);
191
+ if (phase0Repos.length > 0 && enabledStrategies.has('merged')) {
192
+ info(MODULE, `Phase 0: Searching issues in ${phase0Repos.length} merged-PR repos (no label filter)...`);
193
+ const remainingNeeded = maxResults - allCandidates.length;
194
+ if (remainingNeeded > 0) {
195
+ const { candidates: mergedCandidates, allBatchesFailed, rateLimitHit, } = await searchInRepos(this.octokit, this.vetter, phase0Repos, baseQualifiers, [], remainingNeeded, 'merged_pr', filterIssues);
196
+ allCandidates.push(...mergedCandidates);
197
+ if (allBatchesFailed) {
198
+ phase0Error = 'All merged-PR repo batches failed';
199
+ }
200
+ if (rateLimitHit) {
201
+ rateLimitHitDuringSearch = true;
202
+ }
203
+ info(MODULE, `Found ${mergedCandidates.length} candidates from merged-PR repos`);
204
+ }
205
+ strategiesUsed.push('merged');
206
+ }
207
+ // Phase 0.5: Search preferred organizations (explicit user preference)
208
+ // Skip if budget is critical — Phase 0 results are sufficient
209
+ let phase0_5Error = null;
210
+ const preferredOrgs = config.preferredOrgs ?? [];
211
+ if (allCandidates.length < maxResults && preferredOrgs.length > 0 && searchBudget >= CRITICAL_BUDGET_THRESHOLD && enabledStrategies.has('orgs')) {
212
+ // Inter-phase delay to let GitHub's rate limit window cool down
213
+ if (phase0Repos.length > 0)
214
+ await sleep(INTER_PHASE_DELAY_MS);
215
+ // Filter out orgs already covered by Phase 0 repos
216
+ const phase0Orgs = new Set(phase0Repos.map((r) => r.split('/')[0]?.toLowerCase()));
217
+ const orgsToSearch = preferredOrgs.filter((org) => !phase0Orgs.has(org.toLowerCase())).slice(0, 5);
218
+ if (orgsToSearch.length > 0) {
219
+ info(MODULE, `Phase 0.5: Searching issues in ${orgsToSearch.length} preferred org(s)...`);
220
+ const remainingNeeded = maxResults - allCandidates.length;
221
+ const orgRepoFilter = orgsToSearch.map((org) => `org:${org}`).join(' OR ');
222
+ const orgOps = orgsToSearch.length - 1;
223
+ try {
224
+ const allItems = await searchWithChunkedLabels(this.octokit, labels, orgOps, (labelQ) => `${baseQualifiers} ${labelQ} (${orgRepoFilter})`.replace(/ +/g, ' ').trim(), remainingNeeded * 3);
225
+ if (allItems.length > 0) {
226
+ const filtered = filterIssues(allItems).filter((item) => {
227
+ const repoFullName = item.repository_url.split('/').slice(-2).join('/');
228
+ return !phase0RepoSet.has(repoFullName);
229
+ });
230
+ const { candidates: orgCandidates, allFailed: allVetFailed, rateLimitHit, } = await this.vetter.vetIssuesParallel(filtered.slice(0, remainingNeeded * 2).map((i) => i.html_url), remainingNeeded, 'preferred_org');
231
+ allCandidates.push(...orgCandidates);
232
+ if (allVetFailed) {
233
+ phase0_5Error = 'All preferred org issue vetting failed';
234
+ }
235
+ if (rateLimitHit) {
236
+ rateLimitHitDuringSearch = true;
237
+ }
238
+ info(MODULE, `Found ${orgCandidates.length} candidates from preferred orgs`);
239
+ }
240
+ }
241
+ catch (error) {
242
+ const errMsg = errorMessage(error);
243
+ phase0_5Error = errMsg;
244
+ if (isRateLimitError(error)) {
245
+ rateLimitHitDuringSearch = true;
246
+ }
247
+ warn(MODULE, `Error searching preferred orgs: ${errMsg}`);
248
+ }
249
+ }
250
+ strategiesUsed.push('orgs');
251
+ }
252
+ // Phase 1: Search starred repos (filter out already-searched Phase 0 repos)
253
+ // Skip if budget is critical
254
+ if (allCandidates.length < maxResults && starredRepos.length > 0 && searchBudget >= CRITICAL_BUDGET_THRESHOLD && enabledStrategies.has('starred')) {
255
+ await sleep(INTER_PHASE_DELAY_MS);
256
+ const reposToSearch = starredRepos.filter((r) => !phase0RepoSet.has(r));
257
+ if (reposToSearch.length > 0) {
258
+ info(MODULE, `Phase 1: Searching issues in ${reposToSearch.length} starred repos...`);
259
+ const remainingNeeded = maxResults - allCandidates.length;
260
+ if (remainingNeeded > 0) {
261
+ // Cap labels to reduce Search API calls: starred repos already signal user
262
+ // interest, so fewer labels suffice. With 3 labels and batch size 3 (2 repo ORs),
263
+ // each batch fits in a single label chunk instead of 3+, cutting Phase 1 calls
264
+ // from ~12 to ~4.
265
+ const phase1Labels = labels.slice(0, 3);
266
+ const { candidates: starredCandidates, allBatchesFailed, rateLimitHit, } = await searchInRepos(this.octokit, this.vetter, reposToSearch.slice(0, 10), baseQualifiers, phase1Labels, remainingNeeded, 'starred', filterIssues);
267
+ allCandidates.push(...starredCandidates);
268
+ if (allBatchesFailed) {
269
+ phase1Error = 'All starred repo batches failed';
270
+ }
271
+ if (rateLimitHit) {
272
+ rateLimitHitDuringSearch = true;
273
+ }
274
+ info(MODULE, `Found ${starredCandidates.length} candidates from starred repos`);
275
+ }
276
+ }
277
+ strategiesUsed.push('starred');
278
+ }
279
+ // Phase 2: General search (if still need more)
280
+ // Skip if budget is low — Phases 0, 0.5, 1 are cheaper and higher-value
281
+ // When multiple scope tiers are active, fire one query per tier and interleave
282
+ // results to prevent high-volume tiers (e.g., "enhancement") from drowning out
283
+ // beginner results.
284
+ let phase2Error = null;
285
+ if (allCandidates.length < maxResults && searchBudget >= LOW_BUDGET_THRESHOLD && enabledStrategies.has('broad')) {
286
+ await sleep(INTER_PHASE_DELAY_MS);
287
+ info(MODULE, 'Phase 2: General issue search...');
288
+ const remainingNeeded = maxResults - allCandidates.length;
289
+ const seenRepos = new Set(allCandidates.map((c) => c.issue.repo));
290
+ // Build per-tier label groups. Multi-tier when 2+ scopes; single-tier otherwise.
291
+ const tierLabelGroups = [];
292
+ if (scopes && scopes.length > 1) {
293
+ for (const scope of scopes) {
294
+ const scopeLabels = SCOPE_LABELS[scope] ?? [];
295
+ if (scopeLabels.length === 0) {
296
+ warn(MODULE, `Scope "${scope}" has no labels, skipping tier`);
297
+ continue;
298
+ }
299
+ tierLabelGroups.push({ tier: scope, tierLabels: scopeLabels });
300
+ }
301
+ // Custom labels not in any tier get their own pseudo-tier
302
+ const allScopeLabels = new Set(scopes.flatMap((s) => SCOPE_LABELS[s] ?? []));
303
+ const customOnly = config.labels.filter((l) => !allScopeLabels.has(l));
304
+ if (customOnly.length > 0) {
305
+ tierLabelGroups.push({ tier: 'custom', tierLabels: customOnly });
306
+ }
307
+ }
308
+ else {
309
+ tierLabelGroups.push({ tier: 'general', tierLabels: labels });
310
+ }
311
+ const budgetPerTier = Math.ceil(remainingNeeded / tierLabelGroups.length);
312
+ const tierResults = [];
313
+ for (const { tier, tierLabels } of tierLabelGroups) {
314
+ try {
315
+ const allItems = await searchWithChunkedLabels(this.octokit, tierLabels, 0, // no repo/org ORs in Phase 2
316
+ (labelQ) => `${baseQualifiers} ${labelQ}`.replace(/ +/g, ' ').trim(), budgetPerTier * 3);
317
+ info(MODULE, `Phase 2 [${tier}]: processing ${allItems.length} items...`);
318
+ const { candidates: tierCandidates, allVetFailed, rateLimitHit: vetRateLimitHit, } = await filterVetAndScore(this.vetter, allItems, filterIssues, [phase0RepoSet, starredRepoSet, seenRepos], budgetPerTier, minStars, `Phase 2 [${tier}]`);
319
+ tierResults.push(tierCandidates);
320
+ // Update seenRepos so later tiers don't return duplicate repos
321
+ for (const c of tierCandidates)
322
+ seenRepos.add(c.issue.repo);
323
+ if (allVetFailed) {
324
+ phase2Error = (phase2Error ? phase2Error + '; ' : '') + `${tier}: all vetting failed`;
325
+ }
326
+ if (vetRateLimitHit) {
327
+ rateLimitHitDuringSearch = true;
328
+ }
329
+ info(MODULE, `Found ${tierCandidates.length} candidates from ${tier} tier`);
330
+ }
331
+ catch (error) {
332
+ if (getHttpStatusCode(error) === 401)
333
+ throw error;
334
+ const errMsg = errorMessage(error);
335
+ phase2Error = (phase2Error ? phase2Error + '; ' : '') + `${tier}: ${errMsg}`;
336
+ if (isRateLimitError(error)) {
337
+ rateLimitHitDuringSearch = true;
338
+ }
339
+ warn(MODULE, `Error in ${tier} tier search: ${errMsg}`);
340
+ tierResults.push([]);
341
+ }
342
+ }
343
+ const interleaved = interleaveArrays(tierResults);
344
+ if (interleaved.length === 0 && phase2Error) {
345
+ warn(MODULE, `All ${tierLabelGroups.length} scope tiers failed in Phase 2: ${phase2Error}`);
346
+ }
347
+ allCandidates.push(...interleaved.slice(0, remainingNeeded));
348
+ strategiesUsed.push('broad');
349
+ }
350
+ // Phase 3: Actively maintained repos
351
+ // Skip if budget is low — this phase is API-heavy with broad queries
352
+ let phase3Error = null;
353
+ if (allCandidates.length < maxResults && searchBudget >= LOW_BUDGET_THRESHOLD && enabledStrategies.has('maintained')) {
354
+ await sleep(INTER_PHASE_DELAY_MS);
355
+ info(MODULE, 'Phase 3: Searching actively maintained repos...');
356
+ const remainingNeeded = maxResults - allCandidates.length;
357
+ const thirtyDaysAgo = new Date();
358
+ thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
359
+ const pushedSince = thirtyDaysAgo.toISOString().split('T')[0];
360
+ const categoryTopics = getTopicsForCategories(config.projectCategories ?? []);
361
+ const topicQuery = categoryTopics.length > 0 ? `topic:${categoryTopics[0]}` : '';
362
+ const phase3Query = `is:issue is:open no:assignee ${langQuery} ${topicQuery} stars:>=${minStars} pushed:>=${pushedSince} archived:false`
363
+ .replace(/ +/g, ' ')
364
+ .trim();
365
+ try {
366
+ const data = await cachedSearchIssues(this.octokit, {
367
+ q: phase3Query,
368
+ sort: 'updated',
369
+ order: 'desc',
370
+ per_page: remainingNeeded * 3,
371
+ });
372
+ info(MODULE, `Found ${data.total_count} issues in maintained-repo search, processing top ${data.items.length}...`);
373
+ const seenRepos = new Set(allCandidates.map((c) => c.issue.repo));
374
+ const { candidates: starFiltered, allVetFailed, rateLimitHit: vetRateLimitHit, } = await filterVetAndScore(this.vetter, data.items, filterIssues, [phase0RepoSet, starredRepoSet, seenRepos], remainingNeeded, minStars, 'Phase 3');
375
+ allCandidates.push(...starFiltered);
376
+ if (allVetFailed) {
377
+ phase3Error = 'all vetting failed';
378
+ }
379
+ if (vetRateLimitHit) {
380
+ rateLimitHitDuringSearch = true;
381
+ }
382
+ info(MODULE, `Found ${starFiltered.length} candidates from maintained-repo search`);
383
+ }
384
+ catch (error) {
385
+ const errMsg = errorMessage(error);
386
+ phase3Error = errMsg;
387
+ if (isRateLimitError(error)) {
388
+ rateLimitHitDuringSearch = true;
389
+ }
390
+ warn(MODULE, `Error in maintained-repo search: ${errMsg}`);
391
+ }
392
+ strategiesUsed.push('maintained');
393
+ }
394
+ // Determine if phases were skipped due to budget constraints
395
+ const phasesSkippedForBudget = searchBudget < LOW_BUDGET_THRESHOLD;
396
+ let budgetNote = '';
397
+ if (searchBudget < CRITICAL_BUDGET_THRESHOLD) {
398
+ budgetNote = ` Most search phases were skipped due to critically low API quota (${searchBudget} remaining).`;
399
+ }
400
+ else if (phasesSkippedForBudget) {
401
+ budgetNote = ` Some search phases were skipped due to low API quota (${searchBudget} remaining).`;
402
+ }
403
+ if (allCandidates.length === 0) {
404
+ const phaseErrors = [
405
+ phase0Error ? `Phase 0 (merged-PR repos): ${phase0Error}` : null,
406
+ phase0_5Error ? `Phase 0.5 (preferred orgs): ${phase0_5Error}` : null,
407
+ phase1Error ? `Phase 1 (starred repos): ${phase1Error}` : null,
408
+ phase2Error ? `Phase 2 (general): ${phase2Error}` : null,
409
+ phase3Error ? `Phase 3 (maintained repos): ${phase3Error}` : null,
410
+ ].filter(Boolean);
411
+ const details = phaseErrors.length > 0 ? ` ${phaseErrors.join('. ')}.` : '';
412
+ if (rateLimitHitDuringSearch || phasesSkippedForBudget) {
413
+ this.rateLimitWarning =
414
+ `Search returned no results due to GitHub API rate limits.${details}${budgetNote} ` +
415
+ `Try again after the rate limit resets.`;
416
+ return { candidates: [], strategiesUsed };
417
+ }
418
+ throw new ValidationError(`No issue candidates found across all search phases.${details} ` +
419
+ 'Try adjusting your search criteria (languages, labels) or check your network connection.');
420
+ }
421
+ // Surface rate limit warning even with partial results
422
+ if (rateLimitHitDuringSearch || phasesSkippedForBudget) {
423
+ this.rateLimitWarning =
424
+ `Search results may be incomplete: GitHub API rate limits were hit during search.${budgetNote} ` +
425
+ `Found ${allCandidates.length} candidate${allCandidates.length === 1 ? '' : 's'} but some search phases were limited. ` +
426
+ `Try again after the rate limit resets for complete results.`;
427
+ }
428
+ // Sort by priority first, then by recommendation, then by viability score
429
+ allCandidates.sort((a, b) => {
430
+ const priorityOrder = { merged_pr: 0, preferred_org: 1, starred: 2, normal: 3 };
431
+ const priorityDiff = priorityOrder[a.searchPriority] - priorityOrder[b.searchPriority];
432
+ if (priorityDiff !== 0)
433
+ return priorityDiff;
434
+ const recommendationOrder = { approve: 0, needs_review: 1, skip: 2 };
435
+ const recDiff = recommendationOrder[a.recommendation] - recommendationOrder[b.recommendation];
436
+ if (recDiff !== 0)
437
+ return recDiff;
438
+ return b.viabilityScore - a.viabilityScore;
439
+ });
440
+ // Apply per-repo cap: max 2 issues from any single repo
441
+ const capped = applyPerRepoCap(allCandidates, 2);
442
+ info(MODULE, `Search complete: ${tracker.getTotalCalls()} Search API calls used, ${capped.length} candidates returned`);
443
+ return { candidates: capped.slice(0, maxResults), strategiesUsed };
444
+ }
445
+ /**
446
+ * Vet a specific issue for claimability and project health.
447
+ * @param issueUrl - Full GitHub issue URL
448
+ * @returns The vetted issue candidate with recommendation and scores
449
+ * @throws {ValidationError} If the URL is invalid or the issue cannot be fetched
450
+ */
451
+ async vetIssue(issueUrl) {
452
+ return this.vetter.vetIssue(issueUrl);
453
+ }
454
+ /**
455
+ * Derive low-scoring repos from the state reader.
456
+ * A repo is considered "low-scoring" if its score is at or below the threshold.
457
+ */
458
+ deriveLowScoringRepos(threshold) {
459
+ const lowScoring = [];
460
+ // The ScoutStateReader doesn't expose a bulk "get all repos with scores" method,
461
+ // so we rely on the mergedPRRepos + starredRepos as the universe of known repos
462
+ // and check each one's score. Repos not in state simply return null (no penalty).
463
+ const knownRepos = new Set([
464
+ ...this.stateReader.getReposWithMergedPRs(),
465
+ ...this.stateReader.getStarredRepos(),
466
+ ]);
467
+ for (const repo of knownRepos) {
468
+ const score = this.stateReader.getRepoScore(repo);
469
+ if (score !== null && score <= threshold) {
470
+ lowScoring.push(repo);
471
+ }
472
+ }
473
+ return lowScoring;
474
+ }
475
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Issue Eligibility — checks whether an individual issue is claimable:
3
+ * existing PR detection, claim-phrase scanning, user merge history,
4
+ * and requirement clarity analysis.
5
+ *
6
+ * Extracted from issue-vetting.ts to isolate eligibility logic.
7
+ */
8
+ import { Octokit } from '@octokit/rest';
9
+ import type { CheckResult } from './types.js';
10
+ /**
11
+ * Check whether an open PR already exists for the given issue.
12
+ * Uses the timeline API (REST) to detect cross-referenced PRs, avoiding
13
+ * the Search API's strict 30 req/min rate limit.
14
+ */
15
+ export declare function checkNoExistingPR(octokit: Octokit, owner: string, repo: string, issueNumber: number): Promise<CheckResult>;
16
+ /**
17
+ * Check how many merged PRs the authenticated user has in a repo.
18
+ * Uses GitHub Search API. Returns 0 on error (non-fatal).
19
+ * Results are cached per-repo for 15 minutes to avoid redundant Search API
20
+ * calls when multiple issues from the same repo are vetted.
21
+ */
22
+ export declare function checkUserMergedPRsInRepo(octokit: Octokit, owner: string, repo: string): Promise<number>;
23
+ /**
24
+ * Check whether an issue has been claimed by another contributor
25
+ * by scanning recent comments for claim phrases.
26
+ */
27
+ export declare function checkNotClaimed(octokit: Octokit, owner: string, repo: string, issueNumber: number, commentCount: number): Promise<CheckResult>;
28
+ /**
29
+ * Analyze whether an issue body has clear, actionable requirements.
30
+ * Returns true when at least two "clarity indicators" are present:
31
+ * numbered/bulleted steps, code blocks, expected-behavior keywords, length > 200.
32
+ */
33
+ export declare function analyzeRequirements(body: string): boolean;
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Issue Eligibility — checks whether an individual issue is claimable:
3
+ * existing PR detection, claim-phrase scanning, user merge history,
4
+ * and requirement clarity analysis.
5
+ *
6
+ * Extracted from issue-vetting.ts to isolate eligibility logic.
7
+ */
8
+ import { paginateAll } from './pagination.js';
9
+ import { errorMessage } from './errors.js';
10
+ import { warn } from './logger.js';
11
+ import { getHttpCache } from './http-cache.js';
12
+ import { getSearchBudgetTracker } from './search-budget.js';
13
+ const MODULE = 'issue-eligibility';
14
+ /** Phrases that indicate someone has already claimed an issue. */
15
+ const CLAIM_PHRASES = [
16
+ "i'm working on this",
17
+ 'i am working on this',
18
+ "i'll take this",
19
+ 'i will take this',
20
+ 'working on it',
21
+ "i'd like to work on",
22
+ 'i would like to work on',
23
+ 'can i work on',
24
+ 'may i work on',
25
+ 'assigned to me',
26
+ "i'm on it",
27
+ "i'll submit a pr",
28
+ 'i will submit a pr',
29
+ 'working on a fix',
30
+ 'working on a pr',
31
+ ];
32
+ /**
33
+ * Check whether an open PR already exists for the given issue.
34
+ * Uses the timeline API (REST) to detect cross-referenced PRs, avoiding
35
+ * the Search API's strict 30 req/min rate limit.
36
+ */
37
+ export async function checkNoExistingPR(octokit, owner, repo, issueNumber) {
38
+ try {
39
+ // Use the timeline API (REST, not Search) to detect linked PRs.
40
+ // This avoids consuming GitHub Search API quota (30 req/min limit).
41
+ // Timeline captures formally linked PRs via cross-referenced events
42
+ // but may miss PRs that only mention the issue number without a formal
43
+ // link — an acceptable trade-off since most PRs use "Fixes #N" syntax.
44
+ const timeline = await paginateAll((page) => octokit.issues.listEventsForTimeline({
45
+ owner,
46
+ repo,
47
+ issue_number: issueNumber,
48
+ per_page: 100,
49
+ page,
50
+ }));
51
+ const linkedPRs = timeline.filter((event) => {
52
+ const e = event;
53
+ return e.event === 'cross-referenced' && e.source?.issue?.pull_request;
54
+ });
55
+ return { passed: linkedPRs.length === 0 };
56
+ }
57
+ catch (error) {
58
+ const errMsg = errorMessage(error);
59
+ warn(MODULE, `Failed to check for existing PRs on ${owner}/${repo}#${issueNumber}: ${errMsg}. Assuming no existing PR.`);
60
+ return { passed: true, inconclusive: true, reason: errMsg };
61
+ }
62
+ }
63
+ /** TTL for cached merged-PR counts per repo (15 minutes). */
64
+ const MERGED_PR_CACHE_TTL_MS = 15 * 60 * 1000;
65
+ /**
66
+ * Check how many merged PRs the authenticated user has in a repo.
67
+ * Uses GitHub Search API. Returns 0 on error (non-fatal).
68
+ * Results are cached per-repo for 15 minutes to avoid redundant Search API
69
+ * calls when multiple issues from the same repo are vetted.
70
+ */
71
+ export async function checkUserMergedPRsInRepo(octokit, owner, repo) {
72
+ const cache = getHttpCache();
73
+ const cacheKey = `merged-prs:${owner}/${repo}`;
74
+ // Manual cache check — do not use cachedTimeBased because we must NOT cache
75
+ // error-path fallback values (a transient failure returning 0 would poison the
76
+ // cache for 15 minutes, hiding that the user has merged PRs in the repo).
77
+ const cached = cache.getIfFresh(cacheKey, MERGED_PR_CACHE_TTL_MS);
78
+ if (cached != null && typeof cached === 'number') {
79
+ return cached;
80
+ }
81
+ try {
82
+ const tracker = getSearchBudgetTracker();
83
+ await tracker.waitForBudget();
84
+ try {
85
+ // Use @me to search as the authenticated user
86
+ const { data } = await octokit.search.issuesAndPullRequests({
87
+ q: `repo:${owner}/${repo} is:pr is:merged author:@me`,
88
+ per_page: 1, // We only need total_count
89
+ });
90
+ // Only cache successful results
91
+ cache.set(cacheKey, '', data.total_count);
92
+ return data.total_count;
93
+ }
94
+ finally {
95
+ // Always record the call — failed requests still consume GitHub rate limit points
96
+ tracker.recordCall();
97
+ }
98
+ }
99
+ catch (error) {
100
+ const errMsg = errorMessage(error);
101
+ warn(MODULE, `Could not check merged PRs in ${owner}/${repo}: ${errMsg}. Defaulting to 0.`);
102
+ return 0; // Not cached — next call will retry
103
+ }
104
+ }
105
+ /**
106
+ * Check whether an issue has been claimed by another contributor
107
+ * by scanning recent comments for claim phrases.
108
+ */
109
+ export async function checkNotClaimed(octokit, owner, repo, issueNumber, commentCount) {
110
+ if (commentCount === 0)
111
+ return { passed: true };
112
+ try {
113
+ // Paginate through all comments
114
+ const comments = await octokit.paginate(octokit.issues.listComments, {
115
+ owner,
116
+ repo,
117
+ issue_number: issueNumber,
118
+ per_page: 100,
119
+ }, (response) => response.data);
120
+ // Limit to last 100 comments to avoid excessive processing
121
+ const recentComments = comments.slice(-100);
122
+ for (const comment of recentComments) {
123
+ const body = (comment.body || '').toLowerCase();
124
+ if (CLAIM_PHRASES.some((phrase) => body.includes(phrase))) {
125
+ return { passed: false };
126
+ }
127
+ }
128
+ return { passed: true };
129
+ }
130
+ catch (error) {
131
+ const errMsg = errorMessage(error);
132
+ warn(MODULE, `Failed to check claim status on ${owner}/${repo}#${issueNumber}: ${errMsg}. Assuming not claimed.`);
133
+ return { passed: true, inconclusive: true, reason: errMsg };
134
+ }
135
+ }
136
+ /**
137
+ * Analyze whether an issue body has clear, actionable requirements.
138
+ * Returns true when at least two "clarity indicators" are present:
139
+ * numbered/bulleted steps, code blocks, expected-behavior keywords, length > 200.
140
+ */
141
+ export function analyzeRequirements(body) {
142
+ if (!body || body.length < 50)
143
+ return false;
144
+ // Check for clear structure
145
+ const hasSteps = /\d\.|[-*]\s/.test(body);
146
+ const hasCodeBlock = /```/.test(body);
147
+ const hasExpectedBehavior = /expect|should|must|want/i.test(body);
148
+ // Must have at least two indicators of clarity
149
+ const indicators = [hasSteps, hasCodeBlock, hasExpectedBehavior, body.length > 200];
150
+ return indicators.filter(Boolean).length >= 2;
151
+ }