From b08c0b1788095d2a6830a764c0bec77980935985 Mon Sep 17 00:00:00 2001 From: Benjamin Shafii Date: Fri, 20 Nov 2026 16:45:04 -0800 Subject: [PATCH] chore(checks): reject new comments, casts and AI-sounding docs Turn pstack's /no-comments, TypeScript and /unslop guidance into checks that fail only on lines a change adds against origin/dev. - code-habits: the comment rule now covers TypeScript in apps, packages and ee, and new rules reject any, as casts (as const is fine), non-null assertions, ts/eslint/biome suppressions and console.log outside command-line entry points. - prose-habits: markdown lines may not add dashes, AI vocabulary, "serves as", "not just X but Y", chatbot phrases, wordy phrases, curly quotes or filler words. Code, inline code and links are skipped. - Both run in pnpm check and the quick check workflow. AGENTS.md drops the any/cast line the check now enforces. --- .github/workflows/quick-check.yml | 7 +- AGENTS.md | 3 +- apps/app/src/react-app/ARCHITECTURE.md | 5 +- scripts/check-code-habits.mjs | 86 +++++++++++--- scripts/check-code-habits.test.mjs | 50 ++++++++- scripts/check-prose-habits.mjs | 150 +++++++++++++++++++++++++ scripts/check-prose-habits.test.mjs | 39 +++++++ scripts/check.mjs | 7 +- scripts/check.test.mjs | 1 + 9 files changed, 323 insertions(+), 25 deletions(-) create mode 100644 scripts/check-prose-habits.mjs create mode 100644 scripts/check-prose-habits.test.mjs diff --git a/.github/workflows/quick-check.yml b/.github/workflows/quick-check.yml index 2b18bb96614..17728f2fd27 100644 --- a/.github/workflows/quick-check.yml +++ b/.github/workflows/quick-check.yml @@ -150,18 +150,21 @@ jobs: node --test scripts/check-node-source-imports.test.mjs node scripts/check-node-source-imports.mjs # The app's layering and habits, frozen where they stand: no new - # wrong-direction imports, legacy-folder files, comments or effects. + # wrong-direction imports, legacy-folder files, comments, effects, any, + # casts, non-null assertions, suppressions, console.log or AI-sounding docs. - name: Check the app's structure and code habits env: BASE_SHA: ${{ github.event.pull_request.base.sha }} run: | - node --test scripts/check-app-structure.test.mjs scripts/check-code-habits.test.mjs + node --test scripts/check-app-structure.test.mjs scripts/check-code-habits.test.mjs scripts/check-prose-habits.test.mjs node scripts/check-app-structure.mjs if [ -n "${BASE_SHA:-}" ]; then git fetch --no-tags --depth=1 origin "$BASE_SHA" node scripts/check-code-habits.mjs --base "$BASE_SHA" + node scripts/check-prose-habits.mjs --base "$BASE_SHA" else node scripts/check-code-habits.mjs + node scripts/check-prose-habits.mjs fi # Workspace folders match their package names (scripts/check-package-names.mjs). - name: Check workspace package names diff --git a/AGENTS.md b/AGENTS.md index 25dd26e3c9a..c11de3af95c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,8 +20,7 @@ own files, built on OpenCode. This repo is public. * **Generated contracts.** Never commit or hand-edit OpenAPI or `packages/sdk/src/gen/**`. Never regenerate a Drizzle migration snapshot to resolve a conflict. -* **Code.** pnpm only. No `any`, typecasts, or `as` unless unavoidable. Reuse - `@/components`; end users are non-technical. +* **Code.** pnpm only. Reuse `@/components`; end users are non-technical. * **Fix the root cause.** A workaround you find is debt to remove, not a pattern to copy. Never write a comment or doc that justifies a shortcut. * **Checks.** Run `pnpm check` before you say you are done. It is the diff --git a/apps/app/src/react-app/ARCHITECTURE.md b/apps/app/src/react-app/ARCHITECTURE.md index d521be3c60a..567c041c82a 100644 --- a/apps/app/src/react-app/ARCHITECTURE.md +++ b/apps/app/src/react-app/ARCHITECTURE.md @@ -57,8 +57,9 @@ src/ features share into `design-system/`, `kernel/` or `infra/`. `pnpm check` enforces rules 1, 3 and 6 (`scripts/check-app-structure.mjs`) and -rejects new comments and new `useEffect` calls in app code -(`scripts/check-code-habits.mjs`). What existed before the checks is frozen in +rejects new `useEffect` calls in app code (`scripts/check-code-habits.mjs`). +The same script rejects new comments, `any`, casts, non-null assertions, +suppressions and `console.log` across `apps`, `packages` and `ee`. What existed before the checks is frozen in their baselines, which only shrink. Toasts are rendered with `sonner` (`@/components/ui/sonner`), mounted once via diff --git a/scripts/check-code-habits.mjs b/scripts/check-code-habits.mjs index 8950a534350..274add6d905 100644 --- a/scripts/check-code-habits.mjs +++ b/scripts/check-code-habits.mjs @@ -7,28 +7,57 @@ import { fileURLToPath } from "node:url"; const root = fileURLToPath(new URL("../", import.meta.url)); const baselinePath = path.join(root, "scripts/code-habits-baseline.json"); const scope = "apps/app/src"; +const commentRoots = ["apps", "packages", "ee/apps", "ee/packages"]; +const publicApiRoots = ["packages/", "ee/packages/"]; const skipped = new Set(["node_modules", "dist", "build", "__tests__", "fixtures", "__fixtures__", "stories", "storybook", "generated", "__generated__", "gen"]); -const commentMessage = "No new comments in app code. Say it with a name, a type or a test; if the code needs explaining, restructure it."; +const commentMessage = "No new comments. Say it with a name, a type or a test; if the code needs explaining, restructure it."; const effectMessage = "No new useEffect. Fetch with TanStack Query, derive values during render, react to user actions in the event handler, and subscribe to external stores with useSyncExternalStore or the existing Zustand stores."; +const habitMessages = { + "no-new-any": "No new any. Type external data as unknown and parse it with the package's zod schema.", + "no-new-cast": "No new as casts. Parse with a schema, narrow with a check, or use satisfies; as const is fine.", + "no-new-non-null": "No new non-null assertions (!). Narrow with a check, or change the type so the value cannot be missing.", + "no-new-suppression": "No new @ts-ignore, @ts-expect-error, @ts-nocheck, eslint-disable or biome-ignore. Fix the error the suppression hides.", + "no-new-console-log": "No new console.log in shipped code. Use the package's logger, or console.error for a real failure.", +}; const updateMessage = "Effects decreased or the file was removed. Run node scripts/check-code-habits.mjs --update-baseline to tighten the ratchet."; -export function isSourceFile(file, content = "") { - return file.startsWith(`${scope}/`) && /\.tsx?$/.test(file) +export function isSourceFile(file, content = "", roots = [scope]) { + return roots.some((root) => file.startsWith(`${root}/`)) && /\.(?:[cm]?ts|tsx)$/.test(file) && !/\.d\.[cm]?ts$/.test(file) && !file.split("/").some((part) => skipped.has(part)) && !/\.(?:test|spec|stories|story|generated|gen)\./.test(file) - && !/(?:@generated|\bcode generated\b|\bauto-generated\b)/i.test(content.slice(0, 1000)); + && !/(?:@generated|\bcode generated\b|\bauto-generated\b|\bgenerated by\b|\bdo not edit\b)/i.test(content.slice(0, 1000)); } -export function isAllowedComment(text, header = false) { +export function isCommentSource(file, content = "") { + return isSourceFile(file, content, commentRoots); +} + +const issueOrRfcLink = /https?:\/\/(?:github\.com\/[\w.-]+\/[\w.-]+\/(?:issues|pull|discussions)\/\d+|(?:www\.)?rfc-editor\.org\/rfc\/|datatracker\.ietf\.org\/doc\/(?:html\/)?rfc\d+|bugs\.chromium\.org\/|issues\.chromium\.org\/|bugzilla\.mozilla\.org\/|bugs\.webkit\.org\/)/i; + +export function isAllowedComment(text, header = false, publicApiDoc = false) { + const body = text.replace(/^\/\/[\/]?|^\/\*+|\*\/$/g, "").replace(/^\s*\*\s?/gm, "").trim(); + return /^(?:@ts-(?:expect-error|ignore|nocheck)\b|eslint-(?:disable\S*|enable\S*)\b|biome-ignore\b|prettier-ignore\b| habits.push({ line: lineAt(node.getStart(source)), rule }); + if (node.kind === ts.SyntaxKind.AnyKeyword) habit("no-new-any"); + if (ts.isTypeAssertionExpression(node) + || (ts.isAsExpression(node) && !(ts.isTypeReferenceNode(node.type) && ts.isIdentifier(node.type.typeName) && node.type.typeName.text === "const"))) habit("no-new-cast"); + if (ts.isNonNullExpression(node)) habit("no-new-non-null"); + if (!commandLine && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) + && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "console" && node.expression.name.text === "log") habit("no-new-console-log"); if (ts.isCallExpression(node)) { const callee = node.expression; if ((ts.isIdentifier(callee) && effectNames.has(callee.text)) @@ -74,10 +110,12 @@ export function scanSource(file, content) { const start = scanner.getTokenPos(); const stop = scanner.getTextPos(); header &&= content.slice(previousEnd, start).trim() === ""; - comments.push({ line: lineAt(start), endLine: lineAt(stop - 1), allowed: isAllowedComment(content.slice(start, stop), header) }); + if (isSuppression(content.slice(start, stop))) habits.push({ line: lineAt(start), rule: "no-new-suppression" }); + const publicApiDoc = publicApiRoots.some((root) => file.startsWith(root)) && /^\s*export\s/.test(content.slice(stop)); + comments.push({ start, stop, line: lineAt(start), endLine: lineAt(stop - 1), allowed: isAllowedComment(content.slice(start, stop), header, publicApiDoc) }); previousEnd = stop; } - return { file, effects, comments }; + return { file, effects, comments, habits }; } export function checkComments(scan, addedLines) { @@ -93,6 +131,11 @@ export function checkComments(scan, addedLines) { return findings; } +export function checkHabits(scan, addedLines) { + return scan.habits.filter((habit) => addedLines.has(habit.line)) + .map((habit) => ({ file: scan.file, line: habit.line, rule: habit.rule, message: habitMessages[habit.rule] })); +} + export function makeBaseline(scans) { return { version: 1, effects: Object.fromEntries(scans.filter((scan) => scan.effects.length > 0) .sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0).map((scan) => [scan.file, scan.effects.length])) }; @@ -135,7 +178,7 @@ export function addedLinesFromDiff(diff) { } function git(...args) { - return execFileSync("git", ["-c", "core.quotepath=false", ...args], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 32 * 1024 * 1024 }); + return execFileSync("git", ["-c", "core.quotepath=false", ...args], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 512 * 1024 * 1024 }); } async function files(directory) { const result = []; @@ -175,13 +218,22 @@ export async function main(args = process.argv.slice(2)) { console.log("Code habits: comment rule skipped; no base commit could be resolved (use --base or fetch origin/dev)."); } if (base) { - const added = addedLinesFromDiff(git("diff", "-U0", "--no-renames", base, "--", scope)); - const untracked = new Set(git("ls-files", "--others", "--exclude-standard", "-z", "--", scope).split("\0").filter(Boolean)); - for (const scan of scans) { - const lines = untracked.has(scan.file) - ? new Set(scan.comments.flatMap((comment) => Array.from({ length: comment.endLine - comment.line + 1 }, (_, index) => comment.line + index))) - : added.get(scan.file) ?? new Set(); - findings.push(...checkComments(scan, lines)); + const added = addedLinesFromDiff(git("diff", "-U0", "--no-renames", base, "--", ...commentRoots)); + const untracked = new Set(git("ls-files", "--others", "--exclude-standard", "-z", "--", ...commentRoots).split("\0").filter(Boolean)); + for (const file of [...new Set([...added.keys(), ...untracked])].sort()) { + if (!isCommentSource(file)) continue; + let content; + try { + content = await readFile(path.join(root, file), "utf8"); + } catch { + continue; + } + if (!isCommentSource(file, content)) continue; + const scan = scanSource(file, content); + const lines = untracked.has(file) + ? new Set(Array.from({ length: content.split("\n").length }, (_, index) => index + 1)) + : added.get(file) ?? new Set(); + findings.push(...checkComments(scan, lines), ...checkHabits(scan, lines)); } } findings.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line || a.rule.localeCompare(b.rule)); diff --git a/scripts/check-code-habits.test.mjs b/scripts/check-code-habits.test.mjs index 57cf408ca39..cab2b5103f7 100644 --- a/scripts/check-code-habits.test.mjs +++ b/scripts/check-code-habits.test.mjs @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { scanSource, checkComments, isAllowedComment, isSourceFile, makeBaseline, ratchet, addedLinesFromDiff } from "./check-code-habits.mjs"; +import { scanSource, checkComments, checkHabits, isAllowedComment, isCommentSource, isSourceFile, makeBaseline, ratchet, addedLinesFromDiff } from "./check-code-habits.mjs"; const file = "apps/app/src/example.tsx"; const scan = (content) => scanSource(file, content); @@ -100,6 +100,54 @@ test("skips tests, fixtures, stories and generated sources", () => { assert.equal(isSourceFile(`apps/app/src/${name}`), false, name); } assert.equal(isSourceFile(file, "// @generated\nconst value = 1;"), false); + assert.equal(isSourceFile(file, "// Generated by `pnpm features:sync`. Do not edit.\nconst value = 1;"), false); assert.equal(isSourceFile(file), true); assert.equal(isSourceFile("ee/apps/app/src/example.tsx"), false); }); + +test("comment rule covers TypeScript across apps, packages and ee, not declarations or tests", () => { + for (const name of ["apps/server/src/a.ts", "packages/sdk/src/a.mts", "ee/apps/den-web/app/page.tsx", "ee/packages/den-db/src/a.cts"]) { + assert.equal(isCommentSource(name), true, name); + } + for (const name of ["scripts/a.ts", "evals/a.ts", "packages/sdk/src/a.d.ts", "ee/apps/den-api/test/a.test.ts", "packages/sdk/src/gen/a.ts"]) { + assert.equal(isCommentSource(name), false, name); + } +}); + +test("keeps doc comments on exported package APIs only", () => { + const source = "/** The contract. */\nexport function value() {}\n/** Internal. */\nfunction other() {}"; + assert.deepEqual(scanSource("packages/sdk/src/a.ts", source).comments.map((comment) => comment.allowed), [true, false]); + assert.deepEqual(scanSource("ee/packages/den-db/src/a.ts", source).comments.map((comment) => comment.allowed), [true, false]); + assert.deepEqual(scanSource("apps/server/src/a.ts", source).comments.map((comment) => comment.allowed), [false, false]); + assert.equal(scanSource("packages/sdk/src/a.ts", "// The contract.\nexport function value() {}").comments[0].allowed, false); +}); + +test("keeps issue and RFC links, not other links", () => { + for (const text of ["// Safari drops the header: https://bugs.webkit.org/show_bug.cgi?id=1", "// https://github.com/owner/repo/issues/42", "/* See https://www.rfc-editor.org/rfc/rfc6749#section-4.1 */", "// https://datatracker.ietf.org/doc/html/rfc7636"]) { + assert.equal(isAllowedComment(text), true, text); + } + assert.equal(isAllowedComment("// see https://example.com/docs"), false); + assert.equal(isAllowedComment("// see https://github.com/owner/repo/blob/main/a.ts"), false); +}); + +const habitRules = (source, name = file) => checkHabits(scanSource(name, source), new Set(source.split("\n").map((_, index) => index + 1))).map((finding) => finding.rule); + +test("flags any, casts, non-null assertions, suppressions and console.log on added lines", () => { + assert.deepEqual(habitRules("let a: any;"), ["no-new-any"]); + assert.deepEqual(habitRules("const a = b as string;\nconst c = d;"), ["no-new-cast"]); + assert.deepEqual(habitRules("const a = b!.c;"), ["no-new-non-null"]); + assert.deepEqual(habitRules("// @ts-expect-error broken\nconst a = 1;\n/* eslint-disable no-console */\n// biome-ignore lint: x\n// @ts-ignore"), ["no-new-suppression", "no-new-suppression", "no-new-suppression", "no-new-suppression"]); + assert.deepEqual(habitRules('console.log("x");'), ["no-new-console-log"]); +}); + +test("allows as const, satisfies, console.error, prettier-ignore and console.log in command-line entry points", () => { + assert.deepEqual(habitRules('const a = ["x"] as const;\nconst b = { a } satisfies object;\nconsole.error("x");\n// prettier-ignore\nconst c = 1;'), []); + assert.deepEqual(habitRules('#!/usr/bin/env node\nconsole.log("x");', "packages/world/src/main.ts"), []); + assert.deepEqual(habitRules('console.log("x");', "packages/world/src/cli.ts"), []); + assert.deepEqual(habitRules('console.log("x");', "packages/world/src/cli/run.ts"), []); +}); + +test("habits only fail on added lines", () => { + const scan = scanSource(file, "let a: any;\nlet b: any;"); + assert.deepEqual(checkHabits(scan, new Set([2])).map((finding) => finding.line), [2]); +}); diff --git a/scripts/check-prose-habits.mjs b/scripts/check-prose-habits.mjs new file mode 100644 index 00000000000..1eadd75c84f --- /dev/null +++ b/scripts/check-prose-habits.mjs @@ -0,0 +1,150 @@ +import { execFileSync } from "node:child_process"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { addedLinesFromDiff } from "./check-code-habits.mjs"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const skipped = /(?:^|\/)(?:node_modules|dist|build|vendor|fixtures|__fixtures__)\/|(?:^|\/)CHANGELOG\.md$/; + +export const rules = [ + { + rule: "no-dash", + test: (line) => /[–—]|\S\s+-{1,2}\s+\S/.test(line + .replace(/^\s*(?:[-*+]|\d+\.)\s+/, "") + .replace(/^\s*\|.*\|\s*$/, (row) => row.replace(/\|\s*:?-+:?\s*(?=\|)/g, "|").replace(/\|\s*[–—-]\s*(?=\|)/g, "|")) + .replace(/(\d)–(?=\d)/g, "$1")), + message: "No em dashes, en dashes or hyphens used as dashes. Use a period or a comma.", + }, + { + rule: "no-ai-vocabulary", + test: (line) => /\b(?:additionally|crucial|delve[sd]?|delving|enhanc(?:e|es|ed|ing)|foster(?:s|ed|ing)?|pivotal|showcas(?:e|es|ed|ing)|testament|vibrant|seamless(?:ly)?|robust)\b/i.test(line), + message: "No AI vocabulary (additionally, crucial, delve, enhance, foster, pivotal, showcase, testament, vibrant, seamless, robust). Say the plain fact.", + }, + { + rule: "no-serves-as", + test: (line) => /\b(?:serves?|serving|stands?) as\b|\bboasts?\b/i.test(line), + message: "Say \"is\" or \"has\", not \"serves as\", \"stands as\" or \"boasts\".", + }, + { + rule: "no-not-just", + test: (line) => /\bnot (?:just|only|merely)\b[^.]{1,120}\bbut\b/i.test(line), + message: "No \"not just X, but Y\". State the point.", + }, + { + rule: "no-chatbot-phrase", + test: (line) => /\b(?:I hope this helps|great question|let me know if|feel free to|happy to help|as an AI)\b|\bcertainly!/i.test(line), + message: "No chatbot phrases. Docs are read later, not replied to.", + }, + { + rule: "no-wordy-phrase", + test: (line) => /\bin order to\b|\butili[sz](?:e|es|ed|ing|ation)\b|\bleverag(?:e|es|ed|ing)\b/i.test(line), + message: "Use \"to\" for \"in order to\" and \"use\" for \"utilize\" or \"leverage\".", + }, + { + rule: "no-curly-quotes", + test: (line) => /[‘’“”]/.test(line), + message: "Use straight quotes (' and \"), not curly ones.", + }, + { + rule: "no-filler-word", + test: (line) => /\b(?:simply|easy|easily|please)\b|\betc\./i.test(line), + message: "Cut \"simply\", \"easy\", \"please\" and \"etc.\". Say what to do, or list every item.", + }, +]; + +export function proseLines(content) { + const lines = content.split("\n"); + const result = []; + let fence; + let comment = false; + lines.forEach((raw, index) => { + const fenceMatch = raw.match(/^\s*(`{3,}|~{3,})/); + if (fence) { + if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length) fence = undefined; + return; + } + if (fenceMatch) { + fence = fenceMatch[1]; + return; + } + if (/^(?: {4}|\t)/.test(raw) && (index === 0 || lines[index - 1].trim() === "" || /^(?: {4}|\t)/.test(lines[index - 1])) + && !/^\s*(?:[-*+]|\d+\.)\s/.test(raw)) return; + let line = raw; + if (comment || line.includes(""); + if (comment && end === -1) return; + line = comment ? line.slice(end + 3) : line; + comment = false; + line = line.replace(//g, ""); + const open = line.indexOf("\n\n simply indented code\n"; + assert.deepEqual(rulesFor(content), []); + assert.deepEqual(proseLines("a\n```\nb\n```\nc").map((line) => line.line), [1, 5]); +}); + +test("only fails on added lines", () => { + assert.deepEqual(checkProse("docs/a.md", "Simply one.\nSimply two.", new Set([2])).map((finding) => finding.line), [2]); +}); + +test("checks markdown outside dependencies and changelogs", () => { + assert.equal(isProseFile("docs/features/a/README.md"), true); + assert.equal(isProseFile("AGENTS.md"), true); + assert.equal(isProseFile("node_modules/x/README.md"), false); + assert.equal(isProseFile("apps/desktop/CHANGELOG.md"), false); + assert.equal(isProseFile("docs/a.ts"), false); +}); diff --git a/scripts/check.mjs b/scripts/check.mjs index 25c278dca8c..2992c8536fe 100644 --- a/scripts/check.mjs +++ b/scripts/check.mjs @@ -67,7 +67,12 @@ export const CHECKS = [ { name: "code-habits", command: ["node", "scripts/check-code-habits.mjs"], - fix: "Remove the comment or the effect as the message says. Do not add it to the baseline.", + fix: "Remove the comment, effect, any, cast, non-null assertion, suppression or console.log as the message says. Do not add it to the baseline.", + }, + { + name: "prose-habits", + command: ["node", "scripts/check-prose-habits.mjs"], + fix: "Rewrite the flagged markdown line as the message says. Code blocks and inline code are not checked.", }, { name: "spec-lint", diff --git a/scripts/check.test.mjs b/scripts/check.test.mjs index b5f5827958e..94fb04d82c9 100644 --- a/scripts/check.test.mjs +++ b/scripts/check.test.mjs @@ -25,6 +25,7 @@ test("the checks CI requires are the commands pnpm check runs", () => { "node scripts/check-app-structure.mjs", "node scripts/check-package-names.mjs", "node scripts/check-code-habits.mjs", + "node scripts/check-prose-habits.mjs", ]) { assert.ok(workflow.includes(command), `quick-check.yml no longer runs: ${command}`); assert.ok(CHECKS.some((check) => check.command.join(" ") === command), `pnpm check does not run: ${command}`);