@oss-autopilot/core 3.37.0 → 3.39.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 (78) hide show
  1. package/dist/cli-registry.js +7 -4
  2. package/dist/cli.bundle.cjs +134 -127
  3. package/dist/commands/comments.js +4 -3
  4. package/dist/commands/config.js +18 -11
  5. package/dist/commands/daily-dismiss-filter.d.ts +37 -0
  6. package/dist/commands/daily-dismiss-filter.js +80 -0
  7. package/dist/commands/daily-merged-pr-notes.d.ts +27 -0
  8. package/dist/commands/daily-merged-pr-notes.js +166 -0
  9. package/dist/commands/daily-reviewed-prs.d.ts +41 -0
  10. package/dist/commands/daily-reviewed-prs.js +270 -0
  11. package/dist/commands/daily-warnings.d.ts +28 -0
  12. package/dist/commands/daily-warnings.js +37 -0
  13. package/dist/commands/daily.d.ts +22 -1
  14. package/dist/commands/daily.js +299 -108
  15. package/dist/commands/dashboard-cache.js +9 -2
  16. package/dist/commands/dashboard-data.js +40 -20
  17. package/dist/commands/dashboard-gist-sync.d.ts +9 -1
  18. package/dist/commands/dashboard-gist-sync.js +24 -3
  19. package/dist/commands/dashboard-server.js +9 -5
  20. package/dist/commands/dismiss.d.ts +25 -5
  21. package/dist/commands/dismiss.js +40 -11
  22. package/dist/commands/guidelines.js +21 -14
  23. package/dist/commands/init.js +3 -2
  24. package/dist/commands/ledger-backfill.js +4 -3
  25. package/dist/commands/move.js +9 -6
  26. package/dist/commands/overnight-push-prep.js +5 -2
  27. package/dist/commands/overnight.js +62 -24
  28. package/dist/commands/scout-bridge.js +4 -1
  29. package/dist/commands/search.js +9 -6
  30. package/dist/commands/setup.js +7 -3
  31. package/dist/commands/validation.d.ts +11 -0
  32. package/dist/commands/validation.js +38 -0
  33. package/dist/core/checklist-analysis.js +34 -0
  34. package/dist/core/closed-pr-status.d.ts +73 -0
  35. package/dist/core/closed-pr-status.js +113 -0
  36. package/dist/core/comment-decision.d.ts +10 -3
  37. package/dist/core/comment-decision.js +13 -5
  38. package/dist/core/comment-utils.d.ts +38 -1
  39. package/dist/core/comment-utils.js +124 -1
  40. package/dist/core/concurrency.d.ts +6 -0
  41. package/dist/core/concurrency.js +13 -0
  42. package/dist/core/daily-logic.d.ts +13 -1
  43. package/dist/core/daily-logic.js +59 -2
  44. package/dist/core/engaged-issues.d.ts +93 -0
  45. package/dist/core/engaged-issues.js +183 -0
  46. package/dist/core/errors.d.ts +4 -0
  47. package/dist/core/errors.js +11 -1
  48. package/dist/core/eval-report.d.ts +9 -0
  49. package/dist/core/eval-report.js +4 -0
  50. package/dist/core/gist-state-store.d.ts +5 -2
  51. package/dist/core/gist-state-store.js +7 -4
  52. package/dist/core/github-stats.d.ts +10 -0
  53. package/dist/core/github-stats.js +35 -0
  54. package/dist/core/index.d.ts +10 -5
  55. package/dist/core/index.js +9 -4
  56. package/dist/core/issue-conversation.d.ts +83 -12
  57. package/dist/core/issue-conversation.js +306 -118
  58. package/dist/core/merged-pr-notes.d.ts +192 -0
  59. package/dist/core/merged-pr-notes.js +340 -0
  60. package/dist/core/pick-snapshot.js +1 -1
  61. package/dist/core/pr-assembly.js +3 -0
  62. package/dist/core/pr-monitor.d.ts +62 -0
  63. package/dist/core/pr-monitor.js +113 -3
  64. package/dist/core/reviewed-prs-fetch.d.ts +91 -0
  65. package/dist/core/reviewed-prs-fetch.js +271 -0
  66. package/dist/core/reviewed-prs.d.ts +244 -0
  67. package/dist/core/reviewed-prs.js +380 -0
  68. package/dist/core/state-persistence.js +8 -24
  69. package/dist/core/state-schema.d.ts +6 -0
  70. package/dist/core/state-schema.js +9 -0
  71. package/dist/core/state.d.ts +106 -11
  72. package/dist/core/state.js +246 -24
  73. package/dist/core/types.d.ts +47 -0
  74. package/dist/core/urls.d.ts +13 -0
  75. package/dist/core/urls.js +16 -0
  76. package/dist/formatters/json.d.ts +186 -1
  77. package/dist/formatters/json.js +78 -0
  78. package/package.json +1 -1
@@ -6,59 +6,22 @@
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, computeLedgerRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, } from '../core/index.js';
9
+ import { getStateManager, parseGitHubUrl, issueRefKey, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, computeLedgerRepoSignals, GistConcurrencyError, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, collectEngagedIssues, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, selectClosedPRStatusCandidates, toClosedPRStatusUpdate, } from '../core/index.js';
10
10
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
11
+ import { DEFAULT_CONCURRENCY, runWorkerPool } from '../core/concurrency.js';
11
12
  import { wrapUntrustedContent } from '../core/untrusted-content.js';
12
13
  import { computeStrategy, shouldComputeStrategy } from '../core/strategy.js';
13
- import { warn } from '../core/logger.js';
14
+ import { debug, warn } from '../core/logger.js';
14
15
  import { emptyPRCountsResult } from '../core/github-stats.js';
15
16
  import { findRepoTransfers } from '../core/repo-score-manager.js';
16
17
  import { updateMonthlyAnalytics } from './dashboard-data.js';
17
18
  import { deduplicateDigest, compactActionableIssues, compactRepoGroups, buildStalenessWarning, } from '../formatters/json.js';
18
19
  import { reconcileMergedPRsWithList } from './merge-loop.js';
20
+ import { describeError, httpStatusLabel, isGoneError, nonFatalCatchWithWarning, recordWarning, } from './daily-warnings.js';
21
+ import { fenceMergedPRNotes, runMergedPRNotesPhase } from './daily-merged-pr-notes.js';
22
+ import { fenceReviewedPR, runReviewedPRsPhase } from './daily-reviewed-prs.js';
23
+ import { batchOnFreshBaseline, filterDismissedIssues } from './daily-dismiss-filter.js';
19
24
  const MODULE = 'daily';
20
- /**
21
- * Run a batch against a baseline that is fresh as of right now.
22
- *
23
- * A daily run spends tens of seconds on the network between loading state and
24
- * each of its saves. If the dashboard, `move`, or another CLI call writes
25
- * state.json in that time, the compare-and-swap in `saveState` rejects the
26
- * save, and because the baseline never moved, every later batch in the run is
27
- * rejected too: repo scores, analytics, the merged/closed ledger and lastDigest
28
- * were all dropped, surfacing only as warnings. Reloading first picks up the
29
- * other writer's change and shrinks the window to the batch itself.
30
- *
31
- * Only safe where the callback reads state live through the manager, as the
32
- * batches in this file do. A callback that writes from a snapshot taken
33
- * earlier would overwrite the other writer's fields, which is why this is not
34
- * done inside `StateManager.batch` for every caller.
35
- */
36
- function batchOnFreshBaseline(stateManager, fn) {
37
- stateManager.reloadIfChanged();
38
- stateManager.batch(fn);
39
- }
40
- /**
41
- * Record a non-fatal failure: push a structured entry into the run's warnings
42
- * collector AND emit the existing log line. Consumers (dashboard, MCP, tests)
43
- * inspect `DailyOutput.warnings` so a partial run is visible beyond log noise.
44
- * See #1042.
45
- */
46
- function recordWarning(warnings, phase, operation, err, humanMessage) {
47
- const message = humanMessage ?? errorMessage(err);
48
- warnings.push({ phase, operation, message });
49
- warn(MODULE, `${operation}: ${message}`);
50
- }
51
- /**
52
- * Variant of `nonFatalCatch` that also records a structured warning. Returns
53
- * the fallback value on error (same semantics as `nonFatalCatch`) AND pushes
54
- * an entry into the collector so the failure shows up in `DailyOutput.warnings`.
55
- */
56
- function nonFatalCatchWithWarning(opts) {
57
- return (err) => {
58
- recordWarning(opts.warnings, opts.phase, opts.operation, err);
59
- return opts.fallback;
60
- };
61
- }
62
25
  // Re-export domain functions so existing consumers (tests, dashboard, startup)
63
26
  // can continue importing from './daily.js' without changes.
64
27
  export { applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, printDigest, CRITICAL_STATUSES, } from '../core/index.js';
@@ -67,6 +30,22 @@ export { applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacit
67
30
  // (#1208 M7). Re-exported here for backward compatibility with anyone
68
31
  // importing from this module.
69
32
  import { buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest } from '../core/daily-logic.js';
33
+ /** Lowercased `owner/repo` of a GitHub PR or issue URL, or undefined when it does not parse. */
34
+ function repoKeyOf(url) {
35
+ const parsed = parseGitHubUrl(url);
36
+ return parsed ? `${parsed.owner}/${parsed.repo}`.toLowerCase() : undefined;
37
+ }
38
+ /**
39
+ * Reasons a successor of `pr` could be missing from this run's lists, or an
40
+ * empty array when the supersede check can be trusted for it.
41
+ */
42
+ function successorGapsFor(pr, gaps) {
43
+ const reasons = [...gaps.everywhere];
44
+ const repoKey = repoKeyOf(pr.url) ?? pr.repo.toLowerCase();
45
+ if (gaps.failedRepos.has(repoKey))
46
+ reasons.push(`a PR fetch in ${repoKey} failed`);
47
+ return reasons;
48
+ }
70
49
  // ---------------------------------------------------------------------------
71
50
  // Phase functions
72
51
  // ---------------------------------------------------------------------------
@@ -109,7 +88,8 @@ async function fetchPRData(prMonitor, token, warnings) {
109
88
  // Fetch merged PR counts, closed PR counts, recently closed PRs, recently merged PRs, and commented issues in parallel
110
89
  // All stats fetches are non-critical (cosmetic/scoring), so isolate their failure
111
90
  const issueMonitor = new IssueConversationMonitor(token);
112
- const [mergedResult, closedResult, recentlyClosedPRs, recentlyMergedPRs, issueConversationResult] = await Promise.all([
91
+ let didRecentlyMergedFetchFail = false;
92
+ const [mergedResult, closedResult, recentlyClosedPRs, recentlyMergedPRs] = await Promise.all([
113
93
  prMonitor.fetchUserMergedPRCounts(starFilter).catch(nonFatalCatchWithWarning({
114
94
  warnings,
115
95
  phase: 'fetch',
@@ -128,29 +108,48 @@ async function fetchPRData(prMonitor, token, warnings) {
128
108
  operation: 'fetch recently closed PRs',
129
109
  fallback: [],
130
110
  })),
131
- prMonitor.fetchRecentlyMergedPRs().catch(nonFatalCatchWithWarning({
132
- warnings,
133
- phase: 'fetch',
134
- operation: 'fetch recently merged PRs',
135
- fallback: [],
136
- })),
137
- // Issue conversation fetch has custom messaging based on the error content, so it keeps its bespoke catch.
138
- issueMonitor.fetchCommentedIssues().catch((error) => {
139
- if (isRateLimitOrAuthError(error))
140
- throw error;
141
- const msg = errorMessage(error);
142
- const needsSetup = msg.includes('No GitHub username configured');
143
- const humanMessage = needsSetup
144
- ? `Issue conversation tracking requires setup: ${msg}`
145
- : `Issue conversation fetch failed: ${msg}`;
146
- recordWarning(warnings, 'fetch', 'fetch commented issues', error, humanMessage);
147
- return {
148
- issues: [],
149
- failures: [{ issueUrl: 'N/A', error: `Issue conversation fetch failed: ${msg}` }],
150
- };
111
+ prMonitor.fetchRecentlyMergedPRs().catch((error) => {
112
+ // Phase 3.6 treats a fallback here as an incomplete view of the
113
+ // user's PRs (a just-merged successor would be invisible).
114
+ didRecentlyMergedFetchFail = true;
115
+ return nonFatalCatchWithWarning({
116
+ warnings,
117
+ phase: 'fetch',
118
+ operation: 'fetch recently merged PRs',
119
+ fallback: [],
120
+ })(error);
151
121
  }),
152
122
  ]);
153
- const commentedIssues = issueConversationResult.issues;
123
+ // Issue conversations run after the PR lists: the engaged set (#1862)
124
+ // needs the open, recently closed and recently merged PRs. The fetch has
125
+ // custom messaging based on the error content, so it keeps its bespoke catch.
126
+ const engaged = collectEngagedIssues({
127
+ recentlyClosedPRs,
128
+ recentlyMergedPRs,
129
+ claims: state.activeIssues,
130
+ openPRs: prs,
131
+ ledgerClosedPRs: getStateManager().getClosedPRs(),
132
+ ledgerMergedPRs: getStateManager().getMergedPRs(),
133
+ });
134
+ const issueConversationResult = await issueMonitor.fetchCommentedIssues({ engaged }).catch((error) => {
135
+ if (isRateLimitOrAuthError(error))
136
+ throw error;
137
+ const msg = errorMessage(error);
138
+ const needsSetup = msg.includes('No GitHub username configured');
139
+ const humanMessage = needsSetup
140
+ ? `Issue conversation tracking requires setup: ${msg}`
141
+ : `Issue conversation fetch failed: ${msg}`;
142
+ recordWarning(warnings, 'fetch', 'fetch commented issues', error, humanMessage);
143
+ return {
144
+ issues: [],
145
+ failures: [{ issueUrl: 'N/A', error: `Issue conversation fetch failed: ${msg}` }],
146
+ warnings: [],
147
+ };
148
+ });
149
+ const { issues: commentedIssues, warnings: issueMonitorWarnings } = issueConversationResult;
150
+ for (const message of issueMonitorWarnings) {
151
+ warnings.push({ phase: 'fetch', operation: 'fetch commented issues', message });
152
+ }
154
153
  if (issueConversationResult.failures.length > 0) {
155
154
  warnings.push({
156
155
  phase: 'fetch',
@@ -161,8 +160,24 @@ async function fetchPRData(prMonitor, token, warnings) {
161
160
  }
162
161
  const { repos: mergedCounts, monthlyCounts, monthlyOpenedCounts: openedFromMerged } = mergedResult;
163
162
  const { repos: closedCounts, monthlyCounts: monthlyClosedCounts, monthlyOpenedCounts: openedFromClosed, } = closedResult;
163
+ // A failed PR URL comes from the Search API, so it parses; should one not,
164
+ // its repo is unknown and the conservative reading is "could be anywhere".
165
+ const successorGaps = { everywhere: [], failedRepos: new Set() };
166
+ if (fetchResult.searchTruncated)
167
+ successorGaps.everywhere.push('the open-PR search was truncated');
168
+ if (didRecentlyMergedFetchFail)
169
+ successorGaps.everywhere.push('the recently-merged fetch failed');
170
+ for (const failure of failures) {
171
+ const repoKey = repoKeyOf(failure.prUrl);
172
+ if (repoKey)
173
+ successorGaps.failedRepos.add(repoKey);
174
+ else
175
+ successorGaps.everywhere.push(`a PR fetch failed for an unparseable URL (${failure.prUrl})`);
176
+ }
164
177
  return {
165
178
  searchedPRs: [...mergedResult.searchedPRs, ...closedResult.searchedPRs],
179
+ recentlyMergedFetchFailed: didRecentlyMergedFetchFail,
180
+ successorGaps,
166
181
  prs,
167
182
  failures,
168
183
  mergedCounts,
@@ -455,50 +470,26 @@ function partitionPRs(prMonitor, prs, recentlyClosedPRs, recentlyMergedPRs, warn
455
470
  * Assesses capacity, filters dismissed issues, computes actionable items,
456
471
  * and assembles the action menu.
457
472
  */
458
- function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, failures, warnings, previousLastDigestAt, unextractedMergeCount) {
473
+ function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, failures, warnings, previousLastDigestAt, unextractedMergeCount, closedPRStatusUpdates = [], mergedPRNotes = [], reviewedPRs = []) {
459
474
  const stateManager = getStateManager();
460
475
  // Assess capacity from active PRs only (shelved PRs excluded). Reload first
461
476
  // so maxActivePRs reflects a config change made while the run was fetching.
462
477
  stateManager.reloadIfChanged();
463
478
  const capacity = assessCapacity(activePRs, stateManager.getState().config.maxActivePRs, shelvedPRs.length);
479
+ // One nudge per issue (#1863): an issue listed under closedPRStatusUpdates
480
+ // leaves the commented-issue list for this run unless it carries a new
481
+ // maintainer reply. The claim Phase 3.6 just released (or never recorded)
482
+ // means the issue is, or will be from the next run, back in
483
+ // fetchCommentedIssues' results; without a reply it would only be listed
484
+ // as "waiting" there, which the status nudge already covers. A reply is a
485
+ // different ask (answer the maintainer) and must stay visible under
486
+ // issue_replies even though the closed-PR workflow also shows the thread.
487
+ // Once the user posts the status update the nudge drops and the issue
488
+ // returns to the regular reply flow.
489
+ const statusUpdateIssueKeys = new Set(closedPRStatusUpdates.map((u) => issueRefKey(u.issueUrl) ?? u.issueUrl));
490
+ const remainingCommentedIssues = commentedIssues.filter((issue) => issue.status === 'new_response' || !statusUpdateIssueKeys.has(issueRefKey(issue.url) ?? issue.url));
464
491
  // Filter dismissed issues: suppress if dismissed after last response, resurface + auto-undismiss if new activity.
465
- // Batch: undismissIssue calls trigger autoSave — batch produces a single disk write for all auto-undismisses.
466
- let filteredCommentedIssues = [];
467
- try {
468
- batchOnFreshBaseline(stateManager, () => {
469
- filteredCommentedIssues = commentedIssues.filter((issue) => {
470
- const dismissedAt = stateManager.getIssueDismissedAt(issue.url);
471
- if (!dismissedAt)
472
- return true; // Not dismissed — include
473
- if (issue.status === 'new_response') {
474
- const responseTime = new Date(issue.lastResponseAt).getTime();
475
- const dismissTime = new Date(dismissedAt).getTime();
476
- if (isNaN(responseTime) || isNaN(dismissTime)) {
477
- // Invalid timestamp — fail open (include issue to be safe) without
478
- // permanently removing dismiss record (may be a transient data issue)
479
- warn(MODULE, `Invalid timestamp in dismiss check for ${issue.url}, including issue`);
480
- return true;
481
- }
482
- if (responseTime > dismissTime) {
483
- // New activity after dismiss — auto-undismiss and resurface
484
- warn(MODULE, `Auto-undismissing issue ${issue.url}: new response at ${issue.lastResponseAt} after dismiss at ${dismissedAt}`);
485
- try {
486
- stateManager.undismissIssue(issue.url);
487
- }
488
- catch (error) {
489
- recordWarning(warnings, 'dismiss-filter', `persist auto-undismiss for ${issue.url}`, error);
490
- }
491
- return true;
492
- }
493
- }
494
- // Still dismissed (last response is at or before dismiss timestamp)
495
- return false;
496
- });
497
- });
498
- }
499
- catch (error) {
500
- recordWarning(warnings, 'dismiss-filter', 'persist auto-undismiss state', error);
501
- }
492
+ const filteredCommentedIssues = filterDismissedIssues(stateManager, remainingCommentedIssues, warnings);
502
493
  const issueResponses = filteredCommentedIssues.filter((i) => i.status === 'new_response');
503
494
  const summary = formatSummary(digest, capacity, issueResponses);
504
495
  // Auto-undismiss mutations are auto-saved by undismissIssue()
@@ -511,7 +502,12 @@ function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, fa
511
502
  // Close candidates are usually dormant and auto-shelved, so count them over
512
503
  // all open PRs (digest.openPRs includes shelved), not activePRs.
513
504
  const closeSuggested = digest.openPRs.filter(shouldSuggestClose).length;
514
- const actionMenu = computeActionMenu(actionableIssues, capacity, filteredCommentedIssues, { ...attention, closeSuggested }, unextractedMergeCount);
505
+ const actionMenu = computeActionMenu(actionableIssues, capacity, filteredCommentedIssues, { ...attention, closeSuggested }, unextractedMergeCount, closedPRStatusUpdates.length,
506
+ // One action per entry the workflow handles on its own; covered
507
+ // thanks-only entries ride along with their carrier.
508
+ mergedPRNotes.filter((entry) => entry.ackCoveredBy === undefined).length,
509
+ // Other people's PRs: a menu item, never a capacity or attention count.
510
+ reviewedPRs.length);
515
511
  const repoGroups = groupPRsByRepo(activePRs);
516
512
  // Periodic strategy snapshot (#1270 Step 2). Cadence-gated to fire every
517
513
  // 30 days OR after 5+ PRs merge since the last snapshot, whichever comes
@@ -546,6 +542,171 @@ function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, fa
546
542
  strategySummary,
547
543
  };
548
544
  }
545
+ const CLOSED_PR_STATUS_OPERATION = 'closed-PR status updates';
546
+ /**
547
+ * Phase 3.6: Closed-PR status updates (#1863).
548
+ *
549
+ * A PR of the user's that closed without merge usually leaves its write-up
550
+ * in the PR thread while the linked issue still shows their claim as the
551
+ * latest word. For each such PR, release the local claim and, unless the
552
+ * user has already commented on the issue since the close, hand the pair to
553
+ * the action menu so the workflow can draft a status comment (never
554
+ * auto-posted).
555
+ *
556
+ * The release is an irreversible state write, so every guard errs toward
557
+ * doing nothing:
558
+ * - A candidate is withheld (one warning naming each withheld PR) when this
559
+ * run's PR fetch may have missed a successor for it: the open-PR search
560
+ * was truncated, the recently-merged fetch failed, or a per-PR fetch in
561
+ * the candidate's own repo failed (`SuccessorGaps`). Candidates in other
562
+ * repos, and closed PRs the fetched lists already supersede, are
563
+ * unaffected.
564
+ * - Only PRs the configured user closed themselves count. A maintainer or
565
+ * bot close is neither released nor nudged (`PRMonitor.fetchPRClosedBy`).
566
+ * - The supersede check (`selectClosedPRStatusCandidates`) treats any open
567
+ * PR that mentions the issue or the closed PR as a successor, closing
568
+ * keyword or not, and drops PRs outside the 7-day window.
569
+ * - An issue the user dismissed at or after the close (the workflow's
570
+ * "skip" choice runs the existing `dismiss` command) is skipped entirely.
571
+ * - `releaseIssue(issueUrl, closedAt)` keeps a claim recorded after the
572
+ * close: a re-claim inside the window is deliberate.
573
+ * - A 404/410 from either lookup drops the candidate with a warning instead
574
+ * of nudging every day about something that is gone.
575
+ *
576
+ * Releasing does not change capacity (`assessCapacity` counts open PRs
577
+ * only); it takes the issue out of `activeIssues`, so it stops reading as in
578
+ * progress and re-enters the commented-issue monitor from the next run.
579
+ *
580
+ * "Only once": there is no posted-stamp in state. The nudge disappears when
581
+ * the user's comment lands on the issue, when they dismiss the issue URL,
582
+ * and at the latest when the PR leaves the 7-day window.
583
+ *
584
+ * Non-fatal: failures land in `warnings[]` under `closed-pr-status`, except
585
+ * rate-limit/auth errors, which propagate like every other phase's.
586
+ */
587
+ async function prepareClosedPRStatusUpdates(prMonitor, token, input, warnings) {
588
+ const { recentlyClosedPRs, openPRs, recentlyMergedPRs, successorGaps } = input;
589
+ if (recentlyClosedPRs.every((pr) => pr.issueUrl === undefined))
590
+ return [];
591
+ const stateManager = getStateManager();
592
+ const username = stateManager.getState().config.githubUsername;
593
+ if (!username) {
594
+ recordWarning(warnings, 'closed-pr-status', CLOSED_PR_STATUS_OPERATION, null, 'skipped: no GitHub username configured');
595
+ return [];
596
+ }
597
+ const user = username.toLowerCase();
598
+ // recentlyMergedPRs is also in the ledger by now (Phase 3 wrote it), but
599
+ // that write is best-effort inside a try/catch, so the fresh list stays an
600
+ // input of its own: a successor must never go unseen because a save failed.
601
+ const notDismissed = selectClosedPRStatusCandidates(recentlyClosedPRs, [
602
+ ...openPRs,
603
+ ...recentlyMergedPRs,
604
+ ...stateManager.getMergedPRs(),
605
+ ]).filter((pr) => {
606
+ const dismissedAt = stateManager.getIssueDismissedAt(pr.issueUrl);
607
+ if (dismissedAt === undefined)
608
+ return true;
609
+ // Dismissed at/after the close (or with an unreadable stamp): the user
610
+ // declined this nudge. Dismissed before the close: unrelated, proceed.
611
+ const dismissedMs = Date.parse(dismissedAt);
612
+ if (Number.isNaN(dismissedMs) || dismissedMs >= Date.parse(pr.closedAt)) {
613
+ debug(MODULE, `closed-pr-status: ${pr.issueUrl} dismissed at ${dismissedAt}, after close ${pr.closedAt}; skipping`);
614
+ return false;
615
+ }
616
+ return true;
617
+ });
618
+ // Gate after selection, per candidate: a closed PR the fetched lists
619
+ // already supersede needs no complete view, and a per-PR failure in
620
+ // another repo cannot hide this PR's successor. Withheld candidates are
621
+ // named so the user can tell which release did not happen.
622
+ const withheld = [];
623
+ const candidates = notDismissed.filter((pr) => {
624
+ const reasons = successorGapsFor(pr, successorGaps);
625
+ if (reasons.length === 0)
626
+ return true;
627
+ withheld.push(`${pr.url} (${reasons.join('; ')})`);
628
+ return false;
629
+ });
630
+ if (withheld.length > 0) {
631
+ recordWarning(warnings, 'closed-pr-status', CLOSED_PR_STATUS_OPERATION, null, `withheld, supersede check unreliable on this run's partial PR fetch: ${withheld.join(', ')}`);
632
+ }
633
+ if (candidates.length === 0)
634
+ return [];
635
+ const issueMonitor = new IssueConversationMonitor(token);
636
+ // Outcome per candidate that passed both lookups, keyed by candidate so
637
+ // the output keeps `candidates` order however the workers finish.
638
+ const verified = new Map();
639
+ await runWorkerPool(candidates, async (pr) => {
640
+ let closedBy;
641
+ try {
642
+ closedBy = await prMonitor.fetchPRClosedBy(pr.url);
643
+ }
644
+ catch (error) {
645
+ if (isRateLimitOrAuthError(error))
646
+ throw error;
647
+ const detail = isGoneError(error)
648
+ ? `PR no longer reachable (${httpStatusLabel(error)}); dropped`
649
+ : `${describeError(error)}; cannot verify who closed it, dropped`;
650
+ recordWarning(warnings, 'closed-pr-status', `check who closed ${pr.url}`, error, detail);
651
+ return;
652
+ }
653
+ if (closedBy?.toLowerCase() !== user) {
654
+ debug(MODULE, `closed-pr-status: ${pr.url} closed by ${closedBy ?? 'unknown'}, not ${username}; skipping`);
655
+ return;
656
+ }
657
+ let hasCommented = false;
658
+ try {
659
+ hasCommented = await issueMonitor.hasUserCommentSince(pr.issueUrl, pr.closedAt);
660
+ }
661
+ catch (error) {
662
+ if (isRateLimitOrAuthError(error))
663
+ throw error;
664
+ if (isGoneError(error)) {
665
+ recordWarning(warnings, 'closed-pr-status', `check comments on ${pr.issueUrl}`, error, `issue no longer reachable (${httpStatusLabel(error)}); dropped`);
666
+ return;
667
+ }
668
+ // Unknown whether the user already posted: keep the nudge (the
669
+ // workflow shows the issue thread before anything is drafted) and
670
+ // say why rather than silently dropping it.
671
+ recordWarning(warnings, 'closed-pr-status', `check comments on ${pr.issueUrl}`, error, `${describeError(error)}; keeping the nudge`);
672
+ }
673
+ verified.set(pr, { hasCommented });
674
+ }, DEFAULT_CONCURRENCY);
675
+ // Release after the lookups: only PRs the user closed themselves reach
676
+ // this point. The user may have told the issue already (no nudge) and the
677
+ // claim still goes: the PR is closed per GitHub either way.
678
+ const toRelease = candidates.filter((pr) => verified.has(pr));
679
+ if (toRelease.length > 0) {
680
+ try {
681
+ batchOnFreshBaseline(stateManager, () => {
682
+ for (const pr of toRelease) {
683
+ stateManager.releaseIssue(pr.issueUrl, pr.closedAt);
684
+ }
685
+ });
686
+ }
687
+ catch (error) {
688
+ recordWarning(warnings, 'closed-pr-status', 'release issue claims', error);
689
+ }
690
+ }
691
+ return toRelease.filter((pr) => verified.get(pr)?.hasCommented === false).map((pr) => toClosedPRStatusUpdate(pr));
692
+ }
693
+ /**
694
+ * Phase 3.6 entry point: runs {@link prepareClosedPRStatusUpdates} and turns
695
+ * any non-fatal failure into a `closed-pr-status` warning plus an empty list.
696
+ * Rate-limit/auth errors from the per-candidate GitHub calls end the run
697
+ * like every other phase's.
698
+ */
699
+ async function runClosedPRStatusPhase(prMonitor, token, input, warnings) {
700
+ try {
701
+ return await prepareClosedPRStatusUpdates(prMonitor, token, input, warnings);
702
+ }
703
+ catch (error) {
704
+ if (isRateLimitOrAuthError(error))
705
+ throw error;
706
+ recordWarning(warnings, 'closed-pr-status', 'prepare closed-PR status updates', error);
707
+ return [];
708
+ }
709
+ }
549
710
  // ---------------------------------------------------------------------------
550
711
  // Public API
551
712
  // ---------------------------------------------------------------------------
@@ -604,6 +765,9 @@ export function toDailyOutput(result) {
604
765
  // no `listUpdates` key at all — serialized output and goldens unchanged.
605
766
  ...(result.listUpdates && { listUpdates: result.listUpdates }),
606
767
  ...(result.pendingLearnings && { pendingLearnings: result.pendingLearnings }),
768
+ ...(result.closedPRStatusUpdates && { closedPRStatusUpdates: result.closedPRStatusUpdates }),
769
+ ...(result.mergedPRNotes && { mergedPRNotes: result.mergedPRNotes.map((entry) => fenceMergedPRNotes(entry)) }),
770
+ ...(result.reviewedPRs && { reviewedPRs: result.reviewedPRs.map((entry) => fenceReviewedPR(entry)) }),
607
771
  };
608
772
  }
609
773
  /**
@@ -619,6 +783,8 @@ export function toDailyOutput(result) {
619
783
  * 3. updateAnalytics — store monthly chart data
620
784
  * 4. partitionPRs — shelve/unshelve, generate digest
621
785
  * 5. generateDigestOutput — capacity, dismiss filter, action menu assembly
786
+ * plus the read-only side phases 3.6 (closed-PR status), 3.7 (merged-PR
787
+ * notes) and 3.8 (review follow-ups on PRs the user reviewed, #1857).
622
788
  *
623
789
  * @param token - GitHub personal access token
624
790
  * @returns Deduplicated daily output
@@ -637,6 +803,9 @@ async function executeDailyCheckInternal(token) {
637
803
  // One collector shared by every phase — threaded through explicitly so the
638
804
  // callgraph documents which phases can produce non-fatal warnings. See #1042.
639
805
  const warnings = [];
806
+ // This run's mutations cannot be re-applied, so if a concurrent tool's
807
+ // conflict recovery refreshes state mid-run they are gone; say so at the end.
808
+ const generationAtStart = getStateManager().refreshGeneration;
640
809
  // Surface gist-mode degradation in the machine-readable envelope (#1431):
641
810
  // a degraded process (local-only under a gist config, or a #1443 degraded
642
811
  // bootstrap) writes mutations that will not sync. Previously the only
@@ -661,7 +830,7 @@ async function executeDailyCheckInternal(token) {
661
830
  (loadRecovery.rejectedPath ? `; rejected file preserved at ${loadRecovery.rejectedPath}` : '')));
662
831
  }
663
832
  // Phase 1: Fetch all PR data from GitHub
664
- const { prs, failures, mergedCounts, closedCounts, searchedPRs, monthlyCounts, monthlyClosedCounts, openedFromMerged, openedFromClosed, recentlyClosedPRs, recentlyMergedPRs, commentedIssues, } = await fetchPRData(prMonitor, token, warnings);
833
+ const { prs, failures, mergedCounts, closedCounts, searchedPRs, monthlyCounts, monthlyClosedCounts, openedFromMerged, openedFromClosed, recentlyClosedPRs, recentlyMergedPRs, recentlyMergedFetchFailed, commentedIssues, successorGaps, } = await fetchPRData(prMonitor, token, warnings);
665
834
  // Phase 2: Update repo scores (signals, star counts, trust sync)
666
835
  await updateRepoScores(prMonitor, prs, mergedCounts, closedCounts, searchedPRs, warnings);
667
836
  // Phase 3: Persist monthly analytics and store merged/closed PR history.
@@ -767,19 +936,33 @@ async function executeDailyCheckInternal(token) {
767
936
  // persistence:'provided' checkpoint() has no gist store and no local store, so
768
937
  // it persisted nothing. Cross-tool sharing happens through buildScoutState
769
938
  // reading AgentState, not through pushing events at scout.
939
+ // Phase 3.6: closed-PR status nudges + claim release (#1863).
940
+ const closedPRStatusUpdates = await runClosedPRStatusPhase(prMonitor, token, { openPRs: prs, recentlyClosedPRs, recentlyMergedPRs, successorGaps }, warnings);
941
+ // Phase 3.7: maintainer notes on recently merged PRs (#1861). Read-only.
942
+ const mergedPRNotes = await runMergedPRNotesPhase(prMonitor, { recentlyMergedPRs, recentlyMergedFetchFailed }, warnings);
943
+ // Phase 3.8: review follow-ups on PRs the user reviewed (#1857). Read-only.
944
+ const reviewedPRs = await runReviewedPRsPhase(prMonitor, warnings);
770
945
  // Capture lastDigestAt BEFORE Phase 4 overwrites it with the current run's timestamp.
771
946
  // Used by collectActionableIssues to determine which PRs are "new" (created since last digest).
772
947
  const previousLastDigestAt = getStateManager().getState().lastDigestAt;
773
948
  // Phase 4: Partition PRs, generate and save digest
774
949
  const { activePRs, shelvedPRs, digest } = partitionPRs(prMonitor, prs, recentlyClosedPRs, recentlyMergedPRs, warnings);
775
950
  // Phase 5: Build structured output (capacity, dismiss filter, action menu)
776
- const result = generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, failures, warnings, previousLastDigestAt, unextractedMergeCount);
951
+ const result = generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, failures, warnings, previousLastDigestAt, unextractedMergeCount, closedPRStatusUpdates, mergedPRNotes, reviewedPRs);
777
952
  if (listUpdates) {
778
953
  result.listUpdates = listUpdates;
779
954
  }
780
955
  if (pendingLearnings) {
781
956
  result.pendingLearnings = pendingLearnings;
782
957
  }
958
+ if (closedPRStatusUpdates.length > 0) {
959
+ result.closedPRStatusUpdates = closedPRStatusUpdates;
960
+ }
961
+ if (mergedPRNotes.length > 0) {
962
+ result.mergedPRNotes = mergedPRNotes;
963
+ }
964
+ if (reviewedPRs.length > 0)
965
+ result.reviewedPRs = reviewedPRs;
783
966
  // Checkpoint: push state to Gist if in Gist mode.
784
967
  // If getStateManagerAsync was not called before this command ran,
785
968
  // isGistMode() will be false and checkpoint is correctly skipped.
@@ -788,6 +971,9 @@ async function executeDailyCheckInternal(token) {
788
971
  try {
789
972
  const sm = getStateManager();
790
973
  if (sm.isGistMode()) {
974
+ if (sm.refreshGeneration !== generationAtStart) {
975
+ 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'));
976
+ }
791
977
  // checkpoint() resolves false (no throw) when the push failed after
792
978
  // its retry — previously discarded, reporting clean success while
793
979
  // cross-machine state silently drifted (#1370).
@@ -798,7 +984,12 @@ async function executeDailyCheckInternal(token) {
798
984
  }
799
985
  }
800
986
  catch (err) {
801
- recordWarning(warnings, 'gist-checkpoint', 'Gist checkpoint', err);
987
+ // A conflict cannot be recovered here (nothing re-applies a daily run):
988
+ // the next refresh drops this run's changes, so say that, not "retry".
989
+ const cause = err instanceof GistConcurrencyError
990
+ ? new Error("another machine pushed during this run; this run's state changes were NOT synced and will be dropped, re-run daily")
991
+ : err;
992
+ recordWarning(warnings, 'gist-checkpoint', 'Gist checkpoint', cause);
802
993
  }
803
994
  return result;
804
995
  }
@@ -8,7 +8,7 @@
8
8
  * it as a collaborator; nothing here touches req/res.
9
9
  */
10
10
  import * as fs from 'node:fs';
11
- import { getStateManager, applyStatusOverrides, classifyAttentionBucket } from '../core/index.js';
11
+ import { getStateManager, applyStatusOverrides, classifyAttentionBucket, isCoveredByDismiss } from '../core/index.js';
12
12
  import { errorMessage } from '../core/errors.js';
13
13
  import { warn } from '../core/logger.js';
14
14
  import { computePRsByRepo, computeTopRepos, getMonthlyData, buildDashboardStats, reconcileShelvePartition, storedToMergedPRs, storedToClosedPRs, } from './dashboard-data.js';
@@ -95,8 +95,15 @@ export function buildDashboardJson(digest, state, commentedIssues, allMergedPRs,
95
95
  const filteredMergedPRs = mergedPRs.filter(isAboveMinStars);
96
96
  const filteredClosedPRs = closedPRs.filter(isAboveMinStars);
97
97
  const stats = buildDashboardStats(overriddenDigest, state, filteredMergedPRs.length, filteredClosedPRs.length);
98
+ // Same rule as the daily run's dismiss filter (#1862): a dismiss hides the
99
+ // reply it was stamped against; a newer reply resurfaces the issue.
98
100
  const dismissedIssues = state.config.dismissedIssues || {};
99
- const issueResponses = commentedIssues.filter((i) => i.status === 'new_response' && !(i.url in dismissedIssues));
101
+ const issueResponses = commentedIssues.filter((i) => {
102
+ if (i.status !== 'new_response')
103
+ return false;
104
+ const dismissedAt = dismissedIssues[i.url];
105
+ return !dismissedAt || !isCoveredByDismiss(dismissedAt, i.lastResponseAt);
106
+ });
100
107
  // Build repo metadata map from repoScores — omit repos without stars or language to avoid empty entries
101
108
  const repoMetadata = {};
102
109
  for (const [repo, score] of Object.entries(repoScores)) {
@@ -3,7 +3,7 @@
3
3
  * Handles GitHub API calls, PR grouping, stats computation, and monthly chart data.
4
4
  * Consumed by the dashboard HTTP server (dashboard-server.ts) for the SPA API.
5
5
  */
6
- import { getStateManager, PRMonitor, IssueConversationMonitor, getOctokit, CRITICAL_STATUSES, applyStatusOverrides, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, } from '../core/index.js';
6
+ import { getStateManager, PRMonitor, IssueConversationMonitor, getOctokit, CRITICAL_STATUSES, applyStatusOverrides, collectEngagedIssues, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, } from '../core/index.js';
7
7
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
8
8
  import { warn } from '../core/logger.js';
9
9
  import { emptyPRCountsResult, fetchMergedPRsSince, fetchClosedPRsSince } from '../core/github-stats.js';
@@ -165,6 +165,14 @@ export function updateMonthlyAnalytics(prs, monthlyCounts, monthlyClosedCounts,
165
165
  }
166
166
  return failures;
167
167
  }
168
+ /**
169
+ * The partial-data banner entry for the issue monitor's notices (#1862): the
170
+ * direct-fetch cap, a gone issue, a truncated thread. The monitor already
171
+ * logged each one; the banner lists operations, so they collapse to one label.
172
+ */
173
+ function engagedScanLabels(issueMonitorWarnings) {
174
+ return issueMonitorWarnings.length > 0 ? ['scan engaged issues'] : [];
175
+ }
168
176
  /**
169
177
  * Fetch fresh dashboard data from GitHub.
170
178
  * Returns the digest and commented issues, updating state as a side effect.
@@ -217,7 +225,7 @@ export async function fetchDashboardData(token) {
217
225
  return fallback;
218
226
  };
219
227
  };
220
- const [{ prs, failures, warnings: fetchWarnings }, recentlyClosedPRs, recentlyMergedPRs, mergedResult, closedResult, fetchedIssues, newMergedPRs, newClosedPRs,] = await Promise.all([
228
+ const [{ prs, failures, warnings: fetchWarnings }, recentlyClosedPRs, recentlyMergedPRs, mergedResult, closedResult, newMergedPRs, newClosedPRs,] = await Promise.all([
221
229
  prMonitor.fetchUserOpenPRs(),
222
230
  prMonitor.fetchRecentlyClosedPRs().catch(trackingCatch('fetch recently closed PRs', [])),
223
231
  prMonitor.fetchRecentlyMergedPRs().catch(trackingCatch('fetch recently merged PRs', [])),
@@ -227,27 +235,39 @@ export async function fetchDashboardData(token) {
227
235
  prMonitor
228
236
  .fetchUserClosedPRCounts(starFilter)
229
237
  .catch(trackingCatch('fetch closed PR counts', emptyPRCountsResult())),
230
- // Issue conversation fetch has custom messaging based on the error content, so it keeps its bespoke catch.
231
- issueMonitor.fetchCommentedIssues().catch((error) => {
232
- if (isRateLimitOrAuthError(error))
233
- throw error;
234
- const msg = errorMessage(error);
235
- if (msg.includes('No GitHub username configured')) {
236
- warn(MODULE, `Issue conversation tracking requires setup: ${msg}`);
237
- }
238
- else {
239
- warn(MODULE, `Issue conversation fetch failed: ${msg}`);
240
- partialFailures.push('fetch issue conversations');
241
- }
242
- return {
243
- issues: [],
244
- failures: [{ issueUrl: 'N/A', error: `Issue conversation fetch failed: ${msg}` }],
245
- };
246
- }),
247
238
  fetchMergedPRsSince(octokit, config, mergedFetchSince).catch(trackingCatch('fetch merged PRs for storage', [])),
248
239
  fetchClosedPRsSince(octokit, config, closedWatermark).catch(trackingCatch('fetch closed PRs for storage', [])),
249
240
  ]);
250
- const commentedIssues = fetchedIssues.issues;
241
+ // Issue conversations run after the PR lists: the engaged set (#1862)
242
+ // needs the open, recently closed and recently merged PRs. The fetch has
243
+ // custom messaging based on the error content, so it keeps its bespoke catch.
244
+ const engaged = collectEngagedIssues({
245
+ recentlyClosedPRs,
246
+ recentlyMergedPRs,
247
+ claims: stateManager.getState().activeIssues,
248
+ openPRs: prs,
249
+ ledgerClosedPRs: stateManager.getClosedPRs(),
250
+ ledgerMergedPRs: stateManager.getMergedPRs(),
251
+ });
252
+ const fetchedIssues = await issueMonitor.fetchCommentedIssues({ engaged }).catch((error) => {
253
+ if (isRateLimitOrAuthError(error))
254
+ throw error;
255
+ const msg = errorMessage(error);
256
+ if (msg.includes('No GitHub username configured')) {
257
+ warn(MODULE, `Issue conversation tracking requires setup: ${msg}`);
258
+ }
259
+ else {
260
+ warn(MODULE, `Issue conversation fetch failed: ${msg}`);
261
+ partialFailures.push('fetch issue conversations');
262
+ }
263
+ return {
264
+ issues: [],
265
+ failures: [{ issueUrl: 'N/A', error: `Issue conversation fetch failed: ${msg}` }],
266
+ warnings: [],
267
+ };
268
+ });
269
+ const { issues: commentedIssues, warnings: issueMonitorWarnings } = fetchedIssues;
270
+ partialFailures.push(...engagedScanLabels(issueMonitorWarnings));
251
271
  if (fetchedIssues.failures.length > 0) {
252
272
  warn(MODULE, `${fetchedIssues.failures.length} issue conversation check(s) failed`);
253
273
  }