@oss-autopilot/core 3.36.0 → 3.37.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.
@@ -6,7 +6,7 @@
6
6
  * Domain logic lives in src/core/daily-logic.ts; this file is a thin
7
7
  * orchestration layer that wires up the phases and handles I/O.
8
8
  */
9
- import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, } from '../core/index.js';
9
+ import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, } from '../core/index.js';
10
10
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
11
11
  import { wrapUntrustedContent } from '../core/untrusted-content.js';
12
12
  import { computeStrategy, shouldComputeStrategy } from '../core/strategy.js';
@@ -255,6 +255,22 @@ async function updateRepoScores(prMonitor, prs, mergedCounts, closedCounts, sear
255
255
  });
256
256
  warn(MODULE, `[CLOSED_COUNT_UPDATES_FAILED] ${closedCountFailures} of ${closedCounts.size} closed count update(s) failed.`);
257
257
  }
258
+ // Ledger-derived signals, recomputed each run for every scored repo so a
259
+ // corrected closeReason clears hostility and repos without samples reset to null.
260
+ const ledgerSignals = computeLedgerRepoSignals([...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()], prs);
261
+ for (const repo of Object.keys(stateManager.getState().repoScores)) {
262
+ const derived = ledgerSignals.get(repo);
263
+ const update = {
264
+ avgResponseDays: derived?.avgResponseDays ?? null,
265
+ signals: { hasHostileComments: derived?.hasHostileComments ?? false },
266
+ };
267
+ try {
268
+ stateManager.updateRepoScore(repo, update);
269
+ }
270
+ catch (error) {
271
+ warn(MODULE, `Failed to update ledger signals for ${repo}: ${errorMessage(error)}`);
272
+ }
273
+ }
258
274
  // Update repo signals from observed open PR data
259
275
  const repoSignals = computeRepoSignals(prs);
260
276
  let signalUpdateFailures = 0;
@@ -8,6 +8,12 @@
8
8
  * - `openedAt` and `issueUrl` (GitHub's `closingIssuesReferences`) via
9
9
  * batched GraphQL; each answered PR is stamped `backfilledAt` so later
10
10
  * runs only query new entries.
11
+ * - `firstMaintainerResponseAt` (earliest maintainer comment or review, by
12
+ * the dormancy clock's rule), which feeds each repo's `avgResponseDays`.
13
+ * Each lookup stamps `responseRule`; entries with an older or missing rule
14
+ * (never looked up, or recorded under the old any-non-author rule) are
15
+ * re-queried once and their value overwritten. When the first page has no
16
+ * maintainer response, later pages are fetched (up to RESPONSE_MAX_PAGES).
11
17
  * - `closeReason` for closed-unmerged entries, from who closed the PR and its
12
18
  * last comments (core/close-reason.ts).
13
19
  * - `pick` for entries with no vet-time snapshot, from the curated issue list
@@ -26,6 +32,7 @@ export interface LedgerBackfillOutput {
26
32
  issueUrl: number;
27
33
  closeReason: number;
28
34
  pick: number;
35
+ firstMaintainerResponseAt: number;
29
36
  };
30
37
  /** Curated-list files scanned for vet scores. */
31
38
  listFiles: string[];
@@ -8,6 +8,12 @@
8
8
  * - `openedAt` and `issueUrl` (GitHub's `closingIssuesReferences`) via
9
9
  * batched GraphQL; each answered PR is stamped `backfilledAt` so later
10
10
  * runs only query new entries.
11
+ * - `firstMaintainerResponseAt` (earliest maintainer comment or review, by
12
+ * the dormancy clock's rule), which feeds each repo's `avgResponseDays`.
13
+ * Each lookup stamps `responseRule`; entries with an older or missing rule
14
+ * (never looked up, or recorded under the old any-non-author rule) are
15
+ * re-queried once and their value overwritten. When the first page has no
16
+ * maintainer response, later pages are fetched (up to RESPONSE_MAX_PAGES).
11
17
  * - `closeReason` for closed-unmerged entries, from who closed the PR and its
12
18
  * last comments (core/close-reason.ts).
13
19
  * - `pick` for entries with no vet-time snapshot, from the curated issue list
@@ -23,6 +29,7 @@ import { classifyCloseReason, classifySelfClose } from '../core/close-reason.js'
23
29
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
24
30
  import { getOctokit, requireGitHubToken, getStateManager, parseGitHubUrl } from '../core/index.js';
25
31
  import { isGraphqlRateLimited } from '../core/pr-graphql.js';
32
+ import { getFirstMaintainerResponseAt, MAINTAINER_RESPONSE_RULE } from '../core/review-analysis.js';
26
33
  import { maybeCheckpoint } from '../core/state.js';
27
34
  import { detectIssueListPath } from './locate-issue-list.js';
28
35
  import { findListEntryUrlByPrUrl } from './merge-loop.js';
@@ -30,12 +37,101 @@ import { parseIssueList } from './parse-list.js';
30
37
  const BATCH_SIZE = 40;
31
38
  /** The curated list keeps issues scored at least this (see /oss-search's score filter). */
32
39
  const LIST_KEEP_SCORE = 6;
40
+ /** Comments and reviews fetched per page when looking for the first maintainer response. */
41
+ const RESPONSE_PAGE_SIZE = 10;
42
+ /**
43
+ * Pages of each scanned before a PR is recorded as unanswered.
44
+ * ponytail: a PR with 50+ non-maintainer comments and reviews before the
45
+ * first maintainer reply reads as unanswered; raise this if that shows up.
46
+ */
47
+ const RESPONSE_MAX_PAGES = 5;
48
+ const responseSelection = (isPaged) => `
49
+ firstComments: comments(first: ${RESPONSE_PAGE_SIZE}${isPaged ? `, after: $c` : ''}) {
50
+ pageInfo { hasNextPage endCursor } nodes { author { __typename login } authorAssociation createdAt } }
51
+ reviews(first: ${RESPONSE_PAGE_SIZE}${isPaged ? `, after: $rc` : ''}) {
52
+ pageInfo { hasNextPage endCursor } nodes { author { __typename login } submittedAt } }`;
33
53
  const PR_FIELDS = `
34
54
  createdAt
35
55
  author { __typename login }
36
56
  closingIssuesReferences(first: 1) { nodes { url } }
37
57
  timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { actor { __typename login } } } }
38
- comments(last: 5) { nodes { author { __typename login } body } }`;
58
+ comments(last: 5) { nodes { author { __typename login } body } }${responseSelection(false)}`;
59
+ const MORE_RESPONSES_QUERY = `query($o: String!, $r: String!, $n: Int!, $c: String, $rc: String) {
60
+ repository(owner: $o, name: $r) { pullRequest(number: $n) {${responseSelection(true)}} } }`;
61
+ /** GraphQL actor in the REST `user` shape; `type: 'Bot'` lets isBotAuthor drop bots without a `[bot]` suffix. */
62
+ const restUser = (a) => (a ? { login: a.login, type: a.__typename } : null);
63
+ /** Earliest maintainer comment or review, by the same rule as live enrichment and the dormancy clock. */
64
+ function firstResponseAt(node) {
65
+ const comments = (node.firstComments?.nodes ?? [])
66
+ .filter((c) => c !== null)
67
+ .map((c) => ({ user: restUser(c.author), author_association: c.authorAssociation, created_at: c.createdAt }));
68
+ const reviews = (node.reviews?.nodes ?? [])
69
+ .filter((r) => r !== null)
70
+ .map((r) => ({ user: restUser(r.author), submitted_at: r.submittedAt }));
71
+ return node.author?.login ? getFirstMaintainerResponseAt(comments, reviews, node.author.login) : undefined;
72
+ }
73
+ const hasMore = (node) => !!(node.firstComments?.pageInfo?.hasNextPage || node.reviews?.pageInfo?.hasNextPage);
74
+ /** The next page of comments and reviews after the cursors `node` holds. */
75
+ async function fetchNextResponsePage(octokit, ref, node) {
76
+ const data = await octokit.graphql(MORE_RESPONSES_QUERY, {
77
+ o: ref.owner,
78
+ r: ref.repo,
79
+ n: ref.number,
80
+ c: node.firstComments?.pageInfo?.endCursor ?? null,
81
+ rc: node.reviews?.pageInfo?.endCursor ?? null,
82
+ });
83
+ return data.repository?.pullRequest;
84
+ }
85
+ /**
86
+ * First maintainer response for `node`, fetching later comment/review pages
87
+ * while none is found and more exist. Returns `isPending` when a page fetch
88
+ * failed, so the entry is left for the next run instead of recorded as
89
+ * unanswered. Rate-limit and auth errors rethrow.
90
+ */
91
+ async function resolveFirstResponse(octokit, url, node, warnings) {
92
+ const ref = parseGitHubUrl(url);
93
+ let at = firstResponseAt(node);
94
+ for (let page = 1; !at && ref && page < RESPONSE_MAX_PAGES && hasMore(node); page++) {
95
+ let more;
96
+ try {
97
+ more = await fetchNextResponsePage(octokit, ref, node);
98
+ }
99
+ catch (err) {
100
+ if (isRateLimitOrAuthError(err) || isGraphqlRateLimited(err))
101
+ throw err;
102
+ warnings.push(`response lookup for ${url} failed: ${errorMessage(err)}`);
103
+ return { isPending: true };
104
+ }
105
+ if (!more)
106
+ return { isPending: true };
107
+ // Earlier pages held no response, so only the new page matters. An
108
+ // exhausted connection re-queried past its last cursor comes back empty.
109
+ node.firstComments = more.firstComments;
110
+ node.reviews = more.reviews;
111
+ at = firstResponseAt(node);
112
+ }
113
+ return { at, isPending: false };
114
+ }
115
+ /** Record each fetched node's first response (URL -> at) in `responses`; pending lookups are left out. */
116
+ async function resolveResponses(octokit, nodes, responses, warnings) {
117
+ if (!nodes)
118
+ return;
119
+ for (const [url, node] of nodes) {
120
+ const { at, isPending } = await resolveFirstResponse(octokit, url, node, warnings);
121
+ if (!isPending)
122
+ responses.set(url, at);
123
+ }
124
+ }
125
+ /** Lookups in `responses` that found a response. */
126
+ function countFound(responses) {
127
+ let found = 0;
128
+ for (const at of responses.values())
129
+ if (at)
130
+ found++;
131
+ return found;
132
+ }
133
+ /** True when the entry's first response was never computed under the current maintainer rule. */
134
+ const isResponseStale = (e) => e.responseRule !== MAINTAINER_RESPONSE_RULE;
39
135
  /** One aliased GraphQL query for a batch of PR URLs. Fatal errors rethrow; null means the batch failed outright. */
40
136
  async function fetchBatch(octokit, urls, warnings) {
41
137
  const varDefs = [];
@@ -135,15 +231,18 @@ export async function runLedgerBackfill(options = {}) {
135
231
  if (!listPath)
136
232
  warnings.push('no curated issue list found; list vet scores were not imported');
137
233
  const lists = listPath ? readListFiles(listPath, warnings) : [];
138
- // 1. GitHub: openedAt, closing issue, close reason, for entries not yet
139
- // backfilled, plus self-closed entries recorded before selfCloseReason existed.
234
+ // 1. GitHub: openedAt, closing issue, close reason, first response, for
235
+ // entries not yet backfilled, plus one-time re-fetches for fields added
236
+ // later: selfCloseReason on self-closed entries, and firstMaintainerResponseAt
237
+ // on entries not looked up under the current maintainer rule.
140
238
  const needsFetch = [
141
- ...stateManager.getMergedPRs().filter((e) => !e.backfilledAt),
239
+ ...stateManager.getMergedPRs().filter((e) => !e.backfilledAt || isResponseStale(e)),
142
240
  ...stateManager
143
241
  .getClosedPRs()
144
- .filter((e) => !e.backfilledAt || (e.closeReason === 'self-closed' && !e.selfCloseReason)),
242
+ .filter((e) => !e.backfilledAt || isResponseStale(e) || (e.closeReason === 'self-closed' && !e.selfCloseReason)),
145
243
  ].map((e) => e.url);
146
244
  const nodes = new Map();
245
+ const responses = new Map();
147
246
  let fatal;
148
247
  if (needsFetch.length > 0) {
149
248
  const octokit = getOctokit(requireGitHubToken());
@@ -155,6 +254,7 @@ export async function runLedgerBackfill(options = {}) {
155
254
  failedBatches++;
156
255
  for (const [url, node] of batch ?? [])
157
256
  nodes.set(url, node);
257
+ await resolveResponses(octokit, batch, responses, warnings);
158
258
  }
159
259
  catch (err) {
160
260
  // Rate limit or auth: keep what earlier batches got, persist it, then rethrow.
@@ -181,7 +281,12 @@ export async function runLedgerBackfill(options = {}) {
181
281
  // A vet-time snapshot (joined by addMergedPRs/addClosedPRs) beats the list
182
282
  // score, and a list score for a different issue than the PR closes is dropped.
183
283
  const pick = fromList && fromList.issueUrl === issueUrl && !snapshotFor(issueUrl) ? fromList : undefined;
184
- return { openedAt: node?.createdAt, issueUrl, pick, ...(node && { backfilledAt: now }) };
284
+ return {
285
+ openedAt: node?.createdAt,
286
+ issueUrl,
287
+ pick,
288
+ ...(node && { backfilledAt: now }),
289
+ };
185
290
  };
186
291
  stateManager.batch(() => {
187
292
  stateManager.addMergedPRs(merged.map((e) => ({ url: e.url, title: e.title, mergedAt: e.mergedAt, ...recovered(e) })));
@@ -201,6 +306,9 @@ export async function runLedgerBackfill(options = {}) {
201
306
  const selfCloseReason = context && (e.closeReason ?? closeReason) === 'self-closed' ? classifySelfClose(context) : undefined;
202
307
  return { url: e.url, title: e.title, closedAt: e.closedAt, ...recovered(e), closeReason, selfCloseReason };
203
308
  }));
309
+ // Overwrite, not fill-missing: a value recorded under an older rule is replaced.
310
+ for (const [url, at] of responses)
311
+ stateManager.setLedgerResponse(url, at, MAINTAINER_RESPONSE_RULE);
204
312
  });
205
313
  const after = countFilled([...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()]);
206
314
  const gistSyncWarning = await maybeCheckpoint(stateManager, 'ledger-backfill');
@@ -213,6 +321,8 @@ export async function runLedgerBackfill(options = {}) {
213
321
  issueUrl: after.issueUrl - before.issueUrl,
214
322
  closeReason: after.closeReason - before.closeReason,
215
323
  pick: after.pick - before.pick,
324
+ // Lookups that found a response (overwrites included), not a before/after delta.
325
+ firstMaintainerResponseAt: countFound(responses),
216
326
  },
217
327
  listFiles: lists.map((l) => l.file),
218
328
  unresolved: needsFetch.length - nodes.size,
@@ -9,7 +9,7 @@ import { detectIssueList } from './startup.js';
9
9
  import { computeSuccessGrade, gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
10
10
  import { repoCapField } from '../core/repo-cap.js';
11
11
  import { ValidationError } from '../core/errors.js';
12
- import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, getOctokit, requireGitHubToken, parseGitHubUrl, verifyIssuesBatch, } from '../core/index.js';
12
+ import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, traitsFromVerification, isFirstInRepo, getOctokit, requireGitHubToken, parseGitHubUrl, verifyIssuesBatch, RULED_OUT_VERDICTS, } from '../core/index.js';
13
13
  const UNKNOWN_GRADE = computeSuccessGrade({ avgResponseDays: null, mergeRate: null, daysSinceLastCommit: null });
14
14
  const KNOWN_SKIP_REASONS = new Set([
15
15
  'issue_closed',
@@ -119,12 +119,6 @@ export function listStatusFromVerdict(verdict) {
119
119
  }
120
120
  }
121
121
  }
122
- /**
123
- * Verdicts that conclusively rule an issue out as a new opportunity. For these
124
- * we skip scout's grade/health vet entirely — there is nothing to grade — and
125
- * build the result row straight from the verification.
126
- */
127
- const RULED_OUT_VERDICTS = new Set(['closed', 'taken', 'own-open-pr']);
128
122
  /** The per-row `verification` sub-object: the authoritative facts behind the
129
123
  * status, projected from the full {@link IssueVerification}. */
130
124
  function toVerificationSummary(v) {
@@ -204,11 +198,12 @@ export async function runVetList(options = {}) {
204
198
  // Vet-time predictions for calibration (#1824), recorded once after the fan-out.
205
199
  const picks = [];
206
200
  /**
207
- * Run scout's grade/health vet for an issue (the search-driven path). `recordPick` is false on the
208
- * verify-errored fallback: without verify's own-open-pr verdict, scout's
209
- * linked-PR check can miss the user's own PR and record a post-hoc grade.
201
+ * Run scout's grade/health vet for an issue (the search-driven path). A pick is
202
+ * recorded only with a `verification`: on the verify-errored fallback, without
203
+ * verify's own-open-pr verdict, scout's linked-PR check can miss the user's own
204
+ * PR and record a post-hoc grade.
210
205
  */
211
- async function runScoutVet(item, recordPick) {
206
+ async function runScoutVet(item, verification) {
212
207
  const candidate = await scout.vetIssue(item.url);
213
208
  const grade = gradeFromCandidate({
214
209
  repo: candidate.issue.repo,
@@ -241,9 +236,14 @@ export async function runVetList(options = {}) {
241
236
  grade,
242
237
  ...repoCapField(getStateManager().getState(), candidate.issue.repo),
243
238
  };
244
- const pick = recordPick ? pickSnapshotFromVet(vetResult, 'vet-list') : undefined;
245
- if (pick)
246
- picks.push(pick);
239
+ if (verification) {
240
+ const pick = pickSnapshotFromVet(vetResult, 'vet-list', {
241
+ ...traitsFromVerification(verification),
242
+ firstInRepo: isFirstInRepo(candidate.issue.repo, getStateManager().getRepoScore(candidate.issue.repo), getStateManager().getState().mergedPRs),
243
+ });
244
+ if (pick)
245
+ picks.push(pick);
246
+ }
247
247
  return { vetResult, skipReason: extractSkipReason(candidate) };
248
248
  }
249
249
  function errorRow(item, error) {
@@ -283,7 +283,7 @@ export async function runVetList(options = {}) {
283
283
  : toMessage(verifyError),
284
284
  };
285
285
  try {
286
- const { vetResult, skipReason } = await runScoutVet(item, false);
286
+ const { vetResult, skipReason } = await runScoutVet(item);
287
287
  return { ...vetResult, listStatus: classifyListStatus(vetResult, skipReason), ...verifyErrorTag };
288
288
  }
289
289
  catch (error) {
@@ -293,14 +293,15 @@ export async function runVetList(options = {}) {
293
293
  const v = verification.verification;
294
294
  const summary = toVerificationSummary(v);
295
295
  const listStatus = listStatusFromVerdict(v.verdict);
296
- // Conclusively ruled out — skip the scout vet entirely.
296
+ // Conclusively ruled out: skip the scout vet entirely and build the row
297
+ // straight from the verification.
297
298
  if (RULED_OUT_VERDICTS.has(v.verdict)) {
298
299
  return { ...ruledOutVetOutput(v), listStatus, verification: summary };
299
300
  }
300
301
  // available / at-risk: still worth grading. The verdict stays authoritative
301
302
  // for listStatus; scout only supplies grade/health/recommendation.
302
303
  try {
303
- const { vetResult } = await runScoutVet(item, true);
304
+ const { vetResult } = await runScoutVet(item, v);
304
305
  return { ...vetResult, listStatus, verification: summary };
305
306
  }
306
307
  catch (error) {
@@ -6,7 +6,7 @@ import { adaptScoutLinkedPR, buildCandidateLinkedPR, createAutopilotScout } from
6
6
  import { ISSUE_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';
7
7
  import { gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
8
8
  import { repoCapField } from '../core/repo-cap.js';
9
- import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots } from '../core/index.js';
9
+ import { getStateManager, getOctokit, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, fetchIssueVerification, RULED_OUT_VERDICTS, traitsFromVerification, isFirstInRepo, requireGitHubToken, errorMessage, warn, } from '../core/index.js';
10
10
  /**
11
11
  * Vet a specific GitHub issue for claimability and project health.
12
12
  *
@@ -51,6 +51,31 @@ export async function runVet(options) {
51
51
  grade,
52
52
  ...repoCapField(getStateManager().getState(), candidate.issue.repo),
53
53
  };
54
- const pick = pickSnapshotFromVet(output, 'vet');
54
+ const pick = await pickFor(output);
55
55
  return { ...output, ...(await persistPickSnapshots(getStateManager(), pick ? [pick] : [])) };
56
56
  }
57
+ /**
58
+ * The pick to record for this vet. One verify GraphQL call supplies the issue
59
+ * author, comment count and competing PRs, and applies vet-list's rule: no pick
60
+ * for a closed, taken or own-PR issue (scout's first-linked-PR check can miss these). A failed verify never fails the vet:
61
+ * the pick then falls back to scout's facts.
62
+ */
63
+ async function pickFor(output) {
64
+ if (output.linkedPRClassification?.startsWith('user_'))
65
+ return undefined;
66
+ const { repo, number, url } = output.issue;
67
+ const [owner, name] = repo.split('/', 2);
68
+ let verification;
69
+ try {
70
+ verification = await fetchIssueVerification(getOctokit(requireGitHubToken()), { repo: name, owner, number });
71
+ }
72
+ catch (error) {
73
+ warn('vet', `Could not verify ${url} for pick traits: ${errorMessage(error)}`);
74
+ }
75
+ if (verification && RULED_OUT_VERDICTS.has(verification.verdict))
76
+ return undefined;
77
+ return pickSnapshotFromVet(output, 'vet', {
78
+ ...(verification && traitsFromVerification(verification)),
79
+ firstInRepo: isFirstInRepo(repo, getStateManager().getRepoScore(repo), getStateManager().getState().mergedPRs),
80
+ });
81
+ }
@@ -119,6 +119,39 @@ export declare function groupPRsByRepo(prs: FetchedPR[]): RepoGroup[];
119
119
  * @returns Map of repo names to maintainer responsiveness signals
120
120
  */
121
121
  export declare function computeRepoSignals(prs: FetchedPR[]): Map<string, ComputedRepoSignals>;
122
+ /**
123
+ * Per-repo signals derived from the outcome ledger, recomputed each daily run
124
+ * so a corrected ledger entry corrects the score (no one-way latching):
125
+ * - avgResponseDays: MEDIAN days to first maintainer response (name kept for
126
+ * the schema; median so one forgotten PR doesn't skew it). Unanswered PRs
127
+ * are censored, not dropped, so a repo that ignores most PRs can't grade
128
+ * fast off the one it answered. Each PR opened in the last 12 months gives:
129
+ * - answered: openedAt -> firstMaintainerResponseAt
130
+ * - merged with no recorded response: openedAt -> mergedAt (the merge was
131
+ * the response; errs slow, since any earlier reply went unrecorded)
132
+ * - closed and confirmed unanswered under the current maintainer rule
133
+ * (responseRule), except self-closes: openedAt -> closedAt, a lower bound
134
+ * - open and still waiting: createdAt -> now, a lower bound
135
+ * Lower bounds count only from 14 days (CENSORED_MIN_DAYS): a PR opened
136
+ * yesterday or closed within days says nothing yet and would grade fast.
137
+ * Null below 3 samples.
138
+ * - hasHostileComments: any closed PR here has closeReason 'ai-policy'.
139
+ *
140
+ * Repos with no ledger or open PR data are absent; callers treat absent as
141
+ * `{ avgResponseDays: null, hasHostileComments: false }`.
142
+ */
143
+ export declare function computeLedgerRepoSignals(ledger: ReadonlyArray<{
144
+ url: string;
145
+ openedAt?: string;
146
+ firstMaintainerResponseAt?: string;
147
+ mergedAt?: string;
148
+ closedAt?: string;
149
+ responseRule?: number;
150
+ closeReason?: string;
151
+ }>, openPRs: ReadonlyArray<Pick<FetchedPR, 'url' | 'createdAt' | 'firstMaintainerResponseAt'>>, nowMs?: number): Map<string, {
152
+ avgResponseDays: number | null;
153
+ hasHostileComments: boolean;
154
+ }>;
122
155
  /**
123
156
  * Assess whether user has capacity for new issues.
124
157
  * Only active (non-shelved) PRs count against the limit.
@@ -17,6 +17,8 @@
17
17
  import { warn } from './logger.js';
18
18
  import { errorMessage } from './errors.js';
19
19
  import { getStateManager } from './state.js';
20
+ import { parseGitHubUrl } from './urls.js';
21
+ import { MAINTAINER_RESPONSE_RULE } from './review-analysis.js';
20
22
  // ---------------------------------------------------------------------------
21
23
  // Constants
22
24
  // ---------------------------------------------------------------------------
@@ -230,6 +232,106 @@ export function computeRepoSignals(prs) {
230
232
  }
231
233
  return result;
232
234
  }
235
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
236
+ /** Fewer samples than this and avgResponseDays stays null (unknown). */
237
+ const MIN_RESPONSE_SAMPLES = 3;
238
+ /** Only PRs opened within this window feed avgResponseDays. */
239
+ const RESPONSE_WINDOW_DAYS = 365;
240
+ /**
241
+ * A lower bound (unanswered PR) counts only at or above this many days: the
242
+ * top of the 7-point band in issue-grading's gradeResponsiveness. A shorter
243
+ * wait says nothing about the repo yet and would only pull the median fast.
244
+ */
245
+ const CENSORED_MIN_DAYS = 14;
246
+ const toMs = (t) => (t ? Date.parse(t) : undefined);
247
+ /** Days from `openedAt` to `endMs`, or undefined when unusable or opened before `windowStart`. */
248
+ function responseDays(openedAt, endMs, windowStart) {
249
+ if (endMs === undefined || !openedAt)
250
+ return undefined;
251
+ const startMs = Date.parse(openedAt);
252
+ if (startMs < windowStart)
253
+ return undefined;
254
+ const days = (endMs - startMs) / MS_PER_DAY;
255
+ return Number.isFinite(days) && days >= 0 ? days : undefined;
256
+ }
257
+ /** Where a ledger entry's response sample ends, and whether that end is only a lower bound. */
258
+ function ledgerSampleEnd(e) {
259
+ // mergedAt stands in when no response was recorded; it errs slow.
260
+ const exact = toMs(e.firstMaintainerResponseAt) ?? toMs(e.mergedAt);
261
+ if (exact !== undefined)
262
+ return { endMs: exact, isLowerBound: false };
263
+ const isConfirmedUnanswered = e.responseRule === MAINTAINER_RESPONSE_RULE && e.closeReason !== 'self-closed';
264
+ return { endMs: isConfirmedUnanswered ? toMs(e.closedAt) : undefined, isLowerBound: true };
265
+ }
266
+ /** Median of `values` (sorts in place), or null with fewer than `minCount`. */
267
+ function medianOf(values, minCount) {
268
+ if (values.length < minCount)
269
+ return null;
270
+ values.sort((a, b) => a - b);
271
+ const mid = Math.floor(values.length / 2);
272
+ if (values.length % 2 === 1)
273
+ return values[mid];
274
+ return (values[mid - 1] + values[mid]) / 2;
275
+ }
276
+ /**
277
+ * Per-repo signals derived from the outcome ledger, recomputed each daily run
278
+ * so a corrected ledger entry corrects the score (no one-way latching):
279
+ * - avgResponseDays: MEDIAN days to first maintainer response (name kept for
280
+ * the schema; median so one forgotten PR doesn't skew it). Unanswered PRs
281
+ * are censored, not dropped, so a repo that ignores most PRs can't grade
282
+ * fast off the one it answered. Each PR opened in the last 12 months gives:
283
+ * - answered: openedAt -> firstMaintainerResponseAt
284
+ * - merged with no recorded response: openedAt -> mergedAt (the merge was
285
+ * the response; errs slow, since any earlier reply went unrecorded)
286
+ * - closed and confirmed unanswered under the current maintainer rule
287
+ * (responseRule), except self-closes: openedAt -> closedAt, a lower bound
288
+ * - open and still waiting: createdAt -> now, a lower bound
289
+ * Lower bounds count only from 14 days (CENSORED_MIN_DAYS): a PR opened
290
+ * yesterday or closed within days says nothing yet and would grade fast.
291
+ * Null below 3 samples.
292
+ * - hasHostileComments: any closed PR here has closeReason 'ai-policy'.
293
+ *
294
+ * Repos with no ledger or open PR data are absent; callers treat absent as
295
+ * `{ avgResponseDays: null, hasHostileComments: false }`.
296
+ */
297
+ export function computeLedgerRepoSignals(ledger, openPRs, nowMs = Date.now()) {
298
+ const byRepo = new Map();
299
+ const windowStart = nowMs - RESPONSE_WINDOW_DAYS * MS_PER_DAY;
300
+ const add = (url, openedAt, endMs, isLowerBound, closeReason) => {
301
+ const ref = parseGitHubUrl(url);
302
+ if (!ref)
303
+ return;
304
+ const repo = `${ref.owner}/${ref.repo}`;
305
+ const entry = byRepo.get(repo) ?? { samples: [], hostile: false };
306
+ byRepo.set(repo, entry);
307
+ if (closeReason === 'ai-policy')
308
+ entry.hostile = true;
309
+ const days = responseDays(openedAt, endMs, windowStart);
310
+ if (days !== undefined && (!isLowerBound || days >= CENSORED_MIN_DAYS))
311
+ entry.samples.push(days);
312
+ };
313
+ const seen = new Set();
314
+ for (const e of ledger) {
315
+ seen.add(e.url);
316
+ const { endMs, isLowerBound } = ledgerSampleEnd(e);
317
+ add(e.url, e.openedAt, endMs, isLowerBound, e.closeReason);
318
+ }
319
+ for (const pr of openPRs) {
320
+ if (seen.has(pr.url))
321
+ continue;
322
+ const exact = toMs(pr.firstMaintainerResponseAt);
323
+ add(pr.url, pr.createdAt, exact ?? nowMs, exact === undefined);
324
+ }
325
+ const result = new Map();
326
+ for (const [repo, { samples, hostile }] of byRepo) {
327
+ const median = medianOf(samples, MIN_RESPONSE_SAMPLES);
328
+ result.set(repo, {
329
+ avgResponseDays: median === null ? null : Math.round(median * 10) / 10,
330
+ hasHostileComments: hostile,
331
+ });
332
+ }
333
+ return result;
334
+ }
233
335
  /**
234
336
  * Assess whether user has capacity for new issues.
235
337
  * Only active (non-shelved) PRs count against the limit.
@@ -40,6 +40,14 @@ export interface EvalReport {
40
40
  byGrade: EvalBucket[];
41
41
  byStars: EvalBucket[];
42
42
  byMonth: EvalBucket[];
43
+ /** All outcomes: first PR in the repo vs returning. */
44
+ byFirstInRepo: EvalBucket[];
45
+ /** Picks only; picks recorded before the trait existed land in `not recorded`. */
46
+ byIssueAuthorRole: EvalBucket[];
47
+ /** Picks only: open PRs by others on the issue at pick time. */
48
+ byCompetingPRs: EvalBucket[];
49
+ /** Picks with labels only; one pick can count in several label groups. */
50
+ byLabel: EvalBucket[];
43
51
  closeReasons: Record<string, number>;
44
52
  quality: {
45
53
  withReviewState: number;