@oss-autopilot/core 3.42.5 → 3.44.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 (192) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +428 -27
  3. package/dist/cli.bundle.cjs +212 -156
  4. package/dist/commands/check-integration.js +5 -1
  5. package/dist/commands/cleanup.d.ts +80 -0
  6. package/dist/commands/cleanup.js +334 -0
  7. package/dist/commands/comments.d.ts +14 -1
  8. package/dist/commands/comments.js +17 -5
  9. package/dist/commands/config.d.ts +2 -0
  10. package/dist/commands/config.js +63 -6
  11. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  12. package/dist/commands/daily-dismiss-filter.js +17 -1
  13. package/dist/commands/daily-ledger.d.ts +150 -0
  14. package/dist/commands/daily-ledger.js +248 -0
  15. package/dist/commands/daily-recent-prs.d.ts +26 -0
  16. package/dist/commands/daily-recent-prs.js +55 -0
  17. package/dist/commands/daily-render.d.ts +2 -1
  18. package/dist/commands/daily-render.js +4 -1
  19. package/dist/commands/daily.d.ts +5 -1
  20. package/dist/commands/daily.js +83 -93
  21. package/dist/commands/dashboard-cache.d.ts +2 -0
  22. package/dist/commands/dashboard-cache.js +33 -8
  23. package/dist/commands/dashboard-data.js +113 -69
  24. package/dist/commands/dashboard-gist-sync.js +3 -1
  25. package/dist/commands/dashboard-lifecycle.d.ts +36 -8
  26. package/dist/commands/dashboard-lifecycle.js +132 -39
  27. package/dist/commands/dashboard-process.d.ts +49 -1
  28. package/dist/commands/dashboard-process.js +111 -12
  29. package/dist/commands/dashboard-server.js +89 -23
  30. package/dist/commands/detect-formatters.js +1 -0
  31. package/dist/commands/dismiss.js +11 -7
  32. package/dist/commands/doctor.d.ts +15 -1
  33. package/dist/commands/doctor.js +66 -5
  34. package/dist/commands/draft.d.ts +77 -0
  35. package/dist/commands/draft.js +218 -0
  36. package/dist/commands/eval.js +1 -0
  37. package/dist/commands/fork-prune.d.ts +58 -0
  38. package/dist/commands/fork-prune.js +247 -0
  39. package/dist/commands/guidelines.d.ts +69 -2
  40. package/dist/commands/guidelines.js +158 -14
  41. package/dist/commands/index.d.ts +29 -4
  42. package/dist/commands/index.js +20 -3
  43. package/dist/commands/issue-thread.d.ts +46 -0
  44. package/dist/commands/issue-thread.js +123 -0
  45. package/dist/commands/ledger-backfill.d.ts +9 -0
  46. package/dist/commands/ledger-backfill.js +44 -1
  47. package/dist/commands/list-mark-done.d.ts +2 -1
  48. package/dist/commands/list-mark-done.js +3 -1
  49. package/dist/commands/list-move-tier.d.ts +2 -1
  50. package/dist/commands/list-move-tier.js +3 -1
  51. package/dist/commands/local-repos.js +10 -5
  52. package/dist/commands/locate-issue-list.d.ts +40 -17
  53. package/dist/commands/locate-issue-list.js +148 -88
  54. package/dist/commands/move.js +7 -1
  55. package/dist/commands/overnight-handoff.d.ts +17 -7
  56. package/dist/commands/overnight-handoff.js +36 -14
  57. package/dist/commands/overnight-push-prep.d.ts +14 -8
  58. package/dist/commands/overnight-push-prep.js +107 -35
  59. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  60. package/dist/commands/overnight-tool-rules.js +217 -0
  61. package/dist/commands/overnight.d.ts +5 -6
  62. package/dist/commands/overnight.js +61 -140
  63. package/dist/commands/parse-list.js +7 -1
  64. package/dist/commands/policy.d.ts +90 -0
  65. package/dist/commands/policy.js +276 -0
  66. package/dist/commands/pr-create.d.ts +48 -0
  67. package/dist/commands/pr-create.js +200 -0
  68. package/dist/commands/pr-preflight.d.ts +69 -0
  69. package/dist/commands/pr-preflight.js +348 -0
  70. package/dist/commands/repo-vet.d.ts +9 -0
  71. package/dist/commands/repo-vet.js +36 -11
  72. package/dist/commands/scout-bridge.js +18 -8
  73. package/dist/commands/search.js +7 -0
  74. package/dist/commands/setup.d.ts +3 -3
  75. package/dist/commands/setup.js +160 -48
  76. package/dist/commands/skip-add.js +10 -1
  77. package/dist/commands/startup.d.ts +12 -3
  78. package/dist/commands/startup.js +82 -49
  79. package/dist/commands/state-cmd.d.ts +2 -0
  80. package/dist/commands/state-cmd.js +5 -1
  81. package/dist/commands/stats.js +1 -0
  82. package/dist/commands/status.js +6 -0
  83. package/dist/commands/strategy.js +1 -0
  84. package/dist/commands/validation.d.ts +5 -0
  85. package/dist/commands/validation.js +5 -0
  86. package/dist/commands/vet-list.d.ts +6 -0
  87. package/dist/commands/vet-list.js +26 -1
  88. package/dist/commands/vet.d.ts +20 -0
  89. package/dist/commands/vet.js +133 -2
  90. package/dist/commands/work.d.ts +4 -0
  91. package/dist/commands/work.js +34 -11
  92. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  93. package/dist/core/anti-llm-policy.d.ts +3 -0
  94. package/dist/core/anti-llm-policy.js +3 -0
  95. package/dist/core/auth.js +2 -0
  96. package/dist/core/ci-analysis.d.ts +7 -2
  97. package/dist/core/ci-analysis.js +76 -21
  98. package/dist/core/commit-date.d.ts +45 -0
  99. package/dist/core/commit-date.js +45 -0
  100. package/dist/core/compliance-score.d.ts +3 -0
  101. package/dist/core/compliance-score.js +13 -9
  102. package/dist/core/config-registry.d.ts +27 -2
  103. package/dist/core/config-registry.js +94 -7
  104. package/dist/core/contributing.d.ts +2 -3
  105. package/dist/core/contributing.js +2 -3
  106. package/dist/core/daily-logic.d.ts +30 -5
  107. package/dist/core/daily-logic.js +68 -19
  108. package/dist/core/errors.d.ts +37 -3
  109. package/dist/core/errors.js +54 -5
  110. package/dist/core/fork-prune.d.ts +149 -0
  111. package/dist/core/fork-prune.js +333 -0
  112. package/dist/core/gist-health.d.ts +15 -3
  113. package/dist/core/gist-health.js +8 -0
  114. package/dist/core/gist-state-store.d.ts +24 -4
  115. package/dist/core/gist-state-store.js +98 -51
  116. package/dist/core/github-stats.d.ts +110 -16
  117. package/dist/core/github-stats.js +295 -110
  118. package/dist/core/http-cache.d.ts +0 -10
  119. package/dist/core/http-cache.js +0 -19
  120. package/dist/core/index.d.ts +13 -6
  121. package/dist/core/index.js +16 -6
  122. package/dist/core/issue-conversation.d.ts +8 -2
  123. package/dist/core/issue-conversation.js +31 -12
  124. package/dist/core/local-config.d.ts +95 -0
  125. package/dist/core/local-config.js +270 -0
  126. package/dist/core/merged-pr-notes.d.ts +2 -2
  127. package/dist/core/pacing.d.ts +41 -0
  128. package/dist/core/pacing.js +115 -0
  129. package/dist/core/pagination.d.ts +55 -0
  130. package/dist/core/pagination.js +59 -0
  131. package/dist/core/paths.d.ts +7 -0
  132. package/dist/core/paths.js +9 -0
  133. package/dist/core/pr-assembly.d.ts +2 -0
  134. package/dist/core/pr-assembly.js +6 -2
  135. package/dist/core/pr-graphql.d.ts +53 -4
  136. package/dist/core/pr-graphql.js +87 -14
  137. package/dist/core/pr-monitor.d.ts +35 -12
  138. package/dist/core/pr-monitor.js +110 -26
  139. package/dist/core/pr-preflight.d.ts +154 -0
  140. package/dist/core/pr-preflight.js +753 -0
  141. package/dist/core/pr-quality-rubric.d.ts +0 -6
  142. package/dist/core/pr-quality-rubric.js +0 -8
  143. package/dist/core/pr-template.d.ts +2 -0
  144. package/dist/core/pr-template.js +5 -1
  145. package/dist/core/prose-script.d.ts +72 -0
  146. package/dist/core/prose-script.js +223 -0
  147. package/dist/core/repo-policy.d.ts +111 -0
  148. package/dist/core/repo-policy.js +428 -0
  149. package/dist/core/repo-score-manager.d.ts +66 -0
  150. package/dist/core/repo-score-manager.js +140 -1
  151. package/dist/core/review-analysis.d.ts +49 -21
  152. package/dist/core/review-analysis.js +89 -15
  153. package/dist/core/reviewed-prs-fetch.js +11 -29
  154. package/dist/core/reviewed-prs.js +8 -15
  155. package/dist/core/stale-data.d.ts +78 -0
  156. package/dist/core/stale-data.js +153 -0
  157. package/dist/core/state-persistence.d.ts +62 -27
  158. package/dist/core/state-persistence.js +338 -119
  159. package/dist/core/state-schema.d.ts +152 -210
  160. package/dist/core/state-schema.js +232 -80
  161. package/dist/core/state.d.ts +81 -8
  162. package/dist/core/state.js +239 -46
  163. package/dist/core/status-determination.js +32 -12
  164. package/dist/core/strategy.js +3 -1
  165. package/dist/core/types.d.ts +22 -1
  166. package/dist/core/types.js +1 -0
  167. package/dist/core/untrusted-content.d.ts +30 -11
  168. package/dist/core/untrusted-content.js +95 -42
  169. package/dist/core/urls.d.ts +33 -0
  170. package/dist/core/urls.js +94 -0
  171. package/dist/dashboard/assets/chart-panel-B-nLVgzQ.js +3 -0
  172. package/dist/dashboard/assets/index-5IvMGokL.js +55 -0
  173. package/dist/dashboard/index.html +1 -1
  174. package/dist/formatters/json.d.ts +432 -10
  175. package/dist/formatters/json.js +156 -1
  176. package/package.json +6 -6
  177. package/dist/core/ci-enforced-tools.d.ts +0 -35
  178. package/dist/core/ci-enforced-tools.js +0 -109
  179. package/dist/core/comment-decision.d.ts +0 -79
  180. package/dist/core/comment-decision.js +0 -82
  181. package/dist/core/extraction-categories.d.ts +0 -55
  182. package/dist/core/extraction-categories.js +0 -108
  183. package/dist/core/follow-up-history.d.ts +0 -40
  184. package/dist/core/follow-up-history.js +0 -71
  185. package/dist/core/issue-effort.d.ts +0 -29
  186. package/dist/core/issue-effort.js +0 -47
  187. package/dist/core/maintainer-hints.d.ts +0 -23
  188. package/dist/core/maintainer-hints.js +0 -36
  189. package/dist/core/workflow-state.d.ts +0 -56
  190. package/dist/core/workflow-state.js +0 -101
  191. package/dist/dashboard/assets/chart-panel-DPKNBUts.js +0 -3
  192. package/dist/dashboard/assets/index-B25bZOYX.js +0 -55
@@ -2,10 +2,12 @@
2
2
  * GitHub Stats - Fetching merged/closed PR counts with star-based filtering.
3
3
  * Extracted from PRMonitor to isolate statistics-gathering API calls (#263).
4
4
  */
5
- import { extractOwnerRepo, parseGitHubUrl, isOwnRepo, isUntrackedOrg } from './urls.js';
5
+ import { extractOwnerRepo, findClosingRefs, MAX_BODY_CHARS, parseGitHubUrl, isOwnRepo, isUntrackedOrg, stripNonProse, } from './urls.js';
6
6
  import { isBelowMinStars } from './types.js';
7
7
  import { debug, warn } from './logger.js';
8
+ import { describeError } from './errors.js';
8
9
  import { getHttpCache } from './http-cache.js';
10
+ import { searchAllPages } from './pagination.js';
9
11
  const MODULE = 'github-stats';
10
12
  /** TTL for cached PR count results (24 hours — these stats change slowly). */
11
13
  export const PR_COUNTS_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
@@ -15,11 +17,6 @@ export const PR_COUNTS_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
15
17
  * 3 pages × 100 per_page = 300 results, which covers the vast majority of users.
16
18
  */
17
19
  const MAX_PAGINATION_PAGES = 3;
18
- const CLOSING_KEYWORD_RE = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)(?::\s*|\s+)(?:https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/issues\/(\d+)|([\w.-]+\/[\w.-]+)?#(\d+))\b/i;
19
- /** HTML comments and code: where PR templates keep example `Fixes #123` lines. */
20
- const NON_PROSE_RE = /<!--[\s\S]*?-->|```[\s\S]*?```|(`+)[^`]*\1/g;
21
- /** GitHub's PR body limit; also bounds NON_PROSE_RE's scan on an unclosed `<!--`. */
22
- const MAX_BODY_CHARS = 65_536;
23
20
  /**
24
21
  * Issue URL a PR closes, from the first GitHub closing keyword in its body
25
22
  * (#1824): `Fixes #12`, `closes owner/repo#12`, or `resolves <issue url>`.
@@ -29,13 +26,13 @@ const MAX_BODY_CHARS = 65_536;
29
26
  * first. Switch to GraphQL `closingIssuesReferences` if that ever matters.
30
27
  */
31
28
  export function closingIssueUrl(body, prUrl) {
32
- const m = body?.slice(0, MAX_BODY_CHARS).replace(NON_PROSE_RE, ' ').match(CLOSING_KEYWORD_RE);
33
- if (!m)
29
+ const [ref] = body ? findClosingRefs(body, { markdown: true }) : [];
30
+ if (!ref)
34
31
  return undefined;
35
32
  const own = extractOwnerRepo(prUrl);
36
33
  // A bare `#12` refers to the PR's own repo.
37
- const target = m[1] ?? m[3] ?? (own && `${own.owner}/${own.repo}`);
38
- return target ? `https://github.com/${target}/issues/${m[2] ?? m[4]}` : undefined;
34
+ const target = ref.repo ?? (own && `${own.owner}/${own.repo}`);
35
+ return target ? `https://github.com/${target}/issues/${ref.number}` : undefined;
39
36
  }
40
37
  /**
41
38
  * A github.com issue or pull URL, rewritten to ` owner/repo#N ` before the
@@ -61,9 +58,7 @@ const ISSUE_MENTION_RE = /(?<![\w/.-])([\w-]+\/[\w.-]+)?#(\d+)\b/g;
61
58
  */
62
59
  export function mentionedIssueUrls(title, body, prUrl) {
63
60
  const own = extractOwnerRepo(prUrl);
64
- const text = `${title ?? ''}\n${body?.slice(0, MAX_BODY_CHARS) ?? ''}`
65
- .replaceAll(NON_PROSE_RE, ' ')
66
- .replaceAll(ISSUE_URL_RE, ' $1#$2 ');
61
+ const text = stripNonProse(`${title ?? ''}\n${body?.slice(0, MAX_BODY_CHARS) ?? ''}`).replaceAll(ISSUE_URL_RE, ' $1#$2 ');
67
62
  const urls = new Set();
68
63
  for (const m of text.matchAll(ISSUE_MENTION_RE)) {
69
64
  const target = m[1] ?? (own && `${own.owner}/${own.repo}`);
@@ -72,6 +67,35 @@ export function mentionedIssueUrls(title, body, prUrl) {
72
67
  }
73
68
  return [...urls];
74
69
  }
70
+ /** GitHub rejects a search whose text is longer than this. */
71
+ const MAX_SEARCH_QUERY_CHARS = 256;
72
+ /**
73
+ * Room kept inside that limit for what callers add around the scope: the
74
+ * state qualifiers (`is:pr is:closed is:unmerged`) and two date bounds.
75
+ */
76
+ const SCOPE_QUERY_BUDGET = MAX_SEARCH_QUERY_CHARS - 96;
77
+ /** An organisation login that is safe to put in a search query. */
78
+ const ORG_LOGIN_RE = /^[\w.-]+$/;
79
+ /**
80
+ * Which of the user's PRs the ledgers and their counts cover: public
81
+ * repositories only, not the user's own, and not organisations in
82
+ * `config.untrackedOrgs` (the user's employer). One fragment, so the merged
83
+ * and closed ledger fetches and the count searches cannot drift apart: a
84
+ * count taken over a wider set than the ledger can hold would report a gap
85
+ * no back-fill closes.
86
+ */
87
+ export function externalPRScope(username, untrackedOrgs = []) {
88
+ const base = `is:public author:${username} -user:${username}`;
89
+ const exclusions = untrackedOrgs.map((org) => ` -org:${org}`).join('');
90
+ // No cap on the number of exclusions: a live search with ten `-org:` terms
91
+ // was accepted and returned a count. GitHub's documented limit of five
92
+ // operators is about the AND / OR / NOT keywords, not `-qualifier` terms.
93
+ const isExact = untrackedOrgs.every((org) => ORG_LOGIN_RE.test(org)) && base.length + exclusions.length <= SCOPE_QUERY_BUDGET;
94
+ if (!isExact) {
95
+ debug(MODULE, 'untrackedOrgs do not fit in a search query; filtering results instead, totals are not comparable.');
96
+ }
97
+ return { query: isExact ? base + exclusions : base, isExact };
98
+ }
75
99
  /** Returns an empty PRCountsResult. Used as the fallback when stats fetches fail or username is empty. */
76
100
  export function emptyPRCountsResult() {
77
101
  return {
@@ -94,7 +118,8 @@ function isCachedPRCounts(v) {
94
118
  typeof obj.monthlyOpenedCounts === 'object' &&
95
119
  obj.monthlyOpenedCounts !== null &&
96
120
  typeof obj.dailyActivityCounts === 'object' &&
97
- obj.dailyActivityCounts !== null);
121
+ obj.dailyActivityCounts !== null &&
122
+ ['number', 'undefined'].includes(typeof obj.totalCount));
98
123
  }
99
124
  /**
100
125
  * Shared paginated search for user PR counts with histogram tracking.
@@ -104,14 +129,19 @@ function isCachedPRCounts(v) {
104
129
  * string (e.g. mergedAt or closedAt) used for monthly counts and daily activity.
105
130
  * Return an empty string to skip histogram tracking for that item.
106
131
  */
107
- async function fetchUserPRCounts(octokit, githubUsername, query, label, accumulateRepo, starFilter) {
132
+ async function fetchUserPRCounts(octokit, githubUsername, query, label, accumulateRepo, starFilter, untrackedOrgs) {
108
133
  if (!githubUsername) {
109
134
  return emptyPRCountsResult();
110
135
  }
111
136
  // Check for a fresh cached result (avoids 10-20 paginated API calls)
112
137
  const cache = getHttpCache();
113
138
  const minStarsSuffix = starFilter ? `:stars${starFilter.minStars}` : '';
114
- const cacheKey = `pr-counts:v3:${label}:${githubUsername}${minStarsSuffix}`;
139
+ // v4: public repositories only, untracked organisations excluded (#1924).
140
+ // Sorted, so reordering the setting does not discard a fresh cache entry.
141
+ const orgKey = untrackedOrgs.map((org) => org.toLowerCase()).sort((a, b) => a.localeCompare(b));
142
+ const orgsSuffix = orgKey.length > 0 ? `:-${orgKey.join(',')}` : '';
143
+ const cacheKey = `pr-counts:v4:${label}:${githubUsername}${minStarsSuffix}${orgsSuffix}`;
144
+ const scope = externalPRScope(githubUsername, untrackedOrgs);
115
145
  const cached = cache.getIfFresh(cacheKey, PR_COUNTS_CACHE_TTL_MS);
116
146
  if (cached && isCachedPRCounts(cached)) {
117
147
  debug(MODULE, `Using cached ${label} PR counts for @${githubUsername}`);
@@ -122,6 +152,7 @@ async function fetchUserPRCounts(octokit, githubUsername, query, label, accumula
122
152
  dailyActivityCounts: cached.dailyActivityCounts,
123
153
  searchedPRs: Array.isArray(cached.searchedPRs) ? cached.searchedPRs : [],
124
154
  truncated: cached.truncated === true,
155
+ totalCount: cached.totalCount,
125
156
  };
126
157
  }
127
158
  debug(MODULE, `Fetching ${label} PR counts for @${githubUsername}...`);
@@ -135,7 +166,7 @@ async function fetchUserPRCounts(octokit, githubUsername, query, label, accumula
135
166
  let totalCount;
136
167
  while (true) {
137
168
  const { data } = await octokit.search.issuesAndPullRequests({
138
- q: `is:pr ${query} author:${githubUsername} -user:${githubUsername}`,
169
+ q: `is:pr ${query} ${scope.query}`,
139
170
  sort: 'updated',
140
171
  order: 'desc',
141
172
  per_page: 100,
@@ -150,8 +181,9 @@ async function fetchUserPRCounts(octokit, githubUsername, query, label, accumula
150
181
  }
151
182
  const { owner } = parsed;
152
183
  const repo = `${owner}/${parsed.repo}`;
153
- // Skip own repos (PRs to your own repos aren't OSS contributions)
154
- if (isOwnRepo(owner, githubUsername))
184
+ // Skip own repos (PRs to your own repos aren't OSS contributions) and
185
+ // untracked organisations (never counted, whether or not the query excluded them).
186
+ if (isOwnRepo(owner, githubUsername) || isUntrackedOrg(owner, untrackedOrgs))
155
187
  continue;
156
188
  searchedPRs.push({ url: item.html_url, title: item.title ?? '' });
157
189
  // Skip repos below the minimum star threshold (#576).
@@ -193,6 +225,7 @@ async function fetchUserPRCounts(octokit, githubUsername, query, label, accumula
193
225
  warn(MODULE, `Pagination capped at ${MAX_PAGINATION_PAGES} pages: fetched ${fetched} of ${totalCount} ${label} PRs. Stats may be incomplete for prolific contributors.`);
194
226
  }
195
227
  debug(MODULE, `Found ${fetched} ${label} PRs across ${repos.size} repos`);
228
+ const comparableTotal = scope.isExact ? totalCount : undefined;
196
229
  // Cache the aggregated result (Map → entries array for JSON serialization).
197
230
  // Note: truncated results (from pagination cap) are cached with the same TTL. This is an
198
231
  // accepted tradeoff — prolific contributors (300+ PRs) may see slightly incomplete stats
@@ -200,18 +233,27 @@ async function fetchUserPRCounts(octokit, githubUsername, query, label, accumula
200
233
  cache.set(cacheKey, '', {
201
234
  reposEntries: Array.from(repos.entries()),
202
235
  truncated: isTruncated,
236
+ totalCount: comparableTotal,
203
237
  monthlyCounts,
204
238
  monthlyOpenedCounts,
205
239
  dailyActivityCounts,
206
240
  searchedPRs,
207
241
  });
208
- return { repos, monthlyCounts, monthlyOpenedCounts, dailyActivityCounts, searchedPRs, truncated: isTruncated };
242
+ return {
243
+ repos,
244
+ monthlyCounts,
245
+ monthlyOpenedCounts,
246
+ dailyActivityCounts,
247
+ searchedPRs,
248
+ totalCount: comparableTotal,
249
+ truncated: isTruncated,
250
+ };
209
251
  }
210
252
  /**
211
253
  * Fetch merged PR counts and latest merge dates per repository for the configured user.
212
254
  * Also builds a monthly histogram of all merges for the contribution timeline.
213
255
  */
214
- export function fetchUserMergedPRCounts(octokit, githubUsername, starFilter) {
256
+ export function fetchUserMergedPRCounts(octokit, githubUsername, starFilter, untrackedOrgs = []) {
215
257
  return fetchUserPRCounts(octokit, githubUsername, 'is:merged', 'merged', (repos, repo, item) => {
216
258
  if (!item.pull_request?.merged_at) {
217
259
  warn(MODULE, `merged_at missing for merged PR ${item.html_url}${item.closed_at ? ', falling back to closed_at' : ', no date available'}`);
@@ -228,17 +270,32 @@ export function fetchUserMergedPRCounts(octokit, githubUsername, starFilter) {
228
270
  repos.set(repo, { count: 1, lastMergedAt: mergedAt });
229
271
  }
230
272
  return mergedAt;
231
- }, starFilter);
273
+ }, starFilter, untrackedOrgs);
232
274
  }
233
275
  /**
234
276
  * Fetch closed-without-merge PR counts per repository for the configured user.
235
277
  * Used to populate closedWithoutMergeCount in repo scores for accurate merge rate.
236
278
  */
237
- export function fetchUserClosedPRCounts(octokit, githubUsername, starFilter) {
279
+ export function fetchUserClosedPRCounts(octokit, githubUsername, starFilter, untrackedOrgs = []) {
238
280
  return fetchUserPRCounts(octokit, githubUsername, 'is:closed is:unmerged', 'closed', (repos, repo, item) => {
239
281
  repos.set(repo, (repos.get(repo) || 0) + 1);
240
282
  return item.closed_at || '';
241
- }, starFilter);
283
+ }, starFilter, untrackedOrgs);
284
+ }
285
+ /** Word a partial recent-PR search: a failed later page, else the counts read. */
286
+ function describeRecentListTruncation(label, search) {
287
+ const read = search.items.length;
288
+ if (search.failure) {
289
+ const cause = describeError(search.failure.error);
290
+ return {
291
+ label: `recently ${label} PR search failed on page ${search.failure.page} (${read} read)`,
292
+ message: `Recently ${label} PR search failed on page ${search.failure.page} (${cause}); only the ${read} result(s) from the page(s) before it were read. Some recently ${label} PRs may be missing this run.`,
293
+ };
294
+ }
295
+ return {
296
+ label: `recently ${label} PR search truncated (${read} of ${search.totalCount})`,
297
+ message: `Recently ${label} PR search is partial: read the ${read} most recently updated of ${search.totalCount} result(s). Some recently ${label} PRs may be missing this run.`,
298
+ };
242
299
  }
243
300
  /**
244
301
  * Shared helper: search for recent PRs and filter out own repos.
@@ -250,8 +307,15 @@ export function fetchUserClosedPRCounts(octokit, githubUsername, starFilter) {
250
307
  * vanishes from any `closed:>=X` filter even though the API returns a correct
251
308
  * `closed_at`. `updated` is the sort key, so it is always indexed. We narrow to
252
309
  * the real window here with `dateOf`.
310
+ *
311
+ * Reads up to `SEARCH_MAX_PAGES` pages (`searchAllPages`). When the list is
312
+ * still partial (more results than were read, a later page failed, or GitHub
313
+ * flagged the search incomplete), what was read is returned and the
314
+ * recent-list truncation is logged and pushed to `truncations`, so the caller
315
+ * can report it and hold back anything that reads "not in this list" as a
316
+ * fact (#1928).
253
317
  */
254
- async function fetchRecentPRs(octokit, config, query, label, days, mapItem, dateOf) {
318
+ async function fetchRecentPRs(octokit, config, query, label, days, mapItem, dateOf, truncations) {
255
319
  if (!config.githubUsername) {
256
320
  warn(MODULE, `Skipping recently ${label} PRs fetch: no githubUsername configured. Run /setup-oss to configure.`);
257
321
  return [];
@@ -260,14 +324,25 @@ async function fetchRecentPRs(octokit, config, query, label, days, mapItem, date
260
324
  sinceDate.setDate(sinceDate.getDate() - days);
261
325
  const since = sinceDate.toISOString().split('T', 1)[0]; // YYYY-MM-DD
262
326
  debug(MODULE, `Fetching recently ${label} PRs for @${config.githubUsername} (since ${since})...`);
263
- const { data } = await octokit.search.issuesAndPullRequests({
264
- q: query.replace('{username}', config.githubUsername).replace('{since}', since),
327
+ // The shared scope keeps untracked organisations out of the search itself,
328
+ // so their PRs use no page slots; the owner filter below stays for a list
329
+ // that does not fit in a query.
330
+ const scope = externalPRScope(config.githubUsername, config.untrackedOrgs);
331
+ const search = await searchAllPages((page) => octokit.search.issuesAndPullRequests({
332
+ page,
333
+ q: query.replace('{scope}', scope.query).replace('{since}', since),
265
334
  sort: 'updated',
266
335
  order: 'desc',
267
336
  per_page: 100,
268
- });
337
+ }));
338
+ const { items } = search;
339
+ if (search.truncated) {
340
+ const truncation = describeRecentListTruncation(label, search);
341
+ warn(MODULE, truncation.message);
342
+ truncations?.push(truncation);
343
+ }
269
344
  const results = [];
270
- for (const item of data.items) {
345
+ for (const item of items) {
271
346
  const parsed = parseGitHubUrl(item.html_url);
272
347
  if (!parsed) {
273
348
  warn(MODULE, `Could not parse GitHub URL from API response: ${item.html_url}`);
@@ -293,8 +368,8 @@ async function fetchRecentPRs(octokit, config, query, label, days, mapItem, date
293
368
  * Fetch PRs closed without merge in the last N days.
294
369
  * Returns lightweight ClosedPR objects for surfacing in the daily digest.
295
370
  */
296
- export async function fetchRecentlyClosedPRs(octokit, config, days = 7) {
297
- return fetchRecentPRs(octokit, config, 'is:pr is:closed is:unmerged is:public author:{username} updated:>={since}', 'closed', days, (item, { repo, number }) => ({
371
+ export async function fetchRecentlyClosedPRs(octokit, config, days = 7, truncations) {
372
+ return fetchRecentPRs(octokit, config, 'is:pr is:closed is:unmerged {scope} updated:>={since}', 'closed', days, (item, { repo, number }) => ({
298
373
  url: item.html_url,
299
374
  repo,
300
375
  number,
@@ -303,14 +378,14 @@ export async function fetchRecentlyClosedPRs(octokit, config, days = 7) {
303
378
  // Free on the search result — feeds the outcome ledger (#1461).
304
379
  openedAt: item.created_at || undefined,
305
380
  issueUrl: closingIssueUrl(item.body, item.html_url),
306
- }), (item) => item.closed_at);
381
+ }), (item) => item.closed_at, truncations);
307
382
  }
308
383
  /**
309
384
  * Fetch PRs merged in the last N days.
310
385
  * Returns lightweight MergedPR objects for surfacing as wins in the dashboard.
311
386
  */
312
- export async function fetchRecentlyMergedPRs(octokit, config, days = 7) {
313
- return fetchRecentPRs(octokit, config, 'is:pr is:merged is:public author:{username} updated:>={since}', 'merged', days, (item, { repo, number }) => {
387
+ export async function fetchRecentlyMergedPRs(octokit, config, days = 7, truncations) {
388
+ return fetchRecentPRs(octokit, config, 'is:pr is:merged {scope} updated:>={since}', 'merged', days, (item, { repo, number }) => {
314
389
  const mergedAt = item.pull_request?.merged_at;
315
390
  if (!mergedAt) {
316
391
  warn(MODULE, `merged_at missing for merged PR ${item.html_url}${item.closed_at ? ', falling back to closed_at' : ', no date available'}`);
@@ -325,96 +400,206 @@ export async function fetchRecentlyMergedPRs(octokit, config, days = 7) {
325
400
  openedAt: item.created_at || undefined,
326
401
  issueUrl: closingIssueUrl(item.body, item.html_url),
327
402
  };
328
- }, (item) => item.pull_request?.merged_at || item.closed_at);
403
+ }, (item) => item.pull_request?.merged_at || item.closed_at, truncations);
329
404
  }
330
- async function fetchPRsSince(octokit, config, adapter, since) {
331
- if (!config.githubUsername) {
332
- warn(MODULE, `Skipping ${adapter.kind} PRs fetch: no githubUsername configured.`);
333
- return [];
334
- }
335
- const q = adapter.buildQuery(config.githubUsername, since);
336
- debug(MODULE, `Fetching ${adapter.kind} PRs${since ? ` since ${since}` : ' (all time)'}...`);
337
- const results = [];
338
- let page = 1;
339
- let fetched = 0;
340
- // Populated from the first Search API response; always set before we exit the loop.
341
- let totalCount;
342
- while (true) {
405
+ /**
406
+ * Most PRs a ledger gap fetch takes in one run (the Search API's own cap for
407
+ * a single query). A search matching more returns nothing: the caller stores
408
+ * no rows, so the ledger's newest entry stays where it was, the next run asks
409
+ * for the same range, and `ledger-backfill` (no limit) is the way out.
410
+ */
411
+ export const LEDGER_GAP_MAX_RESULTS = 1000;
412
+ /** What the daily run and the dashboard report when a merged-ledger gap fetch is truncated. */
413
+ export const MERGED_LEDGER_TRUNCATED_MESSAGE = `More than ${LEDGER_GAP_MAX_RESULTS} merged PRs changed since the merged-PR ledger was last filled, ` +
414
+ 'so none were stored. Run `ledger-backfill` to fetch the full history.';
415
+ /** What the daily run and the dashboard report when a closed-ledger gap fetch is truncated. */
416
+ export const CLOSED_LEDGER_TRUNCATED_MESSAGE = `More than ${LEDGER_GAP_MAX_RESULTS} closed PRs changed since the closed-PR ledger was last filled, ` +
417
+ 'so none were stored. Run `ledger-backfill` to fetch the full history.';
418
+ /**
419
+ * A ledger with fewer rows than this that is short of GitHub's all-time count
420
+ * is refetched from the start (#1504, #1925): a recent row stored ahead of the
421
+ * history behind it would otherwise hide that history from every gap fetch.
422
+ * Past it a short ledger keeps its watermark, so a contributor whose count
423
+ * legitimately exceeds the ledger doesn't refetch everything on every run;
424
+ * the count warning and `ledger-backfill` cover that case.
425
+ */
426
+ export const LEDGER_BACKFILL_CEILING = 300;
427
+ /**
428
+ * The watermark a ledger gap fetch starts from: undefined (all time) when the
429
+ * ledger holds `stored` rows, fewer than `allTimeCount` and under
430
+ * {@link LEDGER_BACKFILL_CEILING}, and the whole history fits in one gap fetch
431
+ * ({@link LEDGER_GAP_MAX_RESULTS}); otherwise `watermark`. An unknown count
432
+ * keeps the watermark.
433
+ *
434
+ * A history larger than one fetch would come back truncated with no rows, and
435
+ * the caller then stores nothing, the recent list included, on every run. So
436
+ * that ledger keeps growing from its watermark and the count warning points
437
+ * at `ledger-backfill`, which fetches without a limit.
438
+ */
439
+ export function gapFetchWatermark(watermark, stored, allTimeCount) {
440
+ const total = allTimeCount ?? 0;
441
+ return stored < total && stored < LEDGER_BACKFILL_CEILING && total <= LEDGER_GAP_MAX_RESULTS ? undefined : watermark;
442
+ }
443
+ /** How far before the watermark a gap fetch starts: covers clock skew and search indexing lag. */
444
+ const LEDGER_GAP_OVERLAP_MS = 24 * 60 * 60 * 1000;
445
+ /**
446
+ * The search bound for a ledger watermark (its newest stored date): one
447
+ * overlap earlier, at second precision. An absent or unparseable watermark
448
+ * gives undefined, which means "all time".
449
+ */
450
+ export function withLedgerOverlap(watermark = '') {
451
+ const time = Date.parse(watermark);
452
+ if (Number.isNaN(time))
453
+ return undefined;
454
+ const bound = new Date(time - LEDGER_GAP_OVERLAP_MS);
455
+ return `${bound.toISOString().slice(0, 19)}Z`;
456
+ }
457
+ /**
458
+ * Up to MAX_PAGINATION_PAGES pages of `q`, oldest-created first. That order
459
+ * never changes while paging (a PR's creation date is fixed), and it lets the
460
+ * caller continue past the page cap with a `created:>=` bound instead of deep
461
+ * pages. Stops after the first page when the total exceeds `maxResults`.
462
+ */
463
+ async function fetchSearchWindow(octokit, q, maxResults) {
464
+ const items = [];
465
+ let totalCount = 0;
466
+ let isExhausted = false;
467
+ for (let page = 1; !isExhausted && page <= MAX_PAGINATION_PAGES && totalCount <= maxResults; page++) {
343
468
  const { data } = await octokit.search.issuesAndPullRequests({
344
469
  q,
345
- sort: 'updated',
346
- order: 'desc',
470
+ sort: 'created',
471
+ order: 'asc',
347
472
  per_page: 100,
348
473
  page,
349
474
  });
350
475
  totalCount = data.total_count;
351
- for (const item of data.items) {
352
- const parsed = parseGitHubUrl(item.html_url);
353
- if (!parsed) {
354
- warn(MODULE, `Skipping ${adapter.kind} PR with unparseable URL: ${item.html_url}`);
355
- continue;
356
- }
357
- if (isOwnRepo(parsed.owner, config.githubUsername))
358
- continue;
359
- const date = adapter.extractDate(item);
360
- if (!date) {
361
- warn(MODULE, `Skipping ${adapter.kind} PR with no ${adapter.dateNoun} date: ${item.html_url}`);
362
- continue;
363
- }
364
- results.push(adapter.buildRecord(item, date));
476
+ items.push(...data.items);
477
+ isExhausted = items.length >= totalCount || data.items.length === 0;
478
+ }
479
+ return { items, totalCount, isExhausted };
480
+ }
481
+ /** The stored-shape record for a search item, or undefined when it is skipped. */
482
+ function toStoredRecord(item, config, adapter) {
483
+ const parsed = parseGitHubUrl(item.html_url);
484
+ if (!parsed) {
485
+ warn(MODULE, `Skipping ${adapter.kind} PR with unparseable URL: ${item.html_url}`);
486
+ return undefined;
487
+ }
488
+ if (isOwnRepo(parsed.owner, config.githubUsername))
489
+ return undefined;
490
+ // Never stored, whether or not the query could exclude the organisation.
491
+ if (isUntrackedOrg(parsed.owner, config.untrackedOrgs))
492
+ return undefined;
493
+ const date = adapter.extractDate(item);
494
+ if (!date) {
495
+ warn(MODULE, `Skipping ${adapter.kind} PR with no ${adapter.dateNoun} date: ${item.html_url}`);
496
+ return undefined;
497
+ }
498
+ return adapter.buildRecord(item, date);
499
+ }
500
+ /**
501
+ * A window that ended on its page cap without a later creation date to
502
+ * continue from (300 PRs created in one second, or no creation dates). The
503
+ * walk would repeat it forever, so it counts as truncated.
504
+ */
505
+ function isWalkStuck(page, cursor, next) {
506
+ return !page.isExhausted && (!next || next === cursor);
507
+ }
508
+ /**
509
+ * Every PR matching the adapter's query for `since`, or `truncated` when
510
+ * there are more than `maxResults`. Walks the results in windows of
511
+ * MAX_PAGINATION_PAGES pages, each starting at the creation date the last one
512
+ * ended on, so no request goes to a deep page. A request failure rejects;
513
+ * nothing partial is returned either way.
514
+ */
515
+ async function fetchPRsSince(octokit, config, adapter, since, maxResults) {
516
+ if (!config.githubUsername) {
517
+ warn(MODULE, `Skipping ${adapter.kind} PRs fetch: no githubUsername configured.`);
518
+ return { prs: [], truncated: false };
519
+ }
520
+ const scope = externalPRScope(config.githubUsername, config.untrackedOrgs);
521
+ const baseQuery = adapter.buildQuery(scope.query, since);
522
+ debug(MODULE, `Fetching ${adapter.kind} PRs: ${baseQuery}`);
523
+ const prs = [];
524
+ const seen = new Set();
525
+ let query = baseQuery;
526
+ let cursor;
527
+ for (;;) {
528
+ const page = await fetchSearchWindow(octokit, query, maxResults);
529
+ const next = page.items.at(-1)?.created_at ?? undefined;
530
+ if (page.totalCount > maxResults || isWalkStuck(page, cursor, next)) {
531
+ warn(MODULE, `Not storing ${adapter.kind} PRs: the search matched ${page.totalCount}, more than one run fetches.`);
532
+ return { prs: [], truncated: true };
365
533
  }
366
- fetched += data.items.length;
367
- if (fetched >= totalCount || fetched >= 1000 || data.items.length === 0 || page >= MAX_PAGINATION_PAGES) {
368
- break;
534
+ for (const item of page.items) {
535
+ const record = toStoredRecord(item, config, adapter);
536
+ if (record && !seen.has(record.url))
537
+ prs.push(record);
538
+ seen.add(item.html_url);
369
539
  }
370
- page++;
371
- }
372
- if (fetched < totalCount && page >= MAX_PAGINATION_PAGES) {
373
- warn(MODULE, `Pagination capped at ${MAX_PAGINATION_PAGES} pages: fetched ${fetched} of ${totalCount} ${adapter.kind} PRs. Oldest PRs may be missing.`);
540
+ if (page.isExhausted)
541
+ break;
542
+ cursor = next;
543
+ query = `${baseQuery} created:>=${cursor}`;
374
544
  }
375
- debug(MODULE, `Fetched ${results.length} ${adapter.kind} PRs${since ? ' (incremental)' : ' (initial)'}`);
376
- return results;
545
+ debug(MODULE, `Fetched ${prs.length} ${adapter.kind} PRs`);
546
+ return { prs, truncated: false };
377
547
  }
548
+ const MERGED_ADAPTER = {
549
+ kind: 'merged',
550
+ dateNoun: 'merge',
551
+ // Bounded on `updated`, not `merged`: GitHub can index a PR for `updated:`
552
+ // while its merge-date facet is missing (see fetchRecentPRs), and such a PR
553
+ // would never match `merged:>`. Every PR merged after a date was also
554
+ // updated after it, so this is a superset; re-seen rows dedupe on write.
555
+ buildQuery: (scope, s) => `is:pr is:merged ${scope}` + (s ? ` updated:>${s}` : ''),
556
+ extractDate: (item) => item.pull_request?.merged_at || item.closed_at || '',
557
+ buildRecord: (item, date) => ({
558
+ url: item.html_url,
559
+ title: item.title,
560
+ mergedAt: date,
561
+ // Free on the search result — feeds the outcome ledger (#1461).
562
+ openedAt: item.created_at || undefined,
563
+ issueUrl: closingIssueUrl(item.body, item.html_url),
564
+ }),
565
+ };
378
566
  /**
379
- * Fetch merged PRs since a watermark date for incremental storage.
380
- * If no watermark is provided (first-ever fetch), fetches all merged PRs (up to pagination cap).
381
- * Returns StoredMergedPR[] (url, title, mergedAt, openedAt) for state persistence.
567
+ * The one fetch that fills the merged-PR ledger (#1924), shared by the daily
568
+ * run, the dashboard and `ledger-backfill`: every merged PR updated since
569
+ * `watermark` (the ledger's newest `mergedAt`) minus a one-day overlap, or
570
+ * all of them when there is no watermark.
571
+ *
572
+ * `truncated` (more than `maxResults` matches) returns no rows. Callers must
573
+ * then add nothing newer to the ledger, so its watermark does not move past
574
+ * the range that was not fetched. `ledger-backfill` passes `Infinity`.
382
575
  */
383
- export async function fetchMergedPRsSince(octokit, config, since) {
384
- return fetchPRsSince(octokit, config, {
385
- kind: 'merged',
386
- dateNoun: 'merge',
387
- buildQuery: (u, s) => `is:pr is:merged author:${u} -user:${u}${s ? ` merged:>${s}` : ''}`,
388
- extractDate: (item) => item.pull_request?.merged_at || item.closed_at || '',
389
- buildRecord: (item, date) => ({
390
- url: item.html_url,
391
- title: item.title,
392
- mergedAt: date,
393
- // Free on the search result — feeds the outcome ledger (#1461).
394
- openedAt: item.created_at || undefined,
395
- issueUrl: closingIssueUrl(item.body, item.html_url),
396
- }),
397
- }, since);
576
+ export async function fetchMergedPRsSince(octokit, config, watermark, maxResults = LEDGER_GAP_MAX_RESULTS) {
577
+ return fetchPRsSince(octokit, config, MERGED_ADAPTER, withLedgerOverlap(watermark), maxResults);
398
578
  }
579
+ const CLOSED_ADAPTER = {
580
+ kind: 'closed',
581
+ dateNoun: 'close',
582
+ // `is:unmerged` leaves out merged PRs, which GitHub also counts as closed.
583
+ // Bounded on `updated` for the same reason as MERGED_ADAPTER: the close-date
584
+ // facet can be missing from the index (see fetchRecentPRs).
585
+ buildQuery: (scope, s) => `is:pr is:closed is:unmerged ${scope}` + (s ? ` updated:>${s}` : ''),
586
+ extractDate: (item) => item.closed_at || '',
587
+ buildRecord: (item, date) => ({
588
+ url: item.html_url,
589
+ title: item.title,
590
+ closedAt: date,
591
+ // Free on the search result — feeds the outcome ledger (#1461).
592
+ openedAt: item.created_at || undefined,
593
+ issueUrl: closingIssueUrl(item.body, item.html_url),
594
+ }),
595
+ };
399
596
  /**
400
- * Fetch closed-without-merge PRs since a watermark date for incremental storage.
401
- * If no watermark is provided (first-ever fetch), fetches all closed PRs (up to pagination cap).
402
- * Returns StoredClosedPR[] (url, title, closedAt, openedAt) for state persistence.
403
- * Uses `is:unmerged` to exclude merged PRs (which are also "closed" in GitHub's model).
597
+ * The closed-without-merge mirror of {@link fetchMergedPRsSince} (#1925),
598
+ * shared by the daily run, the dashboard and `ledger-backfill`: every closed
599
+ * PR updated since `watermark` (the ledger's newest `closedAt`) minus a
600
+ * one-day overlap, or all of them when there is no watermark. Same
601
+ * `truncated` contract: no rows, so the watermark does not move.
404
602
  */
405
- export async function fetchClosedPRsSince(octokit, config, since) {
406
- return fetchPRsSince(octokit, config, {
407
- kind: 'closed',
408
- dateNoun: 'close',
409
- buildQuery: (u, s) => `is:pr is:closed is:unmerged author:${u} -user:${u}${s ? ` closed:>${s}` : ''}`,
410
- extractDate: (item) => item.closed_at || '',
411
- buildRecord: (item, date) => ({
412
- url: item.html_url,
413
- title: item.title,
414
- closedAt: date,
415
- // Free on the search result — feeds the outcome ledger (#1461).
416
- openedAt: item.created_at || undefined,
417
- issueUrl: closingIssueUrl(item.body, item.html_url),
418
- }),
419
- }, since);
603
+ export async function fetchClosedPRsSince(octokit, config, watermark, maxResults = LEDGER_GAP_MAX_RESULTS) {
604
+ return fetchPRsSince(octokit, config, CLOSED_ADAPTER, withLedgerOverlap(watermark), maxResults);
420
605
  }
@@ -106,13 +106,3 @@ export declare function cachedRequest<T>(cache: HttpCache, url: string, fetcher:
106
106
  data: T;
107
107
  headers?: Record<string, string>;
108
108
  }>): Promise<T>;
109
- /**
110
- * Time-based cache wrapper (no ETag / conditional requests).
111
- *
112
- * If a cached result exists and is younger than `maxAgeMs`, returns it.
113
- * Otherwise calls `fetcher`, caches the result, and returns it.
114
- *
115
- * Use this for expensive operations whose results change slowly
116
- * (e.g. search queries, project health checks).
117
- */
118
- export declare function cachedTimeBased<T>(cache: HttpCache, key: string, maxAgeMs: number, fetcher: () => Promise<T>): Promise<T>;
@@ -334,25 +334,6 @@ export async function cachedRequest(cache, url, fetcher) {
334
334
  cleanup();
335
335
  }
336
336
  }
337
- /**
338
- * Time-based cache wrapper (no ETag / conditional requests).
339
- *
340
- * If a cached result exists and is younger than `maxAgeMs`, returns it.
341
- * Otherwise calls `fetcher`, caches the result, and returns it.
342
- *
343
- * Use this for expensive operations whose results change slowly
344
- * (e.g. search queries, project health checks).
345
- */
346
- export async function cachedTimeBased(cache, key, maxAgeMs, fetcher) {
347
- const cached = cache.getIfFresh(key, maxAgeMs);
348
- if (cached) {
349
- debug(MODULE, `Time-based cache hit for ${key}`);
350
- return cached;
351
- }
352
- const result = await fetcher();
353
- cache.set(key, '', result);
354
- return result;
355
- }
356
337
  /**
357
338
  * Detect whether an error is a 304 Not Modified response.
358
339
  * Octokit throws a RequestError with status 304 for conditional requests.