chore: delegate llm tasks to static analysis tools. Remind robots they have a role to play too

This commit is contained in:
Stuart Anderson
2026-09-23 12:55:46 -05:00
parent a6deb1c1d1
commit 9d391bfa62
18 changed files with 485 additions and 5 deletions

View File

@@ -91,6 +91,12 @@ undo a behaviour the maintainer asked for is a decline, with that intent as the
reason. Repo rules are a valid source: Greptile enforces the comment discipline
from `CLAUDE.md` and `review-polish`, and those findings stand.
For every valid finding, ask whether a static check could have caught it. If it
is pattern-shaped (a banned import, character, CSS value, or SFC shape), add or
enable the ESLint rule in the fix commit (`frontend/eslint-plugin-romm/` for
custom rules, with a `RuleTester` test), or name the rule as a follow-up in the
reply. A bot catching the same thing twice is a missing rule.
Suggestion blocks are a starting point, not a patch to apply blindly. Check they
are complete and not duplicating a call a neighbouring branch already makes.

View File

@@ -45,7 +45,7 @@ If any fails: **shared composite** if generic across features, **feature composi
### Primitive boundaries
- **Can use**: tokens, other primitives, Vue, generic composables (`useInput*`, `useFocus*`).
- **Cannot use**: Pinia stores, API services, `emitter`, `router` (a `RouterLink` may be accepted as a prop), `i18n` directly. **No `$t()` in primitives** — text comes via props or slots.
- **Cannot use**: Pinia stores, API services, `emitter`, `router` (a `RouterLink` may be accepted as a prop), `i18n` directly. **No `$t()` in primitives** — text comes via props or slots. ESLint's `@typescript-eslint/no-restricted-imports` block for `src/v2/lib` enforces the import side. Domain knowledge that is not an import (a hardcoded `/assets/...` path, domain-named props) still needs review.
- **Chrome labels** are the exception to "via props": the accessible name
of a control the primitive renders for itself (a dialog's close button, a
chip's remove X, a date field's steppers, a stepper's "Step 2 of 5") is
@@ -72,6 +72,7 @@ If any fails: **shared composite** if generic across features, **feature composi
- `defineOptions({ inheritAttrs: false })` on every wrapper, paired with `v-bind="$attrs"` and slot passthrough (without the bind, attrs vanish silently).
- Props via `defineProps<Props>()` (interface), never runtime declarations. Emits via `defineEmits<{...}>()`. Slots with payload via `defineSlots<{}>()`.
- Order: `<script setup>` → `<template>` → `<style scoped>`. Unscoped `<style>` (teleport overrides only) goes after the scoped block.
- ESLint enforces `lang="ts"`, `<script setup>`, block order, and type-based `defineProps`/`defineEmits` on `src/v2/**/*.vue`.
### Import order & aliases

View File

@@ -49,7 +49,7 @@ When a dialog opens, push a scope; when it closes, pop. This stops Escape from c
## Responsive layout (universal viewport)
- **Single breakpoint source: `useBreakpoint`** (`src/v2/composables/useBreakpoint/`). Material thresholds: `xs <600`, `sm 600–959`, `md 960–1279`, `lg 1280–1919`, `xl ≥1920`. `installBreakpointAttribute()` mirrors the active set onto `<html data-bp="…">` (from `AppLayout` and `AuthLayout` in the app, and from `.storybook/preview.ts` so stories match production CSS).
- **Layout switches live in CSS** via the attribute selector: `html[data-bp~="xs"] .foo { … }`, `html[data-bp~="sm-and-down"] .foo { … }`. **No raw `@media` for layout** — the only allowed `@media` are `prefers-reduced-motion` and print. The attribute is on `<html>` so it reaches teleported overlays.
- **Layout switches live in CSS** via the attribute selector: `html[data-bp~="xs"] .foo { … }`, `html[data-bp~="sm-and-down"] .foo { … }`. **No raw `@media` for layout** — the only allowed `@media` are `prefers-reduced-motion` and print. The attribute is on `<html>` so it reaches teleported overlays. `romm/no-layout-media-query` (ESLint) enforces this in SFC styles.
- **Conditional rendering** (mount/unmount a different component per tier) uses the `useBreakpoint()` refs in `<script>` — e.g. `v-if="xs"`. Prefer mount-gating over `display:none` for focusable chrome so hidden controls never sit in the tab/spatial-nav order.
- **`--r-row-pad` is the global horizontal gutter**, already re-scoped responsive in `global.css` (36 → 20 → 14px). Consume `var(--r-row-pad)`; don't hard-code a smaller `xs` padding per component.
- **Touch targets** scale with the breakpoint, never with `data-input`: `--r-touch-target` (44px) at `sm-and-down`, less only where the row would not fit.

View File

@@ -69,6 +69,8 @@ Outside `src/v2/tokens/index.ts` (the source-of-truth TS module) and the generat
If a literal would otherwise be needed, the answer is: **add a token** (steps above), then consume via `var(--r-color-...)` or the named export.
`romm/no-color-literal` (ESLint, `frontend/eslint-plugin-romm/`) flags hex and color-function literals in SFC `<style>` blocks under `src/v2`. It does not see `.css` files, stories' inline styles, or colors in TS strings.
## Style conventions
- Scoped `<style>` by default; unscoped only for teleport overrides.

View File

@@ -145,6 +145,12 @@ Run from `frontend/`:
1. `npm run typecheck`: zero errors (`vue-tsc --noEmit`).
2. `npm run typecheck:scripts`: zero errors (`tsc -p tsconfig.node.json`, covers `scripts/`).
3. `npm run lint` _(if present)_ / ESLint clean. Trunk also runs ESLint + Prettier in CI.
If polish turned up a mechanical pattern (you fixed the same kind of thing
twice), encode it instead of relying on the next reviewer: enable a stock
rule in `eslint.config.js`, or add `frontend/eslint-plugin-romm/rules/<name>.js`
plus `<name>.test.ts` (`RuleTester`, valid and invalid cases), register it in
the plugin's `index.js`, and turn it on in `eslint.config.js`. Test with
`npx vitest run eslint-plugin-romm` and `npm run typecheck:scripts`.
4. `npm run test`: zero failures (Vitest + happy-dom; runs unit tests **and** every `/lib` story's `play()` via `composeStories`).
5. `npm run build`: zero failures (CI sanity check).

View File

@@ -66,7 +66,8 @@ These live in `.claude/skills/` and carry the detailed rules. Invoke the one tha
**Tests travel with code.** New logic gets a test; new endpoints get endpoint tests; new v2 primitives get a Storybook story (+ `play()` if interactive).
**Verify before handoff.** Don't say "done" on UI work without testing it in the browser in both themes and all input modalities. See `review-polish`.
**English first.** Outside of language files, all code, comments, identifiers, `.md` files, and commit/PR messages are in English.
**No em-dashes.** Never use em-dashes (—) when writing comments or text. Use commas, parentheses, or separate sentences instead.
**No em-dashes.** Never use em-dashes (—) when writing comments or text. Use commas, parentheses, or separate sentences instead. ESLint (`romm/no-em-dash`) enforces this under `frontend/src/v2`.
**Write the check, don't delegate it to a model.** When a rule is mechanical (an import, a character, a CSS pattern, an SFC shape), it belongs in ESLint, `tsconfig`, or a CI script, not in a skill an LLM reviewer re-reads on every PR. Agents own this: when you hit or fix a repeatable review finding, turn on a stock rule or add one to `frontend/eslint-plugin-romm/` with a `RuleTester` test, in the same PR or as a named follow-up. Encode the rule that finds violations; fixing existing violations is separate work. Keep model review for judgment calls.
**Keep comments short.** Comments should be concise, and focus on the "why" rather than the "what" (the code itself is the "what"). A comment is one or two lines; a docstring is one sentence plus `Args:`/`Returns:` when the signature needs it. Three or more lines of prose means you are explaining, not commenting. See `review-polish` for what to cut.
**Don't restate the code.** The code is self-documenting, so skip comments that narrate what a reader can already see (which button sits where, that something is disabled when empty, obvious ordering). Comment only non-obvious "why" that the code can't convey on its own.
**One home per value.** Before declaring a constant, type, limit, regex, or store getter, search for an existing one and import it. Validation limits live on the model and are imported by endpoints; a type lives in the component that owns it and is exported. Don't add a near-duplicate that differs only by sorting, and don't invent an identity scheme where a foreign key already exists.

View File

@@ -0,0 +1,14 @@
// @ts-check
import noColorLiteral from "./rules/no-color-literal.js";
import noEmDash from "./rules/no-em-dash.js";
import noLayoutMediaQuery from "./rules/no-layout-media-query.js";
/** @type {import("eslint").ESLint.Plugin} */
export default {
meta: { name: "eslint-plugin-romm" },
rules: {
"no-color-literal": noColorLiteral,
"no-em-dash": noEmDash,
"no-layout-media-query": noLayoutMediaQuery,
},
};

View File

@@ -0,0 +1,53 @@
// @ts-check
import { sfcStyleBlocks } from "../utils/sfcStyles.js";
// A declaration starts right after `{` or `;`, so selectors like
// `.a:not(#abc)` are never read as values.
const DECLARATION = /(?<=[{;]\s*)(--[\w-]+|[a-z-]+)\s*:([^;{}]*)/gi;
const URL_CALL = /url\([^)]*\)/gi;
const COLOR_LITERAL =
/#[0-9a-f]{3,8}\b|\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\(/gi;
/** @type {import("eslint").Rule.RuleModule} */
export default {
meta: {
type: "problem",
docs: {
description:
"Disallow hex and color-function literals in SFC styles; use a --r-color-* token or color-mix().",
},
schema: [],
messages: {
colorLiteral:
"Color literal `{{literal}}`: use a `var(--r-color-*)` token, or `color-mix()` over a token or named color. Add a token in src/v2/tokens/index.ts if none fits.",
},
},
create(context) {
return {
Program() {
const { sourceCode } = context;
for (const block of sfcStyleBlocks(context)) {
for (const decl of block.text.matchAll(DECLARATION)) {
const value = decl[2];
const valueStart =
block.start + (decl.index ?? 0) + decl[0].length - value.length;
const scanned = value.replace(URL_CALL, (u) =>
" ".repeat(u.length),
);
for (const hit of scanned.matchAll(COLOR_LITERAL)) {
const index = valueStart + (hit.index ?? 0);
context.report({
loc: {
start: sourceCode.getLocFromIndex(index),
end: sourceCode.getLocFromIndex(index + hit[0].length),
},
messageId: "colorLiteral",
data: { literal: hit[0] },
});
}
}
}
},
};
},
};

View File

@@ -0,0 +1,72 @@
import rule from "./no-color-literal.js";
import { ruleTester, sfc } from "./testing";
const error = (literal: string) => ({
messageId: "colorLiteral",
data: { literal },
});
ruleTester.run("no-color-literal", rule, {
valid: [
{ code: sfc(".a { color: var(--r-color-fg); }"), filename: "A.vue" },
{
code: sfc(
".a { box-shadow: 0 1px 2px color-mix(in srgb, black 40%, transparent); }",
),
filename: "A.vue",
},
{
code: sfc(
".a { background: color-mix(in srgb, var(--r-color-bg) 60%, transparent); }",
),
filename: "A.vue",
},
{ code: sfc(".a:not(#abc) { color: currentColor; }"), filename: "A.vue" },
{ code: sfc("#fade { fill: url(#fade); }"), filename: "A.vue" },
{ code: sfc("/* was #fff */\n.a { color: white; }"), filename: "A.vue" },
{ code: 'const fill = "#ffffff";' },
{
code: '<script setup lang="ts">const c = "rgba(0,0,0,.5)";</script>\n<template><div /></template>\n',
filename: "A.vue",
},
],
invalid: [
{
code: sfc(".a { color: #fff; }"),
filename: "A.vue",
errors: [error("#fff")],
},
{
code: sfc(".a { --r-color-fg: #ffffff; }"),
filename: "A.vue",
errors: [error("#ffffff")],
},
{
code: sfc(".a { text-shadow: 0 1px 3px rgba(0, 0, 0, 0.7); }"),
filename: "A.vue",
errors: [error("rgba(")],
},
{
code: sfc(
".a { color: hsl(0 0% 100%); border-color: oklch(70% 0.1 200); }",
),
filename: "A.vue",
errors: [error("hsl("), error("oklch(")],
},
{
code: sfc(".a { background: linear-gradient(#000, #111); }"),
filename: "A.vue",
errors: [error("#000"), error("#111")],
},
{
code: sfc(".a {\n color: #abc;\n}"),
filename: "A.vue",
errors: [{ ...error("#abc"), line: 5, column: 10 }],
},
{
code: `${sfc(".a { color: var(--r-color-fg); }")}<style>\n.b { color: #123456; }\n</style>\n`,
filename: "A.vue",
errors: [error("#123456")],
},
],
});

View File

@@ -0,0 +1,34 @@
// @ts-check
/** @type {import("eslint").Rule.RuleModule} */
export default {
meta: {
type: "problem",
docs: {
description:
"Disallow the em dash (U+2014) in source, comments, and templates.",
},
schema: [],
messages: {
emDash:
"Replace the em dash with a comma, parentheses, or a separate sentence.",
},
},
create(context) {
return {
Program() {
const { sourceCode } = context;
for (const match of sourceCode.text.matchAll(/\u2014/g)) {
const index = match.index ?? 0;
context.report({
loc: {
start: sourceCode.getLocFromIndex(index),
end: sourceCode.getLocFromIndex(index + 1),
},
messageId: "emDash",
});
}
},
};
},
};

View File

@@ -0,0 +1,30 @@
import rule from "./no-em-dash.js";
import { ruleTester, sfc } from "./testing";
const error = { messageId: "emDash" };
ruleTester.run("no-em-dash", rule, {
valid: [
{ code: "// A comma, then (parentheses) - and a hyphen.\nconst a = 1;" },
{ code: 'const range = "1\u20134";' },
{ code: sfc(".a { color: var(--r-color-fg); }"), filename: "A.vue" },
],
invalid: [
{ code: "// Loads icons \u2014 slowly.\nconst a = 1;", errors: [error] },
{ code: 'const empty = "\u2014";', errors: [error] },
{
code: "/** One \u2014 two \u2014 three. */\nexport const x = 1;",
errors: [error, error],
},
{
code: '<script setup lang="ts"></script>\n<template><p>Save \u2014 now</p></template>\n',
filename: "A.vue",
errors: [{ ...error, line: 2 }],
},
{
code: sfc("/* Glass \u2014 dark */\n.a { color: var(--r-color-fg); }"),
filename: "A.vue",
errors: [{ ...error, line: 4 }],
},
],
});

View File

@@ -0,0 +1,45 @@
// @ts-check
import { sfcStyleBlocks } from "../utils/sfcStyles.js";
const MEDIA_RULE = /@media\b([^{;]*)/gi;
// Whatever is left after removing these is a condition the rule rejects.
const ALLOWED_PARTS =
/\(\s*prefers-reduced-motion\b[^)]*\)|\b(?:print|screen|all|only|not|and)\b|[\s,]/gi;
/** @type {import("eslint").Rule.RuleModule} */
export default {
meta: {
type: "problem",
docs: {
description:
"Disallow @media in SFC styles except prefers-reduced-motion and print; layout switches use html[data-bp~=...].",
},
schema: [],
messages: {
layoutMedia:
'Use `html[data-bp~="..."]` selectors (useBreakpoint) for layout. Only `prefers-reduced-motion` and `print` media queries are allowed.',
},
},
create(context) {
return {
Program() {
const { sourceCode } = context;
for (const block of sfcStyleBlocks(context)) {
for (const rule of block.text.matchAll(MEDIA_RULE)) {
if (rule[1].replace(ALLOWED_PARTS, "") === "") continue;
const index = block.start + (rule.index ?? 0);
context.report({
loc: {
start: sourceCode.getLocFromIndex(index),
end: sourceCode.getLocFromIndex(
index + rule[0].trimEnd().length,
),
},
messageId: "layoutMedia",
});
}
}
},
};
},
};

View File

@@ -0,0 +1,60 @@
import rule from "./no-layout-media-query.js";
import { ruleTester, sfc } from "./testing";
const error = { messageId: "layoutMedia" };
ruleTester.run("no-layout-media-query", rule, {
valid: [
{
code: sfc(
"@media (prefers-reduced-motion: reduce) { .a { transition: none; } }",
),
filename: "A.vue",
},
{ code: sfc("@media print { .a { display: none; } }"), filename: "A.vue" },
{
code: sfc(
"@media not print and (prefers-reduced-motion: no-preference) { .a { opacity: 1; } }",
),
filename: "A.vue",
},
{
code: sfc('html[data-bp~="xs"] .a { display: none; }'),
filename: "A.vue",
},
{
code: sfc("/* @media (max-width: 600px) */\n.a { color: red; }"),
filename: "A.vue",
},
{ code: 'const q = "@media (max-width: 600px)";' },
],
invalid: [
{
code: sfc("@media (max-width: 600px) { .a { display: none; } }"),
filename: "A.vue",
errors: [{ ...error, line: 4, column: 1 }],
},
{
code: sfc("@media screen and (min-width: 960px) { .a { gap: 0; } }"),
filename: "A.vue",
errors: [error],
},
{
code: sfc(
"@media (prefers-reduced-motion: reduce), (width < 600px) { .a { gap: 0; } }",
),
filename: "A.vue",
errors: [error],
},
{
code: sfc("@media (hover: hover) { .a:hover { opacity: 1; } }"),
filename: "A.vue",
errors: [error],
},
{
code: sfc(".a { @media (max-width: 600px) { gap: 0; } }"),
filename: "A.vue",
errors: [error],
},
],
});

View File

@@ -0,0 +1,22 @@
import type { Linter } from "eslint";
import { RuleTester } from "eslint";
import vue from "eslint-plugin-vue";
const vueParser = vue.configs["flat/base"]
.map((config: Linter.Config) => config.languageOptions?.parser)
.find(Boolean);
if (!vueParser)
throw new Error("eslint-plugin-vue no longer exposes its parser");
export const ruleTester = new RuleTester({
languageOptions: {
parser: vueParser,
ecmaVersion: 2022,
sourceType: "module",
},
});
export function sfc(style: string, lang = ""): string {
return `<script setup lang="ts"></script>\n<template><div /></template>\n<style scoped${lang}>\n${style}\n</style>\n`;
}

View File

@@ -0,0 +1,44 @@
// @ts-check
/**
* @typedef {{ text: string, start: number }} StyleBlock
* @typedef {{ type: string, name?: string, range: [number, number], children?: SfcNode[] }} SfcNode
*/
/**
* The `<style>` blocks of a Vue SFC, with comments blanked out so offsets
* still map to the source. Empty for files that are not SFCs.
* @param {import("eslint").Rule.RuleContext} context
* @returns {StyleBlock[]}
*/
export function sfcStyleBlocks(context) {
const { sourceCode } = context;
const services =
/** @type {{ getDocumentFragment?: () => SfcNode | null }} */ (
sourceCode.parserServices ?? {}
);
const fragment = services.getDocumentFragment?.();
if (!fragment?.children) return [];
/** @type {StyleBlock[]} */
const blocks = [];
for (const node of fragment.children) {
if (node.type !== "VElement" || node.name !== "style") continue;
const body = node.children?.[0];
if (!body) continue;
const [start, end] = body.range;
blocks.push({
text: blankComments(sourceCode.text.slice(start, end)),
start,
});
}
return blocks;
}
/**
* Replace CSS comments with spaces of the same length.
* @param {string} css
*/
function blankComments(css) {
return css.replace(/\/\*[\s\S]*?\*\//g, (c) => c.replace(/[^\n]/g, " "));
}

View File

@@ -6,6 +6,7 @@ import vue from "eslint-plugin-vue";
import vuea11y from "eslint-plugin-vuejs-accessibility";
import globals from "globals";
import tseslint from "typescript-eslint";
import romm from "./eslint-plugin-romm/index.js";
export default tseslint.config(
eslint.configs.recommended,
@@ -57,6 +58,8 @@ export default tseslint.config(
"*.local",
"*.config.js",
"src/plugins/*.d.ts",
// Typechecked by tsconfig.node.json, outside the app project service.
"eslint-plugin-romm/**",
],
languageOptions: {
parserOptions: {
@@ -119,6 +122,83 @@ export default tseslint.config(
files: ["src/console/**"],
rules: { "import-x/no-cycle": "off" },
},
// v2 primitives: no stores, services, i18n, emitter, or product domain.
{
files: ["src/v2/lib/**/*.ts", "src/v2/lib/**/*.vue"],
ignores: ["**/*.stories.ts", "**/*.test.ts"],
rules: {
"@typescript-eslint/no-restricted-imports": [
"error",
{
paths: [
{ name: "pinia", message: "Primitives take state via props." },
{
name: "vue-i18n",
message:
"Primitives take text via props, slots, or useChromeLabels().",
},
{ name: "axios", message: "Primitives do not fetch." },
{
name: "vue-router",
importNames: ["useRouter", "useRoute"],
message: "Primitives accept a RouterLink `to`, not the router.",
},
],
patterns: [
{
group: [
"@/services/*",
"@/services/**",
"@/stores/*",
"@/stores/**",
],
message:
"Primitives do not use services or stores; move this to a shared or feature composite.",
},
{
group: ["@/__generated__", "@/__generated__/**"],
message:
"Backend types are product domain; primitives take generic props.",
},
{
group: ["@/types/emitter"],
message: "Primitives do not use the emitter.",
},
{
group: [
"@/v2/components/**",
"@/v2/composables/usePlatformIconCache",
"@/v2/composables/usePlatformIconCache/**",
],
message:
"Primitives cannot depend on composites or domain composables.",
},
],
},
],
},
},
// v2 SFC shape, from the frontend-v2-components skill.
{
files: ["src/v2/**/*.vue"],
rules: {
"vue/block-lang": ["error", { script: { lang: "ts" } }],
"vue/component-api-style": ["error", ["script-setup"]],
"vue/block-order": ["error", { order: ["script", "template", "style"] }],
"vue/define-props-declaration": ["error", "type-based"],
"vue/define-emits-declaration": ["error", "type-based"],
},
},
// Repo rules without a stock equivalent live in ./eslint-plugin-romm.
{
files: ["src/v2/**/*.ts", "src/v2/**/*.vue"],
plugins: { romm },
rules: {
"romm/no-em-dash": "error",
"romm/no-color-literal": "error",
"romm/no-layout-media-query": "error",
},
},
// Keep last: Prettier owns formatting, so this switches off every
// stylistic rule the two tools would otherwise fight over.
prettierConfig,

View File

@@ -6,7 +6,13 @@
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"allowJs": true,
"checkJs": true,
"types": ["node"]
},
"include": ["scripts/**/*.ts"]
"include": [
"scripts/**/*.ts",
"eslint-plugin-romm/**/*.js",
"eslint-plugin-romm/**/*.ts"
]
}

View File

@@ -15,7 +15,11 @@ export default defineConfig({
environment: "happy-dom",
globals: true,
setupFiles: ["./vitest.setup.ts"],
include: ["src/**/*.{test,spec}.ts", "test/**/*.{test,spec}.ts"],
include: [
"src/**/*.{test,spec}.ts",
"test/**/*.{test,spec}.ts",
"eslint-plugin-romm/**/*.test.ts",
],
server: {
deps: {
inline: ["vuetify"],