@oss-autopilot/core 3.33.1 → 3.35.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.
@@ -0,0 +1,213 @@
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
+ const HOUR = 3_600_000;
10
+ /** Minimum bucket size before a flag is raised. */
11
+ const MIN_FLAG_N = 5;
12
+ function repoOf(url) {
13
+ return url.split('/').slice(3, 5).join('/');
14
+ }
15
+ function hoursBetween(from, to) {
16
+ if (!from || !to)
17
+ return undefined;
18
+ const ms = Date.parse(to) - Date.parse(from);
19
+ return Number.isFinite(ms) && ms >= 0 ? ms / HOUR : undefined;
20
+ }
21
+ function median(values) {
22
+ if (values.length === 0)
23
+ return null;
24
+ const sorted = [...values].sort((a, b) => a - b);
25
+ const mid = Math.floor(sorted.length / 2);
26
+ const m = sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
27
+ return Math.round(m * 10) / 10;
28
+ }
29
+ function rate(part, whole) {
30
+ return whole === 0 ? null : Math.round((part / whole) * 100) / 100;
31
+ }
32
+ function bucket(key, rows) {
33
+ const count = (o) => rows.filter((r) => r.outcome === o).length;
34
+ const merged = count('merged');
35
+ return {
36
+ key,
37
+ n: rows.length,
38
+ merged,
39
+ closed: count('closed'),
40
+ dormant: count('dormant'),
41
+ mergeRate: rate(merged, rows.length),
42
+ medianHoursToMerge: median(rows.flatMap((r) => (r.hoursToMerge === undefined ? [] : [r.hoursToMerge]))),
43
+ medianHoursToFirstResponse: median(rows.flatMap((r) => (r.hoursToFirstResponse === undefined ? [] : [r.hoursToFirstResponse]))),
44
+ };
45
+ }
46
+ /** Group rows by a key function, keeping `order` first and dropping empty groups. */
47
+ function groupBy(rows, keyOf, order = []) {
48
+ const groups = new Map(order.map((k) => [k, []]));
49
+ for (const r of rows) {
50
+ const k = keyOf(r);
51
+ if (!groups.has(k))
52
+ groups.set(k, []);
53
+ groups.get(k).push(r);
54
+ }
55
+ return [...groups].filter(([, g]) => g.length > 0).map(([k, g]) => bucket(k, g));
56
+ }
57
+ function gradeRange(grade) {
58
+ if (grade === undefined)
59
+ return 'none';
60
+ if (grade <= 4)
61
+ return '1-4';
62
+ if (grade <= 6)
63
+ return '5-6';
64
+ if (grade <= 8)
65
+ return '7-8';
66
+ return '9-10';
67
+ }
68
+ function starRange(stars) {
69
+ if (stars === undefined)
70
+ return 'unknown';
71
+ if (stars < 100)
72
+ return '<100';
73
+ if (stars < 1000)
74
+ return '100-1k';
75
+ if (stars < 10_000)
76
+ return '1k-10k';
77
+ return '10k+';
78
+ }
79
+ function collectRows(state) {
80
+ const starsOf = (repo) => state.repoScores[repo]?.stargazersCount;
81
+ const common = (e) => {
82
+ const repo = repoOf(e.url);
83
+ return {
84
+ url: e.url,
85
+ repo,
86
+ grade: e.pick?.grade,
87
+ gradeSource: e.pick ? (e.pick.source === 'list' ? 'list' : 'vet') : undefined,
88
+ stars: e.pick?.stargazersCount ?? starsOf(repo),
89
+ hoursToFirstResponse: hoursBetween(e.openedAt, e.firstMaintainerResponseAt),
90
+ changesRequested: e.lastReviewDecision ? e.lastReviewDecision === 'changes_requested' : undefined,
91
+ ciFailing: e.lastCiStatus ? e.lastCiStatus === 'failing' : undefined,
92
+ };
93
+ };
94
+ const merged = (state.mergedPRs ?? []).map((e) => ({
95
+ ...common(e),
96
+ outcome: 'merged',
97
+ month: e.mergedAt.slice(0, 7),
98
+ hoursToMerge: hoursBetween(e.openedAt, e.mergedAt),
99
+ }));
100
+ const closed = (state.closedPRs ?? []).map((e) => ({
101
+ ...common(e),
102
+ outcome: 'closed',
103
+ month: e.closedAt.slice(0, 7),
104
+ closeReason: e.closeReason,
105
+ selfCloseReason: e.selfCloseReason,
106
+ }));
107
+ const dormant = (state.lastDigest?.openPRs ?? [])
108
+ .filter((pr) => pr.stalenessTier === 'dormant')
109
+ .map((pr) => ({ url: pr.url, repo: pr.repo, outcome: 'dormant', stars: starsOf(pr.repo) }));
110
+ return [...merged, ...closed, ...dormant];
111
+ }
112
+ const pct = (v) => (v === null ? 'n/a' : `${Math.round(v * 100)}%`);
113
+ const hrs = (v) => (v === null ? 'n/a' : `${v}h`);
114
+ export function computeEvalReport(state, now = new Date()) {
115
+ const rows = collectRows(state);
116
+ const graded = rows.filter((r) => r.gradeSource === 'vet' && r.outcome !== 'dormant');
117
+ const high = graded.filter((r) => r.grade >= 7);
118
+ const low = graded.filter((r) => r.grade <= 5);
119
+ const mergedShare = (g) => g.filter((r) => r.outcome === 'merged').length / g.length;
120
+ const separable = high.length >= MIN_FLAG_N && low.length >= MIN_FLAG_N;
121
+ const gap = separable ? Math.round((mergedShare(high) - mergedShare(low)) * 100) / 100 : null;
122
+ const closedRows = rows.filter((r) => r.outcome === 'closed');
123
+ const closeReasons = {};
124
+ const approachClosuresByMonth = {};
125
+ for (const r of closedRows) {
126
+ // Self-closed splits by what preceded it, e.g. "self-closed: no-response".
127
+ const reason = r.selfCloseReason ? `self-closed: ${r.selfCloseReason}` : (r.closeReason ?? 'unclassified');
128
+ closeReasons[reason] = (closeReasons[reason] ?? 0) + 1;
129
+ if ((r.closeReason === 'ai-policy' || r.closeReason === 'rejected') && r.month) {
130
+ approachClosuresByMonth[r.month] = (approachClosuresByMonth[r.month] ?? 0) + 1;
131
+ }
132
+ }
133
+ const reviewed = rows.filter((r) => r.changesRequested !== undefined);
134
+ const ciKnown = rows.filter((r) => r.ciFailing !== undefined);
135
+ const byGrade = groupBy(rows, (r) => (r.gradeSource ? `${r.gradeSource} ${gradeRange(r.grade)}` : 'no prediction'), [
136
+ 'vet 9-10',
137
+ 'vet 7-8',
138
+ 'vet 5-6',
139
+ 'vet 1-4',
140
+ 'list 9-10',
141
+ 'list 7-8',
142
+ 'list 5-6',
143
+ 'list 1-4',
144
+ 'no prediction',
145
+ ]);
146
+ const flags = byGrade
147
+ .filter((b) => /(?:9-10|7-8)$/.test(b.key) && b.n >= MIN_FLAG_N && (b.mergeRate ?? 1) < 0.6)
148
+ .map((b) => `${b.key}: high-grade picks merge at ${Math.round(b.mergeRate * 100)}% (n=${b.n})`);
149
+ if (gap !== null && gap <= 0) {
150
+ flags.push(`vet grades do not separate outcomes: grade>=7 merges at ${pct(rate(high.filter((r) => r.outcome === 'merged').length, high.length))} (n=${high.length}), grade<=5 at ${pct(rate(low.filter((r) => r.outcome === 'merged').length, low.length))} (n=${low.length})`);
151
+ }
152
+ return {
153
+ generatedAt: now.toISOString(),
154
+ totals: bucket('all', rows),
155
+ headlines: {
156
+ mergeRate1kStars: bucket('>=1k stars', rows.filter((r) => (r.stars ?? 0) >= 1000)),
157
+ calibration: { gap, highN: high.length, lowN: low.length },
158
+ approachClosuresByMonth,
159
+ },
160
+ byGrade,
161
+ byStars: groupBy(rows, (r) => starRange(r.stars), ['10k+', '1k-10k', '100-1k', '<100', 'unknown']),
162
+ byMonth: groupBy(rows.filter((r) => r.month), (r) => r.month).sort((a, b) => b.key.localeCompare(a.key)),
163
+ closeReasons,
164
+ quality: {
165
+ withReviewState: reviewed.length,
166
+ changesRequestedShare: rate(reviewed.filter((r) => r.changesRequested).length, reviewed.length),
167
+ ciFailingShare: rate(ciKnown.filter((r) => r.ciFailing).length, ciKnown.length),
168
+ },
169
+ calibrationPairs: graded.length,
170
+ flags,
171
+ };
172
+ }
173
+ function table(title, buckets) {
174
+ return [
175
+ `## ${title}`,
176
+ '',
177
+ '| Bucket | n | Merged | Closed | Dormant | Merge rate | Median to merge | Median to first response |',
178
+ '|---|---|---|---|---|---|---|---|',
179
+ ...buckets.map((b) => `| ${b.key} | ${b.n} | ${b.merged} | ${b.closed} | ${b.dormant} | ${pct(b.mergeRate)} | ${hrs(b.medianHoursToMerge)} | ${hrs(b.medianHoursToFirstResponse)} |`),
180
+ '',
181
+ ];
182
+ }
183
+ export function formatEvalMarkdown(r) {
184
+ const h = r.headlines;
185
+ const recentMonths = Object.keys(h.approachClosuresByMonth).sort().reverse().slice(0, 6);
186
+ return [
187
+ `# oss-autopilot eval (${r.generatedAt.slice(0, 10)})`,
188
+ '',
189
+ '## Headlines',
190
+ '',
191
+ `- Merge rate on repos with 1k+ stars: **${pct(h.mergeRate1kStars.mergeRate)}** (n=${h.mergeRate1kStars.n})`,
192
+ `- 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)`,
193
+ `- Approach or AI-policy closures by month: ${recentMonths.length ? recentMonths.map((m) => `${m}: ${h.approachClosuresByMonth[m]}`).join(', ') : 'none'}`,
194
+ `- Overall: ${r.totals.n} outcomes, merge rate ${pct(r.totals.mergeRate)} (dormant counted as not merged)`,
195
+ '',
196
+ ...(r.flags.length ? ['## Flags', '', ...r.flags.map((f) => `- ${f}`), ''] : []),
197
+ ...table('By grade at pick time', r.byGrade),
198
+ ...table('By repo stars', r.byStars),
199
+ ...table('By month', r.byMonth.slice(0, 12)),
200
+ '## Close reasons',
201
+ '',
202
+ ...Object.entries(r.closeReasons)
203
+ .sort((a, b) => b[1] - a[1])
204
+ .map(([k, v]) => `- ${k}: ${v}`),
205
+ '',
206
+ '## Review quality',
207
+ '',
208
+ `- PRs with a recorded review state: ${r.quality.withReviewState}`,
209
+ `- Changes requested before the outcome: ${pct(r.quality.changesRequestedShare)}`,
210
+ `- CI failing at last sight: ${pct(r.quality.ciFailingShare)}`,
211
+ '',
212
+ ].join('\n');
213
+ }
@@ -46,7 +46,7 @@
46
46
  * a freeform-only push needs no re-read and cannot clobber another file.
47
47
  */
48
48
  import * as fs from 'node:fs';
49
- import { AgentStateSchema } from './state-schema.js';
49
+ import { AgentStateSchema, NEWER_WRITER_HINT, unknownStateKeys } from './state-schema.js';
50
50
  import { serializeState } from './state-prune.js';
51
51
  import { atomicWriteFileSync, createFreshState, migrateV1ToV2, migrateV2ToV3, migrateV3ToV4, } from './state-persistence.js';
52
52
  import { getGistIdPath, getStateCachePath } from './paths.js';
@@ -755,6 +755,9 @@ export class GistStateStore {
755
755
  if (obj.version === 3)
756
756
  obj = migrateV3ToV4(obj);
757
757
  }
758
+ const newer = unknownStateKeys(obj);
759
+ if (newer.length > 0)
760
+ warn(MODULE, `Gist state (fields: ${newer.join(', ')}) ${NEWER_WRITER_HINT}`);
758
761
  return AgentStateSchema.parse(obj);
759
762
  }
760
763
  catch (err) {
@@ -6,6 +6,15 @@ import { Octokit } from '@octokit/rest';
6
6
  import { ClosedPR, MergedPR, StoredMergedPR, StoredClosedPR, type StarFilter } from './types.js';
7
7
  /** TTL for cached PR count results (24 hours — these stats change slowly). */
8
8
  export declare const PR_COUNTS_CACHE_TTL_MS: number;
9
+ /**
10
+ * Issue URL a PR closes, from the first GitHub closing keyword in its body
11
+ * (#1824): `Fixes #12`, `closes owner/repo#12`, or `resolves <issue url>`.
12
+ * Joins the outcome ledger to vet-time predictions at zero API cost.
13
+ *
14
+ * ponytail: first keyword wins; a PR closing several issues links only the
15
+ * first. Switch to GraphQL `closingIssuesReferences` if that ever matters.
16
+ */
17
+ export declare function closingIssueUrl(body: string | null | undefined, prUrl: string): string | undefined;
9
18
  /** Return type shared by both merged and closed PR count functions. */
10
19
  export interface PRCountsResult<R> {
11
20
  repos: Map<string, R>;
@@ -15,6 +15,28 @@ export const PR_COUNTS_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
15
15
  * 3 pages × 100 per_page = 300 results, which covers the vast majority of users.
16
16
  */
17
17
  const MAX_PAGINATION_PAGES = 3;
18
+ const CLOSING_KEYWORD_RE = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)(?::\s*|\s+)(?:https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/(\d+)|([\w.-]+\/[\w.-]+)?#(\d+))\b/i;
19
+ /** HTML comments and code: where PR templates keep example `Fixes #123` lines. */
20
+ const NON_PROSE_RE = /<!--[\s\S]*?-->|```[\s\S]*?```|(`+)[^`]*\1/g;
21
+ /** GitHub's PR body limit; also bounds NON_PROSE_RE's scan on an unclosed `<!--`. */
22
+ const MAX_BODY_CHARS = 65_536;
23
+ /**
24
+ * Issue URL a PR closes, from the first GitHub closing keyword in its body
25
+ * (#1824): `Fixes #12`, `closes owner/repo#12`, or `resolves <issue url>`.
26
+ * Joins the outcome ledger to vet-time predictions at zero API cost.
27
+ *
28
+ * ponytail: first keyword wins; a PR closing several issues links only the
29
+ * first. Switch to GraphQL `closingIssuesReferences` if that ever matters.
30
+ */
31
+ export function closingIssueUrl(body, prUrl) {
32
+ const m = body?.slice(0, MAX_BODY_CHARS).replace(NON_PROSE_RE, ' ').match(CLOSING_KEYWORD_RE);
33
+ if (!m)
34
+ return undefined;
35
+ const own = extractOwnerRepo(prUrl);
36
+ // A bare `#12` refers to the PR's own repo.
37
+ const target = m[1] ?? m[3] ?? (own && `${own.owner}/${own.repo}`);
38
+ return target ? `https://github.com/${target}/issues/${m[2] ?? m[4]}` : undefined;
39
+ }
18
40
  /** Returns an empty PRCountsResult. Used as the fallback when stats fetches fail or username is empty. */
19
41
  export function emptyPRCountsResult() {
20
42
  return { repos: new Map(), monthlyCounts: {}, monthlyOpenedCounts: {}, dailyActivityCounts: {}, searchedPRs: [] };
@@ -235,6 +257,7 @@ export async function fetchRecentlyClosedPRs(octokit, config, days = 7) {
235
257
  closedAt: item.closed_at || '',
236
258
  // Free on the search result — feeds the outcome ledger (#1461).
237
259
  openedAt: item.created_at || undefined,
260
+ issueUrl: closingIssueUrl(item.body, item.html_url),
238
261
  }), (item) => item.closed_at);
239
262
  }
240
263
  /**
@@ -255,6 +278,7 @@ export async function fetchRecentlyMergedPRs(octokit, config, days = 7) {
255
278
  mergedAt: mergedAt || item.closed_at || '',
256
279
  // Free on the search result — feeds the outcome ledger (#1461).
257
280
  openedAt: item.created_at || undefined,
281
+ issueUrl: closingIssueUrl(item.body, item.html_url),
258
282
  };
259
283
  }, (item) => item.pull_request?.merged_at || item.closed_at);
260
284
  }
@@ -323,6 +347,7 @@ export async function fetchMergedPRsSince(octokit, config, since) {
323
347
  mergedAt: date,
324
348
  // Free on the search result — feeds the outcome ledger (#1461).
325
349
  openedAt: item.created_at || undefined,
350
+ issueUrl: closingIssueUrl(item.body, item.html_url),
326
351
  }),
327
352
  }, since);
328
353
  }
@@ -344,6 +369,7 @@ export async function fetchClosedPRsSince(octokit, config, since) {
344
369
  closedAt: date,
345
370
  // Free on the search result — feeds the outcome ledger (#1461).
346
371
  openedAt: item.created_at || undefined,
372
+ issueUrl: closingIssueUrl(item.body, item.html_url),
347
373
  }),
348
374
  }, since);
349
375
  }
@@ -19,7 +19,7 @@ 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, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
22
+ export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, 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';
@@ -31,3 +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';
@@ -20,7 +20,7 @@ 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, formatActionHint, formatBriefSummary, formatSummary, printDigest, } from './daily-logic.js';
23
+ export { CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, 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';
@@ -35,3 +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';
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Vet-time predictions for calibration (#1824): what `vet` / `vet-list`
3
+ * thought of an issue, kept so the outcome ledger can compare it against how
4
+ * the PR that closed the issue actually ended.
5
+ */
6
+ import type { VetOutput } from '../formatters/json.js';
7
+ import { type StateManager } from './state.js';
8
+ import type { PickSnapshot } from './types.js';
9
+ /**
10
+ * The prediction to keep for a vetted issue, or undefined when the user's own
11
+ * PR is already linked: scout then grades the issue as taken, which is a
12
+ * post-hoc verdict, not the prediction that picked it.
13
+ */
14
+ export declare function pickSnapshotFromVet(vet: VetOutput, source: PickSnapshot['source']): PickSnapshot | undefined;
15
+ /**
16
+ * Persist predictions without ever failing the vet that produced them. `vet`
17
+ * used to be read-only, so a state save here can race another writer; that
18
+ * and a failed Gist push (#1629) come back as envelope fields instead.
19
+ */
20
+ export declare function persistPickSnapshots(stateManager: StateManager, snapshots: PickSnapshot[]): Promise<{
21
+ pickRecordError?: string;
22
+ gistSyncWarning?: string;
23
+ }>;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Vet-time predictions for calibration (#1824): what `vet` / `vet-list`
3
+ * thought of an issue, kept so the outcome ledger can compare it against how
4
+ * the PR that closed the issue actually ended.
5
+ */
6
+ import { errorMessage } from './errors.js';
7
+ import { warn } from './logger.js';
8
+ import { maybeCheckpoint } from './state.js';
9
+ const MODULE = 'pick-snapshot';
10
+ /**
11
+ * The prediction to keep for a vetted issue, or undefined when the user's own
12
+ * PR is already linked: scout then grades the issue as taken, which is a
13
+ * post-hoc verdict, not the prediction that picked it.
14
+ */
15
+ // ponytail: scout reports only the first linked PR, so a standalone `vet` of an
16
+ // issue whose first reference is someone else's PR can still miss the user's
17
+ // own. First-wins in recordPickSnapshots limits this to never-vetted issues.
18
+ export function pickSnapshotFromVet(vet, source) {
19
+ if (vet.linkedPRClassification?.startsWith('user_'))
20
+ return undefined;
21
+ const stars = vet.projectHealth?.stargazersCount;
22
+ return {
23
+ issueUrl: vet.issue.url,
24
+ grade: vet.grade.score,
25
+ recommendation: vet.recommendation,
26
+ // Stars at pick time feed the eval's repo-size cut (#1825); not recoverable later.
27
+ ...(typeof stars === 'number' && { stargazersCount: stars }),
28
+ source,
29
+ capturedAt: new Date().toISOString(),
30
+ };
31
+ }
32
+ /**
33
+ * Persist predictions without ever failing the vet that produced them. `vet`
34
+ * used to be read-only, so a state save here can race another writer; that
35
+ * and a failed Gist push (#1629) come back as envelope fields instead.
36
+ */
37
+ export async function persistPickSnapshots(stateManager, snapshots) {
38
+ if (snapshots.length === 0)
39
+ return {};
40
+ try {
41
+ stateManager.reloadIfChanged();
42
+ stateManager.recordPickSnapshots(snapshots);
43
+ }
44
+ catch (error) {
45
+ const pickRecordError = `Could not record the vet prediction: ${errorMessage(error)}`;
46
+ warn(MODULE, pickRecordError);
47
+ return { pickRecordError };
48
+ }
49
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
50
+ return gistSyncWarning ? { gistSyncWarning } : {};
51
+ }
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import * as fs from 'node:fs';
7
7
  import * as path from 'node:path';
8
- import { AgentStateSchema } from './state-schema.js';
8
+ import { AgentStateSchema, NEWER_WRITER_HINT, unknownStateKeys } from './state-schema.js';
9
9
  import { serializeState } from './state-prune.js';
10
10
  import { getStatePath, getBackupDir, getDataDir, getLegacyStatePath, getLegacyBackupDir } from './paths.js';
11
11
  import { errorMessage, ConcurrencyError } from './errors.js';
@@ -378,7 +378,11 @@ export function loadState() {
378
378
  wasMigrated = true;
379
379
  }
380
380
  }
381
- // Validate through Zod schema (strips unknown keys in memory; stale keys persist on disk until next save)
381
+ // Validate through Zod schema. Unknown keys pass through (#1831): they
382
+ // come from a newer release and must survive this version's next save.
383
+ const newer = unknownStateKeys(raw);
384
+ if (newer.length > 0)
385
+ warn(MODULE, `State file (fields: ${newer.join(', ')}) ${NEWER_WRITER_HINT}`);
382
386
  const parsed = AgentStateSchema.safeParse(raw);
383
387
  if (!parsed.success) {
384
388
  const summary = parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ');