@oss-autopilot/core 3.38.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 (63) hide show
  1. package/dist/cli-registry.js +7 -4
  2. package/dist/cli.bundle.cjs +139 -132
  3. package/dist/commands/daily-dismiss-filter.d.ts +37 -0
  4. package/dist/commands/daily-dismiss-filter.js +80 -0
  5. package/dist/commands/daily-merged-pr-notes.d.ts +27 -0
  6. package/dist/commands/daily-merged-pr-notes.js +166 -0
  7. package/dist/commands/daily-reviewed-prs.d.ts +41 -0
  8. package/dist/commands/daily-reviewed-prs.js +270 -0
  9. package/dist/commands/daily-warnings.d.ts +28 -0
  10. package/dist/commands/daily-warnings.js +37 -0
  11. package/dist/commands/daily.d.ts +22 -1
  12. package/dist/commands/daily.js +287 -107
  13. package/dist/commands/dashboard-cache.js +9 -2
  14. package/dist/commands/dashboard-data.js +40 -20
  15. package/dist/commands/dashboard-gist-sync.d.ts +4 -0
  16. package/dist/commands/dashboard-gist-sync.js +5 -1
  17. package/dist/commands/dismiss.d.ts +25 -5
  18. package/dist/commands/dismiss.js +38 -10
  19. package/dist/commands/overnight.js +14 -1
  20. package/dist/commands/scout-bridge.js +4 -1
  21. package/dist/commands/validation.d.ts +11 -0
  22. package/dist/commands/validation.js +16 -0
  23. package/dist/core/checklist-analysis.js +34 -0
  24. package/dist/core/closed-pr-status.d.ts +73 -0
  25. package/dist/core/closed-pr-status.js +113 -0
  26. package/dist/core/comment-decision.d.ts +10 -3
  27. package/dist/core/comment-decision.js +13 -5
  28. package/dist/core/comment-utils.d.ts +38 -1
  29. package/dist/core/comment-utils.js +124 -1
  30. package/dist/core/concurrency.d.ts +6 -0
  31. package/dist/core/concurrency.js +13 -0
  32. package/dist/core/daily-logic.d.ts +13 -1
  33. package/dist/core/daily-logic.js +59 -2
  34. package/dist/core/engaged-issues.d.ts +93 -0
  35. package/dist/core/engaged-issues.js +183 -0
  36. package/dist/core/errors.d.ts +4 -0
  37. package/dist/core/errors.js +10 -0
  38. package/dist/core/github-stats.d.ts +10 -0
  39. package/dist/core/github-stats.js +35 -0
  40. package/dist/core/index.d.ts +10 -5
  41. package/dist/core/index.js +9 -4
  42. package/dist/core/issue-conversation.d.ts +83 -12
  43. package/dist/core/issue-conversation.js +306 -118
  44. package/dist/core/merged-pr-notes.d.ts +192 -0
  45. package/dist/core/merged-pr-notes.js +340 -0
  46. package/dist/core/pr-assembly.js +3 -0
  47. package/dist/core/pr-monitor.d.ts +62 -0
  48. package/dist/core/pr-monitor.js +113 -3
  49. package/dist/core/reviewed-prs-fetch.d.ts +91 -0
  50. package/dist/core/reviewed-prs-fetch.js +271 -0
  51. package/dist/core/reviewed-prs.d.ts +244 -0
  52. package/dist/core/reviewed-prs.js +380 -0
  53. package/dist/core/state-persistence.js +4 -23
  54. package/dist/core/state-schema.d.ts +6 -0
  55. package/dist/core/state-schema.js +9 -0
  56. package/dist/core/state.d.ts +70 -8
  57. package/dist/core/state.js +101 -10
  58. package/dist/core/types.d.ts +47 -0
  59. package/dist/core/urls.d.ts +13 -0
  60. package/dist/core/urls.js +16 -0
  61. package/dist/formatters/json.d.ts +186 -1
  62. package/dist/formatters/json.js +78 -0
  63. package/package.json +1 -1
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The daily run's dismissed-issue filter and the fresh-baseline batch helper
3
+ * it persists through. Split out of daily.ts so the filter can be exercised
4
+ * against a real StateManager (dismiss, resurface, reload from disk) without
5
+ * mocking the whole daily pipeline.
6
+ */
7
+ import { getStateManager, type CommentedIssue } from '../core/index.js';
8
+ import type { DailyWarning } from '../formatters/json.js';
9
+ type StateManagerLike = Pick<ReturnType<typeof getStateManager>, 'reloadIfChanged' | 'batch' | 'getIssueDismissedAt' | 'undismissIssue'>;
10
+ /**
11
+ * Run a batch against a baseline that is fresh as of right now.
12
+ *
13
+ * A daily run spends tens of seconds on the network between loading state and
14
+ * each of its saves. If the dashboard, `move`, or another CLI call writes
15
+ * state.json in that time, the compare-and-swap in `saveState` rejects the
16
+ * save, and because the baseline never moved, every later batch in the run is
17
+ * rejected too: repo scores, analytics, the merged/closed ledger and lastDigest
18
+ * were all dropped, surfacing only as warnings. Reloading first picks up the
19
+ * other writer's change and shrinks the window to the batch itself.
20
+ *
21
+ * Only safe where the callback reads state live through the manager, as the
22
+ * batches in daily.ts do. A callback that writes from a snapshot taken
23
+ * earlier would overwrite the other writer's fields, which is why this is not
24
+ * done inside `StateManager.batch` for every caller.
25
+ */
26
+ export declare function batchOnFreshBaseline(stateManager: Pick<StateManagerLike, 'reloadIfChanged' | 'batch'>, fn: () => void): void;
27
+ /**
28
+ * Drop the commented issues the user dismissed, unless a reply newer than
29
+ * the dismiss arrived: that issue comes back and its dismiss record is
30
+ * removed, so the dashboard (which applies the same `isCoveredByDismiss`
31
+ * comparison, #1862) and the next run agree. Runs inside one fresh-baseline
32
+ * batch so every auto-undismiss lands in a single disk write; a persistence
33
+ * failure is recorded under the `dismiss-filter` phase and the issues are
34
+ * still returned.
35
+ */
36
+ export declare function filterDismissedIssues(stateManager: StateManagerLike, issues: CommentedIssue[], warnings: DailyWarning[]): CommentedIssue[];
37
+ export {};
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The daily run's dismissed-issue filter and the fresh-baseline batch helper
3
+ * it persists through. Split out of daily.ts so the filter can be exercised
4
+ * against a real StateManager (dismiss, resurface, reload from disk) without
5
+ * mocking the whole daily pipeline.
6
+ */
7
+ import { isCoveredByDismiss } from '../core/index.js';
8
+ import { warn } from '../core/logger.js';
9
+ import { recordWarning } from './daily-warnings.js';
10
+ const MODULE = 'daily';
11
+ /**
12
+ * Run a batch against a baseline that is fresh as of right now.
13
+ *
14
+ * A daily run spends tens of seconds on the network between loading state and
15
+ * each of its saves. If the dashboard, `move`, or another CLI call writes
16
+ * state.json in that time, the compare-and-swap in `saveState` rejects the
17
+ * save, and because the baseline never moved, every later batch in the run is
18
+ * rejected too: repo scores, analytics, the merged/closed ledger and lastDigest
19
+ * were all dropped, surfacing only as warnings. Reloading first picks up the
20
+ * other writer's change and shrinks the window to the batch itself.
21
+ *
22
+ * Only safe where the callback reads state live through the manager, as the
23
+ * batches in daily.ts do. A callback that writes from a snapshot taken
24
+ * earlier would overwrite the other writer's fields, which is why this is not
25
+ * done inside `StateManager.batch` for every caller.
26
+ */
27
+ export function batchOnFreshBaseline(stateManager, fn) {
28
+ stateManager.reloadIfChanged();
29
+ stateManager.batch(fn);
30
+ }
31
+ /**
32
+ * Drop the commented issues the user dismissed, unless a reply newer than
33
+ * the dismiss arrived: that issue comes back and its dismiss record is
34
+ * removed, so the dashboard (which applies the same `isCoveredByDismiss`
35
+ * comparison, #1862) and the next run agree. Runs inside one fresh-baseline
36
+ * batch so every auto-undismiss lands in a single disk write; a persistence
37
+ * failure is recorded under the `dismiss-filter` phase and the issues are
38
+ * still returned.
39
+ */
40
+ export function filterDismissedIssues(stateManager, issues, warnings) {
41
+ let filtered = [];
42
+ try {
43
+ batchOnFreshBaseline(stateManager, () => {
44
+ filtered = issues.filter((issue) => shouldKeep(stateManager, issue, warnings));
45
+ });
46
+ }
47
+ catch (error) {
48
+ recordWarning(warnings, 'dismiss-filter', 'persist auto-undismiss state', error);
49
+ }
50
+ return filtered;
51
+ }
52
+ /** Whether `issue` stays in the digest; undismisses it when a newer reply arrived. */
53
+ function shouldKeep(stateManager, issue, warnings) {
54
+ const dismissedAt = stateManager.getIssueDismissedAt(issue.url);
55
+ if (!dismissedAt)
56
+ return true; // Not dismissed — include
57
+ if (issue.status !== 'new_response')
58
+ return false; // Still dismissed
59
+ if (Number.isNaN(Date.parse(issue.lastResponseAt)) || Number.isNaN(Date.parse(dismissedAt))) {
60
+ // Invalid timestamp — fail open (include issue to be safe) without
61
+ // permanently removing dismiss record (may be a transient data issue)
62
+ warn(MODULE, `Invalid timestamp in dismiss check for ${issue.url}, including issue`);
63
+ return true;
64
+ }
65
+ // Still dismissed when the last response is at or before the dismiss timestamp.
66
+ if (isCoveredByDismiss(dismissedAt, issue.lastResponseAt))
67
+ return false;
68
+ // New activity after dismiss — auto-undismiss and resurface
69
+ warn(MODULE, `Auto-undismissing issue ${issue.url}: new response at ${issue.lastResponseAt} after dismiss at ${dismissedAt}`);
70
+ undismissSafely(stateManager, issue.url, warnings);
71
+ return true;
72
+ }
73
+ function undismissSafely(stateManager, url, warnings) {
74
+ try {
75
+ stateManager.undismissIssue(url);
76
+ }
77
+ catch (error) {
78
+ recordWarning(warnings, 'dismiss-filter', `persist auto-undismiss for ${url}`, error);
79
+ }
80
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Daily Phase 3.7: maintainer notes on recently merged PRs (#1861).
3
+ *
4
+ * Kept out of daily.ts (file-size ceiling). Pure selection lives in
5
+ * core/merged-pr-notes.ts; this module owns the per-PR fetch, the dismiss
6
+ * check, the warnings, and the agent-facing fencing of note excerpts.
7
+ */
8
+ import { type PRMonitor, type MergedPR, type MergedPRNotes } from '../core/index.js';
9
+ import type { DailyWarning } from '../formatters/json.js';
10
+ /** What Phase 1 learned about the recently merged list. */
11
+ export interface MergedPRNotesInput {
12
+ recentlyMergedPRs: MergedPR[];
13
+ /** The list is the [] fallback of a failed fetch; the phase is skipped with a warning. */
14
+ recentlyMergedFetchFailed: boolean;
15
+ }
16
+ /**
17
+ * Phase 3.7 entry point: runs {@link prepareMergedPRNotes} and turns any
18
+ * non-fatal failure into a `merged-pr-notes` warning plus an empty list.
19
+ * Rate-limit/auth errors end the run like every other phase's.
20
+ */
21
+ export declare function runMergedPRNotesPhase(prMonitor: PRMonitor, input: MergedPRNotesInput, warnings: DailyWarning[]): Promise<MergedPRNotes[]>;
22
+ /**
23
+ * Fence the GitHub-sourced note excerpts for agent-facing JSON (#1372), at
24
+ * the same boundary as daily.ts's `fenceCommentedIssue`: the internal result
25
+ * keeps raw text for the text renderer and tests.
26
+ */
27
+ export declare function fenceMergedPRNotes(entry: MergedPRNotes): MergedPRNotes;
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Daily Phase 3.7: maintainer notes on recently merged PRs (#1861).
3
+ *
4
+ * Kept out of daily.ts (file-size ceiling). Pure selection lives in
5
+ * core/merged-pr-notes.ts; this module owns the per-PR fetch, the dismiss
6
+ * check, the warnings, and the agent-facing fencing of note excerpts.
7
+ */
8
+ import { getStateManager, groupThanksOnlyAcknowledgments, latestNoteAt, omitAcknowledgedViaCarrier, scanMergedPR, } from '../core/index.js';
9
+ import { isRateLimitOrAuthError } from '../core/errors.js';
10
+ import { DEFAULT_CONCURRENCY, runWorkerPool } from '../core/concurrency.js';
11
+ import { debug, warn } from '../core/logger.js';
12
+ import { wrapUntrustedContent } from '../core/untrusted-content.js';
13
+ import { describeError, httpStatusLabel, isGoneError, recordWarning } from './daily-warnings.js';
14
+ const MODULE = 'daily';
15
+ const OPERATION = 'merged-PR maintainer notes';
16
+ /**
17
+ * Whether the user declined this PR's notes: its URL was dismissed at or
18
+ * after the newest note. A note newer than the dismiss resurfaces the PR,
19
+ * same as issue replies. An unreadable stamp fails open (the PR is listed)
20
+ * with a log line, matching the issue path's dismiss filter.
21
+ */
22
+ function isDismissed(prUrl, notes, dismissedAt) {
23
+ if (dismissedAt === undefined)
24
+ return false;
25
+ const dismissedMs = Date.parse(dismissedAt);
26
+ if (Number.isNaN(dismissedMs)) {
27
+ warn(MODULE, `merged-pr-notes: ${prUrl} has an unreadable dismiss timestamp ${JSON.stringify(dismissedAt)}; listing`);
28
+ return false;
29
+ }
30
+ const newestNoteAt = latestNoteAt(notes);
31
+ if (dismissedMs >= Date.parse(newestNoteAt)) {
32
+ debug(MODULE, `merged-pr-notes: ${prUrl} dismissed at ${dismissedAt}, after newest note ${newestNoteAt}; skipping`);
33
+ return true;
34
+ }
35
+ return false;
36
+ }
37
+ /**
38
+ * Fetch one PR's activity, turning a failure into a warning that names the
39
+ * PR and its HTTP status. Returns undefined when the PR is dropped for this
40
+ * run: on a fetch error, or when any of the four lists hit the pagination
41
+ * cap (the cap cuts the newest items, which is where the user's own reply
42
+ * would be, so an incomplete thread would nag about an answered note).
43
+ * Rate-limit/auth errors propagate.
44
+ */
45
+ async function fetchActivity(prMonitor, pr, warnings) {
46
+ const operation = `fetch activity on ${pr.url}`;
47
+ let activity;
48
+ try {
49
+ activity = await prMonitor.fetchMergedPRActivity(pr.url);
50
+ }
51
+ catch (error) {
52
+ if (isRateLimitOrAuthError(error))
53
+ throw error;
54
+ const detail = isGoneError(error)
55
+ ? `PR no longer reachable (${httpStatusLabel(error)}); dropped`
56
+ : `${describeError(error)}; dropped`;
57
+ recordWarning(warnings, 'merged-pr-notes', operation, error, detail);
58
+ return undefined;
59
+ }
60
+ if (activity.truncatedLists.length > 0) {
61
+ recordWarning(warnings, 'merged-pr-notes', operation, null, `pagination cap reached on ${activity.truncatedLists.join(', ')}; the newest activity (including any reply of yours) may be missing; dropped`);
62
+ return undefined;
63
+ }
64
+ return activity;
65
+ }
66
+ /**
67
+ * For each PR in this run's recently merged list (already limited to repos
68
+ * the user does not own and outside `untrackedOrgs` by the search), fetch its
69
+ * comments, reviews, inline review comments and commits and keep the notes
70
+ * `scanMergedPR` says still wait for the user: maintainer comments after the
71
+ * user's last word (comment or commit) and no earlier than an hour before
72
+ * the merge, plus commits someone else pushed on top. Thanks-only entries in
73
+ * one repo collapse onto the most recent PR (`ackCoveredBy`), and once the
74
+ * user has commented on that carrier the covered entries stop coming back
75
+ * (`omitAcknowledgedViaCarrier`).
76
+ *
77
+ * "Only once": nothing is written to state. An entry disappears when the
78
+ * user comments on the PR (or on its group's carrier) after the notes, when
79
+ * they dismiss the PR URL at or after the newest note (the workflow's "skip"
80
+ * runs the existing `dismiss`, which accepts PR URLs and re-stamps on
81
+ * repeat), and at the latest when the PR leaves the recently-merged window.
82
+ *
83
+ * Non-fatal: a per-PR failure (fetch error, pagination cap, or an error
84
+ * while reading the thread) drops that PR with a `merged-pr-notes` warning
85
+ * naming it; rate-limit/auth errors propagate like every other phase's.
86
+ */
87
+ async function prepareMergedPRNotes(prMonitor, { recentlyMergedPRs, recentlyMergedFetchFailed }, warnings) {
88
+ if (recentlyMergedFetchFailed) {
89
+ recordWarning(warnings, 'merged-pr-notes', OPERATION, null, 'skipped: recently-merged fetch failed');
90
+ return [];
91
+ }
92
+ if (recentlyMergedPRs.length === 0)
93
+ return [];
94
+ const stateManager = getStateManager();
95
+ const username = stateManager.getState().config.githubUsername;
96
+ if (!username) {
97
+ recordWarning(warnings, 'merged-pr-notes', OPERATION, null, 'skipped: no GitHub username configured');
98
+ return [];
99
+ }
100
+ // Keyed by PR so the output keeps the fetched order however the workers finish.
101
+ const pending = new Map();
102
+ const carriers = [];
103
+ const recordScan = (pr, activity) => {
104
+ const scan = scanMergedPR(pr, activity, username);
105
+ if (scan.thanksOnlyThread) {
106
+ carriers.push({ prUrl: pr.url, repo: pr.repo, mergedAt: pr.mergedAt, lastUserCommentMs: scan.lastUserCommentMs });
107
+ }
108
+ if (!scan.pending || isDismissed(pr.url, scan.pending, stateManager.getIssueDismissedAt(pr.url)))
109
+ return;
110
+ pending.set(pr, scan.pending);
111
+ };
112
+ await runWorkerPool(recentlyMergedPRs, async (pr) => {
113
+ const activity = await fetchActivity(prMonitor, pr, warnings);
114
+ if (!activity)
115
+ return;
116
+ try {
117
+ recordScan(pr, activity);
118
+ }
119
+ catch (error) {
120
+ if (isRateLimitOrAuthError(error))
121
+ throw error;
122
+ recordWarning(warnings, 'merged-pr-notes', `read activity on ${pr.url}`, error, `${describeError(error)}; dropped`);
123
+ }
124
+ }, DEFAULT_CONCURRENCY);
125
+ const ordered = [];
126
+ for (const pr of recentlyMergedPRs) {
127
+ const notes = pending.get(pr);
128
+ if (notes)
129
+ ordered.push(notes);
130
+ }
131
+ return groupThanksOnlyAcknowledgments(omitAcknowledgedViaCarrier(ordered, carriers));
132
+ }
133
+ /**
134
+ * Phase 3.7 entry point: runs {@link prepareMergedPRNotes} and turns any
135
+ * non-fatal failure into a `merged-pr-notes` warning plus an empty list.
136
+ * Rate-limit/auth errors end the run like every other phase's.
137
+ */
138
+ export async function runMergedPRNotesPhase(prMonitor, input, warnings) {
139
+ try {
140
+ return await prepareMergedPRNotes(prMonitor, input, warnings);
141
+ }
142
+ catch (error) {
143
+ if (isRateLimitOrAuthError(error))
144
+ throw error;
145
+ recordWarning(warnings, 'merged-pr-notes', 'prepare merged-PR maintainer notes', error);
146
+ return [];
147
+ }
148
+ }
149
+ /**
150
+ * Fence the GitHub-sourced note excerpts for agent-facing JSON (#1372), at
151
+ * the same boundary as daily.ts's `fenceCommentedIssue`: the internal result
152
+ * keeps raw text for the text renderer and tests.
153
+ */
154
+ export function fenceMergedPRNotes(entry) {
155
+ const label = `${entry.repo}#${entry.number}`;
156
+ return {
157
+ ...entry,
158
+ notes: entry.notes.map((note) => ({
159
+ ...note,
160
+ excerpt: wrapUntrustedContent(note.excerpt, label, {
161
+ author: note.author,
162
+ source: note.kind === 'commit' ? 'pr-commit' : 'pr-comment',
163
+ }),
164
+ })),
165
+ };
166
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Daily Phase 3.8: review follow-ups on PRs the user reviewed (#1857).
3
+ *
4
+ * Kept out of daily.ts (file-size ceiling). Pure selection lives in
5
+ * core/reviewed-prs.ts; this module owns the search, the per-PR fetch, the
6
+ * compare call that turns `reviewedSha` into a range or a rebase flag, the
7
+ * dismiss check, the warnings, and the agent-facing fencing of excerpts.
8
+ *
9
+ * API cost per run: two searches (up to three pages each), then for the
10
+ * {@link REVIEWED_PR_MAX_PER_RUN} most recently updated reviewed PRs not
11
+ * already dismissed at or after their last update, five calls each (PR,
12
+ * comments, reviews, inline comments, commits) and, when the PR turns out
13
+ * actionable, the head moved and a range could be honest, one compare.
14
+ */
15
+ import { type PRMonitor, type ReviewedPRFollowUp } from '../core/index.js';
16
+ import type { DailyWarning } from '../formatters/json.js';
17
+ /**
18
+ * Reviewed PRs enriched per run, most recently updated first (#1857). Five
19
+ * calls each, so this bounds the phase at roughly 250 calls plus compares;
20
+ * a reviewer with more open reviewed PRs than this sees one warning naming
21
+ * how many were left unchecked. The search result is sorted by `updated_at`
22
+ * across both searches and dismissed PRs are dropped before the cap, so the
23
+ * PRs left out are the ones nothing has happened on for longest.
24
+ */
25
+ export declare const REVIEWED_PR_MAX_PER_RUN = 50;
26
+ /** The three PRMonitor calls this phase makes; a structural type so tests can pass a stub. */
27
+ export type ReviewedPRSource = Pick<PRMonitor, 'fetchReviewedOpenPRs' | 'fetchReviewedPRActivity' | 'fetchCompareStatus'>;
28
+ /**
29
+ * Phase 3.8 entry point: runs {@link prepareReviewedPRs} and turns any
30
+ * non-fatal failure (including a failed search) into a `reviewed-prs`
31
+ * warning plus an empty list. Rate-limit/auth errors end the run like every
32
+ * other phase's.
33
+ */
34
+ export declare function runReviewedPRsPhase(source: ReviewedPRSource, warnings: DailyWarning[]): Promise<ReviewedPRFollowUp[]>;
35
+ /**
36
+ * Fence the GitHub-sourced text for agent-facing JSON (#1372), at the same
37
+ * boundary as daily.ts's `fenceCommentedIssue`: question excerpts and commit
38
+ * subjects. The internal result keeps raw text for the text renderer and
39
+ * tests.
40
+ */
41
+ export declare function fenceReviewedPR(entry: ReviewedPRFollowUp): ReviewedPRFollowUp;
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Daily Phase 3.8: review follow-ups on PRs the user reviewed (#1857).
3
+ *
4
+ * Kept out of daily.ts (file-size ceiling). Pure selection lives in
5
+ * core/reviewed-prs.ts; this module owns the search, the per-PR fetch, the
6
+ * compare call that turns `reviewedSha` into a range or a rebase flag, the
7
+ * dismiss check, the warnings, and the agent-facing fencing of excerpts.
8
+ *
9
+ * API cost per run: two searches (up to three pages each), then for the
10
+ * {@link REVIEWED_PR_MAX_PER_RUN} most recently updated reviewed PRs not
11
+ * already dismissed at or after their last update, five calls each (PR,
12
+ * comments, reviews, inline comments, commits) and, when the PR turns out
13
+ * actionable, the head moved and a range could be honest, one compare.
14
+ */
15
+ import { getStateManager, scanReviewedPR, } from '../core/index.js';
16
+ import { isRateLimitOrAuthError } from '../core/errors.js';
17
+ import { DEFAULT_CONCURRENCY, runWorkerPool } from '../core/concurrency.js';
18
+ import { debug, warn } from '../core/logger.js';
19
+ import { wrapUntrustedContent } from '../core/untrusted-content.js';
20
+ import { describeError, httpStatusLabel, isGoneError, recordWarning } from './daily-warnings.js';
21
+ const MODULE = 'daily';
22
+ const OPERATION = 'review follow-ups';
23
+ /**
24
+ * Reviewed PRs enriched per run, most recently updated first (#1857). Five
25
+ * calls each, so this bounds the phase at roughly 250 calls plus compares;
26
+ * a reviewer with more open reviewed PRs than this sees one warning naming
27
+ * how many were left unchecked. The search result is sorted by `updated_at`
28
+ * across both searches and dismissed PRs are dropped before the cap, so the
29
+ * PRs left out are the ones nothing has happened on for longest.
30
+ */
31
+ export const REVIEWED_PR_MAX_PER_RUN = 50;
32
+ /**
33
+ * Whether the user declined this PR: its URL was dismissed at or after
34
+ * `activityAt` (the search's `updated_at` before the fetch, the newest
35
+ * qualifying commit or comment after the scan). Newer activity resurfaces
36
+ * the PR, same as merged-PR notes. An unreadable stamp fails open (the PR is
37
+ * listed) with a log line, matching the issue path's dismiss filter.
38
+ */
39
+ function isDismissed(prUrl, activityAt, dismissedAt) {
40
+ if (dismissedAt === undefined)
41
+ return false;
42
+ const dismissedMs = Date.parse(dismissedAt);
43
+ const activityMs = Date.parse(activityAt);
44
+ if (Number.isNaN(dismissedMs) || Number.isNaN(activityMs)) {
45
+ warn(MODULE, `reviewed-prs: ${prUrl} has an unreadable dismiss (${JSON.stringify(dismissedAt)}) or activity (${JSON.stringify(activityAt)}) timestamp; listing`);
46
+ return false;
47
+ }
48
+ if (dismissedMs >= activityMs) {
49
+ debug(MODULE, `reviewed-prs: ${prUrl} dismissed at ${dismissedAt}, after latest activity ${activityAt}; skipping`);
50
+ return true;
51
+ }
52
+ return false;
53
+ }
54
+ /**
55
+ * The dismiss check after the scan, in two modes.
56
+ *
57
+ * With a recorded head (`dismiss <pr-url> --head <sha>`, what the workflow's
58
+ * "skip" passes): the head is the push signal. A different head means the
59
+ * author pushed since the dismiss, so the PR is listed; the same head means
60
+ * the commit list is what the user saw when dismissing, so only a qualifying
61
+ * comment posted after the stamp (`latestCommentAt`) brings it back. Bot,
62
+ * label and bystander updates move the search's `updated_at` but neither of
63
+ * these, so they no longer resurface a skipped PR.
64
+ *
65
+ * Without one (a dismiss made before heads were recorded, or by hand): the
66
+ * stamp is all there is. Comment dates are when the comment was posted, so
67
+ * `latestActivityAt` settles a comments-only follow-up. Commit dates say when
68
+ * a commit was written, not when it was pushed, so a commit the scan found
69
+ * after the reviewed one (cherry-pick, rebased fix) can carry a date before
70
+ * the dismiss and would hide a push that happened after it. When any listed
71
+ * commit is dated at or before the stamp, the search's `updated_at`, which
72
+ * does move on push, stands in for the activity time; since every commit the
73
+ * user saw when dismissing is dated before the stamp too, a follow-up with
74
+ * commits is then hidden only by the pre-fetch `updated_at` check, which errs
75
+ * toward showing the PR again rather than missing a push.
76
+ */
77
+ function isEntryDismissed(pr, entry, dismissedAt, dismissedHead) {
78
+ if (dismissedAt === undefined)
79
+ return false;
80
+ if (dismissedHead !== undefined) {
81
+ if (entry.headSha !== dismissedHead) {
82
+ debug(MODULE, `reviewed-prs: ${pr.url} head moved since the dismiss (${dismissedHead.slice(0, 7)}); listing`);
83
+ return false;
84
+ }
85
+ if (entry.latestCommentAt === undefined) {
86
+ debug(MODULE, `reviewed-prs: ${pr.url} dismissed at head ${dismissedHead.slice(0, 7)}, no comment since; skipping`);
87
+ return true;
88
+ }
89
+ return isDismissed(pr.url, entry.latestCommentAt, dismissedAt);
90
+ }
91
+ const dismissedMs = Date.parse(dismissedAt);
92
+ const hasCommitDatedBeforeStamp = entry.commits.some((commit) => Date.parse(commit.date) <= dismissedMs);
93
+ return isDismissed(pr.url, hasCommitDatedBeforeStamp ? pr.updatedAt : entry.latestActivityAt, dismissedAt);
94
+ }
95
+ /**
96
+ * Fetch one PR's activity, turning a failure into a warning that names the
97
+ * PR and its HTTP status. Returns undefined when the PR is dropped for this
98
+ * run: on a fetch error, or when any list hit the pagination cap (the cap
99
+ * cuts the newest items, which is where the author's reply and the user's
100
+ * own re-review would be). Rate-limit/auth errors propagate.
101
+ */
102
+ async function fetchActivity(source, pr, warnings) {
103
+ const operation = `fetch activity on ${pr.url}`;
104
+ let activity;
105
+ try {
106
+ activity = await source.fetchReviewedPRActivity(pr.url);
107
+ }
108
+ catch (error) {
109
+ if (isRateLimitOrAuthError(error))
110
+ throw error;
111
+ const detail = isGoneError(error)
112
+ ? `PR no longer reachable (${httpStatusLabel(error)}); dropped`
113
+ : `${describeError(error)}; dropped`;
114
+ recordWarning(warnings, 'reviewed-prs', operation, error, detail);
115
+ return undefined;
116
+ }
117
+ if (activity.truncatedLists.length > 0) {
118
+ recordWarning(warnings, 'reviewed-prs', operation, null, `pagination cap reached on ${activity.truncatedLists.join(', ')}; the newest activity (including any re-review of yours) may be missing; dropped`);
119
+ return undefined;
120
+ }
121
+ return activity;
122
+ }
123
+ /**
124
+ * Fill in `compareRange` / `compareUrl` or `rebased` from GitHub's compare
125
+ * status. No call when the head is where the review left it (comments
126
+ * only), when the reviewed commit could not be named (plain comment), or
127
+ * when the scan already ruled a range out from the commit list (`rebased`:
128
+ * the reviewed commit is gone; `mergedUpstream`: upstream was merged in
129
+ * after it; `baseUnknown`: the reviewed commit's place in the list is
130
+ * unknown). On an error other than 404 (which `fetchCompareStatus` maps to
131
+ * `missing`) the entry keeps neither range nor flag, with a warning: an
132
+ * unverified range could be wrong, and the commit list is still there.
133
+ * Rate-limit/auth errors propagate.
134
+ */
135
+ async function resolveCompare(source, entry, warnings) {
136
+ if (entry.reviewedSha === undefined || entry.reviewedSha === entry.headSha)
137
+ return;
138
+ if (entry.rebased || entry.mergedUpstream || entry.baseUnknown)
139
+ return;
140
+ let status;
141
+ try {
142
+ status = await source.fetchCompareStatus(entry.prUrl, entry.reviewedSha, entry.headSha);
143
+ }
144
+ catch (error) {
145
+ if (isRateLimitOrAuthError(error))
146
+ throw error;
147
+ recordWarning(warnings, 'reviewed-prs', `compare ${entry.reviewedSha.slice(0, 7)}...${entry.headSha.slice(0, 7)} on ${entry.prUrl}`, error, `${describeError(error)}; cannot tell whether the branch was rebased, showing the commit list only`);
148
+ return;
149
+ }
150
+ if (status === 'ahead' || status === 'identical') {
151
+ entry.compareRange = `${entry.reviewedSha}...${entry.headSha}`;
152
+ entry.compareUrl = `${entry.prUrl.replace(/\/pull\/\d+$/, '')}/compare/${entry.compareRange}`;
153
+ return;
154
+ }
155
+ debug(MODULE, `reviewed-prs: ${entry.prUrl} compare status ${status}; flagging as rebased`);
156
+ entry.rebased = true;
157
+ }
158
+ /**
159
+ * Search for the open PRs the user reviewed or commented on but did not
160
+ * author, fetch each one's thread, and keep the PRs where the author has
161
+ * moved things since the user's last review or comment (`scanReviewedPR`):
162
+ * commits pushed, a reply from the author, or a comment addressed to the
163
+ * user. For each kept PR whose head moved and whose commit list did not
164
+ * already rule a range out, ask GitHub whether the reviewed commit is still
165
+ * an ancestor of the head: if so the entry carries the compare range, if
166
+ * not it is flagged `rebased` and carries the commit list instead.
167
+ *
168
+ * "Only once": nothing is written to state. An entry disappears when the
169
+ * user comments or reviews again (their last word moves past the activity),
170
+ * when they dismiss the PR URL (the workflow's "skip" runs the existing
171
+ * `dismiss` with the entry's `headSha`, so the PR stays hidden until a new
172
+ * push or a comment after the dismiss; see `isEntryDismissed`), and when
173
+ * the PR closes or merges. A PR dismissed at or after its search
174
+ * `updated_at` is skipped before any per-PR call, and the dismiss filter
175
+ * runs before the per-run cap so dismissed PRs do not use up its slots.
176
+ *
177
+ * Never counted toward capacity or `needsAddressingPRs`: these are other
178
+ * people's PRs.
179
+ *
180
+ * Non-fatal: a per-PR failure (fetch error, pagination cap, an error while
181
+ * reading the thread, or a failed compare) drops or degrades that PR with a
182
+ * `reviewed-prs` warning naming it; rate-limit/auth errors propagate like
183
+ * every other phase's.
184
+ */
185
+ async function prepareReviewedPRs(source, warnings) {
186
+ const stateManager = getStateManager();
187
+ const username = stateManager.getState().config.githubUsername;
188
+ if (!username) {
189
+ recordWarning(warnings, 'reviewed-prs', OPERATION, null, 'skipped: no GitHub username configured');
190
+ return [];
191
+ }
192
+ const search = await source.fetchReviewedOpenPRs();
193
+ for (const message of search.warnings) {
194
+ recordWarning(warnings, 'reviewed-prs', 'search reviewed PRs (incomplete)', null, message);
195
+ }
196
+ const notDismissed = search.prs.filter((pr) => !isDismissed(pr.url, pr.updatedAt, stateManager.getIssueDismissedAt(pr.url)));
197
+ const candidates = notDismissed.slice(0, REVIEWED_PR_MAX_PER_RUN);
198
+ if (notDismissed.length > candidates.length) {
199
+ recordWarning(warnings, 'reviewed-prs', OPERATION, null, `${notDismissed.length - candidates.length} reviewed PR(s) beyond the per-run cap of ${REVIEWED_PR_MAX_PER_RUN} were not checked (the least recently updated); dismiss or re-review stale ones to make room`);
200
+ }
201
+ if (candidates.length === 0)
202
+ return [];
203
+ // Keyed by PR so the output keeps the search order however the workers finish.
204
+ const pending = new Map();
205
+ await runWorkerPool(candidates, async (pr) => {
206
+ const activity = await fetchActivity(source, pr, warnings);
207
+ if (!activity)
208
+ return;
209
+ let entry;
210
+ try {
211
+ entry = scanReviewedPR(pr, activity, username);
212
+ }
213
+ catch (error) {
214
+ if (isRateLimitOrAuthError(error))
215
+ throw error;
216
+ recordWarning(warnings, 'reviewed-prs', `read activity on ${pr.url}`, error, `${describeError(error)}; dropped`);
217
+ return;
218
+ }
219
+ if (!entry)
220
+ return;
221
+ if (isEntryDismissed(pr, entry, stateManager.getIssueDismissedAt(pr.url), stateManager.getDismissedPRHead(pr.url)))
222
+ return;
223
+ await resolveCompare(source, entry, warnings);
224
+ pending.set(pr, entry);
225
+ }, DEFAULT_CONCURRENCY);
226
+ const ordered = [];
227
+ for (const pr of candidates) {
228
+ const entry = pending.get(pr);
229
+ if (entry)
230
+ ordered.push(entry);
231
+ }
232
+ return ordered;
233
+ }
234
+ /**
235
+ * Phase 3.8 entry point: runs {@link prepareReviewedPRs} and turns any
236
+ * non-fatal failure (including a failed search) into a `reviewed-prs`
237
+ * warning plus an empty list. Rate-limit/auth errors end the run like every
238
+ * other phase's.
239
+ */
240
+ export async function runReviewedPRsPhase(source, warnings) {
241
+ try {
242
+ return await prepareReviewedPRs(source, warnings);
243
+ }
244
+ catch (error) {
245
+ if (isRateLimitOrAuthError(error))
246
+ throw error;
247
+ recordWarning(warnings, 'reviewed-prs', `prepare ${OPERATION}`, error, describeError(error));
248
+ return [];
249
+ }
250
+ }
251
+ /**
252
+ * Fence the GitHub-sourced text for agent-facing JSON (#1372), at the same
253
+ * boundary as daily.ts's `fenceCommentedIssue`: question excerpts and commit
254
+ * subjects. The internal result keeps raw text for the text renderer and
255
+ * tests.
256
+ */
257
+ export function fenceReviewedPR(entry) {
258
+ const label = `${entry.repo}#${entry.number}`;
259
+ return {
260
+ ...entry,
261
+ questions: entry.questions.map((question) => ({
262
+ ...question,
263
+ excerpt: wrapUntrustedContent(question.excerpt, label, { author: question.author, source: 'pr-comment' }),
264
+ })),
265
+ commits: entry.commits.map((commit) => ({
266
+ ...commit,
267
+ subject: wrapUntrustedContent(commit.subject, label, { author: commit.author, source: 'pr-commit' }),
268
+ })),
269
+ };
270
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Non-fatal warning helpers shared by the daily phases (#1042). Split out of
3
+ * daily.ts so the per-phase modules (closed-PR status, merged-PR notes) can
4
+ * record warnings the same way without importing the orchestrator.
5
+ */
6
+ import type { DailyWarning, DailyWarningPhase } from '../formatters/json.js';
7
+ /** Defined in core/errors.ts so core modules can word their own warnings the same way. */
8
+ export { describeError, httpStatusLabel } from '../core/errors.js';
9
+ /**
10
+ * Record a non-fatal failure: push a structured entry into the run's warnings
11
+ * collector AND emit the existing log line. Consumers (dashboard, MCP, tests)
12
+ * inspect `DailyOutput.warnings` so a partial run is visible beyond log noise.
13
+ * See #1042.
14
+ */
15
+ export declare function recordWarning(warnings: DailyWarning[], phase: DailyWarningPhase, operation: string, err: unknown, humanMessage?: string): void;
16
+ /**
17
+ * Variant of `nonFatalCatch` that also records a structured warning. Returns
18
+ * the fallback value on error (same semantics as `nonFatalCatch`) AND pushes
19
+ * an entry into the collector so the failure shows up in `DailyOutput.warnings`.
20
+ */
21
+ export declare function nonFatalCatchWithWarning<T>(opts: {
22
+ warnings: DailyWarning[];
23
+ phase: DailyWarningPhase;
24
+ operation: string;
25
+ fallback: T;
26
+ }): (err: unknown) => T;
27
+ /** 404/410: the issue or PR is gone (deleted, transferred, or now private). */
28
+ export declare function isGoneError(error: unknown): boolean;