diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 45185550..4c3e2923 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -2,6 +2,26 @@ +## Whole-change check + + + ## Checklist ([PRODUCT.md](https://github.com/eizedev/pivotkit/blob/main/PRODUCT.md#what-a-contribution-delivers)) - [ ] Linked issue; for a new feature, the answers to the five questions @@ -12,5 +32,5 @@ ## Test plan - [ ] The checks of [Check your change](https://github.com/eizedev/pivotkit/blob/main/CONTRIBUTING.md#check-your-change): those for every change, and those for what this one changes -- [ ] `npm run growth` passes, or the known baseline entry it fails on is named in the Summary +- [ ] `npm run growth` passes, or the known baseline entry it fails on is named in the whole-change check - [ ] What I ran, with numbers where a check gives some, such as benchmark timings: diff --git a/.github/workflows/whole-change-check.yml b/.github/workflows/whole-change-check.yml new file mode 100644 index 00000000..570b8fea --- /dev/null +++ b/.github/workflows/whole-change-check.yml @@ -0,0 +1,45 @@ +name: Whole-change check + +# A pull request that changes docs or code says in its description what its author read whole and how +# the change reshaped it (scripts/whole-change-check.js says what counts and who is exempt). It runs +# again when the description is edited, so fixing the description turns it green; a workflow of its +# own, so an edit does not run all of CI again. +# +# The description, title and author reach the script only through env: whoever opens the pull request +# writes them, and an expression inside `run` would become part of the shell script. +on: + # every base branch, as ci.yml + pull_request: + types: [opened, synchronize, reopened, edited] + +permissions: + contents: read + +concurrency: + group: whole-change-check-${{ github.ref }} + cancel-in-progress: true + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # the merge commit and its first parent, the base: their difference is what the pull request changes + fetch-depth: 2 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: "24" + - name: Whole-change check + env: + PR_BODY: ${{ github.event.pull_request.body }} + PR_TITLE: ${{ github.event.pull_request.title }} + PR_AUTHOR: ${{ github.event.pull_request.user.login }} + run: | + # quotepath off: a path with non-ASCII letters as it is, not quoted and escaped. No renames: + # a file moved out of scope counts by its old path too + CHANGED_FILES="$(git -c core.quotepath=off diff --no-renames --name-only HEAD^1 HEAD)" + export CHANGED_FILES + node scripts/whole-change-check.js diff --git a/AGENTS.md b/AGENTS.md index f333350f..9269eb17 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,7 +60,7 @@ npm run pack:check # what npm pack would publish, checked npm run growth # functions, unused exports, duplication, docs pages may not grow ``` `npm run growth` compares with `scripts/growth-baseline.json`; when an offender shrinks, `node scripts/growth.js --update` lowers it. -When it fails on a known baseline entry, [CONTRIBUTING.md](CONTRIBUTING.md#check-your-change) says what to do. +When it fails, [CONTRIBUTING.md](CONTRIBUTING.md#check-your-change) says what to do; a raised baseline needs its reason in the pull request's whole-change check. One package, the UI and the browser tests. A package's `AGENTS.md` lists its size and benchmark commands: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 997cf7b0..56331c6e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,9 +48,9 @@ the header of `scripts/growth.js` explains each check. If it fails: - on a function or docs page that is already in `scripts/growth-baseline.json` under the same file and name, also when your change made it bigger, or on the total of all docs pages: name it in the - pull request's summary, for example "growth fails on the known entry `LevelMenu`". The red check - is expected, and the maintainer fixes it before the merge. CI skips the later steps of that job, - so run `npm test` and `npm run types` locally and say so. + pull request's whole-change check with why it grew, for example "growth fails on the known entry + `LevelMenu`: ...". The red check is expected, and the maintainer decides before the merge. CI skips + the later steps of that job, so run `npm test` and `npm run types` locally and say so. - because an entry shrank: run `node scripts/growth.js --update` and commit the baseline. - on anything else (a new entry, duplicated code, a renamed or moved function): that one is yours to fix. @@ -111,6 +111,8 @@ After `uvx zensical@ build --strict`, `node scripts/check-readme-links. ## Pull request - Link the issue. Write `Fixes #n` in the description, not in commit messages. +- A change to docs or code fills in the template's whole-change check: what you read whole, and how + you reshaped it instead of appending. CI fails without it; editing the description runs it again. - Say what you tested. - A larger feature is reviewed by a user, an operator and a developer, from the packed packages. - An independent review before you open the pull request is strongly recommended. diff --git a/PRODUCT.md b/PRODUCT.md index b514ad5c..303ac019 100644 --- a/PRODUCT.md +++ b/PRODUCT.md @@ -110,10 +110,12 @@ same for everyone. [CONTRIBUTING.md](CONTRIBUTING.md) has the commands. - Tests that fail without the change and pass with it. No test weakened to pass. - Docs and upgrading notes that describe the new state. A changelog entry is welcome; [CONTRIBUTING.md](CONTRIBUTING.md#changelog-and-commits) says what happens without one. +- For a change to docs or code, a whole-change check in the description: each touched page or + function read whole, and how the change reshaped it instead of appending. - Strongly recommended: an independent review before you open the pull request. Have code an AI assistant wrote reviewed by a reviewer that did not write it (a person or a separate AI session), and read, run and understand it yourself. The maintainer reviews every pull request neutrally anyway. What your own review would have found comes back as questions and change requests, and it delays the merge. -- Green CI on the commit that gets merged. A growth check that fails on a known entry is the - maintainer's to fix ([CONTRIBUTING.md](CONTRIBUTING.md#check-your-change)). +- Green CI on the commit that gets merged. On a growth check that fails on a known entry, the + maintainer decides ([CONTRIBUTING.md](CONTRIBUTING.md#check-your-change)). diff --git a/scripts/growth.js b/scripts/growth.js index f63eff8a..7de3a816 100644 --- a/scripts/growth.js +++ b/scripts/growth.js @@ -58,12 +58,19 @@ export const DOCS_TOTAL_MARGIN = 1; /** The folders under docs/ that hold build output, not pages. */ const DOCS_BUILD_OUTPUT = new Set(["playground", "schema", "assets"]); +/** + * What to do when a function or a page grew. A number cannot judge sense: the guard is an alarm to + * look at the whole, and squeezing lines or cutting words to pass it makes the code or page worse. + */ +const STOP = `Stop and read the whole of it; write what you found in the pull request's whole-change check (.github/PULL_REQUEST_TEMPLATE.md, "Whole-change check").`; +const OR_RAISE = `Or raise the baseline with ${UPDATE} --accept-growth, with the reason in the whole-change check and the maintainer's approval. Never merge lines or cut words only to pass the number.`; + /** What to do when a guard fails, said once per guard. */ const ADVICE = { - functions: `Split the function into smaller ones, one job each (AGENTS.md, "How we build"). Limits: ${FUNCTION_LIMITS.lines} lines without blank lines and comments, complexity ${FUNCTION_LIMITS.complexity}.`, + functions: `The function grew. ${STOP} Then reshape it for real: extract the jobs it does beside its own (AGENTS.md, "Small units"). ${OR_RAISE} Limits: ${FUNCTION_LIMITS.lines} lines without blank lines and comments, complexity ${FUNCTION_LIMITS.complexity}.`, unused: "Delete the export or the file nobody uses. If it is public API, export it from the package's entry point (its package.json \"exports\"). If knip is wrong, say so in knip.json.", duplication: "Move the copied code into one function or module that both places import (AGENTS.md, \"One place per fact\"). The threshold is in .jscpd.json.", - docs: "Shorten the page, or split it into pages with one topic each; rewrite instead of appending (AGENTS.md, \"Docs and changelogs\").", + docs: `The page grew. ${STOP} Then reshape it for real: move detail to a sub-page and link it, write a list or a table instead of prose, or move a section to the page that owns its topic (AGENTS.md, "Docs and changelogs"). ${OR_RAISE}`, }; const posix = (path, base = root) => relative(base, path).split(sep).join("/"); @@ -340,7 +347,7 @@ async function main(argv) { writeFileSync(BASELINE, formatBaseline(next)); console.log(`wrote ${posix(fileURLToPath(BASELINE))}`); } else if (update) { - console.error(`\nThe baseline was not written: something grew. Fix that, or raise the baseline with ${UPDATE} --accept-growth and say why in the pull request.`); + console.error(`\nThe baseline was not written: something grew. Reshape it, or raise the baseline with ${UPDATE} --accept-growth and give the reason in the pull request's whole-change check.`); } process.exitCode = failed ? 1 : 0; } diff --git a/scripts/whole-change-check.js b/scripts/whole-change-check.js new file mode 100644 index 00000000..c8deab72 --- /dev/null +++ b/scripts/whole-change-check.js @@ -0,0 +1,89 @@ +// Whole-change check: a pull request that changes docs or code has a "## Whole-change check" section +// with text in its description. There its author says what they read whole and how the change +// reshaped it instead of appending (.github/PULL_REQUEST_TEMPLATE.md). The growth guards (growth.js) +// count lines; a number cannot judge sense, so this asks for the judgement, and the review judges it. +// +// .github/workflows/whole-change-check.yml runs it on every pull request, also when the description +// is edited. It reads everything from environment variables, never from the command line, because +// the description and title are written by whoever opens the pull request: +// +// PR_BODY, PR_TITLE, PR_AUTHOR the description, the title and the author's login +// CHANGED_FILES the changed paths, one per line +// +// Exempt are Dependabot's pull requests and release pull requests (RELEASING.md), known by their +// title: "chore(release): ... x.y.z" or "chore(): release ... x.y.z", the scope optional. The +// title is the author's word; the review sees it. +import { isMain } from "./is-main.js"; + +/** The heading the description needs, without its "## ". */ +export const HEADING = "Whole-change check"; + +/** The paths whose change needs the check: Markdown of the docs site, READMEs and the root, and code. */ +const SCOPE = [/^docs\/.*\.md$/, /(^|\/)README\.md$/, /^[^/]+\.md$/, /^packages\/[^/]+\/src\//, /^scripts\//]; + +/** + * The changed paths that need the check. + * @param {string[]} files + */ +export const inScope = (files) => files.filter((file) => SCOPE.some((re) => re.test(file))); + +/** + * The text of the description's whole-change check, without HTML comments (the template's prompts), + * up to the next heading of level 1 or 2; null when the description has no such heading. + * @param {string | null | undefined} body + */ +export function sectionText(body) { + // an unclosed comment hides the rest of the description, on GitHub as here + const lines = String(body ?? "").replace(/|$)/g, "").split(/\r?\n/); + // the level of each heading line, 0 for other lines; a "#" inside a code fence is no heading + let fenced = false; + const levels = lines.map((line) => { + if (/^ {0,3}(?:```|~~~)/.test(line)) fenced = !fenced; + return fenced ? 0 : (/^ {0,3}(#{1,6})\s/.exec(line)?.[1].length ?? 0); + }); + const start = lines.findIndex((line, i) => levels[i] === 2 && /^ {0,3}##\s+whole-change check\s*#*\s*$/i.test(line)); + if (start === -1) return null; + const end = levels.findIndex((level, i) => i > start && level > 0 && level <= 2); + return lines.slice(start + 1, end === -1 ? undefined : end).join("\n").trim(); +} + +/** + * Why a pull request needs no whole-change check whatever it changes, or null. + * @param {{ author?: string, title?: string }} pr + */ +export function exemption({ author = "", title = "" }) { + if (author === "dependabot[bot]") return "a Dependabot pull request"; + if (/^chore(?:\(release\)!?:|(?:\([^)]*\))?!?:\s*release\b).*\s\d+\.\d+\.\d+$/i.test(title)) return "a release pull request"; + return null; +} + +/** + * The verdict on a pull request, with the text to print. + * @param {{ body?: string | null, title?: string, author?: string, files: string[] }} pr + * @returns {{ ok: boolean, message: string }} + */ +export function check({ body, title, author, files }) { + const exempt = exemption({ author, title }); + if (exempt) return { ok: true, message: `Whole-change check: not needed for ${exempt}.` }; + const touched = inScope(files); + if (touched.length === 0) return { ok: true, message: "Whole-change check: not needed, no docs or code changed." }; + if (/[\p{L}\p{N}]/u.test(sectionText(body) ?? "")) return { ok: true, message: "Whole-change check: found in the description." }; + const shown = touched.slice(0, 10).join("\n ") + (touched.length > 10 ? `\n and ${touched.length - 10} more` : ""); + return { + ok: false, + message: [ + `This pull request changes docs or code:\n ${shown}`, + `Its description needs a "## ${HEADING}" section with text: what you read whole, and how you`, + "reshaped it instead of appending. The prompts are in .github/PULL_REQUEST_TEMPLATE.md.", + "Edit the description; the check runs again.", + ].join("\n"), + }; +} + +if (isMain(import.meta.url)) { + const { PR_BODY, PR_TITLE, PR_AUTHOR, CHANGED_FILES = "" } = process.env; + const files = CHANGED_FILES.split("\n").map((line) => line.trim()).filter(Boolean); + const { ok, message } = check({ body: PR_BODY, title: PR_TITLE, author: PR_AUTHOR, files }); + (ok ? console.log : console.error)(message); + process.exitCode = ok ? 0 : 1; +} diff --git a/tests/whole-change-check.test.js b/tests/whole-change-check.test.js new file mode 100644 index 00000000..eca67562 --- /dev/null +++ b/tests/whole-change-check.test.js @@ -0,0 +1,68 @@ +// scripts/whole-change-check.js: which changes need the description's whole-change check, what counts +// as one, and who is exempt. The workflow that runs it is checked in tests/workflows.test.js. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { check, exemption, inScope, sectionText } from "../scripts/whole-change-check.js"; + +const template = readFileSync(new URL("../.github/PULL_REQUEST_TEMPLATE.md", import.meta.url), "utf8"); +const pr = (body, files = ["docs/use/fields.md"], more = {}) => check({ body, title: "docs: fields", author: "someone", files, ...more }); + +test("docs, READMEs, root Markdown, package sources and scripts need the check; the rest does not", () => { + const needed = ["docs/use/fields.md", "docs/reference/view-file.md", "README.md", "packages/pivotkit-core/README.md", "AGENTS.md", "CONTRIBUTING.md", "packages/pivotkit-core/src/engine.js", "scripts/growth.js"]; + const not = ["docs/openapi.json", "packages/pivotkit-core/test/engine.test.js", "packages/pivotkit-core/package.json", "packages/pivotkit-core/CHANGELOG.md", "tests/ci.test.js", ".github/workflows/ci.yml", "package-lock.json"]; + assert.deepEqual(inScope([...needed, ...not]), needed); +}); + +test("the template as it is fails: its prompts are a comment", () => { + assert.equal(sectionText(template), ""); + assert.equal(pr(template).ok, false); +}); + +test("the template with an answer under the heading passes", () => { + const filled = template.replace(/(## Whole-change check\s*)/, "$1\n\nfields.md: read whole; moved the folded details to filters.md."); + assert.equal(pr(filled).ok, true); +}); + +test("a missing, empty or only-comment section fails, and the message says what to add", () => { + for (const body of [null, undefined, "", "## Summary\n\nText.", "## Whole-change check\n\n## Test plan\n\nRan it.", "## Whole-change check\n\n", "## Whole-change check\n\n- [ ]\n"]) { + const result = pr(body); + assert.equal(result.ok, false, JSON.stringify(body)); + assert.match(result.message, /docs\/use\/fields\.md/); + assert.match(result.message, /"## Whole-change check" section with text/); + assert.match(result.message, /PULL_REQUEST_TEMPLATE\.md/); + } +}); + +test("the section ends at the next heading of level 1 or 2, not at a sub-heading", () => { + assert.equal(sectionText("## Whole-change check\r\nRead it whole.\r\n## Test plan\r\nRan."), "Read it whole."); + assert.equal(sectionText("## Summary\n\nx\n\n## Whole-change check\n\n### Docs\nRead it whole."), "### Docs\nRead it whole."); + assert.equal(sectionText("# Title\n## whole-change check ##\nok\n# Next"), "ok"); + // a heading inside a comment or within a line does not count + assert.equal(sectionText(""), null); + assert.equal(sectionText("Text about ## Whole-change check"), null); + // a heading inside a code fence is text + assert.equal(sectionText("```\n## Whole-change check\nfake\n```"), null); + assert.equal(sectionText("## Whole-change check\n```\n## not a heading\n```\nRead it whole.\n## Test plan"), "```\n## not a heading\n```\nRead it whole."); +}); + +test("an unclosed comment hides the rest, as GitHub renders it", () => { + assert.equal(sectionText("## Whole-change check\n