@oss-autopilot/core 3.33.0 → 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.
Files changed (86) hide show
  1. package/dist/cli-pre-action.js +20 -20
  2. package/dist/cli-registry.js +59 -23
  3. package/dist/cli.bundle.cjs +140 -129
  4. package/dist/commands/check-integration.d.ts +2 -2
  5. package/dist/commands/comments.js +3 -3
  6. package/dist/commands/compliance-score.js +1 -1
  7. package/dist/commands/config.js +1 -1
  8. package/dist/commands/daily-render.js +6 -13
  9. package/dist/commands/daily.d.ts +1 -2
  10. package/dist/commands/daily.js +8 -4
  11. package/dist/commands/dashboard-cache.js +1 -1
  12. package/dist/commands/dashboard-data.js +7 -6
  13. package/dist/commands/dashboard-lifecycle.js +3 -5
  14. package/dist/commands/dashboard-server.js +3 -3
  15. package/dist/commands/detect-formatters.d.ts +1 -1
  16. package/dist/commands/dismiss.js +2 -2
  17. package/dist/commands/doctor.js +3 -3
  18. package/dist/commands/eval.d.ts +11 -0
  19. package/dist/commands/eval.js +11 -0
  20. package/dist/commands/features.js +1 -1
  21. package/dist/commands/guidelines.js +5 -5
  22. package/dist/commands/index.d.ts +1 -0
  23. package/dist/commands/index.js +1 -0
  24. package/dist/commands/init.js +1 -1
  25. package/dist/commands/ledger-backfill.d.ts +40 -0
  26. package/dist/commands/ledger-backfill.js +216 -0
  27. package/dist/commands/local-repos.d.ts +1 -1
  28. package/dist/commands/overnight.js +13 -18
  29. package/dist/commands/parse-list.d.ts +2 -2
  30. package/dist/commands/parse-list.js +7 -7
  31. package/dist/commands/repo-vet.js +3 -3
  32. package/dist/commands/search.js +9 -10
  33. package/dist/commands/setup.js +8 -8
  34. package/dist/commands/startup.js +1 -1
  35. package/dist/commands/status.d.ts +1 -1
  36. package/dist/commands/vet-list.js +17 -7
  37. package/dist/commands/vet.js +5 -3
  38. package/dist/core/__fixtures__/prompt-injection-payloads.js +1 -1
  39. package/dist/core/anti-llm-policy.js +3 -3
  40. package/dist/core/checklist-analysis.d.ts +3 -0
  41. package/dist/core/checklist-analysis.js +67 -16
  42. package/dist/core/ci-analysis.js +1 -1
  43. package/dist/core/close-reason.d.ts +25 -0
  44. package/dist/core/close-reason.js +28 -0
  45. package/dist/core/comment-decision.js +1 -1
  46. package/dist/core/compliance-score.js +2 -2
  47. package/dist/core/daily-logic.d.ts +12 -0
  48. package/dist/core/daily-logic.js +11 -2
  49. package/dist/core/display-utils.js +1 -1
  50. package/dist/core/errors.js +4 -5
  51. package/dist/core/eval-report.d.ts +55 -0
  52. package/dist/core/eval-report.js +211 -0
  53. package/dist/core/follow-up-history.d.ts +1 -2
  54. package/dist/core/follow-up-history.js +1 -1
  55. package/dist/core/github-stats.d.ts +9 -0
  56. package/dist/core/github-stats.js +27 -1
  57. package/dist/core/guidelines-store.js +2 -2
  58. package/dist/core/http-cache.js +1 -2
  59. package/dist/core/index.d.ts +3 -2
  60. package/dist/core/index.js +3 -2
  61. package/dist/core/issue-conversation.js +1 -1
  62. package/dist/core/issue-effort.js +12 -6
  63. package/dist/core/paths.d.ts +7 -0
  64. package/dist/core/paths.js +25 -3
  65. package/dist/core/pick-snapshot.d.ts +23 -0
  66. package/dist/core/pick-snapshot.js +51 -0
  67. package/dist/core/pr-comments-fetcher.js +1 -1
  68. package/dist/core/review-analysis.js +5 -9
  69. package/dist/core/state-persistence.js +1 -1
  70. package/dist/core/state-schema.d.ts +117 -0
  71. package/dist/core/state-schema.js +48 -0
  72. package/dist/core/state.d.ts +22 -1
  73. package/dist/core/state.js +65 -12
  74. package/dist/core/strategy.js +2 -3
  75. package/dist/core/types.d.ts +1 -1
  76. package/dist/core/untrusted-content.js +9 -9
  77. package/dist/core/urls.js +1 -1
  78. package/dist/dashboard/assets/chart-panel-DPKNBUts.js +3 -0
  79. package/dist/dashboard/assets/{confetti.module-BYDB1iN2.js → confetti.module-D2UmBLOm.js} +1 -1
  80. package/dist/dashboard/assets/index-B25bZOYX.js +55 -0
  81. package/dist/dashboard/index.html +1 -1
  82. package/dist/formatters/json.d.ts +10 -2
  83. package/dist/formatters/json.js +2 -2
  84. package/package.json +1 -1
  85. package/dist/dashboard/assets/chart-panel-CmNIsCjO.js +0 -3
  86. package/dist/dashboard/assets/index-CTKGc-Ns.js +0 -55
@@ -83,7 +83,7 @@ function makeExcerpt(text, matchIndex, matchLength) {
83
83
  const end = Math.min(text.length, matchIndex + matchLength + EXCERPT_RADIUS);
84
84
  const prefix = start > 0 ? '…' : '';
85
85
  const suffix = end < text.length ? '…' : '';
86
- return `${prefix}${text.slice(start, end).replace(/\s+/g, ' ').trim()}${suffix}`;
86
+ return `${prefix}${text.slice(start, end).replaceAll(/\s+/g, ' ').trim()}${suffix}`;
87
87
  }
88
88
  /**
89
89
  * Normalize exotic whitespace and hyphens so patterns written with plain
@@ -94,8 +94,8 @@ function makeExcerpt(text, matchIndex, matchLength) {
94
94
  function normalizeText(text) {
95
95
  return text
96
96
  .normalize('NFKC')
97
- .replace(/\u00A0/g, ' ')
98
- .replace(/[\u2010-\u2015]/g, '-');
97
+ .replaceAll('\u{A0}', ' ')
98
+ .replaceAll(/[\u2010-\u2015]/g, '-');
99
99
  }
100
100
  export function scanForAntiLLMPolicy(text) {
101
101
  if (typeof text !== 'string') {
@@ -16,6 +16,9 @@ export declare function isConditionalChecklistItem(line: string): boolean;
16
16
  * - Sections whose heading matches "type of change" / "kind of change" / "category"
17
17
  * are treated as single-select radio groups: satisfied when at least one box is
18
18
  * checked, so the remaining unchecked boxes are not counted as incomplete.
19
+ * - Unchecked boxes directly under a conditional lead-in line ("If you add ...:")
20
+ * are treated as conditional (#1796).
21
+ * Agreement boxes (CLA, code of conduct, licence, sign-off) always count.
19
22
  */
20
23
  export declare function analyzeChecklist(body: string): {
21
24
  hasIncompleteChecklist: boolean;
@@ -8,8 +8,16 @@
8
8
  * Conservative — only skips items with clear conditional language.
9
9
  */
10
10
  const CONDITIONAL_CHECKLIST_PATTERN = /\(if\s|\bif applicable\b|\bif needed\b|\bif relevant\b|\bonly if\b|\bwhen applicable\b|\(optional\)|- \[ \]\s*optional\b|\bn\/a\b|\bnot applicable\b|\bif required\b|\bif necessary\b/;
11
+ /** An author's reason for leaving a box unchecked: "(Not run: ...)" or "(Skipped: ...)" (#1796). */
12
+ const UNCHECKED_REASON_RE = /\((?:not run|skipped)\s*:\s*[^\s)][^)]*\)/i;
13
+ /**
14
+ * Boxes about agreements (CLA, code of conduct, licence, sign-off) are never
15
+ * exempt, whatever lead-in or annotation surrounds them (#1796).
16
+ */
17
+ const NEVER_EXEMPT_RE = /\b(?:cla|code of conduct|agree\w*|sign|signed|licen[cs]\w*)\b/i;
11
18
  export function isConditionalChecklistItem(line) {
12
- return CONDITIONAL_CHECKLIST_PATTERN.test(line.toLowerCase());
19
+ const lower = line.toLowerCase();
20
+ return (CONDITIONAL_CHECKLIST_PATTERN.test(lower) || UNCHECKED_REASON_RE.test(line)) && !NEVER_EXEMPT_RE.test(line);
13
21
  }
14
22
  // Matches markdown headings; `\S` after whitespace prevents backtracking with `.*` (#1718)
15
23
  const HEADING_RE = /^#{1,6}\s+(\S.*)/;
@@ -20,6 +28,25 @@ const HEADING_RE = /^#{1,6}\s+(\S.*)/;
20
28
  * prose like "Complete one of the following only if it applies". (#1760)
21
29
  */
22
30
  const PICK_ONE_COMMENT_RE = /<!--[^>]*(?:exactly\s+one|pick\s+one|choose\s+one)[^>]*-->/i;
31
+ /**
32
+ * A prose line that conditions the checkbox run directly below it on the change,
33
+ * e.g. "If you add a dependency:" or "If the PR changes the schema:" (#1796).
34
+ * The subject and the change verb must open the line, so "If this PR is a
35
+ * draft:" or "If the code of conduct applies:" do not qualify.
36
+ */
37
+ const LEAD_IN_OPENER_RE = /^(?:if|when|only if)\s+/i;
38
+ const LEAD_IN_YOU_VERB_RE = /^(?:you|this change)\s+(?:add|change|modif|updat|remov|introduc|touch)\w*\b/i;
39
+ const LEAD_IN_SUBJECT_VERB_RE = /^(?:the\s+)?(?:pr|change|code)\s+(?:adds|changes|modifies|updates|removes|introduces|touches)\b/i;
40
+ const ENDS_WITH_ONLY_COLON_RE = /^[^:]*:\s*$/;
41
+ function isConditionalLeadIn(line) {
42
+ const opener = LEAD_IN_OPENER_RE.exec(line);
43
+ if (!opener || !ENDS_WITH_ONLY_COLON_RE.test(line))
44
+ return false;
45
+ const rest = line.slice(opener[0].length);
46
+ return LEAD_IN_YOU_VERB_RE.test(rest) || LEAD_IN_SUBJECT_VERB_RE.test(rest);
47
+ }
48
+ /** An unindented checkbox line; nested boxes end a conditional run. */
49
+ const TOP_LEVEL_CHECKBOX_RE = /^- \[[ x]\]/i;
23
50
  /** Matches any checkbox line (checked or unchecked). */
24
51
  const ANY_CHECKBOX_RE = /^.*- \[[ x]\].*$/i;
25
52
  /**
@@ -70,7 +97,7 @@ function hasLeaveUncheckedNote(section) {
70
97
  }
71
98
  /**
72
99
  * Mark unchecked lines in a single pick-one run as exempt if exactly one box is
73
- * checked. Extracted to keep `collectPickOneExemptLineIndices` within complexity
100
+ * checked. Extracted to keep `collectRunExemptLineIndices` within complexity
74
101
  * limits.
75
102
  */
76
103
  function markPickOneRunExempt(lines, runStart, runEnd, exempt) {
@@ -82,30 +109,51 @@ function markPickOneRunExempt(lines, runStart, runEnd, exempt) {
82
109
  exempt.add(k);
83
110
  }
84
111
  }
112
+ /** Mark the unchecked lines in a run under a conditional lead-in as exempt (#1796). */
113
+ function markConditionalRunExempt(lines, runStart, runEnd, exempt) {
114
+ for (let k = runStart; k < runEnd; k++) {
115
+ if (/- \[ \]/.test(lines[k]) && !NEVER_EXEMPT_RE.test(lines[k]))
116
+ exempt.add(k);
117
+ }
118
+ }
119
+ const PICK_ONE_RUN = { skipBlanks: true, inRun: ANY_CHECKBOX_RE, mark: markPickOneRunExempt };
120
+ const CONDITIONAL_RUN = { skipBlanks: false, inRun: TOP_LEVEL_CHECKBOX_RE, mark: markConditionalRunExempt };
121
+ /** The run rule a line introduces, if any. */
122
+ function runRuleFor(line) {
123
+ if (PICK_ONE_COMMENT_RE.test(line))
124
+ return PICK_ONE_RUN;
125
+ if (isConditionalLeadIn(line))
126
+ return CONDITIONAL_RUN;
127
+ return undefined;
128
+ }
85
129
  /**
86
- * Returns the set of line indices (within `lines`) that are unchecked checkbox lines
87
- * belonging to a satisfied pick-one group. A pick-one group is a contiguous checkbox
88
- * run immediately following an HTML comment matching PICK_ONE_COMMENT_RE. The group is
89
- * satisfied when exactly one box in the run is checked; in that case the unchecked
90
- * alternatives are intentional and must not be counted as incomplete. (#1760)
130
+ * Returns the set of line indices (within `lines`) of unchecked checkbox lines that
131
+ * are intentionally unchecked because of the line introducing their run:
132
+ * - a pick-one HTML comment (PICK_ONE_COMMENT_RE) whose run has exactly one box
133
+ * checked, so the unchecked alternatives are intentional (#1760);
134
+ * - a conditional lead-in line ({@link isConditionalLeadIn}), so its run is
135
+ * conditional like an "(if ...)" item, except NEVER_EXEMPT_RE boxes (#1796).
136
+ * A pick-one run is the contiguous checkbox lines after the comment, past blanks;
137
+ * a conditional run is the unindented boxes directly below the lead-in.
91
138
  */
92
- function collectPickOneExemptLineIndices(lines) {
139
+ function collectRunExemptLineIndices(lines) {
93
140
  const exempt = new Set();
94
141
  let i = 0;
95
142
  while (i < lines.length) {
96
- if (!PICK_ONE_COMMENT_RE.test(lines[i])) {
143
+ const rule = runRuleFor(lines[i]);
144
+ if (!rule) {
97
145
  i++;
98
146
  continue;
99
147
  }
100
- // Advance past the comment, skipping any blank lines before the checkbox run
148
+ // Advance past the introducing line, skipping any blank lines before the checkbox run
101
149
  let j = i + 1;
102
- while (j < lines.length && lines[j].trim() === '')
150
+ while (rule.skipBlanks && j < lines.length && lines[j].trim() === '')
103
151
  j++;
104
152
  // Collect the contiguous checkbox run
105
153
  const runStart = j;
106
- while (j < lines.length && ANY_CHECKBOX_RE.test(lines[j]))
154
+ while (j < lines.length && rule.inRun.test(lines[j]))
107
155
  j++;
108
- markPickOneRunExempt(lines, runStart, j, exempt);
156
+ rule.mark(lines, runStart, j, exempt);
109
157
  i = j;
110
158
  }
111
159
  return exempt;
@@ -127,9 +175,9 @@ function analyzeSectionItems(section) {
127
175
  const isTypeOfChange = section.heading !== null && TYPE_OF_CHANGE_RE.test(section.heading);
128
176
  if (isTypeOfChange && checked >= 1)
129
177
  return { checked, nonConditionalUnchecked: 0 };
130
- // Pick-one groups: unchecked alternatives in a satisfied pick-one group are exempt. (#1760)
131
- const pickOneExempt = collectPickOneExemptLineIndices(section.lines);
132
- const nonConditionalUnchecked = section.lines.filter((l, idx) => /^.*- \[ \].*$/.test(l) && !isConditionalChecklistItem(l) && !pickOneExempt.has(idx));
178
+ // Pick-one groups (#1760) and runs under a conditional lead-in line (#1796).
179
+ const runExempt = collectRunExemptLineIndices(section.lines);
180
+ const nonConditionalUnchecked = section.lines.filter((l, idx) => /^.*- \[ \].*$/.test(l) && !isConditionalChecklistItem(l) && !runExempt.has(idx));
133
181
  return { checked, nonConditionalUnchecked: nonConditionalUnchecked.length };
134
182
  }
135
183
  /**
@@ -144,6 +192,9 @@ function analyzeSectionItems(section) {
144
192
  * - Sections whose heading matches "type of change" / "kind of change" / "category"
145
193
  * are treated as single-select radio groups: satisfied when at least one box is
146
194
  * checked, so the remaining unchecked boxes are not counted as incomplete.
195
+ * - Unchecked boxes directly under a conditional lead-in line ("If you add ...:")
196
+ * are treated as conditional (#1796).
197
+ * Agreement boxes (CLA, code of conduct, licence, sign-off) always count.
147
198
  */
148
199
  export function analyzeChecklist(body) {
149
200
  if (!body)
@@ -367,7 +367,7 @@ export async function getCIStatus(octokit, owner, repo, sha) {
367
367
  if (statusCode === 401 || statusCode === 403 || statusCode === 429) {
368
368
  throw error;
369
369
  }
370
- else if (statusCode === 404) {
370
+ if (statusCode === 404) {
371
371
  // Repo might not have CI configured, this is normal
372
372
  debug('pr-monitor', `CI check 404 for ${owner}/${repo} (no CI configured)`);
373
373
  }
@@ -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
+ }
@@ -50,7 +50,7 @@ export function shouldDraftResponse(input) {
50
50
  if (alwaysDraftCategories.has(item.category)) {
51
51
  return {
52
52
  shouldDraft: true,
53
- reason: `${item.category.replace(/_/g, ' ')} — diff alone cannot address this`,
53
+ reason: `${item.category.replaceAll('_', ' ')} — diff alone cannot address this`,
54
54
  };
55
55
  }
56
56
  }
@@ -240,8 +240,8 @@ function proseOf(body) {
240
240
  }
241
241
  return (uncommented
242
242
  // A heading is a short title line, not a sentence that starts with "# ".
243
- .replace(/^ {0,3}#{1,6}[ \t]+[^\n]{0,60}$/gm, (line) => (/[.!?。]\s*$/.test(line) ? line : ''))
244
- .replace(CLOSING_REF, '')
243
+ .replaceAll(/^ {0,3}#{1,6}[ \t]+[^\n]{0,60}$/gm, (line) => (/[.!?。]\s*$/.test(line) ? line : ''))
244
+ .replaceAll(CLOSING_REF, '')
245
245
  .trim());
246
246
  }
247
247
  // Headings are never required: a sentence or two of what and why is a full
@@ -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.
@@ -453,8 +463,7 @@ export function computeActionMenu(actionableIssues, capacity, commentedIssues =
453
463
  searchItem.capacityWarning = `You have ${capacity.criticalIssueCount} critical issue(s) needing attention. Resolve them before claiming new issues.`;
454
464
  }
455
465
  }
456
- items.push(searchItem);
457
- items.push({
466
+ items.push(searchItem, {
458
467
  key: 'done',
459
468
  label: 'Done for now',
460
469
  description: 'End session with summary',
@@ -94,7 +94,7 @@ function labelToPlainText(reason) {
94
94
  const label = ACTION_DISPLAY[reason]?.label;
95
95
  if (!label)
96
96
  return reason;
97
- return label.replace(/[[\]]/g, '').toLowerCase();
97
+ return label.replaceAll(/[[\]]/g, '').toLowerCase();
98
98
  }
99
99
  /** Compute display label and description for a FetchedPR (#79). */
100
100
  export function computeDisplayLabel(pr) {
@@ -272,15 +272,14 @@ export function isTransientNetworkError(err) {
272
272
  return true;
273
273
  // Node socket-level errors expose `code`
274
274
  const code = err.code;
275
- if (typeof code === 'string') {
276
- if (code === 'ECONNRESET' ||
275
+ if (typeof code === 'string' &&
276
+ (code === 'ECONNRESET' ||
277
277
  code === 'ETIMEDOUT' ||
278
278
  code === 'ENETUNREACH' ||
279
279
  code === 'ENOTFOUND' ||
280
280
  code === 'ECONNREFUSED' ||
281
- code === 'EAI_AGAIN') {
282
- return true;
283
- }
281
+ code === 'EAI_AGAIN')) {
282
+ return true;
284
283
  }
285
284
  // Octokit's RequestError surfaces the underlying name; fetch timeout is AbortError
286
285
  const name = err.name;
@@ -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;
@@ -0,0 +1,211 @@
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
+ }));
106
+ const dormant = (state.lastDigest?.openPRs ?? [])
107
+ .filter((pr) => pr.stalenessTier === 'dormant')
108
+ .map((pr) => ({ url: pr.url, repo: pr.repo, outcome: 'dormant', stars: starsOf(pr.repo) }));
109
+ return [...merged, ...closed, ...dormant];
110
+ }
111
+ const pct = (v) => (v === null ? 'n/a' : `${Math.round(v * 100)}%`);
112
+ const hrs = (v) => (v === null ? 'n/a' : `${v}h`);
113
+ export function computeEvalReport(state, now = new Date()) {
114
+ const rows = collectRows(state);
115
+ const graded = rows.filter((r) => r.gradeSource === 'vet' && r.outcome !== 'dormant');
116
+ const high = graded.filter((r) => r.grade >= 7);
117
+ const low = graded.filter((r) => r.grade <= 5);
118
+ const mergedShare = (g) => g.filter((r) => r.outcome === 'merged').length / g.length;
119
+ const separable = high.length >= MIN_FLAG_N && low.length >= MIN_FLAG_N;
120
+ const gap = separable ? Math.round((mergedShare(high) - mergedShare(low)) * 100) / 100 : null;
121
+ const closedRows = rows.filter((r) => r.outcome === 'closed');
122
+ const closeReasons = {};
123
+ const approachClosuresByMonth = {};
124
+ for (const r of closedRows) {
125
+ const reason = r.closeReason ?? 'unclassified';
126
+ closeReasons[reason] = (closeReasons[reason] ?? 0) + 1;
127
+ if ((r.closeReason === 'ai-policy' || r.closeReason === 'rejected') && r.month) {
128
+ approachClosuresByMonth[r.month] = (approachClosuresByMonth[r.month] ?? 0) + 1;
129
+ }
130
+ }
131
+ const reviewed = rows.filter((r) => r.changesRequested !== undefined);
132
+ const ciKnown = rows.filter((r) => r.ciFailing !== undefined);
133
+ const byGrade = groupBy(rows, (r) => (r.gradeSource ? `${r.gradeSource} ${gradeRange(r.grade)}` : 'no prediction'), [
134
+ 'vet 9-10',
135
+ 'vet 7-8',
136
+ 'vet 5-6',
137
+ 'vet 1-4',
138
+ 'list 9-10',
139
+ 'list 7-8',
140
+ 'list 5-6',
141
+ 'list 1-4',
142
+ 'no prediction',
143
+ ]);
144
+ const flags = byGrade
145
+ .filter((b) => /(?:9-10|7-8)$/.test(b.key) && b.n >= MIN_FLAG_N && (b.mergeRate ?? 1) < 0.6)
146
+ .map((b) => `${b.key}: high-grade picks merge at ${Math.round(b.mergeRate * 100)}% (n=${b.n})`);
147
+ if (gap !== null && gap <= 0) {
148
+ 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})`);
149
+ }
150
+ return {
151
+ generatedAt: now.toISOString(),
152
+ totals: bucket('all', rows),
153
+ headlines: {
154
+ mergeRate1kStars: bucket('>=1k stars', rows.filter((r) => (r.stars ?? 0) >= 1000)),
155
+ calibration: { gap, highN: high.length, lowN: low.length },
156
+ approachClosuresByMonth,
157
+ },
158
+ byGrade,
159
+ byStars: groupBy(rows, (r) => starRange(r.stars), ['10k+', '1k-10k', '100-1k', '<100', 'unknown']),
160
+ byMonth: groupBy(rows.filter((r) => r.month), (r) => r.month).sort((a, b) => b.key.localeCompare(a.key)),
161
+ closeReasons,
162
+ quality: {
163
+ withReviewState: reviewed.length,
164
+ changesRequestedShare: rate(reviewed.filter((r) => r.changesRequested).length, reviewed.length),
165
+ ciFailingShare: rate(ciKnown.filter((r) => r.ciFailing).length, ciKnown.length),
166
+ },
167
+ calibrationPairs: graded.length,
168
+ flags,
169
+ };
170
+ }
171
+ function table(title, buckets) {
172
+ return [
173
+ `## ${title}`,
174
+ '',
175
+ '| Bucket | n | Merged | Closed | Dormant | Merge rate | Median to merge | Median to first response |',
176
+ '|---|---|---|---|---|---|---|---|',
177
+ ...buckets.map((b) => `| ${b.key} | ${b.n} | ${b.merged} | ${b.closed} | ${b.dormant} | ${pct(b.mergeRate)} | ${hrs(b.medianHoursToMerge)} | ${hrs(b.medianHoursToFirstResponse)} |`),
178
+ '',
179
+ ];
180
+ }
181
+ export function formatEvalMarkdown(r) {
182
+ const h = r.headlines;
183
+ const recentMonths = Object.keys(h.approachClosuresByMonth).sort().reverse().slice(0, 6);
184
+ return [
185
+ `# oss-autopilot eval (${r.generatedAt.slice(0, 10)})`,
186
+ '',
187
+ '## Headlines',
188
+ '',
189
+ `- Merge rate on repos with 1k+ stars: **${pct(h.mergeRate1kStars.mergeRate)}** (n=${h.mergeRate1kStars.n})`,
190
+ `- 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)`,
191
+ `- Approach or AI-policy closures by month: ${recentMonths.length ? recentMonths.map((m) => `${m}: ${h.approachClosuresByMonth[m]}`).join(', ') : 'none'}`,
192
+ `- Overall: ${r.totals.n} outcomes, merge rate ${pct(r.totals.mergeRate)} (dormant counted as not merged)`,
193
+ '',
194
+ ...(r.flags.length ? ['## Flags', '', ...r.flags.map((f) => `- ${f}`), ''] : []),
195
+ ...table('By grade at pick time', r.byGrade),
196
+ ...table('By repo stars', r.byStars),
197
+ ...table('By month', r.byMonth.slice(0, 12)),
198
+ '## Close reasons',
199
+ '',
200
+ ...Object.entries(r.closeReasons)
201
+ .sort((a, b) => b[1] - a[1])
202
+ .map(([k, v]) => `- ${k}: ${v}`),
203
+ '',
204
+ '## Review quality',
205
+ '',
206
+ `- PRs with a recorded review state: ${r.quality.withReviewState}`,
207
+ `- Changes requested before the outcome: ${pct(r.quality.changesRequestedShare)}`,
208
+ `- CI failing at last sight: ${pct(r.quality.ciFailingShare)}`,
209
+ '',
210
+ ].join('\n');
211
+ }
@@ -8,8 +8,7 @@
8
8
  *
9
9
  * Pure functions — callers manage state I/O.
10
10
  */
11
- import type { AgentState } from './state-schema.js';
12
- import type { FollowUpEntry } from './state-schema.js';
11
+ import type { AgentState, FollowUpEntry } from './state-schema.js';
13
12
  export type FollowUpTier = 'light_check_in' | 'direct_check_in' | 'final_check_in';
14
13
  /**
15
14
  * Tier window in days. The "no second ping in the same window" rule
@@ -52,7 +52,7 @@ export function isWithinTierWindow(state, prUrl, tier, now = new Date()) {
52
52
  const ageMs = now.getTime() - Date.parse(last.timestamp);
53
53
  if (Number.isNaN(ageMs))
54
54
  return false;
55
- const windowMs = TIER_WINDOW_DAYS[tier] * 86400000;
55
+ const windowMs = TIER_WINDOW_DAYS[tier] * 86_400_000;
56
56
  return ageMs < windowMs;
57
57
  }
58
58
  /**
@@ -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>;