@oss-autopilot/core 3.36.0 → 3.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/cli-registry.js +1 -1
  2. package/dist/cli.bundle.cjs +143 -130
  3. package/dist/commands/comments.js +4 -3
  4. package/dist/commands/config.js +18 -11
  5. package/dist/commands/daily.js +29 -2
  6. package/dist/commands/dashboard-gist-sync.d.ts +5 -1
  7. package/dist/commands/dashboard-gist-sync.js +19 -2
  8. package/dist/commands/dashboard-server.js +9 -5
  9. package/dist/commands/dismiss.js +4 -3
  10. package/dist/commands/guidelines.js +21 -14
  11. package/dist/commands/init.js +3 -2
  12. package/dist/commands/ledger-backfill.d.ts +7 -0
  13. package/dist/commands/ledger-backfill.js +120 -9
  14. package/dist/commands/move.js +9 -6
  15. package/dist/commands/overnight-push-prep.js +5 -2
  16. package/dist/commands/overnight.js +48 -23
  17. package/dist/commands/search.js +9 -6
  18. package/dist/commands/setup.js +7 -3
  19. package/dist/commands/validation.js +22 -0
  20. package/dist/commands/vet-list.js +18 -17
  21. package/dist/commands/vet.js +27 -2
  22. package/dist/core/daily-logic.d.ts +33 -0
  23. package/dist/core/daily-logic.js +102 -0
  24. package/dist/core/errors.js +1 -1
  25. package/dist/core/eval-report.d.ts +17 -0
  26. package/dist/core/eval-report.js +85 -4
  27. package/dist/core/gist-state-store.d.ts +5 -2
  28. package/dist/core/gist-state-store.js +7 -4
  29. package/dist/core/index.d.ts +3 -3
  30. package/dist/core/index.js +3 -3
  31. package/dist/core/issue-verification.d.ts +12 -0
  32. package/dist/core/issue-verification.js +18 -0
  33. package/dist/core/pick-snapshot.d.ts +19 -2
  34. package/dist/core/pick-snapshot.js +28 -2
  35. package/dist/core/pr-monitor.d.ts +0 -6
  36. package/dist/core/pr-monitor.js +0 -13
  37. package/dist/core/repo-score-manager.d.ts +0 -13
  38. package/dist/core/repo-score-manager.js +0 -24
  39. package/dist/core/review-analysis.d.ts +34 -14
  40. package/dist/core/review-analysis.js +61 -32
  41. package/dist/core/state-persistence.js +4 -1
  42. package/dist/core/state-schema.d.ts +46 -0
  43. package/dist/core/state-schema.js +28 -0
  44. package/dist/core/state.d.ts +44 -18
  45. package/dist/core/state.js +164 -38
  46. package/dist/formatters/json.d.ts +4 -0
  47. package/dist/formatters/json.js +4 -0
  48. package/package.json +1 -1
@@ -252,7 +252,7 @@ export async function runOvernight() {
252
252
  }
253
253
  // executeDailyCheck already checkpointed the Gist; this write came after it,
254
254
  // and in Gist mode setLastOvernight only reaches the local cache (#1629 class).
255
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
255
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.setLastOvernight(record));
256
256
  return {
257
257
  ...body,
258
258
  reportPath,
@@ -303,16 +303,28 @@ export async function runOvernightImplementBlocked(options) {
303
303
  throw new Error(`${options.url} is not tonight's implement item (${last.implementUrl ?? 'none queued'})`);
304
304
  }
305
305
  const note = options.note ?? (options.fromReport ? readPreparerReport(options.fromReport).note : undefined);
306
- const implementAttempts = [
307
- ...(last.implementAttempts ?? []),
308
- { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note },
309
- ];
310
- sm.setLastOvernight({ ...last, implementAttempts });
306
+ const attempt = { url: options.url, attemptedAt: new Date().toISOString(), outcome: 'blocked', note };
307
+ // Reads the live record each time so a re-apply after a Gist refresh lands
308
+ // on the refreshed copy, not on the `last` captured above; idempotent.
309
+ const apply = () => {
310
+ const base = sm.getLastOvernight() ?? last;
311
+ const attempts = base.implementAttempts ?? [];
312
+ const record = attempts.some((a) => a.attemptedAt === attempt.attemptedAt)
313
+ ? base
314
+ : { ...base, implementAttempts: [...attempts, attempt] };
315
+ sm.setLastOvernight(record);
316
+ return record;
317
+ };
318
+ const record = apply();
311
319
  const dropDir = handoffDir();
312
320
  if (dropDir)
313
- exportHandoff(dropDir, { ...last, implementAttempts });
314
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
315
- return { url: options.url, attemptCount: implementAttempts.length, ...(gistSyncWarning && { gistSyncWarning }) };
321
+ exportHandoff(dropDir, record);
322
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, apply);
323
+ return {
324
+ url: options.url,
325
+ attemptCount: record.implementAttempts?.length ?? 0,
326
+ ...(gistSyncWarning && { gistSyncWarning }),
327
+ };
316
328
  }
317
329
  /** Append one prepared branch to state and to the report of the latest run. */
318
330
  export async function runOvernightRecord(options) {
@@ -342,21 +354,34 @@ export async function runOvernightRecord(options) {
342
354
  throw new ValidationError('No worktree to bundle: pass --worktree, or a report with WORKTREE:.');
343
355
  writeHandoffBundle(dropDir, entry.worktree, branch);
344
356
  }
345
- const prepared = [...last.prepared, entry];
346
- // Recording the branch for tonight's list issue is what marks the attempt
347
- // as prepared, so the next run moves on to the next Pursue item.
348
- const implementAttempts = options.url === last.implementUrl
349
- ? [
350
- ...(last.implementAttempts ?? []),
351
- { url: options.url, attemptedAt: entry.recordedAt, outcome: 'prepared' },
352
- ]
353
- : last.implementAttempts;
354
- sm.setLastOvernight({ ...last, prepared, implementAttempts });
355
- const { reportRecreated } = writePreparedSection(last.reportPath, prepared);
356
- publishReport(sm, last.reportPath);
357
+ // Reads the live record each time so a re-apply after a Gist refresh lands
358
+ // on the refreshed copy, not on the `last` captured above; idempotent.
359
+ const apply = () => {
360
+ const base = sm.getLastOvernight() ?? last;
361
+ if (base.prepared.some((p) => p.branch === entry.branch)) {
362
+ sm.setLastOvernight(base);
363
+ return base;
364
+ }
365
+ const prepared = [...base.prepared, entry];
366
+ // Recording the branch for tonight's list issue is what marks the attempt
367
+ // as prepared, so the next run moves on to the next Pursue item.
368
+ const implementAttempts = options.url === base.implementUrl
369
+ ? [
370
+ ...(base.implementAttempts ?? []),
371
+ { url: options.url, attemptedAt: entry.recordedAt, outcome: 'prepared' },
372
+ ]
373
+ : base.implementAttempts;
374
+ const record = { ...base, prepared, implementAttempts };
375
+ sm.setLastOvernight(record);
376
+ return record;
377
+ };
378
+ const record = apply();
379
+ const { prepared } = record;
380
+ const { reportRecreated } = writePreparedSection(record.reportPath, prepared);
381
+ publishReport(sm, record.reportPath);
357
382
  if (dropDir)
358
- exportHandoff(dropDir, { ...last, prepared, implementAttempts });
359
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
383
+ exportHandoff(dropDir, record);
384
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, apply);
360
385
  return {
361
386
  reportPath: last.reportPath,
362
387
  preparedCount: prepared.length,
@@ -192,15 +192,18 @@ export async function runSearch(options) {
192
192
  // hidden-but-surfaced issues also rotate out. Persists to AgentState.
193
193
  let gistSyncWarning = null;
194
194
  if (options.record !== false) {
195
- recordSearchSeen(stateManager, result.candidates.map((c) => c.issue.url));
196
- // Scout advanced its broad-phase language cursor in its own (provided,
197
- // non-persisted) state; copy it back so the next run starts from the next
198
- // language slice instead of offset 0 every time (#1630).
199
- stateManager.setSearchRotation(scout.getState().searchRotation);
195
+ const record = () => {
196
+ recordSearchSeen(stateManager, result.candidates.map((c) => c.issue.url));
197
+ // Scout advanced its broad-phase language cursor in its own (provided,
198
+ // non-persisted) state; copy it back so the next run starts from the next
199
+ // language slice instead of offset 0 every time (#1630).
200
+ stateManager.setSearchRotation(scout.getState().searchRotation);
201
+ };
202
+ record();
200
203
  // In Gist mode setSearchSeen only writes the local cache; without a
201
204
  // checkpoint the seen-set never reaches the Gist and the next startup's
202
205
  // Gist refetch overwrites the cache with the empty remote copy (#1629).
203
- gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
206
+ gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, record);
204
207
  }
205
208
  // #1354: never surface issues the user already has an open PR for. Uses
206
209
  // scout's structured linked-PR metadata when present; candidates without it
@@ -54,7 +54,10 @@ export async function runSetup(options) {
54
54
  throw new ValidationError(formatUnknownKeyError(key, 'setup'));
55
55
  }
56
56
  }
57
- stateManager.batch(() => {
57
+ // Named so the Gist conflict path can re-apply the same settings on a
58
+ // refreshed baseline (maybeCheckpoint below).
59
+ const applySettings = () => {
60
+ warnings.length = 0;
58
61
  for (const setting of options.set) {
59
62
  const [key, ...valueParts] = setting.split('=');
60
63
  const value = valueParts.join('=');
@@ -368,11 +371,12 @@ export async function runSetup(options) {
368
371
  }
369
372
  }
370
373
  }
371
- });
374
+ };
375
+ stateManager.batch(applySettings);
372
376
  // Push the settings mutation to the Gist in gist mode (no-op locally).
373
377
  // Without this the change only hits the local cache and the next
374
378
  // bootstrap reverts it from the Gist (#1440).
375
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
379
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.batch(applySettings));
376
380
  return {
377
381
  success: true,
378
382
  settings: results,
@@ -58,8 +58,30 @@ export function validateMessage(message) {
58
58
  if (message.length > MAX_MESSAGE_LENGTH) {
59
59
  throw new ValidationError(`Message exceeds maximum length of ${MAX_MESSAGE_LENGTH} characters`);
60
60
  }
61
+ // The no-AI-attribution rule (CLAUDE.md, skills/contribution-ethics) was
62
+ // prompt-level only; this is the one write boundary every post/claim
63
+ // crosses, so enforce it here (audit 2026-10-30 L1).
64
+ // Best-effort guard, not enforcement: the prompt-level rule stays the
65
+ // contract; this catches the common pasted shapes. Format characters are
66
+ // stripped so "C\u200Blaude" is seen, and fenced code blocks are ignored
67
+ // so a reply quoting the trailer it removed is not rejected.
68
+ const cleaned = message.replace(/\p{Cf}/gu, '').replace(/```[\s\S]*?```/g, '');
69
+ if (AI_ATTRIBUTION_PATTERNS.some((pattern) => pattern.test(cleaned))) {
70
+ throw new ValidationError('Message contains AI attribution (a Co-Authored-By / Claude-Session trailer or "Generated with Claude Code"); remove it');
71
+ }
61
72
  return message;
62
73
  }
74
+ /**
75
+ * Markers the contribution-ethics skill forbids in anything posted to GitHub:
76
+ * trailer lines and the "Generated/Made/Built with|by Claude Code" footer,
77
+ * both anchored to line start (leading indent allowed, so a pasted Git log
78
+ * still matches) so quoting or negating one mid-sentence is fine.
79
+ */
80
+ const AI_ATTRIBUTION_PATTERNS = [
81
+ /^[ \t]*co-authored-by:.*\b(?:claude|anthropic)\b/im,
82
+ /^[ \t]*claude-session:/im,
83
+ /^[ \t]*(?:\u{1F916} ?)?(?:generated|made|built) (?:with|by) [[*]*claude code\b/imu,
84
+ ];
63
85
  /**
64
86
  * Validate that a repository identifier matches the "owner/repo" format.
65
87
  * Returns the identifier if valid, throws if invalid.
@@ -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.
@@ -133,7 +133,7 @@ export class GistConcurrencyError extends OssAutopilotError {
133
133
  remoteEtag;
134
134
  constructor(expectedEtag, remoteEtag) {
135
135
  super('Another machine pushed to the state Gist while this push was in flight, and the merge attempt also collided. ' +
136
- 'Re-run `oss-autopilot state --sync` to retry — your local mutations are still in memory.', 'CONCURRENCY_ERROR');
136
+ 'Your local mutations are still in memory, but `state --sync` cannot merge them: re-run the command that made the change.', 'CONCURRENCY_ERROR');
137
137
  this.expectedEtag = expectedEtag;
138
138
  this.remoteEtag = remoteEtag;
139
139
  this.name = 'GistConcurrencyError';
@@ -34,12 +34,29 @@ export interface EvalReport {
34
34
  highN: number;
35
35
  lowN: number;
36
36
  };
37
+ /**
38
+ * Merged and closed PRs that close an issue, and how many of them carry a
39
+ * vet-time grade. A low share means picks skipped `vet`, so calibration
40
+ * cannot be measured.
41
+ */
42
+ vetCoverage: {
43
+ graded: number;
44
+ of: number;
45
+ };
37
46
  /** Closures as ai-policy or rejected, per close month. */
38
47
  approachClosuresByMonth: Record<string, number>;
39
48
  };
40
49
  byGrade: EvalBucket[];
41
50
  byStars: EvalBucket[];
42
51
  byMonth: EvalBucket[];
52
+ /** All outcomes: first PR in the repo vs returning. */
53
+ byFirstInRepo: EvalBucket[];
54
+ /** Picks only; picks recorded before the trait existed land in `not recorded`. */
55
+ byIssueAuthorRole: EvalBucket[];
56
+ /** Picks only: open PRs by others on the issue at pick time. */
57
+ byCompetingPRs: EvalBucket[];
58
+ /** Picks with labels only; one pick can count in several label groups. */
59
+ byLabel: EvalBucket[];
43
60
  closeReasons: Record<string, number>;
44
61
  quality: {
45
62
  withReviewState: number;