@oss-autopilot/core 3.43.0 → 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 (100) hide show
  1. package/dist/cli-registry.js +160 -6
  2. package/dist/cli.bundle.cjs +207 -180
  3. package/dist/commands/check-integration.js +4 -1
  4. package/dist/commands/cleanup.d.ts +6 -2
  5. package/dist/commands/cleanup.js +72 -7
  6. package/dist/commands/comments.d.ts +8 -1
  7. package/dist/commands/comments.js +11 -3
  8. package/dist/commands/config.d.ts +2 -0
  9. package/dist/commands/config.js +26 -1
  10. package/dist/commands/daily-ledger.d.ts +33 -5
  11. package/dist/commands/daily-ledger.js +36 -13
  12. package/dist/commands/daily-render.d.ts +2 -1
  13. package/dist/commands/daily-render.js +4 -1
  14. package/dist/commands/daily.d.ts +3 -0
  15. package/dist/commands/daily.js +25 -5
  16. package/dist/commands/dashboard-data.js +70 -61
  17. package/dist/commands/dashboard-lifecycle.d.ts +36 -8
  18. package/dist/commands/dashboard-lifecycle.js +131 -38
  19. package/dist/commands/dashboard-process.d.ts +35 -0
  20. package/dist/commands/dashboard-process.js +65 -5
  21. package/dist/commands/dismiss.js +7 -6
  22. package/dist/commands/doctor.js +1 -8
  23. package/dist/commands/fork-prune.d.ts +58 -0
  24. package/dist/commands/fork-prune.js +247 -0
  25. package/dist/commands/guidelines.d.ts +46 -1
  26. package/dist/commands/guidelines.js +111 -12
  27. package/dist/commands/index.d.ts +5 -0
  28. package/dist/commands/index.js +5 -0
  29. package/dist/commands/overnight-push-prep.d.ts +2 -1
  30. package/dist/commands/overnight-push-prep.js +3 -3
  31. package/dist/commands/policy.d.ts +5 -1
  32. package/dist/commands/policy.js +14 -1
  33. package/dist/commands/pr-create.d.ts +48 -0
  34. package/dist/commands/pr-create.js +200 -0
  35. package/dist/commands/pr-preflight.d.ts +28 -2
  36. package/dist/commands/pr-preflight.js +63 -9
  37. package/dist/commands/setup.js +120 -36
  38. package/dist/commands/startup.d.ts +7 -0
  39. package/dist/commands/startup.js +17 -0
  40. package/dist/commands/status.js +5 -0
  41. package/dist/commands/validation.d.ts +5 -0
  42. package/dist/commands/validation.js +5 -0
  43. package/dist/commands/vet-list.js +2 -2
  44. package/dist/commands/vet.d.ts +8 -0
  45. package/dist/commands/vet.js +15 -1
  46. package/dist/commands/work.d.ts +4 -0
  47. package/dist/commands/work.js +34 -11
  48. package/dist/core/commit-date.d.ts +31 -5
  49. package/dist/core/commit-date.js +36 -8
  50. package/dist/core/compliance-score.d.ts +3 -0
  51. package/dist/core/compliance-score.js +13 -9
  52. package/dist/core/config-registry.d.ts +27 -2
  53. package/dist/core/config-registry.js +83 -2
  54. package/dist/core/daily-logic.d.ts +4 -1
  55. package/dist/core/daily-logic.js +13 -2
  56. package/dist/core/fork-prune.d.ts +149 -0
  57. package/dist/core/fork-prune.js +333 -0
  58. package/dist/core/gist-state-store.js +4 -8
  59. package/dist/core/github-stats.d.ts +7 -1
  60. package/dist/core/github-stats.js +15 -15
  61. package/dist/core/index.d.ts +1 -1
  62. package/dist/core/index.js +1 -1
  63. package/dist/core/local-config.js +2 -3
  64. package/dist/core/pacing.d.ts +41 -0
  65. package/dist/core/pacing.js +115 -0
  66. package/dist/core/pr-assembly.d.ts +2 -0
  67. package/dist/core/pr-graphql.d.ts +16 -1
  68. package/dist/core/pr-graphql.js +15 -3
  69. package/dist/core/pr-monitor.d.ts +6 -0
  70. package/dist/core/pr-monitor.js +46 -10
  71. package/dist/core/pr-preflight.d.ts +41 -0
  72. package/dist/core/pr-preflight.js +406 -17
  73. package/dist/core/prose-script.d.ts +72 -0
  74. package/dist/core/prose-script.js +223 -0
  75. package/dist/core/repo-policy.d.ts +8 -2
  76. package/dist/core/repo-policy.js +34 -6
  77. package/dist/core/repo-score-manager.d.ts +18 -0
  78. package/dist/core/repo-score-manager.js +29 -0
  79. package/dist/core/review-analysis.d.ts +15 -2
  80. package/dist/core/review-analysis.js +22 -5
  81. package/dist/core/stale-data.d.ts +44 -7
  82. package/dist/core/stale-data.js +46 -8
  83. package/dist/core/state-persistence.js +2 -4
  84. package/dist/core/state-schema.d.ts +39 -0
  85. package/dist/core/state-schema.js +68 -1
  86. package/dist/core/state.d.ts +21 -0
  87. package/dist/core/state.js +47 -0
  88. package/dist/core/status-determination.js +10 -8
  89. package/dist/core/untrusted-content.d.ts +3 -3
  90. package/dist/core/untrusted-content.js +26 -8
  91. package/dist/core/urls.d.ts +24 -0
  92. package/dist/core/urls.js +76 -0
  93. package/dist/dashboard/assets/chart-panel-B-nLVgzQ.js +3 -0
  94. package/dist/dashboard/assets/index-5IvMGokL.js +55 -0
  95. package/dist/dashboard/index.html +1 -1
  96. package/dist/formatters/json.d.ts +171 -5
  97. package/dist/formatters/json.js +79 -0
  98. package/package.json +6 -6
  99. package/dist/dashboard/assets/chart-panel-C_C1lFTI.js +0 -3
  100. package/dist/dashboard/assets/index-B--H66Jk.js +0 -55
@@ -16,8 +16,10 @@ import { emptyPRCountsResult } from '../core/github-stats.js';
16
16
  import { updateMonthlyAnalytics } from './dashboard-data.js';
17
17
  import { deduplicateDigest, compactActionableIssues, compactRepoGroups, buildStalenessWarning, } from '../formatters/json.js';
18
18
  import { reconcileMergedPRsWithList } from './merge-loop.js';
19
+ import { guidelineProposalStatus, isProposalRepo } from './guidelines.js';
19
20
  import { describeError, httpStatusLabel, isGoneError, nonFatalCatchWithWarning, recordWarning, } from './daily-warnings.js';
20
21
  import { formatBriefSummary, formatSummary } from './daily-render.js';
22
+ import { getPacingStatus } from '../core/pacing.js';
21
23
  import { fenceMergedPRNotes, runMergedPRNotesPhase } from './daily-merged-pr-notes.js';
22
24
  import { fetchRecentPRLists } from './daily-recent-prs.js';
23
25
  import { fenceReviewedPR, runReviewedPRsPhase } from './daily-reviewed-prs.js';
@@ -33,6 +35,7 @@ export { formatBriefSummary, formatSummary, printDigest } from './daily-render.j
33
35
  // (#1208 M7). Re-exported here for backward compatibility with anyone
34
36
  // importing from this module.
35
37
  import { buildStarFilter } from '../core/daily-logic.js';
38
+ import { cachedForkPruneLine } from './fork-prune.js';
36
39
  /** Lowercased `owner/repo` of a GitHub PR or issue URL, or undefined when it does not parse. */
37
40
  function repoKeyOf(url) {
38
41
  const parsed = parseGitHubUrl(url);
@@ -212,6 +215,9 @@ async function updateRepoScores(prMonitor, prs, mergedCounts, truncatedSearches,
212
215
  // Outer try-catch: save failure should not crash the daily check (in-memory mutations still apply).
213
216
  try {
214
217
  batchOnFreshBaseline(stateManager, () => {
218
+ // Counts below are written in steps (reset or search count, then the
219
+ // ledger raise); only the net change re-evaluates a repo (#2045).
220
+ const outcomesBefore = stateManager.snapshotRepoOutcomes();
215
221
  // Re-key transferred repos and evict reopened/merged PRs from the closed
216
222
  // ledger before anything below reads or writes repoScores (#1923).
217
223
  syncLedgersWithGitHub(stateManager, searchedPRs, prs);
@@ -316,6 +322,7 @@ async function updateRepoScores(prMonitor, prs, mergedCounts, truncatedSearches,
316
322
  });
317
323
  warn(MODULE, `[SIGNAL_UPDATES_FAILED] ${signalUpdateFailures} of ${repoSignals.size} signal update(s) failed. This may indicate corrupted state.`);
318
324
  }
325
+ stateManager.restoreUnchangedEvaluations(outcomesBefore);
319
326
  });
320
327
  }
321
328
  catch (error) {
@@ -488,7 +495,12 @@ function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, fa
488
495
  // Filter dismissed issues: suppress if dismissed after last response, resurface + auto-undismiss if new activity.
489
496
  const filteredCommentedIssues = filterDismissedIssues(stateManager, remainingCommentedIssues, warnings);
490
497
  const issueResponses = filteredCommentedIssues.filter((i) => i.status === 'new_response');
491
- const summary = formatSummary(digest, capacity, issueResponses);
498
+ // Counted over this run's digest, which may not be saved to state yet (#1911).
499
+ const pacing = getPacingStatus({ ...stateManager.getState(), lastDigest: digest });
500
+ // The fork line reads the last fork-prune dry run's cached count: daily makes no fork scan (#1912).
501
+ const forkPruneLine = cachedForkPruneLine();
502
+ const baseSummary = formatSummary(digest, capacity, issueResponses, pacing);
503
+ const summary = forkPruneLine ? `${baseSummary}\n${forkPruneLine}\n` : baseSummary;
492
504
  // Auto-undismiss mutations are auto-saved by undismissIssue()
493
505
  const actionableIssues = collectActionableIssues(activePRs, previousLastDigestAt);
494
506
  digest.summary.totalNeedingAttention = actionableIssues.length;
@@ -541,6 +553,7 @@ function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, fa
541
553
  warnings,
542
554
  strategySummary,
543
555
  ...(workClaims.length > 0 && { workClaims }),
556
+ ...(pacing && { pacing }),
544
557
  };
545
558
  }
546
559
  const CLOSED_PR_STATUS_OPERATION = 'closed-PR status updates';
@@ -770,6 +783,7 @@ export function toDailyOutput(result) {
770
783
  ...(result.mergedPRNotes && { mergedPRNotes: result.mergedPRNotes.map((entry) => fenceMergedPRNotes(entry)) }),
771
784
  ...(result.reviewedPRs && { reviewedPRs: result.reviewedPRs.map((entry) => fenceReviewedPR(entry)) }),
772
785
  ...(result.workClaims && { workClaims: result.workClaims }),
786
+ ...(result.pacing && { pacing: result.pacing }),
773
787
  };
774
788
  }
775
789
  /**
@@ -839,7 +853,7 @@ async function executeDailyCheckInternal(token) {
839
853
  await updateRepoScores(prMonitor, prs, mergedCounts, truncatedSearches, closedCounts, searchedPRs, warnings);
840
854
  // Merges and closes since each ledger's newest entry, fetched before Phase 3 adds to it (#1924, #1925).
841
855
  const [mergedGap, closedGap] = await Promise.all([
842
- fetchMergedLedgerGap(getOctokit(token), getStateManager(), warnings),
856
+ fetchMergedLedgerGap(getOctokit(token), getStateManager(), warnings, mergedTotalCount),
843
857
  fetchClosedLedgerGap(getOctokit(token), getStateManager(), warnings, closedTotalCount),
844
858
  ]);
845
859
  // Phase 3: Persist monthly analytics and store merged/closed PR history.
@@ -909,13 +923,19 @@ async function executeDailyCheckInternal(token) {
909
923
  if (unextractedMergeCount > 0 && sm.getState().config.autoExtractLearnings) {
910
924
  unextractedMergeCount = 0;
911
925
  if (sm.isGistMode()) {
912
- const repos = new Set();
926
+ const repoSet = new Set();
913
927
  for (const pr of unextracted) {
914
928
  const parsed = parseGitHubUrl(pr.url);
915
929
  if (parsed)
916
- repos.add(`${parsed.owner}/${parsed.repo}`);
930
+ repoSet.add(`${parsed.owner}/${parsed.repo}`);
917
931
  }
918
- pendingLearnings = { repos: [...repos].sort(), prCount: unextracted.length };
932
+ const repos = [...repoSet].sort();
933
+ // Proposal state per repo (#2041): the host neither builds paths nor re-extracts.
934
+ const prsOf = (repo) => unextracted.filter((pr) => pr.url.startsWith(`https://github.com/${repo}/`));
935
+ const proposals = repos
936
+ .filter((repo) => isProposalRepo(repo))
937
+ .map((repo) => guidelineProposalStatus(repo, prsOf(repo)));
938
+ pendingLearnings = { repos, proposals, prCount: unextracted.length };
919
939
  }
920
940
  else {
921
941
  warnings.push({
@@ -3,12 +3,13 @@
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, shouldAutoUnshelve, applyStatusOverrides, collectEngagedIssues, toShelvedPRRef, buildStarFilter, firstMaintainerResponseFromDigest, lastReviewStateFromDigest, } from '../core/index.js';
6
+ import { getStateManager, PRMonitor, IssueConversationMonitor, getOctokit, CRITICAL_STATUSES, shouldAutoUnshelve, applyStatusOverrides, collectEngagedIssues, toShelvedPRRef, buildStarFilter, } 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, gapFetchWatermark, LEDGER_BACKFILL_CEILING, CLOSED_LEDGER_TRUNCATED_MESSAGE, MERGED_LEDGER_TRUNCATED_MESSAGE, } from '../core/github-stats.js';
9
+ import { emptyPRCountsResult, CLOSED_LEDGER_TRUNCATED_MESSAGE, MERGED_LEDGER_TRUNCATED_MESSAGE, } from '../core/github-stats.js';
10
10
  import { parseGitHubUrl, issueRefKey } from '../core/urls.js';
11
11
  import { isBelowMinStars, } from '../core/types.js';
12
+ import { evictNeverTrackedRepos, fetchClosedLedgerGap, fetchMergedLedgerGap, storeClosedLedger, storeMergedLedger, syncLedgersWithGitHub, } from './daily-ledger.js';
12
13
  const MODULE = 'dashboard-data';
13
14
  export function buildDashboardStats(digest, state, storedMergedCount, storedClosedCount) {
14
15
  const summary = digest.summary || {
@@ -189,15 +190,18 @@ function engagedScanLabels(result) {
189
190
  return labels;
190
191
  }
191
192
  /**
192
- * The rows of a ledger gap fetch (#1924). A truncated fetch has none and
193
- * puts `truncatedMessage` on the partial-data banner.
193
+ * Name a ledger gap fetch that stored nothing on the partial-data banner
194
+ * (#1924): `failedLabel` when it failed, `truncatedMessage` when it matched
195
+ * more than one refresh fetches.
194
196
  */
195
- function gapRows(gap, truncatedMessage, partialFailures) {
196
- if (gap.truncated) {
197
+ function reportLedgerGap(gap, failedLabel, truncatedMessage, partialFailures) {
198
+ if (!gap) {
199
+ partialFailures.push(failedLabel);
200
+ }
201
+ else if (gap.truncated) {
197
202
  partialFailures.push(truncatedMessage);
198
203
  warn(MODULE, truncatedMessage);
199
204
  }
200
- return gap.prs;
201
205
  }
202
206
  /**
203
207
  * Fetch fresh dashboard data from GitHub.
@@ -209,34 +213,8 @@ export async function fetchDashboardData(token) {
209
213
  const prMonitor = new PRMonitor(token);
210
214
  const issueMonitor = new IssueConversationMonitor(token);
211
215
  const octokit = getOctokit(token);
212
- const config = stateManager.getState().config;
213
216
  // Build star filter from cached repoScores (#576)
214
217
  const starFilter = buildStarFilter(stateManager.getState());
215
- // Get watermarks for incremental PR fetch
216
- const watermark = stateManager.getMergedPRWatermark();
217
- const closedWatermark = stateManager.getClosedPRWatermark();
218
- // Self-heal a ledger stranded behind a recent watermark (#1504). The
219
- // incremental fetch only asks for merges newer than the newest stored one,
220
- // so once the recent-merge feed (daily's recentlyMergedPRs) seeds the ledger
221
- // before any full historical fetch ran, the older history can never be
222
- // recovered. When the stored detail count is materially below the known
223
- // all-time merged count, drop the watermark for a one-shot full backfill
224
- // (bounded by the existing pagination cap); once the ledger catches up the
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.
228
- const storedMergedCount = stateManager.getMergedPRs().length;
229
- const knownMergedAllTime = stateManager.getState().lastDigest?.summary?.totalMergedAllTime ?? 0;
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;
235
- const mergedFetchSince = mergedNeedsBackfill ? undefined : watermark;
236
- if (mergedNeedsBackfill) {
237
- warn(MODULE, `Merged-PR ledger has ${storedMergedCount} of ~${knownMergedAllTime} known merges; ` +
238
- 'running a full backfill (watermark dropped) to recover history (#1504).');
239
- }
240
218
  // Track which non-critical sub-fetches degraded to fallbacks so the SPA
241
219
  // can surface a "partial data" banner instead of silently showing zeros.
242
220
  // Rate-limit / auth errors still rethrow via isRateLimitOrAuthError —
@@ -251,11 +229,19 @@ export async function fetchDashboardData(token) {
251
229
  return fallback;
252
230
  };
253
231
  };
232
+ // The ledger phases daily runs (daily-ledger.ts), so gaps, backfill and
233
+ // eviction follow one rule (#2038). Their warnings stay out of the banner:
234
+ // the gaps are reported from their results below, and the "ledger is
235
+ // short, run ledger-backfill" check is the daily run's to report.
236
+ const ledgerWarnings = [];
237
+ const gapOptions = { rethrowIf: isRateLimitOrAuthError };
254
238
  const recentListTruncations = [];
239
+ const mergedCounts = prMonitor
240
+ .fetchUserMergedPRCounts(starFilter)
241
+ .catch(trackingCatch('fetch merged PR counts', emptyPRCountsResult()));
255
242
  const closedCounts = prMonitor
256
243
  .fetchUserClosedPRCounts(starFilter)
257
244
  .catch(trackingCatch('fetch closed PR counts', emptyPRCountsResult()));
258
- const storedClosedCount = stateManager.getClosedPRs().length;
259
245
  const [{ prs, failures, warnings: fetchWarnings }, recentlyClosedPRs, recentlyMergedPRs, mergedResult, closedResult, mergedGap, closedGap,] = await Promise.all([
260
246
  prMonitor.fetchUserOpenPRs(),
261
247
  prMonitor
@@ -264,21 +250,17 @@ export async function fetchDashboardData(token) {
264
250
  prMonitor
265
251
  .fetchRecentlyMergedPRs(7, recentListTruncations)
266
252
  .catch(trackingCatch('fetch recently merged PRs', [])),
267
- prMonitor
268
- .fetchUserMergedPRCounts(starFilter)
269
- .catch(trackingCatch('fetch merged PR counts', emptyPRCountsResult())),
253
+ mergedCounts,
270
254
  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 })),
255
+ // The gap fetches wait for the counts: a ledger short of its all-time
256
+ // count under the ceiling is fetched from the start (gapFetchWatermark,
257
+ // #1504, #1925). Nothing else adds ledger rows before they are stored, so
258
+ // a failed or truncated fetch leaves the watermark alone.
259
+ mergedCounts.then((counts) => fetchMergedLedgerGap(octokit, stateManager, ledgerWarnings, counts.totalCount, gapOptions)),
260
+ closedCounts.then((counts) => fetchClosedLedgerGap(octokit, stateManager, ledgerWarnings, counts.totalCount, gapOptions)),
279
261
  ]);
280
- const newMergedPRs = gapRows(mergedGap, MERGED_LEDGER_TRUNCATED_MESSAGE, partialFailures);
281
- const newClosedPRs = gapRows(closedGap, CLOSED_LEDGER_TRUNCATED_MESSAGE, partialFailures);
262
+ reportLedgerGap(mergedGap, 'fetch merged PRs for storage', MERGED_LEDGER_TRUNCATED_MESSAGE, partialFailures);
263
+ reportLedgerGap(closedGap, 'fetch closed PRs for storage', CLOSED_LEDGER_TRUNCATED_MESSAGE, partialFailures);
282
264
  // Issue conversations run after the PR lists: the engaged set (#1862)
283
265
  // needs the open, recently closed and recently merged PRs. The fetch has
284
266
  // custom messaging based on the error content, so it keeps its bespoke catch.
@@ -340,19 +322,41 @@ export async function fetchDashboardData(token) {
340
322
  // Per-PR override failures (#1448) land in partialFailures so the SPA
341
323
  // banner flags PRs silently showing their un-overridden status.
342
324
  const overriddenPRs = applyStatusOverrides(prs, stateManager.getState(), partialFailures);
325
+ // Re-key transferred repos, drop closed-ledger rows that were reopened
326
+ // or merged (#1923) and rows in untracked organisations (#1924), as the
327
+ // daily run does before it stores. Private repositories are evicted by
328
+ // the daily run only: it is the one that reads repository visibility.
329
+ // Separate guards, so one failing does not skip the other.
330
+ try {
331
+ syncLedgersWithGitHub(stateManager, [...mergedResult.searchedPRs, ...closedResult.searchedPRs], prs);
332
+ }
333
+ catch (error) {
334
+ partialFailures.push('clean up PR ledgers');
335
+ warn(MODULE, `Failed to clean up PR ledgers: ${errorMessage(error)}`);
336
+ }
337
+ try {
338
+ evictNeverTrackedRepos(stateManager, []);
339
+ }
340
+ catch (error) {
341
+ partialFailures.push('remove untracked PRs');
342
+ warn(MODULE, `Failed to remove untracked PRs: ${errorMessage(error)}`);
343
+ }
343
344
  // Previous run's digest — read BEFORE setLastDigest below replaces it.
344
345
  // Supplies best-effort firstMaintainerResponseAt for PRs that were
345
346
  // enriched while open, mirroring daily's Phase 3 (#1461). openedAt is
346
347
  // already on the entries (created_at from the search result).
347
348
  const previousDigest = stateManager.getState().lastDigest;
348
- // Store new merged PRs incrementally (dedupes by URL; re-seen entries
349
- // upgrade missing ledger fields in place)
349
+ // Store the gap plus the recent list, only when the gap was fetched
350
+ // whole, as the daily run does (dedupes by URL; re-seen entries upgrade
351
+ // missing ledger fields in place).
350
352
  try {
351
- const { dropped } = stateManager.addMergedPRs(newMergedPRs.map((pr) => ({
352
- ...pr,
353
- firstMaintainerResponseAt: pr.firstMaintainerResponseAt ?? firstMaintainerResponseFromDigest(previousDigest, pr.url),
354
- ...lastReviewStateFromDigest(previousDigest, pr.url),
355
- })));
353
+ const dropped = storeMergedLedger(stateManager, {
354
+ gap: mergedGap,
355
+ allTimeCount: mergedResult.totalCount,
356
+ recentlyMergedPRs,
357
+ previousDigest,
358
+ warnings: ledgerWarnings,
359
+ });
356
360
  if (dropped > 0) {
357
361
  partialFailures.push(`Dropped ${dropped} merged PR(s) with invalid URLs before persistence`);
358
362
  }
@@ -361,14 +365,14 @@ export async function fetchDashboardData(token) {
361
365
  partialFailures.push('store merged PRs');
362
366
  warn(MODULE, `Failed to store merged PRs: ${errorMessage(error)}`);
363
367
  }
364
- // Store new closed PRs incrementally (dedupes by URL; re-seen entries
365
- // upgrade missing ledger fields in place)
366
368
  try {
367
- const { dropped } = stateManager.addClosedPRs(newClosedPRs.map((pr) => ({
368
- ...pr,
369
- firstMaintainerResponseAt: pr.firstMaintainerResponseAt ?? firstMaintainerResponseFromDigest(previousDigest, pr.url),
370
- ...lastReviewStateFromDigest(previousDigest, pr.url),
371
- })));
369
+ const dropped = storeClosedLedger(stateManager, {
370
+ gap: closedGap,
371
+ allTimeCount: closedResult.totalCount,
372
+ recentlyClosedPRs,
373
+ previousDigest,
374
+ warnings: ledgerWarnings,
375
+ });
372
376
  if (dropped > 0) {
373
377
  partialFailures.push(`Dropped ${dropped} closed PR(s) with invalid URLs before persistence`);
374
378
  }
@@ -411,6 +415,11 @@ export async function fetchDashboardData(token) {
411
415
  partialFailures.push('persist dashboard state');
412
416
  warn(MODULE, `Failed to persist dashboard state: ${errorMessage(error)}`);
413
417
  }
418
+ // Gap failures were logged where they happened; the short-ledger check was not.
419
+ for (const warning of ledgerWarnings) {
420
+ if (warning.phase === 'analytics')
421
+ warn(MODULE, warning.message);
422
+ }
414
423
  warn(MODULE, `Refreshed: ${prs.length} PRs fetched`);
415
424
  // Convert stored PRs to full types (derive repo/number from URL) — read-only, outside batch
416
425
  const allMergedPRs = storedToMergedPRs(stateManager.getMergedPRs());
@@ -23,17 +23,26 @@ export interface LaunchResult {
23
23
  */
24
24
  export declare function resolveCliEntry(argv1: string, assetsDir: string): string;
25
25
  /**
26
- * Stop the running dashboard server if a different CLI version launched it (#548).
26
+ * Stop the running dashboard server if an older CLI version launched it (#548).
27
27
  *
28
28
  * The server's refresh path re-classifies PRs with its own bundled code and
29
29
  * writes the result to state, so an old-version server overwrites whatever a
30
30
  * newer `daily` just wrote (#1709). The server cannot detect this itself:
31
31
  * plugin updates install into a new versioned directory, so the old server's
32
32
  * own package.json never changes. Callers running the current CLI (startup,
33
- * `daily`) therefore make the check.
33
+ * `daily`, `dashboard launch`) therefore make the check.
34
34
  *
35
- * Returns the running server when it is left up (same or unknown version, or
36
- * the kill failed), or null when none is running or the stale one was stopped.
35
+ * A newer server is left running: a long-lived session on an old plugin root
36
+ * must not replace it with its own older code (#1882).
37
+ *
38
+ * A server that does not answer `/api/health` as ours (one from before 3.43.0
39
+ * has no such route, and a busy one can miss the timeout) is stopped too
40
+ * unless it is newer, but only after its command line identifies it as
41
+ * `dashboard serve`. Otherwise the PID may have been recycled to an unrelated
42
+ * process and is never signalled (#1927).
43
+ *
44
+ * Returns the running server when it is left up (same, newer or unknown
45
+ * version, or the kill failed), or null when none is running or it was stopped.
37
46
  */
38
47
  export declare function stopStaleDashboardServer(): Promise<LaunchResult | null>;
39
48
  /**
@@ -42,11 +51,30 @@ export declare function stopStaleDashboardServer(): Promise<LaunchResult | null>
42
51
  * Returns the server URL if launched successfully, or null if the SPA assets
43
52
  * are not available (dashboard is skipped).
44
53
  *
45
- * If a server from the current version is already running (detected via PID
46
- * file + health probe), returns its URL without launching a new one. A server
47
- * from another version is stopped first, even when the assets are missing and
48
- * no replacement can be launched (#1709).
54
+ * If a server from the current or a newer version is already running
55
+ * (detected via PID file + health probe), returns its URL without launching a
56
+ * new one. A server from an older version is stopped first, even when the
57
+ * assets are missing and no replacement can be launched (#1709). See
58
+ * stopStaleDashboardServer for the rules.
49
59
  */
50
60
  export declare function launchDashboardServer(options?: {
51
61
  port?: number;
62
+ /** Append the server's stdout and stderr here instead of discarding them. */
63
+ logFile?: string;
52
64
  }): Promise<LaunchResult | null>;
65
+ export interface DashboardLaunchOutput {
66
+ status: 'launched' | 'already_running';
67
+ url: string;
68
+ port: number;
69
+ /** Where the server's output goes when this command started it. */
70
+ logFile: string;
71
+ }
72
+ /**
73
+ * `dashboard launch`: reuse the running server or start one in the
74
+ * background, through the same version check and health probe as startup.
75
+ * The `/oss-dashboard` command calls this instead of probing the server
76
+ * itself (#2039).
77
+ */
78
+ export declare function runDashboardLaunch(options: {
79
+ port: number;
80
+ }): Promise<DashboardLaunchOutput>;
@@ -6,9 +6,9 @@
6
6
  import { spawn } from 'node:child_process';
7
7
  import * as fs from 'node:fs';
8
8
  import * as path from 'node:path';
9
- import { findRunningDashboardServer, isDashboardServerRunning, readDashboardServerInfo, removeDashboardServerInfo, } from './dashboard-process.js';
9
+ import { isDashboardServeProcess, isDashboardServerRunning, probeDashboardServer, readDashboardServerInfo, removeDashboardServerInfo, } from './dashboard-process.js';
10
10
  import { resolveAssetsDir } from './dashboard.js';
11
- import { getCLIVersion } from '../core/index.js';
11
+ import { getCLIVersion, getDataDir } from '../core/index.js';
12
12
  const DEFAULT_PORT = 3000;
13
13
  const POLL_INTERVAL_MS = 200;
14
14
  const MAX_POLL_ATTEMPTS = 25; // 5 seconds total
@@ -24,55 +24,128 @@ export function resolveCliEntry(argv1, assetsDir) {
24
24
  const coreBundle = path.resolve(assetsDir, '../../core/dist/cli.bundle.cjs');
25
25
  return fs.existsSync(coreBundle) ? coreBundle : argv1;
26
26
  }
27
+ /** Open `logFile` for appending and mark where this server's output starts. */
28
+ function openLogFile(logFile) {
29
+ const startedAt = new Date();
30
+ const fd = fs.openSync(logFile, 'a', 0o600);
31
+ fs.writeSync(fd, `--- dashboard server started ${startedAt.toISOString()} ---\n`);
32
+ return fd;
33
+ }
34
+ /** Spawn `dashboard serve` detached, with its output discarded or appended to `logFile`. */
35
+ function spawnDashboardServer(cliPath, port, logFile) {
36
+ const logFd = logFile ? openLogFile(logFile) : undefined;
37
+ const stdio = logFd === undefined ? 'ignore' : ['ignore', logFd, logFd];
38
+ try {
39
+ return spawn('node', [cliPath, 'dashboard', 'serve', '--port', String(port), '--no-open'], {
40
+ detached: true,
41
+ stdio,
42
+ });
43
+ }
44
+ finally {
45
+ // The child holds its own copy of the descriptor.
46
+ if (logFd !== undefined)
47
+ fs.closeSync(logFd);
48
+ }
49
+ }
27
50
  function sleep(ms) {
28
51
  return new Promise((resolve) => setTimeout(resolve, ms));
29
52
  }
53
+ /** `x.y.z` of a version string, or null when it does not start with one. */
54
+ function parseVersion(version) {
55
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
56
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
57
+ }
30
58
  /**
31
- * Stop the running dashboard server if a different CLI version launched it (#548).
59
+ * How the version a server recorded compares with the current CLI's. A PID
60
+ * file with no version predates the stamp (#548), so it is older. `unknown`
61
+ * when either side cannot be read (`getCLIVersion` falls back to 0.0.0).
62
+ */
63
+ function compareServerVersion(serverVersion, currentVersion) {
64
+ const current = parseVersion(currentVersion);
65
+ if (currentVersion === '0.0.0' || !current)
66
+ return 'unknown';
67
+ if (serverVersion === undefined)
68
+ return 'older';
69
+ const server = parseVersion(serverVersion);
70
+ if (!server)
71
+ return 'unknown';
72
+ const diff = server.map((part, i) => part - current[i]).find((d) => d !== 0) ?? 0;
73
+ if (diff === 0)
74
+ return 'same';
75
+ return diff < 0 ? 'older' : 'newer';
76
+ }
77
+ /**
78
+ * SIGTERM the server the PID file records and remove the file. Returns null
79
+ * once it is stopped, or `running` when the signal could not be delivered
80
+ * (e.g. EPERM): the server is still up, so the caller must not spawn another.
81
+ */
82
+ function stopDashboardServer(info, running) {
83
+ try {
84
+ process.kill(info.pid, 'SIGTERM');
85
+ }
86
+ catch (err) {
87
+ // ESRCH = already exited
88
+ if (err.code !== 'ESRCH') {
89
+ console.error(`[DASHBOARD] Could not kill outdated dashboard (PID ${info.pid}): ${err.message}`);
90
+ return running;
91
+ }
92
+ }
93
+ removeDashboardServerInfo();
94
+ return null;
95
+ }
96
+ /**
97
+ * Stop the running dashboard server if an older CLI version launched it (#548).
32
98
  *
33
99
  * The server's refresh path re-classifies PRs with its own bundled code and
34
100
  * writes the result to state, so an old-version server overwrites whatever a
35
101
  * newer `daily` just wrote (#1709). The server cannot detect this itself:
36
102
  * plugin updates install into a new versioned directory, so the old server's
37
103
  * own package.json never changes. Callers running the current CLI (startup,
38
- * `daily`) therefore make the check.
104
+ * `daily`, `dashboard launch`) therefore make the check.
105
+ *
106
+ * A newer server is left running: a long-lived session on an old plugin root
107
+ * must not replace it with its own older code (#1882).
39
108
  *
40
- * Returns the running server when it is left up (same or unknown version, or
41
- * the kill failed), or null when none is running or the stale one was stopped.
109
+ * A server that does not answer `/api/health` as ours (one from before 3.43.0
110
+ * has no such route, and a busy one can miss the timeout) is stopped too
111
+ * unless it is newer, but only after its command line identifies it as
112
+ * `dashboard serve`. Otherwise the PID may have been recycled to an unrelated
113
+ * process and is never signalled (#1927).
114
+ *
115
+ * Returns the running server when it is left up (same, newer or unknown
116
+ * version, or the kill failed), or null when none is running or it was stopped.
42
117
  */
43
118
  export async function stopStaleDashboardServer() {
44
- const existing = await findRunningDashboardServer();
45
- if (!existing)
46
- return null;
47
- const info = readDashboardServerInfo();
48
- // PID file disappeared between health check and now (race condition).
49
- if (!info)
119
+ const probe = await probeDashboardServer();
120
+ if (probe.status === 'none')
50
121
  return null;
122
+ const { info } = probe;
51
123
  const running = {
52
- url: existing.url,
53
- port: existing.port,
124
+ url: `http://oss.localhost:${info.port}`,
125
+ port: info.port,
54
126
  alreadyRunning: true,
55
127
  lastBrowserOpenedAt: info.lastBrowserOpenedAt,
56
128
  };
57
129
  const currentVersion = getCLIVersion();
58
- if (!info.version || currentVersion === '0.0.0' || info.version === currentVersion) {
59
- return running;
60
- }
61
- console.error(`[DASHBOARD] Dashboard server version mismatch (running: ${info.version}, current: ${currentVersion}). Stopping it...`);
62
- try {
63
- process.kill(info.pid, 'SIGTERM');
64
- }
65
- catch (err) {
66
- // ESRCH = already exited
67
- if (err.code !== 'ESRCH') {
68
- console.error(`[DASHBOARD] Could not kill outdated dashboard (PID ${info.pid}): ${err.message}`);
69
- // Could not kill old server (e.g. EPERM); report it as running rather
70
- // than letting the caller attempt a doomed spawn on the same port.
130
+ const age = compareServerVersion(info.version, currentVersion);
131
+ if (probe.status === 'running') {
132
+ // A server that answers /api/health is 3.43.0 or later and always records
133
+ // its version; keep the old reading of a missing one as "leave it".
134
+ if (!info.version || age !== 'older')
71
135
  return running;
72
- }
136
+ console.error(`[DASHBOARD] Dashboard server version mismatch (running: ${info.version}, current: ${currentVersion}). Stopping it...`);
137
+ return stopDashboardServer(info, running);
73
138
  }
74
- removeDashboardServerInfo();
75
- return null;
139
+ if (age === 'unknown' || !isDashboardServeProcess(info.pid)) {
140
+ // Not identified as our server, or no version to compare: the stale-PID-file
141
+ // case. Never signal it (#1927).
142
+ removeDashboardServerInfo();
143
+ return null;
144
+ }
145
+ if (age === 'newer')
146
+ return running;
147
+ console.error(`[DASHBOARD] Dashboard server (PID ${info.pid}, version ${info.version ?? 'unknown'}) did not answer the health check. Stopping it...`);
148
+ return stopDashboardServer(info, running);
76
149
  }
77
150
  /**
78
151
  * Launch the interactive dashboard SPA server as a detached background process.
@@ -80,10 +153,11 @@ export async function stopStaleDashboardServer() {
80
153
  * Returns the server URL if launched successfully, or null if the SPA assets
81
154
  * are not available (dashboard is skipped).
82
155
  *
83
- * If a server from the current version is already running (detected via PID
84
- * file + health probe), returns its URL without launching a new one. A server
85
- * from another version is stopped first, even when the assets are missing and
86
- * no replacement can be launched (#1709).
156
+ * If a server from the current or a newer version is already running
157
+ * (detected via PID file + health probe), returns its URL without launching a
158
+ * new one. A server from an older version is stopped first, even when the
159
+ * assets are missing and no replacement can be launched (#1709). See
160
+ * stopStaleDashboardServer for the rules.
87
161
  */
88
162
  export async function launchDashboardServer(options) {
89
163
  // 1. Check if SPA assets exist
@@ -99,10 +173,7 @@ export async function launchDashboardServer(options) {
99
173
  // 3. Launch as detached child process
100
174
  const port = options?.port ?? DEFAULT_PORT;
101
175
  const cliPath = resolveCliEntry(process.argv[1], assetsDir);
102
- const child = spawn('node', [cliPath, 'dashboard', 'serve', '--port', String(port), '--no-open'], {
103
- detached: true,
104
- stdio: 'ignore',
105
- });
176
+ const child = spawnDashboardServer(cliPath, port, options?.logFile);
106
177
  // Track spawn failures and early exits so the polling loop can bail early
107
178
  let spawnFailed = false;
108
179
  let childExited = false;
@@ -146,3 +217,25 @@ export async function launchDashboardServer(options) {
146
217
  }
147
218
  return null;
148
219
  }
220
+ /**
221
+ * `dashboard launch`: reuse the running server or start one in the
222
+ * background, through the same version check and health probe as startup.
223
+ * The `/oss-dashboard` command calls this instead of probing the server
224
+ * itself (#2039).
225
+ */
226
+ export async function runDashboardLaunch(options) {
227
+ const logFile = path.join(getDataDir(), 'dashboard.log');
228
+ const result = await launchDashboardServer({ port: options.port, logFile });
229
+ if (!result) {
230
+ if (!resolveAssetsDir()) {
231
+ throw new Error('Dashboard SPA assets not found. Build with: cd packages/dashboard && pnpm run build');
232
+ }
233
+ throw new Error(`Dashboard server did not start. Logs: ${logFile}`);
234
+ }
235
+ return {
236
+ status: result.alreadyRunning ? 'already_running' : 'launched',
237
+ url: result.url,
238
+ port: result.port,
239
+ logFile,
240
+ };
241
+ }
@@ -34,7 +34,42 @@ export declare function removeOwnDashboardServerInfo(): void;
34
34
  * PID) never passes as the dashboard.
35
35
  */
36
36
  export declare function isDashboardServerRunning(port: number, pid: number): Promise<boolean>;
37
+ /**
38
+ * What the PID file points at. `unverified` means the recorded PID is alive
39
+ * but did not answer `/api/health` as ours: a recycled PID, a server too busy
40
+ * to answer within the timeout, or a server from before 3.43.0, which has no
41
+ * health route (#1882). The PID file is left in place for the caller to decide.
42
+ */
43
+ export type DashboardServerProbe = {
44
+ status: 'none';
45
+ } | {
46
+ info: DashboardServerInfo;
47
+ status: 'running';
48
+ port: number;
49
+ url: string;
50
+ } | {
51
+ status: 'unverified';
52
+ info: DashboardServerInfo;
53
+ };
54
+ export declare function probeDashboardServer(): Promise<DashboardServerProbe>;
37
55
  export declare function findRunningDashboardServer(): Promise<{
38
56
  port: number;
39
57
  url: string;
40
58
  } | null>;
59
+ /**
60
+ * True only for the command line the launchers spawn: `node [--flags] <cli
61
+ * entry> dashboard serve ...`. Matching "dashboard serve" anywhere in argv
62
+ * would accept a recycled PID now running e.g. `grep -rn "dashboard serve"`
63
+ * or a shell wrapper. Anything else, including paths with spaces and a tsx
64
+ * dev server, reads as false, which only ever means "never signal".
65
+ */
66
+ export declare function isDashboardServeCommand(command: string): boolean;
67
+ /**
68
+ * True only when the process at `pid` is a `dashboard serve` process, read
69
+ * from its command line (see isDashboardServeCommand). This is what lets a
70
+ * caller signal a server that does not answer `/api/health` (#1882) without
71
+ * ever signalling a PID that was recycled to an unrelated program (#1927).
72
+ * Anything that cannot be checked (no `ps`, as on Windows, or an exited PID)
73
+ * reads as false.
74
+ */
75
+ export declare function isDashboardServeProcess(pid: number): boolean;