@oss-autopilot/core 3.36.0 → 3.38.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 (48) hide show
  1. package/dist/cli-registry.js +1 -1
  2. package/dist/cli.bundle.cjs +143 -130
  3. package/dist/commands/comments.js +4 -3
  4. package/dist/commands/config.js +18 -11
  5. package/dist/commands/daily.js +29 -2
  6. package/dist/commands/dashboard-gist-sync.d.ts +5 -1
  7. package/dist/commands/dashboard-gist-sync.js +19 -2
  8. package/dist/commands/dashboard-server.js +9 -5
  9. package/dist/commands/dismiss.js +4 -3
  10. package/dist/commands/guidelines.js +21 -14
  11. package/dist/commands/init.js +3 -2
  12. package/dist/commands/ledger-backfill.d.ts +7 -0
  13. package/dist/commands/ledger-backfill.js +120 -9
  14. package/dist/commands/move.js +9 -6
  15. package/dist/commands/overnight-push-prep.js +5 -2
  16. package/dist/commands/overnight.js +48 -23
  17. package/dist/commands/search.js +9 -6
  18. package/dist/commands/setup.js +7 -3
  19. package/dist/commands/validation.js +22 -0
  20. package/dist/commands/vet-list.js +18 -17
  21. package/dist/commands/vet.js +27 -2
  22. package/dist/core/daily-logic.d.ts +33 -0
  23. package/dist/core/daily-logic.js +102 -0
  24. package/dist/core/errors.js +1 -1
  25. package/dist/core/eval-report.d.ts +17 -0
  26. package/dist/core/eval-report.js +85 -4
  27. package/dist/core/gist-state-store.d.ts +5 -2
  28. package/dist/core/gist-state-store.js +7 -4
  29. package/dist/core/index.d.ts +3 -3
  30. package/dist/core/index.js +3 -3
  31. package/dist/core/issue-verification.d.ts +12 -0
  32. package/dist/core/issue-verification.js +18 -0
  33. package/dist/core/pick-snapshot.d.ts +19 -2
  34. package/dist/core/pick-snapshot.js +28 -2
  35. package/dist/core/pr-monitor.d.ts +0 -6
  36. package/dist/core/pr-monitor.js +0 -13
  37. package/dist/core/repo-score-manager.d.ts +0 -13
  38. package/dist/core/repo-score-manager.js +0 -24
  39. package/dist/core/review-analysis.d.ts +34 -14
  40. package/dist/core/review-analysis.js +61 -32
  41. package/dist/core/state-persistence.js +4 -1
  42. package/dist/core/state-schema.d.ts +46 -0
  43. package/dist/core/state-schema.js +28 -0
  44. package/dist/core/state.d.ts +44 -18
  45. package/dist/core/state.js +164 -38
  46. package/dist/formatters/json.d.ts +4 -0
  47. package/dist/formatters/json.js +4 -0
  48. package/package.json +1 -1
@@ -76,13 +76,59 @@ function starRange(stars) {
76
76
  return '1k-10k';
77
77
  return '10k+';
78
78
  }
79
+ /** Normalized label groups for the label cut; a label matches by substring. */
80
+ // Word boundaries by letters only: `\b` treats `_` as a word char, so
81
+ // `good_first_issue` / `type_bug` would never match.
82
+ const wordRe = (alternatives) => new RegExp(`(?:^|[^a-z])(?:${alternatives})(?![a-z])`);
83
+ const LABEL_GROUPS = [
84
+ ['good first issue', wordRe('good[ _-]?first|beginners?|easy|first.?timers?|starter(?![_-][a-z])')],
85
+ ['help wanted', wordRe('help[ _-]?wanted')],
86
+ ['bug', wordRe('bugs?')],
87
+ ['enhancement', wordRe('enhancements?|features?')],
88
+ ['documentation', wordRe('docs?|documentation')],
89
+ ];
90
+ const MAINTAINER_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
91
+ const OUTSIDER_ASSOCIATIONS = new Set(['NONE', 'FIRST_TIMER', 'FIRST_TIME_CONTRIBUTOR', 'MANNEQUIN']);
92
+ /** Issue-author bucket from the raw association recorded at pick time. */
93
+ function authorRole(pick) {
94
+ if (pick.issueAuthorIsBot)
95
+ return 'bot';
96
+ const a = pick.issueAuthorAssociation;
97
+ if (a === undefined)
98
+ return NOT_RECORDED;
99
+ if (MAINTAINER_ASSOCIATIONS.has(a))
100
+ return 'maintainer';
101
+ if (a === 'CONTRIBUTOR')
102
+ return 'contributor';
103
+ return OUTSIDER_ASSOCIATIONS.has(a) ? 'outsider' : 'unknown';
104
+ }
105
+ const NO_LABEL_GROUP = 'none of these';
106
+ const NOT_RECORDED = 'not recorded';
107
+ function labelGroups(labels) {
108
+ const lower = labels.map((l) => l.toLowerCase());
109
+ const groups = LABEL_GROUPS.filter(([, re]) => lower.some((l) => re.test(l))).map(([g]) => g);
110
+ return groups.length > 0 ? groups : [NO_LABEL_GROUP];
111
+ }
79
112
  function collectRows(state) {
80
113
  const starsOf = (repo) => state.repoScores[repo]?.stargazersCount;
81
- const common = (e) => {
114
+ // Merge times per repo, so a PR is first-in-repo when no merge in the same
115
+ // repo precedes its opening. Works for entries recorded before picks existed.
116
+ // ponytail: only sees merges the ledger holds; older merges count as none.
117
+ const mergeTimes = new Map();
118
+ const mergedLedger = state.mergedPRs ?? [];
119
+ for (const e of mergedLedger) {
120
+ const repo = repoOf(e.url).toLowerCase();
121
+ mergeTimes.set(repo, [...(mergeTimes.get(repo) ?? []), Date.parse(e.mergedAt)]);
122
+ }
123
+ const isFirstAt = (repo, at) => (mergeTimes.get(repo.toLowerCase()) ?? []).every((t) => t >= at);
124
+ const common = (e, at) => {
82
125
  const repo = repoOf(e.url);
83
126
  return {
84
127
  url: e.url,
85
128
  repo,
129
+ issueUrl: e.issueUrl,
130
+ firstInRepo: e.pick?.firstInRepo ?? isFirstAt(repo, Date.parse(e.openedAt ?? at)),
131
+ pick: e.pick,
86
132
  grade: e.pick?.grade,
87
133
  gradeSource: e.pick ? (e.pick.source === 'list' ? 'list' : 'vet') : undefined,
88
134
  stars: e.pick?.stargazersCount ?? starsOf(repo),
@@ -92,13 +138,13 @@ function collectRows(state) {
92
138
  };
93
139
  };
94
140
  const merged = (state.mergedPRs ?? []).map((e) => ({
95
- ...common(e),
141
+ ...common(e, e.mergedAt),
96
142
  outcome: 'merged',
97
143
  month: e.mergedAt.slice(0, 7),
98
144
  hoursToMerge: hoursBetween(e.openedAt, e.mergedAt),
99
145
  }));
100
146
  const closed = (state.closedPRs ?? []).map((e) => ({
101
- ...common(e),
147
+ ...common(e, e.closedAt),
102
148
  outcome: 'closed',
103
149
  month: e.closedAt.slice(0, 7),
104
150
  closeReason: e.closeReason,
@@ -106,7 +152,13 @@ function collectRows(state) {
106
152
  }));
107
153
  const dormant = (state.lastDigest?.openPRs ?? [])
108
154
  .filter((pr) => pr.stalenessTier === 'dormant')
109
- .map((pr) => ({ url: pr.url, repo: pr.repo, outcome: 'dormant', stars: starsOf(pr.repo) }));
155
+ .map((pr) => ({
156
+ url: pr.url,
157
+ repo: pr.repo,
158
+ outcome: 'dormant',
159
+ stars: starsOf(pr.repo),
160
+ firstInRepo: isFirstAt(pr.repo, Date.parse(pr.createdAt)),
161
+ }));
110
162
  return [...merged, ...closed, ...dormant];
111
163
  }
112
164
  const pct = (v) => (v === null ? 'n/a' : `${Math.round(v * 100)}%`);
@@ -130,6 +182,8 @@ export function computeEvalReport(state, now = new Date()) {
130
182
  approachClosuresByMonth[r.month] = (approachClosuresByMonth[r.month] ?? 0) + 1;
131
183
  }
132
184
  }
185
+ const picked = rows.filter((r) => r.pick);
186
+ const closesIssue = rows.filter((r) => r.issueUrl && r.outcome !== 'dormant');
133
187
  const reviewed = rows.filter((r) => r.changesRequested !== undefined);
134
188
  const ciKnown = rows.filter((r) => r.ciFailing !== undefined);
135
189
  const byGrade = groupBy(rows, (r) => (r.gradeSource ? `${r.gradeSource} ${gradeRange(r.grade)}` : 'no prediction'), [
@@ -155,11 +209,33 @@ export function computeEvalReport(state, now = new Date()) {
155
209
  headlines: {
156
210
  mergeRate1kStars: bucket('>=1k stars', rows.filter((r) => (r.stars ?? 0) >= 1000)),
157
211
  calibration: { gap, highN: high.length, lowN: low.length },
212
+ vetCoverage: { graded: closesIssue.filter((r) => r.gradeSource === 'vet').length, of: closesIssue.length },
158
213
  approachClosuresByMonth,
159
214
  },
160
215
  byGrade,
161
216
  byStars: groupBy(rows, (r) => starRange(r.stars), ['10k+', '1k-10k', '100-1k', '<100', 'unknown']),
162
217
  byMonth: groupBy(rows.filter((r) => r.month), (r) => r.month).sort((a, b) => b.key.localeCompare(a.key)),
218
+ byFirstInRepo: groupBy(rows, (r) => (r.firstInRepo ? 'first in repo' : 'returning'), [
219
+ 'first in repo',
220
+ 'returning',
221
+ ]),
222
+ byIssueAuthorRole: groupBy(picked, (r) => authorRole(r.pick), [
223
+ 'maintainer',
224
+ 'contributor',
225
+ 'outsider',
226
+ 'bot',
227
+ 'unknown',
228
+ NOT_RECORDED,
229
+ ]),
230
+ byCompetingPRs: groupBy(picked, (r) => {
231
+ const n = r.pick.competingPRs;
232
+ if (n === undefined)
233
+ return NOT_RECORDED;
234
+ return n === 0 ? '0' : '1+';
235
+ }, ['0', '1+', NOT_RECORDED]),
236
+ byLabel: [...LABEL_GROUPS.map(([g]) => g), NO_LABEL_GROUP]
237
+ .map((g) => bucket(g, picked.filter((r) => r.pick.labels && labelGroups(r.pick.labels).includes(g))))
238
+ .filter((b) => b.n > 0),
163
239
  closeReasons,
164
240
  quality: {
165
241
  withReviewState: reviewed.length,
@@ -190,6 +266,7 @@ export function formatEvalMarkdown(r) {
190
266
  '',
191
267
  `- Merge rate on repos with 1k+ stars: **${pct(h.mergeRate1kStars.mergeRate)}** (n=${h.mergeRate1kStars.n})`,
192
268
  `- Calibration gap, vet grades (grade>=7 minus grade<=5 merge rate): **${h.calibration.gap ?? 'n/a'}** (n=${h.calibration.highN} vs ${h.calibration.lowN}; needs ${MIN_FLAG_N} each)`,
269
+ `- Vet grade recorded at pick: **${h.vetCoverage.graded} of ${h.vetCoverage.of}** merged or closed PRs that close an issue`,
193
270
  `- Approach or AI-policy closures by month: ${recentMonths.length ? recentMonths.map((m) => `${m}: ${h.approachClosuresByMonth[m]}`).join(', ') : 'none'}`,
194
271
  `- Overall: ${r.totals.n} outcomes, merge rate ${pct(r.totals.mergeRate)} (dormant counted as not merged)`,
195
272
  '',
@@ -197,6 +274,10 @@ export function formatEvalMarkdown(r) {
197
274
  ...table('By grade at pick time', r.byGrade),
198
275
  ...table('By repo stars', r.byStars),
199
276
  ...table('By month', r.byMonth.slice(0, 12)),
277
+ ...table('First PR in repo vs returning', r.byFirstInRepo),
278
+ ...table('By issue author (picks)', r.byIssueAuthorRole),
279
+ ...table('By competing PRs at pick time (picks)', r.byCompetingPRs),
280
+ ...table('By issue label (picks; one pick can match several)', r.byLabel),
200
281
  '## Close reasons',
201
282
  '',
202
283
  ...Object.entries(r.closeReasons)
@@ -271,10 +271,13 @@ export declare class GistStateStore {
271
271
  * outcomes that previously collapsed into a single boolean (#1209 L9):
272
272
  * - `{ status: 'refreshed' }` — fresh data loaded successfully.
273
273
  * - `{ status: 'no-gist' }` — store not in Gist mode (e.g. degraded).
274
- * - `{ status: 'throttled', sinceLastMs }` — within the 30s throttle.
274
+ * - `{ status: 'throttled', sinceLastMs }` — within the 30s throttle
275
+ * (skipped when `options.force` is set).
275
276
  * - `{ status: 'error', error }` — fetch attempt failed.
276
277
  */
277
- refreshFromGist(): Promise<RefreshResult>;
278
+ refreshFromGist(options?: {
279
+ force?: boolean;
280
+ }): Promise<RefreshResult>;
278
281
  /**
279
282
  * Refuse to write a file the Gist could no longer serve back (raw_url stops
280
283
  * at 10 MB), and warn once a file passes ~900 KB so growth is visible before
@@ -577,17 +577,20 @@ export class GistStateStore {
577
577
  * outcomes that previously collapsed into a single boolean (#1209 L9):
578
578
  * - `{ status: 'refreshed' }` — fresh data loaded successfully.
579
579
  * - `{ status: 'no-gist' }` — store not in Gist mode (e.g. degraded).
580
- * - `{ status: 'throttled', sinceLastMs }` — within the 30s throttle.
580
+ * - `{ status: 'throttled', sinceLastMs }` — within the 30s throttle
581
+ * (skipped when `options.force` is set).
581
582
  * - `{ status: 'error', error }` — fetch attempt failed.
582
583
  */
583
- async refreshFromGist() {
584
+ async refreshFromGist(options = {}) {
584
585
  if (!this.gistId)
585
586
  return { status: 'no-gist' };
586
587
  const now = Date.now();
587
588
  const sinceLastMs = now - this.lastRefreshAt;
588
589
  // Throttle hits are not failures — preserve any previous lastRefreshError
589
- // for the caller to inspect.
590
- if (sinceLastMs < GistStateStore.REFRESH_THROTTLE_MS) {
590
+ // for the caller to inspect. `force` bypasses the throttle for the
591
+ // conflict-recovery path: a retry that re-reads the same stale baseline
592
+ // fails identically (audit 2026-10-30 M1).
593
+ if (sinceLastMs < GistStateStore.REFRESH_THROTTLE_MS && !options.force) {
591
594
  return { status: 'throttled', sinceLastMs };
592
595
  }
593
596
  // Stamp the ATTEMPT, success or failure (#1443): the success-only stamp
@@ -19,11 +19,11 @@ export { DEFAULT_CONCURRENCY } from './concurrency.js';
19
19
  export { OssAutopilotError, ConfigurationError, ValidationError, GistPermissionError, ConcurrencyError, GistConcurrencyError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, errorMessage, getHttpStatusCode, isRateLimitError, isRateLimitOrAuthError, nonFatalCatch, resolveErrorCode, } from './errors.js';
20
20
  export { enableDebug, isDebugEnabled, debug, info, warn, timed } from './logger.js';
21
21
  export { HttpCache, getHttpCache, cachedRequest, type CacheEntry } from './http-cache.js';
22
- export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
22
+ export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
23
23
  export { computeContributionStats, type ContributionStats, type ComputeStatsInput } from './stats.js';
24
24
  export { fetchPRTemplate, type PRTemplateResult } from './pr-template.js';
25
25
  export { classifyLinkedPR, isLinkedPRStalled, STALLED_PR_THRESHOLD_DAYS, type LinkedPR, type LinkedPRClassification, type LinkedPRState, } from './linked-pr-classification.js';
26
- export { classifyIssueAvailability, fetchIssueVerification, verifyIssuesBatch, MAX_VERIFY_CONCURRENCY, type BatchVerificationResult, type IssueAvailabilityVerdict, type IssueVerification, type LinkedPRLinkType, type VerifiedLinkedPR, type VerifyIssueParams, } from './issue-verification.js';
26
+ export { classifyIssueAvailability, fetchIssueVerification, verifyIssuesBatch, MAX_VERIFY_CONCURRENCY, RULED_OUT_VERDICTS, type BatchVerificationResult, type IssueAvailabilityVerdict, type IssueVerification, type LinkedPRLinkType, type VerifiedLinkedPR, type VerifyIssueParams, } from './issue-verification.js';
27
27
  export { classifyAttentionBucket, summarizeAttentionBuckets, shouldSuggestClose, STUCK_CI_THRESHOLD_DAYS, DORMANT_FOLLOWUP_THRESHOLD_DAYS, type AttentionBucket, type AttentionInput, type AttentionSummary, } from './pr-attention.js';
28
28
  export { scanForAntiLLMPolicy, type AntiLLMCategory, type AntiLLMMatch, type AntiLLMScanResult, } from './anti-llm-policy.js';
29
29
  export { detectFormatters, diagnoseCIFormatterFailure, getPreferredFormatter, type DetectedFormatter, type FormatterDetectionResult, type CIFormatterDiagnosis, type FormatterName, } from './formatter-detection.js';
@@ -31,4 +31,4 @@ export { CONFIG_KEY_REGISTRY, type ConfigKeyDef, type SettableVia, isKnownKey, g
31
31
  export { DashboardDataSchema, DashboardStatsSchema, validateDashboardData, type DashboardDataParsed, } from './dashboard-data-schema.js';
32
32
  export { fetchPRCommentBundle, fetchPRCommentBundlesBatch, type PRCommentBundle, type PRReviewEntry, type PRReviewCommentEntry, type PRIssueCommentEntry, } from './pr-comments-fetcher.js';
33
33
  export * from './types.js';
34
- export { pickSnapshotFromVet, persistPickSnapshots } from './pick-snapshot.js';
34
+ export { pickSnapshotFromVet, persistPickSnapshots, traitsFromVerification, isFirstInRepo } from './pick-snapshot.js';
@@ -20,11 +20,11 @@ export { DEFAULT_CONCURRENCY } from './concurrency.js';
20
20
  export { OssAutopilotError, ConfigurationError, ValidationError, GistPermissionError, ConcurrencyError, GistConcurrencyError, GistFileSizeError, GIST_FILE_SIZE_REMEDY, errorMessage, getHttpStatusCode, isRateLimitError, isRateLimitOrAuthError, nonFatalCatch, resolveErrorCode, } from './errors.js';
21
21
  export { enableDebug, isDebugEnabled, debug, info, warn, timed } from './logger.js';
22
22
  export { HttpCache, getHttpCache, cachedRequest } from './http-cache.js';
23
- export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
23
+ export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
24
24
  export { computeContributionStats } from './stats.js';
25
25
  export { fetchPRTemplate } from './pr-template.js';
26
26
  export { classifyLinkedPR, isLinkedPRStalled, STALLED_PR_THRESHOLD_DAYS, } from './linked-pr-classification.js';
27
- export { classifyIssueAvailability, fetchIssueVerification, verifyIssuesBatch, MAX_VERIFY_CONCURRENCY, } from './issue-verification.js';
27
+ export { classifyIssueAvailability, fetchIssueVerification, verifyIssuesBatch, MAX_VERIFY_CONCURRENCY, RULED_OUT_VERDICTS, } from './issue-verification.js';
28
28
  export { classifyAttentionBucket, summarizeAttentionBuckets, shouldSuggestClose, STUCK_CI_THRESHOLD_DAYS, DORMANT_FOLLOWUP_THRESHOLD_DAYS, } from './pr-attention.js';
29
29
  export { scanForAntiLLMPolicy, } from './anti-llm-policy.js';
30
30
  export { detectFormatters, diagnoseCIFormatterFailure, getPreferredFormatter, } from './formatter-detection.js';
@@ -35,4 +35,4 @@ export { DashboardDataSchema, DashboardStatsSchema, validateDashboardData, } fro
35
35
  // silently drift (#1208 M5).
36
36
  export { fetchPRCommentBundle, fetchPRCommentBundlesBatch, } from './pr-comments-fetcher.js';
37
37
  export * from './types.js';
38
- export { pickSnapshotFromVet, persistPickSnapshots } from './pick-snapshot.js';
38
+ export { pickSnapshotFromVet, persistPickSnapshots, traitsFromVerification, isFirstInRepo } from './pick-snapshot.js';
@@ -46,6 +46,11 @@ export interface VerifiedLinkedPR {
46
46
  * - `available` — open, unassigned, no claiming PRs.
47
47
  */
48
48
  export type IssueAvailabilityVerdict = 'closed' | 'own-open-pr' | 'taken' | 'at-risk' | 'available';
49
+ /**
50
+ * Verdicts that conclusively rule an issue out as a new opportunity: nothing
51
+ * to grade, and no pick to record. Shared by `vet` and `vet-list`.
52
+ */
53
+ export declare const RULED_OUT_VERDICTS: ReadonlySet<IssueAvailabilityVerdict>;
49
54
  export interface IssueVerification {
50
55
  url: string;
51
56
  owner: string;
@@ -61,6 +66,13 @@ export interface IssueVerification {
61
66
  stateReason: 'completed' | 'not_planned' | 'reopened' | 'duplicate' | null;
62
67
  closedAt: string | null;
63
68
  assignees: string[];
69
+ /** Issue author login; null for ghost (deleted) accounts. */
70
+ author: string | null;
71
+ /** GitHub CommentAuthorAssociation of the issue author (OWNER, MEMBER, NONE, ...). */
72
+ authorAssociation: string | null;
73
+ /** The issue was opened by a GitHub App / bot account. */
74
+ authorIsBot: boolean;
75
+ commentCount: number | null;
64
76
  linkedPRs: VerifiedLinkedPR[];
65
77
  verdict: IssueAvailabilityVerdict;
66
78
  verdictReason: string;
@@ -16,6 +16,11 @@
16
16
  * "Taken" verdict.
17
17
  */
18
18
  import { ValidationError } from './errors.js';
19
+ /**
20
+ * Verdicts that conclusively rule an issue out as a new opportunity: nothing
21
+ * to grade, and no pick to record. Shared by `vet` and `vet-list`.
22
+ */
23
+ export const RULED_OUT_VERDICTS = new Set(['closed', 'taken', 'own-open-pr']);
19
24
  function isSameLogin(a, b) {
20
25
  return a !== null && a !== '' && b !== '' && a.toLowerCase() === b.toLowerCase();
21
26
  }
@@ -92,6 +97,14 @@ const VERIFY_ISSUE_QUERY = /* GraphQL */ `
92
97
  state
93
98
  stateReason
94
99
  closedAt
100
+ authorAssociation
101
+ author {
102
+ __typename
103
+ login
104
+ }
105
+ comments {
106
+ totalCount
107
+ }
95
108
  assignees(first: 10) {
96
109
  nodes {
97
110
  login
@@ -245,6 +258,7 @@ export async function fetchIssueVerification(octokit, params) {
245
258
  const state = issue.state.toLowerCase();
246
259
  const stateReason = (issue.stateReason?.toLowerCase() ?? null);
247
260
  const assignees = issue.assignees.nodes.flatMap((n) => (n ? [n.login] : []));
261
+ const issueAuthor = issue.author?.login ?? null;
248
262
  const { verdict, verdictReason } = classifyIssueAvailability({
249
263
  state,
250
264
  stateReason,
@@ -262,6 +276,10 @@ export async function fetchIssueVerification(octokit, params) {
262
276
  stateReason,
263
277
  closedAt: issue.closedAt,
264
278
  assignees,
279
+ author: issueAuthor,
280
+ authorAssociation: issue.authorAssociation ?? null,
281
+ authorIsBot: issue.author?.__typename === 'Bot' || (issueAuthor?.endsWith('[bot]') ?? false),
282
+ commentCount: issue.comments?.totalCount ?? null,
265
283
  linkedPRs,
266
284
  verdict,
267
285
  verdictReason,
@@ -4,14 +4,31 @@
4
4
  * the PR that closed the issue actually ended.
5
5
  */
6
6
  import type { VetOutput } from '../formatters/json.js';
7
+ import type { IssueVerification } from './issue-verification.js';
7
8
  import { type StateManager } from './state.js';
8
- import type { PickSnapshot } from './types.js';
9
+ import type { PickSnapshot, RepoScore, StoredMergedPR } from './types.js';
9
10
  /**
10
11
  * The prediction to keep for a vetted issue, or undefined when the user's own
11
12
  * PR is already linked: scout then grades the issue as taken, which is a
12
13
  * post-hoc verdict, not the prediction that picked it.
13
14
  */
14
- export declare function pickSnapshotFromVet(vet: VetOutput, source: PickSnapshot['source']): PickSnapshot | undefined;
15
+ export declare function pickSnapshotFromVet(vet: VetOutput, source: PickSnapshot['source'], traits?: PickTraits): PickSnapshot | undefined;
16
+ /** Vet-time facts the vet output itself does not carry. All optional: each is best-effort. */
17
+ export interface PickTraits {
18
+ /** GitHub author association of the issue author, raw (OWNER, NONE, ...). */
19
+ issueAuthorAssociation?: string;
20
+ issueAuthorIsBot?: boolean;
21
+ commentCount?: number;
22
+ /** Open, non-draft closing PRs by others, when the caller has a verification. */
23
+ competingPRs?: number;
24
+ /** Open PRs by others that only cross-reference the issue. */
25
+ mentioningPRs?: number;
26
+ firstInRepo?: boolean;
27
+ }
28
+ /** The pick traits a verification already carries, so a pick costs no extra API call. */
29
+ export declare function traitsFromVerification(v: IssueVerification): PickTraits;
30
+ /** True when neither the repo score nor the merged ledger shows a merged PR by the user in `repo`. */
31
+ export declare function isFirstInRepo(repo: string, repoScore: Pick<RepoScore, 'mergedPRCount'> | undefined, mergedPRs: ReadonlyArray<Pick<StoredMergedPR, 'url'>> | undefined): boolean;
15
32
  /**
16
33
  * Persist predictions without ever failing the vet that produced them. `vet`
17
34
  * used to be read-only, so a state save here can race another writer; that
@@ -15,10 +15,15 @@ const MODULE = 'pick-snapshot';
15
15
  // ponytail: scout reports only the first linked PR, so a standalone `vet` of an
16
16
  // issue whose first reference is someone else's PR can still miss the user's
17
17
  // own. First-wins in recordPickSnapshots limits this to never-vetted issues.
18
- export function pickSnapshotFromVet(vet, source) {
18
+ export function pickSnapshotFromVet(vet, source, traits = {}) {
19
19
  if (vet.linkedPRClassification?.startsWith('user_'))
20
20
  return undefined;
21
21
  const stars = vet.projectHealth?.stargazersCount;
22
+ // ponytail: when verification failed, scout's first linked PR gives a 0/1
23
+ // lower bound; callers pass the verified count otherwise.
24
+ const fromScout = vet.linkedPRClassification && Number(vet.linkedPRClassification === 'other_open');
25
+ const { competingPRs = fromScout, ...rest } = traits;
26
+ const recorded = Object.entries({ ...rest, competingPRs }).filter(([, value]) => value !== undefined);
22
27
  return {
23
28
  issueUrl: vet.issue.url,
24
29
  grade: vet.grade.score,
@@ -27,8 +32,29 @@ export function pickSnapshotFromVet(vet, source) {
27
32
  ...(typeof stars === 'number' && { stargazersCount: stars }),
28
33
  source,
29
34
  capturedAt: new Date().toISOString(),
35
+ labels: vet.issue.labels,
36
+ ...Object.fromEntries(recorded),
30
37
  };
31
38
  }
39
+ /** The pick traits a verification already carries, so a pick costs no extra API call. */
40
+ export function traitsFromVerification(v) {
41
+ const open = v.linkedPRs.filter((pr) => pr.state === 'open' && !pr.isOwn);
42
+ return {
43
+ ...(v.authorAssociation !== null && { issueAuthorAssociation: v.authorAssociation }),
44
+ issueAuthorIsBot: v.authorIsBot,
45
+ ...(v.commentCount !== null && { commentCount: v.commentCount }),
46
+ // Only a closing PR is a claim; a cross-reference is a mention (see issue-verification).
47
+ competingPRs: open.filter((pr) => pr.linkType === 'closing' && !pr.isDraft).length,
48
+ mentioningPRs: open.filter((pr) => pr.linkType === 'cross-referenced').length,
49
+ };
50
+ }
51
+ /** True when neither the repo score nor the merged ledger shows a merged PR by the user in `repo`. */
52
+ export function isFirstInRepo(repo, repoScore, mergedPRs) {
53
+ if ((repoScore?.mergedPRCount ?? 0) > 0)
54
+ return false;
55
+ const prefix = `https://github.com/${repo}/`.toLowerCase();
56
+ return (mergedPRs ?? []).every((pr) => !pr.url.toLowerCase().startsWith(prefix));
57
+ }
32
58
  /**
33
59
  * Persist predictions without ever failing the vet that produced them. `vet`
34
60
  * used to be read-only, so a state save here can race another writer; that
@@ -46,6 +72,6 @@ export async function persistPickSnapshots(stateManager, snapshots) {
46
72
  warn(MODULE, pickRecordError);
47
73
  return { pickRecordError };
48
74
  }
49
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
75
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.recordPickSnapshots(snapshots));
50
76
  return gistSyncWarning ? { gistSyncWarning } : {};
51
77
  }
@@ -152,12 +152,6 @@ export declare class PRMonitor {
152
152
  * @returns Daily digest with categorized PRs and summary stats
153
153
  */
154
154
  generateDigest(prs: FetchedPR[], recentlyClosedPRs?: ClosedPR[], recentlyMergedPRs?: MergedPR[]): DailyDigest;
155
- /**
156
- * Update repository scores based on observed PR (called when we detect merged/closed PRs).
157
- * @param repo - Repository in "owner/repo" format
158
- * @param wasMerged - true if the PR was merged, false if closed without merge
159
- */
160
- updateRepoScoreFromObservedPR(repo: string, wasMerged: boolean): Promise<void>;
161
155
  }
162
156
  interface RestTimelineEvent {
163
157
  event?: string;
@@ -592,19 +592,6 @@ export class PRMonitor {
592
592
  },
593
593
  };
594
594
  }
595
- /**
596
- * Update repository scores based on observed PR (called when we detect merged/closed PRs).
597
- * @param repo - Repository in "owner/repo" format
598
- * @param wasMerged - true if the PR was merged, false if closed without merge
599
- */
600
- async updateRepoScoreFromObservedPR(repo, wasMerged) {
601
- if (wasMerged) {
602
- this.stateManager.incrementMergedCount(repo);
603
- }
604
- else {
605
- this.stateManager.incrementClosedCount(repo);
606
- }
607
- }
608
595
  }
609
596
  /** Timeline event kinds whose actor marks maintainer engagement. */
610
597
  const ACTIVITY_TIMELINE_EVENTS = new Set(['head_ref_force_pushed', 'review_requested', 'labeled']);
@@ -35,19 +35,6 @@ export declare function getRepoScore(state: Readonly<AgentState>, repo: string):
35
35
  * numeric score is recalculated.
36
36
  */
37
37
  export declare function updateRepoScore(state: AgentState, repo: string, updates: RepoScoreUpdate): void;
38
- /**
39
- * Increment the merged PR count for a repository and recalculate its score.
40
- */
41
- export declare function incrementMergedCount(state: AgentState, repo: string): void;
42
- /**
43
- * Increment the closed-without-merge count for a repository and recalculate its score.
44
- */
45
- export declare function incrementClosedCount(state: AgentState, repo: string): void;
46
- /**
47
- * Mark a repository as having hostile maintainer comments and recalculate its score.
48
- * This applies a -2 penalty to the score. Creates a default score record if needed.
49
- */
50
- export declare function markRepoHostile(state: AgentState, repo: string): void;
51
38
  /**
52
39
  * Get repositories where the user has at least one merged PR, sorted by merged count descending.
53
40
  */
@@ -155,30 +155,6 @@ export function updateRepoScore(state, repo, updates) {
155
155
  }
156
156
  debug(MODULE, `Updated repo score for ${repo}: ${repoScore.score}/10`);
157
157
  }
158
- /**
159
- * Increment the merged PR count for a repository and recalculate its score.
160
- */
161
- export function incrementMergedCount(state, repo) {
162
- const newCount = (state.repoScores[repo]?.mergedPRCount ?? 0) + 1;
163
- updateRepoScore(state, repo, {
164
- mergedPRCount: newCount,
165
- lastMergedAt: new Date().toISOString(),
166
- });
167
- }
168
- /**
169
- * Increment the closed-without-merge count for a repository and recalculate its score.
170
- */
171
- export function incrementClosedCount(state, repo) {
172
- const newCount = (state.repoScores[repo]?.closedWithoutMergeCount ?? 0) + 1;
173
- updateRepoScore(state, repo, { closedWithoutMergeCount: newCount });
174
- }
175
- /**
176
- * Mark a repository as having hostile maintainer comments and recalculate its score.
177
- * This applies a -2 penalty to the score. Creates a default score record if needed.
178
- */
179
- export function markRepoHostile(state, repo) {
180
- updateRepoScore(state, repo, { signals: { hasHostileComments: true } });
181
- }
182
158
  /**
183
159
  * Get repositories where the user has at least one merged PR, sorted by merged count descending.
184
160
  */
@@ -25,20 +25,30 @@ export interface ReviewComment {
25
25
  * Only APPROVED, CHANGES_REQUESTED and DISMISSED change a reviewer's standing
26
26
  * verdict on GitHub. COMMENTED is also what GitHub records for every inline
27
27
  * reply, so it must not overwrite an earlier verdict from the same reviewer.
28
+ *
29
+ * Bot-authored reviews (e.g. an AI review bot posting APPROVE) are ignored so a
30
+ * bot alone never reads as maintainer approval or a changes request (#1840).
28
31
  */
29
32
  export declare function determineReviewDecision(reviews: Array<{
30
33
  state?: string | null;
31
34
  user?: {
32
35
  login?: string;
36
+ type?: string | null;
33
37
  } | null;
34
38
  }>): ReviewDecision;
35
39
  /**
36
- * Get the date of the latest CHANGES_REQUESTED review (from any reviewer).
40
+ * Get the date of the latest CHANGES_REQUESTED review (from any human reviewer).
37
41
  * Used to detect needs_changes status when review feedback is in inline comments.
42
+ * Bot reviews are skipped (#1840): a bot re-reviewing every push would otherwise
43
+ * move the date past the author's fix commit.
38
44
  */
39
45
  export declare function getLatestChangesRequestedDate(reviews: Array<{
40
46
  state?: string | null;
41
47
  submitted_at?: string | null;
48
+ user?: {
49
+ login?: string;
50
+ type?: string | null;
51
+ } | null;
42
52
  }>): string | undefined;
43
53
  /**
44
54
  * Check if all inline comments in a COMMENTED review are self-replies.
@@ -61,21 +71,15 @@ export declare function getInlineCommentBody(reviewId: number, reviewComments: R
61
71
  export declare function reviewHasInlineComments(reviewId: number, reviewComments: ReviewComment[]): boolean;
62
72
  /**
63
73
  * Earliest maintainer response timestamp across issue comments and submitted
64
- * reviews (#1461). A "response" is any comment or review by a non-bot
65
- * account other than the contributor — acknowledgments and approvals count,
66
- * since for latency purposes any human maintainer reply is a response.
67
- * Computed from data fetchPRDetails already holds in memory (zero extra API
68
- * calls). Returns undefined when no maintainer has responded yet.
74
+ * reviews (#1461). "Maintainer" is the same rule the dormancy clock uses
75
+ * ({@link isMaintainerEngagement}): issue comments count only from OWNER /
76
+ * MEMBER / COLLABORATOR (any non-bot non-contributor when the association is
77
+ * unknown), reviews from any non-bot non-contributor. Acknowledgments and
78
+ * approvals count. Returns undefined when no maintainer has responded yet.
69
79
  */
70
- export declare function getFirstMaintainerResponseAt(comments: Array<{
71
- user?: {
72
- login?: string;
73
- } | null;
80
+ export declare function getFirstMaintainerResponseAt(comments: Array<ActorFields & {
74
81
  created_at: string;
75
- }>, reviews: Array<{
76
- user?: {
77
- login?: string;
78
- } | null;
82
+ }>, reviews: Array<ActorFields & {
79
83
  submitted_at?: string | null;
80
84
  }>, username: string): string | undefined;
81
85
  /**
@@ -129,6 +133,22 @@ type ActorFields = {
129
133
  } | null;
130
134
  author_association?: string | null;
131
135
  };
136
+ /**
137
+ * Version of {@link isMaintainerEngagement}. Bump it when the rule changes so
138
+ * ledger-backfill recomputes stored `firstMaintainerResponseAt` values. Rule 1
139
+ * (implicit, unstamped) counted any non-author non-bot issue comment.
140
+ */
141
+ export declare const MAINTAINER_RESPONSE_RULE = 2;
142
+ /**
143
+ * Whether a comment or review counts as maintainer engagement. Shared by the
144
+ * dormancy clock ({@link getLastMaintainerActivity}, #1842) and first-response
145
+ * latency ({@link getFirstMaintainerResponseAt}) so both agree on who a
146
+ * maintainer is: never the contributor or a bot; an issue comment additionally
147
+ * needs an OWNER / MEMBER / COLLABORATOR association when one is known, so
148
+ * drive-by "+1"s don't count. Reviews and inline review comments count from
149
+ * any other account, since codeowners often show as CONTRIBUTOR.
150
+ */
151
+ export declare function isMaintainerEngagement(actor: ActorFields, username: string, kind: 'issue-comment' | 'review'): boolean;
132
152
  /**
133
153
  * Latest maintainer activity on a PR, falling back to `createdAt` when no
134
154
  * maintainer has engaged, plus the number of contributor pings since then.