@oss-autopilot/core 3.35.0 → 3.37.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 (49) hide show
  1. package/dist/cli-registry.js +25 -2
  2. package/dist/cli.bundle.cjs +142 -118
  3. package/dist/commands/daily.js +21 -2
  4. package/dist/commands/ledger-backfill.d.ts +7 -0
  5. package/dist/commands/ledger-backfill.js +116 -6
  6. package/dist/commands/repo-cap.d.ts +10 -0
  7. package/dist/commands/repo-cap.js +23 -0
  8. package/dist/commands/scout-bridge.js +8 -2
  9. package/dist/commands/search.js +7 -1
  10. package/dist/commands/setup.js +6 -4
  11. package/dist/commands/vet-list.js +20 -17
  12. package/dist/commands/vet.js +29 -2
  13. package/dist/core/ci-analysis.js +14 -1
  14. package/dist/core/comment-utils.d.ts +5 -2
  15. package/dist/core/comment-utils.js +11 -3
  16. package/dist/core/config-registry.js +12 -0
  17. package/dist/core/daily-logic.d.ts +36 -1
  18. package/dist/core/daily-logic.js +113 -3
  19. package/dist/core/eval-report.d.ts +8 -0
  20. package/dist/core/eval-report.js +81 -4
  21. package/dist/core/index.d.ts +4 -4
  22. package/dist/core/index.js +4 -4
  23. package/dist/core/issue-verification.d.ts +12 -0
  24. package/dist/core/issue-verification.js +18 -0
  25. package/dist/core/pick-snapshot.d.ts +19 -2
  26. package/dist/core/pick-snapshot.js +27 -1
  27. package/dist/core/pr-assembly.d.ts +11 -1
  28. package/dist/core/pr-assembly.js +21 -4
  29. package/dist/core/pr-attention.d.ts +14 -0
  30. package/dist/core/pr-attention.js +18 -0
  31. package/dist/core/pr-graphql.d.ts +31 -1
  32. package/dist/core/pr-graphql.js +49 -5
  33. package/dist/core/pr-monitor.d.ts +37 -6
  34. package/dist/core/pr-monitor.js +41 -12
  35. package/dist/core/repo-cap.d.ts +46 -0
  36. package/dist/core/repo-cap.js +102 -0
  37. package/dist/core/repo-score-manager.d.ts +0 -13
  38. package/dist/core/repo-score-manager.js +0 -24
  39. package/dist/core/review-analysis.d.ts +98 -14
  40. package/dist/core/review-analysis.js +145 -25
  41. package/dist/core/state-schema.d.ts +58 -0
  42. package/dist/core/state-schema.js +37 -0
  43. package/dist/core/state.d.ts +8 -15
  44. package/dist/core/state.js +19 -24
  45. package/dist/core/status-determination.js +11 -11
  46. package/dist/core/types.d.ts +32 -2
  47. package/dist/formatters/json.d.ts +29 -0
  48. package/dist/formatters/json.js +17 -0
  49. package/package.json +1 -1
@@ -42,6 +42,20 @@ export type AttentionInput = Pick<FetchedPR, 'status' | 'ciStatus' | 'reviewDeci
42
42
  * diverge on what a count means.
43
43
  */
44
44
  export declare function classifyAttentionBucket(pr: AttentionInput): AttentionBucket;
45
+ /**
46
+ * Unanswered contributor pings after which a dormant PR becomes a
47
+ * close-with-offer-to-reopen candidate instead of another nudge.
48
+ */
49
+ export declare const CLOSE_SUGGESTION_MIN_PINGS = 2;
50
+ /**
51
+ * True when a PR is dormant on the maintainer clock (`stalenessTier`, which
52
+ * ignores the contributor's own activity), still waiting on the maintainer,
53
+ * and the contributor has already pinged at least
54
+ * {@link CLOSE_SUGGESTION_MIN_PINGS} times with no reply. Surfaced through
55
+ * the dormant follow-up workflow as a suggestion only; nothing is closed or
56
+ * posted automatically.
57
+ */
58
+ export declare function shouldSuggestClose(pr: Pick<FetchedPR, 'status' | 'stalenessTier' | 'authorPingsSinceMaintainerActivity'>): boolean;
45
59
  export interface AttentionSummary {
46
60
  needsAttention: number;
47
61
  stuckCI: number;
@@ -49,6 +49,24 @@ export function classifyAttentionBucket(pr) {
49
49
  }
50
50
  return 'waiting';
51
51
  }
52
+ /**
53
+ * Unanswered contributor pings after which a dormant PR becomes a
54
+ * close-with-offer-to-reopen candidate instead of another nudge.
55
+ */
56
+ export const CLOSE_SUGGESTION_MIN_PINGS = 2;
57
+ /**
58
+ * True when a PR is dormant on the maintainer clock (`stalenessTier`, which
59
+ * ignores the contributor's own activity), still waiting on the maintainer,
60
+ * and the contributor has already pinged at least
61
+ * {@link CLOSE_SUGGESTION_MIN_PINGS} times with no reply. Surfaced through
62
+ * the dormant follow-up workflow as a suggestion only; nothing is closed or
63
+ * posted automatically.
64
+ */
65
+ export function shouldSuggestClose(pr) {
66
+ return (pr.status === 'waiting_on_maintainer' &&
67
+ pr.stalenessTier === 'dormant' &&
68
+ (pr.authorPingsSinceMaintainerActivity ?? 0) >= CLOSE_SUGGESTION_MIN_PINGS);
69
+ }
52
70
  /** Count PRs per bucket — the shape both headline surfaces render from. */
53
71
  export function summarizeAttentionBuckets(prs) {
54
72
  const summary = { needsAttention: 0, stuckCI: 0, dormantFollowup: 0, waiting: 0 };
@@ -24,7 +24,7 @@
24
24
  */
25
25
  import type { Octokit } from '@octokit/rest';
26
26
  import { CIStatusResult } from './types.js';
27
- import type { ReviewComment } from './review-analysis.js';
27
+ import type { ActivityEvent, ReviewComment } from './review-analysis.js';
28
28
  import type { AssemblyComment, AssemblyReview, CommitInfo } from './pr-assembly.js';
29
29
  /** PRs per aliased GraphQL query. GitHub recommends modest batch sizes; ~10 keeps
30
30
  * each query cheap (~1 point) and well under node/complexity limits. */
@@ -39,6 +39,10 @@ export declare const THREAD_COMMENTS_CAP = 20;
39
39
  * contexts than this is sent to REST so a failing check beyond the cap can't be
40
40
  * silently dropped and mislabel the PR as passing. */
41
41
  export declare const CI_CONTEXTS_CAP = 100;
42
+ /** Newest timeline events (commits, force-pushes, review requests, labels)
43
+ * requested per PR. Only the newest non-contributor event matters for the
44
+ * dormancy clock, so overflow is not routed to REST. */
45
+ export declare const TIMELINE_CAP = 50;
42
46
  /** A single PR to enrich. */
43
47
  export interface PRRef {
44
48
  owner: string;
@@ -64,6 +68,7 @@ export interface NormalizedPRData {
64
68
  comments: AssemblyComment[];
65
69
  reviews: AssemblyReview[];
66
70
  reviewComments: ReviewComment[];
71
+ activityEvents: ActivityEvent[];
67
72
  ciStatus: CIStatusResult;
68
73
  commitInfo: CommitInfo;
69
74
  }
@@ -79,6 +84,24 @@ interface GraphQLActor {
79
84
  login: string;
80
85
  __typename?: string;
81
86
  }
87
+ type GraphQLGitActor = {
88
+ user: {
89
+ login: string;
90
+ } | null;
91
+ } | null;
92
+ type GraphQLTimelineNode = {
93
+ __typename: 'PullRequestCommit';
94
+ commit: {
95
+ authoredDate: string | null;
96
+ committedDate: string | null;
97
+ author: GraphQLGitActor;
98
+ committer: GraphQLGitActor;
99
+ } | null;
100
+ } | {
101
+ __typename: 'HeadRefForcePushedEvent' | 'ReviewRequestedEvent' | 'LabeledEvent';
102
+ createdAt: string;
103
+ actor: GraphQLActor | null;
104
+ };
82
105
  interface GraphQLCheckRunNode {
83
106
  __typename: 'CheckRun';
84
107
  name: string;
@@ -129,6 +152,7 @@ interface GraphQLPullRequestNode {
129
152
  totalCount: number;
130
153
  nodes: Array<{
131
154
  author: GraphQLActor | null;
155
+ authorAssociation?: string | null;
132
156
  body: string | null;
133
157
  createdAt: string;
134
158
  }>;
@@ -141,6 +165,7 @@ interface GraphQLPullRequestNode {
141
165
  body: string | null;
142
166
  submittedAt: string | null;
143
167
  author: GraphQLActor | null;
168
+ authorAssociation?: string | null;
144
169
  }>;
145
170
  };
146
171
  reviewThreads: {
@@ -153,6 +178,7 @@ interface GraphQLPullRequestNode {
153
178
  body: string | null;
154
179
  createdAt: string;
155
180
  author: GraphQLActor | null;
181
+ authorAssociation?: string | null;
156
182
  replyTo: {
157
183
  databaseId: number | null;
158
184
  } | null;
@@ -168,6 +194,10 @@ interface GraphQLPullRequestNode {
168
194
  commit: GraphQLCommitNode;
169
195
  }>;
170
196
  };
197
+ /** Optional so nodes from older fixtures/producers still normalize. */
198
+ timelineItems?: {
199
+ nodes: GraphQLTimelineNode[];
200
+ } | null;
171
201
  }
172
202
  /**
173
203
  * Build a parameterized aliased GraphQL query for a batch of PRs. Owner / repo /
@@ -39,6 +39,10 @@ export const THREAD_COMMENTS_CAP = 20;
39
39
  * contexts than this is sent to REST so a failing check beyond the cap can't be
40
40
  * silently dropped and mislabel the PR as passing. */
41
41
  export const CI_CONTEXTS_CAP = 100;
42
+ /** Newest timeline events (commits, force-pushes, review requests, labels)
43
+ * requested per PR. Only the newest non-contributor event matters for the
44
+ * dormancy clock, so overflow is not routed to REST. */
45
+ export const TIMELINE_CAP = 50;
42
46
  /**
43
47
  * GraphQL reports a GitHub App as `__typename: 'Bot'` with a bare login, where
44
48
  * REST reports the same account as `login: 'name[bot]'`. Restore the REST spelling
@@ -47,6 +51,32 @@ export const CI_CONTEXTS_CAP = 100;
47
51
  function restLogin(actor) {
48
52
  return actor.__typename === 'Bot' && !actor.login.endsWith('[bot]') ? `${actor.login}[bot]` : actor.login;
49
53
  }
54
+ /** REST-shaped `user` (login + type) for a GraphQL actor, so REST and GraphQL agree on bots. */
55
+ function restUser(actor) {
56
+ return actor ? { login: restLogin(actor), type: actor.__typename } : null;
57
+ }
58
+ /** Flatten timeline nodes into activity events (commits yield author and committer). */
59
+ function toActivityEvents(nodes) {
60
+ return nodes.flatMap((n) => {
61
+ if (n.__typename === 'PullRequestCommit') {
62
+ const c = n.commit;
63
+ if (!c)
64
+ return [];
65
+ return [
66
+ { login: c.author?.user?.login, at: c.authoredDate, isPush: true },
67
+ { login: c.committer?.user?.login, at: c.committedDate, isPush: true },
68
+ ];
69
+ }
70
+ return [
71
+ {
72
+ login: n.actor ? restLogin(n.actor) : null,
73
+ type: n.actor?.__typename,
74
+ at: n.createdAt,
75
+ isPush: n.__typename === 'HeadRefForcePushedEvent',
76
+ },
77
+ ];
78
+ });
79
+ }
50
80
  const PR_FIELDS = `
51
81
  databaseId
52
82
  number
@@ -58,11 +88,11 @@ const PR_FIELDS = `
58
88
  updatedAt
59
89
  comments(last: ${COMMENTS_CAP}) {
60
90
  totalCount
61
- nodes { author { login __typename } body createdAt }
91
+ nodes { author { login __typename } authorAssociation body createdAt }
62
92
  }
63
93
  reviews(last: ${REVIEWS_CAP}) {
64
94
  totalCount
65
- nodes { databaseId state body submittedAt author { login __typename } }
95
+ nodes { databaseId state body submittedAt author { login __typename } authorAssociation }
66
96
  }
67
97
  reviewThreads(last: ${REVIEW_THREADS_CAP}) {
68
98
  totalCount
@@ -74,12 +104,22 @@ const PR_FIELDS = `
74
104
  body
75
105
  createdAt
76
106
  author { login __typename }
107
+ authorAssociation
77
108
  replyTo { databaseId }
78
109
  pullRequestReview { databaseId }
79
110
  }
80
111
  }
81
112
  }
82
113
  }
114
+ timelineItems(last: ${TIMELINE_CAP}, itemTypes: [PULL_REQUEST_COMMIT, HEAD_REF_FORCE_PUSHED_EVENT, REVIEW_REQUESTED_EVENT, LABELED_EVENT]) {
115
+ nodes {
116
+ __typename
117
+ ... on PullRequestCommit { commit { authoredDate committedDate author { user { login } } committer { user { login } } } }
118
+ ... on HeadRefForcePushedEvent { createdAt actor { login __typename } }
119
+ ... on ReviewRequestedEvent { createdAt actor { login __typename } }
120
+ ... on LabeledEvent { createdAt actor { login __typename } }
121
+ }
122
+ }
83
123
  commits(last: 1) {
84
124
  nodes {
85
125
  commit {
@@ -172,7 +212,8 @@ export function normalizePRNode(node) {
172
212
  return { kind: 'overflow' };
173
213
  }
174
214
  const comments = node.comments.nodes.map((c) => ({
175
- user: c.author ? { login: restLogin(c.author) } : null,
215
+ user: restUser(c.author),
216
+ author_association: c.authorAssociation,
176
217
  body: c.body,
177
218
  created_at: c.createdAt,
178
219
  }));
@@ -181,7 +222,8 @@ export function normalizePRNode(node) {
181
222
  const reviews = node.reviews.nodes
182
223
  .filter((r) => r.state !== 'PENDING')
183
224
  .map((r) => ({
184
- user: r.author ? { login: restLogin(r.author) } : null,
225
+ user: restUser(r.author),
226
+ author_association: r.authorAssociation,
185
227
  body: r.body,
186
228
  submitted_at: r.submittedAt,
187
229
  state: r.state,
@@ -189,7 +231,8 @@ export function normalizePRNode(node) {
189
231
  }));
190
232
  const reviewComments = node.reviewThreads.nodes.flatMap((thread) => thread.comments.nodes.map((c) => ({
191
233
  id: c.databaseId ?? 0,
192
- user: c.author ? { login: restLogin(c.author) } : null,
234
+ user: restUser(c.author),
235
+ author_association: c.authorAssociation,
193
236
  body: c.body,
194
237
  created_at: c.createdAt,
195
238
  in_reply_to_id: c.replyTo?.databaseId ?? undefined,
@@ -213,6 +256,7 @@ export function normalizePRNode(node) {
213
256
  comments,
214
257
  reviews,
215
258
  reviewComments,
259
+ activityEvents: toActivityEvents(node.timelineItems?.nodes ?? []),
216
260
  ciStatus: toCIStatus(commit),
217
261
  commitInfo,
218
262
  },
@@ -13,6 +13,7 @@
13
13
  * - status-determination.ts: PR status classification logic
14
14
  */
15
15
  import { FetchedPR, DailyDigest, ClosedPR, MergedPR, StarFilter } from './types.js';
16
+ import { type ActivityEvent } from './review-analysis.js';
16
17
  import { type PRCountsResult } from './github-stats.js';
17
18
  export { computeDisplayLabel } from './display-utils.js';
18
19
  export { categorizeCIStatus, classifyCICheck, classifyFailingChecks, getCIStatus } from './ci-analysis.js';
@@ -87,6 +88,14 @@ export declare class PRMonitor {
87
88
  * the computed status is identical regardless of transport.
88
89
  */
89
90
  private fetchPRDetails;
91
+ /**
92
+ * REST counterpart of the GraphQL `timelineItems` selection: commits (author
93
+ * and committer) plus force-push / review-request / label events, used for
94
+ * the maintainer-activity dormancy clock. Non-critical: rate-limit and auth
95
+ * errors propagate, anything else degrades to no events (comments and
96
+ * reviews still drive the clock).
97
+ */
98
+ private fetchActivityEvents;
90
99
  /**
91
100
  * Fetch the HEAD commit's author date and login via REST `repos.getCommit`.
92
101
  * Rate-limit errors propagate (silently swallowing them produces misleading
@@ -143,10 +152,32 @@ export declare class PRMonitor {
143
152
  * @returns Daily digest with categorized PRs and summary stats
144
153
  */
145
154
  generateDigest(prs: FetchedPR[], recentlyClosedPRs?: ClosedPR[], recentlyMergedPRs?: MergedPR[]): DailyDigest;
146
- /**
147
- * Update repository scores based on observed PR (called when we detect merged/closed PRs).
148
- * @param repo - Repository in "owner/repo" format
149
- * @param wasMerged - true if the PR was merged, false if closed without merge
150
- */
151
- updateRepoScoreFromObservedPR(repo: string, wasMerged: boolean): Promise<void>;
152
155
  }
156
+ interface RestTimelineEvent {
157
+ event?: string;
158
+ created_at?: string;
159
+ actor?: {
160
+ login?: string;
161
+ type?: string;
162
+ } | null;
163
+ }
164
+ interface RestPRCommit {
165
+ author?: {
166
+ login?: string;
167
+ type?: string;
168
+ } | null;
169
+ committer?: {
170
+ login?: string;
171
+ type?: string;
172
+ } | null;
173
+ commit: {
174
+ author?: {
175
+ date?: string;
176
+ } | null;
177
+ committer?: {
178
+ date?: string;
179
+ } | null;
180
+ };
181
+ }
182
+ /** Map REST timeline events and PR commits into {@link ActivityEvent}s (mirrors the GraphQL mapping). */
183
+ export declare function restActivityEvents(timeline: RestTimelineEvent[], commits: RestPRCommit[]): ActivityEvent[];
@@ -365,6 +365,7 @@ export class PRMonitor {
365
365
  }
366
366
  const ghPR = prResponse.data;
367
367
  const reviews = reviewsResult.items;
368
+ const activityEvents = await this.fetchActivityEvents(owner, repo, number);
368
369
  const ciStatus = await getCIStatus(this.octokit, owner, repo, ghPR.head.sha);
369
370
  // The commit date is only consulted (and only fetched) when the PR has an
370
371
  // unresponded maintainer comment or a changes-requested review — the shared
@@ -388,9 +389,32 @@ export class PRMonitor {
388
389
  comments,
389
390
  reviews,
390
391
  reviewComments,
392
+ activityEvents,
391
393
  ciStatus,
392
394
  }, config, commitInfo);
393
395
  }
396
+ /**
397
+ * REST counterpart of the GraphQL `timelineItems` selection: commits (author
398
+ * and committer) plus force-push / review-request / label events, used for
399
+ * the maintainer-activity dormancy clock. Non-critical: rate-limit and auth
400
+ * errors propagate, anything else degrades to no events (comments and
401
+ * reviews still drive the clock).
402
+ */
403
+ async fetchActivityEvents(owner, repo, number) {
404
+ try {
405
+ const [timeline, commits] = await Promise.all([
406
+ paginateAllDetailed((page) => this.octokit.issues.listEventsForTimeline({ owner, repo, page, issue_number: number, per_page: 100 })),
407
+ paginateAllDetailed((page) => this.octokit.pulls.listCommits({ owner, repo, page, pull_number: number, per_page: 100 })),
408
+ ]);
409
+ return restActivityEvents(timeline.items, commits.items);
410
+ }
411
+ catch (err) {
412
+ if (isRateLimitOrAuthError(err))
413
+ throw err;
414
+ warn(MODULE, `Failed to fetch timeline for ${owner}/${repo}#${number}: ${errorMessage(err)}`);
415
+ return [];
416
+ }
417
+ }
394
418
  /**
395
419
  * Fetch the HEAD commit's author date and login via REST `repos.getCommit`.
396
420
  * Rate-limit errors propagate (silently swallowing them produces misleading
@@ -443,6 +467,7 @@ export class PRMonitor {
443
467
  comments: data.comments,
444
468
  reviews: data.reviews,
445
469
  reviewComments: data.reviewComments,
470
+ activityEvents: data.activityEvents,
446
471
  ciStatus: data.ciStatus,
447
472
  }, config, data.commitInfo);
448
473
  }
@@ -567,17 +592,21 @@ export class PRMonitor {
567
592
  },
568
593
  };
569
594
  }
570
- /**
571
- * Update repository scores based on observed PR (called when we detect merged/closed PRs).
572
- * @param repo - Repository in "owner/repo" format
573
- * @param wasMerged - true if the PR was merged, false if closed without merge
574
- */
575
- async updateRepoScoreFromObservedPR(repo, wasMerged) {
576
- if (wasMerged) {
577
- this.stateManager.incrementMergedCount(repo);
578
- }
579
- else {
580
- this.stateManager.incrementClosedCount(repo);
581
- }
595
+ }
596
+ /** Timeline event kinds whose actor marks maintainer engagement. */
597
+ const ACTIVITY_TIMELINE_EVENTS = new Set(['head_ref_force_pushed', 'review_requested', 'labeled']);
598
+ /** Map REST timeline events and PR commits into {@link ActivityEvent}s (mirrors the GraphQL mapping). */
599
+ export function restActivityEvents(timeline, commits) {
600
+ const events = timeline
601
+ .filter((e) => e.event && ACTIVITY_TIMELINE_EVENTS.has(e.event))
602
+ .map((e) => ({
603
+ login: e.actor?.login,
604
+ type: e.actor?.type,
605
+ at: e.created_at,
606
+ isPush: e.event === 'head_ref_force_pushed',
607
+ }));
608
+ for (const c of commits) {
609
+ events.push({ login: c.author?.login, type: c.author?.type, at: c.commit.author?.date, isPush: true }, { login: c.committer?.login, type: c.committer?.type, at: c.commit.committer?.date, isPush: true });
582
610
  }
611
+ return events;
583
612
  }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Per-repo open-PR cap. First PRs into a repo merge less often than later
3
+ * ones, so discovery leaves a repo out once the user has
4
+ * `maxOpenPRsColdRepo` open PRs there while none of their PRs in it have
5
+ * merged, or `maxOpenPRsPerRepo` open PRs in any repo (off by default).
6
+ * 0 disables either cap.
7
+ *
8
+ * Discovery counts open PRs from the last digest (`state.lastDigest.openPRs`),
9
+ * as fresh as the last `daily` run. The `repo-cap` command passes a live
10
+ * count from GitHub instead.
11
+ */
12
+ import type { AgentState } from './state-schema.js';
13
+ export interface RepoCapStatus {
14
+ repo: string;
15
+ openPRCount: number;
16
+ /** Where `openPRCount` came from: the last digest, or a live GitHub search. */
17
+ countSource: 'digest' | 'github';
18
+ mergedPRCount: number;
19
+ /** True while the user has no merged PR in this repo, so the cold cap applies. */
20
+ cold: boolean;
21
+ /** The cap that applies (0 = no cap). */
22
+ cap: number;
23
+ atCap: boolean;
24
+ /** The repo is in `config.excludeRepos`. */
25
+ excluded: boolean;
26
+ /** Human-readable reason, set when `atCap` or `excluded`. */
27
+ reason?: string;
28
+ }
29
+ /** Open-PR counts from the last digest, keyed by lowercased owner/repo. */
30
+ export declare function openPRCountsByRepo(state: Readonly<AgentState>): Map<string, number>;
31
+ /**
32
+ * Cap status for one repo. `openPRCount` defaults to the digest count; pass a
33
+ * live count (with `countSource: 'github'`) to override it.
34
+ */
35
+ export declare function getRepoCapStatus(state: Readonly<AgentState>, repo: string, live?: {
36
+ openPRCount: number;
37
+ }): RepoCapStatus;
38
+ /**
39
+ * Repos (owner/repo, first spelling seen in the digest) at their open-PR cap,
40
+ * from the last digest. Discovery passes these to scout as excluded repos.
41
+ */
42
+ export declare function reposAtCap(state: Readonly<AgentState>): string[];
43
+ /** `{ repoCap }` when the repo is at cap or excluded, else `{}`; spread into vet output. */
44
+ export declare function repoCapField(state: Readonly<AgentState>, repo: string): {
45
+ repoCap?: RepoCapStatus;
46
+ };
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Per-repo open-PR cap. First PRs into a repo merge less often than later
3
+ * ones, so discovery leaves a repo out once the user has
4
+ * `maxOpenPRsColdRepo` open PRs there while none of their PRs in it have
5
+ * merged, or `maxOpenPRsPerRepo` open PRs in any repo (off by default).
6
+ * 0 disables either cap.
7
+ *
8
+ * Discovery counts open PRs from the last digest (`state.lastDigest.openPRs`),
9
+ * as fresh as the last `daily` run. The `repo-cap` command passes a live
10
+ * count from GitHub instead.
11
+ */
12
+ import { parseGitHubUrl } from './urls.js';
13
+ /** Open-PR counts from the last digest, keyed by lowercased owner/repo. */
14
+ export function openPRCountsByRepo(state) {
15
+ const counts = new Map();
16
+ const openPRs = state.lastDigest?.openPRs;
17
+ if (!openPRs)
18
+ return counts;
19
+ for (const pr of openPRs) {
20
+ const key = pr.repo.toLowerCase();
21
+ counts.set(key, (counts.get(key) ?? 0) + 1);
22
+ }
23
+ return counts;
24
+ }
25
+ function mergedCount(state, repo) {
26
+ const key = repo.toLowerCase();
27
+ const scoreEntry = Object.entries(state.repoScores ?? {}).find(([r]) => r.toLowerCase() === key)?.[1];
28
+ const fromScore = scoreEntry?.mergedPRCount ?? 0;
29
+ if (fromScore > 0)
30
+ return fromScore;
31
+ // Fall back to the outcome ledger: repoScores can lag behind it.
32
+ return (state.mergedPRs ?? []).filter((pr) => {
33
+ const parsed = parseGitHubUrl(pr.url);
34
+ return parsed !== null && `${parsed.owner}/${parsed.repo}`.toLowerCase() === key;
35
+ }).length;
36
+ }
37
+ /** The tighter of the caps that apply (0 = none). */
38
+ function applicableCap(config, isCold) {
39
+ const { maxOpenPRsPerRepo = 0, maxOpenPRsColdRepo = 0 } = config;
40
+ const caps = [maxOpenPRsPerRepo, isCold ? maxOpenPRsColdRepo : 0].filter((c) => c > 0);
41
+ return caps.length > 0 ? Math.min(...caps) : 0;
42
+ }
43
+ function capReason(status) {
44
+ const reasons = [];
45
+ if (status.excluded)
46
+ reasons.push(`${status.repo} is in excludeRepos`);
47
+ if (status.atCap) {
48
+ const coldNote = status.cold ? ' for a repo where none of your PRs have merged yet' : '';
49
+ reasons.push(`${status.repo} has ${status.openPRCount} open PR(s), at the cap of ${status.cap}${coldNote}`);
50
+ }
51
+ return reasons.length > 0 ? reasons.join('; ') : undefined;
52
+ }
53
+ /**
54
+ * Cap status for one repo. `openPRCount` defaults to the digest count; pass a
55
+ * live count (with `countSource: 'github'`) to override it.
56
+ */
57
+ export function getRepoCapStatus(state, repo, live) {
58
+ // ponytail: tolerate partial states (test fixtures, hand-built mocks); a
59
+ // parsed AgentState always has these defaults.
60
+ const config = state.config ?? {};
61
+ const openPRCount = live?.openPRCount ?? openPRCountsByRepo(state).get(repo.toLowerCase()) ?? 0;
62
+ const merged = mergedCount(state, repo);
63
+ const isCold = merged === 0;
64
+ const limit = applicableCap(config, isCold);
65
+ const status = {
66
+ repo,
67
+ openPRCount,
68
+ countSource: live ? 'github' : 'digest',
69
+ mergedPRCount: merged,
70
+ cold: isCold,
71
+ cap: limit,
72
+ atCap: limit > 0 && openPRCount >= limit,
73
+ excluded: (config.excludeRepos ?? []).some((r) => r.toLowerCase() === repo.toLowerCase()),
74
+ };
75
+ const reason = capReason(status);
76
+ return reason ? { ...status, reason } : status;
77
+ }
78
+ /**
79
+ * Repos (owner/repo, first spelling seen in the digest) at their open-PR cap,
80
+ * from the last digest. Discovery passes these to scout as excluded repos.
81
+ */
82
+ export function reposAtCap(state) {
83
+ const openPRs = state.lastDigest?.openPRs;
84
+ if (!openPRs)
85
+ return [];
86
+ const seen = new Set();
87
+ const capped = [];
88
+ for (const pr of openPRs) {
89
+ const key = pr.repo.toLowerCase();
90
+ if (seen.has(key))
91
+ continue;
92
+ seen.add(key);
93
+ if (getRepoCapStatus(state, pr.repo).atCap)
94
+ capped.push(pr.repo);
95
+ }
96
+ return capped;
97
+ }
98
+ /** `{ repoCap }` when the repo is at cap or excluded, else `{}`; spread into vet output. */
99
+ export function repoCapField(state, repo) {
100
+ const status = getRepoCapStatus(state, repo);
101
+ return status.reason ? { repoCap: status } : {};
102
+ }
@@ -35,19 +35,6 @@ export declare function getRepoScore(state: Readonly<AgentState>, repo: string):
35
35
  * numeric score is recalculated.
36
36
  */
37
37
  export declare function updateRepoScore(state: AgentState, repo: string, updates: RepoScoreUpdate): void;
38
- /**
39
- * Increment the merged PR count for a repository and recalculate its score.
40
- */
41
- export declare function incrementMergedCount(state: AgentState, repo: string): void;
42
- /**
43
- * Increment the closed-without-merge count for a repository and recalculate its score.
44
- */
45
- export declare function incrementClosedCount(state: AgentState, repo: string): void;
46
- /**
47
- * Mark a repository as having hostile maintainer comments and recalculate its score.
48
- * This applies a -2 penalty to the score. Creates a default score record if needed.
49
- */
50
- export declare function markRepoHostile(state: AgentState, repo: string): void;
51
38
  /**
52
39
  * Get repositories where the user has at least one merged PR, sorted by merged count descending.
53
40
  */
@@ -155,30 +155,6 @@ export function updateRepoScore(state, repo, updates) {
155
155
  }
156
156
  debug(MODULE, `Updated repo score for ${repo}: ${repoScore.score}/10`);
157
157
  }
158
- /**
159
- * Increment the merged PR count for a repository and recalculate its score.
160
- */
161
- export function incrementMergedCount(state, repo) {
162
- const newCount = (state.repoScores[repo]?.mergedPRCount ?? 0) + 1;
163
- updateRepoScore(state, repo, {
164
- mergedPRCount: newCount,
165
- lastMergedAt: new Date().toISOString(),
166
- });
167
- }
168
- /**
169
- * Increment the closed-without-merge count for a repository and recalculate its score.
170
- */
171
- export function incrementClosedCount(state, repo) {
172
- const newCount = (state.repoScores[repo]?.closedWithoutMergeCount ?? 0) + 1;
173
- updateRepoScore(state, repo, { closedWithoutMergeCount: newCount });
174
- }
175
- /**
176
- * Mark a repository as having hostile maintainer comments and recalculate its score.
177
- * This applies a -2 penalty to the score. Creates a default score record if needed.
178
- */
179
- export function markRepoHostile(state, repo) {
180
- updateRepoScore(state, repo, { signals: { hasHostileComments: true } });
181
- }
182
158
  /**
183
159
  * Get repositories where the user has at least one merged PR, sorted by merged count descending.
184
160
  */