@oss-autopilot/core 3.43.0 → 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 (100) hide show
  1. package/dist/cli-registry.js +160 -6
  2. package/dist/cli.bundle.cjs +207 -180
  3. package/dist/commands/check-integration.js +4 -1
  4. package/dist/commands/cleanup.d.ts +6 -2
  5. package/dist/commands/cleanup.js +72 -7
  6. package/dist/commands/comments.d.ts +8 -1
  7. package/dist/commands/comments.js +11 -3
  8. package/dist/commands/config.d.ts +2 -0
  9. package/dist/commands/config.js +26 -1
  10. package/dist/commands/daily-ledger.d.ts +33 -5
  11. package/dist/commands/daily-ledger.js +36 -13
  12. package/dist/commands/daily-render.d.ts +2 -1
  13. package/dist/commands/daily-render.js +4 -1
  14. package/dist/commands/daily.d.ts +3 -0
  15. package/dist/commands/daily.js +25 -5
  16. package/dist/commands/dashboard-data.js +70 -61
  17. package/dist/commands/dashboard-lifecycle.d.ts +36 -8
  18. package/dist/commands/dashboard-lifecycle.js +131 -38
  19. package/dist/commands/dashboard-process.d.ts +35 -0
  20. package/dist/commands/dashboard-process.js +65 -5
  21. package/dist/commands/dismiss.js +7 -6
  22. package/dist/commands/doctor.js +1 -8
  23. package/dist/commands/fork-prune.d.ts +58 -0
  24. package/dist/commands/fork-prune.js +247 -0
  25. package/dist/commands/guidelines.d.ts +46 -1
  26. package/dist/commands/guidelines.js +111 -12
  27. package/dist/commands/index.d.ts +5 -0
  28. package/dist/commands/index.js +5 -0
  29. package/dist/commands/overnight-push-prep.d.ts +2 -1
  30. package/dist/commands/overnight-push-prep.js +3 -3
  31. package/dist/commands/policy.d.ts +5 -1
  32. package/dist/commands/policy.js +14 -1
  33. package/dist/commands/pr-create.d.ts +48 -0
  34. package/dist/commands/pr-create.js +200 -0
  35. package/dist/commands/pr-preflight.d.ts +28 -2
  36. package/dist/commands/pr-preflight.js +63 -9
  37. package/dist/commands/setup.js +120 -36
  38. package/dist/commands/startup.d.ts +7 -0
  39. package/dist/commands/startup.js +17 -0
  40. package/dist/commands/status.js +5 -0
  41. package/dist/commands/validation.d.ts +5 -0
  42. package/dist/commands/validation.js +5 -0
  43. package/dist/commands/vet-list.js +2 -2
  44. package/dist/commands/vet.d.ts +8 -0
  45. package/dist/commands/vet.js +15 -1
  46. package/dist/commands/work.d.ts +4 -0
  47. package/dist/commands/work.js +34 -11
  48. package/dist/core/commit-date.d.ts +31 -5
  49. package/dist/core/commit-date.js +36 -8
  50. package/dist/core/compliance-score.d.ts +3 -0
  51. package/dist/core/compliance-score.js +13 -9
  52. package/dist/core/config-registry.d.ts +27 -2
  53. package/dist/core/config-registry.js +83 -2
  54. package/dist/core/daily-logic.d.ts +4 -1
  55. package/dist/core/daily-logic.js +13 -2
  56. package/dist/core/fork-prune.d.ts +149 -0
  57. package/dist/core/fork-prune.js +333 -0
  58. package/dist/core/gist-state-store.js +4 -8
  59. package/dist/core/github-stats.d.ts +7 -1
  60. package/dist/core/github-stats.js +15 -15
  61. package/dist/core/index.d.ts +1 -1
  62. package/dist/core/index.js +1 -1
  63. package/dist/core/local-config.js +2 -3
  64. package/dist/core/pacing.d.ts +41 -0
  65. package/dist/core/pacing.js +115 -0
  66. package/dist/core/pr-assembly.d.ts +2 -0
  67. package/dist/core/pr-graphql.d.ts +16 -1
  68. package/dist/core/pr-graphql.js +15 -3
  69. package/dist/core/pr-monitor.d.ts +6 -0
  70. package/dist/core/pr-monitor.js +46 -10
  71. package/dist/core/pr-preflight.d.ts +41 -0
  72. package/dist/core/pr-preflight.js +406 -17
  73. package/dist/core/prose-script.d.ts +72 -0
  74. package/dist/core/prose-script.js +223 -0
  75. package/dist/core/repo-policy.d.ts +8 -2
  76. package/dist/core/repo-policy.js +34 -6
  77. package/dist/core/repo-score-manager.d.ts +18 -0
  78. package/dist/core/repo-score-manager.js +29 -0
  79. package/dist/core/review-analysis.d.ts +15 -2
  80. package/dist/core/review-analysis.js +22 -5
  81. package/dist/core/stale-data.d.ts +44 -7
  82. package/dist/core/stale-data.js +46 -8
  83. package/dist/core/state-persistence.js +2 -4
  84. package/dist/core/state-schema.d.ts +39 -0
  85. package/dist/core/state-schema.js +68 -1
  86. package/dist/core/state.d.ts +21 -0
  87. package/dist/core/state.js +47 -0
  88. package/dist/core/status-determination.js +10 -8
  89. package/dist/core/untrusted-content.d.ts +3 -3
  90. package/dist/core/untrusted-content.js +26 -8
  91. package/dist/core/urls.d.ts +24 -0
  92. package/dist/core/urls.js +76 -0
  93. package/dist/dashboard/assets/chart-panel-B-nLVgzQ.js +3 -0
  94. package/dist/dashboard/assets/index-5IvMGokL.js +55 -0
  95. package/dist/dashboard/index.html +1 -1
  96. package/dist/formatters/json.d.ts +171 -5
  97. package/dist/formatters/json.js +79 -0
  98. package/package.json +6 -6
  99. package/dist/dashboard/assets/chart-panel-C_C1lFTI.js +0 -3
  100. package/dist/dashboard/assets/index-B--H66Jk.js +0 -55
@@ -7,9 +7,11 @@
7
7
  * A new check is one more function in `PREFLIGHT_CHECKS` (plus the facts it
8
8
  * needs); the verdict and the output shape do not change.
9
9
  */
10
+ import { hasDescription } from './compliance-score.js';
11
+ import { DEFAULT_REPO_SCRIPTS, describeMismatch, scriptMismatch, titleMismatch, } from './prose-script.js';
10
12
  import { banNote, fencePolicyText, quote, summarizePolicy } from './repo-policy.js';
11
13
  import { wrapUntrustedContent } from './untrusted-content.js';
12
- import { isOwnRepo, splitRepo } from './urls.js';
14
+ import { findClosingRefs, isOwnRepo, splitRepo } from './urls.js';
13
15
  /** Past this many commits behind, the drift check warns even when no upstream commit touches the branch's files. */
14
16
  export const BEHIND_WARN_THRESHOLD = 20;
15
17
  function check(id, status, summary, details) {
@@ -210,16 +212,65 @@ export function checkRepoCap(facts) {
210
212
  const limit = cap.cap > 0 ? `of ${cap.cap} allowed` : '(no cap set)';
211
213
  return check(id, 'pass', `${cap.openPRCount} open PR(s) in ${cap.repo} ${limit}`, details);
212
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
+ }
213
267
  /** Each rule the policy states that this PR has not met, as the action that meets it. */
214
268
  function policyAsks(facts, policy, repo) {
215
269
  const isFirst = facts.isFirstContribution;
216
270
  const login = facts.login?.toLowerCase();
217
271
  const isAssigned = (facts.issue?.assignees ?? []).some((a) => a.toLowerCase() === login);
218
272
  const rules = [
219
- [
220
- policy.aiPolicy === 'disclosure-required',
221
- `${repo} requires an AI-use disclosure: add the line in details.disclosureText to the PR body`,
222
- ],
273
+ ...disclosureAsk(facts, policy, repo),
223
274
  [
224
275
  isFirst && policy.aiPolicy === 'unknown',
225
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>`,
@@ -228,16 +279,143 @@ function policyAsks(facts, policy, repo) {
228
279
  !isAssigned && policy.prGate === 'claim-first',
229
280
  `${repo} wants the issue claimed first: comment on it and get assigned before opening the PR`,
230
281
  ],
231
- [
232
- policy.prGate === 'maintainer-label',
233
- `${repo} wants a maintainer to accept the issue first: confirm it carries their approval label`,
234
- ],
282
+ ...maintainerLabelAsk(facts, policy, repo),
235
283
  [isFirst && policy.cla === 'required', `${repo} requires a signed CLA: sign it when the CLA bot asks on the PR`],
236
284
  [policy.prGate === 'collaborators-only' && facts.github?.canPush !== true, collaboratorsAsk(facts, policy, repo)],
237
285
  ...maxOpenAsk(facts, policy, repo),
238
286
  ];
239
287
  return rules.filter(([applies]) => applies).map(([, ask]) => ask);
240
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
+ }
241
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. */
242
420
  function maxOpenAsk(facts, policy, repo) {
243
421
  const max = policy.maxOpenAiPRs;
@@ -289,7 +467,14 @@ export function checkRepoPolicy(facts) {
289
467
  return check(id, 'skipped', 'no upstream repository');
290
468
  if (!policy)
291
469
  return noPolicyCheck(id, repo, facts.isFirstContribution);
292
- const details = { ...summarizePolicy(policy), ...fencePolicyText(repo, policy) };
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
+ };
293
478
  const stop = policyStop(facts, policy, repo);
294
479
  if (stop)
295
480
  return check(id, 'fail', stop, details);
@@ -299,18 +484,13 @@ export function checkRepoPolicy(facts) {
299
484
  return check(id, 'pass', `${repo}: AI policy ${policy.aiPolicy}, PR gate ${policy.prGate}`, details);
300
485
  }
301
486
  const AUTO_SUBJECT = /^(?:Revert "|Reapply "|(?:fixup|squash|amend)! )/;
302
- /** A GitHub closing keyword, on the same line as `#12`, `owner/repo#12` or an issue URL. */
303
- const CLOSING_KEYWORD = String.raw `\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?[ \t]+`;
304
- const CLOSING_REFS = [
305
- new RegExp(String.raw `${CLOSING_KEYWORD}\S*#\d+`, 'i'),
306
- new RegExp(String.raw `${CLOSING_KEYWORD}https?://github\.com/[^/\s]+/[^/\s]+/issues/\d+`, 'i'),
307
- ];
308
487
  /** Per commit rule id: true when a commit message breaks it. An id this release does not know is not checked. */
309
488
  const COMMIT_RULE_BROKEN = {
310
489
  // Reverts and autosquash commits keep the subject Git wrote.
311
490
  'conventional-commits': (m) => !AUTO_SUBJECT.test(m) && !/^\w+(?:\([^)\n]*\))?!?: \S/.test(m),
312
491
  'dco-signoff': (m) => !/^Signed-off-by: .+ <[^>\n]+>\s*$/im.test(m),
313
- 'no-closing-keyword-in-commit': (m) => CLOSING_REFS.some((re) => re.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,
314
494
  };
315
495
  const MAX_LISTED_VIOLATIONS = 10;
316
496
  /**
@@ -341,6 +521,212 @@ export function checkCommitRules(facts) {
341
521
  violations: wrapUntrustedContent(broken.slice(0, MAX_LISTED_VIOLATIONS).join('\n'), 'commit-subjects'),
342
522
  });
343
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
+ }
344
730
  /** Every check, in output order. A new check is added here. */
345
731
  export const PREFLIGHT_CHECKS = [
346
732
  checkDrift,
@@ -349,8 +735,11 @@ export const PREFLIGHT_CHECKS = [
349
735
  checkWorkingTree,
350
736
  checkCompetingWork,
351
737
  checkRepoCap,
738
+ checkPacing,
352
739
  checkRepoPolicy,
353
740
  checkCommitRules,
741
+ checkPrDescription,
742
+ checkPrLanguage,
354
743
  ];
355
744
  /** `fail` when any check fails, else `warn` when any warns, else `pass`. Skipped checks do not count. */
356
745
  export function preflightVerdict(checks) {
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The writing system of outgoing prose against the one a repo uses (#1909).
3
+ *
4
+ * A cheap script check, not language detection: it counts letters per
5
+ * Unicode script outside code, quoted text, URLs and identifiers. English and
6
+ * Spanish are both Latin script and look the same here; Chinese text sent to
7
+ * an English-language repo, the failure this guards against, does not.
8
+ * Latin-script text is never refused: English is welcome in any repo, and a
9
+ * non-Latin README that names English products would otherwise block it.
10
+ */
11
+ import type { Octokit } from '@octokit/rest';
12
+ export type ProseScript = 'Latin' | 'Han/Kana' | 'Hangul' | 'Cyrillic' | 'Arabic' | 'Hebrew' | 'Thai' | 'Devanagari' | 'Greek';
13
+ /** The script assumed when the repo's README and CONTRIBUTING cannot be read: English, per #1909. */
14
+ export declare const DEFAULT_REPO_SCRIPTS: readonly ProseScript[];
15
+ /** A script with at least this share of a repo's doc prose is one the repo writes in; two can pass (bilingual docs). */
16
+ export declare const REPO_SCRIPT_MIN_SHARE = 0.2;
17
+ /** Below this much weighted prose the docs say nothing reliable about the repo's language. */
18
+ export declare const MIN_REPO_PROSE_WEIGHT = 40;
19
+ /** Text is refused only when foreign-script prose is the majority: names and quoted errors in another script pass. */
20
+ export declare const MISMATCH_SHARE = 0.5;
21
+ /** Less foreign-script prose than this never blocks, so a short reply with one foreign word passes. */
22
+ export declare const MIN_FOREIGN_WEIGHT = 12;
23
+ /** Titles count every letter as 1: a short English title naming a CJK product (`Add 微信支付 support`) stays English. */
24
+ export declare const MIN_TITLE_FOREIGN_LETTERS = 4;
25
+ /** A title is refused only when more than two thirds of its letters are foreign, so a name beside two English words passes. */
26
+ export declare const TITLE_MISMATCH_SHARE: number;
27
+ /**
28
+ * The prose lines of `text`: no code, blockquotes, comments, URLs, tags or
29
+ * identifiers. A fence that never closes is text, so it cannot hide what follows.
30
+ */
31
+ export declare function proseLines(text: string): string[];
32
+ /** The scripts a repo's docs are written in; null when they hold too little prose to tell. */
33
+ export declare function docScripts(docs: string): ProseScript[] | null;
34
+ export interface ScriptMismatch {
35
+ /** Scripts in the text the repo does not write in (never Latin). */
36
+ foreign: ProseScript[];
37
+ /** Weighted share of the text's prose in those scripts, 0 to 1. */
38
+ share: number;
39
+ /** The first prose lines with a foreign-script letter, cut short. */
40
+ excerpt: string;
41
+ }
42
+ /**
43
+ * Null when `text` is written in the `accepted` scripts, in Latin script, or
44
+ * is too short to tell; else what does not match.
45
+ */
46
+ export declare function scriptMismatch(text: string, accepted: readonly ProseScript[]): ScriptMismatch | null;
47
+ /** {@link scriptMismatch} for a PR title: prefix dropped, every letter weighs 1, a stricter share. */
48
+ export declare function titleMismatch(title: string, accepted: readonly ProseScript[]): ScriptMismatch | null;
49
+ export interface RepoScripts {
50
+ scripts: readonly ProseScript[];
51
+ /** True when the docs could not be read or said too little, so {@link DEFAULT_REPO_SCRIPTS} was used. */
52
+ isDefault: boolean;
53
+ }
54
+ /** The denial text: which repo, which scripts, how much, and the offending lines. */
55
+ export declare function describeMismatch(repo: string, repoScripts: RepoScripts, mismatch: ScriptMismatch): string;
56
+ /**
57
+ * The scripts `owner/repo` writes in, read from its README and CONTRIBUTING
58
+ * through the shared ETag cache. Never throws: an unreadable repo gets the
59
+ * English default, marked `isDefault`.
60
+ */
61
+ export declare function readRepoScripts(octokit: Octokit, owner: string, repo: string): Promise<RepoScripts>;
62
+ /**
63
+ * Check `text` against the script `owner/repo` writes in (#1909). Every
64
+ * comment `post` and `claim` send, from the CLI or MCP, crosses this before
65
+ * GitHub is written to. A mismatch is refused; with `isMismatchAllowed` (a CLI
66
+ * flag only, never an MCP argument) it comes back as a warning instead. No
67
+ * rewrite, no translation.
68
+ */
69
+ export declare function checkRepoScript(octokit: Octokit, target: {
70
+ owner: string;
71
+ repo: string;
72
+ }, text: string, isMismatchAllowed: boolean): Promise<string | undefined>;