@oss-autopilot/core 3.34.0 → 3.36.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 (44) hide show
  1. package/dist/cli-registry.js +24 -1
  2. package/dist/cli.bundle.cjs +136 -125
  3. package/dist/commands/daily.js +5 -2
  4. package/dist/commands/ledger-backfill.js +15 -9
  5. package/dist/commands/repo-cap.d.ts +10 -0
  6. package/dist/commands/repo-cap.js +23 -0
  7. package/dist/commands/scout-bridge.js +8 -2
  8. package/dist/commands/search.js +7 -1
  9. package/dist/commands/setup.js +6 -4
  10. package/dist/commands/vet-list.js +2 -0
  11. package/dist/commands/vet.js +2 -0
  12. package/dist/core/ci-analysis.js +14 -1
  13. package/dist/core/close-reason.d.ts +11 -0
  14. package/dist/core/close-reason.js +29 -1
  15. package/dist/core/comment-utils.d.ts +5 -2
  16. package/dist/core/comment-utils.js +11 -3
  17. package/dist/core/config-registry.js +12 -0
  18. package/dist/core/daily-logic.d.ts +3 -1
  19. package/dist/core/daily-logic.js +11 -3
  20. package/dist/core/eval-report.js +3 -1
  21. package/dist/core/gist-state-store.js +4 -1
  22. package/dist/core/index.d.ts +1 -1
  23. package/dist/core/index.js +1 -1
  24. package/dist/core/pr-assembly.d.ts +11 -1
  25. package/dist/core/pr-assembly.js +21 -4
  26. package/dist/core/pr-attention.d.ts +14 -0
  27. package/dist/core/pr-attention.js +18 -0
  28. package/dist/core/pr-graphql.d.ts +31 -1
  29. package/dist/core/pr-graphql.js +49 -5
  30. package/dist/core/pr-monitor.d.ts +37 -0
  31. package/dist/core/pr-monitor.js +42 -0
  32. package/dist/core/repo-cap.d.ts +46 -0
  33. package/dist/core/repo-cap.js +102 -0
  34. package/dist/core/review-analysis.d.ts +64 -0
  35. package/dist/core/review-analysis.js +92 -1
  36. package/dist/core/state-persistence.js +6 -2
  37. package/dist/core/state-schema.d.ts +285 -87
  38. package/dist/core/state-schema.js +91 -27
  39. package/dist/core/state.js +1 -0
  40. package/dist/core/status-determination.js +11 -11
  41. package/dist/core/types.d.ts +32 -2
  42. package/dist/formatters/json.d.ts +25 -0
  43. package/dist/formatters/json.js +13 -0
  44. package/package.json +1 -1
@@ -6,7 +6,7 @@
6
6
  * Domain logic lives in src/core/daily-logic.ts; this file is a thin
7
7
  * orchestration layer that wires up the phases and handles I/O.
8
8
  */
9
- import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, } from '../core/index.js';
9
+ import { getStateManager, parseGitHubUrl, PRMonitor, IssueConversationMonitor, requireGitHubToken, renderGistWarning, CRITICAL_STATUSES, applyStatusOverrides, computeRepoSignals, groupPRsByRepo, assessCapacity, collectActionableIssues, computeActionMenu, toShelvedPRRef, formatBriefSummary, formatSummary, summarizeAttentionBuckets, shouldSuggestClose, } from '../core/index.js';
10
10
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
11
11
  import { wrapUntrustedContent } from '../core/untrusted-content.js';
12
12
  import { computeStrategy, shouldComputeStrategy } from '../core/strategy.js';
@@ -492,7 +492,10 @@ function generateDigestOutput(digest, activePRs, shelvedPRs, commentedIssues, fa
492
492
  // the same buckets per-PR, so the headline counts cannot diverge.
493
493
  const attention = summarizeAttentionBuckets(activePRs);
494
494
  const briefSummary = formatBriefSummary(digest, actionableIssues.length, issueResponses.length, attention);
495
- const actionMenu = computeActionMenu(actionableIssues, capacity, filteredCommentedIssues, attention, unextractedMergeCount);
495
+ // Close candidates are usually dormant and auto-shelved, so count them over
496
+ // all open PRs (digest.openPRs includes shelved), not activePRs.
497
+ const closeSuggested = digest.openPRs.filter(shouldSuggestClose).length;
498
+ const actionMenu = computeActionMenu(actionableIssues, capacity, filteredCommentedIssues, { ...attention, closeSuggested }, unextractedMergeCount);
496
499
  const repoGroups = groupPRsByRepo(activePRs);
497
500
  // Periodic strategy snapshot (#1270 Step 2). Cadence-gated to fire every
498
501
  // 30 days OR after 5+ PRs merge since the last snapshot, whichever comes
@@ -19,7 +19,7 @@
19
19
  */
20
20
  import * as fs from 'node:fs';
21
21
  import * as path from 'node:path';
22
- import { classifyCloseReason } from '../core/close-reason.js';
22
+ import { classifyCloseReason, classifySelfClose } from '../core/close-reason.js';
23
23
  import { errorMessage, isRateLimitOrAuthError } from '../core/errors.js';
24
24
  import { getOctokit, requireGitHubToken, getStateManager, parseGitHubUrl } from '../core/index.js';
25
25
  import { isGraphqlRateLimited } from '../core/pr-graphql.js';
@@ -135,10 +135,14 @@ export async function runLedgerBackfill(options = {}) {
135
135
  if (!listPath)
136
136
  warnings.push('no curated issue list found; list vet scores were not imported');
137
137
  const lists = listPath ? readListFiles(listPath, warnings) : [];
138
- // 1. GitHub: openedAt, closing issue, close reason, for entries not yet backfilled.
139
- const needsFetch = [...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()]
140
- .filter((e) => !e.backfilledAt)
141
- .map((e) => e.url);
138
+ // 1. GitHub: openedAt, closing issue, close reason, for entries not yet
139
+ // backfilled, plus self-closed entries recorded before selfCloseReason existed.
140
+ const needsFetch = [
141
+ ...stateManager.getMergedPRs().filter((e) => !e.backfilledAt),
142
+ ...stateManager
143
+ .getClosedPRs()
144
+ .filter((e) => !e.backfilledAt || (e.closeReason === 'self-closed' && !e.selfCloseReason)),
145
+ ].map((e) => e.url);
142
146
  const nodes = new Map();
143
147
  let fatal;
144
148
  if (needsFetch.length > 0) {
@@ -185,15 +189,17 @@ export async function runLedgerBackfill(options = {}) {
185
189
  const node = nodes.get(e.url);
186
190
  const closedEvent = node?.timelineItems?.nodes.at(-1);
187
191
  // No closed event in the answer: leave the reason unset rather than guess.
188
- const closeReason = closedEvent
189
- ? classifyCloseReason({
192
+ const context = closedEvent
193
+ ? {
190
194
  author: node?.author?.login,
191
195
  closer: closedEvent.actor?.login,
192
196
  closerIsBot: closedEvent.actor?.__typename === 'Bot',
193
197
  comments: (node?.comments?.nodes ?? []).flatMap((c) => c ? [{ author: c.author?.login, isBot: c.author?.__typename === 'Bot', body: c.body }] : []),
194
- })
198
+ }
195
199
  : undefined;
196
- return { url: e.url, title: e.title, closedAt: e.closedAt, ...recovered(e), closeReason };
200
+ const closeReason = context && classifyCloseReason(context);
201
+ const selfCloseReason = context && (e.closeReason ?? closeReason) === 'self-closed' ? classifySelfClose(context) : undefined;
202
+ return { url: e.url, title: e.title, closedAt: e.closedAt, ...recovered(e), closeReason, selfCloseReason };
197
203
  }));
198
204
  });
199
205
  const after = countFilled([...stateManager.getMergedPRs(), ...stateManager.getClosedPRs()]);
@@ -0,0 +1,10 @@
1
+ /**
2
+ * repo-cap command: per-repo open-PR cap and excludeRepos check for one repo.
3
+ * Used by the draft-first workflow before pushing. The open-PR count is live
4
+ * from GitHub so PRs opened earlier in the same session count; merges (for
5
+ * the cold cap) come from local state.
6
+ */
7
+ import { type RepoCapStatus } from '../core/repo-cap.js';
8
+ export declare function runRepoCap(options: {
9
+ repo: string;
10
+ }): Promise<RepoCapStatus>;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * repo-cap command: per-repo open-PR cap and excludeRepos check for one repo.
3
+ * Used by the draft-first workflow before pushing. The open-PR count is live
4
+ * from GitHub so PRs opened earlier in the same session count; merges (for
5
+ * the cold cap) come from local state.
6
+ */
7
+ import { getOctokit, getStateManager, requireGitHubToken } from '../core/index.js';
8
+ import { ConfigurationError } from '../core/errors.js';
9
+ import { getRepoCapStatus } from '../core/repo-cap.js';
10
+ import { validateRepoIdentifier } from './validation.js';
11
+ export async function runRepoCap(options) {
12
+ const repo = validateRepoIdentifier(options.repo);
13
+ const state = getStateManager().getState();
14
+ const username = state.config.githubUsername;
15
+ if (!username) {
16
+ throw new ConfigurationError('githubUsername is not configured; run setup first.');
17
+ }
18
+ const { data } = await getOctokit(requireGitHubToken()).search.issuesAndPullRequests({
19
+ q: `is:pr is:open author:${username} repo:${repo}`,
20
+ per_page: 1,
21
+ });
22
+ return getRepoCapStatus(state, repo, { openPRCount: data.total_count });
23
+ }
@@ -2,6 +2,7 @@
2
2
  * Bridge between oss-autopilot's AgentState and oss-scout's OssScout API.
3
3
  * Maps state fields and creates scout instances for search/vet commands.
4
4
  */
5
+ import { reposAtCap } from '../core/repo-cap.js';
5
6
  import { createScout } from '@oss-scout/core';
6
7
  import { getStateManager, isLinkedPRStalled, parseGitHubUrl, requireGitHubToken } from '../core/index.js';
7
8
  import { SearchRotationSchema } from '../core/state-schema.js';
@@ -120,6 +121,11 @@ export function buildScoutState(diagnostics) {
120
121
  // count/anchorThreshold/splitRatio/broad), so preferences are the only
121
122
  // channel by which bias can reach the features path.
122
123
  const strategy = computeStrategy(state);
124
+ // Repos at the per-repo open-PR cap (core/repo-cap.ts) are excluded like
125
+ // excludeRepos, so they use no result slots or rotation entries in search
126
+ // and features, and are dropped from the affinity bias.
127
+ const cappedRepos = reposAtCap(state);
128
+ const cappedSet = new Set(cappedRepos.map((r) => r.toLowerCase()));
123
129
  return {
124
130
  version: 1,
125
131
  // Scout 1.8.1 made this required on the inferred ScoutState type. Scout
@@ -131,7 +137,7 @@ export function buildScoutState(diagnostics) {
131
137
  languages: config.languages,
132
138
  labels: config.labels,
133
139
  scope: config.scope,
134
- excludeRepos: config.excludeRepos,
140
+ excludeRepos: [...config.excludeRepos, ...cappedRepos],
135
141
  excludeOrgs: config.excludeOrgs ?? [],
136
142
  preferredOrgs: config.preferredOrgs ?? [],
137
143
  aiPolicyBlocklist: config.aiPolicyBlocklist,
@@ -167,7 +173,7 @@ export function buildScoutState(diagnostics) {
167
173
  // command uses per-call; avoidRepos/boostIssueTypes are user settings
168
174
  // (config-registry keys); diversityRatio matches the search policy.
169
175
  preferLanguages: strategy?.recommendations.languages ?? [],
170
- preferRepos: strategy?.recommendations.repos ?? [],
176
+ preferRepos: (strategy?.recommendations.repos ?? []).filter((r) => !cappedSet.has(r.toLowerCase())),
171
177
  diversityRatio: SEARCH_DIVERSITY_RATIO,
172
178
  avoidRepos: config.avoidRepos ?? [],
173
179
  boostIssueTypes: config.boostIssueTypes ?? [],
@@ -9,6 +9,7 @@ import { gradeFromCandidate, reconcileRecommendation } from '../core/issue-gradi
9
9
  import { computeStrategy } from '../core/strategy.js';
10
10
  import { refreshStarredReposIfStale } from '../core/starred-repos.js';
11
11
  import { debug, warn } from '../core/logger.js';
12
+ import { reposAtCap as findReposAtCap } from '../core/repo-cap.js';
12
13
  import { SCOUT_ROTATION_TTL_DAYS, SEARCH_SEEN_RETENTION_DAYS } from '../core/state-prune.js';
13
14
  const MODULE = 'search';
14
15
  /**
@@ -162,7 +163,11 @@ export async function runSearch(options) {
162
163
  // not passed per-call: scout reads them from the bridge-built preferences.
163
164
  const strategy = computeStrategy(stateManager.getState());
164
165
  const preferLanguages = strategy?.recommendations.languages ?? undefined;
165
- const preferRepos = strategy?.recommendations.repos ?? undefined;
166
+ // Repos at the per-repo open-PR cap are excluded inside scout (scout-bridge)
167
+ // so they use no result slots; keep the per-call bias from pulling them back.
168
+ const reposAtCap = findReposAtCap(stateManager.getState());
169
+ const cappedSet = new Set(reposAtCap.map((r) => r.toLowerCase()));
170
+ const preferRepos = strategy?.recommendations.repos?.filter((r) => !cappedSet.has(r.toLowerCase()));
166
171
  if (preferLanguages?.length || preferRepos?.length) {
167
172
  debug(MODULE, `Applying strategy bias to search: preferLanguages=${JSON.stringify(preferLanguages ?? [])}, preferRepos=${JSON.stringify(preferRepos ?? [])}`);
168
173
  }
@@ -276,6 +281,7 @@ export async function runSearch(options) {
276
281
  excludedRepos: result.excludedRepos,
277
282
  aiPolicyBlocklist: result.aiPolicyBlocklist,
278
283
  hiddenOwnPRCount,
284
+ reposAtCap,
279
285
  };
280
286
  if (gistSyncWarning) {
281
287
  searchOutput.gistSyncWarning = gistSyncWarning;
@@ -65,10 +65,12 @@ export async function runSetup(options) {
65
65
  results[key] = value;
66
66
  break;
67
67
  }
68
- case 'maxActivePRs': {
69
- const maxPRs = parseNonNegativeInt(value, 'maxActivePRs');
70
- stateManager.updateConfig({ maxActivePRs: maxPRs });
71
- results[key] = String(maxPRs);
68
+ case 'maxActivePRs':
69
+ case 'maxOpenPRsPerRepo':
70
+ case 'maxOpenPRsColdRepo': {
71
+ const limit = parseNonNegativeInt(value, key);
72
+ stateManager.updateConfig({ [key]: limit });
73
+ results[key] = String(limit);
72
74
  break;
73
75
  }
74
76
  case 'dormantDays': {
@@ -7,6 +7,7 @@ import { adaptScoutLinkedPR, buildCandidateLinkedPR, createAutopilotScout } from
7
7
  import { runParseList, pruneIssueList } from './parse-list.js';
8
8
  import { detectIssueList } from './startup.js';
9
9
  import { computeSuccessGrade, gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
10
+ import { repoCapField } from '../core/repo-cap.js';
10
11
  import { ValidationError } from '../core/errors.js';
11
12
  import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots, getOctokit, requireGitHubToken, parseGitHubUrl, verifyIssuesBatch, } from '../core/index.js';
12
13
  const UNKNOWN_GRADE = computeSuccessGrade({ avgResponseDays: null, mergeRate: null, daysSinceLastCommit: null });
@@ -238,6 +239,7 @@ export async function runVetList(options = {}) {
238
239
  ...(linkedPR && { linkedPR }),
239
240
  slmTriage: candidate.slmTriage ?? null,
240
241
  grade,
242
+ ...repoCapField(getStateManager().getState(), candidate.issue.repo),
241
243
  };
242
244
  const pick = recordPick ? pickSnapshotFromVet(vetResult, 'vet-list') : undefined;
243
245
  if (pick)
@@ -5,6 +5,7 @@
5
5
  import { adaptScoutLinkedPR, buildCandidateLinkedPR, createAutopilotScout } from './scout-bridge.js';
6
6
  import { ISSUE_URL_PATTERN, validateGitHubUrl, validateUrl } from './validation.js';
7
7
  import { gradeFromCandidate, reconcileRecommendation } from '../core/issue-grading.js';
8
+ import { repoCapField } from '../core/repo-cap.js';
8
9
  import { getStateManager, classifyLinkedPR, pickSnapshotFromVet, persistPickSnapshots } from '../core/index.js';
9
10
  /**
10
11
  * Vet a specific GitHub issue for claimability and project health.
@@ -48,6 +49,7 @@ export async function runVet(options) {
48
49
  ...(linkedPR && { linkedPR }),
49
50
  slmTriage: candidate.slmTriage ?? null,
50
51
  grade,
52
+ ...repoCapField(getStateManager().getState(), candidate.issue.repo),
51
53
  };
52
54
  const pick = pickSnapshotFromVet(output, 'vet');
53
55
  return { ...output, ...(await persistPickSnapshots(getStateManager(), pick ? [pick] : [])) };
@@ -32,8 +32,21 @@ const FORK_LIMITATION_PATTERNS = [
32
32
  /**
33
33
  * Known CI check name patterns that indicate authorization gates (#81).
34
34
  * These require maintainer approval and are not real failures.
35
+ * Label/triage gates (e.g. "check PR labels", "Check PR type labels",
36
+ * "needs-triage") are included: only maintainers can apply the labels that
37
+ * satisfy them, so the contributor has nothing to fix.
35
38
  */
36
- const AUTH_GATE_PATTERNS = [/authoriz/i, /approval/i, /\bcla\b/i, /license\/cla/i];
39
+ const AUTH_GATE_PATTERNS = [
40
+ /authoriz/i,
41
+ /approval/i,
42
+ /\bcla\b/i,
43
+ /license\/cla/i,
44
+ // Anchored to gate wording so real checks like "label-studio / build" or
45
+ // "e2e-label-tests" stay actionable.
46
+ /\b(?:pr|type|require[sd]?|check|missing)[\s-]+(?:\w+[\s-]+)?labels?\b/i,
47
+ /\blabeler\b/i,
48
+ /\btriage\b/i,
49
+ ];
37
50
  /**
38
51
  * Known CI check name patterns that indicate infrastructure/transient failures (#145).
39
52
  * These are runner issues, dependency install problems, or service outages — not code failures.
@@ -11,6 +11,12 @@
11
11
  */
12
12
  export declare const CLOSE_REASONS: readonly ["ai-policy", "superseded", "stale", "self-closed", "rejected", "unknown"];
13
13
  export type CloseReason = (typeof CLOSE_REASONS)[number];
14
+ /**
15
+ * Why the author closed their own PR (#1824): the "self-closed" bucket is
16
+ * most closures, and "I withdrew it" hides three different stories.
17
+ */
18
+ export declare const SELF_CLOSE_REASONS: readonly ["superseded", "no-traction", "after-feedback", "no-response"];
19
+ export type SelfCloseReason = (typeof SELF_CLOSE_REASONS)[number];
14
20
  export interface CloseContext {
15
21
  author?: string;
16
22
  /** Login of whoever closed the PR; undefined when GitHub reports no actor (ghost). */
@@ -22,4 +28,9 @@ export interface CloseContext {
22
28
  body: string;
23
29
  }>;
24
30
  }
31
+ /**
32
+ * Split an author-closed PR by what preceded the close. Call only when
33
+ * {@link classifyCloseReason} returned 'self-closed'.
34
+ */
35
+ export declare function classifySelfClose({ author, comments }: CloseContext): SelfCloseReason;
25
36
  export declare function classifyCloseReason({ author, closer, closerIsBot, comments }: CloseContext): CloseReason;
@@ -10,10 +10,38 @@
10
10
  * `rejected` turns out to hide distinct causes worth separating.
11
11
  */
12
12
  export const CLOSE_REASONS = ['ai-policy', 'superseded', 'stale', 'self-closed', 'rejected', 'unknown'];
13
+ /**
14
+ * Why the author closed their own PR (#1824): the "self-closed" bucket is
15
+ * most closures, and "I withdrew it" hides three different stories.
16
+ */
17
+ export const SELF_CLOSE_REASONS = ['superseded', 'no-traction', 'after-feedback', 'no-response'];
13
18
  // Policy phrasing only: a bare "AI" or "Claude" shows up in ordinary review talk.
14
19
  const AI_POLICY_RE = /\b(?:AI|LLM)[- ](?:generated|written|authored|slop|polic(?:y|ies))|(?:generated|written) (?:by|with) (?:an? )?(?:AI|LLM|ChatGPT|Copilot)\b|vibe[- ]?cod|machine[- ]generated/i;
15
- const SUPERSEDED_RE = /clos(?:e|ing) (?:this )?as (?:a )?duplicate|duplicate of #\d+|superseded by|already (?:been )?(?:fixed|merged|addressed|resolved|implemented)|fixed (?:in|by|via) #\d+|in fav(?:ou)?r of #\d+/i;
20
+ const SUPERSEDED_RE = /clos(?:e|ing) (?:this )?as (?:a )?duplicate|duplicate of #\d+|superseded by|already (?:been )?(?:fixed|merged|addressed|resolved|implemented)|fixed (?:in|by|via) #\d+|in favou?r of #\d+/i;
16
21
  const STALE_RE = /marked as stale|clos(?:e|ing) (?:this )?(?:as|due to) (?:stale|inactiv)|no activity (?:for|in)/i;
22
+ // The author's own explanation, phrased the way real closing comments are:
23
+ // "v0.6 covers this", "#1684 landed the same fix", "#1408 is in", "in favor of #6087".
24
+ const AUTHOR_SUPERSEDED = [
25
+ /already (?:been )?(?:fixed|merged|addressed|resolved|implemented|landed|applied|several)/i,
26
+ /cover(?:s|ed) (?:this|everything|the same)|same (?:one-line )?fix|(?:landed|fixed|ships?) the same/i,
27
+ /has (?:landed|shipped)|is in and|(?:fixed|addressed|resolved|landed|applied) (?:upstream|elsewhere)/i,
28
+ /upstream (?:upgrade|commit|fix)|supersed|in favou?r of|replaced by|duplicate/i,
29
+ /no longer (?:needed|relevant|reproduc|applies)/i,
30
+ ];
31
+ // Withdrawn because nobody picked it up.
32
+ const NO_TRACTION_RE = /traction|(?:been )?quiet|unmaintained|actively (?:reviewing|maintained)|not maintained|no (?:response|activity)|keep the queue tidy|sitting in (?:your|the) queue|stale/i;
33
+ /**
34
+ * Split an author-closed PR by what preceded the close. Call only when
35
+ * {@link classifyCloseReason} returned 'self-closed'.
36
+ */
37
+ export function classifySelfClose({ author, comments }) {
38
+ const own = comments.filter((c) => !c.isBot && c.author === author).map((c) => c.body);
39
+ if (own.some((b) => AUTHOR_SUPERSEDED.some((re) => re.test(b))))
40
+ return 'superseded';
41
+ if (own.some((b) => NO_TRACTION_RE.test(b)))
42
+ return 'no-traction';
43
+ return comments.some((c) => !c.isBot && c.author !== author) ? 'after-feedback' : 'no-response';
44
+ }
17
45
  export function classifyCloseReason({ author, closer, closerIsBot, comments }) {
18
46
  const human = comments.filter((c) => !c.isBot && c.author !== author).map((c) => c.body);
19
47
  if (human.some((b) => AI_POLICY_RE.test(b)))
@@ -4,9 +4,12 @@
4
4
  */
5
5
  /**
6
6
  * Check if a comment author is a bot account.
7
- * Matches the [bot] suffix convention and known bot usernames (case-insensitive).
7
+ * Matches the [bot] suffix convention (GitHub Apps; the GraphQL path maps
8
+ * `__typename: 'Bot'` to it), user-account bots named `*-bot` / `*-robot`
9
+ * (e.g. `miq-bot`, `k8s-ci-robot`), known bot usernames (case-insensitive),
10
+ * and REST `user.type === 'Bot'` when the caller has it (e.g. `Copilot`).
8
11
  */
9
- export declare function isBotAuthor(author: string): boolean;
12
+ export declare function isBotAuthor(author: string, userType?: string | null): boolean;
10
13
  /**
11
14
  * Detect acknowledgment comments that don't require a response.
12
15
  * Returns true only when: no question mark, matches an acknowledgment keyword, and under 100 chars.
@@ -8,6 +8,7 @@ const KNOWN_BOT_USERNAMES = new Set([
8
8
  'changeset-bot',
9
9
  'claassistant',
10
10
  'codecov-commenter',
11
+ 'copilot',
11
12
  'greenkeeper',
12
13
  'imgbot',
13
14
  'netlify',
@@ -16,13 +17,20 @@ const KNOWN_BOT_USERNAMES = new Set([
16
17
  'sonarcloud',
17
18
  'stale',
18
19
  'vercel',
20
+ 'web-flow',
19
21
  ]);
20
22
  /**
21
23
  * Check if a comment author is a bot account.
22
- * Matches the [bot] suffix convention and known bot usernames (case-insensitive).
24
+ * Matches the [bot] suffix convention (GitHub Apps; the GraphQL path maps
25
+ * `__typename: 'Bot'` to it), user-account bots named `*-bot` / `*-robot`
26
+ * (e.g. `miq-bot`, `k8s-ci-robot`), known bot usernames (case-insensitive),
27
+ * and REST `user.type === 'Bot'` when the caller has it (e.g. `Copilot`).
23
28
  */
24
- export function isBotAuthor(author) {
25
- return author.includes('[bot]') || KNOWN_BOT_USERNAMES.has(author.toLowerCase());
29
+ export function isBotAuthor(author, userType) {
30
+ if (userType === 'Bot')
31
+ return true;
32
+ const lower = author.toLowerCase();
33
+ return (lower.includes('[bot]') || lower.endsWith('-bot') || lower.endsWith('-robot') || KNOWN_BOT_USERNAMES.has(lower));
26
34
  }
27
35
  /**
28
36
  * Detect acknowledgment comments that don't require a response.
@@ -31,6 +31,18 @@ export const CONFIG_KEY_REGISTRY = [
31
31
  settableVia: 'setup',
32
32
  valueHint: 'non-negative integer (0 = no limit)',
33
33
  },
34
+ {
35
+ key: 'maxOpenPRsPerRepo',
36
+ description: 'Discovery leaves out a repo once you have this many open PRs there, and the pre-push check warns. Default 0 (off).',
37
+ settableVia: 'setup',
38
+ valueHint: 'non-negative integer (0 = no limit)',
39
+ },
40
+ {
41
+ key: 'maxOpenPRsColdRepo',
42
+ description: 'Per-repo open-PR cap while none of your PRs in that repo have merged (default 1). Discovery leaves the repo out and the pre-push check warns. 0 disables.',
43
+ settableVia: 'setup',
44
+ valueHint: 'non-negative integer (0 = no limit)',
45
+ },
34
46
  {
35
47
  key: 'dormantDays',
36
48
  description: 'Alias for dormantThresholdDays: days of inactivity before a PR is considered dormant.',
@@ -159,5 +159,7 @@ export declare function collectActionableIssues(prs: FetchedPR[], lastDigestAt?:
159
159
  * @param unextractedMergeCount - Recently merged PRs whose learnings have not been extracted yet (#1463); non-zero adds an extract_learnings item
160
160
  * @returns Action menu with context flags for orchestration
161
161
  */
162
- export declare function computeActionMenu(actionableIssues: ActionableIssue[], capacity: CapacityAssessment, commentedIssues?: CommentedIssue[], attention?: Pick<AttentionSummary, 'stuckCI' | 'dormantFollowup'>, unextractedMergeCount?: number): ActionMenu;
162
+ export declare function computeActionMenu(actionableIssues: ActionableIssue[], capacity: CapacityAssessment, commentedIssues?: CommentedIssue[], attention?: Pick<AttentionSummary, 'stuckCI' | 'dormantFollowup'> & {
163
+ closeSuggested?: number;
164
+ }, unextractedMergeCount?: number): ActionMenu;
163
165
  export { formatActionHint, formatBriefSummary, formatSummary, printDigest } from '../commands/daily-render.js';
@@ -416,19 +416,27 @@ export function computeActionMenu(actionableIssues, capacity, commentedIssues =
416
416
  // summarizeAttentionBuckets get a menu path to workflows/dormant-pr-follow-up.md
417
417
  // instead of only a headline count. Emitted only when a bucket is non-zero,
418
418
  // so menus without stuck/dormant PRs are unchanged.
419
+ // closeSuggested (shouldSuggestClose) counts dormant PRs already pinged
420
+ // twice with no reply; they are usually auto-shelved, so they would
421
+ // otherwise never reach this menu.
419
422
  const stuckCI = attention?.stuckCI ?? 0;
420
423
  const dormantFollowup = attention?.dormantFollowup ?? 0;
421
- if (stuckCI > 0 || dormantFollowup > 0) {
424
+ const closeSuggested = attention?.closeSuggested ?? 0;
425
+ if (stuckCI > 0 || dormantFollowup > 0 || closeSuggested > 0) {
422
426
  const parts = [];
423
427
  if (stuckCI > 0)
424
428
  parts.push(`${stuckCI} stuck-CI`);
425
429
  if (dormantFollowup > 0)
426
430
  parts.push(`${dormantFollowup} dormant`);
427
- const total = stuckCI + dormantFollowup;
431
+ if (closeSuggested > 0)
432
+ parts.push(`${closeSuggested} close-candidate`);
433
+ const total = stuckCI + dormantFollowup + closeSuggested;
428
434
  items.push({
429
435
  key: 'follow_up',
430
436
  label: `Follow up on ${parts.join(' and ')} PR${total === 1 ? '' : 's'}`,
431
- description: 'Waiting PRs that may need a nudge (pending CI or no review activity)',
437
+ description: closeSuggested > 0
438
+ ? 'Waiting PRs that may need a nudge, or a close with an offer to reopen after repeated unanswered pings'
439
+ : 'Waiting PRs that may need a nudge (pending CI or no review activity)',
432
440
  });
433
441
  }
434
442
  // Extract-learnings nudge (#1463) — recently merged PRs whose ledger
@@ -102,6 +102,7 @@ function collectRows(state) {
102
102
  outcome: 'closed',
103
103
  month: e.closedAt.slice(0, 7),
104
104
  closeReason: e.closeReason,
105
+ selfCloseReason: e.selfCloseReason,
105
106
  }));
106
107
  const dormant = (state.lastDigest?.openPRs ?? [])
107
108
  .filter((pr) => pr.stalenessTier === 'dormant')
@@ -122,7 +123,8 @@ export function computeEvalReport(state, now = new Date()) {
122
123
  const closeReasons = {};
123
124
  const approachClosuresByMonth = {};
124
125
  for (const r of closedRows) {
125
- const reason = r.closeReason ?? 'unclassified';
126
+ // Self-closed splits by what preceded it, e.g. "self-closed: no-response".
127
+ const reason = r.selfCloseReason ? `self-closed: ${r.selfCloseReason}` : (r.closeReason ?? 'unclassified');
126
128
  closeReasons[reason] = (closeReasons[reason] ?? 0) + 1;
127
129
  if ((r.closeReason === 'ai-policy' || r.closeReason === 'rejected') && r.month) {
128
130
  approachClosuresByMonth[r.month] = (approachClosuresByMonth[r.month] ?? 0) + 1;
@@ -46,7 +46,7 @@
46
46
  * a freeform-only push needs no re-read and cannot clobber another file.
47
47
  */
48
48
  import * as fs from 'node:fs';
49
- import { AgentStateSchema } from './state-schema.js';
49
+ import { AgentStateSchema, NEWER_WRITER_HINT, unknownStateKeys } from './state-schema.js';
50
50
  import { serializeState } from './state-prune.js';
51
51
  import { atomicWriteFileSync, createFreshState, migrateV1ToV2, migrateV2ToV3, migrateV3ToV4, } from './state-persistence.js';
52
52
  import { getGistIdPath, getStateCachePath } from './paths.js';
@@ -755,6 +755,9 @@ export class GistStateStore {
755
755
  if (obj.version === 3)
756
756
  obj = migrateV3ToV4(obj);
757
757
  }
758
+ const newer = unknownStateKeys(obj);
759
+ if (newer.length > 0)
760
+ warn(MODULE, `Gist state (fields: ${newer.join(', ')}) ${NEWER_WRITER_HINT}`);
758
761
  return AgentStateSchema.parse(obj);
759
762
  }
760
763
  catch (err) {
@@ -24,7 +24,7 @@ export { computeContributionStats, type ContributionStats, type ComputeStatsInpu
24
24
  export { fetchPRTemplate, type PRTemplateResult } from './pr-template.js';
25
25
  export { classifyLinkedPR, isLinkedPRStalled, STALLED_PR_THRESHOLD_DAYS, type LinkedPR, type LinkedPRClassification, type LinkedPRState, } from './linked-pr-classification.js';
26
26
  export { classifyIssueAvailability, fetchIssueVerification, verifyIssuesBatch, MAX_VERIFY_CONCURRENCY, type BatchVerificationResult, type IssueAvailabilityVerdict, type IssueVerification, type LinkedPRLinkType, type VerifiedLinkedPR, type VerifyIssueParams, } from './issue-verification.js';
27
- export { classifyAttentionBucket, summarizeAttentionBuckets, STUCK_CI_THRESHOLD_DAYS, DORMANT_FOLLOWUP_THRESHOLD_DAYS, type AttentionBucket, type AttentionInput, type AttentionSummary, } from './pr-attention.js';
27
+ export { classifyAttentionBucket, summarizeAttentionBuckets, shouldSuggestClose, STUCK_CI_THRESHOLD_DAYS, DORMANT_FOLLOWUP_THRESHOLD_DAYS, type AttentionBucket, type AttentionInput, type AttentionSummary, } from './pr-attention.js';
28
28
  export { scanForAntiLLMPolicy, type AntiLLMCategory, type AntiLLMMatch, type AntiLLMScanResult, } from './anti-llm-policy.js';
29
29
  export { detectFormatters, diagnoseCIFormatterFailure, getPreferredFormatter, type DetectedFormatter, type FormatterDetectionResult, type CIFormatterDiagnosis, type FormatterName, } from './formatter-detection.js';
30
30
  export { CONFIG_KEY_REGISTRY, type ConfigKeyDef, type SettableVia, isKnownKey, getKeyDef, getSetupKeys, getConfigKeys, suggestKey, formatUnknownKeyError, } from './config-registry.js';
@@ -25,7 +25,7 @@ export { computeContributionStats } from './stats.js';
25
25
  export { fetchPRTemplate } from './pr-template.js';
26
26
  export { classifyLinkedPR, isLinkedPRStalled, STALLED_PR_THRESHOLD_DAYS, } from './linked-pr-classification.js';
27
27
  export { classifyIssueAvailability, fetchIssueVerification, verifyIssuesBatch, MAX_VERIFY_CONCURRENCY, } from './issue-verification.js';
28
- export { classifyAttentionBucket, summarizeAttentionBuckets, STUCK_CI_THRESHOLD_DAYS, DORMANT_FOLLOWUP_THRESHOLD_DAYS, } from './pr-attention.js';
28
+ export { classifyAttentionBucket, summarizeAttentionBuckets, shouldSuggestClose, STUCK_CI_THRESHOLD_DAYS, DORMANT_FOLLOWUP_THRESHOLD_DAYS, } from './pr-attention.js';
29
29
  export { scanForAntiLLMPolicy, } from './anti-llm-policy.js';
30
30
  export { detectFormatters, diagnoseCIFormatterFailure, getPreferredFormatter, } from './formatter-detection.js';
31
31
  export { CONFIG_KEY_REGISTRY, isKnownKey, getKeyDef, getSetupKeys, getConfigKeys, suggestKey, formatUnknownKeyError, } from './config-registry.js';
@@ -10,12 +10,14 @@
10
10
  * regardless of the transport used to fetch the data.
11
11
  */
12
12
  import { FetchedPR, CIStatusResult } from './types.js';
13
- import { type ReviewComment } from './review-analysis.js';
13
+ import { type ReviewComment, type ActivityEvent } from './review-analysis.js';
14
14
  /** Issue comment in the shape `checkUnrespondedComments`/`getFirstMaintainerResponseAt` read. */
15
15
  export interface AssemblyComment {
16
16
  user?: {
17
17
  login?: string;
18
+ type?: string | null;
18
19
  } | null;
20
+ author_association?: string | null;
19
21
  body?: string | null;
20
22
  created_at: string;
21
23
  }
@@ -23,7 +25,9 @@ export interface AssemblyComment {
23
25
  export interface AssemblyReview {
24
26
  user?: {
25
27
  login?: string;
28
+ type?: string | null;
26
29
  } | null;
30
+ author_association?: string | null;
27
31
  body?: string | null;
28
32
  submitted_at?: string | null;
29
33
  state?: string | null;
@@ -51,6 +55,12 @@ export interface PRSignals {
51
55
  comments: AssemblyComment[];
52
56
  reviews: AssemblyReview[];
53
57
  reviewComments: ReviewComment[];
58
+ /**
59
+ * Non-comment activity that can mark maintainer engagement: commits (by
60
+ * author and committer), force-pushes, review requests, labels. Optional;
61
+ * absent means comments/reviews alone drive the dormancy clock.
62
+ */
63
+ activityEvents?: ActivityEvent[];
54
64
  ciStatus: CIStatusResult;
55
65
  }
56
66
  /** Config subset the assembly needs — the fields `determineStatus` and comment analysis consume. */
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { daysBetween } from './dates.js';
13
13
  import { determineStatus } from './status-determination.js';
14
- import { determineReviewDecision, getLatestChangesRequestedDate, checkUnrespondedComments, getFirstMaintainerResponseAt, } from './review-analysis.js';
14
+ import { determineReviewDecision, getLatestChangesRequestedDate, checkUnrespondedComments, getFirstMaintainerResponseAt, getLastMaintainerActivity, } from './review-analysis.js';
15
15
  import { analyzeChecklist } from './checklist-analysis.js';
16
16
  import { extractMaintainerActionHints } from './maintainer-analysis.js';
17
17
  import { categorizeCIStatus, classifyFailingChecks } from './ci-analysis.js';
@@ -53,8 +53,16 @@ export async function assembleFetchedPR(signals, config, commitInfo) {
53
53
  const { hasIncompleteChecklist, checklistStats } = analyzeChecklist(signals.body || '');
54
54
  // Extract maintainer action hints from comments (delegated to maintainer-analysis module)
55
55
  const maintainerActionHints = extractMaintainerActionHints(lastMaintainerComment?.body, reviewDecision);
56
- // Calculate days since activity
57
- const daysSinceActivity = daysBetween(new Date(signals.updatedAt), new Date());
56
+ // Days since ANY activity (updatedAt). The contributor's own pings and
57
+ // rebases reset this, so it drives follow-up timing and stale-CI demotion,
58
+ // not dormancy.
59
+ const now = new Date();
60
+ const daysSinceActivity = daysBetween(new Date(signals.updatedAt), now);
61
+ // Days since the last non-contributor, non-bot activity (or PR creation).
62
+ // This drives stalenessTier so a PR the maintainers ignore goes dormant
63
+ // even while the contributor keeps pinging it.
64
+ const { lastMaintainerActivityAt, authorPingsSinceMaintainerActivity } = getLastMaintainerActivity(comments, reviews, reviewComments, signals.activityEvents ?? [], config.githubUsername, signals.createdAt);
65
+ const daysSinceMaintainerActivity = daysBetween(new Date(lastMaintainerActivityAt), now);
58
66
  // Find the date of the latest changes_requested review (delegated to review-analysis module)
59
67
  const latestChangesRequestedDate = getLatestChangesRequestedDate(reviews);
60
68
  const { status: ciStatus, failingCheckNames, failingCheckConclusions } = signals.ciStatus;
@@ -71,6 +79,7 @@ export async function assembleFetchedPR(signals, config, commitInfo) {
71
79
  hasIncompleteChecklist,
72
80
  reviewDecision,
73
81
  daysSinceActivity,
82
+ daysSinceMaintainerActivity,
74
83
  dormantThreshold: config.dormantThresholdDays,
75
84
  approachingThreshold: config.approachingDormantDays,
76
85
  latestCommitDate,
@@ -95,6 +104,9 @@ export async function assembleFetchedPR(signals, config, commitInfo) {
95
104
  updatedAt: signals.updatedAt,
96
105
  firstMaintainerResponseAt,
97
106
  daysSinceActivity,
107
+ lastMaintainerActivityAt,
108
+ daysSinceMaintainerActivity,
109
+ authorPingsSinceMaintainerActivity,
98
110
  ciStatus,
99
111
  failingCheckNames,
100
112
  classifiedChecks,
@@ -113,6 +125,11 @@ export async function assembleFetchedPR(signals, config, commitInfo) {
113
125
  // Compute display labels (#79) — delegated to display-utils module
114
126
  const { displayLabel, displayDescription } = computeDisplayLabel(pr);
115
127
  pr.displayLabel = displayLabel;
116
- pr.displayDescription = displayDescription;
128
+ // Incomplete checklist is informational, never needs_addressing on its own
129
+ // (see collectAllActionReasons); keep it visible as a note.
130
+ pr.displayDescription =
131
+ hasIncompleteChecklist && checklistStats
132
+ ? `${displayDescription} (note: checklist ${checklistStats.checked}/${checklistStats.total})`
133
+ : displayDescription;
117
134
  return pr;
118
135
  }
@@ -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;