@whil/guardrails 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +208 -2
  3. package/catalog-assets/claude-hooks/guardrails-check.sh +37 -0
  4. package/catalog-assets/eslint-guardrails/config.mjs +21 -0
  5. package/catalog-assets/eslint-rules/_rule-tester.mjs +21 -0
  6. package/catalog-assets/eslint-rules/cache-policy-constant.mjs +35 -0
  7. package/catalog-assets/eslint-rules/client-imports-server.mjs +26 -0
  8. package/catalog-assets/eslint-rules/effects-in-hooks.mjs +46 -0
  9. package/catalog-assets/eslint-rules/env-through-config.mjs +26 -0
  10. package/catalog-assets/eslint-rules/hook-body-order.mjs +169 -0
  11. package/catalog-assets/eslint-rules/import-boundaries.mjs +97 -0
  12. package/catalog-assets/eslint-rules/no-comments.mjs +35 -0
  13. package/catalog-assets/eslint-rules/no-default-export.mjs +20 -0
  14. package/catalog-assets/eslint-rules/no-delete.mjs +16 -0
  15. package/catalog-assets/eslint-rules/no-enum.mjs +14 -0
  16. package/catalog-assets/eslint-rules/no-heavy-inline-styles.mjs +20 -0
  17. package/catalog-assets/eslint-rules/no-let.mjs +14 -0
  18. package/catalog-assets/eslint-rules/no-logic-in-jsx.mjs +23 -0
  19. package/catalog-assets/eslint-rules/no-manual-memoization.mjs +45 -0
  20. package/catalog-assets/eslint-rules/no-member-assignment.mjs +28 -0
  21. package/catalog-assets/eslint-rules/no-module-cache.mjs +40 -0
  22. package/catalog-assets/eslint-rules/no-mutating-array-methods.mjs +85 -0
  23. package/catalog-assets/eslint-rules/no-process-exit.mjs +15 -0
  24. package/catalog-assets/eslint-rules/no-state-mutation.mjs +62 -0
  25. package/catalog-assets/eslint-rules/no-unnecessary-use-client.mjs +40 -0
  26. package/catalog-assets/eslint-rules/pure-components.mjs +48 -0
  27. package/catalog-assets/eslint-rules/query-key-constant.mjs +54 -0
  28. package/catalog-assets/eslint-rules/require-disable-reason.mjs +29 -0
  29. package/catalog-assets/eslint-rules/restrict-timers.mjs +35 -0
  30. package/catalog-assets/eslint-rules/rules-of-hooks.mjs +51 -0
  31. package/catalog-assets/eslint-rules/thin-api-routes.mjs +18 -0
  32. package/catalog-assets/eslint-rules/thin-routes.mjs +18 -0
  33. package/catalog-assets/eslint-rules/virtualized-lists.mjs +32 -0
  34. package/catalog-assets/githooks/commit-msg +13 -0
  35. package/catalog-assets/githooks/pre-commit +26 -0
  36. package/catalog-assets/scripts/check-exact-deps.mjs +26 -0
  37. package/dist/cli.js +54 -0
  38. package/dist/core/app/analysis.js +6 -0
  39. package/dist/core/app/args.js +44 -0
  40. package/dist/core/app/catalog.js +20 -0
  41. package/dist/core/app/ci-plan.js +14 -0
  42. package/dist/core/app/claude.js +37 -0
  43. package/dist/core/app/commands/add-rule.js +32 -0
  44. package/dist/core/app/commands/agents-md.js +13 -0
  45. package/dist/core/app/commands/apply.js +74 -0
  46. package/dist/core/app/commands/audit.js +38 -0
  47. package/dist/core/app/commands/check.js +33 -0
  48. package/dist/core/app/commands/detect.js +16 -0
  49. package/dist/core/app/commands/init.js +124 -0
  50. package/dist/core/app/commands/learn.js +48 -0
  51. package/dist/core/app/commands/plan.js +40 -0
  52. package/dist/core/app/commands/pr-status.js +66 -0
  53. package/dist/core/app/commands/self-check.js +17 -0
  54. package/dist/core/app/git.js +75 -0
  55. package/dist/core/app/github.js +146 -0
  56. package/dist/core/app/hooks-script.js +27 -0
  57. package/dist/core/app/output.js +17 -0
  58. package/dist/core/app/run.js +32 -0
  59. package/dist/core/app/session.js +18 -0
  60. package/dist/core/app/timing.js +11 -0
  61. package/dist/core/domain/agents-md.js +92 -0
  62. package/dist/core/domain/audit-report.js +7 -0
  63. package/dist/core/domain/changes.js +8 -0
  64. package/dist/core/domain/check-report.js +23 -0
  65. package/dist/core/domain/claude-settings.js +42 -0
  66. package/dist/core/domain/constraint.js +7 -0
  67. package/dist/core/domain/diagnostics.js +3 -0
  68. package/dist/core/domain/errors.js +20 -0
  69. package/dist/core/domain/facts.js +18 -0
  70. package/dist/core/domain/init-report.js +28 -0
  71. package/dist/core/domain/json.js +43 -0
  72. package/dist/core/domain/learn.js +78 -0
  73. package/dist/core/domain/log-parse.js +99 -0
  74. package/dist/core/domain/pack-defaults.js +17 -0
  75. package/dist/core/domain/pack.js +1 -0
  76. package/dist/core/domain/pr-comment.js +45 -0
  77. package/dist/core/domain/pr-loop.js +85 -0
  78. package/dist/core/domain/profile.js +25 -0
  79. package/dist/core/domain/protection.js +43 -0
  80. package/dist/core/domain/ratchet.js +40 -0
  81. package/dist/core/domain/registry.js +32 -0
  82. package/dist/core/domain/remote.js +4 -0
  83. package/dist/core/domain/result.js +25 -0
  84. package/dist/core/domain/thresholds.js +9 -0
  85. package/dist/core/domain/types.js +1 -0
  86. package/dist/core/domain/workflows.js +252 -0
  87. package/dist/core/infra/assets.js +7 -0
  88. package/dist/core/infra/backup.js +31 -0
  89. package/dist/core/infra/baseline.js +8 -0
  90. package/dist/core/infra/changes.js +17 -0
  91. package/dist/core/infra/exec.js +14 -0
  92. package/dist/core/infra/facts.js +61 -0
  93. package/dist/core/infra/fs.js +87 -0
  94. package/dist/core/infra/gh.js +32 -0
  95. package/dist/core/infra/hooks.js +31 -0
  96. package/dist/core/infra/learn-sources.js +40 -0
  97. package/dist/core/infra/pr.js +48 -0
  98. package/dist/packs/index.js +6 -0
  99. package/dist/packs/js-ts/app/add-rule.js +116 -0
  100. package/dist/packs/js-ts/app/analysis.js +104 -0
  101. package/dist/packs/js-ts/app/bootstrap.js +16 -0
  102. package/dist/packs/js-ts/app/eslint-constraints.js +155 -0
  103. package/dist/packs/js-ts/app/eslint-files.js +56 -0
  104. package/dist/packs/js-ts/app/fixes.js +3 -0
  105. package/dist/packs/js-ts/app/pr-rules.js +30 -0
  106. package/dist/packs/js-ts/app/project.js +87 -0
  107. package/dist/packs/js-ts/app/tests.js +63 -0
  108. package/dist/packs/js-ts/domain/catalog-specs.js +147 -0
  109. package/dist/packs/js-ts/domain/ci.js +47 -0
  110. package/dist/packs/js-ts/domain/data.js +34 -0
  111. package/dist/packs/js-ts/domain/diagnostics-js.js +17 -0
  112. package/dist/packs/js-ts/domain/disables.js +11 -0
  113. package/dist/packs/js-ts/domain/eslint-output.js +46 -0
  114. package/dist/packs/js-ts/domain/eslint-state.js +80 -0
  115. package/dist/packs/js-ts/domain/hooks.js +49 -0
  116. package/dist/packs/js-ts/domain/pr-diagnostics.js +33 -0
  117. package/dist/packs/js-ts/domain/pr-tests.js +27 -0
  118. package/dist/packs/js-ts/domain/profile-pure.js +51 -0
  119. package/dist/packs/js-ts/domain/profile.js +112 -0
  120. package/dist/packs/js-ts/domain/report.js +74 -0
  121. package/dist/packs/js-ts/domain/rule-templates.js +44 -0
  122. package/dist/packs/js-ts/domain/signals.js +14 -0
  123. package/dist/packs/js-ts/domain/testing.js +33 -0
  124. package/dist/packs/js-ts/domain/ts-options.js +13 -0
  125. package/dist/packs/js-ts/index.js +50 -0
  126. package/dist/packs/js-ts/infra/eslint.js +50 -0
  127. package/dist/packs/js-ts/infra/scan.js +25 -0
  128. package/dist/packs/js-ts/infra/tsc.js +21 -0
  129. package/dist/packs/nextjs/domain/data.js +9 -0
  130. package/dist/packs/nextjs/domain/profile.js +21 -0
  131. package/dist/packs/nextjs/domain/specs.js +33 -0
  132. package/dist/packs/nextjs/index.js +23 -0
  133. package/dist/packs/node/domain/specs.js +23 -0
  134. package/dist/packs/node/index.js +26 -0
  135. package/dist/packs/react/domain/data.js +9 -0
  136. package/dist/packs/react/domain/specs.js +63 -0
  137. package/dist/packs/react/index.js +30 -0
  138. package/dist/packs/react-native/domain/specs.js +29 -0
  139. package/dist/packs/react-native/domain/testing.js +20 -0
  140. package/dist/packs/react-native/index.js +30 -0
  141. package/package.json +60 -4
@@ -0,0 +1,50 @@
1
+ import { addRuleJsTs } from "./app/add-rule.js";
2
+ import { analyzeJsTs } from "./app/analysis.js";
3
+ import { JS_TS_BOOTSTRAP } from "./app/bootstrap.js";
4
+ import { eslintConstraint, unusedDisableDirectives } from "./app/eslint-constraints.js";
5
+ import { exactDeps, pkgScripts, tsStrictMax } from "./app/project.js";
6
+ import { testsConstraint } from "./app/tests.js";
7
+ import { JS_TS_CI, JS_TS_COMMANDS } from "./domain/ci.js";
8
+ import { fixesOf, JS_TS_SPECS } from "./domain/catalog-specs.js";
9
+ import { jsTs } from "./domain/data.js";
10
+ import { JS_TS_SIGNALS } from "./domain/signals.js";
11
+ import { JS_TS_HOOKS } from "./domain/hooks.js";
12
+ import { JS_TS_PROBE, deriveJsTs, describeJsTs } from "./domain/profile.js";
13
+ import { packageRunCommand } from "./domain/profile-pure.js";
14
+ import { VITEST_SPEC } from "./domain/testing.js";
15
+ const script = (name) => (profile) => {
16
+ const data = jsTs(profile);
17
+ return data.scripts[name] ? packageRunCommand(data.packageManager, name) : null;
18
+ };
19
+ const detect = (facts) => {
20
+ const hasPackage = facts.json["package.json"] !== undefined;
21
+ const hasTypescript = facts.json["tsconfig.json"] !== undefined;
22
+ return {
23
+ confidence: hasPackage ? (hasTypescript ? 1 : 0.6) : 0,
24
+ evidence: [...(hasPackage ? ["package.json"] : []), ...(hasTypescript ? ["tsconfig.json"] : [])],
25
+ };
26
+ };
27
+ export const jsTsPack = {
28
+ id: "js-ts",
29
+ title: "JavaScript and TypeScript: strict tsconfig, ESLint with the guardrails plugin, immutability, no any, no comments",
30
+ extends: [],
31
+ probe: JS_TS_PROBE,
32
+ detect,
33
+ profile: (facts) => ({ ...deriveJsTs(facts) }),
34
+ constraints: [pkgScripts, tsStrictMax, ...JS_TS_SPECS.map(eslintConstraint), unusedDisableDirectives, exactDeps, testsConstraint],
35
+ fixes: fixesOf(JS_TS_SPECS),
36
+ signals: JS_TS_SIGNALS,
37
+ tools: {
38
+ linter: { id: "eslint", command: script("lint") },
39
+ typecheck: { id: "tsc", command: script("typecheck") },
40
+ formatter: null,
41
+ test: { id: "vitest", command: script("test") },
42
+ },
43
+ commands: JS_TS_COMMANDS,
44
+ ci: JS_TS_CI,
45
+ hooks: { ...JS_TS_HOOKS, bootstrap: JS_TS_BOOTSTRAP },
46
+ testing: VITEST_SPEC,
47
+ analyze: analyzeJsTs,
48
+ addRule: addRuleJsTs,
49
+ describe: (profile) => describeJsTs(jsTs(profile)),
50
+ };
@@ -0,0 +1,50 @@
1
+ import { join } from "node:path";
2
+ import { LINT_NOT_RUN, parseEslintJson } from "../domain/eslint-output.js";
3
+ import { isRecord, parseStrictJson } from "../../../core/domain/json.js";
4
+ import { exists, removeFile, writeTemp } from "../../../core/infra/fs.js";
5
+ import { runAsync, runSync } from "../../../core/infra/exec.js";
6
+ function bin(root) {
7
+ return join(root, "node_modules", ".bin", "eslint");
8
+ }
9
+ export function hasEslint(root) {
10
+ return exists(root, "node_modules/.bin/eslint");
11
+ }
12
+ function lintArgs(data, paths) {
13
+ const targets = paths.length > 0 ? paths : data.paths.sourceGlobs.length > 0 ? data.paths.sourceGlobs : ["."];
14
+ return [...targets, "--format", "json", "--no-error-on-unmatched-pattern"];
15
+ }
16
+ function toOutcome(root, result) {
17
+ const parsed = result.status <= 1 ? parseEslintJson(root, result.stdout) : null;
18
+ if (parsed === null)
19
+ return LINT_NOT_RUN((result.stderr || result.stdout).trim().split("\n").slice(0, 6).join("\n"));
20
+ return { ran: true, error: null, ...parsed };
21
+ }
22
+ export function lintRepo(root, data, paths = []) {
23
+ return hasEslint(root) ? toOutcome(root, runSync(bin(root), lintArgs(data, paths), root)) : LINT_NOT_RUN("eslint is not installed in node_modules");
24
+ }
25
+ export async function lintRepoAsync(root, data, paths = []) {
26
+ return hasEslint(root) ? toOutcome(root, await runAsync(bin(root), lintArgs(data, paths), root)) : LINT_NOT_RUN("eslint is not installed in node_modules");
27
+ }
28
+ export function probeRules(root, filename, code) {
29
+ const unusable = { rules: new Set(), usable: false };
30
+ if (!writeTemp(root, filename, code))
31
+ return unusable;
32
+ try {
33
+ const result = runSync(bin(root), [filename, "--format", "json"], root);
34
+ const parsed = result.status <= 1 ? parseEslintJson(root, result.stdout) : null;
35
+ if (parsed === null || parsed.fatal.length > 0)
36
+ return unusable;
37
+ return { rules: new Set(parsed.violations.map((violation) => violation.rule)), usable: true };
38
+ }
39
+ finally {
40
+ removeFile(root, filename);
41
+ }
42
+ }
43
+ export function printConfigRules(root, filename) {
44
+ const result = runSync(bin(root), ["--print-config", filename], root);
45
+ if (result.status !== 0)
46
+ return null;
47
+ const parsed = parseStrictJson(result.stdout);
48
+ const rules = parsed.ok && isRecord(parsed.value) ? parsed.value["rules"] : null;
49
+ return isRecord(rules) ? rules : null;
50
+ }
@@ -0,0 +1,25 @@
1
+ import { readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { findDisableDirectives } from "../domain/disables.js";
4
+ const SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
5
+ const SKIPPED_DIRS = ["node_modules", ".next", "dist", "build", "out", ".git", "coverage"];
6
+ function walk(root, rel) {
7
+ const stat = statSync(join(root, rel), { throwIfNoEntry: false });
8
+ if (stat === undefined)
9
+ return [];
10
+ if (stat.isFile())
11
+ return SOURCE_EXTENSIONS.some((extension) => rel.endsWith(extension)) ? [rel] : [];
12
+ return readdirSync(join(root, rel))
13
+ .filter((name) => !SKIPPED_DIRS.includes(name))
14
+ .toSorted()
15
+ .flatMap((name) => walk(root, rel === "" ? name : `${rel}/${name}`));
16
+ }
17
+ export function sourceRoots(data) {
18
+ const roots = data.paths.sourceGlobs.map((glob) => glob.split("/**")[0] ?? "");
19
+ return roots.length > 0 ? [...new Set(roots)] : [""];
20
+ }
21
+ export function scanDisableDirectives(root, data) {
22
+ return sourceRoots(data)
23
+ .flatMap((dir) => walk(root, dir))
24
+ .flatMap((file) => findDisableDirectives(readFileSync(join(root, file), "utf8")).map((found) => ({ file, ...found })));
25
+ }
@@ -0,0 +1,21 @@
1
+ import { join } from "node:path";
2
+ import { parseTscOutput } from "../domain/diagnostics-js.js";
3
+ import { exists } from "../../../core/infra/fs.js";
4
+ import { runAsync, runSync } from "../../../core/infra/exec.js";
5
+ const ARGS = ["--noEmit", "--pretty", "false"];
6
+ const MISSING = Object.freeze({ ran: false, diagnostics: [], error: "tsc is not installed in node_modules" });
7
+ function bin(root) {
8
+ return join(root, "node_modules", ".bin", "tsc");
9
+ }
10
+ function toOutcome(result) {
11
+ const diagnostics = parseTscOutput(`${result.stdout}\n${result.stderr}`);
12
+ if (result.status !== 0 && diagnostics.length === 0)
13
+ return { ran: false, diagnostics, error: (result.stdout || result.stderr).trim().slice(0, 500) };
14
+ return { ran: true, diagnostics, error: null };
15
+ }
16
+ export function runTsc(root) {
17
+ return exists(root, "node_modules/.bin/tsc") ? toOutcome(runSync(bin(root), ARGS, root)) : MISSING;
18
+ }
19
+ export async function runTscAsync(root) {
20
+ return exists(root, "node_modules/.bin/tsc") ? toOutcome(await runAsync(bin(root), ARGS, root)) : MISSING;
21
+ }
@@ -0,0 +1,9 @@
1
+ import { isRecord } from "../../../core/domain/json.js";
2
+ const EMPTY = { version: null, router: null, pageGlobs: [], apiGlobs: [], routeGlobs: [] };
3
+ function isNextData(value) {
4
+ return isRecord(value) && Array.isArray(value["pageGlobs"]) && Array.isArray(value["apiGlobs"]);
5
+ }
6
+ export function nextOf(profile) {
7
+ const value = profile.stack["nextjs"];
8
+ return isNextData(value) ? value : EMPTY;
9
+ }
@@ -0,0 +1,21 @@
1
+ const CONFIGS = ["**/*.config.{ts,mjs,js,cjs,mts}"];
2
+ const APP_FILES = "{page,layout,loading,error,global-error,not-found,template,default}";
3
+ function routerOf(facts) {
4
+ const app = facts.present.includes("src/app") || facts.present.includes("app");
5
+ const pages = facts.present.includes("src/pages") || facts.present.includes("pages");
6
+ return app && pages ? "both" : app ? "app" : pages ? "pages" : null;
7
+ }
8
+ export function nextData(facts, version) {
9
+ const router = routerOf(facts);
10
+ const app = router === "app" || router === "both";
11
+ const pages = router === "pages" || router === "both";
12
+ const pageGlobs = [...(app ? [`**/app/**/${APP_FILES}.{ts,tsx}`] : []), ...(pages ? ["**/pages/**/*.{ts,tsx}"] : [])];
13
+ const apiGlobs = [...(app ? ["**/app/**/route.{ts,tsx}"] : []), ...(pages ? ["**/pages/api/**/*.{ts,tsx}"] : [])];
14
+ return {
15
+ version,
16
+ router,
17
+ pageGlobs,
18
+ apiGlobs,
19
+ routeGlobs: [...CONFIGS, ...pageGlobs, ...apiGlobs, "**/app/**/route.{ts,tsx}", "**/{middleware,proxy,instrumentation}.{ts,js}"],
20
+ };
21
+ }
@@ -0,0 +1,33 @@
1
+ import { THRESHOLDS } from "../../../core/domain/thresholds.js";
2
+ import { own } from "../../js-ts/domain/catalog-specs.js";
3
+ import { nextOf } from "./data.js";
4
+ const MAX_ROUTE_LINES = THRESHOLDS.routeLines.value;
5
+ const MAX_API_LINES = THRESHOLDS.apiRouteLines.value;
6
+ export const NEXTJS_SPECS = Object.freeze([
7
+ {
8
+ id: "next-no-unnecessary-use-client",
9
+ title: "'use client' only where the file needs the client",
10
+ why: "A client boundary ships the file and everything it imports to the browser; without hooks, handlers or browser APIs it should stay a server component.",
11
+ rules: [{ name: own("no-unnecessary-use-client"), fix: "Delete the `'use client'` directive, or move the interactive part into a small client component and keep this file on the server.", probe: "'use client';\nexport function A() {\n return null;\n}\n" }],
12
+ },
13
+ {
14
+ id: "next-server-client-boundary",
15
+ title: "Client files never import server-only modules",
16
+ why: "A 'use client' file that imports next/headers, server-only, Node built-ins or a server folder breaks the build or leaks server code to the browser.",
17
+ rules: [{ name: own("client-imports-server"), fix: "Fetch the data in a server component and pass it down as props, or call a server action or route handler from the client.", probe: "'use client';\nimport { cookies } from \"next/headers\";\nexport const a = cookies;\n" }],
18
+ },
19
+ {
20
+ id: "next-thin-routes",
21
+ title: `Page and layout files stay under ${String(MAX_ROUTE_LINES)} lines`,
22
+ why: "A route file only wires data to a view; logic that lives in the route cannot be reused or tested.",
23
+ applies: (profile) => (nextOf(profile).pageGlobs.length === 0 ? "no page or layout files detected" : null),
24
+ rules: [{ name: own("thin-routes"), files: (profile) => nextOf(profile).pageGlobs, options: () => [{ max: MAX_ROUTE_LINES }], fix: "Move the logic to a feature module or a server function and keep the route as composition: fetch, then render a view component." }],
25
+ },
26
+ {
27
+ id: "next-thin-api-routes",
28
+ title: `API routes stay under ${String(MAX_API_LINES)} lines`,
29
+ why: "A route handler should parse the request, call a service and return a response; business logic in the handler cannot be reused or tested.",
30
+ applies: (profile) => (nextOf(profile).apiGlobs.length === 0 ? "no route handlers or pages/api files detected" : null),
31
+ rules: [{ name: own("thin-api-routes"), files: (profile) => nextOf(profile).apiGlobs, options: () => [{ max: MAX_API_LINES }], fix: "Move the logic to a service module; the handler parses the request, calls the service and returns the response." }],
32
+ },
33
+ ]);
@@ -0,0 +1,23 @@
1
+ import { definePack } from "../../core/domain/pack-defaults.js";
2
+ import { VITEST_SPEC } from "../js-ts/domain/testing.js";
3
+ import { eslintConstraint } from "../js-ts/app/eslint-constraints.js";
4
+ import { fixesOf } from "../js-ts/domain/catalog-specs.js";
5
+ import { dependenciesOf, installedVersion } from "../js-ts/domain/profile.js";
6
+ import { nextOf } from "./domain/data.js";
7
+ import { NEXTJS_SPECS } from "./domain/specs.js";
8
+ import { nextData } from "./domain/profile.js";
9
+ export const nextjsPack = definePack({
10
+ id: "nextjs",
11
+ title: "Next.js (App and Pages Router): server/client boundary, no unnecessary 'use client', thin routes, thin API routes",
12
+ extends: ["react"],
13
+ probe: { paths: ["app", "pages", "src/app", "src/pages", "next.config.ts", "next.config.mjs", "next.config.js"], json: ["node_modules/next/package.json"], text: [], tree: [] },
14
+ detect: (facts) => {
15
+ const present = dependenciesOf(facts).has("next");
16
+ return { confidence: present ? 1 : 0, evidence: present ? ["next dependency"] : [] };
17
+ },
18
+ profile: (facts) => ({ ...nextData(facts, installedVersion(facts, "next")) }),
19
+ constraints: NEXTJS_SPECS.map(eslintConstraint),
20
+ fixes: fixesOf(NEXTJS_SPECS),
21
+ testing: VITEST_SPEC,
22
+ describe: (profile) => [`next ${nextOf(profile).version ?? "?"}, router ${nextOf(profile).router ?? "none"}`],
23
+ });
@@ -0,0 +1,23 @@
1
+ import { own } from "../../js-ts/domain/catalog-specs.js";
2
+ const CONFIG_GLOBS = ["**/config/**", "**/*.config.{ts,js,mjs,cjs}", "**/env.{ts,js,mjs}", "**/config.{ts,js,mjs}"];
3
+ const ENTRY_GLOBS = ["**/cli.{ts,js,mjs}", "**/bin/**", "**/main.{ts,js,mjs}", "**/server.{ts,js,mjs}"];
4
+ export const NODE_SPECS = Object.freeze([
5
+ {
6
+ id: "env-through-config",
7
+ title: "process.env is read only in config files",
8
+ why: "Scattered environment reads make a missing variable fail late, in the first request; one config module fails at startup and lists what is missing.",
9
+ rules: [{ name: own("env-through-config"), ignores: () => CONFIG_GLOBS, fix: "Read the variable once in a config module (`src/config.ts`, `src/config/*.ts`, `env.ts`), validate it there, and import the typed value.", probe: "export const url = process.env.DATABASE_URL;\n" }],
10
+ },
11
+ {
12
+ id: "no-process-exit",
13
+ title: "process.exit only at the entry point",
14
+ why: "Exiting from deep code skips cleanup and makes the function impossible to test; return an error and let the entry point decide the exit code.",
15
+ rules: [{ name: own("no-process-exit"), ignores: () => ENTRY_GLOBS, fix: "Return a Result or throw to the entry point (cli, main, server) and call `process.exit` there once.", probe: "export function stop() {\n process.exit(1);\n}\n" }],
16
+ },
17
+ {
18
+ id: "no-module-cache",
19
+ title: "No mutable Map/Set at module level",
20
+ why: "A module-level Map or Set is state shared by every request and session; it survives resets and leaks between tests.",
21
+ rules: [{ name: own("no-module-cache"), fix: "Create the collection inside a factory (`createXCache()`) held by its owner, or type it `ReadonlyMap`/`ReadonlySet` if it never changes.", probe: "export const seen = new Set<string>();\n" }],
22
+ },
23
+ ]);
@@ -0,0 +1,26 @@
1
+ import { definePack } from "../../core/domain/pack-defaults.js";
2
+ import { VITEST_SPEC } from "../js-ts/domain/testing.js";
3
+ import { eslintConstraint } from "../js-ts/app/eslint-constraints.js";
4
+ import { fixesOf } from "../js-ts/domain/catalog-specs.js";
5
+ import { dependenciesOf, packageField } from "../js-ts/domain/profile.js";
6
+ import { NODE_SPECS } from "./domain/specs.js";
7
+ const SERVER_LIBRARIES = ["express", "fastify", "koa", "hono", "@nestjs/core", "@hapi/hapi", "commander", "yargs", "citty", "cac"];
8
+ export const nodePack = definePack({
9
+ id: "node",
10
+ title: "Node backends and CLIs: env read only in config, process.exit only at the entry point, no shared mutable module state",
11
+ extends: ["js-ts"],
12
+ probe: { paths: [], json: [], text: [], tree: [] },
13
+ detect: (facts) => {
14
+ const deps = dependenciesOf(facts);
15
+ const library = SERVER_LIBRARIES.find((name) => deps.has(name));
16
+ const bin = packageField(facts, "bin") !== undefined;
17
+ const types = deps.has("@types/node");
18
+ const evidence = [...(library === undefined ? [] : [library]), ...(bin ? ["package.json bin"] : []), ...(types ? ["@types/node"] : [])];
19
+ return { confidence: library !== undefined || bin ? 1 : types ? 0.5 : 0, evidence };
20
+ },
21
+ profile: () => ({}),
22
+ constraints: NODE_SPECS.map(eslintConstraint),
23
+ fixes: fixesOf(NODE_SPECS),
24
+ testing: VITEST_SPEC,
25
+ describe: () => ["backend/CLI rules active"],
26
+ });
@@ -0,0 +1,9 @@
1
+ import { isRecord } from "../../../core/domain/json.js";
2
+ const EMPTY = { version: null, compiler: false, tanstackQuery: false };
3
+ function isReactData(value) {
4
+ return isRecord(value) && typeof value["compiler"] === "boolean" && typeof value["tanstackQuery"] === "boolean";
5
+ }
6
+ export function reactOf(profile) {
7
+ const value = profile.stack["react"];
8
+ return isReactData(value) ? value : EMPTY;
9
+ }
@@ -0,0 +1,63 @@
1
+ import { own } from "../../js-ts/domain/catalog-specs.js";
2
+ import { hookGlobsOf } from "../../js-ts/domain/data.js";
3
+ import { reactOf } from "./data.js";
4
+ const queryOnly = (profile) => (reactOf(profile).tanstackQuery ? null : "@tanstack/react-query not detected");
5
+ export const REACT_SPECS = Object.freeze([
6
+ {
7
+ id: "rules-of-hooks",
8
+ title: "Hooks are called unconditionally at the top level of components and hooks",
9
+ why: "A hook behind a condition, loop or nested function changes call order between renders and corrupts state.",
10
+ rules: [{ name: own("rules-of-hooks"), fix: "Move the hook call to the top level of the component or custom hook, before any early return; put the condition inside the hook or in the returned value.", probe: 'export function A({ on }: { on: boolean }) {\n if (on) useThing();\n return null;\n}\n' }],
11
+ },
12
+ {
13
+ id: "effects-in-hooks",
14
+ title: "Effects live only in named hooks",
15
+ why: "Effects inside components hide the external system they sync with.",
16
+ rules: [{ name: own("effects-in-hooks"), ignores: hookGlobsOf, fix: "Move the effect into a `use*` hook (own file or hooks folder) and call the hook.", probe: 'import { useEffect } from "react";\n' }],
17
+ },
18
+ {
19
+ id: "hook-body-order",
20
+ title: "Component and hook bodies follow one order",
21
+ why: "One fixed order (hooks, derived values, handlers, effects, render) keeps every reader and agent consistent.",
22
+ rules: [{ name: own("hook-body-order"), fix: "Move the statement to its block: hooks, derived values and guards, handlers, effects, render." }],
23
+ },
24
+ {
25
+ id: "no-state-mutation",
26
+ title: "State and props are never mutated",
27
+ why: "React compares by reference: a mutated state array or object does not re-render and breaks memoization.",
28
+ rules: [{ name: own("no-state-mutation"), fix: "Create a new value and pass it to the setter: `setItems([...items, item])`, `setUser({ ...user, name })`.", probe: 'declare function useState<T>(v: T): [T, (v: T) => void];\nexport function A() {\n const [items] = useState<number[]>([]);\n items.push(1);\n return null;\n}\n' }],
29
+ },
30
+ {
31
+ id: "pure-components",
32
+ title: "Components are pure during render",
33
+ why: "Render must return the same output for the same inputs; clocks, randomness, network and browser globals belong in hooks and handlers.",
34
+ rules: [{ name: own("pure-components"), fix: "Move the impure call into a hook or event handler, or pass the value in as a prop or state.", probe: "export function A() {\n const id = Math.random();\n return id;\n}\n" }],
35
+ },
36
+ {
37
+ id: "restrict-timers",
38
+ title: "Timers only in hooks",
39
+ why: "A timer outside a hook has no cleanup and fires after the screen is gone.",
40
+ rules: [{ name: own("restrict-timers"), ignores: hookGlobsOf, fix: "Move the timer into a hook with cleanup in the effect return.", probe: "setTimeout(() => 1, 1);\n" }],
41
+ },
42
+ {
43
+ id: "no-manual-memoization",
44
+ title: "No manual memoization with the React Compiler on",
45
+ why: "The Compiler memoizes; manual wrappers only hide rule violations.",
46
+ applies: (profile) => (reactOf(profile).compiler ? null : "React Compiler not detected"),
47
+ rules: [{ name: own("no-manual-memoization"), fix: "Remove `useMemo`, `useCallback` and `memo`; write the plain function or value.", probe: 'import { useMemo } from "react";\n' }],
48
+ },
49
+ {
50
+ id: "query-key-constant",
51
+ title: "Query keys start with a <NAME>_QUERY_KEY constant",
52
+ why: "Literal keys drift between the hook and its invalidations.",
53
+ applies: queryOnly,
54
+ rules: [{ name: own("query-key-constant"), fix: "Export `<NAME>_QUERY_KEY` from the hook that owns the query and start the key with it.", probe: 'export const a = { queryKey: ["user"] };\n' }],
55
+ },
56
+ {
57
+ id: "cache-policy-constant",
58
+ title: "staleTime and gcTime use named constants",
59
+ why: "Inline cache numbers cannot be audited or changed in one place.",
60
+ applies: queryOnly,
61
+ rules: [{ name: own("cache-policy-constant"), fix: "Use a named constant such as `USER_STALE_TIME_MS`.", probe: "export const a = { staleTime: 1000 };\n" }],
62
+ },
63
+ ]);
@@ -0,0 +1,30 @@
1
+ import { definePack } from "../../core/domain/pack-defaults.js";
2
+ import { VITEST_SPEC } from "../js-ts/domain/testing.js";
3
+ import { eslintConstraint } from "../js-ts/app/eslint-constraints.js";
4
+ import { fixesOf } from "../js-ts/domain/catalog-specs.js";
5
+ import { dependenciesOf, installedVersion } from "../js-ts/domain/profile.js";
6
+ import { reactOf } from "./domain/data.js";
7
+ import { REACT_SPECS } from "./domain/specs.js";
8
+ export const reactPack = definePack({
9
+ id: "react",
10
+ title: "React: rules of hooks, effects only in hooks, no state mutation, pure components, React Compiler and query conventions",
11
+ extends: ["js-ts"],
12
+ probe: { paths: ["node_modules/.bin/react-compiler"], json: ["node_modules/react/package.json"], text: ["next.config.ts", "next.config.mjs", "next.config.js", "babel.config.js", "app.json"], tree: [] },
13
+ detect: (facts) => {
14
+ const deps = dependenciesOf(facts);
15
+ return { confidence: deps.has("react") ? 1 : 0, evidence: deps.has("react") ? ["react dependency"] : [] };
16
+ },
17
+ profile: (facts) => {
18
+ const deps = dependenciesOf(facts);
19
+ const texts = Object.values(facts.text);
20
+ return {
21
+ version: installedVersion(facts, "react"),
22
+ compiler: deps.has("babel-plugin-react-compiler") || texts.some((text) => text.includes("reactCompiler") || text.includes("react-compiler")),
23
+ tanstackQuery: deps.has("@tanstack/react-query"),
24
+ };
25
+ },
26
+ constraints: REACT_SPECS.map(eslintConstraint),
27
+ fixes: fixesOf(REACT_SPECS),
28
+ testing: VITEST_SPEC,
29
+ describe: (profile) => [`react ${reactOf(profile).version ?? "?"}, compiler ${reactOf(profile).compiler ? "on" : "off"}, tanstack query ${reactOf(profile).tanstackQuery ? "yes" : "no"}`],
30
+ });
@@ -0,0 +1,29 @@
1
+ import { THRESHOLDS } from "../../../core/domain/thresholds.js";
2
+ import { own } from "../../js-ts/domain/catalog-specs.js";
3
+ const WEB_ONLY_IMPORTS = ["react-dom", "react-dom/*", "next", "next/*", "node:*", "fs", "fs/*", "path", "child_process", "os", "react-native/Libraries/*", "react-native/Libraries/**"];
4
+ export const REACT_NATIVE_SPECS = Object.freeze([
5
+ {
6
+ id: "rn-no-heavy-inline-styles",
7
+ title: "No heavy inline style objects",
8
+ why: "An inline style object is rebuilt on every render and cannot be validated or reused; StyleSheet.create builds it once.",
9
+ rules: [{ name: own("no-heavy-inline-styles"), options: () => [{ max: THRESHOLDS.inlineStyleProperties.value }], fix: "Move the style to `StyleSheet.create({ name: { ... } })` and reference it: `style={styles.name}`. Inline is allowed only for one or two dynamic values.", probe: "export const A = () => <View style={{ flex: 1, padding: 8, margin: 4 }} />;\n" }],
10
+ },
11
+ {
12
+ id: "rn-virtualized-lists",
13
+ title: "Lists are virtualized",
14
+ why: "A ScrollView renders every child at once; a long list needs FlatList or FlashList to mount only what is visible.",
15
+ rules: [{ name: own("virtualized-lists"), fix: "Replace `<ScrollView>{items.map(...)}</ScrollView>` with `<FlatList data={items} renderItem={...} keyExtractor={...} />` (or FlashList).", probe: "export const A = ({ items }: { items: string[] }) => <ScrollView>{items.map((item) => <Text key={item}>{item}</Text>)}</ScrollView>;\n" }],
16
+ },
17
+ {
18
+ id: "rn-no-logic-in-render",
19
+ title: "No logic inside JSX",
20
+ why: "Filtering, sorting and multi-statement handlers inside JSX run on every render and hide what the component actually does.",
21
+ rules: [{ name: own("no-logic-in-jsx"), fix: "Compute the value above the return (a derived const or a hook) and handle events with a named handler declared before the return.", probe: "export const A = ({ items }: { items: number[] }) => <List data={items.filter((item) => item > 1)} />;\n" }],
22
+ },
23
+ {
24
+ id: "rn-native-import-limits",
25
+ title: "Native code does not import web or Node modules",
26
+ why: "react-dom, next and Node built-ins do not exist in the native runtime; the bundle fails or ships dead code.",
27
+ rules: [{ name: "no-restricted-imports", options: () => [{ patterns: [{ group: WEB_ONLY_IMPORTS, message: "This module does not exist in React Native. Use a native equivalent (react-native, expo-*) or move the code to a web-only package." }] }], fix: "Remove the web/Node import; use the react-native or expo-* equivalent, or move that code to a web-only package." }],
28
+ },
29
+ ]);
@@ -0,0 +1,20 @@
1
+ import { jsTs } from "../../js-ts/domain/data.js";
2
+ export const JEST_EXPO_SPEC = {
3
+ runner: "jest",
4
+ packages: ["jest", "jest-expo", "@types/jest"],
5
+ configFile: "jest.config.cjs",
6
+ script: "jest --coverage",
7
+ coverageSummary: "coverage/coverage-summary.json",
8
+ config: (profile) => {
9
+ const dir = jsTs(profile).paths.srcDir ?? ".";
10
+ return [
11
+ "module.exports = {",
12
+ ' preset: "jest-expo",',
13
+ ` collectCoverageFrom: ["${dir}/**/*.{ts,tsx}", "!${dir}/**/*.test.{ts,tsx}"],`,
14
+ ' coverageReporters: ["json-summary", "text-summary"],',
15
+ ' coverageDirectory: "coverage",',
16
+ "};",
17
+ "",
18
+ ].join("\n");
19
+ },
20
+ };
@@ -0,0 +1,30 @@
1
+ import { definePack } from "../../core/domain/pack-defaults.js";
2
+ import { eslintConstraint } from "../js-ts/app/eslint-constraints.js";
3
+ import { fixesOf } from "../js-ts/domain/catalog-specs.js";
4
+ import { jsTs } from "../js-ts/domain/data.js";
5
+ import { packageRunCommand } from "../js-ts/domain/profile-pure.js";
6
+ import { dependenciesOf, packageField } from "../js-ts/domain/profile.js";
7
+ import { REACT_NATIVE_SPECS } from "./domain/specs.js";
8
+ import { JEST_EXPO_SPEC } from "./domain/testing.js";
9
+ const expoRoutes = ["**/app/**/{_layout,index,+not-found,+html}.{ts,tsx}", "**/app/**/*.{ts,tsx}"];
10
+ export const reactNativePack = definePack({
11
+ id: "react-native",
12
+ title: "React Native and Expo: StyleSheet over heavy inline styles, virtualized lists, no logic in JSX, no web or Node imports",
13
+ extends: ["react"],
14
+ probe: { paths: ["app.json", "app.config.ts", "app.config.js", "eas.json"], json: ["app.json"], text: [], tree: [] },
15
+ detect: (facts) => {
16
+ const deps = dependenciesOf(facts);
17
+ const evidence = ["react-native", "expo"].filter((name) => deps.has(name));
18
+ return { confidence: evidence.length > 0 ? 1 : 0, evidence };
19
+ },
20
+ profile: (facts) => {
21
+ const deps = dependenciesOf(facts);
22
+ const expo = deps.has("expo");
23
+ return { expo, expoRouter: deps.has("expo-router"), main: packageField(facts, "main") ?? null, routeGlobs: expo && deps.has("expo-router") ? expoRoutes : [] };
24
+ },
25
+ constraints: REACT_NATIVE_SPECS.map(eslintConstraint),
26
+ fixes: fixesOf(REACT_NATIVE_SPECS),
27
+ tools: { linter: null, typecheck: null, formatter: null, test: { id: "jest", command: (profile) => (jsTs(profile).scripts.test ? packageRunCommand(jsTs(profile).packageManager, "test") : null) } },
28
+ testing: JEST_EXPO_SPEC,
29
+ describe: () => ["native rules active"],
30
+ });
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@whil/guardrails",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "CLI for AI agents: turns repeated agent mistakes into deterministic checks (lint, types, hooks, CI).",
5
+ "license": "MIT",
6
+ "author": "Ivan Garcia",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/ivanglpz/guardrails.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/ivanglpz/guardrails/issues"
13
+ },
14
+ "homepage": "https://github.com/ivanglpz/guardrails#readme",
15
+ "keywords": [
16
+ "ai",
17
+ "agents",
18
+ "guardrails",
19
+ "eslint",
20
+ "lint",
21
+ "ci",
22
+ "claude-code",
23
+ "typescript",
24
+ "cli"
25
+ ],
26
+ "type": "module",
27
+ "bin": {
28
+ "guardrails": "dist/cli.js"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "catalog-assets",
33
+ "!**/*.test.mjs"
34
+ ],
35
+ "engines": {
36
+ "node": ">=22"
37
+ },
38
+ "scripts": {
39
+ "check-exact-deps": "node scripts/check-exact-deps.mjs",
40
+ "build": "pnpm run clean && tsc -p tsconfig.build.json",
41
+ "typecheck": "tsc --noEmit",
42
+ "lint": "eslint .",
43
+ "test": "vitest run --coverage",
44
+ "self-check": "pnpm run build && node dist/cli.js self-check --offline",
45
+ "prepare": "git config core.hooksPath .githooks || true",
46
+ "check-pack": "node scripts/check-pack.mjs",
47
+ "clean": "node scripts/clean.mjs"
48
+ },
49
+ "devDependencies": {
50
+ "@eslint/js": "10.0.1",
51
+ "@types/node": "26.6.11",
52
+ "@vitest/coverage-v8": "5.1.2",
53
+ "eslint": "10.16.0",
54
+ "typescript": "6.0.3",
55
+ "typescript-eslint": "8.74.0",
56
+ "vitest": "5.1.2"
57
+ },
58
+ "packageManager": "pnpm@11.1.1",
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }