@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,9 +2,11 @@
2
2
  * Config command
3
3
  * Shows or updates configuration
4
4
  */
5
- import { CONFIG_KEY_REGISTRY, formatUnknownKeyError, getStateManager, maybeCheckpoint, } from '../core/index.js';
5
+ import { CONFIG_KEY_REGISTRY, formatUnknownKeyError, getKeyDef, getStateManager, maybeCheckpoint, } from '../core/index.js';
6
6
  import { ValidationError } from '../core/errors.js';
7
+ import { MACHINE_PATH_KEYS, getMachinePath, getMachinePathSource, getMachineScanPaths, setMachinePath, } from '../core/local-config.js';
7
8
  import { ISSUE_SCOPES, DIFF_TOOLS } from '../core/types.js';
9
+ import { runSetup } from './setup.js';
8
10
  import { validateGitHubUsername } from './validation.js';
9
11
  const MODULE = 'config';
10
12
  function validateScope(value) {
@@ -13,6 +15,37 @@ function validateScope(value) {
13
15
  }
14
16
  return value;
15
17
  }
18
+ /**
19
+ * The config as this machine uses it: the two path settings show the value in
20
+ * effect here (local file first, synced value as fallback), not whatever
21
+ * another machine last synced (#1950). `machinePathSources` says where each
22
+ * shown path comes from and is omitted when neither is configured.
23
+ * `localRepoScanPaths` shows this machine's scan roots (source `set` or
24
+ * `adopted`), and is omitted when the defaults are in use (#2010).
25
+ */
26
+ function showConfig(config) {
27
+ const shown = { ...config };
28
+ const sources = {};
29
+ for (const key of MACHINE_PATH_KEYS) {
30
+ const value = getMachinePath(key, config);
31
+ if (value === undefined)
32
+ delete shown[key];
33
+ else
34
+ shown[key] = value;
35
+ const source = getMachinePathSource(key, config);
36
+ if (source)
37
+ sources[key] = source;
38
+ }
39
+ const scanPaths = getMachineScanPaths(config.localRepoScanPaths);
40
+ if (scanPaths) {
41
+ shown.localRepoScanPaths = scanPaths.paths;
42
+ sources.localRepoScanPaths = scanPaths.source;
43
+ }
44
+ else {
45
+ delete shown.localRepoScanPaths;
46
+ }
47
+ return { config: shown, ...(Object.keys(sources).length > 0 && { machinePathSources: sources }) };
48
+ }
16
49
  /**
17
50
  * Read or write user configuration settings.
18
51
  * When called without a key, returns the full config.
@@ -36,12 +69,17 @@ export async function runConfig(options) {
36
69
  const stateManager = getStateManager();
37
70
  if (!options.key) {
38
71
  // Show current config
39
- return { config: stateManager.getState().config };
72
+ return showConfig(stateManager.getState().config);
40
73
  }
41
74
  if (!options.value) {
42
75
  throw new Error('Value required');
43
76
  }
44
77
  const { key, value } = options;
78
+ // `config --list-keys` and the MCP tool's key enum advertise setup-scoped
79
+ // keys too, so apply them through setup's validators (#1887, #1913).
80
+ if (getKeyDef(key)?.settableVia === 'setup') {
81
+ return runSetupKey(key, value);
82
+ }
45
83
  const apply = () => applyConfigKey(stateManager, key, value);
46
84
  apply();
47
85
  // Push the config mutation to the Gist in gist mode (no-op locally).
@@ -50,6 +88,25 @@ export async function runConfig(options) {
50
88
  const gistSyncWarning = await maybeCheckpoint(stateManager, MODULE, apply);
51
89
  return { success: true, key, value, ...(gistSyncWarning && { gistSyncWarning }) };
52
90
  }
91
+ /**
92
+ * Set a setup-scoped key via `setup --set key=value`. Setup skips some
93
+ * values without storing anything (e.g. `complete` with anything but
94
+ * `true`); that is an error here, never a success (#1887).
95
+ */
96
+ async function runSetupKey(key, value) {
97
+ const result = await runSetup({ set: [`${key}=${value}`] });
98
+ if (!('settings' in result) || result.settings[key] === undefined) {
99
+ const hint = getKeyDef(key)?.valueHint;
100
+ throw new ValidationError(`${key} was not changed: "${value}" is not a value it accepts (expected ${hint}).`);
101
+ }
102
+ return {
103
+ success: true,
104
+ key,
105
+ value: result.settings[key],
106
+ ...(result.warnings && { warnings: result.warnings }),
107
+ ...(result.gistSyncWarning && { gistSyncWarning: result.gistSyncWarning }),
108
+ };
109
+ }
53
110
  /**
54
111
  * Apply one config key. Reads the current config fresh so the Gist conflict
55
112
  * path can re-run it on a refreshed baseline without stale array merges.
@@ -89,12 +146,12 @@ function applyConfigKey(stateManager, key, value) {
89
146
  break;
90
147
  }
91
148
  case 'remove-scope': {
92
- const scope = validateScope(value);
149
+ // Not validated: a stored scope a newer release added must be removable (#2005).
93
150
  const existingScopes = currentConfig.scope ?? [];
94
- if (!existingScopes.includes(scope)) {
151
+ if (!existingScopes.includes(value)) {
95
152
  throw new Error(`Scope "${value}" is not currently set`);
96
153
  }
97
- const filtered = existingScopes.filter((s) => s !== scope);
154
+ const filtered = existingScopes.filter((s) => s !== value);
98
155
  if (filtered.length === 0) {
99
156
  throw new Error('Cannot remove the last scope. Use setup to clear scopes entirely.');
100
157
  }
@@ -172,7 +229,7 @@ function applyConfigKey(stateManager, key, value) {
172
229
  break;
173
230
  }
174
231
  case 'issueListPath': {
175
- stateManager.updateConfig({ issueListPath: value || undefined });
232
+ setMachinePath('issueListPath', value || undefined);
176
233
  break;
177
234
  }
178
235
  case 'diffTool': {
@@ -7,6 +7,13 @@
7
7
  import { getStateManager, type CommentedIssue } from '../core/index.js';
8
8
  import type { DailyWarning } from '../formatters/json.js';
9
9
  type StateManagerLike = Pick<ReturnType<typeof getStateManager>, 'reloadIfChanged' | 'batch' | 'getIssueDismissedAt' | 'undismissIssue'>;
10
+ /**
11
+ * Reload state where the run only wants to pick up a config edit made while
12
+ * it was fetching. A failed reload there is not worth the run (the digest is
13
+ * already saved): it becomes a warning and the run continues on in-memory
14
+ * state. State written by a newer release still stops it (#1951).
15
+ */
16
+ export declare function reloadOrWarn(stateManager: Pick<StateManagerLike, 'reloadIfChanged'>, warnings: DailyWarning[]): void;
10
17
  /**
11
18
  * Run a batch against a baseline that is fresh as of right now.
12
19
  *
@@ -4,10 +4,26 @@
4
4
  * against a real StateManager (dismiss, resurface, reload from disk) without
5
5
  * mocking the whole daily pipeline.
6
6
  */
7
- import { isCoveredByDismiss } from '../core/index.js';
7
+ import { isCoveredByDismiss, NewerStateVersionError } from '../core/index.js';
8
8
  import { warn } from '../core/logger.js';
9
9
  import { recordWarning } from './daily-warnings.js';
10
10
  const MODULE = 'daily';
11
+ /**
12
+ * Reload state where the run only wants to pick up a config edit made while
13
+ * it was fetching. A failed reload there is not worth the run (the digest is
14
+ * already saved): it becomes a warning and the run continues on in-memory
15
+ * state. State written by a newer release still stops it (#1951).
16
+ */
17
+ export function reloadOrWarn(stateManager, warnings) {
18
+ try {
19
+ stateManager.reloadIfChanged();
20
+ }
21
+ catch (err) {
22
+ if (err instanceof NewerStateVersionError)
23
+ throw err;
24
+ recordWarning(warnings, 'state-load', 'reload state before capacity check', err);
25
+ }
26
+ }
11
27
  /**
12
28
  * Run a batch against a baseline that is fresh as of right now.
13
29
  *
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Ledger upkeep the daily run does before it rewrites per-repo counts. Kept
3
+ * out of daily.ts so ledger rules live in one small place.
4
+ */
5
+ import type { Octokit } from '@octokit/rest';
6
+ import { type PRsSinceResult } from '../core/github-stats.js';
7
+ import type { getStateManager } from '../core/index.js';
8
+ import type { RepoMetadata } from '../core/pr-monitor.js';
9
+ import type { ClosedPR, DailyDigest, MergedPR, StoredClosedPR, StoredMergedPR } from '../core/types.js';
10
+ import type { DailyWarning } from '../formatters/json.js';
11
+ type StateManagerLike = ReturnType<typeof getStateManager>;
12
+ type LedgerStateManager = Pick<StateManagerLike, 'getMergedPRs' | 'getClosedPRs' | 'renameRepo' | 'evictClosedPRs'>;
13
+ /**
14
+ * Bring the stored merged/closed ledgers in line with what GitHub reports now.
15
+ * Must run before anything reads or writes repoScores in the same batch.
16
+ *
17
+ * 1. Re-key transferred/renamed repos, so the old name isn't zeroed and then
18
+ * re-bumped from stored PR URLs on the next load (which double counted its
19
+ * merges in getStats).
20
+ * 2. Drop closed-ledger entries that were reopened (now in `openPRs`) or have
21
+ * since merged, so the count reconciliation that follows no longer raises
22
+ * `closedWithoutMergeCount` back to a ledger that still holds them (#1923).
23
+ * This runs every day, so state inflated before the fix heals on the next
24
+ * run, as does an entry another machine's older copy brought back.
25
+ *
26
+ * @param searchedPRs - every merged/closed PR the count searches returned
27
+ * @param openPRs - the user's currently open PRs, as just fetched
28
+ */
29
+ export declare function syncLedgersWithGitHub(stateManager: LedgerStateManager, searchedPRs: ReadonlyArray<{
30
+ url: string;
31
+ title: string;
32
+ }>, openPRs: ReadonlyArray<{
33
+ url: string;
34
+ }>): void;
35
+ /**
36
+ * Write the star counts and languages a repository read returned, then drop
37
+ * what is stored about repositories whose PRs are never tracked (#1924):
38
+ * those in `config.untrackedOrgs`, and those this read reported private.
39
+ * The fetches no longer return either kind; this removes what earlier
40
+ * versions stored, and what another machine's older copy brings back.
41
+ *
42
+ * Only an explicit `isPrivate: true` in `repoMetadata` counts as private. A
43
+ * repository missing from the map (404, network error, aborted chunk, or the
44
+ * whole fetch failing) or with no flag is left alone, so deleted, renamed and
45
+ * transferred repositories keep their rows.
46
+ */
47
+ export declare function applyRepoMetadata(stateManager: Pick<StateManagerLike, 'updateRepoScore' | 'evictExcludedRepos'>, repoMetadata: ReadonlyMap<string, RepoMetadata>, warnings: DailyWarning[]): void;
48
+ /**
49
+ * Drop what is stored about repositories whose PRs are never tracked (#1924):
50
+ * those in `config.untrackedOrgs`, and `privateRepos`. The daily run learns
51
+ * which repositories are private from its metadata read (applyRepoMetadata);
52
+ * the dashboard refresh has no such read and passes none, so it removes only
53
+ * the untracked organisations' rows.
54
+ */
55
+ export declare function evictNeverTrackedRepos(stateManager: Pick<StateManagerLike, 'evictExcludedRepos'>, privateRepos: readonly string[]): void;
56
+ /**
57
+ * Zero `closedWithoutMergeCount` for repos the closed-PR count search no
58
+ * longer returns, mirroring the stale reset daily does for merged counts.
59
+ * Without it, a repo whose closed PRs were all reopened or merged leaves the
60
+ * search and keeps its last search-set count for good (#1923). The count
61
+ * reconciliation that follows in the same batch raises each repo back to its
62
+ * closed-ledger count, so only the surplus over the ledger is dropped.
63
+ *
64
+ * Skipped, like the merged reset, when the search returned nothing while state
65
+ * has closed counts (possible transient API failure) or when it hit its
66
+ * pagination cap (an absent repo may still have closed PRs).
67
+ */
68
+ export declare function resetStaleClosedCounts(stateManager: Pick<StateManagerLike, 'getState' | 'updateRepoScore'>, closedCounts: ReadonlyMap<string, number>, wasSearchTruncated: boolean): void;
69
+ /** This run's merged-ledger gap fetch; undefined when the fetch failed. */
70
+ export type MergedLedgerGap = PRsSinceResult<StoredMergedPR> | undefined;
71
+ /** This run's closed-ledger gap fetch; undefined when the fetch failed. */
72
+ export type ClosedLedgerGap = PRsSinceResult<StoredClosedPR> | undefined;
73
+ /** How a gap fetch treats a failure. */
74
+ export interface LedgerGapOptions {
75
+ /**
76
+ * Errors to rethrow instead of recording. The dashboard refresh passes
77
+ * isRateLimitOrAuthError, since those abort the whole refresh there; the
78
+ * daily run records every failure and carries on.
79
+ */
80
+ rethrowIf?: (error: unknown) => boolean;
81
+ }
82
+ /**
83
+ * Fetch every merged PR since the ledger's newest entry (#1924). The recent
84
+ * list daily shows covers seven days, so after a longer pause it alone left
85
+ * the merges in between out of the ledger for good. Must run before anything
86
+ * in this run adds to the merged ledger: the watermark is read here. Shared
87
+ * by the daily run and the dashboard refresh, so both follow one rule.
88
+ *
89
+ * A ledger left short of `allTimeCount` (seeded ahead of its history, #1504)
90
+ * is fetched from the start while it is under the backfill ceiling (see
91
+ * gapFetchWatermark), the same rule as the closed ledger. Past the ceiling,
92
+ * or with an unknown count, the gap fetch starts at the watermark and
93
+ * storeMergedLedger points at `ledger-backfill`.
94
+ *
95
+ * A failed or truncated fetch is recorded in `warnings`, and
96
+ * {@link storeMergedLedger} then stores nothing, so the next run asks for the
97
+ * same range again. Until a run stores them, today's merges are not in the
98
+ * ledger, so the "extract learnings" nudge, which counts ledger rows of
99
+ * recent merges, is also held back for them.
100
+ */
101
+ export declare function fetchMergedLedgerGap(octokit: Octokit, stateManager: Pick<StateManagerLike, 'getState' | 'getMergedPRWatermark' | 'getMergedPRs'>, warnings: DailyWarning[], allTimeCount: number | undefined, options?: LedgerGapOptions): Promise<MergedLedgerGap>;
102
+ /**
103
+ * The closed-ledger mirror of {@link fetchMergedLedgerGap} (#1925). Without
104
+ * it the recent closed list seeded a fresh ledger with last week's closes,
105
+ * and the dashboard's fetch then started from that newest row, so older
106
+ * closed history was never fetched. Must run before anything in this run adds
107
+ * to the closed ledger.
108
+ *
109
+ * A ledger an older version already left short of `allTimeCount` is fetched
110
+ * from the start while it is under the backfill ceiling (see
111
+ * gapFetchWatermark), so it heals without a manual `ledger-backfill`.
112
+ */
113
+ export declare function fetchClosedLedgerGap(octokit: Octokit, stateManager: Pick<StateManagerLike, 'getState' | 'getClosedPRWatermark' | 'getClosedPRs'>, warnings: DailyWarning[], allTimeCount: number | undefined, options?: LedgerGapOptions): Promise<ClosedLedgerGap>;
114
+ /** What a store step takes besides the gap. */
115
+ interface StoreLedgerInput {
116
+ /** Previous run's digest: best-effort first-response and review state for the new rows (#1461). */
117
+ previousDigest: DailyDigest | undefined;
118
+ /** GitHub's all-time count from the count search; undefined when unknown. */
119
+ allTimeCount: number | undefined;
120
+ warnings: DailyWarning[];
121
+ }
122
+ /**
123
+ * Add this run's merges to the merged ledger: the gap since its newest entry
124
+ * plus the recent list (which can also fill an older hole inside its window).
125
+ *
126
+ * Nothing is stored unless the gap was fetched whole. The ledger's newest
127
+ * entry is the next run's starting point, so a recent row stored without the
128
+ * rows before it would move that point past merges nobody fetched.
129
+ *
130
+ * Then compares the ledger with GitHub's all-time merged count (see
131
+ * checkLedgerCount).
132
+ *
133
+ * @returns how many rows addMergedPRs dropped for an invalid URL (0 when nothing was stored)
134
+ */
135
+ export declare function storeMergedLedger(stateManager: Pick<StateManagerLike, 'addMergedPRs' | 'getMergedPRs'>, input: StoreLedgerInput & {
136
+ gap: MergedLedgerGap;
137
+ recentlyMergedPRs: ReadonlyArray<MergedPR>;
138
+ }): number;
139
+ /**
140
+ * The closed-ledger mirror of {@link storeMergedLedger} (#1925): the gap
141
+ * plus the recent closed list, stored only when the gap was fetched whole,
142
+ * then checked against GitHub's all-time closed-without-merge count.
143
+ *
144
+ * @returns how many rows addClosedPRs dropped for an invalid URL (0 when nothing was stored)
145
+ */
146
+ export declare function storeClosedLedger(stateManager: Pick<StateManagerLike, 'addClosedPRs' | 'getClosedPRs'>, input: StoreLedgerInput & {
147
+ gap: ClosedLedgerGap;
148
+ recentlyClosedPRs: ReadonlyArray<ClosedPR>;
149
+ }): number;
150
+ export {};
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Ledger upkeep the daily run does before it rewrites per-repo counts. Kept
3
+ * out of daily.ts so ledger rules live in one small place.
4
+ */
5
+ import { firstMaintainerResponseFromDigest, lastReviewStateFromDigest } from '../core/daily-logic.js';
6
+ import { CLOSED_LEDGER_TRUNCATED_MESSAGE, fetchClosedPRsSince, fetchMergedPRsSince, gapFetchWatermark, MERGED_LEDGER_TRUNCATED_MESSAGE, } from '../core/github-stats.js';
7
+ import { errorMessage } from '../core/errors.js';
8
+ import { debug, warn } from '../core/logger.js';
9
+ import { findRepoTransfers } from '../core/repo-score-manager.js';
10
+ import { recordWarning } from './daily-warnings.js';
11
+ const MODULE = 'daily';
12
+ /**
13
+ * Bring the stored merged/closed ledgers in line with what GitHub reports now.
14
+ * Must run before anything reads or writes repoScores in the same batch.
15
+ *
16
+ * 1. Re-key transferred/renamed repos, so the old name isn't zeroed and then
17
+ * re-bumped from stored PR URLs on the next load (which double counted its
18
+ * merges in getStats).
19
+ * 2. Drop closed-ledger entries that were reopened (now in `openPRs`) or have
20
+ * since merged, so the count reconciliation that follows no longer raises
21
+ * `closedWithoutMergeCount` back to a ledger that still holds them (#1923).
22
+ * This runs every day, so state inflated before the fix heals on the next
23
+ * run, as does an entry another machine's older copy brought back.
24
+ *
25
+ * @param searchedPRs - every merged/closed PR the count searches returned
26
+ * @param openPRs - the user's currently open PRs, as just fetched
27
+ */
28
+ export function syncLedgersWithGitHub(stateManager, searchedPRs, openPRs) {
29
+ const stored = [...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()];
30
+ for (const [from, to] of findRepoTransfers(stored, searchedPRs)) {
31
+ stateManager.renameRepo(from, to);
32
+ }
33
+ stateManager.evictClosedPRs(openPRs.map((pr) => pr.url));
34
+ }
35
+ /**
36
+ * Write the star counts and languages a repository read returned, then drop
37
+ * what is stored about repositories whose PRs are never tracked (#1924):
38
+ * those in `config.untrackedOrgs`, and those this read reported private.
39
+ * The fetches no longer return either kind; this removes what earlier
40
+ * versions stored, and what another machine's older copy brings back.
41
+ *
42
+ * Only an explicit `isPrivate: true` in `repoMetadata` counts as private. A
43
+ * repository missing from the map (404, network error, aborted chunk, or the
44
+ * whole fetch failing) or with no flag is left alone, so deleted, renamed and
45
+ * transferred repositories keep their rows.
46
+ */
47
+ export function applyRepoMetadata(stateManager, repoMetadata, warnings) {
48
+ let failures = 0;
49
+ const privateRepos = [];
50
+ for (const [repo, { stars, language, isPrivate }] of repoMetadata) {
51
+ if (isPrivate === true) {
52
+ // Evicted below; writing its stars first would only recreate the entry.
53
+ privateRepos.push(repo);
54
+ continue;
55
+ }
56
+ try {
57
+ stateManager.updateRepoScore(repo, { stargazersCount: stars, language });
58
+ }
59
+ catch (error) {
60
+ failures++;
61
+ warn(MODULE, `Failed to update metadata for ${repo}: ${errorMessage(error)}`);
62
+ }
63
+ }
64
+ if (failures > 0) {
65
+ warnings.push({
66
+ phase: 'repo-scores',
67
+ operation: 'update repo metadata',
68
+ message: `${failures} of ${repoMetadata.size} metadata update(s) failed. This may indicate corrupted state.`,
69
+ });
70
+ warn(MODULE, `[METADATA_UPDATES_FAILED] ${failures} of ${repoMetadata.size} metadata update(s) failed.`);
71
+ }
72
+ evictNeverTrackedRepos(stateManager, privateRepos);
73
+ }
74
+ /**
75
+ * Drop what is stored about repositories whose PRs are never tracked (#1924):
76
+ * those in `config.untrackedOrgs`, and `privateRepos`. The daily run learns
77
+ * which repositories are private from its metadata read (applyRepoMetadata);
78
+ * the dashboard refresh has no such read and passes none, so it removes only
79
+ * the untracked organisations' rows.
80
+ */
81
+ export function evictNeverTrackedRepos(stateManager, privateRepos) {
82
+ const evicted = stateManager.evictExcludedRepos(privateRepos);
83
+ if (evicted.untrackedOrgRows + evicted.privateRows + evicted.repos > 0) {
84
+ warn(MODULE, `Removed PRs that are never tracked: ${evicted.untrackedOrgRows} ledger row(s) in untracked organisations, ` +
85
+ `${evicted.privateRows} in private repositories, ${evicted.repos} repo score(s).`);
86
+ }
87
+ }
88
+ /**
89
+ * Zero `closedWithoutMergeCount` for repos the closed-PR count search no
90
+ * longer returns, mirroring the stale reset daily does for merged counts.
91
+ * Without it, a repo whose closed PRs were all reopened or merged leaves the
92
+ * search and keeps its last search-set count for good (#1923). The count
93
+ * reconciliation that follows in the same batch raises each repo back to its
94
+ * closed-ledger count, so only the surplus over the ledger is dropped.
95
+ *
96
+ * Skipped, like the merged reset, when the search returned nothing while state
97
+ * has closed counts (possible transient API failure) or when it hit its
98
+ * pagination cap (an absent repo may still have closed PRs).
99
+ */
100
+ export function resetStaleClosedCounts(stateManager, closedCounts, wasSearchTruncated) {
101
+ const withClosed = Object.values(stateManager.getState().repoScores).filter((score) => (score.closedWithoutMergeCount || 0) > 0);
102
+ if (closedCounts.size === 0 && withClosed.length > 0) {
103
+ warn(MODULE, `Skipping stale closed count reset: API returned 0 closed PR results but state has ${withClosed.length} repo(s) with closed PRs. Possible transient API issue.`);
104
+ return;
105
+ }
106
+ if (wasSearchTruncated) {
107
+ debug(MODULE, 'Skipping stale closed count reset: closed PR search was truncated.');
108
+ return;
109
+ }
110
+ for (const score of withClosed) {
111
+ if (!closedCounts.has(score.repo))
112
+ stateManager.updateRepoScore(score.repo, { closedWithoutMergeCount: 0 });
113
+ }
114
+ }
115
+ /** Run one gap fetch, recording a failure or truncation in `warnings`. */
116
+ async function fetchLedgerGap(kind, fetch, truncatedMessage, warnings, options) {
117
+ const operation = `fetch ${kind} PRs for the ledger`;
118
+ let gap;
119
+ try {
120
+ gap = await fetch();
121
+ }
122
+ catch (error) {
123
+ if (options.rethrowIf?.(error))
124
+ throw error;
125
+ recordWarning(warnings, 'fetch', operation, error);
126
+ }
127
+ if (gap?.truncated)
128
+ warnings.push({ phase: 'fetch', message: truncatedMessage, operation });
129
+ return gap;
130
+ }
131
+ /**
132
+ * Compare a ledger with GitHub's all-time count. A hole older than the newest
133
+ * entry is invisible to the gap fetch; the count is the one signal that shows
134
+ * it, and `ledger-backfill` is what fills it. The count search and the ledger
135
+ * fetch share one scope (externalPRScope: public, not the user's own, no
136
+ * untracked organisations), so the two are comparable; when that scope cannot
137
+ * be put in a query the count is undefined and the check is skipped.
138
+ *
139
+ * A ledger larger than the public total is expected while rows GitHub no
140
+ * longer lists (or private ones not yet evicted) remain; each such row can
141
+ * mask one missing public PR until it is gone.
142
+ */
143
+ function checkLedgerCount(kind, stored, allTimeCount, warnings) {
144
+ const missing = (allTimeCount ?? 0) - stored;
145
+ if (missing > 0) {
146
+ warnings.push({
147
+ phase: 'analytics',
148
+ operation: `check ${kind}-PR ledger`,
149
+ message: `The ${kind}-PR ledger holds ${stored} of the ${allTimeCount} ${kind} PRs GitHub reports ` +
150
+ `(${missing} missing). Run \`ledger-backfill\` to fetch them.`,
151
+ });
152
+ }
153
+ }
154
+ /**
155
+ * Fetch every merged PR since the ledger's newest entry (#1924). The recent
156
+ * list daily shows covers seven days, so after a longer pause it alone left
157
+ * the merges in between out of the ledger for good. Must run before anything
158
+ * in this run adds to the merged ledger: the watermark is read here. Shared
159
+ * by the daily run and the dashboard refresh, so both follow one rule.
160
+ *
161
+ * A ledger left short of `allTimeCount` (seeded ahead of its history, #1504)
162
+ * is fetched from the start while it is under the backfill ceiling (see
163
+ * gapFetchWatermark), the same rule as the closed ledger. Past the ceiling,
164
+ * or with an unknown count, the gap fetch starts at the watermark and
165
+ * storeMergedLedger points at `ledger-backfill`.
166
+ *
167
+ * A failed or truncated fetch is recorded in `warnings`, and
168
+ * {@link storeMergedLedger} then stores nothing, so the next run asks for the
169
+ * same range again. Until a run stores them, today's merges are not in the
170
+ * ledger, so the "extract learnings" nudge, which counts ledger rows of
171
+ * recent merges, is also held back for them.
172
+ */
173
+ export function fetchMergedLedgerGap(octokit, stateManager, warnings, allTimeCount, options = {}) {
174
+ const { config } = stateManager.getState();
175
+ const watermark = gapFetchWatermark(stateManager.getMergedPRWatermark(), stateManager.getMergedPRs().length, allTimeCount);
176
+ return fetchLedgerGap('merged', () => fetchMergedPRsSince(octokit, config, watermark), MERGED_LEDGER_TRUNCATED_MESSAGE, warnings, options);
177
+ }
178
+ /**
179
+ * The closed-ledger mirror of {@link fetchMergedLedgerGap} (#1925). Without
180
+ * it the recent closed list seeded a fresh ledger with last week's closes,
181
+ * and the dashboard's fetch then started from that newest row, so older
182
+ * closed history was never fetched. Must run before anything in this run adds
183
+ * to the closed ledger.
184
+ *
185
+ * A ledger an older version already left short of `allTimeCount` is fetched
186
+ * from the start while it is under the backfill ceiling (see
187
+ * gapFetchWatermark), so it heals without a manual `ledger-backfill`.
188
+ */
189
+ export function fetchClosedLedgerGap(octokit, stateManager, warnings, allTimeCount, options = {}) {
190
+ const { config } = stateManager.getState();
191
+ const watermark = gapFetchWatermark(stateManager.getClosedPRWatermark(), stateManager.getClosedPRs().length, allTimeCount);
192
+ return fetchLedgerGap('closed', () => fetchClosedPRsSince(octokit, config, watermark), CLOSED_LEDGER_TRUNCATED_MESSAGE, warnings, options);
193
+ }
194
+ /** Fields both ledgers fill the same way from a fetched or recent row. */
195
+ function ledgerFields(pr, previousDigest) {
196
+ return {
197
+ url: pr.url,
198
+ title: pr.title,
199
+ openedAt: pr.openedAt,
200
+ firstMaintainerResponseAt: firstMaintainerResponseFromDigest(previousDigest, pr.url),
201
+ issueUrl: pr.issueUrl,
202
+ ...lastReviewStateFromDigest(previousDigest, pr.url),
203
+ };
204
+ }
205
+ /**
206
+ * Add this run's merges to the merged ledger: the gap since its newest entry
207
+ * plus the recent list (which can also fill an older hole inside its window).
208
+ *
209
+ * Nothing is stored unless the gap was fetched whole. The ledger's newest
210
+ * entry is the next run's starting point, so a recent row stored without the
211
+ * rows before it would move that point past merges nobody fetched.
212
+ *
213
+ * Then compares the ledger with GitHub's all-time merged count (see
214
+ * checkLedgerCount).
215
+ *
216
+ * @returns how many rows addMergedPRs dropped for an invalid URL (0 when nothing was stored)
217
+ */
218
+ export function storeMergedLedger(stateManager, input) {
219
+ const { gap, previousDigest } = input;
220
+ if (!gap || gap.truncated)
221
+ return 0;
222
+ const rows = [...input.recentlyMergedPRs, ...gap.prs].map((pr) => ({
223
+ ...ledgerFields(pr, previousDigest),
224
+ mergedAt: pr.mergedAt,
225
+ }));
226
+ const dropped = rows.length > 0 ? stateManager.addMergedPRs(rows).dropped : 0;
227
+ checkLedgerCount('merged', stateManager.getMergedPRs().length, input.allTimeCount, input.warnings);
228
+ return dropped;
229
+ }
230
+ /**
231
+ * The closed-ledger mirror of {@link storeMergedLedger} (#1925): the gap
232
+ * plus the recent closed list, stored only when the gap was fetched whole,
233
+ * then checked against GitHub's all-time closed-without-merge count.
234
+ *
235
+ * @returns how many rows addClosedPRs dropped for an invalid URL (0 when nothing was stored)
236
+ */
237
+ export function storeClosedLedger(stateManager, input) {
238
+ const { gap, previousDigest } = input;
239
+ if (!gap || gap.truncated)
240
+ return 0;
241
+ const rows = [...input.recentlyClosedPRs, ...gap.prs].map((pr) => ({
242
+ ...ledgerFields(pr, previousDigest),
243
+ closedAt: pr.closedAt,
244
+ }));
245
+ const dropped = rows.length > 0 ? stateManager.addClosedPRs(rows).dropped : 0;
246
+ checkLedgerCount('closed', stateManager.getClosedPRs().length, input.allTimeCount, input.warnings);
247
+ return dropped;
248
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The daily run's recently closed and recently merged PR lists (#1928).
3
+ * Split out of daily.ts so a failed or partial list is recorded in one place:
4
+ * both land in `warnings[]`, and a merged list that may be missing entries is
5
+ * named as a reason to distrust "no successor PR exists" (Phase 3.6).
6
+ *
7
+ * "Truncation" here is the recent-list truncation (these two 7-day lists),
8
+ * not the count-search truncation of the all-time merged and closed counts.
9
+ */
10
+ import type { ClosedPR, MergedPR, PRMonitor } from '../core/index.js';
11
+ import type { DailyWarning } from '../formatters/json.js';
12
+ export interface RecentPRLists {
13
+ recentlyClosedPRs: ClosedPR[];
14
+ recentlyMergedPRs: MergedPR[];
15
+ /** `recentlyMergedPRs` is the [] fallback of a failed fetch, not an empty result (Phases 3.6 and 3.7). */
16
+ recentlyMergedFetchFailed: boolean;
17
+ /** Why a merged PR could be missing from `recentlyMergedPRs`; empty when the list is whole. */
18
+ successorGapReasons: string[];
19
+ }
20
+ /**
21
+ * Fetch both lists in parallel. Neither failure is fatal: a failed fetch is
22
+ * a warning and an empty list. A partial list (page cap reached, or GitHub
23
+ * flagged the search incomplete) is kept and reported as a warning; for the
24
+ * merged list it is also a successor gap, like a failed fetch.
25
+ */
26
+ export declare function fetchRecentPRLists(prMonitor: Pick<PRMonitor, 'fetchRecentlyClosedPRs' | 'fetchRecentlyMergedPRs'>, warnings: DailyWarning[]): Promise<RecentPRLists>;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The daily run's recently closed and recently merged PR lists (#1928).
3
+ * Split out of daily.ts so a failed or partial list is recorded in one place:
4
+ * both land in `warnings[]`, and a merged list that may be missing entries is
5
+ * named as a reason to distrust "no successor PR exists" (Phase 3.6).
6
+ *
7
+ * "Truncation" here is the recent-list truncation (these two 7-day lists),
8
+ * not the count-search truncation of the all-time merged and closed counts.
9
+ */
10
+ import { recordWarning } from './daily-warnings.js';
11
+ const TRUNCATED_OPERATION = 'fetch recent PRs (truncated)';
12
+ /** Successor-gap reason for a partial merged list; it ends up in the "withheld" warning next to each PR. */
13
+ const MERGED_LIST_TRUNCATED_REASON = 'the recently-merged list was truncated; release the claim by hand if no PR replaced this one, the automatic release stays off while the list is over the page cap';
14
+ /**
15
+ * The list, or undefined (with a warning) when its fetch failed. Rate-limit
16
+ * and auth errors are a warning here too, as they were before #1928:
17
+ * rethrowing would end the whole daily run where it used to degrade.
18
+ */
19
+ async function fetchOrWarn(fetch, operation, warnings) {
20
+ try {
21
+ return await fetch;
22
+ }
23
+ catch (error) {
24
+ recordWarning(warnings, 'fetch', operation, error);
25
+ return undefined;
26
+ }
27
+ }
28
+ /**
29
+ * Fetch both lists in parallel. Neither failure is fatal: a failed fetch is
30
+ * a warning and an empty list. A partial list (page cap reached, or GitHub
31
+ * flagged the search incomplete) is kept and reported as a warning; for the
32
+ * merged list it is also a successor gap, like a failed fetch.
33
+ */
34
+ export async function fetchRecentPRLists(prMonitor, warnings) {
35
+ const closedTruncations = [];
36
+ const mergedTruncations = [];
37
+ const [closed, merged] = await Promise.all([
38
+ fetchOrWarn(prMonitor.fetchRecentlyClosedPRs(7, closedTruncations), 'fetch recently closed PRs', warnings),
39
+ fetchOrWarn(prMonitor.fetchRecentlyMergedPRs(7, mergedTruncations), 'fetch recently merged PRs', warnings),
40
+ ]);
41
+ for (const { message } of [closedTruncations, mergedTruncations].flat()) {
42
+ warnings.push({ message, phase: 'fetch', operation: TRUNCATED_OPERATION });
43
+ }
44
+ const successorGapReasons = [];
45
+ if (merged === undefined)
46
+ successorGapReasons.push('the recently-merged fetch failed');
47
+ if (mergedTruncations.length > 0)
48
+ successorGapReasons.push(MERGED_LIST_TRUNCATED_REASON);
49
+ return {
50
+ successorGapReasons,
51
+ recentlyClosedPRs: closed ?? [],
52
+ recentlyMergedPRs: merged ?? [],
53
+ recentlyMergedFetchFailed: merged === undefined,
54
+ };
55
+ }
@@ -14,6 +14,7 @@
14
14
  * Tests for these renderers live alongside the aggregations test
15
15
  * (daily-logic.test.ts) — pure rendering, easy to assert on string output.
16
16
  */
17
+ import { type PacingStatus } from '../core/pacing.js';
17
18
  import type { CapacityAssessment, CommentedIssue, CommentedIssueWithResponse, DailyDigest, MaintainerActionHint } from '../core/types.js';
18
19
  import type { AttentionSummary } from '../core/pr-attention.js';
19
20
  /**
@@ -31,7 +32,7 @@ export declare function formatBriefSummary(digest: DailyDigest, issueCount: numb
31
32
  * Used in JSON output for Claude to display verbatim — includes all PR sections,
32
33
  * issue replies, and capacity status.
33
34
  */
34
- export declare function formatSummary(digest: DailyDigest, capacity: CapacityAssessment, issueResponses?: CommentedIssueWithResponse[]): string;
35
+ export declare function formatSummary(digest: DailyDigest, capacity: CapacityAssessment, issueResponses?: CommentedIssueWithResponse[], pacing?: PacingStatus | null): string;
35
36
  /**
36
37
  * Print digest to console as plain text. Unified renderer: uses the same
37
38
  * section ordering as {@link formatSummary} but outputs plain text with