@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
@@ -245,7 +245,7 @@ export async function runClaim(options) {
245
245
  let stateSaveWarning;
246
246
  try {
247
247
  const stateManager = getStateManager();
248
- stateManager.addIssue({
248
+ const issue = {
249
249
  id: number,
250
250
  url: options.issueUrl,
251
251
  repo: `${owner}/${repo}`,
@@ -256,11 +256,12 @@ export async function runClaim(options) {
256
256
  createdAt: issueCreatedAt,
257
257
  updatedAt: new Date().toISOString(),
258
258
  vetted: false,
259
- });
259
+ };
260
+ stateManager.addIssue(issue);
260
261
  // Push state to Gist if in Gist mode. Best-effort — the warning is
261
262
  // threaded into the structured output so MCP/dashboard consumers see
262
263
  // the degraded-sync signal, not just the stderr log (#1036 audit H1, #1370).
263
- gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
264
+ gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.addIssue(issue));
264
265
  }
265
266
  catch (error) {
266
267
  // The claim comment is live on GitHub but local state never tracked it —
@@ -34,17 +34,29 @@ export async function runConfig(options) {
34
34
  return { keys: CONFIG_KEY_REGISTRY };
35
35
  }
36
36
  const stateManager = getStateManager();
37
- const currentConfig = stateManager.getState().config;
38
37
  if (!options.key) {
39
38
  // Show current config
40
- return { config: currentConfig };
39
+ return { config: stateManager.getState().config };
41
40
  }
42
41
  if (!options.value) {
43
42
  throw new Error('Value required');
44
43
  }
45
- const value = options.value;
46
- // Handle specific config keys
47
- switch (options.key) {
44
+ const { key, value } = options;
45
+ const apply = () => applyConfigKey(stateManager, key, value);
46
+ apply();
47
+ // Push the config mutation to the Gist in gist mode (no-op locally).
48
+ // Without this the change only hits the local cache and the next
49
+ // bootstrap reverts it from the Gist (#1440).
50
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
51
+ return { success: true, key, value, ...(gistSyncWarning && { gistSyncWarning }) };
52
+ }
53
+ /**
54
+ * Apply one config key. Reads the current config fresh so the Gist conflict
55
+ * path can re-run it on a refreshed baseline without stale array merges.
56
+ */
57
+ function applyConfigKey(stateManager, key, value) {
58
+ const currentConfig = stateManager.getState().config;
59
+ switch (key) {
48
60
  case 'username': {
49
61
  stateManager.updateConfig({ githubUsername: validateGitHubUsername(value) });
50
62
  break;
@@ -177,12 +189,7 @@ export async function runConfig(options) {
177
189
  break;
178
190
  }
179
191
  default: {
180
- throw new ValidationError(formatUnknownKeyError(options.key, 'config'));
192
+ throw new ValidationError(formatUnknownKeyError(key, 'config'));
181
193
  }
182
194
  }
183
- // Push the config mutation to the Gist in gist mode (no-op locally).
184
- // Without this the change only hits the local cache and the next
185
- // bootstrap reverts it from the Gist (#1440).
186
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
187
- return { success: true, key: options.key, value, ...(gistSyncWarning && { gistSyncWarning }) };
188
195
  }
@@ -6,7 +6,7 @@
6
6
  * Domain logic lives in src/core/daily-logic.ts; this file is a thin
7
7
  * orchestration layer that wires up the phases and handles I/O.
8
8
  */
9
- import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, } from '../core/index.js';
9
+ import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, GistConcurrencyError, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, } from '../core/index.js';
10
10
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
11
11
  import { wrapUntrustedContent } from '../core/untrusted-content.js';
12
12
  import { computeStrategy, shouldComputeStrategy } from '../core/strategy.js';
@@ -255,6 +255,22 @@ async function updateRepoScores(prMonitor, prs, mergedCounts, closedCounts, sear
255
255
  });
256
256
  warn(MODULE, `[CLOSED_COUNT_UPDATES_FAILED] ${closedCountFailures} of ${closedCounts.size} closed count update(s) failed.`);
257
257
  }
258
+ // Ledger-derived signals, recomputed each run for every scored repo so a
259
+ // corrected closeReason clears hostility and repos without samples reset to null.
260
+ const ledgerSignals = computeLedgerRepoSignals([...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()], prs);
261
+ for (const repo of Object.keys(stateManager.getState().repoScores)) {
262
+ const derived = ledgerSignals.get(repo);
263
+ const update = {
264
+ avgResponseDays: derived?.avgResponseDays ?? null,
265
+ signals: { hasHostileComments: derived?.hasHostileComments ?? false },
266
+ };
267
+ try {
268
+ stateManager.updateRepoScore(repo, update);
269
+ }
270
+ catch (error) {
271
+ warn(MODULE, `Failed to update ledger signals for ${repo}: ${errorMessage(error)}`);
272
+ }
273
+ }
258
274
  // Update repo signals from observed open PR data
259
275
  const repoSignals = computeRepoSignals(prs);
260
276
  let signalUpdateFailures = 0;
@@ -621,6 +637,9 @@ async function executeDailyCheckInternal(token) {
621
637
  // One collector shared by every phase — threaded through explicitly so the
622
638
  // callgraph documents which phases can produce non-fatal warnings. See #1042.
623
639
  const warnings = [];
640
+ // This run's mutations cannot be re-applied, so if a concurrent tool's
641
+ // conflict recovery refreshes state mid-run they are gone; say so at the end.
642
+ const generationAtStart = getStateManager().refreshGeneration;
624
643
  // Surface gist-mode degradation in the machine-readable envelope (#1431):
625
644
  // a degraded process (local-only under a gist config, or a #1443 degraded
626
645
  // bootstrap) writes mutations that will not sync. Previously the only
@@ -772,6 +791,9 @@ async function executeDailyCheckInternal(token) {
772
791
  try {
773
792
  const sm = getStateManager();
774
793
  if (sm.isGistMode()) {
794
+ if (sm.refreshGeneration !== generationAtStart) {
795
+ recordWarning(warnings, 'gist-checkpoint', 'Gist checkpoint', new Error('state was refreshed from the Gist while this run was in progress; its state changes were dropped, re-run daily'));
796
+ }
775
797
  // checkpoint() resolves false (no throw) when the push failed after
776
798
  // its retry — previously discarded, reporting clean success while
777
799
  // cross-machine state silently drifted (#1370).
@@ -782,7 +804,12 @@ async function executeDailyCheckInternal(token) {
782
804
  }
783
805
  }
784
806
  catch (err) {
785
- recordWarning(warnings, 'gist-checkpoint', 'Gist checkpoint', err);
807
+ // A conflict cannot be recovered here (nothing re-applies a daily run):
808
+ // the next refresh drops this run's changes, so say that, not "retry".
809
+ const cause = err instanceof GistConcurrencyError
810
+ ? new Error("another machine pushed during this run; this run's state changes were NOT synced and will be dropped, re-run daily")
811
+ : err;
812
+ recordWarning(warnings, 'gist-checkpoint', 'Gist checkpoint', cause);
786
813
  }
787
814
  return result;
788
815
  }
@@ -15,6 +15,8 @@ export declare class GistSyncCoordinator {
15
15
  private readonly module;
16
16
  private manager;
17
17
  private pendingGistSyncWarnings;
18
+ /** `refreshGeneration` when the oldest pending warning was recorded. */
19
+ private pendingSince;
18
20
  private lastRecoveryAttemptAt;
19
21
  private recoveryHaltedReason;
20
22
  private degradedMutationCount;
@@ -66,7 +68,9 @@ export declare class GistSyncCoordinator {
66
68
  * notice when the pull actually replaced state (#1443). All dashboard pull
67
69
  * sites go through here; callers flush pending pushes first (#1417), so a
68
70
  * warning that is still pending at pull time means the flush failed. */
69
- pullFromGist(): Promise<boolean>;
71
+ pullFromGist(options?: {
72
+ force?: boolean;
73
+ }): Promise<boolean>;
70
74
  /** Re-attempt gist init while degraded (#1433). The serve process used to
71
75
  * bootstrap exactly once at CLI preAction — with its stderr discarded by
72
76
  * the detached spawn — and never retry, so one blip at startup meant
@@ -37,6 +37,8 @@ export class GistSyncCoordinator {
37
37
  // exactly the event that can destroy it (refreshFromGist wholesale-replaces
38
38
  // state). These clear only when a checkpoint PUSH succeeds.
39
39
  pendingGistSyncWarnings = [];
40
+ /** `refreshGeneration` when the oldest pending warning was recorded. */
41
+ pendingSince = 0;
40
42
  lastRecoveryAttemptAt = 0;
41
43
  recoveryHaltedReason = null;
42
44
  // Mutations acknowledged while degraded (#1433 review): a successful
@@ -65,9 +67,17 @@ export class GistSyncCoordinator {
65
67
  * so any previously pending warning is resolved with it. */
66
68
  recordGistSyncOutcome(warning) {
67
69
  if (warning === null) {
70
+ // ...unless a Gist refresh replaced state since the warning was
71
+ // recorded (a mutation's own conflict recovery does that without going
72
+ // through pullFromGist): the push then carried the Gist's copy, not the
73
+ // un-pushed change, so it is a loss, not a resolution (#1443 invariant).
74
+ if (this.manager.refreshGeneration !== this.pendingSince)
75
+ this.convertPendingWarningsToLossNotices();
68
76
  this.pendingGistSyncWarnings = [];
69
77
  return;
70
78
  }
79
+ if (this.pendingGistSyncWarnings.length === 0)
80
+ this.pendingSince = this.manager.refreshGeneration;
71
81
  if (!this.pendingGistSyncWarnings.includes(warning)) {
72
82
  this.pendingGistSyncWarnings.push(warning);
73
83
  }
@@ -153,8 +163,8 @@ export class GistSyncCoordinator {
153
163
  * notice when the pull actually replaced state (#1443). All dashboard pull
154
164
  * sites go through here; callers flush pending pushes first (#1417), so a
155
165
  * warning that is still pending at pull time means the flush failed. */
156
- async pullFromGist() {
157
- const refreshed = await this.manager.refreshFromGist();
166
+ async pullFromGist(options = {}) {
167
+ const refreshed = await this.manager.refreshFromGist(options);
158
168
  if (refreshed)
159
169
  this.convertPendingWarningsToLossNotices();
160
170
  return refreshed;
@@ -189,7 +199,14 @@ export class GistSyncCoordinator {
189
199
  try {
190
200
  await ensureGistPersistence(currentToken);
191
201
  // The upgrade replaced the core singleton — re-resolve our reference.
202
+ const previous = this.manager;
192
203
  this.manager = getStateManager();
204
+ // A swapped manager starts its own refreshGeneration; re-anchor any
205
+ // still-pending warnings to it so the next successful push is not
206
+ // misread as a loss (or a loss missed) against the old counter.
207
+ if (this.manager !== previous && this.pendingGistSyncWarnings.length > 0) {
208
+ this.pendingSince = this.manager.refreshGeneration;
209
+ }
193
210
  // Genuinely armed only: a retry can resolve via ANOTHER degraded
194
211
  // bootstrap (gist-backed, store disarmed) — that is not a recovery
195
212
  // and must not produce a recovery notice (#1443).
@@ -338,7 +338,7 @@ export async function startDashboardServer(options) {
338
338
  * Returns true when the state source changed (gist pull refreshed, local
339
339
  * file reloaded, or a gist recovery completed) — GET /api/data uses this
340
340
  * to decide whether to rebuild the cached payload (#1446 item 5). */
341
- async function reloadState() {
341
+ async function reloadState(options = {}) {
342
342
  if (gistSync.stateManager.isGistMode()) {
343
343
  await gistSync.flushPendingGistSync();
344
344
  // Both post-pull steps consume the same refreshFromGist outcome, in
@@ -350,7 +350,7 @@ export async function startDashboardServer(options) {
350
350
  // because the background-refresh path also pulls but replaces
351
351
  // cachedDigest unconditionally right after — adoption is a
352
352
  // reloadState-path concern only.
353
- const refreshed = await gistSync.pullFromGist();
353
+ const refreshed = await gistSync.pullFromGist(options);
354
354
  if (refreshed)
355
355
  cache.adoptNewerPulledDigest(gistSync.stateManager.getState().lastDigest);
356
356
  if (gistSync.gistBootstrapDegraded()) {
@@ -481,8 +481,9 @@ export async function startDashboardServer(options) {
481
481
  // never the loaded state) so the read-modify-write window excludes the
482
482
  // body-streaming time (#1397).
483
483
  await reloadState();
484
+ const sm = gistSync.stateManager;
484
485
  try {
485
- await applyMutation();
486
+ await sm.runMutation(async () => applyMutation());
486
487
  }
487
488
  catch (error) {
488
489
  if (!isConcurrencyConflict(error)) {
@@ -498,9 +499,12 @@ export async function startDashboardServer(options) {
498
499
  // in state-concurrency.test.ts. A second consecutive conflict means
499
500
  // sustained contention; surface it as a retryable 409 and let the SPA
500
501
  // re-prime and retry.
502
+ // The retry bypasses the 30s Gist refresh throttle: the reload above
503
+ // stamped it seconds ago, so a throttled reload would re-run the
504
+ // mutation against the same stale baseline (audit 2026-10-30 M1).
501
505
  try {
502
- await reloadState();
503
- await applyMutation();
506
+ await reloadState({ force: true });
507
+ await sm.runMutation(async () => applyMutation());
504
508
  }
505
509
  catch (retryError) {
506
510
  if (isConcurrencyConflict(retryError)) {
@@ -19,8 +19,9 @@ export async function runDismiss(options) {
19
19
  validateUrl(options.url);
20
20
  validateGitHubUrl(options.url, ISSUE_URL_PATTERN, 'issue');
21
21
  const stateManager = getStateManager();
22
- const added = stateManager.dismissIssue(options.url, new Date().toISOString());
23
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
22
+ const dismissedAt = new Date().toISOString();
23
+ const added = stateManager.dismissIssue(options.url, dismissedAt);
24
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.dismissIssue(options.url, dismissedAt));
24
25
  return { dismissed: added, url: options.url, ...(gistSyncWarning && { gistSyncWarning }) };
25
26
  }
26
27
  /**
@@ -36,6 +37,6 @@ export async function runUndismiss(options) {
36
37
  validateGitHubUrl(options.url, ISSUE_URL_PATTERN, 'issue');
37
38
  const stateManager = getStateManager();
38
39
  const removed = stateManager.undismissIssue(options.url);
39
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
40
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, () => stateManager.undismissIssue(options.url));
40
41
  return { undismissed: removed, url: options.url, ...(gistSyncWarning && { gistSyncWarning }) };
41
42
  }
@@ -73,7 +73,7 @@ export async function runGuidelinesStore(options) {
73
73
  // Push to Gist — autoSave only writes the local state-cache mirror in Gist
74
74
  // mode, so without this checkpoint the change never propagates across
75
75
  // machines (#1200).
76
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE);
76
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.setGuidelines(options.repo, options.content));
77
77
  return {
78
78
  repo: options.repo,
79
79
  byteSize: Buffer.byteLength(options.content, 'utf8'),
@@ -93,14 +93,18 @@ export async function runMarkExtracted(options) {
93
93
  const sm = getStateManager();
94
94
  const repoUrlPrefix = `https://github.com/${options.repo}/`;
95
95
  const now = new Date().toISOString();
96
- let marked = 0;
97
- for (const pr of [...(sm.getMergedPRs() ?? []), ...(sm.getClosedPRs() ?? [])]) {
98
- if (!pr.url.startsWith(repoUrlPrefix) || !pr.commentsFetchedAt || pr.learningsExtractedAt)
99
- continue;
100
- sm.markPRLearningsExtracted(pr.url, now);
101
- marked++;
102
- }
103
- const gistSyncWarning = marked > 0 ? await maybeCheckpoint(sm, MODULE) : null;
96
+ const mark = () => {
97
+ let n = 0;
98
+ for (const pr of [...(sm.getMergedPRs() ?? []), ...(sm.getClosedPRs() ?? [])]) {
99
+ if (!pr.url.startsWith(repoUrlPrefix) || !pr.commentsFetchedAt || pr.learningsExtractedAt)
100
+ continue;
101
+ sm.markPRLearningsExtracted(pr.url, now);
102
+ n++;
103
+ }
104
+ return n;
105
+ };
106
+ const marked = mark();
107
+ const gistSyncWarning = marked > 0 ? await maybeCheckpoint(sm, MODULE, mark) : null;
104
108
  return { repo: options.repo, marked, ...(gistSyncWarning && { gistSyncWarning }) };
105
109
  }
106
110
  /** Tombstone the guidelines file for `repo`. */
@@ -115,7 +119,7 @@ export async function runGuidelinesReset(options) {
115
119
  if (existed) {
116
120
  sm.deleteGuidelines(options.repo);
117
121
  // Push to Gist — see runGuidelinesStore note (#1200).
118
- gistSyncWarning = await maybeCheckpoint(sm, MODULE);
122
+ gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.deleteGuidelines(options.repo));
119
123
  }
120
124
  return { repo: options.repo, deleted: existed, ...(gistSyncWarning && { gistSyncWarning }) };
121
125
  }
@@ -180,15 +184,18 @@ export async function runFetchCorpus(options) {
180
184
  // list mirrors the input order until paginateAll fan-out, so we mark on
181
185
  // a per-bundle basis to be safe.
182
186
  const now = new Date().toISOString();
183
- for (const bundle of bundles) {
184
- sm.markPRCommentsFetched(bundle.prUrl, now);
185
- }
187
+ const stamp = () => {
188
+ for (const bundle of bundles) {
189
+ sm.markPRCommentsFetched(bundle.prUrl, now);
190
+ }
191
+ };
192
+ stamp();
186
193
  // Push commentsFetchedAt stamps to Gist so other machines don't re-fetch
187
194
  // the same PRs forever. autoSave only writes the local mirror in Gist
188
195
  // mode (#1200).
189
196
  let gistSyncWarning = null;
190
197
  if (bundles.length > 0) {
191
- gistSyncWarning = await maybeCheckpoint(sm, MODULE);
198
+ gistSyncWarning = await maybeCheckpoint(sm, MODULE, stamp);
192
199
  }
193
200
  // Surface pagination truncation per bundle (#1456): a truncated bundle is
194
201
  // missing its newest comments, so the host should know the corpus for that
@@ -17,11 +17,12 @@ export async function runInit(options) {
17
17
  validateGitHubUsername(options.username);
18
18
  const stateManager = getStateManager();
19
19
  // Set username in config
20
- stateManager.updateConfig({ githubUsername: options.username });
20
+ const apply = () => stateManager.updateConfig({ githubUsername: options.username });
21
+ apply();
21
22
  // Push the config mutation to the Gist in gist mode (no-op locally).
22
23
  // Without this the change only hits the local cache and the next
23
24
  // bootstrap reverts it from the Gist (#1440).
24
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
25
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
25
26
  return {
26
27
  username: options.username,
27
28
  message: 'Username saved. Run `daily` to fetch your open PRs from GitHub.',
@@ -8,6 +8,12 @@
8
8
  * - `openedAt` and `issueUrl` (GitHub's `closingIssuesReferences`) via
9
9
  * batched GraphQL; each answered PR is stamped `backfilledAt` so later
10
10
  * runs only query new entries.
11
+ * - `firstMaintainerResponseAt` (earliest maintainer comment or review, by
12
+ * the dormancy clock's rule), which feeds each repo's `avgResponseDays`.
13
+ * Each lookup stamps `responseRule`; entries with an older or missing rule
14
+ * (never looked up, or recorded under the old any-non-author rule) are
15
+ * re-queried once and their value overwritten. When the first page has no
16
+ * maintainer response, later pages are fetched (up to RESPONSE_MAX_PAGES).
11
17
  * - `closeReason` for closed-unmerged entries, from who closed the PR and its
12
18
  * last comments (core/close-reason.ts).
13
19
  * - `pick` for entries with no vet-time snapshot, from the curated issue list
@@ -26,6 +32,7 @@ export interface LedgerBackfillOutput {
26
32
  issueUrl: number;
27
33
  closeReason: number;
28
34
  pick: number;
35
+ firstMaintainerResponseAt: number;
29
36
  };
30
37
  /** Curated-list files scanned for vet scores. */
31
38
  listFiles: string[];
@@ -8,6 +8,12 @@
8
8
  * - `openedAt` and `issueUrl` (GitHub's `closingIssuesReferences`) via
9
9
  * batched GraphQL; each answered PR is stamped `backfilledAt` so later
10
10
  * runs only query new entries.
11
+ * - `firstMaintainerResponseAt` (earliest maintainer comment or review, by
12
+ * the dormancy clock's rule), which feeds each repo's `avgResponseDays`.
13
+ * Each lookup stamps `responseRule`; entries with an older or missing rule
14
+ * (never looked up, or recorded under the old any-non-author rule) are
15
+ * re-queried once and their value overwritten. When the first page has no
16
+ * maintainer response, later pages are fetched (up to RESPONSE_MAX_PAGES).
11
17
  * - `closeReason` for closed-unmerged entries, from who closed the PR and its
12
18
  * last comments (core/close-reason.ts).
13
19
  * - `pick` for entries with no vet-time snapshot, from the curated issue list
@@ -23,6 +29,7 @@ import { classifyCloseReason, classifySelfClose } from '../core/close-reason.js'
23
29
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
24
30
  import { getOctokit, requireGitHubToken, getStateManager, parseGitHubUrl } from '../core/index.js';
25
31
  import { isGraphqlRateLimited } from '../core/pr-graphql.js';
32
+ import { getFirstMaintainerResponseAt, MAINTAINER_RESPONSE_RULE } from '../core/review-analysis.js';
26
33
  import { maybeCheckpoint } from '../core/state.js';
27
34
  import { detectIssueListPath } from './locate-issue-list.js';
28
35
  import { findListEntryUrlByPrUrl } from './merge-loop.js';
@@ -30,12 +37,101 @@ import { parseIssueList } from './parse-list.js';
30
37
  const BATCH_SIZE = 40;
31
38
  /** The curated list keeps issues scored at least this (see /oss-search's score filter). */
32
39
  const LIST_KEEP_SCORE = 6;
40
+ /** Comments and reviews fetched per page when looking for the first maintainer response. */
41
+ const RESPONSE_PAGE_SIZE = 10;
42
+ /**
43
+ * Pages of each scanned before a PR is recorded as unanswered.
44
+ * ponytail: a PR with 50+ non-maintainer comments and reviews before the
45
+ * first maintainer reply reads as unanswered; raise this if that shows up.
46
+ */
47
+ const RESPONSE_MAX_PAGES = 5;
48
+ const responseSelection = (isPaged) => `
49
+ firstComments: comments(first: ${RESPONSE_PAGE_SIZE}${isPaged ? `, after: $c` : ''}) {
50
+ pageInfo { hasNextPage endCursor } nodes { author { __typename login } authorAssociation createdAt } }
51
+ reviews(first: ${RESPONSE_PAGE_SIZE}${isPaged ? `, after: $rc` : ''}) {
52
+ pageInfo { hasNextPage endCursor } nodes { author { __typename login } submittedAt } }`;
33
53
  const PR_FIELDS = `
34
54
  createdAt
35
55
  author { __typename login }
36
56
  closingIssuesReferences(first: 1) { nodes { url } }
37
57
  timelineItems(itemTypes: [CLOSED_EVENT], last: 1) { nodes { ... on ClosedEvent { actor { __typename login } } } }
38
- comments(last: 5) { nodes { author { __typename login } body } }`;
58
+ comments(last: 5) { nodes { author { __typename login } body } }${responseSelection(false)}`;
59
+ const MORE_RESPONSES_QUERY = `query($o: String!, $r: String!, $n: Int!, $c: String, $rc: String) {
60
+ repository(owner: $o, name: $r) { pullRequest(number: $n) {${responseSelection(true)}} } }`;
61
+ /** GraphQL actor in the REST `user` shape; `type: 'Bot'` lets isBotAuthor drop bots without a `[bot]` suffix. */
62
+ const restUser = (a) => (a ? { login: a.login, type: a.__typename } : null);
63
+ /** Earliest maintainer comment or review, by the same rule as live enrichment and the dormancy clock. */
64
+ function firstResponseAt(node) {
65
+ const comments = (node.firstComments?.nodes ?? [])
66
+ .filter((c) => c !== null)
67
+ .map((c) => ({ user: restUser(c.author), author_association: c.authorAssociation, created_at: c.createdAt }));
68
+ const reviews = (node.reviews?.nodes ?? [])
69
+ .filter((r) => r !== null)
70
+ .map((r) => ({ user: restUser(r.author), submitted_at: r.submittedAt }));
71
+ return node.author?.login ? getFirstMaintainerResponseAt(comments, reviews, node.author.login) : undefined;
72
+ }
73
+ const hasMore = (node) => !!(node.firstComments?.pageInfo?.hasNextPage || node.reviews?.pageInfo?.hasNextPage);
74
+ /** The next page of comments and reviews after the cursors `node` holds. */
75
+ async function fetchNextResponsePage(octokit, ref, node) {
76
+ const data = await octokit.graphql(MORE_RESPONSES_QUERY, {
77
+ o: ref.owner,
78
+ r: ref.repo,
79
+ n: ref.number,
80
+ c: node.firstComments?.pageInfo?.endCursor ?? null,
81
+ rc: node.reviews?.pageInfo?.endCursor ?? null,
82
+ });
83
+ return data.repository?.pullRequest;
84
+ }
85
+ /**
86
+ * First maintainer response for `node`, fetching later comment/review pages
87
+ * while none is found and more exist. Returns `isPending` when a page fetch
88
+ * failed, so the entry is left for the next run instead of recorded as
89
+ * unanswered. Rate-limit and auth errors rethrow.
90
+ */
91
+ async function resolveFirstResponse(octokit, url, node, warnings) {
92
+ const ref = parseGitHubUrl(url);
93
+ let at = firstResponseAt(node);
94
+ for (let page = 1; !at && ref && page < RESPONSE_MAX_PAGES && hasMore(node); page++) {
95
+ let more;
96
+ try {
97
+ more = await fetchNextResponsePage(octokit, ref, node);
98
+ }
99
+ catch (err) {
100
+ if (isRateLimitOrAuthError(err) || isGraphqlRateLimited(err))
101
+ throw err;
102
+ warnings.push(`response lookup for ${url} failed: ${errorMessage(err)}`);
103
+ return { isPending: true };
104
+ }
105
+ if (!more)
106
+ return { isPending: true };
107
+ // Earlier pages held no response, so only the new page matters. An
108
+ // exhausted connection re-queried past its last cursor comes back empty.
109
+ node.firstComments = more.firstComments;
110
+ node.reviews = more.reviews;
111
+ at = firstResponseAt(node);
112
+ }
113
+ return { at, isPending: false };
114
+ }
115
+ /** Record each fetched node's first response (URL -> at) in `responses`; pending lookups are left out. */
116
+ async function resolveResponses(octokit, nodes, responses, warnings) {
117
+ if (!nodes)
118
+ return;
119
+ for (const [url, node] of nodes) {
120
+ const { at, isPending } = await resolveFirstResponse(octokit, url, node, warnings);
121
+ if (!isPending)
122
+ responses.set(url, at);
123
+ }
124
+ }
125
+ /** Lookups in `responses` that found a response. */
126
+ function countFound(responses) {
127
+ let found = 0;
128
+ for (const at of responses.values())
129
+ if (at)
130
+ found++;
131
+ return found;
132
+ }
133
+ /** True when the entry's first response was never computed under the current maintainer rule. */
134
+ const isResponseStale = (e) => e.responseRule !== MAINTAINER_RESPONSE_RULE;
39
135
  /** One aliased GraphQL query for a batch of PR URLs. Fatal errors rethrow; null means the batch failed outright. */
40
136
  async function fetchBatch(octokit, urls, warnings) {
41
137
  const varDefs = [];
@@ -135,15 +231,18 @@ export async function runLedgerBackfill(options = {}) {
135
231
  if (!listPath)
136
232
  warnings.push('no curated issue list found; list vet scores were not imported');
137
233
  const lists = listPath ? readListFiles(listPath, warnings) : [];
138
- // 1. GitHub: openedAt, closing issue, close reason, for entries not yet
139
- // backfilled, plus self-closed entries recorded before selfCloseReason existed.
234
+ // 1. GitHub: openedAt, closing issue, close reason, first response, for
235
+ // entries not yet backfilled, plus one-time re-fetches for fields added
236
+ // later: selfCloseReason on self-closed entries, and firstMaintainerResponseAt
237
+ // on entries not looked up under the current maintainer rule.
140
238
  const needsFetch = [
141
- ...stateManager.getMergedPRs().filter((e) => !e.backfilledAt),
239
+ ...stateManager.getMergedPRs().filter((e) => !e.backfilledAt || isResponseStale(e)),
142
240
  ...stateManager
143
241
  .getClosedPRs()
144
- .filter((e) => !e.backfilledAt || (e.closeReason === 'self-closed' && !e.selfCloseReason)),
242
+ .filter((e) => !e.backfilledAt || isResponseStale(e) || (e.closeReason === 'self-closed' && !e.selfCloseReason)),
145
243
  ].map((e) => e.url);
146
244
  const nodes = new Map();
245
+ const responses = new Map();
147
246
  let fatal;
148
247
  if (needsFetch.length > 0) {
149
248
  const octokit = getOctokit(requireGitHubToken());
@@ -155,6 +254,7 @@ export async function runLedgerBackfill(options = {}) {
155
254
  failedBatches++;
156
255
  for (const [url, node] of batch ?? [])
157
256
  nodes.set(url, node);
257
+ await resolveResponses(octokit, batch, responses, warnings);
158
258
  }
159
259
  catch (err) {
160
260
  // Rate limit or auth: keep what earlier batches got, persist it, then rethrow.
@@ -181,9 +281,14 @@ export async function runLedgerBackfill(options = {}) {
181
281
  // A vet-time snapshot (joined by addMergedPRs/addClosedPRs) beats the list
182
282
  // score, and a list score for a different issue than the PR closes is dropped.
183
283
  const pick = fromList && fromList.issueUrl === issueUrl && !snapshotFor(issueUrl) ? fromList : undefined;
184
- return { openedAt: node?.createdAt, issueUrl, pick, ...(node && { backfilledAt: now }) };
284
+ return {
285
+ openedAt: node?.createdAt,
286
+ issueUrl,
287
+ pick,
288
+ ...(node && { backfilledAt: now }),
289
+ };
185
290
  };
186
- stateManager.batch(() => {
291
+ const applyLedger = () => {
187
292
  stateManager.addMergedPRs(merged.map((e) => ({ url: e.url, title: e.title, mergedAt: e.mergedAt, ...recovered(e) })));
188
293
  stateManager.addClosedPRs(closed.map((e) => {
189
294
  const node = nodes.get(e.url);
@@ -201,9 +306,13 @@ export async function runLedgerBackfill(options = {}) {
201
306
  const selfCloseReason = context && (e.closeReason ?? closeReason) === 'self-closed' ? classifySelfClose(context) : undefined;
202
307
  return { url: e.url, title: e.title, closedAt: e.closedAt, ...recovered(e), closeReason, selfCloseReason };
203
308
  }));
204
- });
309
+ // Overwrite, not fill-missing: a value recorded under an older rule is replaced.
310
+ for (const [url, at] of responses)
311
+ stateManager.setLedgerResponse(url, at, MAINTAINER_RESPONSE_RULE);
312
+ };
313
+ stateManager.batch(applyLedger);
205
314
  const after = countFilled([...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()]);
206
- const gistSyncWarning = await maybeCheckpoint(stateManager, 'ledger-backfill');
315
+ const gistSyncWarning = await maybeCheckpoint(stateManager, 'ledger-backfill', () => stateManager.batch(applyLedger));
207
316
  if (fatal)
208
317
  throw fatal;
209
318
  return {
@@ -213,6 +322,8 @@ export async function runLedgerBackfill(options = {}) {
213
322
  issueUrl: after.issueUrl - before.issueUrl,
214
323
  closeReason: after.closeReason - before.closeReason,
215
324
  pick: after.pick - before.pick,
325
+ // Lookups that found a response (overwrites included), not a before/after delta.
326
+ firstMaintainerResponseAt: countFound(responses),
216
327
  },
217
328
  listFiles: lists.map((l) => l.file),
218
329
  unresolved: needsFetch.length - nodes.size,
@@ -36,19 +36,21 @@ export async function runMove(options) {
36
36
  // Use current time — the CLI doesn't have cached PR data. The override
37
37
  // will auto-clear on the next daily run if the PR has new activity after this.
38
38
  const lastActivityAt = new Date().toISOString();
39
- stateManager.batch(() => {
39
+ const apply = () => stateManager.batch(() => {
40
40
  stateManager.setStatusOverride(options.prUrl, status, lastActivityAt);
41
41
  stateManager.unshelvePR(options.prUrl);
42
42
  });
43
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
43
+ apply();
44
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
44
45
  return withGistSyncWarning({ url: options.prUrl, target, description: `Moved to ${label}` }, gistSyncWarning);
45
46
  }
46
47
  case 'shelved': {
47
- stateManager.batch(() => {
48
+ const apply = () => stateManager.batch(() => {
48
49
  stateManager.shelvePR(options.prUrl);
49
50
  stateManager.clearStatusOverride(options.prUrl);
50
51
  });
51
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
52
+ apply();
53
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
52
54
  return withGistSyncWarning({
53
55
  url: options.prUrl,
54
56
  target,
@@ -56,11 +58,12 @@ export async function runMove(options) {
56
58
  }, gistSyncWarning);
57
59
  }
58
60
  case 'auto': {
59
- stateManager.batch(() => {
61
+ const apply = () => stateManager.batch(() => {
60
62
  stateManager.clearStatusOverride(options.prUrl);
61
63
  stateManager.unshelvePR(options.prUrl);
62
64
  });
63
- const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE);
65
+ apply();
66
+ const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
64
67
  return withGistSyncWarning({
65
68
  url: options.prUrl,
66
69
  target,
@@ -348,7 +348,10 @@ export async function runOvernightPushPrep(options) {
348
348
  async function persist() {
349
349
  if (options.dryRun)
350
350
  return;
351
- sm.setLastOvernight({ ...lastRun, prepared });
351
+ // Live record, not the `lastRun` snapshot: the re-apply below may run
352
+ // after a Gist refresh replaced it.
353
+ const record = () => sm.setLastOvernight({ ...(sm.getLastOvernight() ?? lastRun), prepared });
354
+ record();
352
355
  try {
353
356
  reportRecreated = writePreparedSection(lastRun.reportPath, prepared).reportRecreated;
354
357
  }
@@ -362,7 +365,7 @@ export async function runOvernightPushPrep(options) {
362
365
  // mistaken for a failed report write.
363
366
  if (!reportWarning)
364
367
  publishReport(sm, lastRun.reportPath);
365
- gistSyncWarning = await maybeCheckpoint(sm, MODULE);
368
+ gistSyncWarning = await maybeCheckpoint(sm, MODULE, record);
366
369
  }
367
370
  try {
368
371
  for (const [i, entry] of last.prepared.entries()) {