@oss-autopilot/core 3.42.5 → 3.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +272 -25
  3. package/dist/cli.bundle.cjs +183 -154
  4. package/dist/commands/check-integration.js +1 -0
  5. package/dist/commands/cleanup.d.ts +76 -0
  6. package/dist/commands/cleanup.js +269 -0
  7. package/dist/commands/comments.d.ts +6 -0
  8. package/dist/commands/comments.js +6 -2
  9. package/dist/commands/config.js +37 -5
  10. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  11. package/dist/commands/daily-dismiss-filter.js +17 -1
  12. package/dist/commands/daily-ledger.d.ts +122 -0
  13. package/dist/commands/daily-ledger.js +225 -0
  14. package/dist/commands/daily-recent-prs.d.ts +26 -0
  15. package/dist/commands/daily-recent-prs.js +55 -0
  16. package/dist/commands/daily.d.ts +2 -1
  17. package/dist/commands/daily.js +59 -89
  18. package/dist/commands/dashboard-cache.d.ts +2 -0
  19. package/dist/commands/dashboard-cache.js +33 -8
  20. package/dist/commands/dashboard-data.js +71 -36
  21. package/dist/commands/dashboard-gist-sync.js +3 -1
  22. package/dist/commands/dashboard-lifecycle.js +1 -1
  23. package/dist/commands/dashboard-process.d.ts +14 -1
  24. package/dist/commands/dashboard-process.js +46 -7
  25. package/dist/commands/dashboard-server.js +89 -23
  26. package/dist/commands/detect-formatters.js +1 -0
  27. package/dist/commands/dismiss.js +5 -2
  28. package/dist/commands/doctor.d.ts +15 -1
  29. package/dist/commands/doctor.js +73 -5
  30. package/dist/commands/draft.d.ts +77 -0
  31. package/dist/commands/draft.js +218 -0
  32. package/dist/commands/eval.js +1 -0
  33. package/dist/commands/guidelines.d.ts +23 -1
  34. package/dist/commands/guidelines.js +49 -4
  35. package/dist/commands/index.d.ts +24 -4
  36. package/dist/commands/index.js +15 -3
  37. package/dist/commands/issue-thread.d.ts +46 -0
  38. package/dist/commands/issue-thread.js +123 -0
  39. package/dist/commands/ledger-backfill.d.ts +9 -0
  40. package/dist/commands/ledger-backfill.js +44 -1
  41. package/dist/commands/list-mark-done.d.ts +2 -1
  42. package/dist/commands/list-mark-done.js +3 -1
  43. package/dist/commands/list-move-tier.d.ts +2 -1
  44. package/dist/commands/list-move-tier.js +3 -1
  45. package/dist/commands/local-repos.js +10 -5
  46. package/dist/commands/locate-issue-list.d.ts +40 -17
  47. package/dist/commands/locate-issue-list.js +148 -88
  48. package/dist/commands/move.js +7 -1
  49. package/dist/commands/overnight-handoff.d.ts +17 -7
  50. package/dist/commands/overnight-handoff.js +36 -14
  51. package/dist/commands/overnight-push-prep.d.ts +13 -8
  52. package/dist/commands/overnight-push-prep.js +106 -34
  53. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  54. package/dist/commands/overnight-tool-rules.js +217 -0
  55. package/dist/commands/overnight.d.ts +5 -6
  56. package/dist/commands/overnight.js +61 -140
  57. package/dist/commands/parse-list.js +7 -1
  58. package/dist/commands/policy.d.ts +86 -0
  59. package/dist/commands/policy.js +263 -0
  60. package/dist/commands/pr-preflight.d.ts +43 -0
  61. package/dist/commands/pr-preflight.js +294 -0
  62. package/dist/commands/repo-vet.d.ts +9 -0
  63. package/dist/commands/repo-vet.js +36 -11
  64. package/dist/commands/scout-bridge.js +18 -8
  65. package/dist/commands/search.js +7 -0
  66. package/dist/commands/setup.d.ts +3 -3
  67. package/dist/commands/setup.js +46 -18
  68. package/dist/commands/skip-add.js +10 -1
  69. package/dist/commands/startup.d.ts +5 -3
  70. package/dist/commands/startup.js +65 -49
  71. package/dist/commands/state-cmd.d.ts +2 -0
  72. package/dist/commands/state-cmd.js +5 -1
  73. package/dist/commands/stats.js +1 -0
  74. package/dist/commands/status.js +1 -0
  75. package/dist/commands/strategy.js +1 -0
  76. package/dist/commands/vet-list.d.ts +6 -0
  77. package/dist/commands/vet-list.js +25 -0
  78. package/dist/commands/vet.d.ts +12 -0
  79. package/dist/commands/vet.js +118 -1
  80. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  81. package/dist/core/anti-llm-policy.d.ts +3 -0
  82. package/dist/core/anti-llm-policy.js +3 -0
  83. package/dist/core/auth.js +2 -0
  84. package/dist/core/ci-analysis.d.ts +7 -2
  85. package/dist/core/ci-analysis.js +76 -21
  86. package/dist/core/commit-date.d.ts +19 -0
  87. package/dist/core/commit-date.js +17 -0
  88. package/dist/core/config-registry.js +11 -5
  89. package/dist/core/contributing.d.ts +2 -3
  90. package/dist/core/contributing.js +2 -3
  91. package/dist/core/daily-logic.d.ts +27 -5
  92. package/dist/core/daily-logic.js +57 -19
  93. package/dist/core/errors.d.ts +37 -3
  94. package/dist/core/errors.js +54 -5
  95. package/dist/core/gist-health.d.ts +15 -3
  96. package/dist/core/gist-health.js +8 -0
  97. package/dist/core/gist-state-store.d.ts +24 -4
  98. package/dist/core/gist-state-store.js +97 -46
  99. package/dist/core/github-stats.d.ts +104 -16
  100. package/dist/core/github-stats.js +282 -97
  101. package/dist/core/http-cache.d.ts +0 -10
  102. package/dist/core/http-cache.js +0 -19
  103. package/dist/core/index.d.ts +12 -5
  104. package/dist/core/index.js +15 -5
  105. package/dist/core/issue-conversation.d.ts +8 -2
  106. package/dist/core/issue-conversation.js +31 -12
  107. package/dist/core/local-config.d.ts +95 -0
  108. package/dist/core/local-config.js +271 -0
  109. package/dist/core/merged-pr-notes.d.ts +2 -2
  110. package/dist/core/pagination.d.ts +55 -0
  111. package/dist/core/pagination.js +59 -0
  112. package/dist/core/paths.d.ts +7 -0
  113. package/dist/core/paths.js +9 -0
  114. package/dist/core/pr-assembly.js +6 -2
  115. package/dist/core/pr-graphql.d.ts +37 -3
  116. package/dist/core/pr-graphql.js +73 -12
  117. package/dist/core/pr-monitor.d.ts +29 -12
  118. package/dist/core/pr-monitor.js +71 -23
  119. package/dist/core/pr-preflight.d.ts +113 -0
  120. package/dist/core/pr-preflight.js +364 -0
  121. package/dist/core/pr-quality-rubric.d.ts +0 -6
  122. package/dist/core/pr-quality-rubric.js +0 -8
  123. package/dist/core/pr-template.d.ts +2 -0
  124. package/dist/core/pr-template.js +5 -1
  125. package/dist/core/repo-policy.d.ts +105 -0
  126. package/dist/core/repo-policy.js +400 -0
  127. package/dist/core/repo-score-manager.d.ts +48 -0
  128. package/dist/core/repo-score-manager.js +111 -1
  129. package/dist/core/review-analysis.d.ts +34 -19
  130. package/dist/core/review-analysis.js +67 -10
  131. package/dist/core/reviewed-prs-fetch.js +11 -29
  132. package/dist/core/reviewed-prs.js +8 -15
  133. package/dist/core/stale-data.d.ts +41 -0
  134. package/dist/core/stale-data.js +115 -0
  135. package/dist/core/state-persistence.d.ts +62 -27
  136. package/dist/core/state-persistence.js +338 -117
  137. package/dist/core/state-schema.d.ts +113 -210
  138. package/dist/core/state-schema.js +165 -80
  139. package/dist/core/state.d.ts +60 -8
  140. package/dist/core/state.js +192 -46
  141. package/dist/core/status-determination.js +26 -8
  142. package/dist/core/strategy.js +3 -1
  143. package/dist/core/types.d.ts +22 -1
  144. package/dist/core/types.js +1 -0
  145. package/dist/core/untrusted-content.d.ts +30 -11
  146. package/dist/core/untrusted-content.js +77 -42
  147. package/dist/core/urls.d.ts +9 -0
  148. package/dist/core/urls.js +18 -0
  149. package/dist/dashboard/assets/{chart-panel-DPKNBUts.js → chart-panel-C_C1lFTI.js} +1 -1
  150. package/dist/dashboard/assets/{index-B25bZOYX.js → index-B--H66Jk.js} +1 -1
  151. package/dist/dashboard/index.html +1 -1
  152. package/dist/formatters/json.d.ts +262 -6
  153. package/dist/formatters/json.js +77 -1
  154. package/package.json +1 -1
  155. package/dist/core/ci-enforced-tools.d.ts +0 -35
  156. package/dist/core/ci-enforced-tools.js +0 -109
  157. package/dist/core/comment-decision.d.ts +0 -79
  158. package/dist/core/comment-decision.js +0 -82
  159. package/dist/core/extraction-categories.d.ts +0 -55
  160. package/dist/core/extraction-categories.js +0 -108
  161. package/dist/core/follow-up-history.d.ts +0 -40
  162. package/dist/core/follow-up-history.js +0 -71
  163. package/dist/core/issue-effort.d.ts +0 -29
  164. package/dist/core/issue-effort.js +0 -47
  165. package/dist/core/maintainer-hints.d.ts +0 -23
  166. package/dist/core/maintainer-hints.js +0 -36
  167. package/dist/core/workflow-state.d.ts +0 -56
  168. package/dist/core/workflow-state.js +0 -101
@@ -0,0 +1,400 @@
1
+ /**
2
+ * Per-repo contribution policy (#1953): AI policy, disclosure line, CLA,
3
+ * commit rules and the gate before a PR, as one record per repo.
4
+ *
5
+ * `derivePolicy` runs the anti-LLM / disclosure scans (anti-llm-policy.ts)
6
+ * and the CONTRIBUTING requirement extraction (contributing.ts) over a repo's
7
+ * docs. `vet` and `vet-list` store the result unreviewed, `policy set` stores the user's
8
+ * record, and `pr-preflight` enforces it (including the commit rules).
9
+ *
10
+ * Policy text comes from other people's repos, so a record holds only
11
+ * enumerated values plus short quoted lines ({@link quote}). The older
12
+ * `config.aiPolicyBlocklist` is read as a ban on top of any stored record:
13
+ * nothing stored can lift it ({@link effectivePolicy}).
14
+ */
15
+ import { scanAIDisclosureRequirement, scanForAntiLLMPolicy } from './anti-llm-policy.js';
16
+ import { extractRequirements } from './contributing.js';
17
+ import { POLICY_QUOTE_MAX, RepoPolicySchema } from './state-schema.js';
18
+ import { wrapUntrustedContent } from './untrusted-content.js';
19
+ export const AI_POLICIES = ['allowed', 'disclosure-required', 'banned', 'unknown'];
20
+ export const PR_GATES = ['none', 'claim-first', 'maintainer-label', 'collaborators-only', 'unknown'];
21
+ export const CLA_POLICIES = ['none', 'required', 'unknown'];
22
+ export const COMMIT_RULES = ['conventional-commits', 'dco-signoff', 'no-closing-keyword-in-commit'];
23
+ /** Source label for a ban that comes from `config.aiPolicyBlocklist`. */
24
+ export const BLOCKLIST_SOURCE = 'config aiPolicyBlocklist';
25
+ /** One line, control characters removed, capped at {@link POLICY_QUOTE_MAX}. */
26
+ export function quote(text) {
27
+ const line = text
28
+ .replaceAll(/\p{Cc}/gu, ' ')
29
+ .replaceAll(/\s+/g, ' ')
30
+ .trim();
31
+ return line.length > POLICY_QUOTE_MAX ? `${line.slice(0, POLICY_QUOTE_MAX - 1)}…` : line;
32
+ }
33
+ const BEFORE_PR = /\bbefore\s+(?:opening|submitting|sending|creating|starting|working)\b/i;
34
+ const CLAIM_PHRASE = /\b(?:comment\s+on\s+the\s+issue|ask\s+to\s+be\s+assigned|get\s+assigned|be\s+assigned)\b/i;
35
+ const PR_NOUN = String.raw `(?:pull\s+requests|prs|contributions)`;
36
+ /**
37
+ * `keyword` within a few words after a negation: "do not require a CLA", "no
38
+ * need to be assigned". "without" is not a negation here: "merged without a
39
+ * signed CLA" states the rule.
40
+ */
41
+ function negated(keyword) {
42
+ return new RegExp(String.raw `(?:\bno|\bnot|n't)\s+(?:\w+\s+){0,3}?${keyword}`, 'gi');
43
+ }
44
+ /**
45
+ * `line` with the negated spans blanked, so a positive phrase elsewhere on the
46
+ * line still counts. Known over-match: a negated mention plus a bare
47
+ * re-mention ("no CLA needed, see CLA.md") reads as positive. Accepted: the
48
+ * readings it feeds are unreviewed, and those only warn or need confirmation.
49
+ */
50
+ function affirmed(line, none) {
51
+ return none ? line.replaceAll(none, ' ') : line;
52
+ }
53
+ const GATE_RULES = [
54
+ {
55
+ gate: 'collaborators-only',
56
+ all: [
57
+ new RegExp(String.raw `\bonly\s+accepts?\s+${PR_NOUN}\s+from\s+(?:collaborators|maintainers|team\s+members)\b`, 'i'),
58
+ ],
59
+ },
60
+ {
61
+ gate: 'collaborators-only',
62
+ all: [/(?:\bnot|n't)\s+accept\b/i, new RegExp(String.raw `\b(?:external|outside|unsolicited)\s+${PR_NOUN}\b`, 'i')],
63
+ },
64
+ {
65
+ gate: 'maintainer-label',
66
+ all: [/\bwait\s+(?:for|until)\s+(?:a\s+)?maintainers?\b/i, /\b(?:label|approv|accept|triag)/i, /\bissue/i],
67
+ },
68
+ { gate: 'maintainer-label', all: [/\blabel/i, /\b(?:accepted|approved|ready)\b/i, BEFORE_PR] },
69
+ { gate: 'claim-first', all: [CLAIM_PHRASE, BEFORE_PR], none: negated(String.raw `(?:be\s+|get\s+)?assigned`) },
70
+ ];
71
+ /** Strictest first: the first gate any doc states wins. */
72
+ const GATE_ORDER = ['collaborators-only', 'maintainer-label', 'claim-first'];
73
+ const DCO = /\bDCO\b|signed?-off-by|sign[- ]?off/i;
74
+ const DCO_NEGATED = negated('(?:DCO|sign(?:ed)?[- ]?off)');
75
+ /** Commit rules: a CONTRIBUTING requirement of `category` whose line matches `evidence`, or a line matching `all`. */
76
+ const COMMIT_RULE_MATCHERS = [
77
+ { rule: 'conventional-commits', category: 'commit_format', evidence: /conventional\s+commits?/i },
78
+ // extractRequirements reports cla_dco once per doc, so a CLA line can hide the DCO one: also scan lines.
79
+ { rule: 'dco-signoff', category: 'cla_dco', evidence: DCO, all: [DCO], none: DCO_NEGATED },
80
+ {
81
+ rule: 'no-closing-keyword-in-commit',
82
+ all: [/\b(?:do\s+not|don't|never)\s+(?:use|include|put|add)\b/i, /\b(?:fixes|closes|resolves)\b/i, /\bcommit/i],
83
+ },
84
+ ];
85
+ const CLA_EVIDENCE = /\bCLA\b|contributor\s+license\s+agreement/i;
86
+ const CLA_NEGATED = negated(String.raw `(?:CLA\b|contributor\s+license)`);
87
+ const COUNT_WORDS = { one: 1, 'a single': 1, two: 2, three: 3, four: 4, five: 5 };
88
+ const COUNT = String.raw `(\d{1,2}|one|a\s+single|two|three|four|five)`;
89
+ const AI_PRS = String.raw `(?:open\s+)?(?:AI|LLM)[-\s](?:assisted|generated|authored|written)\s+(?:PRs?|pull\s+requests?)`;
90
+ /**
91
+ * "one AI-assisted PR at a time" (a rate after it does not change it), and "no
92
+ * more than 2 open AI-generated pull requests", "don't open more than one
93
+ * AI-assisted PR" (a rate after these makes them a throughput).
94
+ */
95
+ const AI_PR_LIMITS = [
96
+ {
97
+ re: new RegExp(String.raw `\b${COUNT}\s+${AI_PRS}\s+(?:open\s+)?(?:at\s+(?:a|any\s+one)\s+time|at\s+once)`, 'dgi'),
98
+ isRateChecked: false,
99
+ },
100
+ {
101
+ re: new RegExp(String.raw `(?:\bno\s+more\s+than|(?:\bnot|n't|\bnever)\s+(?:\w+\s+)?more\s+than|\bat\s+most|\bup\s+to|\ba\s+maximum\s+of|\blimit(?:ed)?\s+(?:of|to))\s+${COUNT}\s+${AI_PRS}`, 'dgi'),
102
+ isRateChecked: true,
103
+ },
104
+ ];
105
+ /** "there is no limit on ...", "you don't need to keep to one ...": the rest of the sentence states no limit. */
106
+ const AI_PR_LIMIT_NEGATED = /(?:\bno|\bnot|n't)\s+(?:\w+\s+){0,2}?(?:limit|restrict|cap\b|maximum|requir|need|have\s+to|must)[^.;!?]*/gi;
107
+ /** "... per week", "... a day", "... per contributor per release": a throughput, not an open-PR limit. */
108
+ const RATE_AFTER = /^\s*(?:per|a|an|each|every)\s+(?:week|day|month|year|quarter|release|cycle)\b/i;
109
+ const PER_PERSON = /^\s*per\s+(?:contributor|person|author|user)\b/i;
110
+ /** "maintainers review one ... at a time", "we merge up to 10 ...": what the maintainers do, not a contributor limit. */
111
+ const MAINTAINER_VERB = /\b(?:we|maintainers?|reviewers?)\s+(?:\w+\s+)?(?:review|merg|triag)\w*/i;
112
+ /** A match that states what maintainers do, or a throughput. */
113
+ function isNotALimit(text, match, isRateChecked) {
114
+ const countStart = match.indices?.[1]?.[0] ?? match.index;
115
+ const clause = text
116
+ .slice(0, countStart)
117
+ .split(/[.;!?,]/)
118
+ .at(-1) ?? '';
119
+ if (MAINTAINER_VERB.test(clause))
120
+ return true;
121
+ const after = text.slice(match.index + match[0].length).replace(PER_PERSON, '');
122
+ return isRateChecked && RATE_AFTER.test(after);
123
+ }
124
+ /** The first limit the line states, in reading order; null when none. */
125
+ function aiPrLimit(line) {
126
+ const text = affirmed(line, AI_PR_LIMIT_NEGATED);
127
+ let first = null;
128
+ for (const { re, isRateChecked } of AI_PR_LIMITS) {
129
+ for (const match of text.matchAll(re)) {
130
+ const isEarlier = first === null || match.index < first.index;
131
+ if (isEarlier && !isNotALimit(text, match, isRateChecked))
132
+ first = match;
133
+ }
134
+ }
135
+ if (!first)
136
+ return null;
137
+ const count = first[1];
138
+ const n = COUNT_WORDS[count.toLowerCase().replaceAll(/\s+/g, ' ')] ?? Number(count);
139
+ return n > 0 ? n : null;
140
+ }
141
+ function lineMatching(text, rule) {
142
+ return text.split(/\r?\n/).find((line) => rule.all.every((p) => p.test(affirmed(line, rule.none)))) ?? null;
143
+ }
144
+ /** A ban in any doc wins; then a disclosure ask; then an invitation to mention AI reads as `allowed`. */
145
+ function scanAi(doc, found) {
146
+ const ban = scanForAntiLLMPolicy(doc.content).matches.at(0);
147
+ if (ban) {
148
+ found.ai = { policy: 'banned', file: doc.file, line: ban.excerpt };
149
+ return;
150
+ }
151
+ const isSettled = found.ai?.policy === 'banned' || found.ai?.policy === 'disclosure-required';
152
+ if (isSettled)
153
+ return;
154
+ const disclosure = scanAIDisclosureRequirement(doc.content).matches;
155
+ const asked = disclosure.find((m) => m.category !== 'invited');
156
+ if (asked) {
157
+ found.ai = { policy: 'disclosure-required', file: doc.file, line: asked.excerpt };
158
+ found.disclosure = asked.excerpt;
159
+ return;
160
+ }
161
+ const invited = disclosure.at(0);
162
+ if (invited && !found.ai)
163
+ found.ai = { policy: 'allowed', file: doc.file, line: invited.excerpt };
164
+ }
165
+ function scanCommitRules(doc, requirements, found) {
166
+ for (const matcher of COMMIT_RULE_MATCHERS) {
167
+ if (found.commitRules.some((r) => r.rule === matcher.rule))
168
+ continue;
169
+ const req = requirements.find((r) => r.category === matcher.category && matcher.evidence?.test(affirmed(r.evidence, matcher.none)));
170
+ const line = req?.evidence ?? (matcher.all ? lineMatching(doc.content, { all: matcher.all, none: matcher.none }) : null);
171
+ if (line)
172
+ found.commitRules.push({ rule: matcher.rule, file: doc.file, line });
173
+ }
174
+ }
175
+ function scanRequirements(doc, found) {
176
+ const requirements = extractRequirements(doc.content);
177
+ const cla = requirements.find((r) => r.category === 'cla_dco' && CLA_EVIDENCE.test(affirmed(r.evidence, CLA_NEGATED)));
178
+ if (cla && !found.cla)
179
+ found.cla = { file: doc.file, line: cla.evidence };
180
+ scanCommitRules(doc, requirements, found);
181
+ for (const { gate, ...rule } of GATE_RULES) {
182
+ const line = lineMatching(doc.content, rule);
183
+ if (line && !found.gates.has(gate))
184
+ found.gates.set(gate, { file: doc.file, line });
185
+ }
186
+ if (!found.aiPrLimit)
187
+ scanAiPrLimit(doc, found);
188
+ }
189
+ function scanAiPrLimit(doc, found) {
190
+ const lines = doc.content.split(/\r?\n/);
191
+ for (const line of lines) {
192
+ const max = aiPrLimit(line);
193
+ if (max !== null) {
194
+ found.aiPrLimit = { file: doc.file, line, max };
195
+ return;
196
+ }
197
+ }
198
+ }
199
+ /**
200
+ * Derive a policy from a repo's docs (CONTRIBUTING, PR template, ...). With no
201
+ * docs every field is `unknown`; a doc that is silent on CLA or a PR gate reads
202
+ * as `none`. Silence on AI stays `unknown`: it is not permission.
203
+ */
204
+ export function derivePolicy(docs, now = new Date()) {
205
+ const found = { ai: null, disclosure: null, cla: null, commitRules: [], gates: new Map(), aiPrLimit: null };
206
+ const readable = docs.filter((d) => d.content.trim() !== '');
207
+ for (const doc of readable) {
208
+ scanAi(doc, found);
209
+ scanRequirements(doc, found);
210
+ }
211
+ const gate = GATE_ORDER.find((g) => found.gates.has(g));
212
+ const silent = readable.length > 0 ? 'none' : 'unknown';
213
+ const hits = [found.ai, found.cla, gate ? found.gates.get(gate) : undefined, found.aiPrLimit, ...found.commitRules];
214
+ const source = hits
215
+ .filter((h) => h !== null && h !== undefined)
216
+ .map((h) => ({ file: quote(h.file).slice(0, 100), quotedLine: quote(h.line) }))
217
+ .slice(0, 10);
218
+ return {
219
+ aiPolicy: found.ai?.policy ?? 'unknown',
220
+ ...(found.disclosure !== null && { disclosureText: quote(found.disclosure) }),
221
+ cla: found.cla ? 'required' : silent,
222
+ commitRules: found.commitRules.map((r) => r.rule),
223
+ prGate: gate ?? silent,
224
+ ...(found.aiPrLimit && { maxOpenAiPRs: found.aiPrLimit.max }),
225
+ source,
226
+ reviewedByUser: false,
227
+ updatedAt: now.toISOString(),
228
+ };
229
+ }
230
+ /** Markdown link targets: `[text](target)`. */
231
+ const MD_LINK = /\]\(\s*<?([^\s)>]+)/g;
232
+ const POLICY_DOC_PATH = /(?:^|\/)(?:[^/]*[-_])?(?:contribut|guideline|ai[-_]?(?:policy|usage|use)\b|llm)[^/]*\.(?:md|markdown|rst|txt)$/i;
233
+ /** A folder guide: `docs/contributing/README.md`, `docs/ai-policy/index.md`. */
234
+ const POLICY_DOC_FOLDER = /(?:^|\/)(?:contribut|guideline|ai[-_]?policy)[^/]*\/(?:readme|index)\.md$/i;
235
+ /** Names that match the words but are not guides: the llms.txt site index, a contributors list. */
236
+ const NOT_A_GUIDE = /(?:^|\/)(?:llms(?:-full)?\.txt|contributors\.[^/]*)$/i;
237
+ /** Where scout already reads CONTRIBUTING from. */
238
+ const SCOUT_READ = new Set(['contributing.md', '.github/contributing.md', 'docs/contributing.md']);
239
+ /**
240
+ * Up to `max` paths in `repo` that its README links to and that look like a
241
+ * contribution guide or AI policy (relative links, or github.com blob links to
242
+ * the same repo). Links to other sites, other repos or outside the repo root
243
+ * are dropped, as are the CONTRIBUTING paths scout reads anyway.
244
+ */
245
+ export function linkedPolicyDocs(readme, repo, max = 2) {
246
+ const escaped = repo.replaceAll('.', '\\.');
247
+ const sameRepo = new RegExp(String.raw `^https?://github\.com/${escaped}/blob/[^/]+/`, 'i');
248
+ const paths = new Set();
249
+ for (const [, href] of readme.matchAll(MD_LINK)) {
250
+ const path = policyDocPath(href.split(/[?#]/, 1)[0].replace(sameRepo, ''));
251
+ if (path !== null)
252
+ paths.add(path);
253
+ }
254
+ return [...paths].slice(0, max);
255
+ }
256
+ /** The repo path a link target names when it looks like a contribution doc, else null. */
257
+ function policyDocPath(target) {
258
+ // A scheme means another site (or a blob link to another repo); `..` leaves the repo.
259
+ if (/^[a-z][\w+.-]*:/i.test(target) || target.split('/').includes('..'))
260
+ return null;
261
+ const path = target.replace(/^(?:\.?\/)+/, '');
262
+ const isPolicyDoc = (POLICY_DOC_PATH.test(path) || POLICY_DOC_FOLDER.test(path)) && !NOT_A_GUIDE.test(path);
263
+ return isPolicyDoc && !SCOUT_READ.has(path.toLowerCase()) ? path : null;
264
+ }
265
+ const EPOCH = '1970-01-01T00:00:00.000Z';
266
+ const UNKNOWN_POLICY = {
267
+ aiPolicy: 'unknown',
268
+ cla: 'unknown',
269
+ commitRules: [],
270
+ prGate: 'unknown',
271
+ source: [],
272
+ reviewedByUser: false,
273
+ };
274
+ function rawEntry(state, repo) {
275
+ const raw = state.repoPolicies?.[repo.toLowerCase()];
276
+ return typeof raw === 'object' && raw !== null ? raw : null;
277
+ }
278
+ /** Fields of the stored entry this release does not know (a newer release added them), to keep across an edit. */
279
+ export function unknownFields(state, repo) {
280
+ const raw = rawEntry(state, repo) ?? {};
281
+ const known = new Set(Object.keys(RepoPolicySchema.shape));
282
+ return Object.fromEntries(Object.entries(raw).filter(([key]) => !known.has(key)));
283
+ }
284
+ /** A stored entry this release cannot parse, e.g. one a newer release wrote with a value added since. */
285
+ export function isUnreadable(state, repo) {
286
+ const raw = state.repoPolicies?.[repo.toLowerCase()];
287
+ return raw !== undefined && !RepoPolicySchema.safeParse(raw).success;
288
+ }
289
+ /**
290
+ * The stored record for `repo`, or null when there is none. An entry that does
291
+ * not parse but says `aiPolicy: 'banned'` still reads as a ban (every other
292
+ * field unknown): a newer release's record must not lift a ban here.
293
+ */
294
+ export function storedPolicy(state, repo) {
295
+ const raw = rawEntry(state, repo);
296
+ const parsed = RepoPolicySchema.safeParse(raw);
297
+ if (parsed.success)
298
+ return parsed.data;
299
+ if (raw?.aiPolicy !== 'banned')
300
+ return null;
301
+ return { ...UNKNOWN_POLICY, aiPolicy: 'banned', reviewedByUser: raw.reviewedByUser === true, updatedAt: EPOCH };
302
+ }
303
+ /** True when the raw stored entry says the user set it, even when this release cannot parse the rest. */
304
+ export function isUserReviewed(state, repo) {
305
+ return rawEntry(state, repo)?.reviewedByUser === true;
306
+ }
307
+ export function isBlocklisted(state, repo) {
308
+ const lower = repo.toLowerCase();
309
+ return (state.config.aiPolicyBlocklist ?? []).some((r) => r.toLowerCase() === lower);
310
+ }
311
+ /** The record to apply before the blocklist: the user's, a stored ban, a fresh reading, the stored one. */
312
+ function basePolicy(stored, fresh) {
313
+ // A ban vet recorded stays until the user says otherwise; a later reading that misses it does not clear it.
314
+ if (stored?.reviewedByUser || stored?.aiPolicy === 'banned')
315
+ return stored;
316
+ return fresh ?? stored;
317
+ }
318
+ /**
319
+ * The policy that applies to `repo`: the user's record, else a stored ban,
320
+ * else a freshly derived one when given, else the stored unreviewed one. A repo
321
+ * in `config.aiPolicyBlocklist` is banned whatever is stored: the blocklist is
322
+ * the older ban list, still synced to clients that predate policy records, and
323
+ * a record never relaxes it. Null when nothing is known.
324
+ */
325
+ export function effectivePolicy(state, repo, fresh) {
326
+ const base = basePolicy(storedPolicy(state, repo), fresh);
327
+ if (!isBlocklisted(state, repo))
328
+ return base;
329
+ const policy = base ?? { ...UNKNOWN_POLICY, updatedAt: EPOCH };
330
+ return {
331
+ ...policy,
332
+ aiPolicy: 'banned',
333
+ source: [{ file: BLOCKLIST_SOURCE, quotedLine: quote(repo) }, ...policy.source].slice(0, 10),
334
+ };
335
+ }
336
+ const REPO_KEY = /^[^/\s]+\/[^/\s]+$/;
337
+ /**
338
+ * Where a ban came from, for the user: nothing for one they confirmed; how to
339
+ * lift it otherwise. A blocklist ban is lifted in config, an unreviewed one
340
+ * with `policy set`.
341
+ */
342
+ export function banNote(policy, repo) {
343
+ if (policy.source[0]?.file === BLOCKLIST_SOURCE) {
344
+ return ` (from aiPolicyBlocklist: run \`oss-autopilot policy set --repo ${repo} --ai-policy allowed\` to take it off the list if this is wrong)`;
345
+ }
346
+ if (policy.reviewedByUser)
347
+ return '';
348
+ return ` (read from the repo docs, not reviewed: run \`oss-autopilot policy set --repo ${repo} --ai-policy allowed\` if this is a misreading)`;
349
+ }
350
+ /** Stored `banned` records (lowercase keys), reviewed or not. */
351
+ export function storedBans(state) {
352
+ const bans = [];
353
+ if (!state.repoPolicies)
354
+ return bans;
355
+ const repos = Object.keys(state.repoPolicies);
356
+ for (const repo of repos) {
357
+ // A hand-edited or corrupt key is not a repo; never hand it to search.
358
+ if (!REPO_KEY.test(repo))
359
+ continue;
360
+ const policy = storedPolicy(state, repo);
361
+ if (policy?.aiPolicy === 'banned')
362
+ bans.push({ repo, reviewedByUser: policy.reviewedByUser });
363
+ }
364
+ return bans;
365
+ }
366
+ /**
367
+ * Repos search leaves out: the blocklist as written, then bans the user
368
+ * confirmed. A ban vet read from the docs but nobody reviewed stays searchable
369
+ * (a heuristic must not shrink discovery on its own); vet still says skip.
370
+ */
371
+ export function bannedRepos(state) {
372
+ const blocklist = state.config.aiPolicyBlocklist ?? [];
373
+ const listed = new Set(blocklist.map((r) => r.toLowerCase()));
374
+ const reviewed = storedBans(state)
375
+ .filter((b) => b.reviewedByUser && !listed.has(b.repo))
376
+ .map((b) => b.repo);
377
+ return [...blocklist, ...reviewed];
378
+ }
379
+ export function summarizePolicy(policy) {
380
+ const { aiPolicy, cla, prGate, commitRules, maxOpenAiPRs, reviewedByUser } = policy;
381
+ return { aiPolicy, cla, prGate, commitRules, ...(maxOpenAiPRs !== undefined && { maxOpenAiPRs }), reviewedByUser };
382
+ }
383
+ /** `{ policy }` with the summary to spread into an output, or `{}` when there is no policy. */
384
+ export function policyField(policy) {
385
+ return policy ? { policy: summarizePolicy(policy) } : {};
386
+ }
387
+ /** Quoted lines and disclosure text inside `<github-content>` fences, for agent-facing output. */
388
+ export function fencePolicyText(repo, policy) {
389
+ const lines = policy.source.map((s) => `${s.file}: ${s.quotedLine}`);
390
+ return {
391
+ ...(policy.disclosureText !== undefined && {
392
+ disclosureText: wrapUntrustedContent(policy.disclosureText, repo, { source: 'repo-policy' }),
393
+ }),
394
+ ...(lines.length > 0 && { sources: wrapUntrustedContent(lines.join('\n'), repo, { source: 'repo-policy' }) }),
395
+ };
396
+ }
397
+ /** Same rules, ignoring when they were recorded. */
398
+ export function isSamePolicy(a, b) {
399
+ return JSON.stringify({ ...a, updatedAt: '' }) === JSON.stringify({ ...b, updatedAt: '' });
400
+ }
@@ -71,12 +71,60 @@ export interface Stats {
71
71
  /** Number of PRs needing a response. Always 0 in v2 (sourced from fresh fetch instead). */
72
72
  needsResponse: number;
73
73
  }
74
+ /** What {@link evictExcludedRepos} removed. */
75
+ export interface EvictedRepos {
76
+ /** Ledger rows removed because their owner is in `config.untrackedOrgs`. */
77
+ untrackedOrgRows: number;
78
+ /** Ledger rows removed because GitHub reported their repository private. */
79
+ privateRows: number;
80
+ /** repoScores entries deleted, for either reason. */
81
+ repos: number;
82
+ }
83
+ /**
84
+ * Remove what is stored about repositories whose PRs are never tracked
85
+ * (#1924), so they are no longer counted, shown or synced:
86
+ *
87
+ * - repositories in `config.untrackedOrgs` (the user's employer);
88
+ * - repositories in `privateRepos`. The caller must pass only repositories a
89
+ * successful GitHub read reported `private: true` in this run. A repository
90
+ * that could not be read (404, network error) or whose visibility is not
91
+ * known is not private for this purpose: a deleted, renamed or transferred
92
+ * repository keeps its rows.
93
+ *
94
+ * Earlier versions stored both kinds through the dashboard's ledger fetch and
95
+ * counted them in the count searches. For each such repository the merged and
96
+ * closed ledger rows go, and so does its repoScores entry when it had ledger
97
+ * rows or carries PR counts. An entry without either was written by issue
98
+ * discovery, which untracked organisations do not affect, and stays; deleting
99
+ * it would only make discovery write it again.
100
+ *
101
+ * Idempotent; changes nothing when there are no untracked organisations and
102
+ * no private repositories.
103
+ */
104
+ export declare function evictExcludedRepos(state: AgentState, privateRepos: Iterable<string>): EvictedRepos;
74
105
  /**
75
106
  * Reconcile repoScores merged/closed counts with the stored PR arrays.
76
107
  * Counts PRs per repo from the arrays and bumps repoScores counters when
77
108
  * the array count is higher (never decreases). Returns true if any updates were made.
78
109
  */
79
110
  export declare function reconcilePRCounts(state: AgentState, mergedPRs: StoredMergedPR[], closedPRs: StoredClosedPR[]): boolean;
111
+ /**
112
+ * Drop closed-ledger entries that are no longer closed without merge (#1923):
113
+ * every URL in the merged ledger, plus `notClosedUrls` (PRs the caller just
114
+ * saw open). Closed entries matching neither stay, so a closed PR that is
115
+ * simply outside the current fetch window is kept. Matching is by exact URL,
116
+ * the same key both ledgers deduplicate on.
117
+ *
118
+ * A repo's `closedWithoutMergeCount` drops to its new ledger count when it was
119
+ * at or below the old one, i.e. when the ledger could have been what held it
120
+ * up. A higher counter was set by daily's closed-PR search and is not touched
121
+ * here: the next daily run overwrites it with the search count while the repo
122
+ * is still in that search, or zeroes it and re-raises it to the ledger count
123
+ * once the repo has left an untruncated search (resetStaleClosedCounts).
124
+ *
125
+ * Idempotent. Returns the number of entries removed.
126
+ */
127
+ export declare function evictClosedPRs(state: AgentState, notClosedUrls: Iterable<string>): number;
80
128
  /**
81
129
  * Detect repos that GitHub now reports under a different owner/name.
82
130
  *
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { isBelowMinStars } from './types.js';
11
11
  import { debug, warn } from './logger.js';
12
- import { parseGitHubUrl } from './urls.js';
12
+ import { parseGitHubUrl, isUntrackedOrg } from './urls.js';
13
13
  const MODULE = 'scoring';
14
14
  // ── Scoring constants (#1054) ─────────────────────────────────────────
15
15
  // Previously inlined as magic numbers in `calculateScore`. Extracted with
@@ -222,6 +222,78 @@ function countByRepo(prs) {
222
222
  }
223
223
  return counts;
224
224
  }
225
+ /** The ledger rows to keep; the ones dropped are tallied in `excluded`. */
226
+ function keepTrackedRows(prs, reasonFor, excluded) {
227
+ return prs.filter((pr) => {
228
+ const parsed = parseGitHubUrl(pr.url);
229
+ if (!parsed)
230
+ return true;
231
+ const repo = `${parsed.owner}/${parsed.repo}`.toLowerCase();
232
+ const reason = reasonFor(repo);
233
+ if (!reason)
234
+ return true;
235
+ excluded.counts[reason]++;
236
+ excluded.repoKeys.add(repo);
237
+ return false;
238
+ });
239
+ }
240
+ /**
241
+ * Delete the repoScores entries of excluded repositories that had ledger rows
242
+ * or carry PR counts. Returns how many were deleted.
243
+ */
244
+ function deleteExcludedScores(state, reasonFor, reposWithRows) {
245
+ const doomed = Object.values(state.repoScores).filter((score) => {
246
+ const hasPRs = score.mergedPRCount > 0 || score.closedWithoutMergeCount > 0;
247
+ return (hasPRs || reposWithRows.has(score.repo.toLowerCase())) && reasonFor(score.repo) !== undefined;
248
+ });
249
+ for (const score of doomed)
250
+ delete state.repoScores[score.repo];
251
+ return doomed.length;
252
+ }
253
+ /**
254
+ * Remove what is stored about repositories whose PRs are never tracked
255
+ * (#1924), so they are no longer counted, shown or synced:
256
+ *
257
+ * - repositories in `config.untrackedOrgs` (the user's employer);
258
+ * - repositories in `privateRepos`. The caller must pass only repositories a
259
+ * successful GitHub read reported `private: true` in this run. A repository
260
+ * that could not be read (404, network error) or whose visibility is not
261
+ * known is not private for this purpose: a deleted, renamed or transferred
262
+ * repository keeps its rows.
263
+ *
264
+ * Earlier versions stored both kinds through the dashboard's ledger fetch and
265
+ * counted them in the count searches. For each such repository the merged and
266
+ * closed ledger rows go, and so does its repoScores entry when it had ledger
267
+ * rows or carries PR counts. An entry without either was written by issue
268
+ * discovery, which untracked organisations do not affect, and stays; deleting
269
+ * it would only make discovery write it again.
270
+ *
271
+ * Idempotent; changes nothing when there are no untracked organisations and
272
+ * no private repositories.
273
+ */
274
+ export function evictExcludedRepos(state, privateRepos) {
275
+ const orgs = state.config.untrackedOrgs ?? [];
276
+ const privateSet = new Set();
277
+ for (const repo of privateRepos)
278
+ privateSet.add(repo.toLowerCase());
279
+ const reasonFor = (repo) => {
280
+ if (privateSet.has(repo.toLowerCase()))
281
+ return 'private';
282
+ return isUntrackedOrg(repo.split('/', 1)[0], orgs) ? 'untracked-org' : undefined;
283
+ };
284
+ const excluded = { counts: { 'untracked-org': 0, private: 0 }, repoKeys: new Set() };
285
+ const keptMerged = keepTrackedRows(state.mergedPRs ?? [], reasonFor, excluded);
286
+ const keptClosed = keepTrackedRows(state.closedPRs ?? [], reasonFor, excluded);
287
+ if (excluded.repoKeys.size > 0) {
288
+ state.mergedPRs = keptMerged;
289
+ state.closedPRs = keptClosed;
290
+ }
291
+ return {
292
+ untrackedOrgRows: excluded.counts['untracked-org'],
293
+ privateRows: excluded.counts.private,
294
+ repos: deleteExcludedScores(state, reasonFor, excluded.repoKeys),
295
+ };
296
+ }
225
297
  /**
226
298
  * Reconcile repoScores merged/closed counts with the stored PR arrays.
227
299
  * Counts PRs per repo from the arrays and bumps repoScores counters when
@@ -248,6 +320,44 @@ function reconcileField(state, countsByRepo, field) {
248
320
  }
249
321
  return updated;
250
322
  }
323
+ /**
324
+ * Drop closed-ledger entries that are no longer closed without merge (#1923):
325
+ * every URL in the merged ledger, plus `notClosedUrls` (PRs the caller just
326
+ * saw open). Closed entries matching neither stay, so a closed PR that is
327
+ * simply outside the current fetch window is kept. Matching is by exact URL,
328
+ * the same key both ledgers deduplicate on.
329
+ *
330
+ * A repo's `closedWithoutMergeCount` drops to its new ledger count when it was
331
+ * at or below the old one, i.e. when the ledger could have been what held it
332
+ * up. A higher counter was set by daily's closed-PR search and is not touched
333
+ * here: the next daily run overwrites it with the search count while the repo
334
+ * is still in that search, or zeroes it and re-raises it to the ledger count
335
+ * once the repo has left an untruncated search (resetStaleClosedCounts).
336
+ *
337
+ * Idempotent. Returns the number of entries removed.
338
+ */
339
+ export function evictClosedPRs(state, notClosedUrls) {
340
+ const closed = state.closedPRs ?? [];
341
+ const merged = state.mergedPRs ?? [];
342
+ const gone = new Set(notClosedUrls);
343
+ for (const pr of merged)
344
+ gone.add(pr.url);
345
+ const kept = closed.filter((pr) => !gone.has(pr.url));
346
+ if (kept.length === closed.length)
347
+ return 0;
348
+ const before = countByRepo(closed);
349
+ const after = countByRepo(kept);
350
+ state.closedPRs = kept;
351
+ for (const [repo, was] of before) {
352
+ const now = after.get(repo) ?? 0;
353
+ const current = state.repoScores[repo]?.closedWithoutMergeCount ?? 0;
354
+ if (current > now && current <= was) {
355
+ debug(MODULE, `Evicting reopened/merged PRs: ${repo} closedWithoutMergeCount ${current} → ${now}`);
356
+ updateRepoScore(state, repo, { closedWithoutMergeCount: now });
357
+ }
358
+ }
359
+ return closed.length - kept.length;
360
+ }
251
361
  /**
252
362
  * Detect repos that GitHub now reports under a different owner/name.
253
363
  *
@@ -17,25 +17,28 @@ export interface ReviewComment {
17
17
  in_reply_to_id?: number;
18
18
  pull_request_review_id?: number | null;
19
19
  }
20
- /**
21
- * Determine review decision from reviews list.
22
- * Groups reviews by user, keeping each user's latest verdict, then checks
23
- * for CHANGES_REQUESTED or APPROVED states.
24
- *
25
- * Only APPROVED, CHANGES_REQUESTED and DISMISSED change a reviewer's standing
26
- * verdict on GitHub. COMMENTED is also what GitHub records for every inline
27
- * reply, so it must not overwrite an earlier verdict from the same reviewer.
28
- *
29
- * Bot-authored reviews (e.g. an AI review bot posting APPROVE) are ignored so a
30
- * bot alone never reads as maintainer approval or a changes request (#1840).
31
- */
32
- export declare function determineReviewDecision(reviews: Array<{
20
+ /** The review fields the verdict helpers read. */
21
+ type VerdictReview = {
33
22
  state?: string | null;
23
+ submitted_at?: string | null;
34
24
  user?: {
35
25
  login?: string;
36
26
  type?: string | null;
37
27
  } | null;
38
- }>): ReviewDecision;
28
+ };
29
+ /**
30
+ * Determine review decision from reviews list: changes requested when any
31
+ * reviewer's standing verdict ({@link standingVerdicts}) is CHANGES_REQUESTED,
32
+ * otherwise approved when any is APPROVED.
33
+ */
34
+ export declare function determineReviewDecision(reviews: VerdictReview[]): ReviewDecision;
35
+ /**
36
+ * When `login`'s standing approval (see {@link standingVerdicts}) was
37
+ * submitted, or undefined when that account has no standing APPROVED verdict.
38
+ * Logins compare case-insensitively. Lets the status logic tell whether the
39
+ * author of an unanswered comment approved at or after writing it (#1920).
40
+ */
41
+ export declare function getStandingApprovalDate(reviews: VerdictReview[], login: string | undefined): string | undefined;
39
42
  /**
40
43
  * Get the date of the latest CHANGES_REQUESTED review (from any human reviewer).
41
44
  * Used to detect needs_changes status when review feedback is in inline comments.
@@ -86,12 +89,19 @@ export declare function getFirstMaintainerResponseAt(comments: Array<ActorFields
86
89
  * Check if there are unresponded comments from maintainers.
87
90
  * Combines issue comments and review comments into a timeline,
88
91
  * then finds maintainer comments after the user's last comment.
92
+ *
93
+ * Whose items count (#1921): every review from another human, and every issue
94
+ * comment from another human except a passer-by's. A passer-by is an account
95
+ * whose association is NONE, FIRST_TIMER, FIRST_TIME_CONTRIBUTOR or MANNEQUIN
96
+ * ({@link NO_STANDING_ASSOCIATIONS}) and that has submitted no review (in any
97
+ * state) and no inline review comment on this PR. So an OWNER, MEMBER,
98
+ * COLLABORATOR or CONTRIBUTOR always counts, anyone who reviewed the PR counts
99
+ * whatever their association, and an issue comment with no association data
100
+ * counts: missing a maintainer costs more than surfacing a passer-by. This is
101
+ * deliberately wider than {@link isMaintainerEngagement}, which drives the
102
+ * dormancy clock.
89
103
  */
90
- export declare function checkUnrespondedComments(comments: Array<{
91
- user?: {
92
- login?: string;
93
- type?: string | null;
94
- } | null;
104
+ export declare function checkUnrespondedComments(comments: Array<ActorFields & {
95
105
  body?: string | null;
96
106
  created_at: string;
97
107
  }>, reviews: Array<{
@@ -106,6 +116,11 @@ export declare function checkUnrespondedComments(comments: Array<{
106
116
  }>, reviewComments: ReviewComment[], username: string): {
107
117
  hasUnrespondedComment: boolean;
108
118
  lastMaintainerComment?: FetchedPR['lastMaintainerComment'];
119
+ /** Every unanswered maintainer item, oldest first; the last one is `lastMaintainerComment`. */
120
+ unrespondedComments: Array<{
121
+ author: string;
122
+ createdAt: string;
123
+ }>;
109
124
  };
110
125
  /** A non-comment PR event: a commit, force-push, review request or label. */
111
126
  export interface ActivityEvent {