@oss-autopilot/core 3.42.4 → 3.43.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 (172) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +272 -25
  3. package/dist/cli.bundle.cjs +183 -154
  4. package/dist/commands/check-integration.js +1 -0
  5. package/dist/commands/cleanup.d.ts +76 -0
  6. package/dist/commands/cleanup.js +269 -0
  7. package/dist/commands/comments.d.ts +6 -0
  8. package/dist/commands/comments.js +6 -2
  9. package/dist/commands/config.js +37 -5
  10. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  11. package/dist/commands/daily-dismiss-filter.js +17 -1
  12. package/dist/commands/daily-ledger.d.ts +122 -0
  13. package/dist/commands/daily-ledger.js +225 -0
  14. package/dist/commands/daily-recent-prs.d.ts +26 -0
  15. package/dist/commands/daily-recent-prs.js +55 -0
  16. package/dist/commands/daily.d.ts +2 -1
  17. package/dist/commands/daily.js +59 -89
  18. package/dist/commands/dashboard-cache.d.ts +2 -0
  19. package/dist/commands/dashboard-cache.js +33 -8
  20. package/dist/commands/dashboard-data.js +71 -36
  21. package/dist/commands/dashboard-gist-sync.js +3 -1
  22. package/dist/commands/dashboard-lifecycle.js +1 -1
  23. package/dist/commands/dashboard-process.d.ts +14 -1
  24. package/dist/commands/dashboard-process.js +46 -7
  25. package/dist/commands/dashboard-server.js +89 -23
  26. package/dist/commands/detect-formatters.js +1 -0
  27. package/dist/commands/dismiss.js +5 -2
  28. package/dist/commands/doctor.d.ts +15 -1
  29. package/dist/commands/doctor.js +73 -5
  30. package/dist/commands/draft.d.ts +77 -0
  31. package/dist/commands/draft.js +218 -0
  32. package/dist/commands/eval.js +1 -0
  33. package/dist/commands/guidelines.d.ts +23 -1
  34. package/dist/commands/guidelines.js +49 -4
  35. package/dist/commands/index.d.ts +24 -4
  36. package/dist/commands/index.js +15 -3
  37. package/dist/commands/issue-thread.d.ts +46 -0
  38. package/dist/commands/issue-thread.js +123 -0
  39. package/dist/commands/ledger-backfill.d.ts +9 -0
  40. package/dist/commands/ledger-backfill.js +44 -1
  41. package/dist/commands/list-mark-done.d.ts +2 -1
  42. package/dist/commands/list-mark-done.js +3 -1
  43. package/dist/commands/list-move-tier.d.ts +2 -1
  44. package/dist/commands/list-move-tier.js +3 -1
  45. package/dist/commands/local-repos.js +10 -5
  46. package/dist/commands/locate-issue-list.d.ts +40 -17
  47. package/dist/commands/locate-issue-list.js +148 -88
  48. package/dist/commands/move.js +7 -1
  49. package/dist/commands/overnight-handoff.d.ts +17 -7
  50. package/dist/commands/overnight-handoff.js +36 -14
  51. package/dist/commands/overnight-push-prep.d.ts +13 -8
  52. package/dist/commands/overnight-push-prep.js +106 -34
  53. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  54. package/dist/commands/overnight-tool-rules.js +217 -0
  55. package/dist/commands/overnight.d.ts +5 -6
  56. package/dist/commands/overnight.js +61 -140
  57. package/dist/commands/parse-list.js +7 -1
  58. package/dist/commands/policy.d.ts +86 -0
  59. package/dist/commands/policy.js +263 -0
  60. package/dist/commands/pr-preflight.d.ts +43 -0
  61. package/dist/commands/pr-preflight.js +294 -0
  62. package/dist/commands/repo-vet.d.ts +9 -0
  63. package/dist/commands/repo-vet.js +36 -11
  64. package/dist/commands/scout-bridge.js +18 -8
  65. package/dist/commands/search.js +7 -0
  66. package/dist/commands/setup.d.ts +3 -3
  67. package/dist/commands/setup.js +46 -18
  68. package/dist/commands/skip-add.js +10 -1
  69. package/dist/commands/startup.d.ts +5 -3
  70. package/dist/commands/startup.js +65 -49
  71. package/dist/commands/state-cmd.d.ts +2 -0
  72. package/dist/commands/state-cmd.js +5 -1
  73. package/dist/commands/stats.js +1 -0
  74. package/dist/commands/status.js +1 -0
  75. package/dist/commands/strategy.js +1 -0
  76. package/dist/commands/vet-list.d.ts +6 -0
  77. package/dist/commands/vet-list.js +25 -0
  78. package/dist/commands/vet.d.ts +12 -0
  79. package/dist/commands/vet.js +118 -1
  80. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  81. package/dist/core/anti-llm-policy.d.ts +3 -0
  82. package/dist/core/anti-llm-policy.js +3 -0
  83. package/dist/core/auth.js +2 -0
  84. package/dist/core/checklist-analysis.js +50 -12
  85. package/dist/core/ci-analysis.d.ts +7 -2
  86. package/dist/core/ci-analysis.js +76 -21
  87. package/dist/core/comment-utils.d.ts +1 -1
  88. package/dist/core/comment-utils.js +7 -1
  89. package/dist/core/commit-date.d.ts +19 -0
  90. package/dist/core/commit-date.js +17 -0
  91. package/dist/core/compliance-score.js +11 -7
  92. package/dist/core/config-registry.js +11 -5
  93. package/dist/core/contributing.d.ts +2 -3
  94. package/dist/core/contributing.js +2 -3
  95. package/dist/core/daily-logic.d.ts +27 -5
  96. package/dist/core/daily-logic.js +57 -19
  97. package/dist/core/errors.d.ts +37 -3
  98. package/dist/core/errors.js +54 -5
  99. package/dist/core/gist-health.d.ts +15 -3
  100. package/dist/core/gist-health.js +8 -0
  101. package/dist/core/gist-state-store.d.ts +24 -4
  102. package/dist/core/gist-state-store.js +97 -46
  103. package/dist/core/github-stats.d.ts +104 -16
  104. package/dist/core/github-stats.js +282 -97
  105. package/dist/core/http-cache.d.ts +0 -10
  106. package/dist/core/http-cache.js +0 -19
  107. package/dist/core/index.d.ts +12 -5
  108. package/dist/core/index.js +15 -5
  109. package/dist/core/issue-conversation.d.ts +8 -2
  110. package/dist/core/issue-conversation.js +31 -12
  111. package/dist/core/local-config.d.ts +95 -0
  112. package/dist/core/local-config.js +271 -0
  113. package/dist/core/merged-pr-notes.d.ts +2 -2
  114. package/dist/core/pagination.d.ts +55 -0
  115. package/dist/core/pagination.js +59 -0
  116. package/dist/core/paths.d.ts +7 -0
  117. package/dist/core/paths.js +9 -0
  118. package/dist/core/pr-assembly.js +6 -2
  119. package/dist/core/pr-graphql.d.ts +37 -3
  120. package/dist/core/pr-graphql.js +73 -12
  121. package/dist/core/pr-monitor.d.ts +29 -12
  122. package/dist/core/pr-monitor.js +71 -23
  123. package/dist/core/pr-preflight.d.ts +113 -0
  124. package/dist/core/pr-preflight.js +364 -0
  125. package/dist/core/pr-quality-rubric.d.ts +0 -6
  126. package/dist/core/pr-quality-rubric.js +0 -8
  127. package/dist/core/pr-template.d.ts +2 -0
  128. package/dist/core/pr-template.js +5 -1
  129. package/dist/core/repo-policy.d.ts +105 -0
  130. package/dist/core/repo-policy.js +400 -0
  131. package/dist/core/repo-score-manager.d.ts +48 -0
  132. package/dist/core/repo-score-manager.js +111 -1
  133. package/dist/core/review-analysis.d.ts +34 -19
  134. package/dist/core/review-analysis.js +74 -19
  135. package/dist/core/reviewed-prs-fetch.js +11 -29
  136. package/dist/core/reviewed-prs.js +8 -15
  137. package/dist/core/stale-data.d.ts +41 -0
  138. package/dist/core/stale-data.js +115 -0
  139. package/dist/core/state-persistence.d.ts +62 -27
  140. package/dist/core/state-persistence.js +338 -117
  141. package/dist/core/state-schema.d.ts +113 -210
  142. package/dist/core/state-schema.js +165 -80
  143. package/dist/core/state.d.ts +60 -8
  144. package/dist/core/state.js +192 -46
  145. package/dist/core/status-determination.js +26 -8
  146. package/dist/core/strategy.js +3 -1
  147. package/dist/core/types.d.ts +22 -1
  148. package/dist/core/types.js +1 -0
  149. package/dist/core/untrusted-content.d.ts +30 -11
  150. package/dist/core/untrusted-content.js +77 -42
  151. package/dist/core/urls.d.ts +9 -0
  152. package/dist/core/urls.js +18 -0
  153. package/dist/dashboard/assets/{chart-panel-DPKNBUts.js → chart-panel-C_C1lFTI.js} +1 -1
  154. package/dist/dashboard/assets/{index-B25bZOYX.js → index-B--H66Jk.js} +1 -1
  155. package/dist/dashboard/index.html +1 -1
  156. package/dist/formatters/json.d.ts +262 -6
  157. package/dist/formatters/json.js +77 -1
  158. package/package.json +1 -1
  159. package/dist/core/ci-enforced-tools.d.ts +0 -35
  160. package/dist/core/ci-enforced-tools.js +0 -109
  161. package/dist/core/comment-decision.d.ts +0 -79
  162. package/dist/core/comment-decision.js +0 -82
  163. package/dist/core/extraction-categories.d.ts +0 -55
  164. package/dist/core/extraction-categories.js +0 -108
  165. package/dist/core/follow-up-history.d.ts +0 -40
  166. package/dist/core/follow-up-history.js +0 -71
  167. package/dist/core/issue-effort.d.ts +0 -29
  168. package/dist/core/issue-effort.js +0 -47
  169. package/dist/core/maintainer-hints.d.ts +0 -23
  170. package/dist/core/maintainer-hints.js +0 -36
  171. package/dist/core/workflow-state.d.ts +0 -56
  172. package/dist/core/workflow-state.js +0 -101
@@ -11,11 +11,36 @@ import * as fs from 'node:fs';
11
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
+ import { findRefKey } from '../core/urls.js';
14
15
  import { computePRsByRepo, computeTopRepos, getMonthlyData, buildDashboardStats, reconcileShelvePartition, storedToMergedPRs, storedToClosedPRs, } from './dashboard-data.js';
15
- import { detectIssueList } from './startup.js';
16
+ import { detectIssueListPath, isForeignCheckout } from './locate-issue-list.js';
16
17
  import { parseIssueList } from './parse-list.js';
17
18
  import { isBelowMinStars, } from '../core/types.js';
18
19
  const MODULE = 'dashboard-server';
20
+ // Foreign-checkout verdicts keyed by checkout dir + GitHub username (#2012).
21
+ // The dashboard polls /api/data, and the check runs two synchronous `git`
22
+ // calls; the configured path and its source are still read on every call, so
23
+ // `setup --set issueListPath=...` takes effect on the next request. GET
24
+ // /api/data clears these when state reloads or the list file changes, so a
25
+ // remote change in the list's checkout is seen at the next such event.
26
+ const foreignVerdicts = new Map();
27
+ /** Forget cached foreign-checkout verdicts so the next lookup re-runs Git. */
28
+ export function clearForeignVerdicts() {
29
+ foreignVerdicts.clear();
30
+ }
31
+ function isForeignCheckoutCached(dir) {
32
+ const key = `${dir}\0${getStateManager().getState().config.githubUsername}`;
33
+ let verdict = foreignVerdicts.get(key);
34
+ if (verdict === undefined) {
35
+ verdict = isForeignCheckout(dir);
36
+ foreignVerdicts.set(key, verdict);
37
+ }
38
+ return verdict;
39
+ }
40
+ /** The configured issue list path for the dashboard: no item counting, Git checked once per checkout. */
41
+ function dashboardIssueListPath() {
42
+ return detectIssueListPath(isForeignCheckoutCached)?.path;
43
+ }
19
44
  /**
20
45
  * Read and parse the vetted issue list file (non-fatal on failure).
21
46
  *
@@ -26,10 +51,10 @@ const MODULE = 'dashboard-server';
26
51
  */
27
52
  function readVettedIssues(failures) {
28
53
  try {
29
- const info = detectIssueList();
30
- if (!info)
54
+ const listPath = dashboardIssueListPath();
55
+ if (!listPath)
31
56
  return null;
32
- const content = fs.readFileSync(info.path, 'utf8');
57
+ const content = fs.readFileSync(listPath, 'utf8');
33
58
  return parseIssueList(content);
34
59
  }
35
60
  catch (error) {
@@ -44,10 +69,10 @@ function readVettedIssues(failures) {
44
69
  */
45
70
  export function getIssueListMtimeMs() {
46
71
  try {
47
- const info = detectIssueList();
48
- if (!info)
72
+ const listPath = dashboardIssueListPath();
73
+ if (!listPath)
49
74
  return null;
50
- return fs.statSync(info.path).mtimeMs;
75
+ return fs.statSync(listPath).mtimeMs;
51
76
  }
52
77
  catch {
53
78
  return null;
@@ -101,7 +126,7 @@ export function buildDashboardJson(digest, state, commentedIssues, allMergedPRs,
101
126
  const issueResponses = commentedIssues.filter((i) => {
102
127
  if (i.status !== 'new_response')
103
128
  return false;
104
- const dismissedAt = dismissedIssues[i.url];
129
+ const dismissedAt = dismissedIssues[findRefKey(dismissedIssues, i.url) ?? i.url];
105
130
  return !dismissedAt || !isCoveredByDismiss(dismissedAt, i.lastResponseAt);
106
131
  });
107
132
  // Build repo metadata map from repoScores — omit repos without stars or language to avoid empty entries
@@ -3,11 +3,11 @@
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, collectEngagedIssues, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, } from '../core/index.js';
6
+ import { getStateManager, PRMonitor, IssueConversationMonitor, getOctokit, CRITICAL_STATUSES, shouldAutoUnshelve, 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
- import { emptyPRCountsResult, fetchMergedPRsSince, fetchClosedPRsSince } from '../core/github-stats.js';
10
- import { parseGitHubUrl } from '../core/urls.js';
9
+ import { emptyPRCountsResult, fetchMergedPRsSince, fetchClosedPRsSince, gapFetchWatermark, LEDGER_BACKFILL_CEILING, CLOSED_LEDGER_TRUNCATED_MESSAGE, MERGED_LEDGER_TRUNCATED_MESSAGE, } from '../core/github-stats.js';
10
+ import { parseGitHubUrl, issueRefKey } from '../core/urls.js';
11
11
  import { isBelowMinStars, } from '../core/types.js';
12
12
  const MODULE = 'dashboard-data';
13
13
  export function buildDashboardStats(digest, state, storedMergedCount, storedClosedCount) {
@@ -39,15 +39,18 @@ export function buildDashboardStats(digest, state, storedMergedCount, storedClos
39
39
  * dormant-auto-shelve rule applies (dormant + not needing attention). Mirrors
40
40
  * the partition built in fetchDashboardData (see the `freshShelved` filter).
41
41
  *
42
- * #1352: an explicitly shelved PR that turns critical is NOT shelved for
43
- * display — the daily check auto-unshelves it (`CRITICAL_STATUSES`), so the
44
- * dashboard must agree immediately rather than diverging from the CLI's
45
- * headline count until the next daily run.
42
+ * #1352: an explicitly shelved PR the daily check would auto-unshelve
43
+ * (`shouldAutoUnshelve`: it needs addressing and a maintainer acted after the
44
+ * shelve or the action reason is new, #1922) is NOT shelved for display, so the dashboard agrees
45
+ * immediately rather than diverging from the CLI's headline count until the
46
+ * next daily run.
46
47
  */
47
- function isShelvedForDisplay(pr, explicitlyShelved) {
48
- if (CRITICAL_STATUSES.has(pr.status))
49
- return false;
50
- return explicitlyShelved.has(pr.url) || pr.stalenessTier === 'dormant';
48
+ function isShelvedForDisplay(pr, config) {
49
+ const key = issueRefKey(pr.url);
50
+ const isExplicit = (config.shelvedPRUrls || []).some((url) => (key ? issueRefKey(url) === key : url === pr.url));
51
+ if (isExplicit)
52
+ return !shouldAutoUnshelve(pr, config.shelvedPRInfo);
53
+ return pr.stalenessTier === 'dormant' && !CRITICAL_STATUSES.has(pr.status);
51
54
  }
52
55
  /**
53
56
  * Re-derive `digest.shelvedPRs` and `summary.totalActivePRs` from the CURRENT
@@ -68,17 +71,16 @@ function isShelvedForDisplay(pr, explicitlyShelved) {
68
71
  export function reconcileShelvePartition(digest, state) {
69
72
  const openPRs = (digest.openPRs || []);
70
73
  const openByUrl = new Map(openPRs.map((pr) => [pr.url, pr]));
71
- const explicitlyShelved = new Set(state.config.shelvedPRUrls || []);
72
74
  // Keep baked entries that are either off the open-PR list (daily dormant
73
75
  // partition we can't recompute here) or still shelved under current state.
74
76
  const reconciled = (digest.shelvedPRs || []).filter((ref) => {
75
77
  const pr = openByUrl.get(ref.url);
76
- return !pr || isShelvedForDisplay(pr, explicitlyShelved);
78
+ return !pr || isShelvedForDisplay(pr, state.config);
77
79
  });
78
80
  // Add open PRs that became shelved but aren't represented in the baked list yet.
79
81
  const present = new Set(reconciled.map((ref) => ref.url));
80
82
  for (const pr of openPRs) {
81
- if (!present.has(pr.url) && isShelvedForDisplay(pr, explicitlyShelved)) {
83
+ if (!present.has(pr.url) && isShelvedForDisplay(pr, state.config)) {
82
84
  reconciled.push(toShelvedPRRef(pr));
83
85
  }
84
86
  }
@@ -171,16 +173,32 @@ export function updateMonthlyAnalytics(prs, monthlyCounts, monthlyClosedCounts,
171
173
  * time that does not parse, issues past the comment-fetch cap) collapse to
172
174
  * one label: the monitor already logged each one, and the banner lists
173
175
  * operations. Engaged issues whose batched lookup failed were not checked
174
- * at all this run, so they get their own label.
176
+ * at all this run, so they get their own label, and so does a comment
177
+ * search that returned a partial list (#1928).
175
178
  */
176
179
  function engagedScanLabels(result) {
177
180
  const labels = [];
178
181
  if (result.lookupFailures > 0)
179
182
  labels.push('look up engaged issues');
180
- if (result.warnings.length > 0)
183
+ // A partial comment search is named on its own (#1928); its sentence is one of `warnings`.
184
+ const { searchTruncation } = result;
185
+ if (searchTruncation !== undefined)
186
+ labels.push(searchTruncation);
187
+ if (result.warnings.length > (searchTruncation === undefined ? 0 : 1))
181
188
  labels.push('scan engaged issues');
182
189
  return labels;
183
190
  }
191
+ /**
192
+ * The rows of a ledger gap fetch (#1924). A truncated fetch has none and
193
+ * puts `truncatedMessage` on the partial-data banner.
194
+ */
195
+ function gapRows(gap, truncatedMessage, partialFailures) {
196
+ if (gap.truncated) {
197
+ partialFailures.push(truncatedMessage);
198
+ warn(MODULE, truncatedMessage);
199
+ }
200
+ return gap.prs;
201
+ }
184
202
  /**
185
203
  * Fetch fresh dashboard data from GitHub.
186
204
  * Returns the digest and commented issues, updating state as a side effect.
@@ -204,16 +222,16 @@ export async function fetchDashboardData(token) {
204
222
  // recovered. When the stored detail count is materially below the known
205
223
  // all-time merged count, drop the watermark for a one-shot full backfill
206
224
  // (bounded by the existing pagination cap); once the ledger catches up the
207
- // watermark resumes incremental fetching. Closed PRs are not seeded ahead of
208
- // their backfill in practice, so only merged needs the guard.
225
+ // watermark resumes incremental fetching. The closed ledger gets the same
226
+ // guard below (#1925): the daily run no longer seeds it ahead of its gap
227
+ // fetch, but ledgers an older version seeded that way still need to heal.
209
228
  const storedMergedCount = stateManager.getMergedPRs().length;
210
229
  const knownMergedAllTime = stateManager.getState().lastDigest?.summary?.totalMergedAllTime ?? 0;
211
- // A full backfill can only ever return up to fetchMergedPRsSince's pagination
212
- // cap (MAX_PAGINATION_PAGES * 100 = 300). Stop forcing one once the ledger has
213
- // reached that ceiling, so a contributor whose star-filtered all-time count
214
- // legitimately exceeds 300 doesn't trigger a full refetch on every poll.
215
- const MERGED_BACKFILL_CEILING = 300;
216
- const mergedNeedsBackfill = storedMergedCount < knownMergedAllTime && storedMergedCount < MERGED_BACKFILL_CEILING;
230
+ // Stop forcing one once the ledger has 300 entries, so a contributor whose
231
+ // star-filtered all-time count legitimately exceeds the ledger doesn't
232
+ // trigger a full refetch on every poll. Past that, the daily run reports a
233
+ // short ledger and `ledger-backfill` fills it (#1924).
234
+ const mergedNeedsBackfill = storedMergedCount < knownMergedAllTime && storedMergedCount < LEDGER_BACKFILL_CEILING;
217
235
  const mergedFetchSince = mergedNeedsBackfill ? undefined : watermark;
218
236
  if (mergedNeedsBackfill) {
219
237
  warn(MODULE, `Merged-PR ledger has ${storedMergedCount} of ~${knownMergedAllTime} known merges; ` +
@@ -233,19 +251,34 @@ export async function fetchDashboardData(token) {
233
251
  return fallback;
234
252
  };
235
253
  };
236
- const [{ prs, failures, warnings: fetchWarnings }, recentlyClosedPRs, recentlyMergedPRs, mergedResult, closedResult, newMergedPRs, newClosedPRs,] = await Promise.all([
254
+ const recentListTruncations = [];
255
+ const closedCounts = prMonitor
256
+ .fetchUserClosedPRCounts(starFilter)
257
+ .catch(trackingCatch('fetch closed PR counts', emptyPRCountsResult()));
258
+ const storedClosedCount = stateManager.getClosedPRs().length;
259
+ const [{ prs, failures, warnings: fetchWarnings }, recentlyClosedPRs, recentlyMergedPRs, mergedResult, closedResult, mergedGap, closedGap,] = await Promise.all([
237
260
  prMonitor.fetchUserOpenPRs(),
238
- prMonitor.fetchRecentlyClosedPRs().catch(trackingCatch('fetch recently closed PRs', [])),
239
- prMonitor.fetchRecentlyMergedPRs().catch(trackingCatch('fetch recently merged PRs', [])),
261
+ prMonitor
262
+ .fetchRecentlyClosedPRs(7, recentListTruncations)
263
+ .catch(trackingCatch('fetch recently closed PRs', [])),
264
+ prMonitor
265
+ .fetchRecentlyMergedPRs(7, recentListTruncations)
266
+ .catch(trackingCatch('fetch recently merged PRs', [])),
240
267
  prMonitor
241
268
  .fetchUserMergedPRCounts(starFilter)
242
269
  .catch(trackingCatch('fetch merged PR counts', emptyPRCountsResult())),
243
- prMonitor
244
- .fetchUserClosedPRCounts(starFilter)
245
- .catch(trackingCatch('fetch closed PR counts', emptyPRCountsResult())),
246
- fetchMergedPRsSince(octokit, config, mergedFetchSince).catch(trackingCatch('fetch merged PRs for storage', [])),
247
- fetchClosedPRsSince(octokit, config, closedWatermark).catch(trackingCatch('fetch closed PRs for storage', [])),
270
+ closedCounts,
271
+ // The same gap fetches the daily run uses (#1924, #1925). Nothing else here
272
+ // adds ledger rows, so a failed or truncated fetch leaves the watermark alone.
273
+ fetchMergedPRsSince(octokit, config, mergedFetchSince).catch(trackingCatch('fetch merged PRs for storage', { prs: [], truncated: false })),
274
+ // Waits for the closed count: a ledger short of it under the ceiling is
275
+ // fetched from the start (gapFetchWatermark, #1925).
276
+ closedCounts
277
+ .then((counts) => fetchClosedPRsSince(octokit, config, gapFetchWatermark(closedWatermark, storedClosedCount, counts.totalCount)))
278
+ .catch(trackingCatch('fetch closed PRs for storage', { prs: [], truncated: false })),
248
279
  ]);
280
+ const newMergedPRs = gapRows(mergedGap, MERGED_LEDGER_TRUNCATED_MESSAGE, partialFailures);
281
+ const newClosedPRs = gapRows(closedGap, CLOSED_LEDGER_TRUNCATED_MESSAGE, partialFailures);
249
282
  // Issue conversations run after the PR lists: the engaged set (#1862)
250
283
  // needs the open, recently closed and recently merged PRs. The fetch has
251
284
  // custom messaging based on the error content, so it keeps its bespoke catch.
@@ -292,6 +325,8 @@ export async function fetchDashboardData(token) {
292
325
  warn(MODULE, message);
293
326
  }
294
327
  }
328
+ // Same for a recent-list truncation (#1928): the short label here, the full sentence already logged.
329
+ partialFailures.push(...recentListTruncations.map((truncation) => truncation.label));
295
330
  // Wrap all state mutations in a batch for a single disk write.
296
331
  // try-catch: save errors should not crash the dashboard data fetch.
297
332
  try {
@@ -357,15 +392,15 @@ export async function fetchDashboardData(token) {
357
392
  const digest = prMonitor.generateDigest(prs, recentlyClosedPRs, recentlyMergedPRs);
358
393
  // Apply shelve partitioning for display (auto-unshelve only runs in daily check).
359
394
  // Dormant PRs are treated as shelved unless they need addressing, and a
360
- // critical PR is never display-shelved (#1352) — mirrors the daily
361
- // check's CRITICAL_STATUSES auto-unshelve so headline counts agree.
395
+ // PR the daily check would auto-unshelve is never display-shelved
396
+ // (#1352, #1922) so headline counts agree.
362
397
  // Partitioned over overriddenPRs (#1416): the shelve decision must use
363
398
  // the same post-override status the CLI partitions on.
364
- const shelvedUrls = new Set(stateManager.getState().config.shelvedPRUrls || []);
399
+ const shelveConfig = stateManager.getState().config;
365
400
  // Single copy of the shelve predicate (#1421): isShelvedForDisplay is
366
401
  // the same rule reconcileShelvePartition applies on rebuilds, so its
367
402
  // regression tests now guard this line too.
368
- const freshShelved = overriddenPRs.filter((pr) => isShelvedForDisplay(pr, shelvedUrls));
403
+ const freshShelved = overriddenPRs.filter((pr) => isShelvedForDisplay(pr, shelveConfig));
369
404
  digest.shelvedPRs = freshShelved.map(toShelvedPRRef);
370
405
  digest.autoUnshelvedPRs = [];
371
406
  digest.summary.totalActivePRs = overriddenPRs.length - freshShelved.length;
@@ -196,7 +196,9 @@ export class GistSyncCoordinator {
196
196
  async maybeRecoverGist() {
197
197
  // One probe covers both degraded shapes — health.degraded is non-null
198
198
  // for configured-but-local AND bootstrap-degraded (#1444).
199
- if (this.probeGistHealth()?.degraded == null)
199
+ const degraded = this.probeGistHealth()?.degraded;
200
+ // An unknown mode (#2005) is not recoverable by re-running init.
201
+ if (degraded == null || !degraded.recoverable)
200
202
  return;
201
203
  if (this.recoveryHaltedReason !== null)
202
204
  return;
@@ -126,7 +126,7 @@ export async function launchDashboardServer(options) {
126
126
  }
127
127
  const info = readDashboardServerInfo();
128
128
  // PID file appeared — verify the server is responding
129
- if (info && (await isDashboardServerRunning(info.port))) {
129
+ if (info && (await isDashboardServerRunning(info.port, info.pid))) {
130
130
  return { url: `http://oss.localhost:${info.port}`, port: info.port, alreadyRunning: false };
131
131
  }
132
132
  }
@@ -20,7 +20,20 @@ export declare function readDashboardServerInfo(): DashboardServerInfo | null;
20
20
  */
21
21
  export declare function recordBrowserOpened(port: number): void;
22
22
  export declare function removeDashboardServerInfo(): void;
23
- export declare function isDashboardServerRunning(port: number): Promise<boolean>;
23
+ /**
24
+ * Remove the PID file only when it records this process. A server that lost
25
+ * the file to a newer server (it was probed as dead, then replaced) must not
26
+ * delete the replacement's PID file on its own shutdown (#1927).
27
+ */
28
+ export declare function removeOwnDashboardServerInfo(): void;
29
+ /**
30
+ * Probe GET /api/health, which sits outside the rate limiters and reloads no
31
+ * state: the old probe of /api/data read a busy or throttled server as dead
32
+ * (#1927). The server counts as ours only when the reply names the PID the
33
+ * PID file records, so another program listening on the port (or a recycled
34
+ * PID) never passes as the dashboard.
35
+ */
36
+ export declare function isDashboardServerRunning(port: number, pid: number): Promise<boolean>;
24
37
  export declare function findRunningDashboardServer(): Promise<{
25
38
  port: number;
26
39
  url: string;
@@ -70,13 +70,50 @@ export function removeDashboardServerInfo() {
70
70
  }
71
71
  }
72
72
  }
73
+ /**
74
+ * Remove the PID file only when it records this process. A server that lost
75
+ * the file to a newer server (it was probed as dead, then replaced) must not
76
+ * delete the replacement's PID file on its own shutdown (#1927).
77
+ */
78
+ export function removeOwnDashboardServerInfo() {
79
+ if (readDashboardServerInfo()?.pid === process.pid)
80
+ removeDashboardServerInfo();
81
+ }
73
82
  // ── Health Probe ───────────────────────────────────────────────────────────────
74
- export function isDashboardServerRunning(port) {
83
+ /** Our health reply is a few dozen bytes; anything larger is another program. */
84
+ const MAX_HEALTH_BODY_LENGTH = 1024;
85
+ /** The `pid` field of a health reply, or undefined when the body is not ours. */
86
+ function parseHealthPid(body) {
87
+ let parsed;
88
+ try {
89
+ parsed = JSON.parse(body);
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ return parsed?.pid;
95
+ }
96
+ /**
97
+ * Probe GET /api/health, which sits outside the rate limiters and reloads no
98
+ * state: the old probe of /api/data read a busy or throttled server as dead
99
+ * (#1927). The server counts as ours only when the reply names the PID the
100
+ * PID file records, so another program listening on the port (or a recycled
101
+ * PID) never passes as the dashboard.
102
+ */
103
+ export function isDashboardServerRunning(port, pid) {
75
104
  return new Promise((resolve) => {
76
- const req = http.get(`http://127.0.0.1:${port}/api/data`, { timeout: 2000 }, (res) => {
77
- // Consume response data to free up memory
78
- res.resume();
79
- resolve(res.statusCode === 200);
105
+ const req = http.get(`http://127.0.0.1:${port}/api/health`, { timeout: 2000 }, (res) => {
106
+ let body = '';
107
+ res.setEncoding('utf8');
108
+ res.on('data', (chunk) => {
109
+ body += chunk;
110
+ if (body.length > MAX_HEALTH_BODY_LENGTH) {
111
+ resolve(false);
112
+ req.destroy();
113
+ }
114
+ });
115
+ res.on('end', () => resolve(parseHealthPid(body) === pid));
116
+ res.on('error', () => resolve(false));
80
117
  });
81
118
  req.on('error', () => resolve(false));
82
119
  req.on('timeout', () => {
@@ -104,10 +141,12 @@ export async function findRunningDashboardServer() {
104
141
  return null;
105
142
  }
106
143
  // Process exists — verify it's actually our server via HTTP probe
107
- if (await isDashboardServerRunning(info.port)) {
144
+ if (await isDashboardServerRunning(info.port, info.pid)) {
108
145
  return { port: info.port, url: `http://oss.localhost:${info.port}` };
109
146
  }
110
- // Process exists but not responding on expected port — stale
147
+ // Process exists but is not answering as our server on the expected port:
148
+ // stale. Never signal it. The PID file outlives crashes and reboots, so the
149
+ // PID may have been recycled to an unrelated process (#1927).
111
150
  removeDashboardServerInfo();
112
151
  return null;
113
152
  }
@@ -15,15 +15,15 @@ import * as fs from 'node:fs';
15
15
  import * as path from 'node:path';
16
16
  import * as crypto from 'node:crypto';
17
17
  import { getGitHubToken, getCLIVersion } from '../core/index.js';
18
- import { errorMessage, ValidationError, ConcurrencyError, GistConcurrencyError } from '../core/errors.js';
18
+ import { errorMessage, ValidationError, ConcurrencyError, GistConcurrencyError, StateLockTimeoutError, ConfigurationError, } from '../core/errors.js';
19
19
  import { warn } from '../core/logger.js';
20
20
  import { validateUrl, validateGitHubUrl, PR_URL_PATTERN, ISSUE_URL_PATTERN } from './validation.js';
21
21
  import { fetchDashboardData } from './dashboard-data.js';
22
22
  import { openInBrowser } from './startup.js';
23
- import { writeDashboardServerInfo, removeDashboardServerInfo } from './dashboard-process.js';
23
+ import { writeDashboardServerInfo, removeOwnDashboardServerInfo } from './dashboard-process.js';
24
24
  import { RateLimiter } from './rate-limiter.js';
25
25
  import { GistSyncCoordinator } from './dashboard-gist-sync.js';
26
- import { DashboardCache, getIssueListMtimeMs } from './dashboard-cache.js';
26
+ import { DashboardCache, clearForeignVerdicts, getIssueListMtimeMs } from './dashboard-cache.js';
27
27
  // Re-export the payload builder for backward compatibility — it moved to
28
28
  // dashboard-cache.ts with the cache extraction (#1457) but is unit-tested
29
29
  // (and consumed) under this module's name.
@@ -174,8 +174,33 @@ function sanitizeHeaderValue(value) {
174
174
  * save. See state-concurrency.test.ts (#1378) and errors.ts.
175
175
  */
176
176
  function isConcurrencyConflict(error) {
177
+ if (error instanceof StateLockTimeoutError)
178
+ return false; // a reload cannot help: see didSendStateError
177
179
  return error instanceof ConcurrencyError || error instanceof GistConcurrencyError;
178
180
  }
181
+ /**
182
+ * Answer a state error whose message the user has to see (#1951), and report
183
+ * whether it did. Neither is retried by the page (it retries 409 only), and
184
+ * each message says what to do:
185
+ * - a state-lock timeout (423): the lock is held by another process, so a
186
+ * reload-and-retry cannot help and only blocks the event loop again;
187
+ * - a ConfigurationError (500), e.g. state written by a newer release: a
188
+ * generic "Internal server error" would leave the real message in the
189
+ * detached server's log.
190
+ */
191
+ function didSendStateError(res, error) {
192
+ if (res.headersSent)
193
+ return false;
194
+ if (error instanceof StateLockTimeoutError) {
195
+ sendJson(res, 423, { error: error.message, code: 'STATE_LOCKED', retryable: false });
196
+ return true;
197
+ }
198
+ if (error instanceof ConfigurationError) {
199
+ sendJson(res, 500, { error: error.message, code: error.code, retryable: false });
200
+ return true;
201
+ }
202
+ return false;
203
+ }
179
204
  /**
180
205
  * Send the machine-readable 409 for a concurrency conflict (#1397).
181
206
  * `retryable: true` tells the SPA it can re-prime via GET /api/data and
@@ -239,6 +264,14 @@ export async function startDashboardServer(options) {
239
264
  return;
240
265
  }
241
266
  // ── API routes ─────────────────────────────────────────────────────
267
+ // Liveness probe for isDashboardServerRunning (#1927). Deliberately
268
+ // outside the rate limiters and free of state reloads so a busy or
269
+ // throttled server still answers. The pid lets the prober tell this
270
+ // server from another program listening on the same port.
271
+ if (url === '/api/health' && method === 'GET') {
272
+ sendJson(res, 200, { ok: true, pid: process.pid });
273
+ return;
274
+ }
242
275
  if (url === '/api/data' && method === 'GET') {
243
276
  const check = dataLimiter.check();
244
277
  if (!check.allowed) {
@@ -262,6 +295,8 @@ export async function startDashboardServer(options) {
262
295
  const currentIssueListMtimeMs = getIssueListMtimeMs();
263
296
  const issueListChanged = currentIssueListMtimeMs !== cache.issueListMtimeMs;
264
297
  if (stateChanged || issueListChanged) {
298
+ // Re-check the list's checkout on the same events that rebuild (#2012).
299
+ clearForeignVerdicts();
265
300
  try {
266
301
  cache.rebuild(gistSync.stateManager.getState(), undefined, undefined, currentIssueListMtimeMs);
267
302
  }
@@ -327,6 +362,8 @@ export async function startDashboardServer(options) {
327
362
  }
328
363
  catch (error) {
329
364
  warn(MODULE, `Unhandled request error: ${method} ${url} ${errorMessage(error)}`);
365
+ if (didSendStateError(res, error))
366
+ return;
330
367
  if (!res.headersSent) {
331
368
  sendError(res, 500, 'Internal server error');
332
369
  }
@@ -486,6 +523,8 @@ export async function startDashboardServer(options) {
486
523
  await sm.runMutation(async () => applyMutation());
487
524
  }
488
525
  catch (error) {
526
+ if (didSendStateError(res, error))
527
+ return;
489
528
  if (!isConcurrencyConflict(error)) {
490
529
  warn(MODULE, `Action failed: ${body.action} ${body.url} ${errorMessage(error)}`);
491
530
  sendError(res, 500, 'Action failed');
@@ -507,6 +546,8 @@ export async function startDashboardServer(options) {
507
546
  await sm.runMutation(async () => applyMutation());
508
547
  }
509
548
  catch (retryError) {
549
+ if (didSendStateError(res, retryError))
550
+ return;
510
551
  if (isConcurrencyConflict(retryError)) {
511
552
  warn(MODULE, `Action conflicted twice: ${body.action} ${body.url} ${errorMessage(retryError)}`);
512
553
  sendConflict(res);
@@ -538,31 +579,54 @@ export async function startDashboardServer(options) {
538
579
  sendJson(res, 200, cache.jsonData);
539
580
  }
540
581
  // ── POST /api/refresh handler ────────────────────────────────────────────
541
- async function handleRefresh(_req, res) {
582
+ async function refreshFromGitHub(currentToken) {
583
+ // Clear PRE-EXISTING loss notices before the reload: by now they have
584
+ // been visible across the degraded window. Order matters — this
585
+ // refresh's own reloadState may RECOVER and produce a fresh notice,
586
+ // which must survive into the rebuild below, not be wiped 10 lines
587
+ // after its creation (#1433 pass-2).
588
+ gistSync.clearRecoveryLossNotices();
589
+ await reloadState();
590
+ warn(MODULE, 'Refreshing dashboard data from GitHub...');
591
+ const result = await fetchDashboardData(currentToken);
592
+ cache.adoptFetchResult(result);
593
+ cache.rebuild(gistSync.stateManager.getState(), result.allMergedPRs, result.allClosedPRs);
594
+ // This refresh just fetched GitHub successfully, so a prior
595
+ // background-refresh failure is no longer current (#1487) — clear it as
596
+ // the background success path does.
597
+ cache.lastBackgroundRefreshError = null;
598
+ }
599
+ /** Run a refresh nobody awaits; a failure surfaces as staleness on /api/data (#1205). */
600
+ async function refreshInBackground(currentToken) {
601
+ try {
602
+ await refreshFromGitHub(currentToken);
603
+ }
604
+ catch (error) {
605
+ cache.lastBackgroundRefreshError = errorMessage(error);
606
+ warn(MODULE, `Background data refresh failed (serving cached data): ${cache.lastBackgroundRefreshError}`);
607
+ }
608
+ }
609
+ async function handleRefresh(req, res) {
542
610
  const currentToken = token || getGitHubToken();
543
611
  if (!currentToken) {
544
612
  sendError(res, 401, 'No GitHub token available. Cannot refresh data.');
545
613
  return;
546
614
  }
615
+ // A caller that does not consume the payload (startup's refresh trigger)
616
+ // asks for `Prefer: respond-async` and gets a 202 at once: the refresh is
617
+ // a full GitHub fetch that outlives any sensible client timeout (#1927).
618
+ // The SPA omits the header because it renders the response body.
619
+ if (req.headers['prefer'] === 'respond-async') {
620
+ void refreshInBackground(currentToken);
621
+ sendJson(res, 202, { refreshing: true });
622
+ return;
623
+ }
547
624
  try {
548
- // Clear PRE-EXISTING loss notices before the reload: by now they have
549
- // been visible across the degraded window. Order matters — this
550
- // refresh's own reloadState may RECOVER and produce a fresh notice,
551
- // which must survive into the rebuild below, not be wiped 10 lines
552
- // after its creation (#1433 pass-2).
553
- gistSync.clearRecoveryLossNotices();
554
- await reloadState();
555
- warn(MODULE, 'Refreshing dashboard data from GitHub...');
556
- const result = await fetchDashboardData(currentToken);
557
- cache.adoptFetchResult(result);
558
- cache.rebuild(gistSync.stateManager.getState(), result.allMergedPRs, result.allClosedPRs);
559
- // This manual refresh just fetched GitHub successfully, so a prior
560
- // background-refresh failure is no longer current (#1487) — clear it as
561
- // the background success path does, then emit the staleness headers. A
562
- // gist-divergence marker that survived a failed pull inside reloadState
563
- // still surfaces via getStateStaleness, so the SPA stays honest even
564
- // when the GitHub fetch succeeds but the gist remains unreachable.
565
- cache.lastBackgroundRefreshError = null;
625
+ await refreshFromGitHub(currentToken);
626
+ // Emit the staleness headers: a gist-divergence marker that survived a
627
+ // failed pull inside reloadState still surfaces via getStateStaleness,
628
+ // so the SPA stays honest even when the GitHub fetch succeeds but the
629
+ // gist remains unreachable.
566
630
  applyStalenessHeaders(res);
567
631
  sendJson(res, 200, cache.jsonData);
568
632
  }
@@ -570,6 +634,8 @@ export async function startDashboardServer(options) {
570
634
  // No server-side retry here (unlike handleAction): a refresh re-run is a
571
635
  // full GitHub fetch — expensive and rate-limited. The 409 is retryable
572
636
  // by the client, which re-POSTs /api/refresh on its own schedule (#1397).
637
+ if (didSendStateError(res, error))
638
+ return;
573
639
  if (isConcurrencyConflict(error)) {
574
640
  warn(MODULE, `Dashboard refresh hit a concurrent state write: ${errorMessage(error)}`);
575
641
  sendConflict(res);
@@ -733,7 +799,7 @@ export async function startDashboardServer(options) {
733
799
  // ── Clean shutdown ───────────────────────────────────────────────────────
734
800
  const shutdown = () => {
735
801
  warn(MODULE, 'Shutting down dashboard server...');
736
- removeDashboardServerInfo();
802
+ removeOwnDashboardServerInfo();
737
803
  server.close(() => {
738
804
  process.exit(0);
739
805
  });
@@ -7,6 +7,7 @@ import * as fs from 'node:fs';
7
7
  import * as path from 'node:path';
8
8
  import { detectFormatters, diagnoseCIFormatterFailure } from '../core/formatter-detection.js';
9
9
  import { errorMessage } from '../core/errors.js';
10
+ // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
10
11
  export async function runDetectFormatters(options) {
11
12
  const repoPath = path.resolve(options.repoPath ?? process.cwd());
12
13
  const output = { ...detectFormatters(repoPath) };
@@ -20,6 +20,7 @@
20
20
  */
21
21
  import { getStateManager, maybeCheckpoint } from '../core/index.js';
22
22
  import { ValidationError } from '../core/errors.js';
23
+ import { findRefKey } from '../core/urls.js';
23
24
  import { ISSUE_OR_PR_URL_PATTERN, PR_URL_PATTERN, validateCommitSha, validateGitHubUrl, validateUrl, } from './validation.js';
24
25
  const MODULE = 'dismiss';
25
26
  /**
@@ -66,11 +67,13 @@ function openPRDismissWarning(stateManager, url) {
66
67
  export async function runDismiss(options) {
67
68
  validateUrl(options.url);
68
69
  validateGitHubUrl(options.url, ISSUE_OR_PR_URL_PATTERN, 'issue or PR');
69
- const isPR = PR_URL_PATTERN.test(options.url);
70
+ const stateManager = getStateManager();
71
+ // The /issues/N form of a PR already dismissed as /pull/N is that PR (#2001).
72
+ const existingKey = findRefKey(stateManager.getState().config?.dismissedIssues, options.url);
73
+ const isPR = PR_URL_PATTERN.test(options.url) || (existingKey !== undefined && PR_URL_PATTERN.test(existingKey));
70
74
  if (!isPR && options.head !== undefined) {
71
75
  throw new ValidationError('--head applies to PR URLs only: a dismissed issue has no head commit');
72
76
  }
73
- const stateManager = getStateManager();
74
77
  const dismissedAt = new Date().toISOString();
75
78
  const dismissOptions = {
76
79
  refresh: isPR,
@@ -44,6 +44,20 @@ export declare function checkStateFile(options?: {
44
44
  * stub without mocking the module registry.
45
45
  */
46
46
  export type ScoutImporter = () => Promise<unknown>;
47
- export declare function checkScoutResolvable(importer?: ScoutImporter): Promise<DoctorCheck>;
47
+ export declare function checkScoutResolvable(importer?: ScoutImporter, options?: {
48
+ sourceCheckout?: boolean;
49
+ }): Promise<DoctorCheck>;
48
50
  export declare function checkGitHubRateLimit(preloadedToken?: string | null): Promise<DoctorCheck>;
51
+ /**
52
+ * Stale data under the data directory (#1956): counts only, from the file
53
+ * system; no Git runs here. Which worktrees are safe to remove, and why the
54
+ * others are kept, is what `cleanup` reports.
55
+ */
56
+ export declare function checkStaleData(dataDir?: string): DoctorCheck;
57
+ /**
58
+ * The overnight launchd job carries the tool rules and environment of the
59
+ * version that installed it (#1937): an upgrade that tightens them changes
60
+ * nothing for a schedule already on disk until it is installed again.
61
+ */
62
+ export declare function checkOvernightSchedule(plistPath?: string): DoctorCheck;
49
63
  export declare function runDoctor(): Promise<DoctorOutput>;