Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
ci: a package file's comment share may not rise (#4445)
Miguel Ángel3520c8225c9c
diff --git a/.github/workflows/comments.yml b/.github/workflows/comments.ymlindex e6cd870f34..f11c35f0a2 100644--- a/.github/workflows/comments.yml+++ b/.github/workflows/comments.yml@@ -33,8 +33,13 @@ jobs:# The commented-out-code rule asks the TypeScript parser, a root dependency.- run: bash scripts/ci/install-workspace-dependencies.sh --ignore-scripts- name: Test the checker- run: node --test scripts/check-comment-citations.test.mjs+ run: node --test scripts/check-comment-citations.test.mjs scripts/comment-ratchet.test.mjs- name: Check the comments this diff touchedenv:COMMENT_CHECK_BASE: ${{ github.event.pull_request.base.sha }}run: node scripts/check-comment-citations.mjs+ - name: A package file's comment share may not rise+ if: ${{ !cancelled() }}+ env:+ COMMENT_CHECK_BASE: ${{ github.event.pull_request.base.sha }}+ run: node scripts/comment-ratchet.mjsdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 82401f9a71..3f902055de 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -80,7 +80,9 @@ The `Comments` check (`scripts/check-comment-citations.mjs`) grades the comments- **No commented-out code.** Delete it; git keeps it.- **No block over 40 lines.** Cut it to the why and the invariant. A block that must stay whole (a licence, a diagram, a protocol table) starts with `comment-length: <reason>`.-Only comment blocks holding a line your PR added can fail. Findings elsewhere in a file you touched are printed as warnings, and fixing one while you are there is welcome. To grade files by hand, pass their paths: `node scripts/check-comment-citations.mjs path/to/file.ts`.+- **A package file's comment share may not rise** (`scripts/comment-ratchet.mjs`). For source under `packages/*/src` (tests excluded), a file you change may not end up with a higher share of comment lines than it had where your branch forked, unless you only deleted code. It may not gain a new comment block over 12 lines, and a new file may not start above its package's share. Move the explanation into a name, a type or the PR description.++Only comment blocks holding a line your PR added can fail the citation and block rules. Findings elsewhere in a file you touched are printed as warnings, and fixing one while you are there is welcome. To grade files by hand, pass their paths: `node scripts/check-comment-citations.mjs path/to/file.ts`.## Adding Registry Items (Blocks & Components)diff --git a/package.json b/package.jsonindex a658844d94..2e7fe92a14 100644--- a/package.json+++ b/package.json@@ -52,7 +52,7 @@"player:perf": "bun run --filter @hyperframes/player perf","format:check": "oxfmt --check .","knip": "knip",- "test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts",+ "test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-registry-set-delta.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-pr-captures.test.mjs scripts/check-comment-citations.test.mjs scripts/comment-ratchet.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-media-use-copy-parity.test.mjs scripts/check-svg-sanitize-parity.test.mjs scripts/check-media-use-svg-sanitize-generated.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/check-large-files.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/pr-edit-concurrency.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/host-registry-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/catalog-hosted-files.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs scripts/creator-editing-recipes.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs packages/core/scripts/writeGeneratedFile.test.ts scripts/catalog-publication.test.mjs scripts/ci/resolve-workflow-pr.test.mjs scripts/check-catalog-source-pr.test.mjs scripts/generate-registry-items.test.ts scripts/catalog-drift.test.ts scripts/catalog-fetch-mirror.test.ts scripts/catalog-script-inlining.test.ts scripts/catalog-detail.test.ts scripts/generate-catalog-pages.test.ts scripts/verify-catalog-payloads.test.ts scripts/registry-skill-files.test.ts scripts/creator-editing-capabilities.test.mjs scripts/generate-catalog-previews.test.ts scripts/registry-primitive-payloads.test.ts registry/components/pan-stations/pan-stations.test.mjs && vitest run scripts/catalog/ scripts/contrastRatchet.test.ts scripts/generate-catalog-payloads.test.ts","typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json","test:skills": "node --test 'skills/**/*.test.mjs' 'packages/cli/src/media-use/**/*.test.mjs'","generate:previews": "tsx scripts/generate-template-previews.ts",diff --git a/scripts/comment-ratchet.mjs b/scripts/comment-ratchet.mjsnew file mode 100644index 0000000000..eefdbbcc5d--- /dev/null+++ b/scripts/comment-ratchet.mjs@@ -0,0 +1,149 @@+#!/usr/bin/env node+// fallow-ignore-file complexity+// A changed source file's comment share may not rise versus its own copy at the merge-base, and it+// may not gain a comment block over 12 lines. A new file may not open above its package's share.+// Rules and reasons: CONTRIBUTING.md, "Comments". Line counting is owned by the citation checker.+import { execFileSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { extname } from "node:path";+import { commentBlocks } from "./check-comment-citations.mjs";++const MAX_BLOCK_LINES = 12;++// Product source only: a test's table of cases reads as comment and is the test's content.+export const isSource = (path) =>+ /^packages\/[^/]+\/src\/.+\.tsx?$/.test(path) && !/\.(d|test|spec)\.tsx?$/.test(path);++const packageOf = (path) => path.split("/").slice(0, 2).join("/");++const git = (args) => execFileSync("git", args, { encoding: "utf8", maxBuffer: 256e6 });++// `-M` names both paths of a rename, so a renamed file keeps its own history instead of being+// graded as new.+export function changedPaths(nameStatus) {+ return nameStatus+ .split("\n")+ .filter(Boolean)+ .map((line) => {+ const [status, ...paths] = line.split("\t");+ const [from, to] = /^[RC]\d*$/.test(status) ? paths : [paths[0], paths[0]];+ return { status: status[0], from, to };+ })+ .filter((entry) => entry.from !== undefined && entry.to !== undefined);+}++// Volume counts lines carrying prose, not a block's span: deleting the code between two blocks+// merges their spans, which would read as comments appearing from nowhere.+export function measure(source, ext) {+ const blocks = commentBlocks(source, ext);+ const span = (block) => block.end - block.start + 1;+ return {+ lines: source.split("\n").length,+ comment: blocks.reduce((total, block) => total + block.textLines, 0),+ long: blocks.filter((block) => !block.marked && span(block) > MAX_BLOCK_LINES).length,+ };+}++const share = (entry) => (entry.lines === 0 ? 0 : entry.comment / entry.lines);+const percent = (entry) => `${(share(entry) * 100).toFixed(1)}% (${entry.comment}/${entry.lines})`;++const WALL_ADVICE =+ ` Cut it to the why and the invariant, or mark its first line "comment-length: <reason>"\n` ++ ` if it genuinely must stay (a licence, a diagram, a protocol table).`;++// `base` is the file at the merge-base, or null when new. Share fails only when comment lines+// were added too, since deleting code lifts the share of comments nobody touched.+export function judge(file, head, base, packageShare) {+ const problems = [];+ if (base === null) {+ if (share(head) > packageShare) {+ problems.push(+ `NEW file over its package's comment share: ${file} is ${percent(head)}, the package is ` ++ `${(packageShare * 100).toFixed(1)}%\n` ++ ` A new file starts at or under what its package already carries. Cut the prose, or\n` ++ ` move the explanation into a name or a type.`,+ );+ }+ if (head.long > 0) {+ problems.push(+ `NEW comment block over ${MAX_BLOCK_LINES} lines: ${file} has ${head.long}\n${WALL_ADVICE}`,+ );+ }+ return problems;+ }+ if (share(head) > share(base) && head.comment > base.comment) {+ problems.push(+ `RAISED comment share: ${file} is ${percent(head)}, at the base ${percent(base)}\n` ++ ` ${head.comment - base.comment} comment line(s) added. Cut them, or move the explanation\n` ++ ` into a name or a type. A file's comment share may only go down.`,+ );+ }+ if (head.long > base.long) {+ problems.push(+ `NEW comment block over ${MAX_BLOCK_LINES} lines: ${file} has ${head.long}, the base has ${base.long}\n${WALL_ADVICE}`,+ );+ }+ return problems;+}++// Untrimmed: dropping the trailing newline shortens the base by a line and raises its share.+function atBase(ref, file) {+ try {+ return execFileSync("git", ["show", `${ref}:${file}`], { encoding: "utf8", stdio: "pipe" });+ } catch {+ return null;+ }+}++// The bar for a new file: its package's share over files that existed at the base, so new files+// never set their own bar. A package that is new as a whole is held to every package's share.+function packageTotal(dir, isNew) {+ return git(["ls-files", dir])+ .split("\n")+ .filter((file) => isSource(file) && !isNew.has(file))+ .reduce(+ (sum, file) => {+ const entry = measure(readFileSync(file, "utf8"), extname(file));+ return { lines: sum.lines + entry.lines, comment: sum.comment + entry.comment };+ },+ { lines: 0, comment: 0 },+ );+}++function packageShare(pkg, isNew) {+ const own = packageTotal(`${pkg}/src`, isNew);+ return share(own.lines > 0 ? own : packageTotal("packages", isNew));+}++if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {+ const ref = git(["merge-base", process.env.COMMENT_CHECK_BASE ?? "origin/main", "HEAD"]).trim();+ // Against the working tree, where contents are read from; in CI that is HEAD.+ const changed = changedPaths(git(["diff", "--name-status", "-M", ref, "--", "packages"]))+ .filter(({ status, to }) => status !== "D" && isSource(to))+ .sort((a, b) => a.to.localeCompare(b.to));++ const graded = changed.map(({ from, to }) => ({ to, onBase: atBase(ref, from) }));+ const isNew = new Set(graded.filter(({ onBase }) => onBase === null).map(({ to }) => to));+ const shares = new Map();+ const problems = [];+ for (const { to, onBase } of graded) {+ const head = measure(readFileSync(to, "utf8"), extname(to));+ const pkg = packageOf(to);+ if (onBase === null && !shares.has(pkg)) shares.set(pkg, packageShare(pkg, isNew));+ const base = onBase === null ? null : measure(onBase, extname(to));+ problems.push(...judge(to, head, base, shares.get(pkg) ?? 0));+ }++ const short = git(["rev-parse", "--short", ref]).trim();+ if (problems.length === 0) {+ console.log(+ `comment-ratchet: ${changed.length} changed source file(s) at or under their share at the merge-base ${short}.`,+ );+ process.exit(0);+ }+ for (const problem of problems) console.error(problem);+ console.error(+ `\n${problems.length} problem(s) across ${changed.length} changed source file(s), against the merge-base ${short}.`,+ );+ process.exit(1);+}diff --git a/scripts/comment-ratchet.test.mjs b/scripts/comment-ratchet.test.mjsnew file mode 100644index 0000000000..7cd438273a--- /dev/null+++ b/scripts/comment-ratchet.test.mjs@@ -0,0 +1,220 @@+// fallow-ignore-file complexity+// Each rule gets a test that fails when that rule alone is removed.+import assert from "node:assert/strict";+import { execFileSync, spawnSync } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { test } from "node:test";+import { fileURLToPath } from "node:url";++import { changedPaths, isSource, judge, measure } from "./comment-ratchet.mjs";++const RATCHET = fileURLToPath(new URL("./comment-ratchet.mjs", import.meta.url));+const wall = (lines) => Array.from({ length: lines }, (_, i) => `// line ${i + 1}`).join("\n");+const PACKAGE = 0.4;++test("a 13-line comment block counts as over-long, a 12-line one does not", () => {+ assert.equal(measure(`${wall(13)}\nconst a = 1;\n`, ".ts").long, 1);+ assert.equal(measure(`${wall(12)}\nconst a = 1;\n`, ".ts").long, 0);+});++test("the comment-length marker exempts an over-long block", () => {+ const marked = `// comment-length: a protocol table\n${wall(20)}\nconst a = 1;\n`;+ assert.equal(measure(marked, ".ts").long, 0);+ const bare = `// comment-length:\n${wall(20)}\nconst a = 1;\n`;+ assert.equal(measure(bare, ".ts").long, 1, "no reason, no exemption");+});++test("a JSX comment counts as comment, and code does not", () => {+ const jsx = "export const A = () => (\n <div>\n {/* why */}\n </div>\n);\n";+ assert.equal(measure(jsx, ".tsx").comment, 1);+ assert.equal(measure("const a = 1;\n", ".ts").comment, 0);+});++// 14 physical lines: a bare opener, 12 of prose, a bare closer.+test("a docblock is measured from its opener to its closer", () => {+ const body = Array.from({ length: 12 }, (_, i) => ` * line ${i + 1}`).join("\n");+ const doc = `/**\n${body}\n */\nconst a = 1;\n`;+ assert.equal(doc.split("\n").indexOf(" */"), 13, "the closer is the 14th line");+ assert.equal(measure(doc, ".ts").long, 1);+});++test("volume counts lines carrying prose, not a block span", () => {+ const doc = "/**\n * one\n *\n * two\n */\nconst a = 1;\n";+ assert.equal(measure(doc, ".ts").comment, 2);+});++test("adding a comment line to a file fails", () => {+ const base = { lines: 100, comment: 20, long: 0 };+ const head = { lines: 100, comment: 25, long: 0 };+ const problems = judge("src/a.ts", head, base, PACKAGE);+ assert.equal(problems.length, 1);+ assert.match(+ problems[0],+ /^RAISED comment share: src\/a\.ts is 25\.0% \(25\/100\), at the base 20\.0% \(20\/100\)/,+ );+ assert.match(problems[0], /5 comment line\(s\) added/);+});++test("adding code passes", () => {+ const problems = judge(+ "src/a.ts",+ { lines: 130, comment: 20, long: 0 },+ { lines: 100, comment: 20, long: 0 },+ PACKAGE,+ );+ assert.deepEqual(problems, []);+});++// 20/60 is 33% against 20/100 at 20%: the share rose and no comment line was written.+test("deleting code passes, though it lifts the share", () => {+ const problems = judge(+ "src/a.ts",+ { lines: 60, comment: 20, long: 0 },+ { lines: 100, comment: 20, long: 0 },+ PACKAGE,+ );+ assert.deepEqual(problems, []);+});++test("deleting comments passes silently", () => {+ const problems = judge(+ "src/a.ts",+ { lines: 100, comment: 5, long: 0 },+ { lines: 100, comment: 20, long: 1 },+ PACKAGE,+ );+ assert.deepEqual(problems, []);+});++test("a new over-long block fails even when the share falls", () => {+ const problems = judge(+ "src/a.ts",+ { lines: 400, comment: 40, long: 2 },+ { lines: 100, comment: 20, long: 1 },+ PACKAGE,+ );+ assert.equal(problems.length, 1);+ assert.match(problems[0], /^NEW comment block over 12 lines: src\/a\.ts has 2, the base has 1/);+});++test("a new file may not open above its package's share, nor carry a wall", () => {+ const problems = judge("src/new.ts", { lines: 100, comment: 60, long: 1 }, null, PACKAGE);+ assert.equal(problems.length, 2);+ assert.match(+ problems[0],+ /^NEW file over its package's comment share: src\/new\.ts is 60\.0% \(60\/100\), the package is 40\.0%/,+ );+ assert.match(problems[1], /^NEW comment block over 12 lines: src\/new\.ts has 1/);+});++test("a new file at or under its package's share passes", () => {+ assert.deepEqual(judge("src/new.ts", { lines: 100, comment: 40, long: 0 }, null, PACKAGE), []);+});++test("a rename names both of its paths; everything else names one twice", () => {+ const status = "R100\tpkg/src/old.ts\tpkg/src/new.ts\nM\tpkg/src/kept.ts\nA\tpkg/src/added.ts";+ assert.deepEqual(changedPaths(status), [+ { status: "R", from: "pkg/src/old.ts", to: "pkg/src/new.ts" },+ { status: "M", from: "pkg/src/kept.ts", to: "pkg/src/kept.ts" },+ { status: "A", from: "pkg/src/added.ts", to: "pkg/src/added.ts" },+ ]);+});++test("a pure rename passes, and a rename that adds comments still fails", () => {+ const before = "/**\n * why this exists\n */\nexport const a = 1;\n";+ const after = `// and three\n// more lines\n// of prose\n${before}`;+ const base = measure(before, ".ts");+ assert.deepEqual(judge("src/new.ts", measure(before, ".ts"), base, PACKAGE), []);+ const problems = judge("src/new.ts", measure(after, ".ts"), base, PACKAGE);+ assert.equal(problems.length, 1);+ assert.match(problems[0], /^RAISED comment share: src\/new\.ts is /);+ assert.match(problems[0], /3 comment line\(s\) added/);+});++test("a trailing newline counts as a line", () => {+ assert.equal(measure("// a\n", ".ts").lines, 2);+ assert.equal(measure("// a", ".ts").lines, 1);+});++test("only package source is graded, never tests or declarations", () => {+ assert.equal(isSource("packages/studio/src/App.tsx"), true);+ assert.equal(isSource("packages/core/src/runtime/init.ts"), true);+ assert.equal(isSource("packages/core/src/runtime/init.test.ts"), false);+ assert.equal(isSource("packages/core/src/types.d.ts"), false);+ assert.equal(isSource("packages/core/scripts/build.ts"), false);+ assert.equal(isSource("scripts/contrast.ts"), false);+});++// Drives the entry point on a real two-commit repo, so the merge-base and diff wiring are tested.+function runCli(t, base, head) {+ const root = mkdtempSync(path.join(tmpdir(), "comment-ratchet-"));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ const write = (entries) => {+ for (const [rel, body] of Object.entries(entries)) {+ mkdirSync(path.join(root, path.dirname(rel)), { recursive: true });+ writeFileSync(path.join(root, rel), body);+ }+ };+ const identity = ["-c", "[email protected]", "-c", "user.name=Test"];+ const run = (...argv) => execFileSync("git", argv, { cwd: root, encoding: "utf8" });+ run("init", "-q");+ write(base);+ run("add", "-A");+ run(...identity, "commit", "-qm", "base", "--no-gpg-sign");+ const baseSha = run("rev-parse", "HEAD").trim();+ for (const rel of Object.keys(base)) if (!(rel in head)) rmSync(path.join(root, rel));+ write(head);+ run("add", "-A");+ run(...identity, "commit", "-qm", "head", "--no-gpg-sign");+ const env = { ...process.env, COMMENT_CHECK_BASE: baseSha };+ const cli = spawnSync(process.execPath, [RATCHET], { cwd: root, encoding: "utf8", env });+ return { status: cli.status, output: `${cli.stdout}${cli.stderr}` };+}++const FILE = "packages/web/src/a.ts";+const code = "export const a = 1;\nexport const b = 2;\nexport const c = 3;\n";++test("the CLI fails a diff that adds comment lines to a package source file", (t) => {+ const { status, output } = runCli(t, { [FILE]: code }, { [FILE]: `// why b is two\n${code}` });+ assert.equal(status, 1, output);+ assert.match(output, /RAISED comment share: packages\/web\/src\/a\.ts/);+});++test("the CLI passes a diff that adds code, deletes a file, or edits a test", (t) => {+ const other = "packages/web/src/gone.ts";+ const spec = "packages/web/src/a.test.ts";+ const { status, output } = runCli(+ t,+ { [FILE]: code, [other]: code, [spec]: code },+ { [FILE]: `${code}export const d = 4;\n`, [spec]: `// a note\n${code}` },+ );+ assert.equal(status, 0, output);+ assert.match(output, /1 changed source file\(s\) at or under their share/);+});++test("the CLI holds a new file to its own package's share", (t) => {+ const quiet = "packages/quiet/src/a.ts";+ const loud = "packages/quiet/src/b.ts";+ const { status, output } = runCli(+ t,+ { [quiet]: code },+ { [quiet]: code, [loud]: `// hi\n${code}` },+ );+ assert.equal(status, 1, output);+ assert.match(output, /NEW file over its package's comment share: packages\/quiet\/src\/b\.ts/);+});++// New files must not set their own bar: a whole new package is held to the other packages.+test("the CLI fails a new package whose files are all heavy with comments", (t) => {+ const fresh = (name) => `packages/fresh/src/${name}.ts`;+ const heavy = `// one\n// two\n// three\n${code}`;+ const { status, output } = runCli(+ t,+ { [FILE]: code },+ { [FILE]: code, [fresh("a")]: heavy, [fresh("b")]: heavy },+ );+ assert.equal(status, 1, output);+ assert.match(output, /NEW file over its package's comment share: packages\/fresh\/src\/a\.ts/);+});