@oss-autopilot/core 3.42.5 → 3.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +428 -27
  3. package/dist/cli.bundle.cjs +212 -156
  4. package/dist/commands/check-integration.js +5 -1
  5. package/dist/commands/cleanup.d.ts +80 -0
  6. package/dist/commands/cleanup.js +334 -0
  7. package/dist/commands/comments.d.ts +14 -1
  8. package/dist/commands/comments.js +17 -5
  9. package/dist/commands/config.d.ts +2 -0
  10. package/dist/commands/config.js +63 -6
  11. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  12. package/dist/commands/daily-dismiss-filter.js +17 -1
  13. package/dist/commands/daily-ledger.d.ts +150 -0
  14. package/dist/commands/daily-ledger.js +248 -0
  15. package/dist/commands/daily-recent-prs.d.ts +26 -0
  16. package/dist/commands/daily-recent-prs.js +55 -0
  17. package/dist/commands/daily-render.d.ts +2 -1
  18. package/dist/commands/daily-render.js +4 -1
  19. package/dist/commands/daily.d.ts +5 -1
  20. package/dist/commands/daily.js +83 -93
  21. package/dist/commands/dashboard-cache.d.ts +2 -0
  22. package/dist/commands/dashboard-cache.js +33 -8
  23. package/dist/commands/dashboard-data.js +113 -69
  24. package/dist/commands/dashboard-gist-sync.js +3 -1
  25. package/dist/commands/dashboard-lifecycle.d.ts +36 -8
  26. package/dist/commands/dashboard-lifecycle.js +132 -39
  27. package/dist/commands/dashboard-process.d.ts +49 -1
  28. package/dist/commands/dashboard-process.js +111 -12
  29. package/dist/commands/dashboard-server.js +89 -23
  30. package/dist/commands/detect-formatters.js +1 -0
  31. package/dist/commands/dismiss.js +11 -7
  32. package/dist/commands/doctor.d.ts +15 -1
  33. package/dist/commands/doctor.js +66 -5
  34. package/dist/commands/draft.d.ts +77 -0
  35. package/dist/commands/draft.js +218 -0
  36. package/dist/commands/eval.js +1 -0
  37. package/dist/commands/fork-prune.d.ts +58 -0
  38. package/dist/commands/fork-prune.js +247 -0
  39. package/dist/commands/guidelines.d.ts +69 -2
  40. package/dist/commands/guidelines.js +158 -14
  41. package/dist/commands/index.d.ts +29 -4
  42. package/dist/commands/index.js +20 -3
  43. package/dist/commands/issue-thread.d.ts +46 -0
  44. package/dist/commands/issue-thread.js +123 -0
  45. package/dist/commands/ledger-backfill.d.ts +9 -0
  46. package/dist/commands/ledger-backfill.js +44 -1
  47. package/dist/commands/list-mark-done.d.ts +2 -1
  48. package/dist/commands/list-mark-done.js +3 -1
  49. package/dist/commands/list-move-tier.d.ts +2 -1
  50. package/dist/commands/list-move-tier.js +3 -1
  51. package/dist/commands/local-repos.js +10 -5
  52. package/dist/commands/locate-issue-list.d.ts +40 -17
  53. package/dist/commands/locate-issue-list.js +148 -88
  54. package/dist/commands/move.js +7 -1
  55. package/dist/commands/overnight-handoff.d.ts +17 -7
  56. package/dist/commands/overnight-handoff.js +36 -14
  57. package/dist/commands/overnight-push-prep.d.ts +14 -8
  58. package/dist/commands/overnight-push-prep.js +107 -35
  59. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  60. package/dist/commands/overnight-tool-rules.js +217 -0
  61. package/dist/commands/overnight.d.ts +5 -6
  62. package/dist/commands/overnight.js +61 -140
  63. package/dist/commands/parse-list.js +7 -1
  64. package/dist/commands/policy.d.ts +90 -0
  65. package/dist/commands/policy.js +276 -0
  66. package/dist/commands/pr-create.d.ts +48 -0
  67. package/dist/commands/pr-create.js +200 -0
  68. package/dist/commands/pr-preflight.d.ts +69 -0
  69. package/dist/commands/pr-preflight.js +348 -0
  70. package/dist/commands/repo-vet.d.ts +9 -0
  71. package/dist/commands/repo-vet.js +36 -11
  72. package/dist/commands/scout-bridge.js +18 -8
  73. package/dist/commands/search.js +7 -0
  74. package/dist/commands/setup.d.ts +3 -3
  75. package/dist/commands/setup.js +160 -48
  76. package/dist/commands/skip-add.js +10 -1
  77. package/dist/commands/startup.d.ts +12 -3
  78. package/dist/commands/startup.js +82 -49
  79. package/dist/commands/state-cmd.d.ts +2 -0
  80. package/dist/commands/state-cmd.js +5 -1
  81. package/dist/commands/stats.js +1 -0
  82. package/dist/commands/status.js +6 -0
  83. package/dist/commands/strategy.js +1 -0
  84. package/dist/commands/validation.d.ts +5 -0
  85. package/dist/commands/validation.js +5 -0
  86. package/dist/commands/vet-list.d.ts +6 -0
  87. package/dist/commands/vet-list.js +26 -1
  88. package/dist/commands/vet.d.ts +20 -0
  89. package/dist/commands/vet.js +133 -2
  90. package/dist/commands/work.d.ts +4 -0
  91. package/dist/commands/work.js +34 -11
  92. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  93. package/dist/core/anti-llm-policy.d.ts +3 -0
  94. package/dist/core/anti-llm-policy.js +3 -0
  95. package/dist/core/auth.js +2 -0
  96. package/dist/core/ci-analysis.d.ts +7 -2
  97. package/dist/core/ci-analysis.js +76 -21
  98. package/dist/core/commit-date.d.ts +45 -0
  99. package/dist/core/commit-date.js +45 -0
  100. package/dist/core/compliance-score.d.ts +3 -0
  101. package/dist/core/compliance-score.js +13 -9
  102. package/dist/core/config-registry.d.ts +27 -2
  103. package/dist/core/config-registry.js +94 -7
  104. package/dist/core/contributing.d.ts +2 -3
  105. package/dist/core/contributing.js +2 -3
  106. package/dist/core/daily-logic.d.ts +30 -5
  107. package/dist/core/daily-logic.js +68 -19
  108. package/dist/core/errors.d.ts +37 -3
  109. package/dist/core/errors.js +54 -5
  110. package/dist/core/fork-prune.d.ts +149 -0
  111. package/dist/core/fork-prune.js +333 -0
  112. package/dist/core/gist-health.d.ts +15 -3
  113. package/dist/core/gist-health.js +8 -0
  114. package/dist/core/gist-state-store.d.ts +24 -4
  115. package/dist/core/gist-state-store.js +98 -51
  116. package/dist/core/github-stats.d.ts +110 -16
  117. package/dist/core/github-stats.js +295 -110
  118. package/dist/core/http-cache.d.ts +0 -10
  119. package/dist/core/http-cache.js +0 -19
  120. package/dist/core/index.d.ts +13 -6
  121. package/dist/core/index.js +16 -6
  122. package/dist/core/issue-conversation.d.ts +8 -2
  123. package/dist/core/issue-conversation.js +31 -12
  124. package/dist/core/local-config.d.ts +95 -0
  125. package/dist/core/local-config.js +270 -0
  126. package/dist/core/merged-pr-notes.d.ts +2 -2
  127. package/dist/core/pacing.d.ts +41 -0
  128. package/dist/core/pacing.js +115 -0
  129. package/dist/core/pagination.d.ts +55 -0
  130. package/dist/core/pagination.js +59 -0
  131. package/dist/core/paths.d.ts +7 -0
  132. package/dist/core/paths.js +9 -0
  133. package/dist/core/pr-assembly.d.ts +2 -0
  134. package/dist/core/pr-assembly.js +6 -2
  135. package/dist/core/pr-graphql.d.ts +53 -4
  136. package/dist/core/pr-graphql.js +87 -14
  137. package/dist/core/pr-monitor.d.ts +35 -12
  138. package/dist/core/pr-monitor.js +110 -26
  139. package/dist/core/pr-preflight.d.ts +154 -0
  140. package/dist/core/pr-preflight.js +753 -0
  141. package/dist/core/pr-quality-rubric.d.ts +0 -6
  142. package/dist/core/pr-quality-rubric.js +0 -8
  143. package/dist/core/pr-template.d.ts +2 -0
  144. package/dist/core/pr-template.js +5 -1
  145. package/dist/core/prose-script.d.ts +72 -0
  146. package/dist/core/prose-script.js +223 -0
  147. package/dist/core/repo-policy.d.ts +111 -0
  148. package/dist/core/repo-policy.js +428 -0
  149. package/dist/core/repo-score-manager.d.ts +66 -0
  150. package/dist/core/repo-score-manager.js +140 -1
  151. package/dist/core/review-analysis.d.ts +49 -21
  152. package/dist/core/review-analysis.js +89 -15
  153. package/dist/core/reviewed-prs-fetch.js +11 -29
  154. package/dist/core/reviewed-prs.js +8 -15
  155. package/dist/core/stale-data.d.ts +78 -0
  156. package/dist/core/stale-data.js +153 -0
  157. package/dist/core/state-persistence.d.ts +62 -27
  158. package/dist/core/state-persistence.js +338 -119
  159. package/dist/core/state-schema.d.ts +152 -210
  160. package/dist/core/state-schema.js +232 -80
  161. package/dist/core/state.d.ts +81 -8
  162. package/dist/core/state.js +239 -46
  163. package/dist/core/status-determination.js +32 -12
  164. package/dist/core/strategy.js +3 -1
  165. package/dist/core/types.d.ts +22 -1
  166. package/dist/core/types.js +1 -0
  167. package/dist/core/untrusted-content.d.ts +30 -11
  168. package/dist/core/untrusted-content.js +95 -42
  169. package/dist/core/urls.d.ts +33 -0
  170. package/dist/core/urls.js +94 -0
  171. package/dist/dashboard/assets/chart-panel-B-nLVgzQ.js +3 -0
  172. package/dist/dashboard/assets/index-5IvMGokL.js +55 -0
  173. package/dist/dashboard/index.html +1 -1
  174. package/dist/formatters/json.d.ts +432 -10
  175. package/dist/formatters/json.js +156 -1
  176. package/package.json +6 -6
  177. package/dist/core/ci-enforced-tools.d.ts +0 -35
  178. package/dist/core/ci-enforced-tools.js +0 -109
  179. package/dist/core/comment-decision.d.ts +0 -79
  180. package/dist/core/comment-decision.js +0 -82
  181. package/dist/core/extraction-categories.d.ts +0 -55
  182. package/dist/core/extraction-categories.js +0 -108
  183. package/dist/core/follow-up-history.d.ts +0 -40
  184. package/dist/core/follow-up-history.js +0 -71
  185. package/dist/core/issue-effort.d.ts +0 -29
  186. package/dist/core/issue-effort.js +0 -47
  187. package/dist/core/maintainer-hints.d.ts +0 -23
  188. package/dist/core/maintainer-hints.js +0 -36
  189. package/dist/core/workflow-state.d.ts +0 -56
  190. package/dist/core/workflow-state.js +0 -101
  191. package/dist/dashboard/assets/chart-panel-DPKNBUts.js +0 -3
  192. package/dist/dashboard/assets/index-B25bZOYX.js +0 -55
@@ -0,0 +1,753 @@
1
+ /**
2
+ * PR preflight checks (#1952): the gate that runs before a branch is pushed
3
+ * and a PR is opened in someone else's repository.
4
+ *
5
+ * Every check is a pure function over `PreflightFacts`, which the
6
+ * `pr-preflight` command gathers from the local clone and read-only GitHub calls.
7
+ * A new check is one more function in `PREFLIGHT_CHECKS` (plus the facts it
8
+ * needs); the verdict and the output shape do not change.
9
+ */
10
+ import { hasDescription } from './compliance-score.js';
11
+ import { DEFAULT_REPO_SCRIPTS, describeMismatch, scriptMismatch, titleMismatch, } from './prose-script.js';
12
+ import { banNote, fencePolicyText, quote, summarizePolicy } from './repo-policy.js';
13
+ import { wrapUntrustedContent } from './untrusted-content.js';
14
+ import { findClosingRefs, isOwnRepo, splitRepo } from './urls.js';
15
+ /** Past this many commits behind, the drift check warns even when no upstream commit touches the branch's files. */
16
+ export const BEHIND_WARN_THRESHOLD = 20;
17
+ function check(id, status, summary, details) {
18
+ return details ? { id, status, summary, details } : { id, status, summary };
19
+ }
20
+ /** Why a network check has nothing to judge: GitHub was not consulted, or the read failed. */
21
+ function skipReason(facts, error, fallback) {
22
+ if (facts.networkSkip !== null)
23
+ return facts.networkSkip;
24
+ return error === null ? fallback : `GitHub request failed: ${error}`;
25
+ }
26
+ function driftSummary(facts, ref, behind) {
27
+ if (facts.fetchError !== null) {
28
+ return { status: 'warn', summary: `git fetch failed (${facts.fetchError}); ${ref} may be stale` };
29
+ }
30
+ const upstreamSha = facts.github?.baseHeadSha;
31
+ if (upstreamSha && upstreamSha !== facts.remoteRefSha) {
32
+ return {
33
+ status: 'warn',
34
+ summary: `${ref} is stale (GitHub is at ${upstreamSha.slice(0, 9)}), so ${behind} behind is a lower bound; run again with --fetch`,
35
+ };
36
+ }
37
+ if (facts.overlappingCommits.length > 0) {
38
+ return {
39
+ status: 'warn',
40
+ summary: `${facts.overlappingCommits.length} commit(s) on ${ref} since the branch point touch files this branch changes; the same fix may have landed`,
41
+ };
42
+ }
43
+ if (behind > BEHIND_WARN_THRESHOLD) {
44
+ return { status: 'warn', summary: `${behind} commits behind ${ref}; rebase to lower the conflict risk` };
45
+ }
46
+ const unverified = facts.github
47
+ ? ''
48
+ : ` (freshness of ${ref} not verified: ${skipReason(facts, facts.githubError, 'no GitHub data')})`;
49
+ const position = behind === 0 ? `up to date with ${ref}` : `${behind} commit(s) behind ${ref}, none touching this branch's files`;
50
+ return { status: 'pass', summary: position + unverified };
51
+ }
52
+ /** The measurements, or undefined when the ref is not fetched. Commit subjects are third-party text, so they are fenced. */
53
+ function driftDetails(facts, ref) {
54
+ if (facts.remoteRefSha === null || facts.behind === null)
55
+ return undefined;
56
+ const subjects = facts.overlappingCommits;
57
+ const measured = { ref, behind: facts.behind, ahead: facts.ahead, mergeBase: facts.mergeBase };
58
+ if (subjects.length === 0)
59
+ return { ...measured, overlapCount: 0 };
60
+ return {
61
+ ...measured,
62
+ overlapCount: subjects.length,
63
+ overlappingCommits: wrapUntrustedContent(subjects.join('\n'), 'commit-subjects'),
64
+ };
65
+ }
66
+ /**
67
+ * Commits on the upstream target branch that this branch does not have. Never fetches: a stale ref is reported.
68
+ * The local ref is compared with GitHub only when its remote points at the upstream repository; in a
69
+ * fork-only clone the two are different branches, and "stale, fetch again" would never clear.
70
+ */
71
+ export function checkDrift(facts) {
72
+ const id = 'upstream-drift';
73
+ if (!facts.remote)
74
+ return check(id, 'warn', 'no git remote to compare against');
75
+ if (!facts.base)
76
+ return check(id, 'warn', 'could not determine the default branch; pass --base <branch>');
77
+ const ref = `${facts.remote}/${facts.base}`;
78
+ const details = driftDetails(facts, ref);
79
+ if (facts.repo !== null && !isSameRepo(facts.remoteRepo, facts.repo)) {
80
+ const measured = details
81
+ ? `drift was measured against ${ref} instead (${facts.behind} behind)`
82
+ : 'drift was not measured';
83
+ return check(id, 'warn', `no remote points at ${facts.repo}, so ${measured}; add a remote for ${facts.repo}`, details);
84
+ }
85
+ if (!details || facts.behind === null) {
86
+ const why = facts.fetchError === null ? '' : ` (git fetch failed: ${facts.fetchError})`;
87
+ return check(id, 'warn', `${ref} is not fetched locally${why}; run again with --fetch`);
88
+ }
89
+ const { status, summary } = driftSummary(facts, ref, facts.behind);
90
+ return check(id, status, summary, details);
91
+ }
92
+ function isSameRepo(a, b) {
93
+ return a !== null && b !== null && a.toLowerCase() === b.toLowerCase();
94
+ }
95
+ /** The target branch is missing upstream or is not the default branch. */
96
+ function baseTargetProblem(repo, base, github) {
97
+ const { defaultBranch } = github;
98
+ if (github.baseHeadSha === null) {
99
+ return { status: 'fail', summary: `branch ${base} does not exist on ${repo} (default branch: ${defaultBranch})` };
100
+ }
101
+ if (base === defaultBranch)
102
+ return null;
103
+ return {
104
+ status: 'warn',
105
+ summary: `the PR would target ${base}, not ${defaultBranch}, the default branch of ${repo}; right only if the contribution guide says so`,
106
+ };
107
+ }
108
+ /** The clone does not line up with the upstream repository: wrong repository, renamed default branch. */
109
+ function baseCloneProblem(facts, repo, github) {
110
+ if (github.parent && !facts.issueUrl) {
111
+ return `${repo} is a fork of ${github.parent}; add a remote for the parent or pass the issue URL so the checks run against it`;
112
+ }
113
+ const remote = facts.remote ?? '(none)';
114
+ if (facts.localDefault !== null && facts.localDefault !== github.defaultBranch) {
115
+ return `${repo} now defaults to ${github.defaultBranch} but the clone records ${facts.localDefault}; run git remote set-head ${remote} -a`;
116
+ }
117
+ return null;
118
+ }
119
+ /** The PR targets a branch that exists upstream and is the default branch, on the repository the remote points at. */
120
+ export function checkBaseBranch(facts) {
121
+ const id = 'base-branch';
122
+ const { github, repo, base } = facts;
123
+ if (!github || !repo || !base) {
124
+ const guess = base ? `; local guess: ${base}` : '';
125
+ return check(id, 'skipped', skipReason(facts, facts.githubError, 'no upstream repository') + guess);
126
+ }
127
+ const details = { repo, base, defaultBranch: github.defaultBranch };
128
+ const target = baseTargetProblem(repo, base, github);
129
+ if (target)
130
+ return check(id, target.status, target.summary, details);
131
+ const clone = baseCloneProblem(facts, repo, github);
132
+ if (clone)
133
+ return check(id, 'warn', clone, details);
134
+ return check(id, 'pass', `targets ${base}, the default branch of ${repo}`, details);
135
+ }
136
+ /** The head is a real feature branch, and the user has somewhere to push it. */
137
+ export function checkHeadBranch(facts) {
138
+ const id = 'head-branch';
139
+ const { branch, repo, login } = facts;
140
+ if (branch === null)
141
+ return check(id, 'fail', 'detached HEAD: check out a feature branch before opening a PR');
142
+ if (branch === facts.base) {
143
+ return check(id, 'fail', `on ${branch}, the branch the PR would target; create a feature branch`);
144
+ }
145
+ if (branch === (facts.github?.defaultBranch ?? facts.localDefault)) {
146
+ return check(id, 'warn', `on ${branch}, the default branch; a PR is normally opened from a feature branch`);
147
+ }
148
+ if (!login) {
149
+ return check(id, 'warn', 'githubUsername is not configured, so no fork remote could be confirmed; run setup');
150
+ }
151
+ if (repo && (facts.github?.canPush || isOwnRepo(splitRepo(repo).owner, login))) {
152
+ return check(id, 'pass', `${branch} can be pushed to ${repo} directly`);
153
+ }
154
+ if (facts.pushRemote) {
155
+ return check(id, 'pass', `${branch} can be pushed to your fork (remote ${facts.pushRemote})`);
156
+ }
157
+ return check(id, 'warn', `no remote is owned by ${login}; fork the repository and add the fork as a remote`);
158
+ }
159
+ export function checkWorkingTree(facts) {
160
+ const id = 'working-tree';
161
+ if (facts.dirtyCount === 0)
162
+ return check(id, 'pass', 'working tree is clean');
163
+ return check(id, 'warn', `${facts.dirtyCount} uncommitted change(s) would not be part of the PR`, {
164
+ dirtyCount: facts.dirtyCount,
165
+ });
166
+ }
167
+ const COMPETING_STATUS = {
168
+ available: 'pass',
169
+ 'own-open-pr': 'warn',
170
+ 'at-risk': 'warn',
171
+ taken: 'fail',
172
+ closed: 'fail',
173
+ };
174
+ /** Someone else's open closing PR, an assignment, or a closed issue, from the same verification `verify-issue` runs. */
175
+ export function checkCompetingWork(facts) {
176
+ const id = 'competing-work';
177
+ if (!facts.issueUrl)
178
+ return check(id, 'skipped', 'no issue given');
179
+ const { issue } = facts;
180
+ if (!issue && facts.issueError !== null) {
181
+ // The duplicate-PR guard did not run: a warn, so nobody pushes on a skipped check.
182
+ return check(id, 'warn', `could not verify the issue (${facts.issueError}); check it for competing work by hand`);
183
+ }
184
+ if (!issue)
185
+ return check(id, 'skipped', facts.networkSkip ?? 'the issue was not verified');
186
+ const openPRs = issue.linkedPRs
187
+ .filter((pr) => pr.state === 'open')
188
+ // Titles are left out: they are untrusted text and the URL identifies the PR.
189
+ .map((pr) => ({ number: pr.number, url: pr.url, author: pr.author, isOwn: pr.isOwn, linkType: pr.linkType }));
190
+ return check(id, COMPETING_STATUS[issue.verdict], `${issue.verdict}: ${issue.verdictReason}`, {
191
+ issueUrl: issue.url,
192
+ verdict: issue.verdict,
193
+ state: issue.state,
194
+ assignees: issue.assignees,
195
+ openPRs,
196
+ });
197
+ }
198
+ function capSkipReason(facts) {
199
+ if (!facts.issueUrl)
200
+ return 'no issue given (the cap gates a new PR)';
201
+ return skipReason(facts, facts.capError, 'githubUsername is not configured; run setup');
202
+ }
203
+ /** The user's own open-PR cap and `excludeRepos`, as `repo-cap` reports them. Runs only for an issue: it gates a new PR. */
204
+ export function checkRepoCap(facts) {
205
+ const id = 'repo-cap';
206
+ const { cap } = facts;
207
+ if (!cap)
208
+ return check(id, 'skipped', capSkipReason(facts));
209
+ const details = { ...cap };
210
+ if (cap.reason)
211
+ return check(id, 'warn', cap.reason, details);
212
+ const limit = cap.cap > 0 ? `of ${cap.cap} allowed` : '(no cap set)';
213
+ return check(id, 'pass', `${cap.openPRCount} open PR(s) in ${cap.repo} ${limit}`, details);
214
+ }
215
+ function pacingFull(c, what, key) {
216
+ return `${c.count} new ${what} in the last 24 hours, at the cap of ${c.cap} (${key}); the window frees at ${c.freesAt}`;
217
+ }
218
+ /** The caps this PR would go past: the PR cap, and the fork cap when it needs a new fork. */
219
+ function pacingReached(pacing, isForkNeeded) {
220
+ const reached = [];
221
+ if (pacing.prs?.atCap)
222
+ reached.push(pacingFull(pacing.prs, 'PRs', 'maxNewPrsPerDay'));
223
+ if (isForkNeeded && pacing.forks?.atCap)
224
+ reached.push(pacingFull(pacing.forks, 'forks', 'maxNewForksPerDay'));
225
+ return reached;
226
+ }
227
+ function pacingCounts(pacing) {
228
+ const counts = [];
229
+ if (pacing.prs)
230
+ counts.push(`${pacing.prs.count}/${pacing.prs.cap} new PRs`);
231
+ if (pacing.forks)
232
+ counts.push(`${pacing.forks.count}/${pacing.forks.cap} new forks`);
233
+ return `${counts.join(', ')} in the last 24 hours`;
234
+ }
235
+ /** Why the pacing check has nothing to judge, or null when it does. */
236
+ function pacingSkip(facts) {
237
+ const id = 'pacing';
238
+ if (!facts.pacing)
239
+ return check(id, 'pass', 'no pacing cap set');
240
+ if (!facts.issueUrl)
241
+ return check(id, 'skipped', 'no issue given (the pacing caps gate a new PR)');
242
+ const owner = facts.repo?.split('/', 1)[0];
243
+ if (owner && facts.login && isOwnRepo(owner, facts.login)) {
244
+ return check(id, 'pass', 'PRs to your own repos do not count against the pacing caps');
245
+ }
246
+ return null;
247
+ }
248
+ /**
249
+ * The optional pacing caps (#1911). Runs only for an issue, like `repo-cap`:
250
+ * it gates a new PR, never a push to an existing one. The fork cap applies
251
+ * when the PR needs a new fork: no remote of the user's and no push access.
252
+ * A `fail` here defers the PR: the branch stays local and nothing is lost.
253
+ */
254
+ export function checkPacing(facts) {
255
+ const skip = pacingSkip(facts);
256
+ if (skip || !facts.pacing)
257
+ return skip ?? check('pacing', 'pass', 'no pacing cap set');
258
+ const { pacing } = facts;
259
+ const isForkNeeded = facts.pushRemote === null && facts.github?.canPush !== true;
260
+ const details = { ...pacing, needsFork: isForkNeeded };
261
+ const reached = pacingReached(pacing, isForkNeeded);
262
+ if (reached.length > 0) {
263
+ return check('pacing', 'fail', `deferred: ${reached.join('; ')}. Keep the branch and open the PR after that`, details);
264
+ }
265
+ return check('pacing', 'pass', pacingCounts(pacing), details);
266
+ }
267
+ /** Each rule the policy states that this PR has not met, as the action that meets it. */
268
+ function policyAsks(facts, policy, repo) {
269
+ const isFirst = facts.isFirstContribution;
270
+ const login = facts.login?.toLowerCase();
271
+ const isAssigned = (facts.issue?.assignees ?? []).some((a) => a.toLowerCase() === login);
272
+ const rules = [
273
+ ...disclosureAsk(facts, policy, repo),
274
+ [
275
+ isFirst && policy.aiPolicy === 'unknown',
276
+ `${repo}'s AI policy is unknown and this is your first PR there: read its CONTRIBUTING and README, then record it with policy set --repo ${repo} --ai-policy <value>`,
277
+ ],
278
+ [
279
+ !isAssigned && policy.prGate === 'claim-first',
280
+ `${repo} wants the issue claimed first: comment on it and get assigned before opening the PR`,
281
+ ],
282
+ ...maintainerLabelAsk(facts, policy, repo),
283
+ [isFirst && policy.cla === 'required', `${repo} requires a signed CLA: sign it when the CLA bot asks on the PR`],
284
+ [policy.prGate === 'collaborators-only' && facts.github?.canPush !== true, collaboratorsAsk(facts, policy, repo)],
285
+ ...maxOpenAsk(facts, policy, repo),
286
+ ];
287
+ return rules.filter(([applies]) => applies).map(([, ask]) => ask);
288
+ }
289
+ /** Text compared case-insensitively with whitespace collapsed, as {@link quote} stores the recorded line. */
290
+ function normalized(text) {
291
+ return text.replaceAll(/\s+/g, ' ').trim().toLowerCase();
292
+ }
293
+ /** HTML comments (a closed one, or an unclosed one to the end) and unchecked task-list lines: template text, not a statement. */
294
+ const HTML_COMMENT = /<!--[\s\S]*?(?:-->|$)/g;
295
+ // A list item (bullet or number), also inside a blockquote, whose box is not ticked.
296
+ const UNCHECKED_TASK = /^[\s>]*(?:[-*+]|\d{1,9}[.)])\s+\[ \]/;
297
+ const WORD_CHAR = /[\p{L}\p{N}_]/u;
298
+ /** `wanted` occurs in `text` with no letter or digit right before it, nor right after unless `isOpenEnded`. */
299
+ function hasWholeMatch(text, wanted, isOpenEnded) {
300
+ for (let at = text.indexOf(wanted); at !== -1; at = text.indexOf(wanted, at + 1)) {
301
+ const before = text[at - 1] ?? ' ';
302
+ const after = text[at + wanted.length] ?? ' ';
303
+ if (!WORD_CHAR.test(before) && (isOpenEnded || !WORD_CHAR.test(after)))
304
+ return true;
305
+ }
306
+ return false;
307
+ }
308
+ /**
309
+ * The body states the recorded line: outside HTML comments and unchecked
310
+ * boxes (a PR template keeps both), on word boundaries. A line {@link quote}
311
+ * cut short is matched up to the cut.
312
+ */
313
+ function hasDisclosure(body, line) {
314
+ const isCut = line.endsWith('…');
315
+ const wanted = normalized(isCut ? line.slice(0, -1) : line);
316
+ if (wanted === '')
317
+ return false;
318
+ const lines = body.replaceAll(HTML_COMMENT, ' ').split('\n');
319
+ const stated = normalized(lines.filter((l) => !UNCHECKED_TASK.test(l)).join('\n'));
320
+ return hasWholeMatch(stated, wanted, isCut);
321
+ }
322
+ /**
323
+ * The disclosure a `disclosure-required` repo asks for (#2040). Met when the
324
+ * staged body (`--body-file`) contains the line the user recorded. With no
325
+ * recorded line there is nothing to match: the agent writes one from the rule
326
+ * quoted in `details.sources`, and recording it lets the next run check it.
327
+ */
328
+ function disclosureAsk(facts, policy, repo) {
329
+ if (policy.aiPolicy !== 'disclosure-required')
330
+ return [];
331
+ const required = `${repo} requires an AI-use disclosure`;
332
+ const line = policy.disclosureText;
333
+ if (line === undefined) {
334
+ const record = `policy set --repo ${repo} --ai-policy disclosure-required --disclosure-text <line>`;
335
+ return [
336
+ [
337
+ true,
338
+ `${required}: write one in the PR body that meets the rule quoted in details.sources, then record the line with ${record} so preflight can check the body for it`,
339
+ ],
340
+ ];
341
+ }
342
+ if (facts.prBody === null) {
343
+ return [[true, `${required}: add the line in details.disclosureText to the PR body and pass it with --body-file`]];
344
+ }
345
+ return [
346
+ [
347
+ !hasDisclosure(facts.prBody, line),
348
+ `${required}: the PR body does not contain the line in details.disclosureText`,
349
+ ],
350
+ ];
351
+ }
352
+ /** Lowercase words only, so `status: accepted`, `status/accepted` and `Status-Accepted` compare equal. */
353
+ function words(text) {
354
+ return ` ${text
355
+ .toLowerCase()
356
+ .replaceAll(/[^\p{L}\p{N}]+/gu, ' ')
357
+ .trim()} `;
358
+ }
359
+ /**
360
+ * Labels that look like acceptance, that say it is not one yet, and that close
361
+ * the question. Tested against {@link words}: lowercase words between spaces.
362
+ * They only shape the warn text; they never decide the verdict.
363
+ */
364
+ const LOOKS_ACCEPTED = / (?:accepted|approved|ready|triaged|confirmed|help ?wanted|good first issue) /;
365
+ const NOT_YET = / (?:not|no|needs?|awaiting|pending|waiting|un\w+) /;
366
+ const REJECTED = / (?:wont ?fix|won t fix|invalid|duplicate|not planned|rejected|declined|stale) /;
367
+ function isSameLabel(a, b) {
368
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
369
+ }
370
+ /** A hint for the warn: a label that looks like acceptance. Never changes the verdict. */
371
+ function lookalikeHint(labels) {
372
+ const lookalike = labels.find((label) => LOOKS_ACCEPTED.test(words(label)) && !NOT_YET.test(words(label)));
373
+ return lookalike ? ` (label ${JSON.stringify(quote(lookalike))} looks like acceptance)` : '';
374
+ }
375
+ /** Why the label gate is not met, or null when it is. */
376
+ function labelProblem(labels, policy, repo) {
377
+ const gate = policy.reviewedByUser ? policy.gateLabel : undefined;
378
+ if (gate === undefined) {
379
+ // An unreviewed record needs --ai-policy too: policy set refuses to approve the AI reading by accident.
380
+ const aiFlag = policy.reviewedByUser ? '' : ' --ai-policy <value>';
381
+ const record = `policy set --repo ${repo}${aiFlag} --gate-label "<name>"`;
382
+ return `no gate label is recorded: check the issue's labels (details.issueLabels) against the rule in details.sources, then record the label once with ${record}${lookalikeHint(labels)}`;
383
+ }
384
+ if (labels.length === 0)
385
+ return 'the issue has no labels';
386
+ const hasGate = labels.some((label) => isSameLabel(label, gate));
387
+ if (!hasGate) {
388
+ return `the issue does not carry the recorded gate label (details.gateLabel)${lookalikeHint(labels)}`;
389
+ }
390
+ const closing = labels.find((label) => REJECTED.test(words(label)));
391
+ return closing ? `the issue also carries ${JSON.stringify(quote(closing))}` : null;
392
+ }
393
+ /**
394
+ * The `maintainer-label` gate (#2040): met only when the issue carries the
395
+ * label the user recorded with `policy set --gate-label`, compared exactly
396
+ * (case-insensitive, trimmed). Which label is the gate is never read from repo
397
+ * text: a false pass skips the question and gets the PR closed, a false warn
398
+ * costs one question.
399
+ */
400
+ function maintainerLabelAsk(facts, policy, repo) {
401
+ if (policy.prGate !== 'maintainer-label')
402
+ return [];
403
+ const wants = `${repo} wants a maintainer to accept the issue first`;
404
+ if (!facts.issueUrl) {
405
+ return [
406
+ [true, `${wants}: pass the issue so preflight can read its labels, or confirm it carries their approval label`],
407
+ ];
408
+ }
409
+ const labels = facts.issueLabels;
410
+ if (labels === null) {
411
+ const why = skipReason(facts, facts.labelsError, 'the labels were not read');
412
+ return [
413
+ [true, `${wants} and the issue's labels could not be read (${why}): confirm it carries their approval label`],
414
+ ];
415
+ }
416
+ const problem = labelProblem(labels, policy, repo);
417
+ return [[problem !== null, `${wants} and ${problem}: confirm a maintainer accepted it before opening the PR`]];
418
+ }
419
+ /** The open AI-PR limit when it cannot fail: the count is unknown, or the limit was read from the docs and not reviewed. */
420
+ function maxOpenAsk(facts, policy, repo) {
421
+ const max = policy.maxOpenAiPRs;
422
+ if (max === undefined)
423
+ return [];
424
+ if (!facts.cap)
425
+ return [[true, `${repo} allows ${max} open AI-assisted PR(s): count yours there before opening another`]];
426
+ const isOver = !policy.reviewedByUser && facts.cap.openPRCount >= max;
427
+ const ask = `${repo}'s docs read as allowing ${max} open AI-assisted PR(s) and you have ${facts.cap.openPRCount}: wait for one to close, or record the limit with policy set --repo ${repo} --ai-policy <value> --max-open-ai-prs <n|0> if the docs were misread`;
428
+ return [[isOver, ask]];
429
+ }
430
+ /** The warn for `collaborators-only` when it cannot fail: push access unknown, or the rule not reviewed. */
431
+ function collaboratorsAsk(facts, policy, repo) {
432
+ if (!facts.github) {
433
+ return `${repo} only takes PRs from collaborators and push access could not be checked: confirm you are one before opening the PR`;
434
+ }
435
+ const record = policy.reviewedByUser ? '' : `, or record it with policy set --repo ${repo} if the docs were misread`;
436
+ return `${repo}'s docs read as collaborators-only and you cannot push there: check the rule${record}`;
437
+ }
438
+ /** What the policy forbids outright; null when nothing does. */
439
+ function policyStop(facts, policy, repo) {
440
+ if (policy.aiPolicy === 'banned') {
441
+ return `${repo} does not accept AI-assisted contributions: do not open this PR${banNote(policy, repo)}`;
442
+ }
443
+ // Only a rule the user confirmed, checked against known push access, stops the PR.
444
+ if (policy.prGate === 'collaborators-only' && policy.reviewedByUser && facts.github?.canPush === false) {
445
+ return `${repo} only takes PRs from collaborators: do not open this PR`;
446
+ }
447
+ // Only a limit the user confirmed stops the PR; one read from the docs warns (policyAsks).
448
+ const max = policy.reviewedByUser ? policy.maxOpenAiPRs : undefined;
449
+ if (max !== undefined && facts.cap && facts.cap.openPRCount >= max) {
450
+ return `${repo} allows ${max} open AI-assisted PR(s) and you have ${facts.cap.openPRCount}: wait for one to close`;
451
+ }
452
+ return null;
453
+ }
454
+ function noPolicyCheck(id, repo, isFirst) {
455
+ if (!isFirst)
456
+ return check(id, 'pass', `no contribution policy recorded for ${repo}`);
457
+ return check(id, 'warn', `no contribution policy recorded for ${repo} and this is your first PR there: vet the issue or read its CONTRIBUTING, then record it with policy set --repo ${repo}`);
458
+ }
459
+ /**
460
+ * The repo's contribution policy (#1953): `banned` fails, a rule the PR has
461
+ * not met warns with the action that meets it. Quoted repo text arrives fenced.
462
+ */
463
+ export function checkRepoPolicy(facts) {
464
+ const id = 'repo-policy';
465
+ const { repo, policy } = facts;
466
+ if (!repo)
467
+ return check(id, 'skipped', 'no upstream repository');
468
+ if (!policy)
469
+ return noPolicyCheck(id, repo, facts.isFirstContribution);
470
+ const labels = facts.issueLabels;
471
+ const details = {
472
+ ...summarizePolicy(policy),
473
+ ...fencePolicyText(repo, policy),
474
+ // Label names are set in someone else's repository: fenced like the quoted lines.
475
+ ...(labels !== null &&
476
+ labels.length > 0 && { issueLabels: wrapUntrustedContent(labels.join('\n'), 'issue-labels') }),
477
+ };
478
+ const stop = policyStop(facts, policy, repo);
479
+ if (stop)
480
+ return check(id, 'fail', stop, details);
481
+ const asks = policyAsks(facts, policy, repo);
482
+ if (asks.length > 0)
483
+ return check(id, 'warn', asks.join('; '), details);
484
+ return check(id, 'pass', `${repo}: AI policy ${policy.aiPolicy}, PR gate ${policy.prGate}`, details);
485
+ }
486
+ const AUTO_SUBJECT = /^(?:Revert "|Reapply "|(?:fixup|squash|amend)! )/;
487
+ /** Per commit rule id: true when a commit message breaks it. An id this release does not know is not checked. */
488
+ const COMMIT_RULE_BROKEN = {
489
+ // Reverts and autosquash commits keep the subject Git wrote.
490
+ 'conventional-commits': (m) => !AUTO_SUBJECT.test(m) && !/^\w+(?:\([^)\n]*\))?!?: \S/.test(m),
491
+ 'dco-signoff': (m) => !/^Signed-off-by: .+ <[^>\n]+>\s*$/im.test(m),
492
+ // Plain text, the way a CI bot reads a commit message: backticks do not hide a keyword.
493
+ 'no-closing-keyword-in-commit': (m) => findClosingRefs(m).length > 0,
494
+ };
495
+ const MAX_LISTED_VIOLATIONS = 10;
496
+ /**
497
+ * The repo's recorded commit rules over this branch's commits (local, no
498
+ * network). A rule the user confirmed fails; one read from the docs and not
499
+ * reviewed only warns. Commit subjects arrive fenced.
500
+ */
501
+ export function checkCommitRules(facts) {
502
+ const id = 'commit-rules';
503
+ const { repo, policy, branchCommits } = facts;
504
+ const rules = (policy?.commitRules ?? []).filter((rule) => Object.hasOwn(COMMIT_RULE_BROKEN, rule));
505
+ if (!repo || !policy || rules.length === 0)
506
+ return check(id, 'skipped', 'no commit rules recorded for this repo');
507
+ if (branchCommits === null) {
508
+ return check(id, 'skipped', 'the branch point is unknown (target branch not fetched); run again with --fetch');
509
+ }
510
+ const broken = branchCommits.flatMap((message) => rules
511
+ .filter((rule) => COMMIT_RULE_BROKEN[rule](message))
512
+ .map((rule) => `${rule}: ${quote(message.split('\n', 1)[0])}`));
513
+ if (broken.length === 0) {
514
+ return check(id, 'pass', `${branchCommits.length} commit(s) follow ${rules.join(', ')}`, { rules });
515
+ }
516
+ const unreviewed = policy.reviewedByUser
517
+ ? ''
518
+ : ` (rules read from the repo docs, not reviewed: record them with policy set --repo ${repo} --ai-policy <value> --commit-rules <ids> if misread)`;
519
+ return check(id, policy.reviewedByUser ? 'fail' : 'warn', `${broken.length} commit rule violation(s): reword those commits${unreviewed}`, {
520
+ rules,
521
+ violations: wrapUntrustedContent(broken.slice(0, MAX_LISTED_VIOLATIONS).join('\n'), 'commit-subjects'),
522
+ });
523
+ }
524
+ /**
525
+ * A title opening with a work-in-progress marker. Only these: a prefix a repo's own template asks for is left
526
+ * alone, and a word that merely starts with "wip" (`wip-tracker:`, `WIP.js`, `Wipeout`) is not one.
527
+ */
528
+ const WIP_MARKERS = [
529
+ /^\u{1F6A7}/u,
530
+ // `[WIP]`, `(WIP)`, `[Draft]`, `(Draft)`.
531
+ /^[[(]\s*(?:wip|draft)\s*[\])]/i,
532
+ /^draft\s*:/i,
533
+ // `WIP:`, `WIP!:`, `WIP - x` (hyphen, en dash or em dash), `wip(scope):`, a lone `WIP`.
534
+ /^wip(?:!?\s*:|\s+[-\u{2013}\u{2014}]\s|\(|\s*$)/iu,
535
+ ];
536
+ /** Bare `WIP` then a word: a marker unless that word makes WIP the subject. A heuristic, kept in this one list. */
537
+ const BARE_WIP = /^wip\s+([a-z]+)/i;
538
+ // Nouns after which "WIP" is the topic (`WIP limit for kanban columns`), not a work-in-progress flag.
539
+ const WIP_SUBJECT_NOUNS = new Set([
540
+ 'limit',
541
+ 'limits',
542
+ 'label',
543
+ 'labels',
544
+ 'indicator',
545
+ 'status',
546
+ 'state',
547
+ 'count',
548
+ 'counter',
549
+ 'badge',
550
+ 'board',
551
+ 'column',
552
+ 'columns',
553
+ 'tracker',
554
+ 'tracking',
555
+ 'policy',
556
+ 'queue',
557
+ ]);
558
+ /** The title opens with a work-in-progress marker (#1910, #2087). */
559
+ export function hasWipMarker(title) {
560
+ const trimmed = title.trim();
561
+ if (WIP_MARKERS.some((marker) => marker.test(trimmed)))
562
+ return true;
563
+ const next = BARE_WIP.exec(trimmed)?.[1].toLowerCase();
564
+ return next !== undefined && !WIP_SUBJECT_NOUNS.has(next);
565
+ }
566
+ /** Lines a PR template brings rather than a description of the change, tested on the trimmed line. */
567
+ const HEADING_LINE = /^#{1,6}(?:\s|$)/;
568
+ const CHECKLIST_LINE = /^>?\s*(?:[-*+]|\d{1,9}[.)])\s+\[[ x]\]/i;
569
+ // A bold pseudo-heading, optionally followed by a parenthetical: `**What kind of change is this?** (pick one)`.
570
+ const BOLD_PSEUDO_HEADING = /^(?:\*\*[^*\n]+\*\*|__[^_\n]+__)(?: ?\([^)\n]*\))?$/;
571
+ /** An empty bullet left from a template. */
572
+ const LONE_BULLET = /^[-*+]$/;
573
+ /** A bold line that ends a sentence with `.` or `!` is a description written in bold, not a prompt. */
574
+ const BOLD_SENTENCE = /[.!](?:\*\*|__)$/;
575
+ /** A short label ending in a colon, bold or not: `Description:`, `**Description**:`, `**Description:**`. */
576
+ const LABEL_LINE = /^(?:\*\*|__)?\p{L}[\p{L}\p{N} '&/-]{0,40}(?:\*\*|__)?:(?:\*\*|__)?$/u;
577
+ // `=` of any length, or two or more `-`: a lone `-` is an empty bullet, not an underline.
578
+ const SETEXT_UNDERLINE = /^(?:=+|-{2,})$/;
579
+ /** A heading text line ends without sentence punctuation; a sentence above `---` is a sentence and a rule. */
580
+ const SENTENCE_END = /[.!?]$/;
581
+ const FENCE_MARKER = /^(?:`{3,}|~{3,})/;
582
+ /** Images, links and HTML tags: their alt text, link text, URLs and attributes are not prose. */
583
+ const IMAGE_OR_LINK = /!?\[[^[\]\n]*\]\([^()\n]*\)/g;
584
+ // A tag starts with a letter right after `<` or `</`, so `a < b and c > d` is prose.
585
+ const HTML_TAG = /<\/?[a-z][\w-]*(?:\s[^<>\n]*)?>/gi;
586
+ function isTemplateLine(line, next, templateLines) {
587
+ if (templateLines.has(line) || SETEXT_UNDERLINE.test(line))
588
+ return true;
589
+ // The text line of a setext heading (`Description` over `---`).
590
+ if (next !== undefined && line !== '' && !SENTENCE_END.test(line) && SETEXT_UNDERLINE.test(next))
591
+ return true;
592
+ if (HEADING_LINE.test(line) || CHECKLIST_LINE.test(line))
593
+ return true;
594
+ // Only the pseudo-heading rule exempts a bold sentence: a bold checklist item or heading is still template.
595
+ return BOLD_PSEUDO_HEADING.test(line) && !BOLD_SENTENCE.test(line);
596
+ }
597
+ /** The fence a line opens or closes, or null. A backtick run with a backtick after it is an inline span, not a fence. */
598
+ function fenceOf(line) {
599
+ const marker = FENCE_MARKER.exec(line)?.[0];
600
+ if (marker === undefined)
601
+ return null;
602
+ const info = line.slice(marker.length);
603
+ if (marker.startsWith('`') && info.includes('`'))
604
+ return null;
605
+ return { marker, isBare: info.trim() === '' };
606
+ }
607
+ /** The open fence after `fence` at `index`; a close marks every line from the opener to here in `fenced`. */
608
+ function advanceFence(open, fence, index, fenced) {
609
+ if (open === undefined)
610
+ return { index, marker: fence.marker };
611
+ const isCloser = fence.isBare && fence.marker[0] === open.marker[0] && fence.marker.length >= open.marker.length;
612
+ if (!isCloser)
613
+ return open;
614
+ for (let at = open.index; at <= index; at++)
615
+ fenced.add(at);
616
+ return undefined;
617
+ }
618
+ /**
619
+ * Indexes of lines inside closed fences, fence lines included. A fence closes
620
+ * on the same character with at least the same length and nothing after it;
621
+ * one that never closes is text, so it cannot hide what follows.
622
+ */
623
+ function fencedLines(lines) {
624
+ const fenced = new Set();
625
+ let open;
626
+ for (const [index, line] of lines.entries()) {
627
+ const fence = fenceOf(line);
628
+ if (fence)
629
+ open = advanceFence(open, fence, index, fenced);
630
+ }
631
+ return fenced;
632
+ }
633
+ /**
634
+ * The body without what a template brings: HTML comments first (a comment's
635
+ * closer may sit on a template line), then fenced code, lines that appear in
636
+ * the repo's template, headings, checklists, bold pseudo-headings and labels
637
+ * over empty sections, then images, links and tags.
638
+ */
639
+ function bodyProse(body, template) {
640
+ const templateLines = new Set((template ?? '').split('\n').map((line) => line.trim()));
641
+ templateLines.delete('');
642
+ const lines = body
643
+ .replaceAll(HTML_COMMENT, ' ')
644
+ .split('\n')
645
+ .map((line) => line.trim());
646
+ const fenced = fencedLines(lines);
647
+ const dropped = lines.map((line, index) => fenced.has(index) || isTemplateLine(line, lines[index + 1], templateLines));
648
+ const emptyLabels = emptyLabelLines(lines, dropped);
649
+ const kept = lines.filter((_, index) => !dropped[index] && !emptyLabels[index]);
650
+ return kept.join('\n').replaceAll(IMAGE_OR_LINK, ' ').replaceAll(HTML_TAG, ' ');
651
+ }
652
+ /**
653
+ * Label lines (`Description:`) with nothing after them up to the next heading
654
+ * but blank lines, dropped lines, empty bullets and other labels: placeholders.
655
+ * A label followed by prose is kept, so its section's letters all count. One
656
+ * pass from the end, so a body of many labels stays linear.
657
+ */
658
+ function emptyLabelLines(lines, dropped) {
659
+ const empty = Array.from({ length: lines.length }, () => false);
660
+ let hasProseAhead = false;
661
+ for (let at = lines.length - 1; at >= 0; at -= 1) {
662
+ const line = lines[at];
663
+ const isLabel = LABEL_LINE.test(line);
664
+ empty[at] = isLabel && !hasProseAhead;
665
+ if (HEADING_LINE.test(line)) {
666
+ hasProseAhead = false;
667
+ }
668
+ else {
669
+ hasProseAhead ||= line !== '' && !dropped[at] && !isLabel && !LONE_BULLET.test(line);
670
+ }
671
+ }
672
+ return empty;
673
+ }
674
+ /**
675
+ * The staged title and body are ready to publish (#1910): the body says
676
+ * something beyond what the PR template brings ({@link bodyProse}), and a
677
+ * PR that is not a draft has no WIP marker in its title. Nothing is filled in.
678
+ */
679
+ export function checkPrDescription(facts) {
680
+ const id = 'pr-description';
681
+ const { prBody, prTitle } = facts;
682
+ if (prBody === null && prTitle === null) {
683
+ return check(id, 'skipped', 'no --title-file or --body-file given, so the description and WIP-title gate did not run; re-run with both before opening the PR');
684
+ }
685
+ const problems = [];
686
+ if (prBody !== null && !hasDescription(bodyProse(prBody, facts.prTemplate))) {
687
+ problems.push('empty description: the body has no prose beyond the template headings, comments and checklist; say what changed and why');
688
+ }
689
+ if (prTitle !== null && !facts.isDraft && hasWipMarker(prTitle)) {
690
+ problems.push('WIP title: the title starts with a work-in-progress marker and the PR is not a draft; drop the marker or open a draft');
691
+ }
692
+ if (problems.length > 0)
693
+ return check(id, 'fail', problems.join('; '));
694
+ return check(id, 'pass', 'the staged title and body are ready to publish');
695
+ }
696
+ /**
697
+ * The staged title and body are in the script the repo writes in (#1909). A
698
+ * script check, not language detection: Latin-script languages are not told
699
+ * apart. Without the repo's docs, English (Latin script) is assumed and said so.
700
+ */
701
+ export function checkPrLanguage(facts) {
702
+ const id = 'pr-language';
703
+ const { prBody, prTitle } = facts;
704
+ if (prBody === null && prTitle === null) {
705
+ return check(id, 'skipped', 'no --title-file or --body-file given, so the language check did not run');
706
+ }
707
+ const repoScripts = facts.repoScripts ?? { scripts: DEFAULT_REPO_SCRIPTS, isDefault: true };
708
+ const repo = facts.repo ?? 'the repo';
709
+ // Scored apart: a short non-Latin title would be outweighed by a long English body.
710
+ const parts = [
711
+ ['title', prTitle],
712
+ ['body', prBody],
713
+ ];
714
+ const problems = parts
715
+ .map(([part, text]) => {
716
+ if (text === null)
717
+ return '';
718
+ const mismatch = part === 'title' ? titleMismatch(text, repoScripts.scripts) : scriptMismatch(text, repoScripts.scripts);
719
+ return mismatch ? `${part}: ${describeMismatch(repo, repoScripts, mismatch)}` : '';
720
+ })
721
+ .filter((problem) => problem !== '');
722
+ if (problems.length > 0) {
723
+ // --allow-script-mismatch, a deliberate terminal choice, turns the refusal into a warning.
724
+ return check(id, facts.allowScriptMismatch ? 'warn' : 'fail', problems.join('; '));
725
+ }
726
+ const scripts = repoScripts.scripts.join(' and ');
727
+ const assumed = repoScripts.isDefault ? ` (assumed: ${repo}'s README and CONTRIBUTING were not read)` : '';
728
+ return check(id, 'pass', `the staged title and body match ${repo}'s ${scripts} script or are Latin${assumed}`);
729
+ }
730
+ /** Every check, in output order. A new check is added here. */
731
+ export const PREFLIGHT_CHECKS = [
732
+ checkDrift,
733
+ checkBaseBranch,
734
+ checkHeadBranch,
735
+ checkWorkingTree,
736
+ checkCompetingWork,
737
+ checkRepoCap,
738
+ checkPacing,
739
+ checkRepoPolicy,
740
+ checkCommitRules,
741
+ checkPrDescription,
742
+ checkPrLanguage,
743
+ ];
744
+ /** `fail` when any check fails, else `warn` when any warns, else `pass`. Skipped checks do not count. */
745
+ export function preflightVerdict(checks) {
746
+ if (checks.some((c) => c.status === 'fail'))
747
+ return 'fail';
748
+ return checks.some((c) => c.status === 'warn') ? 'warn' : 'pass';
749
+ }
750
+ export function runPreflightChecks(facts) {
751
+ const checks = PREFLIGHT_CHECKS.map((run) => run(facts));
752
+ return { verdict: preflightVerdict(checks), checks };
753
+ }