@whil/guardrails 0.0.0-stage → 0.2.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 (146) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +222 -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 +57 -0
  38. package/dist/config/runtime.js +15 -0
  39. package/dist/core/app/analysis.js +74 -0
  40. package/dist/core/app/args.js +46 -0
  41. package/dist/core/app/catalog.js +20 -0
  42. package/dist/core/app/ci-plan.js +14 -0
  43. package/dist/core/app/claude.js +37 -0
  44. package/dist/core/app/commands/add-rule.js +32 -0
  45. package/dist/core/app/commands/agents-md.js +13 -0
  46. package/dist/core/app/commands/apply.js +74 -0
  47. package/dist/core/app/commands/audit.js +38 -0
  48. package/dist/core/app/commands/check.js +33 -0
  49. package/dist/core/app/commands/detect.js +16 -0
  50. package/dist/core/app/commands/init.js +127 -0
  51. package/dist/core/app/commands/learn.js +48 -0
  52. package/dist/core/app/commands/plan.js +40 -0
  53. package/dist/core/app/commands/pr-status.js +66 -0
  54. package/dist/core/app/commands/self-check.js +20 -0
  55. package/dist/core/app/git.js +75 -0
  56. package/dist/core/app/github.js +146 -0
  57. package/dist/core/app/hooks-script.js +27 -0
  58. package/dist/core/app/output.js +17 -0
  59. package/dist/core/app/run.js +32 -0
  60. package/dist/core/app/session.js +18 -0
  61. package/dist/core/app/timing.js +11 -0
  62. package/dist/core/domain/agents-md.js +104 -0
  63. package/dist/core/domain/audit-report.js +7 -0
  64. package/dist/core/domain/changes.js +8 -0
  65. package/dist/core/domain/check-report.js +23 -0
  66. package/dist/core/domain/claude-settings.js +42 -0
  67. package/dist/core/domain/constraint.js +7 -0
  68. package/dist/core/domain/diagnostics.js +3 -0
  69. package/dist/core/domain/errors.js +21 -0
  70. package/dist/core/domain/facts.js +18 -0
  71. package/dist/core/domain/init-report.js +28 -0
  72. package/dist/core/domain/json.js +43 -0
  73. package/dist/core/domain/learn.js +78 -0
  74. package/dist/core/domain/log-parse.js +99 -0
  75. package/dist/core/domain/pack-defaults.js +17 -0
  76. package/dist/core/domain/pack.js +1 -0
  77. package/dist/core/domain/perf.js +65 -0
  78. package/dist/core/domain/pr-comment.js +45 -0
  79. package/dist/core/domain/pr-loop.js +85 -0
  80. package/dist/core/domain/profile.js +25 -0
  81. package/dist/core/domain/protection.js +43 -0
  82. package/dist/core/domain/ratchet.js +40 -0
  83. package/dist/core/domain/registry.js +32 -0
  84. package/dist/core/domain/remote.js +4 -0
  85. package/dist/core/domain/result.js +25 -0
  86. package/dist/core/domain/thresholds.js +9 -0
  87. package/dist/core/domain/types.js +1 -0
  88. package/dist/core/domain/workflows.js +252 -0
  89. package/dist/core/infra/assets.js +7 -0
  90. package/dist/core/infra/backup.js +31 -0
  91. package/dist/core/infra/baseline.js +8 -0
  92. package/dist/core/infra/changes.js +17 -0
  93. package/dist/core/infra/exec.js +15 -0
  94. package/dist/core/infra/facts.js +61 -0
  95. package/dist/core/infra/fs.js +87 -0
  96. package/dist/core/infra/gh.js +32 -0
  97. package/dist/core/infra/hash.js +10 -0
  98. package/dist/core/infra/hooks.js +31 -0
  99. package/dist/core/infra/learn-sources.js +40 -0
  100. package/dist/core/infra/lock.js +102 -0
  101. package/dist/core/infra/pr.js +48 -0
  102. package/dist/core/infra/result-cache.js +49 -0
  103. package/dist/packs/index.js +6 -0
  104. package/dist/packs/js-ts/app/add-rule.js +116 -0
  105. package/dist/packs/js-ts/app/analysis.js +111 -0
  106. package/dist/packs/js-ts/app/bootstrap.js +16 -0
  107. package/dist/packs/js-ts/app/eslint-constraints.js +155 -0
  108. package/dist/packs/js-ts/app/eslint-files.js +56 -0
  109. package/dist/packs/js-ts/app/fixes.js +3 -0
  110. package/dist/packs/js-ts/app/pr-rules.js +30 -0
  111. package/dist/packs/js-ts/app/project.js +87 -0
  112. package/dist/packs/js-ts/app/tests.js +63 -0
  113. package/dist/packs/js-ts/domain/catalog-specs.js +147 -0
  114. package/dist/packs/js-ts/domain/ci.js +47 -0
  115. package/dist/packs/js-ts/domain/data.js +34 -0
  116. package/dist/packs/js-ts/domain/diagnostics-js.js +17 -0
  117. package/dist/packs/js-ts/domain/disables.js +11 -0
  118. package/dist/packs/js-ts/domain/eslint-output.js +46 -0
  119. package/dist/packs/js-ts/domain/eslint-state.js +80 -0
  120. package/dist/packs/js-ts/domain/hooks.js +49 -0
  121. package/dist/packs/js-ts/domain/pr-diagnostics.js +33 -0
  122. package/dist/packs/js-ts/domain/pr-tests.js +27 -0
  123. package/dist/packs/js-ts/domain/profile-pure.js +51 -0
  124. package/dist/packs/js-ts/domain/profile.js +112 -0
  125. package/dist/packs/js-ts/domain/report.js +74 -0
  126. package/dist/packs/js-ts/domain/rule-templates.js +44 -0
  127. package/dist/packs/js-ts/domain/signals.js +14 -0
  128. package/dist/packs/js-ts/domain/testing.js +33 -0
  129. package/dist/packs/js-ts/domain/ts-options.js +16 -0
  130. package/dist/packs/js-ts/index.js +50 -0
  131. package/dist/packs/js-ts/infra/eslint.js +50 -0
  132. package/dist/packs/js-ts/infra/scan.js +25 -0
  133. package/dist/packs/js-ts/infra/tsc.js +29 -0
  134. package/dist/packs/nextjs/domain/data.js +9 -0
  135. package/dist/packs/nextjs/domain/profile.js +21 -0
  136. package/dist/packs/nextjs/domain/specs.js +33 -0
  137. package/dist/packs/nextjs/index.js +23 -0
  138. package/dist/packs/node/domain/specs.js +23 -0
  139. package/dist/packs/node/index.js +26 -0
  140. package/dist/packs/react/domain/data.js +9 -0
  141. package/dist/packs/react/domain/specs.js +63 -0
  142. package/dist/packs/react/index.js +30 -0
  143. package/dist/packs/react-native/domain/specs.js +29 -0
  144. package/dist/packs/react-native/domain/testing.js +20 -0
  145. package/dist/packs/react-native/index.js +30 -0
  146. package/package.json +60 -4
@@ -0,0 +1,29 @@
1
+ const DISABLE_DIRECTIVE = /^\s*eslint-disable(-next-line|-line)?\b/;
2
+ const REASON = /\s--\s+\S/;
3
+
4
+ export const requireDisableReason = {
5
+ meta: {
6
+ type: "problem",
7
+ schema: [],
8
+ messages: {
9
+ missing:
10
+ "An eslint-disable needs a reason: write `eslint-disable-next-line <rule> -- <why the rule can't be satisfied here>`. If the reason is only convenience, fix the code instead.",
11
+ },
12
+ },
13
+ create(context) {
14
+ return {
15
+ Program() {
16
+ context.sourceCode
17
+ .getAllComments()
18
+ .filter(
19
+ (comment) =>
20
+ DISABLE_DIRECTIVE.test(comment.value) &&
21
+ !REASON.test(comment.value),
22
+ )
23
+ .forEach((comment) =>
24
+ context.report({ loc: comment.loc, messageId: "missing" }),
25
+ );
26
+ },
27
+ };
28
+ },
29
+ };
@@ -0,0 +1,35 @@
1
+ const TIMERS = ["setTimeout", "setInterval"];
2
+ const GLOBAL_OBJECTS = ["window", "globalThis", "self"];
3
+
4
+ export const restrictTimers = {
5
+ meta: {
6
+ type: "problem",
7
+ schema: [],
8
+ messages: {
9
+ timer:
10
+ "`{{name}}` is only allowed in hooks and the hook folders: a timer outside them has no cleanup and fires after its screen is gone. Move it into a hook that clears it on unmount (`useDebouncedValue`, `useAutosave`) and call the hook.",
11
+ },
12
+ },
13
+ create(context) {
14
+ const report = (node, name) =>
15
+ context.report({ node, messageId: "timer", data: { name } });
16
+ return {
17
+ CallExpression(node) {
18
+ const { callee } = node;
19
+ if (callee.type === "Identifier" && TIMERS.includes(callee.name))
20
+ report(callee, callee.name);
21
+ if (callee.type !== "MemberExpression" || callee.computed) return;
22
+ if (
23
+ callee.object.type !== "Identifier" ||
24
+ !GLOBAL_OBJECTS.includes(callee.object.name)
25
+ )
26
+ return;
27
+ if (
28
+ callee.property.type === "Identifier" &&
29
+ TIMERS.includes(callee.property.name)
30
+ )
31
+ report(callee.property, callee.property.name);
32
+ },
33
+ };
34
+ },
35
+ };
@@ -0,0 +1,51 @@
1
+ const HOOK_NAME = /^use[A-Z0-9]/;
2
+ const COMPONENT_NAME = /^[A-Z]/;
3
+ const BRANCHES = ["IfStatement", "ConditionalExpression", "LogicalExpression", "SwitchStatement", "TryStatement", "ForStatement", "ForInStatement", "ForOfStatement", "WhileStatement", "DoWhileStatement"];
4
+ const WRAPPERS = ["memo", "forwardRef"];
5
+
6
+ function hookName(callee) {
7
+ if (callee.type === "Identifier") return callee.name;
8
+ if (callee.type === "MemberExpression" && callee.object.type === "Identifier" && callee.object.name === "React" && callee.property.type === "Identifier") return callee.property.name;
9
+ return null;
10
+ }
11
+
12
+ function functionName(fn) {
13
+ if (fn.id) return fn.id.name;
14
+ const parent = fn.parent;
15
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name;
16
+ if (parent.type === "CallExpression" && parent.callee.type === "Identifier" && WRAPPERS.includes(parent.callee.name)) return "Wrapped";
17
+ return null;
18
+ }
19
+
20
+ function isFunction(node) {
21
+ return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
22
+ }
23
+
24
+ export const rulesOfHooks = {
25
+ meta: {
26
+ type: "problem",
27
+ schema: [],
28
+ messages: {
29
+ conditional: "`{{name}}` is called conditionally or in a loop. Hooks must run in the same order on every render. Move the call to the top level of the component or hook, before any early return, and put the condition inside the hook or in the value it returns.",
30
+ nested: "`{{name}}` is called outside a component or a custom hook. Hooks only work during render of a component (`PascalCase`) or inside another hook (`useName`). Call it from the component and pass the result down, or rename this function `use...` if it is a hook.",
31
+ },
32
+ },
33
+ create(context) {
34
+ return {
35
+ CallExpression(node) {
36
+ const name = hookName(node.callee);
37
+ if (name === null || !HOOK_NAME.test(name)) return;
38
+ const ancestors = context.sourceCode.getAncestors(node).toReversed();
39
+ const owner = ancestors.find(isFunction);
40
+ if (owner === undefined) return;
41
+ const ownerName = functionName(owner);
42
+ const inside = ancestors.slice(0, ancestors.indexOf(owner));
43
+ if (ownerName === null || !(COMPONENT_NAME.test(ownerName) || HOOK_NAME.test(ownerName))) {
44
+ context.report({ node, messageId: "nested", data: { name } });
45
+ return;
46
+ }
47
+ if (inside.some((ancestor) => BRANCHES.includes(ancestor.type))) context.report({ node, messageId: "conditional", data: { name } });
48
+ },
49
+ };
50
+ },
51
+ };
@@ -0,0 +1,18 @@
1
+ export const thinApiRoutes = {
2
+ meta: {
3
+ type: "suggestion",
4
+ schema: [{ type: "object", properties: { max: { type: "integer" } }, additionalProperties: false }],
5
+ messages: {
6
+ long: "This route handler has {{lines}} lines of code (the limit is {{max}}). A handler parses the request, calls a service and returns the response. Move the logic to a service module.",
7
+ },
8
+ },
9
+ create(context) {
10
+ const max = context.options[0]?.max ?? 60;
11
+ return {
12
+ "Program:exit": (program) => {
13
+ const lines = context.sourceCode.lines.filter((line) => line.trim() !== "").length;
14
+ if (lines > max) context.report({ node: program, messageId: "long", data: { lines: String(lines), max: String(max) } });
15
+ },
16
+ };
17
+ },
18
+ };
@@ -0,0 +1,18 @@
1
+ export const thinRoutes = {
2
+ meta: {
3
+ type: "suggestion",
4
+ schema: [{ type: "object", properties: { max: { type: "integer" } }, additionalProperties: false }],
5
+ messages: {
6
+ long: "This route file has {{lines}} lines of code (the limit is {{max}}). A route only wires data to a view. Move the logic to a feature module or a server function and keep the route as composition: fetch, then render a view component.",
7
+ },
8
+ },
9
+ create(context) {
10
+ const max = context.options[0]?.max ?? 60;
11
+ return {
12
+ "Program:exit": (program) => {
13
+ const lines = context.sourceCode.lines.filter((line) => line.trim() !== "").length;
14
+ if (lines > max) context.report({ node: program, messageId: "long", data: { lines: String(lines), max: String(max) } });
15
+ },
16
+ };
17
+ },
18
+ };
@@ -0,0 +1,32 @@
1
+ function hasMapCall(node) {
2
+ if (node === null || typeof node !== "object") return false;
3
+ if (
4
+ node.type === "CallExpression" &&
5
+ node.callee.type === "MemberExpression" &&
6
+ !node.callee.computed &&
7
+ node.callee.property.type === "Identifier" &&
8
+ node.callee.property.name === "map"
9
+ ) {
10
+ return true;
11
+ }
12
+ return Object.entries(node)
13
+ .filter(([key]) => key !== "parent")
14
+ .some(([, child]) => (Array.isArray(child) ? child.some(hasMapCall) : hasMapCall(child)));
15
+ }
16
+
17
+ export const virtualizedLists = {
18
+ meta: {
19
+ type: "problem",
20
+ schema: [],
21
+ messages: {
22
+ scrollMap: "This `ScrollView` renders a mapped list, so every item mounts at once. Use `FlatList` (or FlashList) with `data`, `renderItem` and `keyExtractor` so only visible rows are mounted.",
23
+ },
24
+ },
25
+ create(context) {
26
+ return {
27
+ "JSXElement[openingElement.name.name='ScrollView']": (node) => {
28
+ if (node.children.some(hasMapCall)) context.report({ node: node.openingElement, messageId: "scrollMap" });
29
+ },
30
+ };
31
+ },
32
+ };
@@ -0,0 +1,13 @@
1
+ #!/bin/sh
2
+ subject=$(head -n 1 "$1")
3
+
4
+ case "$subject" in
5
+ Merge\ * | Revert\ * | fixup!\ * | squash!\ *) exit 0 ;;
6
+ esac
7
+
8
+ pattern='^(feat|fix|refactor|chore|docs|style|test|perf|ci|build|revert)(\([a-z0-9-]+\))?!?: .+'
9
+ if ! printf '%s' "$subject" | grep -Eq "$pattern"; then
10
+ echo "commit-msg: the subject must follow Conventional Commits: <type>(<scope>): <description>" >&2
11
+ echo "types: feat fix refactor chore docs style test perf ci build revert" >&2
12
+ exit 1
13
+ fi
@@ -0,0 +1,26 @@
1
+ #!/bin/sh
2
+
3
+ if [ -f pnpm-lock.yaml ]; then pm=pnpm
4
+ elif [ -f yarn.lock ]; then pm=yarn
5
+ elif [ -f bun.lock ] || [ -f bun.lockb ]; then pm=bun
6
+ else pm=npm
7
+ fi
8
+ run_exec() { if [ "$pm" = npm ]; then npx --no-install "$@"; else "$pm" exec "$@"; fi; }
9
+ has_script() { node -e 'process.exit(require("./package.json").scripts?.[process.argv[1]] ? 0 : 1)' "$1" 2>/dev/null; }
10
+
11
+ if [ -f scripts/check-exact-deps.mjs ] && git diff --cached --name-only | grep -qx 'package.json'; then
12
+ node scripts/check-exact-deps.mjs || exit 1
13
+ fi
14
+
15
+ files=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^(src|app|scripts)/.*\.(ts|tsx|js|jsx|mjs)$')
16
+
17
+ if [ -n "$files" ] && [ -f package.json ]; then
18
+ echo "pre-commit: eslint on staged files"
19
+ # shellcheck disable=SC2086
20
+ run_exec eslint $files || exit 1
21
+ fi
22
+
23
+ if has_script typecheck; then
24
+ echo "pre-commit: typecheck"
25
+ "$pm" run typecheck || exit 1
26
+ fi
@@ -0,0 +1,26 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ const DEPENDENCY_FIELDS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
4
+ const EXACT_VERSION = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
5
+ const PROTOCOL_VERSION = /^(workspace|link|file|npm|catalog):/;
6
+
7
+ function findLooseDependencies(pkg) {
8
+ return DEPENDENCY_FIELDS.flatMap((field) =>
9
+ Object.entries(pkg[field] ?? {})
10
+ .filter(([, range]) => !EXACT_VERSION.test(range) && !PROTOCOL_VERSION.test(range))
11
+ .map(([name, range]) => ({ field, name, range })),
12
+ );
13
+ }
14
+
15
+ const loose = findLooseDependencies(JSON.parse(readFileSync("package.json", "utf8")));
16
+
17
+ if (loose.length > 0) {
18
+ console.error(
19
+ [
20
+ "check-exact-deps: package.json tiene versiones con rango. Todo el repo va con versión exacta para que el lockfile y package.json digan lo mismo y una actualización sea siempre un cambio explícito.",
21
+ ...loose.map(({ field, name, range }) => ` ${field}.${name}: "${range}"`),
22
+ "Arreglo: escribe la versión exacta que tiene el lockfile (sin ^ ni ~), o instala con `pnpm add --save-exact <paquete>@<versión>`.",
23
+ ].join("\n"),
24
+ );
25
+ process.exit(1);
26
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ import { appError } from "./core/domain/errors.js";
3
+ import { parseCli } from "./core/app/args.js";
4
+ import { emitError, emitResult } from "./core/app/output.js";
5
+ import { runCommand } from "./core/app/run.js";
6
+ import { timed } from "./core/app/timing.js";
7
+ import { PACKS } from "./packs/index.js";
8
+ const HELP = `guardrails: turns repeated agent mistakes into deterministic checks.
9
+
10
+ One step: init. Flow: detect -> plan -> apply <id> -> check (loop) -> audit. Every command takes --json, never prompts.
11
+
12
+ init [--dry-run] [--install] [--owner @u]
13
+ detect, pick packs, install the strongest set, set the ratchet baseline
14
+ learn propose new rules from check history, fix commits, reviews and CI failures
15
+ detect read the repo, activate packs, write .guardrails/profile.json
16
+ plan gaps between the repo and the constraint catalog
17
+ apply <id> [--dry-run] install a constraint and verify it
18
+ codeowners needs --owner @user; branch-protection --execute runs gh api
19
+ check [paths...] [--no-cache] [--lock-timeout s]
20
+ every active pack's linters, typechecks and rules: diagnostics with file, line, rule, fix;
21
+ with paths, only those files (tsc errors filtered by path); one heavy run per machine, results cached by tree hash
22
+ add-rule <name> --message ... [--selector --bad --good --files --pack] | --promote
23
+ scaffold a lint rule + test from a correction (the pack that owns rules)
24
+ audit metrics per pack: violations, suppressions without reason, rules in warn
25
+ self-check check + audit in one run (tools run once, in parallel)
26
+ agents-md write AGENTS.md describing this flow
27
+ pr-status [--pr N --wait --comment --ignore a,b --ignore-pending]
28
+ failing checks of the current PR as JSON: check, file, line, rule or test, fix
29
+ pr-repair [--pr N --wait] pr-status plus the attempt counter: fix, push, run again; escalates after 3
30
+
31
+ Global flags: --json --cwd <dir> -h (audit, self-check: --offline skips the GitHub query)
32
+ Exit codes: 0 ok, 1 findings, 2 usage, 3 precondition/conflict/missing dependency, 4 verification failed.
33
+ Env: GUARDRAILS_MAX_JOBS (heavy runs per machine, default 1), GUARDRAILS_LOCK_TIMEOUT_MS, GUARDRAILS_MAX_OLD_SPACE_MB, GUARDRAILS_CACHE_DIR.
34
+ JSON output includes timingMs for the command (check, audit and self-check add phasesMs).
35
+ `;
36
+ async function main(argv) {
37
+ const json = argv.includes("--json");
38
+ const parsed = parseCli(argv, process.cwd());
39
+ if (!parsed.ok)
40
+ return emitError(argv[0] ?? "help", parsed.error, json, 0);
41
+ if (parsed.value.command === "help")
42
+ return { stdout: HELP, stderr: "", exit: 0 };
43
+ const args = parsed.value;
44
+ const run = await timed(() => runCommand(args, PACKS));
45
+ return run.value.ok ? emitResult(args.command, run.value.value, args.json, run.ms) : emitError(args.command, run.value.error, args.json, run.ms);
46
+ }
47
+ function finish(out) {
48
+ process.stderr.write(out.stderr);
49
+ process.stdout.write(out.stdout, () => process.exit(out.exit));
50
+ }
51
+ function internalFailure(cause) {
52
+ const error = appError("internal", cause instanceof Error ? cause.message : String(cause), { fix: "Report this as a bug in guardrails with the command you ran." });
53
+ return { stdout: "", stderr: `error[${error.code}]: ${error.message}\n fix: ${error.fix}\n`, exit: 4 };
54
+ }
55
+ main(process.argv.slice(2)).then(finish, (cause) => {
56
+ finish(internalFailure(cause));
57
+ });
@@ -0,0 +1,15 @@
1
+ import { homedir, platform } from "node:os";
2
+ import { cacheDirFor, DEFAULT_LOCK_TIMEOUT_MS, DEFAULT_MAX_JOBS, DEFAULT_MAX_OLD_SPACE_MB, mergeNodeOptions, positiveInt } from "../core/domain/perf.js";
3
+ export function readRuntime() {
4
+ const env = process.env;
5
+ return {
6
+ maxJobs: positiveInt(env["GUARDRAILS_MAX_JOBS"], DEFAULT_MAX_JOBS),
7
+ lockTimeoutMs: positiveInt(env["GUARDRAILS_LOCK_TIMEOUT_MS"], DEFAULT_LOCK_TIMEOUT_MS),
8
+ maxOldSpaceMb: positiveInt(env["GUARDRAILS_MAX_OLD_SPACE_MB"], DEFAULT_MAX_OLD_SPACE_MB),
9
+ cacheDir: cacheDirFor({ override: env["GUARDRAILS_CACHE_DIR"], xdg: env["XDG_CACHE_HOME"], home: homedir(), platform: platform() }),
10
+ };
11
+ }
12
+ export function childEnv() {
13
+ const env = process.env;
14
+ return { ...env, NODE_OPTIONS: mergeNodeOptions(env["NODE_OPTIONS"], readRuntime().maxOldSpaceMb) };
15
+ }
@@ -0,0 +1,74 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { readRuntime } from "../../config/runtime.js";
5
+ import { cacheable, normalizeScope } from "../domain/perf.js";
6
+ import { ok } from "../domain/result.js";
7
+ import { repoKey, sha256 } from "../infra/hash.js";
8
+ import { acquireLease, pidAlive } from "../infra/lock.js";
9
+ import { readCached, treeKey, writeCached } from "../infra/result-cache.js";
10
+ import { flagBool, flagString } from "./args.js";
11
+ import { timed } from "./timing.js";
12
+ export function optionsFrom(args) {
13
+ const seconds = Number(flagString(args, "lock-timeout"));
14
+ return { noCache: flagBool(args, "no-cache"), lockTimeoutMs: Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null };
15
+ }
16
+ function cliVersion() {
17
+ const parsed = JSON.parse(readFileSync(join(fileURLToPath(new URL(".", import.meta.url)), "..", "..", "..", "package.json"), "utf8"));
18
+ const version = typeof parsed === "object" && parsed !== null ? parsed.version : undefined;
19
+ return typeof version === "string" ? version : "unknown";
20
+ }
21
+ function keyOf(root, profile, packs, scope) {
22
+ const extra = [`cli:${cliVersion()}`, `packs:${packs.map((pack) => pack.id).join(",")}`, `scope:${scope.join(",")}`, `node:${process.version}`];
23
+ return treeKey(root, extra, profile.git.baseBranch);
24
+ }
25
+ function build(root, profile, packs, scope, results, phasesMs, cached) {
26
+ return { root, profile, packs, results, phasesMs, full: scope.length === 0, cached };
27
+ }
28
+ async function execute(root, profile, packs, scope) {
29
+ const wall = await timed(() => Promise.all(packs.map((pack) => pack.analyze({ root, profile, packs }, scope))));
30
+ const phases = wall.value.flatMap((result) => Object.entries(result.phasesMs).map(([name, ms]) => [`${result.pack}.${name}`, ms]));
31
+ return build(root, profile, packs, scope, wall.value, { ...Object.fromEntries(phases), parallelMs: wall.ms }, false);
32
+ }
33
+ function fromCache(target) {
34
+ const hit = target.key === null ? null : readCached(target.slot, target.key);
35
+ return hit === null ? null : build(target.root, target.profile, target.packs, target.scope, hit, { cacheHit: 0 }, true);
36
+ }
37
+ async function runLocked(target) {
38
+ const settled = fromCache(target);
39
+ if (settled !== null)
40
+ return settled;
41
+ const analysis = await execute(target.root, target.profile, target.packs, target.scope);
42
+ const unchanged = target.key !== null && keyOf(target.root, target.profile, target.packs, target.scope) === target.key;
43
+ if (target.key !== null && unchanged && cacheable(analysis.results))
44
+ writeCached(target.slot, target.key, analysis.results);
45
+ return analysis;
46
+ }
47
+ export async function analyze(root, profile, packs, paths, options) {
48
+ const runtime = readRuntime();
49
+ const scope = normalizeScope(root, paths);
50
+ const slot = { dir: runtime.cacheDir, repoKey: repoKey(root), scopeKey: sha256([packs.map((pack) => pack.id).join(","), "\0", scope.join("\0")]).slice(0, 16) };
51
+ const target = { root, profile, packs, scope, slot, key: options.noCache ? null : keyOf(root, profile, packs, scope) };
52
+ const hit = fromCache(target);
53
+ if (hit !== null)
54
+ return ok(hit);
55
+ const lease = await acquireLease({
56
+ dir: join(runtime.cacheDir, "locks"),
57
+ repoKey: slot.repoKey,
58
+ repo: root,
59
+ maxJobs: runtime.maxJobs,
60
+ timeoutMs: options.lockTimeoutMs ?? runtime.lockTimeoutMs,
61
+ pollMs: 250,
62
+ log: (message) => process.stderr.write(`${message}\n`),
63
+ isAlive: pidAlive,
64
+ pid: process.pid,
65
+ });
66
+ if (!lease.ok)
67
+ return lease;
68
+ try {
69
+ return ok(await runLocked(target));
70
+ }
71
+ finally {
72
+ lease.value.release();
73
+ }
74
+ }
@@ -0,0 +1,46 @@
1
+ import { parseArgs } from "node:util";
2
+ import { appError } from "../domain/errors.js";
3
+ import { err, fromThrowing, ok } from "../domain/result.js";
4
+ export const COMMANDS = ["detect", "plan", "apply", "check", "add-rule", "audit", "agents-md", "self-check", "init", "learn", "pr-status", "pr-repair"];
5
+ const OPTIONS = {
6
+ json: { type: "boolean" },
7
+ cwd: { type: "string" },
8
+ help: { type: "boolean", short: "h" },
9
+ "fail-on-gaps": { type: "boolean" },
10
+ "dry-run": { type: "boolean" },
11
+ owner: { type: "string" },
12
+ execute: { type: "boolean" },
13
+ offline: { type: "boolean" },
14
+ from: { type: "string" },
15
+ message: { type: "string" },
16
+ selector: { type: "string" },
17
+ bad: { type: "string" },
18
+ good: { type: "string" },
19
+ files: { type: "string" },
20
+ promote: { type: "boolean" },
21
+ pack: { type: "string" },
22
+ install: { type: "boolean" },
23
+ pr: { type: "string" },
24
+ wait: { type: "boolean" },
25
+ comment: { type: "boolean" },
26
+ ignore: { type: "string" },
27
+ "ignore-pending": { type: "boolean" },
28
+ "no-cache": { type: "boolean" },
29
+ "lock-timeout": { type: "string" },
30
+ };
31
+ const isCommand = (value) => COMMANDS.includes(value);
32
+ export function parseCli(argv, defaultCwd) {
33
+ const parsed = fromThrowing(() => parseArgs({ args: [...argv], options: OPTIONS, allowPositionals: true, strict: true }), (cause) => appError("usage", cause instanceof Error ? cause.message : "invalid arguments", { fix: "Run `guardrails --help` for the commands and flags." }));
34
+ if (!parsed.ok)
35
+ return parsed;
36
+ const [first, ...rest] = parsed.value.positionals;
37
+ const base = { positionals: rest, flags: { ...parsed.value.values }, json: parsed.value.values.json === true, cwd: parsed.value.values.cwd ?? defaultCwd };
38
+ if (first === undefined || parsed.value.values.help === true)
39
+ return ok({ ...base, command: "help", positionals: [] });
40
+ return isCommand(first) ? ok({ ...base, command: first }) : err(appError("usage", `unknown command "${first}"`, { fix: `Use one of: ${COMMANDS.join(", ")}.` }));
41
+ }
42
+ export function flagString(args, name) {
43
+ const value = args.flags[name];
44
+ return typeof value === "string" ? value : undefined;
45
+ }
46
+ export const flagBool = (args, name) => args.flags[name] === true;
@@ -0,0 +1,20 @@
1
+ import { appError } from "../domain/errors.js";
2
+ import { err, ok } from "../domain/result.js";
3
+ import { claudeCheckOnEdit, claudeDenyBypass } from "./claude.js";
4
+ import { gitCommitMsg, gitPreCommit } from "./git.js";
5
+ import { GITHUB_CONSTRAINTS } from "./github.js";
6
+ const CORE_CONSTRAINTS = Object.freeze([claudeCheckOnEdit, claudeDenyBypass, gitPreCommit, gitCommitMsg, ...GITHUB_CONSTRAINTS]);
7
+ export function catalogOf(packs) {
8
+ const entries = [
9
+ ...packs.flatMap((pack) => pack.constraints.map((constraint) => ({ constraint, pack: pack.id }))),
10
+ ...CORE_CONSTRAINTS.map((constraint) => ({ constraint, pack: "core" })),
11
+ ];
12
+ return entries.filter((entry, index) => entries.findIndex((other) => other.constraint.id === entry.constraint.id) === index);
13
+ }
14
+ export function findConstraint(packs, id) {
15
+ const catalog = catalogOf(packs);
16
+ const found = catalog.find((entry) => entry.constraint.id === id);
17
+ return found === undefined
18
+ ? err(appError("unknown-constraint", `no constraint called "${id}"`, { fix: `Run \`guardrails plan --json\` for the ids. Available: ${catalog.map((entry) => entry.constraint.id).join(", ")}.` }))
19
+ : ok(found);
20
+ }
@@ -0,0 +1,14 @@
1
+ export function commandsOf(packs) {
2
+ return packs.map((pack) => pack.commands).find((commands) => commands !== null) ?? null;
3
+ }
4
+ const STATUS_ARGS = "pr-status --json --comment --ignore status --ignore-pending";
5
+ export function ciPlan(profile, packs) {
6
+ const contributions = packs.flatMap((pack) => (pack.ci === null ? [] : [pack.ci]));
7
+ return {
8
+ setup: contributions.flatMap((ci) => ci.setup(profile)),
9
+ steps: contributions.flatMap((ci) => ci.steps(profile)),
10
+ cliCheck: commandsOf(packs)?.exec(profile, "guardrails", "check --json") ?? "guardrails check --json",
11
+ cliStatus: commandsOf(packs)?.exec(profile, "guardrails", STATUS_ARGS) ?? `guardrails ${STATUS_ARGS}`,
12
+ dependabot: contributions.flatMap((ci) => ci.dependabot(profile)),
13
+ };
14
+ }
@@ -0,0 +1,37 @@
1
+ import { DENY_BYPASS, HOOK_PATH, SETTINGS_PATH, denyList, hasCheckHook, withCheckHook, withDeny } from "../domain/claude-settings.js";
2
+ import { andThen, map, ok } from "../domain/result.js";
3
+ import { claudeEditScript } from "./hooks-script.js";
4
+ import { editJsonFile, exists, readJsonRecord, writeIfAbsent } from "../infra/fs.js";
5
+ import { shellSyntax } from "../infra/hooks.js";
6
+ export const claudeCheckOnEdit = {
7
+ id: "claude-check-on-edit",
8
+ title: "Claude hook: linters and typechecks after every edit",
9
+ layer: "claude",
10
+ why: "The closest layer to the agent: it sees the actionable error in the same turn it made the mistake.",
11
+ notApplicable: () => null,
12
+ requires: () => [],
13
+ isInstalled: ({ root }) => exists(root, HOOK_PATH) && hasCheckHook(readJsonRecord(root, SETTINGS_PATH)),
14
+ install: ({ root, profile, packs }) => andThen(writeIfAbsent(root, HOOK_PATH, claudeEditScript(profile, packs), "claude-check-on-edit", 0o755), (hook) => andThen(editJsonFile(root, SETTINGS_PATH, withCheckHook, true), (settings) => ok({ changes: [hook, settings], notes: [], violations: [], levels: {} }))),
15
+ verify: ({ root }) => {
16
+ const syntax = shellSyntax(root, HOOK_PATH);
17
+ return [
18
+ { name: "hook script syntax", ok: syntax.ok, detail: syntax.detail },
19
+ { name: "settings.json registers the hook", ok: hasCheckHook(readJsonRecord(root, SETTINGS_PATH)), detail: `PostToolUse in ${SETTINGS_PATH}` },
20
+ ];
21
+ },
22
+ };
23
+ export const claudeDenyBypass = {
24
+ id: "claude-deny-bypass",
25
+ title: "Claude permissions deny hook bypass and direct pushes to the base branch",
26
+ layer: "claude",
27
+ why: "The agent cannot skip hooks with --no-verify, force-push, change hooksPath or push to main; it must open a PR.",
28
+ notApplicable: () => null,
29
+ requires: () => [],
30
+ isInstalled: ({ root }) => DENY_BYPASS.every((entry) => denyList(readJsonRecord(root, SETTINGS_PATH)).includes(entry)),
31
+ install: ({ root }) => map(editJsonFile(root, SETTINGS_PATH, withDeny, true), (change) => ({ changes: [change], notes: [], violations: [], levels: {} })),
32
+ verify: ({ root }) => {
33
+ const present = denyList(readJsonRecord(root, SETTINGS_PATH));
34
+ const missing = DENY_BYPASS.filter((entry) => !present.includes(entry));
35
+ return [{ name: "deny entries present", ok: missing.length === 0, detail: missing.length === 0 ? `${DENY_BYPASS.length} entries` : `missing: ${missing.join(", ")}` }];
36
+ },
37
+ };
@@ -0,0 +1,32 @@
1
+ import { appError } from "../../domain/errors.js";
2
+ import { andThen, err } from "../../domain/result.js";
3
+ import { flagBool, flagString } from "../args.js";
4
+ import { buildSession } from "../session.js";
5
+ function requestFrom(args, name) {
6
+ return {
7
+ name,
8
+ message: flagString(args, "message") ?? "",
9
+ selector: flagString(args, "selector") ?? "",
10
+ bad: flagString(args, "bad") ?? "",
11
+ good: flagString(args, "good") ?? "",
12
+ files: (flagString(args, "files") ?? "").split(",").filter((item) => item !== ""),
13
+ promote: flagBool(args, "promote"),
14
+ from: flagString(args, "from"),
15
+ };
16
+ }
17
+ const NAME_PATTERN = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;
18
+ export function addRuleCommand(args, registry) {
19
+ return andThen(buildSession(args.cwd, registry), ({ profile, packs }) => {
20
+ const owner = flagString(args, "pack");
21
+ const author = packs.filter((pack) => pack.addRule !== undefined && (owner === undefined || pack.id === owner)).at(-1);
22
+ if (author?.addRule === undefined) {
23
+ return err(appError("not-applicable", "no active pack can author rules", { fix: `Active packs: ${packs.map((pack) => pack.id).join(", ")}. Pass --pack <id> for a pack that supports add-rule.` }));
24
+ }
25
+ const [name] = args.positionals;
26
+ if (name === undefined || !NAME_PATTERN.test(name)) {
27
+ return err(appError("invalid-name", `rule name "${name ?? ""}" must be kebab-case`, { fix: "Pass a kebab-case name, e.g. `guardrails add-rule no-fetch-in-components --message ...`." }));
28
+ }
29
+ const request = requestFrom(args, name);
30
+ return author.addRule({ root: args.cwd, profile, packs }, request);
31
+ });
32
+ }
@@ -0,0 +1,13 @@
1
+ import { mergeAgentsMd, renderAgentsBlock } from "../../domain/agents-md.js";
2
+ import { EXIT } from "../../domain/errors.js";
3
+ import { map } from "../../domain/result.js";
4
+ import { readText, writeManaged } from "../../infra/fs.js";
5
+ import { commandsOf } from "../ci-plan.js";
6
+ import { buildSession } from "../session.js";
7
+ export function agentsMdCommand(root, registry) {
8
+ return map(buildSession(root, registry), ({ profile, packs }) => {
9
+ const exec = (args) => commandsOf(packs)?.exec(profile, "guardrails", args) ?? `guardrails ${args}`;
10
+ const change = writeManaged(root, "AGENTS.md", mergeAgentsMd(readText(root, "AGENTS.md"), renderAgentsBlock(profile, packs, exec)));
11
+ return { exit: EXIT.ok, data: { change, file: "AGENTS.md" }, text: `AGENTS.md ${change.action}` };
12
+ });
13
+ }