@rmartz/pr-policy 1.0.0 → 1.2.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.
package/README.md CHANGED
@@ -18,7 +18,7 @@ new required-status name.
18
18
  | **CI-change classification** ([docs](docs/checks/ci-change.md)) | A `.github/workflows/**` change loosens CI (a removed job, `continue-on-error`, a narrowed trigger, …) and no human has applied `CI change approved` (shows as pending). Owns `CI approval needed`. |
19
19
  | **Base branch** ([docs](docs/checks/base-branch.md)) | The PR targets a branch other than the default and it isn't a non-epic PR on an open epic's branch. A stacked PR waits for its base PR (shows as pending); a base no open PR heads blocks. |
20
20
  | **Title-type rules** ([docs](docs/checks/title.md)) | The squash title isn't a valid Conventional Commit, puts `!` on a non-functional type, disagrees with the `breaking change` label, or types a linter/formatter bump as a non-release, non-`ci` type. |
21
- | **UAT sign-off** ([docs](docs/checks/uat.md)) | The PR isn't docs, tests, CI, dependency-only, or repo metadata, and no trusted user has applied `UAT passed` (or `tested`) or `no UAT needed` (shows as pending). |
21
+ | **UAT sign-off** ([docs](docs/checks/uat.md)) | The PR isn't docs, tests, CI, dependency-only, or repo metadata, and no trusted user has applied `no UAT needed`, or `UAT passed` (or `tested`) since the last push (shows as pending). |
22
22
  | **Dependabot claim verification** ([docs](docs/checks/dependabot.md)) | A Dependabot PR touches a non-dependency path, changes a dependency its description doesn't claim, pins a version other than the claimed one, or edits anything Dependabot never edits (a `package.json` script, a workflow step). |
23
23
  | Domain labels (backlog) | Never blocks. Additive path-glob → domain-label map. |
24
24
  | Milestone inheritance (backlog) | Never blocks. Issue → PR milestone. |
@@ -7,7 +7,7 @@ import {
7
7
  postVerdict,
8
8
  resolveRepoTarget,
9
9
  selectChecks
10
- } from "../chunk-USVRZJHF.js";
10
+ } from "../chunk-XIDP7SRE.js";
11
11
 
12
12
  // src/bin/pr-policy.ts
13
13
  import { readFile } from "fs/promises";
@@ -1215,6 +1215,19 @@ function typePathViolation(type, changedFiles) {
1215
1215
  return void 0;
1216
1216
  }
1217
1217
 
1218
+ // src/checks/title/wip.ts
1219
+ var WIP_MARKERS = [/^\[wip\]\s*/i, /^WIP(?::|\s|$)\s*/, /\s*\[wip\]$/i, /(?:^|\s)WIP$/];
1220
+ function stripWipMarker(title) {
1221
+ let text = title.trim();
1222
+ let marked = false;
1223
+ for (; ; ) {
1224
+ const next = WIP_MARKERS.reduce((current, marker) => current.replace(marker, "").trim(), text);
1225
+ if (next === text) return { title: text, marked };
1226
+ marked = true;
1227
+ text = next;
1228
+ }
1229
+ }
1230
+
1218
1231
  // src/checks/title/index.ts
1219
1232
  var TITLE_CHECK = "title";
1220
1233
  var FUNCTIONAL = FUNCTIONAL_TYPES.map((type) => `\`${type}\``).join("/");
@@ -1222,16 +1235,25 @@ function block2(message) {
1222
1235
  return { check: TITLE_CHECK, message, effect: "block" };
1223
1236
  }
1224
1237
  function decideTitle(pr) {
1238
+ const { title, marked } = stripWipMarker(pr.title);
1239
+ const { findings } = titleRules(pr, title);
1240
+ if (!marked || pr.draft === true) return { findings };
1241
+ const wip = block2(
1242
+ `The title carries a WIP marker, but the PR isn't a draft, so it could merge unfinished. Convert the PR to a draft while the work is in progress, or remove the marker from the title when it's done.`
1243
+ );
1244
+ return { findings: [wip, ...findings] };
1245
+ }
1246
+ function titleRules(pr, text) {
1225
1247
  const labels = new Set(pr.labels.map((label) => label.toLowerCase()));
1226
- if (labels.has(RELEASE_PLEASE_PENDING_LABEL) || isReleasePleaseTitle(pr.title)) {
1248
+ if (labels.has(RELEASE_PLEASE_PENDING_LABEL) || isReleasePleaseTitle(text)) {
1227
1249
  return { findings: [] };
1228
1250
  }
1229
- const title = parseTitle(pr.title);
1251
+ const title = parseTitle(text);
1230
1252
  if (title === null) {
1231
1253
  return {
1232
1254
  findings: [
1233
1255
  block2(
1234
- `\`${pr.title}\` is not a Conventional Commit. Expected \`<type>[(<scope>)][!]: <subject>\` with a type of ${COMMIT_TYPES.join(", ")}. Edit the title; it becomes the squash commit on \`main\`.`
1256
+ `\`${text}\` is not a Conventional Commit. Expected \`<type>[(<scope>)][!]: <subject>\` with a type of ${COMMIT_TYPES.join(", ")}. Edit the title; it becomes the squash commit on \`main\`.`
1235
1257
  )
1236
1258
  ]
1237
1259
  };
@@ -1364,9 +1386,20 @@ var baseBranchCheck = {
1364
1386
  // src/checks/uat/index.ts
1365
1387
  var UAT_CHECK = "uat";
1366
1388
  var PASSING_LABELS = [UAT_PASSED_LABEL, LEGACY_UAT_PASSED_LABEL, NO_UAT_NEEDED_LABEL];
1389
+ var HEAD_BOUND_SIGN_OFFS = [UAT_PASSED_LABEL, LEGACY_UAT_PASSED_LABEL];
1367
1390
  function info2(message) {
1368
1391
  return { check: UAT_CHECK, message, effect: "info" };
1369
1392
  }
1393
+ function staleReason(pr, label) {
1394
+ if (!HEAD_BOUND_SIGN_OFFS.includes(label)) return void 0;
1395
+ if (pr.headPushedAt === void 0) {
1396
+ return "the time the current head was pushed is unknown, so it may predate the head";
1397
+ }
1398
+ const appliedAt = pr.signOffs.find((signOff) => signOff.label === label)?.appliedAt;
1399
+ if (appliedAt === void 0) return "the time it was applied is unknown";
1400
+ if (Date.parse(appliedAt) > Date.parse(pr.headPushedAt)) return void 0;
1401
+ return "it was applied before the current head was pushed, and a new head needs a person to test it again";
1402
+ }
1370
1403
  function decideUat(pr) {
1371
1404
  const categories = trivialCategories(pr);
1372
1405
  if (categories !== void 0) {
@@ -1376,7 +1409,12 @@ function decideUat(pr) {
1376
1409
  if (parseTitle(pr.title)?.type === "refactor") {
1377
1410
  return { findings: [info2("No UAT needed: a refactor changes no behaviour.")] };
1378
1411
  }
1379
- const state = signOffState(pr, PASSING_LABELS);
1412
+ const stale = PASSING_LABELS.flatMap((label) => {
1413
+ const reason = pr.labels.includes(label) ? staleReason(pr, label) : void 0;
1414
+ return reason === void 0 ? [] : [{ label, reason }];
1415
+ });
1416
+ const current = PASSING_LABELS.filter((label) => !stale.some((entry) => entry.label === label));
1417
+ const state = signOffState(pr, current);
1380
1418
  if (state.status === "trusted") {
1381
1419
  return {
1382
1420
  findings: [
@@ -1392,7 +1430,10 @@ function decideUat(pr) {
1392
1430
  message: `Waiting for UAT. A person applies \`${UAT_PASSED_LABEL}\` after testing, or the review agent or a person applies \`${NO_UAT_NEEDED_LABEL}\`.`,
1393
1431
  effect: "hold"
1394
1432
  };
1395
- const why = state.status === "untrusted" ? [info2(`\`${state.label}\` doesn't count: ${state.reason}.`)] : [];
1433
+ const why = stale.map(({ label, reason }) => info2(`\`${label}\` doesn't count: ${reason}.`));
1434
+ if (state.status === "untrusted") {
1435
+ why.push(info2(`\`${state.label}\` doesn't count: ${state.reason}.`));
1436
+ }
1396
1437
  return { findings: [hold, ...why] };
1397
1438
  }
1398
1439
  var uatCheck = {
@@ -1432,10 +1473,10 @@ function buildReport(findings) {
1432
1473
  outcome = "pending";
1433
1474
  title = `Waiting on ${plural(holds.length, "human sign-off")}`;
1434
1475
  }
1435
- const lines = findings.map(
1476
+ const lines2 = findings.map(
1436
1477
  (finding) => `- ${ICONS[finding.effect]} **${finding.check}**: ${finding.message}`
1437
1478
  );
1438
- const summary = lines.length > 0 ? lines.join("\n") : "No policy findings.";
1479
+ const summary = lines2.length > 0 ? lines2.join("\n") : "No policy findings.";
1439
1480
  return { outcome, title, summary, findings };
1440
1481
  }
1441
1482
 
@@ -1489,10 +1530,14 @@ function parseSignOffs(value) {
1489
1530
  return value.map((item, index) => {
1490
1531
  const where = `facts.signOffs[${index}]`;
1491
1532
  if (typeof item !== "object" || item === null) throw new Error(`${where} must be an object`);
1492
- const { label, appliedBy } = item;
1533
+ const { label, appliedBy, appliedAt } = item;
1493
1534
  if (typeof label !== "string") throw new Error(`${where}.label must be a string`);
1535
+ if (!isOptionalString(appliedAt)) throw new Error(`${where}.appliedAt must be a string`);
1536
+ const signOff = { label };
1494
1537
  const actor = parseActor(`${where}.appliedBy`, appliedBy);
1495
- return actor === void 0 ? { label } : { label, appliedBy: actor };
1538
+ if (actor !== void 0) signOff.appliedBy = actor;
1539
+ if (appliedAt !== void 0) signOff.appliedAt = appliedAt;
1540
+ return signOff;
1496
1541
  });
1497
1542
  }
1498
1543
  function parseAuthor(value) {
@@ -1535,14 +1580,20 @@ function parseFacts(raw) {
1535
1580
  body,
1536
1581
  author,
1537
1582
  base,
1583
+ draft,
1538
1584
  labels,
1539
1585
  changedFiles,
1540
1586
  workflowChanges,
1541
1587
  manifestChanges,
1542
- signOffs
1588
+ signOffs,
1589
+ headPushedAt
1543
1590
  } = parsed;
1544
1591
  if (typeof title !== "string") throw new Error("facts.title must be a string");
1545
1592
  if (!isOptionalString(body)) throw new Error("facts.body must be a string");
1593
+ if (!isOptionalString(headPushedAt)) throw new Error("facts.headPushedAt must be a string");
1594
+ if (draft !== void 0 && typeof draft !== "boolean") {
1595
+ throw new Error("facts.draft must be a boolean");
1596
+ }
1546
1597
  if (!isStringArray(labels)) throw new Error("facts.labels must be a string array");
1547
1598
  if (!isStringArray(changedFiles)) throw new Error("facts.changedFiles must be a string array");
1548
1599
  const pr = {
@@ -1558,6 +1609,8 @@ function parseFacts(raw) {
1558
1609
  if (body !== void 0) pr.body = body;
1559
1610
  if (parsedAuthor !== void 0) pr.author = parsedAuthor;
1560
1611
  if (parsedBase !== void 0) pr.base = parsedBase;
1612
+ if (draft !== void 0) pr.draft = draft;
1613
+ if (headPushedAt !== void 0) pr.headPushedAt = headPushedAt;
1561
1614
  return pr;
1562
1615
  }
1563
1616
 
@@ -1769,6 +1822,38 @@ async function postVerdict(target, headSha, evaluation) {
1769
1822
  await postCommitStatus(target, headSha, evaluation);
1770
1823
  }
1771
1824
 
1825
+ // src/github/head-push.ts
1826
+ async function lines(target, endpoint, jq) {
1827
+ const out = await ghCall({ argv: ["gh", "api", "--paginate", endpoint, "--jq", jq] }, null, {
1828
+ cwd: target.cwd
1829
+ });
1830
+ if (out === null) throw new Error(`could not read ${endpoint}`);
1831
+ return out.split("\n").filter((line) => line.trim() !== "");
1832
+ }
1833
+ function times(stamps) {
1834
+ return stamps.map((stamp) => Date.parse(stamp)).filter((ms) => !Number.isNaN(ms));
1835
+ }
1836
+ async function gatherHeadPushedAt(target, headSha) {
1837
+ const forcePushes = times(
1838
+ await lines(
1839
+ target,
1840
+ `repos/${target.repo}/issues/${target.pr}/events`,
1841
+ '.[] | select(.event == "head_ref_force_pushed") | .created_at'
1842
+ )
1843
+ );
1844
+ const suites = times(
1845
+ await lines(
1846
+ target,
1847
+ `repos/${target.repo}/commits/${headSha}/check-suites`,
1848
+ ".check_suites[].created_at"
1849
+ )
1850
+ );
1851
+ const candidates = [...forcePushes];
1852
+ if (suites.length > 0) candidates.push(Math.min(...suites));
1853
+ if (candidates.length === 0) return void 0;
1854
+ return new Date(Math.max(...candidates)).toISOString();
1855
+ }
1856
+
1772
1857
  // src/github/sign-offs.ts
1773
1858
  async function listLabelEvents(target) {
1774
1859
  const out = await ghCall(
@@ -1779,7 +1864,7 @@ async function listLabelEvents(target) {
1779
1864
  "--paginate",
1780
1865
  `repos/${target.repo}/issues/${target.pr}/events`,
1781
1866
  "--jq",
1782
- '.[] | select(.event == "labeled") | {label: .label.name, login: .actor.login, type: .actor.type}'
1867
+ '.[] | select(.event == "labeled") | {label: .label.name, login: .actor.login, type: .actor.type, at: .created_at}'
1783
1868
  ]
1784
1869
  },
1785
1870
  null,
@@ -1815,10 +1900,11 @@ async function gatherSignOffs(target, labels) {
1815
1900
  return Promise.all(
1816
1901
  present.map(async (label) => {
1817
1902
  const event = latest.get(label);
1818
- if (event === void 0 || event.login === null) return { label };
1903
+ if (event === void 0) return { label };
1904
+ if (event.login === null) return { label, appliedAt: event.at };
1819
1905
  const type = event.type ?? "unknown actor";
1820
1906
  const permission = type === "User" ? await lookupPermission(target, event.login) : "none";
1821
- return { label, appliedBy: { login: event.login, type, permission } };
1907
+ return { label, appliedBy: { login: event.login, type, permission }, appliedAt: event.at };
1822
1908
  })
1823
1909
  );
1824
1910
  }
@@ -1921,6 +2007,7 @@ async function gatherFacts(target) {
1921
2007
  body: view.body ?? "",
1922
2008
  author: { login: view.user.login, type: view.user.type },
1923
2009
  base: await gatherBase(target, view),
2010
+ draft: view.draft,
1924
2011
  labels,
1925
2012
  // A rename's old path counts too: moving code into docs/ is not docs-only.
1926
2013
  changedFiles: files.flatMap(
@@ -1930,6 +2017,10 @@ async function gatherFacts(target) {
1930
2017
  manifestChanges,
1931
2018
  signOffs: await gatherSignOffs(target, labels)
1932
2019
  };
2020
+ if (HEAD_BOUND_SIGN_OFFS.some((label) => labels.includes(label))) {
2021
+ const pushedAt = await gatherHeadPushedAt(target, headSha);
2022
+ if (pushedAt !== void 0) facts.headPushedAt = pushedAt;
2023
+ }
1933
2024
  return { facts, headSha };
1934
2025
  }
1935
2026
  async function applyLabelEdits(target, evaluation) {
package/dist/index.d.ts CHANGED
@@ -30,6 +30,8 @@ interface LabelActor {
30
30
  interface SignOff {
31
31
  label: string;
32
32
  appliedBy?: LabelActor;
33
+ /** When its latest `labeled` event happened (ISO 8601), as GitHub records it. */
34
+ appliedAt?: string;
33
35
  }
34
36
  /** The account that opened a PR, as GitHub reports it (`dependabot[bot]`, `Bot`). */
35
37
  interface PullRequestAuthor {
@@ -70,6 +72,11 @@ interface PullRequestFacts {
70
72
  author?: PullRequestAuthor;
71
73
  /** The branch the PR merges into. `gatherFacts` always sets it. */
72
74
  base?: PullRequestBase;
75
+ /**
76
+ * Whether the PR is a draft, which GitHub won't merge. `gatherFacts` always
77
+ * sets it; absent reads as ready for review, so a WIP title fails closed.
78
+ */
79
+ draft?: boolean;
73
80
  labels: readonly string[];
74
81
  /** Every path the PR touches, including the old path of a rename. */
75
82
  changedFiles: readonly string[];
@@ -79,6 +86,13 @@ interface PullRequestFacts {
79
86
  manifestChanges: readonly FileChange[];
80
87
  /** Who applied each sign-off label present on the PR. */
81
88
  signOffs: readonly SignOff[];
89
+ /**
90
+ * When the current head was pushed (ISO 8601), from times the author can't
91
+ * forge: the latest force-push event and the head commit's earliest check
92
+ * suite, never a commit date. `gatherFacts` sets it whenever a head-bound
93
+ * sign-off (`UAT passed`, `tested`) is on the PR; absent, those don't count.
94
+ */
95
+ headPushedAt?: string;
82
96
  }
83
97
  /**
84
98
  * What a finding does to the `pr-policy` check-run:
@@ -264,14 +278,19 @@ declare const mergeBlockCheck: PolicyCheck;
264
278
  declare function isWorkflowPath(path: string): boolean;
265
279
 
266
280
  declare const TITLE_CHECK = "title";
267
- /** Every title rule violated by this PR's current title, labels, and diff. */
281
+ /**
282
+ * Every title rule violated by this PR's current title, labels, and diff. A WIP
283
+ * marker requires the PR to be a draft, which GitHub won't merge; a WIP draft is
284
+ * fine. The other rules judge the title without the marker, so a leading one
285
+ * reads as "not ready" rather than "not a Conventional Commit".
286
+ */
268
287
  declare function decideTitle(pr: PullRequestFacts): CheckResult;
269
288
  declare const titleCheck: PolicyCheck;
270
289
 
271
290
  /**
272
291
  * The Conventional-Commit grammar a squash subject must satisfy. It mirrors the
273
- * fleet's `pr-title-lint.yml` and `commit-convention.yml` exactly, so a title
274
- * this accepts is one the post-merge tripwire accepts too.
292
+ * fleet's `commit-convention.yml`, the post-merge tripwire, exactly, so a title
293
+ * this accepts is one the tripwire accepts too.
275
294
  */
276
295
  declare const COMMIT_TYPES: readonly ["feat", "fix", "docs", "chore", "refactor", "test", "style", "perf", "ci", "build", "revert"];
277
296
  type CommitType = (typeof COMMIT_TYPES)[number];
@@ -379,8 +398,9 @@ declare function evaluatePolicy(pr: PullRequestFacts, checks?: readonly PolicyCh
379
398
  /**
380
399
  * Parse and validate a JSON facts document into `PullRequestFacts`.
381
400
  * `workflowChanges`, `manifestChanges`, and `signOffs` are optional and default
382
- * to none; `body`, `author`, and `base` are optional and stay absent. With no
383
- * `signOffs`, no sign-off label counts: trust fails closed.
401
+ * to none; `body`, `author`, `base`, `draft`, and `headPushedAt` are optional and
402
+ * stay absent. With no `signOffs`, no sign-off label counts, and with no
403
+ * `headPushedAt`, no `UAT passed` does: trust fails closed.
384
404
  */
385
405
  declare function parseFacts(raw: string): PullRequestFacts;
386
406
 
package/dist/index.js CHANGED
@@ -48,7 +48,7 @@ import {
48
48
  sensitiveBumps,
49
49
  statusBody,
50
50
  titleCheck
51
- } from "./chunk-USVRZJHF.js";
51
+ } from "./chunk-XIDP7SRE.js";
52
52
  export {
53
53
  AMBIGUOUS_INDICATORS,
54
54
  BLOCKED_LABEL,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rmartz/pr-policy",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Read-only PR content classifiers — CI-change classification, title-type rules, and more — reported as one blocking pr-policy check-run. Distributed as a pinned Action kept current by Dependabot.",
5
5
  "keywords": [
6
6
  "pr-policy",