@oss-autopilot/core 3.33.1 → 3.34.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.
@@ -66,7 +66,7 @@ export { applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacit
66
66
  // reuse it without crossing the commands → sibling-command boundary
67
67
  // (#1208 M7). Re-exported here for backward compatibility with anyone
68
68
  // importing from this module.
69
- import { buildStarFilter, firstMaintainerResponseFromDigest } from '../core/daily-logic.js';
69
+ import { buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest } from '../core/daily-logic.js';
70
70
  // ---------------------------------------------------------------------------
71
71
  // Phase functions
72
72
  // ---------------------------------------------------------------------------
@@ -674,6 +674,8 @@ async function executeDailyCheckInternal(token) {
674
674
  mergedAt: pr.mergedAt,
675
675
  openedAt: pr.openedAt,
676
676
  firstMaintainerResponseAt: firstMaintainerResponseFromDigest(previousDigest, pr.url),
677
+ issueUrl: pr.issueUrl,
678
+ ...lastReviewStateFromDigest(previousDigest, pr.url),
677
679
  })));
678
680
  }
679
681
  if (recentlyClosedPRs.length > 0) {
@@ -683,6 +685,8 @@ async function executeDailyCheckInternal(token) {
683
685
  closedAt: pr.closedAt,
684
686
  openedAt: pr.openedAt,
685
687
  firstMaintainerResponseAt: firstMaintainerResponseFromDigest(previousDigest, pr.url),
688
+ issueUrl: pr.issueUrl,
689
+ ...lastReviewStateFromDigest(previousDigest, pr.url),
686
690
  })));
687
691
  }
688
692
  });
@@ -3,7 +3,7 @@
3
3
  * Handles GitHub API calls, PR grouping, stats computation, and monthly chart data.
4
4
  * Consumed by the dashboard HTTP server (dashboard-server.ts) for the SPA API.
5
5
  */
6
- import { getStateManager, PRMonitor, IssueConversationMonitor, getOctokit, CRITICAL_STATUSES, applyStatusOverrides, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, } from '../core/index.js';
6
+ import { getStateManager, PRMonitor, IssueConversationMonitor, getOctokit, CRITICAL_STATUSES, applyStatusOverrides, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, } from '../core/index.js';
7
7
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
8
8
  import { warn } from '../core/logger.js';
9
9
  import { emptyPRCountsResult, fetchMergedPRsSince, fetchClosedPRsSince } from '../core/github-stats.js';
@@ -287,6 +287,7 @@ export async function fetchDashboardData(token) {
287
287
  const { dropped } = stateManager.addMergedPRs(newMergedPRs.map((pr) => ({
288
288
  ...pr,
289
289
  firstMaintainerResponseAt: pr.firstMaintainerResponseAt ?? firstMaintainerResponseFromDigest(previousDigest, pr.url),
290
+ ...lastReviewStateFromDigest(previousDigest, pr.url),
290
291
  })));
291
292
  if (dropped > 0) {
292
293
  partialFailures.push(`Dropped ${dropped} merged PR(s) with invalid URLs before persistence`);
@@ -302,6 +303,7 @@ export async function fetchDashboardData(token) {
302
303
  const { dropped } = stateManager.addClosedPRs(newClosedPRs.map((pr) => ({
303
304
  ...pr,
304
305
  firstMaintainerResponseAt: pr.firstMaintainerResponseAt ?? firstMaintainerResponseFromDigest(previousDigest, pr.url),
306
+ ...lastReviewStateFromDigest(previousDigest, pr.url),
305
307
  })));
306
308
  if (dropped > 0) {
307
309
  partialFailures.push(`Dropped ${dropped} closed PR(s) with invalid URLs before persistence`);
@@ -0,0 +1,11 @@
1
+ /**
2
+ * eval command (#1825): calibration and outcome metrics from the outcome
3
+ * ledger. Local-only: reads state, never calls GitHub. Run `ledger-backfill`
4
+ * first so historical entries carry close reasons and list vet scores.
5
+ */
6
+ import { type EvalReport } from '../core/eval-report.js';
7
+ export interface EvalOutput {
8
+ report: EvalReport;
9
+ markdown: string;
10
+ }
11
+ export declare function runEval(): Promise<EvalOutput>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * eval command (#1825): calibration and outcome metrics from the outcome
3
+ * ledger. Local-only: reads state, never calls GitHub. Run `ledger-backfill`
4
+ * first so historical entries carry close reasons and list vet scores.
5
+ */
6
+ import { computeEvalReport, formatEvalMarkdown } from '../core/eval-report.js';
7
+ import { getStateManager } from '../core/index.js';
8
+ export async function runEval() {
9
+ const report = computeEvalReport(getStateManager().getState());
10
+ return { report, markdown: formatEvalMarkdown(report) };
11
+ }
@@ -37,6 +37,7 @@ export { runVet } from './vet.js';
37
37
  export { runVerifyIssue, type VerifyIssueOptions } from './verify-issue.js';
38
38
  /** Re-vet all available issues in a curated issue list for freshness. */
39
39
  export { runVetList } from './vet-list.js';
40
+ export { runEval, type EvalOutput } from './eval.js';
40
41
  /** Fetch PR metadata from GitHub (informational; nothing is persisted). */
41
42
  export { runTrack } from './track.js';
42
43
  /** Score a PR against opensource.guide best practices via the typed core function (#1245). */
@@ -38,6 +38,7 @@ export { runVet } from './vet.js';
38
38
  export { runVerifyIssue } from './verify-issue.js';
39
39
  /** Re-vet all available issues in a curated issue list for freshness. */
40
40
  export { runVetList } from './vet-list.js';
41
+ export { runEval } from './eval.js';
41
42
  // ── PR Management ───────────────────────────────────────────────────────────
42
43
  /** Fetch PR metadata from GitHub (informational; nothing is persisted). */
43
44
  export { runTrack } from './track.js';
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Backfill the outcome ledger (#1824 step 2).
3
+ *
4
+ * Entries written before the ledger carried `openedAt`, `issueUrl`, `pick`
5
+ * and `closeReason` have none of them, so the eval report (#1825) would have
6
+ * no history to calibrate against. This fills what can still be recovered:
7
+ *
8
+ * - `openedAt` and `issueUrl` (GitHub's `closingIssuesReferences`) via
9
+ * batched GraphQL; each answered PR is stamped `backfilledAt` so later
10
+ * runs only query new entries.
11
+ * - `closeReason` for closed-unmerged entries, from who closed the PR and its
12
+ * last comments (core/close-reason.ts).
13
+ * - `pick` for entries with no vet-time snapshot, from the curated issue list
14
+ * and its sibling archives: an entry whose status line links the PR carries
15
+ * the vet score as `**Tier (N/10)**`.
16
+ *
17
+ * Only missing fields are filled (addMergedPRs/addClosedPRs never overwrite),
18
+ * so the command is safe to re-run; the weekly eval job runs it first.
19
+ */
20
+ export interface LedgerBackfillOutput {
21
+ /** Ledger PRs sent to GitHub because they had not been backfilled yet. */
22
+ queried: number;
23
+ /** Entries that gained each field in this run. */
24
+ filled: {
25
+ openedAt: number;
26
+ issueUrl: number;
27
+ closeReason: number;
28
+ pick: number;
29
+ };
30
+ /** Curated-list files scanned for vet scores. */
31
+ listFiles: string[];
32
+ /** PRs GitHub returned nothing for this run; retried next run. */
33
+ unresolved: number;
34
+ /** Partial failures: failed batches, missing PRs by error type, unreadable list files. */
35
+ warnings: string[];
36
+ gistSyncWarning?: string;
37
+ }
38
+ export declare function runLedgerBackfill(options?: {
39
+ issueListPath?: string;
40
+ }): Promise<LedgerBackfillOutput>;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Backfill the outcome ledger (#1824 step 2).
3
+ *
4
+ * Entries written before the ledger carried `openedAt`, `issueUrl`, `pick`
5
+ * and `closeReason` have none of them, so the eval report (#1825) would have
6
+ * no history to calibrate against. This fills what can still be recovered:
7
+ *
8
+ * - `openedAt` and `issueUrl` (GitHub's `closingIssuesReferences`) via
9
+ * batched GraphQL; each answered PR is stamped `backfilledAt` so later
10
+ * runs only query new entries.
11
+ * - `closeReason` for closed-unmerged entries, from who closed the PR and its
12
+ * last comments (core/close-reason.ts).
13
+ * - `pick` for entries with no vet-time snapshot, from the curated issue list
14
+ * and its sibling archives: an entry whose status line links the PR carries
15
+ * the vet score as `**Tier (N/10)**`.
16
+ *
17
+ * Only missing fields are filled (addMergedPRs/addClosedPRs never overwrite),
18
+ * so the command is safe to re-run; the weekly eval job runs it first.
19
+ */
20
+ import * as fs from 'node:fs';
21
+ import * as path from 'node:path';
22
+ import { classifyCloseReason } from '../core/close-reason.js';
23
+ import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
24
+ import { getOctokit, requireGitHubToken, getStateManager, parseGitHubUrl } from '../core/index.js';
25
+ import { isGraphqlRateLimited } from '../core/pr-graphql.js';
26
+ import { maybeCheckpoint } from '../core/state.js';
27
+ import { detectIssueListPath } from './locate-issue-list.js';
28
+ import { findListEntryUrlByPrUrl } from './merge-loop.js';
29
+ import { parseIssueList } from './parse-list.js';
30
+ const BATCH_SIZE = 40;
31
+ /** The curated list keeps issues scored at least this (see /oss-search's score filter). */
32
+ const LIST_KEEP_SCORE = 6;
33
+ const PR_FIELDS = `
34
+ createdAt
35
+ author { __typename login }
36
+ closingIssuesReferences(first: 1) { nodes { url } }
37
+ timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { actor { __typename login } } } }
38
+ comments(last: 5) { nodes { author { __typename login } body } }`;
39
+ /** One aliased GraphQL query for a batch of PR URLs. Fatal errors rethrow; null means the batch failed outright. */
40
+ async function fetchBatch(octokit, urls, warnings) {
41
+ const varDefs = [];
42
+ const selections = [];
43
+ const variables = {};
44
+ urls.forEach((url, i) => {
45
+ const ref = parseGitHubUrl(url);
46
+ if (!ref)
47
+ return;
48
+ varDefs.push(`$o${i}: String!, $r${i}: String!, $n${i}: Int!`);
49
+ Object.assign(variables, { [`o${i}`]: ref.owner, [`r${i}`]: ref.repo, [`n${i}`]: ref.number });
50
+ selections.push(`p${i}: repository(owner: $o${i}, name: $r${i}) { pullRequest(number: $n${i}) {${PR_FIELDS}} }`);
51
+ });
52
+ if (selections.length === 0)
53
+ return new Map();
54
+ const query = `query ledgerBackfill(${varDefs.join(', ')}) {\n${selections.join('\n')}\n}`;
55
+ let data;
56
+ try {
57
+ data = await octokit.graphql(query, variables);
58
+ }
59
+ catch (err) {
60
+ if (isRateLimitOrAuthError(err) || isGraphqlRateLimited(err))
61
+ throw err;
62
+ const partial = err.data;
63
+ if (!partial) {
64
+ warnings.push(`batch of ${urls.length} PRs failed: ${errorMessage(err)}`);
65
+ return null;
66
+ }
67
+ // Some aliases failed (repo deleted, made private, SSO-gated): count by type.
68
+ const types = new Map();
69
+ for (const e of err.errors ?? []) {
70
+ const type = e.type ?? 'ERROR';
71
+ types.set(type, (types.get(type) ?? 0) + 1);
72
+ }
73
+ warnings.push(`PRs GitHub did not return: ${[...types].map(([t, n]) => `${t} x${n}`).join(', ') || 'unknown'}`);
74
+ data = partial;
75
+ }
76
+ const out = new Map();
77
+ urls.forEach((url, i) => {
78
+ const node = data[`p${i}`]?.pullRequest;
79
+ if (node)
80
+ out.set(url, node);
81
+ });
82
+ return out;
83
+ }
84
+ /** The curated list plus sibling files sharing its name stem (`<stem>-archive-*.md`). */
85
+ function readListFiles(issueListPath, warnings) {
86
+ const dir = path.dirname(issueListPath);
87
+ const stem = path.basename(issueListPath, '.md');
88
+ return fs
89
+ .readdirSync(dir)
90
+ .filter((f) => f.startsWith(stem) && f.endsWith('.md'))
91
+ .sort()
92
+ .flatMap((f) => {
93
+ const file = path.join(dir, f);
94
+ try {
95
+ return [{ file, content: fs.readFileSync(file, 'utf8') }];
96
+ }
97
+ catch (err) {
98
+ warnings.push(`skipped list file ${file}: ${errorMessage(err)}`);
99
+ return [];
100
+ }
101
+ });
102
+ }
103
+ /** The list's vet score for the issue whose entry links `prUrl`, if any. */
104
+ function listPick(lists, prUrl) {
105
+ for (const { content } of lists) {
106
+ const issueUrl = findListEntryUrlByPrUrl(content, prUrl);
107
+ // The entry line's first URL can be a PR when an entry tracks one directly.
108
+ if (!issueUrl?.includes('/issues/'))
109
+ continue;
110
+ const parsed = parseIssueList(content);
111
+ const item = [...parsed.available, ...parsed.completed, ...parsed.blocked].find((i) => i.url === issueUrl && i.score !== undefined);
112
+ if (item?.score !== undefined) {
113
+ const recommendation = item.score >= LIST_KEEP_SCORE ? 'approve' : 'skip';
114
+ return { issueUrl, grade: item.score, recommendation, source: 'list' };
115
+ }
116
+ }
117
+ return undefined;
118
+ }
119
+ function countFilled(entries) {
120
+ return {
121
+ openedAt: entries.filter((e) => e.openedAt).length,
122
+ issueUrl: entries.filter((e) => e.issueUrl).length,
123
+ closeReason: entries.filter((e) => 'closeReason' in e && e.closeReason).length,
124
+ pick: entries.filter((e) => e.pick).length,
125
+ };
126
+ }
127
+ export async function runLedgerBackfill(options = {}) {
128
+ const stateManager = getStateManager();
129
+ const warnings = [];
130
+ // Lists first: a bad path should fail before any GitHub work.
131
+ if (options.issueListPath && !fs.existsSync(options.issueListPath)) {
132
+ throw new Error(`Issue list not found: ${options.issueListPath}`);
133
+ }
134
+ const listPath = options.issueListPath ?? detectIssueListPath()?.path;
135
+ if (!listPath)
136
+ warnings.push('no curated issue list found; list vet scores were not imported');
137
+ const lists = listPath ? readListFiles(listPath, warnings) : [];
138
+ // 1. GitHub: openedAt, closing issue, close reason, for entries not yet backfilled.
139
+ const needsFetch = [...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()]
140
+ .filter((e) => !e.backfilledAt)
141
+ .map((e) => e.url);
142
+ const nodes = new Map();
143
+ let fatal;
144
+ if (needsFetch.length > 0) {
145
+ const octokit = getOctokit(requireGitHubToken());
146
+ let failedBatches = 0;
147
+ for (let i = 0; i < needsFetch.length; i += BATCH_SIZE) {
148
+ try {
149
+ const batch = await fetchBatch(octokit, needsFetch.slice(i, i + BATCH_SIZE), warnings);
150
+ if (!batch)
151
+ failedBatches++;
152
+ for (const [url, node] of batch ?? [])
153
+ nodes.set(url, node);
154
+ }
155
+ catch (err) {
156
+ // Rate limit or auth: keep what earlier batches got, persist it, then rethrow.
157
+ fatal = err;
158
+ break;
159
+ }
160
+ }
161
+ if (!fatal && failedBatches === Math.ceil(needsFetch.length / BATCH_SIZE)) {
162
+ throw new Error(`Every GitHub batch failed: ${warnings.join('; ')}`);
163
+ }
164
+ }
165
+ // 2. Merge into fresh state: the GitHub phase can take a while, and upgrades
166
+ // only fill missing fields, so re-applying them to reloaded state is safe.
167
+ stateManager.reloadIfChanged();
168
+ const merged = stateManager.getMergedPRs();
169
+ const closed = stateManager.getClosedPRs();
170
+ const before = countFilled([...merged, ...closed]);
171
+ const snapshotFor = (issueUrl) => issueUrl && stateManager.getPickSnapshots().some((p) => p.issueUrl.toLowerCase() === issueUrl.toLowerCase());
172
+ const now = new Date().toISOString();
173
+ const recovered = (entry) => {
174
+ const node = nodes.get(entry.url);
175
+ const fromList = entry.pick ? undefined : listPick(lists, entry.url);
176
+ const issueUrl = node?.closingIssuesReferences?.nodes[0]?.url ?? entry.pick?.issueUrl ?? fromList?.issueUrl;
177
+ // A vet-time snapshot (joined by addMergedPRs/addClosedPRs) beats the list
178
+ // score, and a list score for a different issue than the PR closes is dropped.
179
+ const pick = fromList && fromList.issueUrl === issueUrl && !snapshotFor(issueUrl) ? fromList : undefined;
180
+ return { openedAt: node?.createdAt, issueUrl, pick, ...(node && { backfilledAt: now }) };
181
+ };
182
+ stateManager.batch(() => {
183
+ stateManager.addMergedPRs(merged.map((e) => ({ url: e.url, title: e.title, mergedAt: e.mergedAt, ...recovered(e) })));
184
+ stateManager.addClosedPRs(closed.map((e) => {
185
+ const node = nodes.get(e.url);
186
+ const closedEvent = node?.timelineItems?.nodes.at(-1);
187
+ // No closed event in the answer: leave the reason unset rather than guess.
188
+ const closeReason = closedEvent
189
+ ? classifyCloseReason({
190
+ author: node?.author?.login,
191
+ closer: closedEvent.actor?.login,
192
+ closerIsBot: closedEvent.actor?.__typename === 'Bot',
193
+ comments: (node?.comments?.nodes ?? []).flatMap((c) => c ? [{ author: c.author?.login, isBot: c.author?.__typename === 'Bot', body: c.body }] : []),
194
+ })
195
+ : undefined;
196
+ return { url: e.url, title: e.title, closedAt: e.closedAt, ...recovered(e), closeReason };
197
+ }));
198
+ });
199
+ const after = countFilled([...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()]);
200
+ const gistSyncWarning = await maybeCheckpoint(stateManager, 'ledger-backfill');
201
+ if (fatal)
202
+ throw fatal;
203
+ return {
204
+ queried: needsFetch.length,
205
+ filled: {
206
+ openedAt: after.openedAt - before.openedAt,
207
+ issueUrl: after.issueUrl - before.issueUrl,
208
+ closeReason: after.closeReason - before.closeReason,
209
+ pick: after.pick - before.pick,
210
+ },
211
+ listFiles: lists.map((l) => l.file),
212
+ unresolved: needsFetch.length - nodes.size,
213
+ warnings,
214
+ ...(gistSyncWarning && { gistSyncWarning }),
215
+ };
216
+ }
@@ -8,7 +8,7 @@ import { runParseList, pruneIssueList } from './parse-list.js';
8
8
  import { detectIssueList } from './startup.js';
9
9
  import { computeSuccessGrade, gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
10
10
  import { ValidationError } from '../core/errors.js';
11
- import { getStateManager, classifyLinkedPR, getOctokit, requireGitHubToken, parseGitHubUrl, verifyIssuesBatch, } from '../core/index.js';
11
+ import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, getOctokit, requireGitHubToken, parseGitHubUrl, verifyIssuesBatch, } from '../core/index.js';
12
12
  const UNKNOWN_GRADE = computeSuccessGrade({ avgResponseDays: null, mergeRate: null, daysSinceLastCommit: null });
13
13
  const KNOWN_SKIP_REASONS = new Set([
14
14
  'issue_closed',
@@ -200,8 +200,14 @@ export async function runVetList(options = {}) {
200
200
  verifyTargets.forEach((t, k) => verificationByIndex.set(t.index, batch[k]));
201
201
  // 3. Vet only the issues still in play; build each row.
202
202
  const scout = await createAutopilotScout();
203
- /** Run scout's grade/health vet for an issue (the search-driven path). */
204
- async function runScoutVet(item) {
203
+ // Vet-time predictions for calibration (#1824), recorded once after the fan-out.
204
+ const picks = [];
205
+ /**
206
+ * Run scout's grade/health vet for an issue (the search-driven path). `recordPick` is false on the
207
+ * verify-errored fallback: without verify's own-open-pr verdict, scout's
208
+ * linked-PR check can miss the user's own PR and record a post-hoc grade.
209
+ */
210
+ async function runScoutVet(item, recordPick) {
205
211
  const candidate = await scout.vetIssue(item.url);
206
212
  const grade = gradeFromCandidate({
207
213
  repo: candidate.issue.repo,
@@ -233,6 +239,9 @@ export async function runVetList(options = {}) {
233
239
  slmTriage: candidate.slmTriage ?? null,
234
240
  grade,
235
241
  };
242
+ const pick = recordPick ? pickSnapshotFromVet(vetResult, 'vet-list') : undefined;
243
+ if (pick)
244
+ picks.push(pick);
236
245
  return { vetResult, skipReason: extractSkipReason(candidate) };
237
246
  }
238
247
  function errorRow(item, error) {
@@ -272,7 +281,7 @@ export async function runVetList(options = {}) {
272
281
  : toMessage(verifyError),
273
282
  };
274
283
  try {
275
- const { vetResult, skipReason } = await runScoutVet(item);
284
+ const { vetResult, skipReason } = await runScoutVet(item, false);
276
285
  return { ...vetResult, listStatus: classifyListStatus(vetResult, skipReason), ...verifyErrorTag };
277
286
  }
278
287
  catch (error) {
@@ -289,7 +298,7 @@ export async function runVetList(options = {}) {
289
298
  // available / at-risk: still worth grading. The verdict stays authoritative
290
299
  // for listStatus; scout only supplies grade/health/recommendation.
291
300
  try {
292
- const { vetResult } = await runScoutVet(item);
301
+ const { vetResult } = await runScoutVet(item, true);
293
302
  return { ...vetResult, listStatus, verification: summary };
294
303
  }
295
304
  catch (error) {
@@ -308,6 +317,7 @@ export async function runVetList(options = {}) {
308
317
  // Start `concurrency` workers (bounds the scout-vet fan-out).
309
318
  const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => processNext());
310
319
  await Promise.all(workers);
320
+ const pickPersistence = await persistPickSnapshots(getStateManager(), picks);
311
321
  // 4. Compute summary
312
322
  const summary = {
313
323
  total: results.length,
@@ -340,5 +350,5 @@ export async function runVetList(options = {}) {
340
350
  pruneResult = { removedCount: 0, error: msg };
341
351
  }
342
352
  }
343
- return { results, summary, pruneResult };
353
+ return { results, summary, pruneResult, ...pickPersistence };
344
354
  }
@@ -5,7 +5,7 @@
5
5
  import { adaptScoutLinkedPR, buildCandidateLinkedPR, createAutopilotScout } from './scout-bridge.js';
6
6
  import { ISSUE_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';
7
7
  import { gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
8
- import { getStateManager, classifyLinkedPR } from '../core/index.js';
8
+ import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots } from '../core/index.js';
9
9
  /**
10
10
  * Vet a specific GitHub issue for claimability and project health.
11
11
  *
@@ -30,7 +30,7 @@ export async function runVet(options) {
30
30
  userLogin,
31
31
  });
32
32
  const linkedPR = buildCandidateLinkedPR(candidate.vettingResult.linkedPR);
33
- return {
33
+ const output = {
34
34
  issue: {
35
35
  repo: candidate.issue.repo,
36
36
  number: candidate.issue.number,
@@ -49,4 +49,6 @@ export async function runVet(options) {
49
49
  slmTriage: candidate.slmTriage ?? null,
50
50
  grade,
51
51
  };
52
+ const pick = pickSnapshotFromVet(output, 'vet');
53
+ return { ...output, ...(await persistPickSnapshots(getStateManager(), pick ? [pick] : [])) };
52
54
  }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Why a PR was closed without merging (#1824), classified from who closed it
3
+ * and its last few comments. Feeds the outcome ledger so the eval report can
4
+ * tell "superseded" from "maintainer rejected it" from "went stale".
5
+ *
6
+ * Only human, non-author comments count: review bots and welcome templates
7
+ * mention "AI" or "duplicate" constantly without meaning a closure reason.
8
+ *
9
+ * ponytail: keyword heuristics over the last comments. Swap in an LLM pass if
10
+ * `rejected` turns out to hide distinct causes worth separating.
11
+ */
12
+ export declare const CLOSE_REASONS: readonly ["ai-policy", "superseded", "stale", "self-closed", "rejected", "unknown"];
13
+ export type CloseReason = (typeof CLOSE_REASONS)[number];
14
+ export interface CloseContext {
15
+ author?: string;
16
+ /** Login of whoever closed the PR; undefined when GitHub reports no actor (ghost). */
17
+ closer?: string;
18
+ closerIsBot?: boolean;
19
+ comments: Array<{
20
+ author?: string;
21
+ isBot?: boolean;
22
+ body: string;
23
+ }>;
24
+ }
25
+ export declare function classifyCloseReason({ author, closer, closerIsBot, comments }: CloseContext): CloseReason;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Why a PR was closed without merging (#1824), classified from who closed it
3
+ * and its last few comments. Feeds the outcome ledger so the eval report can
4
+ * tell "superseded" from "maintainer rejected it" from "went stale".
5
+ *
6
+ * Only human, non-author comments count: review bots and welcome templates
7
+ * mention "AI" or "duplicate" constantly without meaning a closure reason.
8
+ *
9
+ * ponytail: keyword heuristics over the last comments. Swap in an LLM pass if
10
+ * `rejected` turns out to hide distinct causes worth separating.
11
+ */
12
+ export const CLOSE_REASONS = ['ai-policy', 'superseded', 'stale', 'self-closed', 'rejected', 'unknown'];
13
+ // Policy phrasing only: a bare "AI" or "Claude" shows up in ordinary review talk.
14
+ const AI_POLICY_RE = /\b(?:AI|LLM)[- ](?:generated|written|authored|slop|polic(?:y|ies))|(?:generated|written) (?:by|with) (?:an? )?(?:AI|LLM|ChatGPT|Copilot)\b|vibe[- ]?cod|machine[- ]generated/i;
15
+ const SUPERSEDED_RE = /clos(?:e|ing) (?:this )?as (?:a )?duplicate|duplicate of #\d+|superseded by|already (?:been )?(?:fixed|merged|addressed|resolved|implemented)|fixed (?:in|by|via) #\d+|in fav(?:ou)?r of #\d+/i;
16
+ const STALE_RE = /marked as stale|clos(?:e|ing) (?:this )?(?:as|due to) (?:stale|inactiv)|no activity (?:for|in)/i;
17
+ export function classifyCloseReason({ author, closer, closerIsBot, comments }) {
18
+ const human = comments.filter((c) => !c.isBot && c.author !== author).map((c) => c.body);
19
+ if (human.some((b) => AI_POLICY_RE.test(b)))
20
+ return 'ai-policy';
21
+ if (human.some((b) => SUPERSEDED_RE.test(b)))
22
+ return 'superseded';
23
+ if (closerIsBot || human.some((b) => STALE_RE.test(b)))
24
+ return 'stale';
25
+ if (!closer)
26
+ return 'unknown';
27
+ return closer === author ? 'self-closed' : 'rejected';
28
+ }
@@ -90,6 +90,18 @@ export declare function buildStarFilter(state: Readonly<AgentState>): StarFilter
90
90
  export declare function firstMaintainerResponseFromDigest(digest: {
91
91
  openPRs: FetchedPR[];
92
92
  } | undefined, url: string): string | undefined;
93
+ /**
94
+ * Review decision and CI status from the previous run's persisted digest for
95
+ * a just-merged/closed PR (#1824): the last state the PR was seen in while
96
+ * open. Same best-effort lookup and read-before-overwrite contract as
97
+ * {@link firstMaintainerResponseFromDigest}; empty when the PR never appeared.
98
+ */
99
+ export declare function lastReviewStateFromDigest(digest: {
100
+ openPRs: FetchedPR[];
101
+ } | undefined, url: string): {
102
+ lastReviewDecision?: string;
103
+ lastCiStatus?: string;
104
+ };
93
105
  /**
94
106
  * Group PRs by repository (#80).
95
107
  * Ensures one agent per repo during parallel dispatch, preventing branch checkout conflicts.
@@ -187,6 +187,16 @@ export function buildStarFilter(state) {
187
187
  export function firstMaintainerResponseFromDigest(digest, url) {
188
188
  return digest?.openPRs.find((pr) => pr.url === url)?.firstMaintainerResponseAt;
189
189
  }
190
+ /**
191
+ * Review decision and CI status from the previous run's persisted digest for
192
+ * a just-merged/closed PR (#1824): the last state the PR was seen in while
193
+ * open. Same best-effort lookup and read-before-overwrite contract as
194
+ * {@link firstMaintainerResponseFromDigest}; empty when the PR never appeared.
195
+ */
196
+ export function lastReviewStateFromDigest(digest, url) {
197
+ const pr = digest?.openPRs.find((p) => p.url === url);
198
+ return pr ? { lastReviewDecision: pr.reviewDecision, lastCiStatus: pr.ciStatus } : {};
199
+ }
190
200
  /**
191
201
  * Group PRs by repository (#80).
192
202
  * Ensures one agent per repo during parallel dispatch, preventing branch checkout conflicts.
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Eval report (#1825): is oss-autopilot picking better over time?
3
+ *
4
+ * Pure computation over the outcome ledger. Every merged, closed-unmerged and
5
+ * dormant PR is one outcome; the `pick` snapshot recorded at vet time (#1824)
6
+ * is the prediction it is compared against. Merge rate counts dormant PRs in
7
+ * the denominator, so stalled work cannot flatter the number.
8
+ */
9
+ import type { AgentState } from './types.js';
10
+ export interface EvalBucket {
11
+ key: string;
12
+ n: number;
13
+ merged: number;
14
+ closed: number;
15
+ dormant: number;
16
+ /** merged / n, rounded to 2 places; null when n is 0. */
17
+ mergeRate: number | null;
18
+ medianHoursToMerge: number | null;
19
+ medianHoursToFirstResponse: number | null;
20
+ }
21
+ export interface EvalReport {
22
+ generatedAt: string;
23
+ totals: EvalBucket;
24
+ headlines: {
25
+ /** Merge rate on repos with at least 1k stars. */
26
+ mergeRate1kStars: EvalBucket;
27
+ /**
28
+ * Vet-graded picks only (list scores are pre-filtered to 6+, so they can
29
+ * never land on the low side). `gap` is the grade >= 7 merge rate minus
30
+ * the grade <= 5 one, null until both sides have MIN_FLAG_N outcomes.
31
+ */
32
+ calibration: {
33
+ gap: number | null;
34
+ highN: number;
35
+ lowN: number;
36
+ };
37
+ /** Closures as ai-policy or rejected, per close month. */
38
+ approachClosuresByMonth: Record<string, number>;
39
+ };
40
+ byGrade: EvalBucket[];
41
+ byStars: EvalBucket[];
42
+ byMonth: EvalBucket[];
43
+ closeReasons: Record<string, number>;
44
+ quality: {
45
+ withReviewState: number;
46
+ changesRequestedShare: number | null;
47
+ ciFailingShare: number | null;
48
+ };
49
+ /** Vet-graded prediction/outcome pairs (merged + closed). */
50
+ calibrationPairs: number;
51
+ /** Buckets where prediction and outcome disagree. */
52
+ flags: string[];
53
+ }
54
+ export declare function computeEvalReport(state: Readonly<AgentState>, now?: Date): EvalReport;
55
+ export declare function formatEvalMarkdown(r: EvalReport): string;