Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions .github/workflows/quick-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions apps/app/src/react-app/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
86 changes: 69 additions & 17 deletions scripts/check-code-habits.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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|<reference\b|@vite-ignore\b|webpack[A-Z]\w*\s*:|(?:v8|istanbul|c8) ignore\b|@vitest-environment\b|@jsxImportSource\b|@jsx\b|@ts-check\b|#?region\b|#?endregion\b|@refresh\b|[@#]__(?:PURE|NO_SIDE_EFFECTS|INLINE|NOINLINE)__)/.test(body)
|| /^\/\*[!]|@license\b|@preserve\b/.test(text)
|| (header && /\b(?:copyright|license|SPDX-License-Identifier)\b/i.test(body))
|| (publicApiDoc && text.startsWith("/**"))
|| issueOrRfcLink.test(body);
}

export function isSuppression(text) {
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|<reference\b|@vite-ignore\b|webpack[A-Z]\w*\s*:|(?:v8|istanbul) ignore\b|@vitest-environment\b|@jsxImportSource\b)/.test(body)
|| (header && /\b(?:copyright|license|SPDX-License-Identifier)\b/i.test(body));
return /^(?:@ts-(?:expect-error|ignore|nocheck)\b|eslint-disable\S*|biome-ignore\b)/.test(body);
}

export function isCommandLine(file, content) {
return content.startsWith("#!") || /(?:^|\/)(?:cli|bin)(?:\/|\.[cm]?tsx?$)/.test(file);
}

export function scanSource(file, content) {
const source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
const protectedRanges = [];
const effects = [];
const habits = [];
const commandLine = isCommandLine(file, content);
const effectNames = new Set(["useEffect", "useLayoutEffect"]);
const reactNames = new Set(["React"]);
for (const node of source.statements) {
Expand All @@ -46,6 +75,13 @@ export function scanSource(file, content) {
|| node.kind === ts.SyntaxKind.RegularExpressionLiteral || node.kind === ts.SyntaxKind.JsxText) {
protectedRanges.push([node.getStart(source), node.end]);
}
const habit = (rule) => 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))
Expand Down Expand Up @@ -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) {
Expand All @@ -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])) };
Expand Down Expand Up @@ -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 = [];
Expand Down Expand Up @@ -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 <ref> 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));
Expand Down
50 changes: 49 additions & 1 deletion scripts/check-code-habits.test.mjs
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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 = <string>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]);
});
Loading
Loading