Skip to content

Rule cookbook

Rulecheck supports four matcher forms: literal text, regex text, forbidden path, and syntax. The first three recipes show the text and path forms, the middle recipes show how to control where a rule applies, and the syntax recipes select TypeScript, TSX and Rust syntax nodes. The code below comes from the same TypeScript files that CI runs. Copy a recipe into .rulecheck/rules/ and adapt its ID, paths, and fixtures.

From the repository root after building the CLI:

Terminal window
bash docs/examples/run.sh # all recipes
bash docs/examples/run.sh path-globs # one recipe
bash docs/examples/run.sh syntax # the TypeScript/TSX comment selector
bash docs/examples/run.sh syntax-rust # the same selector over Rust

Ban an exact spelling. This is a case-sensitive substring check, not a parser: legacy_mode=true is different from legacy_mode = true. Use a regex if spacing should not matter.

literal.rule.ts
import { defineRule } from "@rulecheck/sdk";
export default defineRule({
id: "config/no-legacy-spelling",
kind: "text",
paths: ["config/*.toml"],
pattern: { kind: "literal", value: "legacy_mode = true" },
remediation: "Remove the legacy setting or set it to false.",
fixtures: [
{ path: "config/app.toml", content: "legacy_mode = false\n", expect: null },
{ path: "config/app.toml", content: "# settings\nlegacy_mode = true\n", expect: { line: 2, column: 1 } },
],
});

Match a line even when spacing varies. This example accepts optional whitespace and trailing comments when looking for debug=true. Rust regex syntax applies; use inline flags such as (?m) instead of JavaScript regex literals.

regex.rule.ts
import { defineRule } from "@rulecheck/sdk";
export default defineRule({
id: "config/no-debug-true",
kind: "text",
paths: ["config/*.toml"],
pattern: { kind: "regex", value: "(?m)^[ \\t]*debug[ \\t]*=[ \\t]*true[ \\t]*(?:#.*)?$" },
remediation: "Set debug to false before committing.",
fixtures: [
{ path: "config/app.toml", content: "debug = false\n", expect: null },
{ path: "config/app.toml", content: "debug=true # temporary\n", expect: { line: 1, column: 1 } },
],
});

Stop a local-only path from entering Git. No pattern or fixture content is needed. A finding is always reported at line 1, column 1. No matching tracked regular file is a pass.

path.rule.ts
import { defineRule } from "@rulecheck/sdk";
export default defineRule({
id: "config/no-local-overrides",
kind: "forbidden-path",
paths: ["config/*.override.toml"],
remediation: "Move the local override outside the tracked checkout.",
fixtures: [
{ path: "config/app.toml", expect: null },
{ path: "config/local.override.toml", expect: { line: 1, column: 1 } },
],
});

The same marker appears in source and generated files, but only src/ is in scope. For text rules, at least one tracked file must be in scope or the check cannot judge.

scope.rule.ts
import { defineRule } from "@rulecheck/sdk";
export default defineRule({
id: "source/no-legacy-marker",
kind: "text",
paths: ["src/**/*.ts"],
pattern: { kind: "literal", value: "legacyMarker" },
remediation: "Replace the legacy marker in source.",
fixtures: [
{ path: "src/app.ts", content: "legacyMarker();\n", expect: { line: 1, column: 1 } },
{ path: "src/app.ts", content: "currentMarker();\n", expect: null },
{ path: "generated/app.ts", content: "legacyMarker();\n", expect: null },
],
});

Use exclude to drop files from a broad scope. A file is checked when it matches paths and nothing in exclude. Fixtures use the same scope, so add a fixture for each excluded area. Both lists are case-sensitive, which means src/Generated/ is still in scope here. If a scope such as **/*.ts would also cover the rule sources, add .rulecheck/** to exclude, as the next recipe shows.

exclude.rule.ts
import { defineRule } from "@rulecheck/sdk";
export default defineRule({
id: "source/no-console-log",
kind: "text",
paths: ["src/**/*.ts"],
exclude: ["src/generated/**", "src/**/*.test.ts"],
pattern: { kind: "literal", value: "console.log(" },
remediation: "Use the project logger instead of console.log.",
fixtures: [
{ path: "src/app.ts", content: "console.log(user);\n", expect: { line: 1, column: 1 } },
{ path: "src/generated/client.ts", content: "console.log(user);\n", expect: null },
{ path: "src/app.test.ts", content: "console.log(user);\n", expect: null },
{ path: "src/Generated/client.ts", content: "console.log(user);\n", expect: { line: 1, column: 1 } },
],
});

In v1, rule sources under .rulecheck/ are scan candidates like any other file, both in a working-tree check and with --commit. A rule’s own file contains its pattern and fixture text, so a broad scope such as **/*.ts reports the rule itself. Add exclude: [".rulecheck/**"] to such a rule. Omitting rule sources automatically is deferred to a later contract version.

rule-sources.rule.ts
import { defineRule } from "@rulecheck/sdk";
export default defineRule({
id: "source/no-debugger",
kind: "text",
paths: ["**/*.ts"],
exclude: [".rulecheck/**"],
pattern: { kind: "literal", value: "debugger;" },
remediation: "Remove the debugger statement.",
fixtures: [
{ path: "src/app.ts", content: "debugger;\n", expect: { line: 1, column: 1 } },
{ path: "scripts/release.ts", content: "debugger;\n", expect: { line: 1, column: 1 } },
{ path: ".rulecheck/rules/rule-sources.rule.ts", content: "debugger;\n", expect: null },
],
});

The runner checks this recipe both ways. With the exclude entry removed, the same policy reports the rule file at its first match, the pattern value, in both modes:

.rulecheck/rules/rule-sources.rule.ts:8:39: [source/no-debugger] Remove the debugger statement.

With the exclude entry, the same checkout is clean, and a debugger; in scripts/release.ts is still reported.

The entries in paths are alternatives. Here, both the core package and API service are checked; the web service is not. Each rule reports only its first match per file, so the second OLD_NAME on the same line adds no finding. Columns are one-based Unicode scalar positions, so the Greek letter before the match still counts as one column.

multi-scope.rule.ts
import { defineRule } from "@rulecheck/sdk";
const marker = "OLD_NAME";
export default defineRule({
id: "source/no-old-name",
kind: "text",
paths: ["packages/core/**/*.ts", "services/api/**/*.ts"],
pattern: { kind: "literal", value: marker },
remediation: "Use NEW_NAME instead.",
fixtures: [
{ path: "packages/core/src/index.ts", content: "// π OLD_NAME OLD_NAME\n", expect: { line: 1, column: 6 } },
{ path: "services/api/index.ts", content: "// OLD_NAME\n", expect: { line: 1, column: 4 } },
{ path: "services/api/index.ts", content: "// old_name\n", expect: null },
{ path: "services/web/index.ts", content: "// OLD_NAME\n", expect: null },
],
});

Mix an exact repository-relative path with a pattern. This example uses ** for recursive matching, {private,local} for alternatives, [0-9] for a character range, and ? for one non-separator character. In the preceding forbidden-path recipe, * matches within one path segment. Use forward slashes in all path patterns.

path-globs.rule.ts
import { defineRule } from "@rulecheck/sdk";
export default defineRule({
id: "config/no-machine-specific-files",
kind: "forbidden-path",
paths: ["docker-compose.override.yml", "config/**/{private,local}-[0-9]?.toml"],
remediation: "Keep machine-specific files out of Git.",
fixtures: [
{ path: "docker-compose.override.yml", expect: { line: 1, column: 1 } },
{ path: "config/team/local-1a.toml", expect: { line: 1, column: 1 } },
{ path: "config/private-2b.toml", expect: { line: 1, column: 1 } },
{ path: "config/safe-1a.toml", expect: null },
{ path: "config/team/local-aa.toml", expect: null },
{ path: "config/team/local-1ab.toml", expect: null },
{ path: "examples/docker-compose.override.yml", expect: null },
],
});

Use expect: null for a clean or out-of-scope example, or an exact { line, column } for a finding. A fixture expects at most one location because each rule reports at most one finding per file. A text fixture must provide content; a forbidden-path fixture must omit it. The cookbook runner checks fixture expectations and then scans real tracked files. It also verifies exit 2 for an unsupported policy version.

One finding per rule per file, at the first match, is the v1 contract for check and its JSON output. Fix that match and run the check again to see the next one. Reporting every match would change finding counts, so it is reserved for a later flag or contract version.

Text and forbidden-path matchers do not parse an AST or understand whether text is inside a comment or a string. Use a syntax rule when the difference matters.

A syntax rule parses each file in scope and reports the first node that its selector picks. This rule reports a comment anywhere inside a function body, including nested blocks, callbacks, class methods and JSX. A comment in a return type, a parameter list or at the top level isn’t in a body, so it passes. // or /* */ inside a string, template literal, regex literal or JSX text isn’t a comment node, so it passes too. The ignore filters drop tool directives such as // eslint-disable-next-line and // @ts-expect-error, plus TODO and FIXME notes.

syntax.rule.ts
import { defineRule } from "@rulecheck/sdk";
// Function-like nodes in the TypeScript and TSX grammars whose `body` field
// holds the function body. A comment counts when it sits anywhere inside that
// body, including nested blocks, callbacks and JSX.
const functionBody = {
kinds: [
"function_declaration",
"function_expression",
"generator_function_declaration",
"generator_function",
"arrow_function",
"method_definition",
],
field: "body",
};
export default defineRule({
id: "source/no-function-body-comments",
kind: "syntax",
paths: ["src/**/*.ts", "src/**/*.tsx"],
selector: {
language: "typescript",
node: "comment",
inside: functionBody,
ignore: [
// Explicit tool directives stay, whatever comment style they use.
{ kind: "regex", value: "^(?://|/\\*)\\s*(?:@ts-(?:expect-error|ignore|nocheck)|eslint-(?:disable|enable)|prettier-ignore|biome-ignore|(?:istanbul|c8|v8) ignore)" },
// So do tracked work markers.
{ kind: "regex", value: "\\b(?:TODO|FIXME)\\b" },
],
},
remediation: "Move the explanation out of the function body or into a name.",
fixtures: [
{ path: "src/app.ts", content: "function f() {\n // explain\n return 1;\n}\n", expect: { line: 2, column: 3 } },
{ path: "src/app.ts", content: "function f(x: number) {\n if (x) {\n for (;;) {\n /* deep */ break;\n }\n }\n}\n", expect: { line: 4, column: 7 } },
{ path: "src/app.ts", content: "export const f = () => {\n return [1].map((x) => {\n // nested callback\n return x;\n });\n};\n", expect: { line: 3, column: 5 } },
{ path: "src/app.ts", content: "class A {\n // between members\n run(): void {\n // in a method\n }\n}\n", expect: { line: 4, column: 5 } },
{ path: "src/app.ts", content: "function f(): /* return type */ number {\n return 1;\n}\n", expect: null },
{ path: "src/app.ts", content: "function f(): Promise</* inner */ number> {\n return Promise.resolve(1);\n}\n", expect: null },
{ path: "src/app.ts", content: "function f(/* parameter */ x: number) {\n return x;\n}\n", expect: null },
{ path: "src/app.ts", content: "// top level\nfunction f() {\n return 1;\n}\n/* after */\n", expect: null },
{ path: "src/app.ts", content: "function f() {\n const a = \"// not a comment\";\n const b = `/* nor this */`;\n const c = /\\/\\/ regex/;\n return [a, b, c];\n}\n", expect: null },
{ path: "src/app.ts", content: "function f() {\n // eslint-disable-next-line no-console\n console.log(1);\n // @ts-expect-error: checked at runtime\n g(1);\n /* istanbul ignore next */\n h();\n // prettier-ignore\n const m = [1,0];\n}\n", expect: null },
{ path: "src/app.ts", content: "function f() {\n // TODO: split this up\n // FIXME(pas): wrong for 0\n return 1;\n}\n", expect: null },
{ path: "src/app.ts", content: "function f() {\n // TODO: later\n const x = 1; // the real comment\n return x;\n}\n", expect: { line: 3, column: 16 } },
{ path: "src/app.tsx", content: "export function App() {\n return (\n <div>\n {/* in JSX */}\n <p>// text, not a comment</p>\n </div>\n );\n}\n", expect: { line: 4, column: 8 } },
{ path: "src/app.tsx", content: "export function App() {\n return <p>// text, not a comment</p>;\n}\n", expect: null },
{ path: "src/app.tsx", content: "export const App = () => <div title=\"/* not a comment */\" />;\n", expect: null },
{ path: "scripts/build.ts", content: "function f() {\n // out of scope\n}\n", expect: null },
],
});

The runner checks a clean checkout first. It has a file header comment, a TODO in a function body, and JSX text that starts with //. Then it adds a comment inside total and expects:

src/total.ts:2:3: [source/no-function-body-comments] Move the explanation out of the function body or into a name.

A text regex for comment lines would also report the header, the TODO and a // line inside a template literal, and it would miss a trailing return 1; // why. The syntax rule reference lists the selector fields and when a file cannot be judged.

The selector is data. This second rule keeps the same inside value and changes only node, so it reports ! non-null assertions in function bodies without an evaluator change. a !== b, !a and a ! in a comment or string are not non_null_expression nodes.

syntax-reuse.rule.ts
import { defineRule } from "@rulecheck/sdk";
// The same function-body selector as the comment recipe, with a different
// node kind. No evaluator change is needed for a new syntax rule.
const functionBody = {
kinds: [
"function_declaration",
"function_expression",
"generator_function_declaration",
"generator_function",
"arrow_function",
"method_definition",
],
field: "body",
};
export default defineRule({
id: "source/no-non-null-assertion",
kind: "syntax",
paths: ["src/**/*.ts", "src/**/*.tsx"],
selector: { language: "typescript", node: "non_null_expression", inside: functionBody },
remediation: "Check for null or undefined instead of asserting with !.",
fixtures: [
{ path: "src/app.ts", content: "function f(m: Map<string, number>) {\n return m.get(\"a\")!;\n}\n", expect: { line: 2, column: 10 } },
{ path: "src/app.tsx", content: "export const App = (p: { n?: string }) => <p>{p.n!}</p>;\n", expect: { line: 1, column: 47 } },
{ path: "src/app.ts", content: "function f(a: number, b: number) {\n return a !== b && !a;\n}\n", expect: null },
{ path: "src/app.ts", content: "function f() {\n // value!\n return \"done!\";\n}\n", expect: null },
{ path: "src/app.ts", content: "class A {\n name!: string;\n}\n", expect: null },
],
});
src/first.ts:2:10: [source/no-non-null-assertion] Check for null or undefined instead of asserting with !.

The same selector works on Rust with language: "rust", which parses .rs files. This rule reports a // comment anywhere inside the body of a function, method or closure, including nested blocks, match arms and macro arguments such as vec![...]. A comment in a return type, a parameter list or at the top level isn’t in a body, so it passes, and so do //! and /// docs on the item. // inside a string or raw string isn’t a comment node. The ignore filters keep // SAFETY: comments, which Clippy’s undocumented_unsafe_blocks lint asks for, and TODO and FIXME notes.

syntax-rust.rule.ts
import { defineRule } from "@rulecheck/sdk";
// Rust items and closures whose `body` field holds the function body. A
// comment counts when it sits anywhere inside that body, including nested
// blocks, closures, methods in an impl and macro arguments.
const functionBody = {
kinds: ["function_item", "closure_expression"],
field: "body",
};
export default defineRule({
id: "source/no-rust-function-body-comments",
kind: "syntax",
paths: ["src/**/*.rs"],
selector: {
language: "rust",
// The Rust grammar has two comment kinds. This rule reports `//` comments,
// including `///` doc comments; a second rule with node "block_comment"
// and the same `inside` covers `/* */`.
node: "line_comment",
inside: functionBody,
ignore: [
// Clippy's undocumented_unsafe_blocks lint requires a SAFETY comment.
{ kind: "regex", value: "^//\\s*SAFETY:" },
// Tracked work markers stay.
{ kind: "regex", value: "\\b(?:TODO|FIXME)\\b" },
],
},
remediation: "Move the explanation out of the function body or into a name.",
fixtures: [
{ path: "src/lib.rs", content: "fn f() -> i32 {\n // explain\n 1\n}\n", expect: { line: 2, column: 5 } },
{ path: "src/lib.rs", content: "fn f(x: i32) {\n if x > 0 {\n loop {\n // deep\n break;\n }\n }\n}\n", expect: { line: 4, column: 13 } },
{ path: "src/lib.rs", content: "pub fn f(xs: &[i32]) -> Vec<i32> {\n xs.iter()\n .map(|x| {\n // in a closure\n x + 1\n })\n .collect()\n}\n", expect: { line: 4, column: 13 } },
{ path: "src/lib.rs", content: "struct A;\n\nimpl A {\n // between items\n fn run(&self) {\n // in a method\n }\n}\n", expect: { line: 6, column: 9 } },
{ path: "src/lib.rs", content: "fn f() -> Vec<i32> {\n vec![\n // in a macro\n 1,\n ]\n}\n", expect: { line: 3, column: 9 } },
{ path: "src/lib.rs", content: "fn f() -> i32 {\n let x = 1; // trailing\n x\n}\n", expect: { line: 2, column: 16 } },
{ path: "src/lib.rs", content: "fn f() -> // return type\n i32 {\n 1\n}\n", expect: null },
{ path: "src/lib.rs", content: "fn f() -> Result<\n // inner\n i32,\n (),\n> {\n Ok(1)\n}\n", expect: null },
{ path: "src/lib.rs", content: "fn f(\n // parameter\n x: i32,\n) -> i32 {\n x\n}\n", expect: null },
{ path: "src/lib.rs", content: "//! Crate docs.\n\n/// Item docs.\n// top level\nfn f() {}\n", expect: null },
{ path: "src/lib.rs", content: "fn f() -> [&'static str; 3] {\n let a = \"// not a comment\";\n let b = r#\"// nor this\"#;\n let c = \"\n// nor this line\n\";\n [a, b, c]\n}\n", expect: null },
{ path: "src/lib.rs", content: "fn f(p: *const i32) -> i32 {\n // SAFETY: the caller passes a valid pointer.\n unsafe { *p }\n}\n", expect: null },
{ path: "src/lib.rs", content: "fn f() -> i32 {\n // TODO: split this up\n // FIXME(pas): wrong for 0\n 1\n}\n", expect: null },
{ path: "src/lib.rs", content: "fn f() -> i32 {\n // TODO: later\n let x = 1; // the real comment\n x\n}\n", expect: { line: 3, column: 16 } },
{ path: "src/lib.rs", content: "fn f() -> i32 {\n /* block */\n 1\n}\n", expect: null },
{ path: "tests/it.rs", content: "fn f() {\n // out of scope\n}\n", expect: null },
],
});

The Rust grammar has two comment kinds: line_comment for //, /// and //!, and block_comment for /* */. This rule selects line_comment, so a /* */ in a body passes, as its last in-scope fixture shows. To report block comments too, add a second rule with node: "block_comment" and the same inside.

The runner checks a clean src/lib.rs first. It has crate and item docs, a TODO, "// none" in a string, and a SAFETY comment. Then it adds a comment inside total and expects:

src/lib.rs:2:5: [source/no-rust-function-body-comments] Move the explanation out of the function body or into a name.