guardrail

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

/guardrail

/guardrail

Generate custom lint rules that enforce architectural decisions at edit time.
生成可在编辑阶段强制执行架构决策的自定义Lint规则。

Philosophy

设计理念

Lint rules are the highest-leverage codification target. They're cheaper than hooks (no custom Python), more durable than CLAUDE.md (automated, not advisory), and work in CI too (not just Claude Code). A lint rule catches violations the moment code is written — and
fast-feedback.py
surfaces the error immediately so Claude self-corrects.
Lint规则是投入产出比最高的代码规范落地方式。它们比钩子更轻量(无需自定义Python代码),比CLAUDE.md更持久(自动化执行,而非仅作为参考),同时也能在CI中运行(不只是在Claude Code里)。Lint规则能在代码编写的瞬间就发现违规问题——而
fast-feedback.py
会立即显示错误,让Claude可以自我修正。

When to Use

适用场景

  • Import boundaries ("all DB access through repository layer")
  • API conventions ("routes must start with /api/v1")
  • Deprecated pattern blocking ("no direct fetch, use apiClient")
  • Auth enforcement ("handlers must call requireAuth")
  • Naming conventions that go beyond basic linting
  • 导入边界约束(如“所有数据库访问必须通过仓储层”)
  • API约定强制执行(如“路由必须以/api/v1开头”)
  • 已弃用模式拦截(如“禁止直接使用fetch,需使用apiClient”)
  • 权限验证强制执行(如“处理器必须调用requireAuth”)
  • 基础Lint规则未覆盖的命名约定

Workflow

工作流程

Phase 1: Accept Pattern

阶段1:确认规则模式

Parse the input. It can be:
  • Natural language: "all database queries must go through the repository layer"
  • Code example: "this import is wrong:
    import { db } from './db'
    "
  • Discovery mode: scan codebase for architectural invariants (when invoked by
    /tune-repo
    )
Clarify the constraint:
  • What EXACTLY should be flagged? (imports, function calls, patterns)
  • What's the fix? (alternative import, wrapper function)
  • Are there exceptions? (test files, migrations, the repository itself)
解析输入内容,输入可以是:
  • 自然语言描述:“所有数据库查询必须通过仓储层执行”
  • 代码示例:“此导入违规:
    import { db } from './db'
  • 发现模式:扫描代码库以识别架构不变量(当由
    /tune-repo
    调用时)
明确约束细节:
  • 具体需要标记哪些内容?(导入语句、函数调用、代码模式)
  • 修复方案是什么?(替代导入、包装函数)
  • 是否存在例外情况?(测试文件、迁移脚本、仓储层自身)

Phase 2: Choose Engine

阶段2:选择规则引擎

CriterionESLintast-grep
LanguageJS/TS onlyAny (Python, Go, Rust, etc.)
FixableYes (auto-fix)Yes (rewrite)
TestingRuleTester built-inYAML snapshot tests
ConfigFlat config pluginsgconfig.yml
SpeedFastVery fast
Default: ESLint for JS/TS projects, ast-grep for everything else. If
--engine
is specified, use that.
评估维度ESLintast-grep
支持语言仅JS/TS任意语言(Python、Go、Rust等)
自动修复支持(auto-fix)支持(rewrite)
测试能力内置RuleTesterYAML快照测试
配置方式Flat config插件sgconfig.yml
运行速度极快
默认规则:JS/TS项目使用ESLint,其他项目使用ast-grep。 如果指定了
--engine
参数,则使用指定的引擎。

Phase 3: Generate Rule

阶段3:生成规则

Read the reference docs for the chosen engine:
  • ESLint:
    references/eslint-rule-anatomy.md
  • ast-grep:
    references/ast-grep-rule-anatomy.md
Read the appropriate template:
  • ESLint:
    templates/eslint-rule.js
    +
    templates/eslint-rule-test.js
  • ast-grep:
    templates/ast-grep-rule.yml
Generate:
  1. Rule implementation with clear error message and fix suggestion
  2. Rule metadata (docs URL, fixable, schema)
  3. Test cases (valid AND invalid examples from the actual codebase)
阅读所选引擎的参考文档:
  • ESLint:
    references/eslint-rule-anatomy.md
  • ast-grep:
    references/ast-grep-rule-anatomy.md
读取对应的模板文件:
  • ESLint:
    templates/eslint-rule.js
    +
    templates/eslint-rule-test.js
  • ast-grep:
    templates/ast-grep-rule.yml
生成以下内容:
  1. 规则实现代码,包含清晰的错误提示和修复建议
  2. 规则元数据(文档链接、是否支持自动修复、配置 schema)
  3. 测试用例(来自实际代码库的合法与非法示例)

Phase 4: Test

阶段4:测试规则

ESLint:
bash
undefined
ESLint测试:
bash
undefined

Run RuleTester

运行RuleTester

node guardrails/rules/<rule-name>.test.js
node guardrails/rules/<rule-name>.test.js

Or if project uses a test runner:

如果项目使用测试运行器:

npx vitest run guardrails/rules/<rule-name>.test.js

**ast-grep:**
```bash
sg scan --config guardrails/sgconfig.yml --test
Also verify against the real codebase:
bash
undefined
npx vitest run guardrails/rules/<rule-name>.test.js

**ast-grep测试:**
```bash
sg scan --config guardrails/sgconfig.yml --test
同时在真实代码库中验证:
bash
undefined

ESLint: run rule on entire project, expect 0 or known violations

ESLint:在整个项目中运行规则,预期0个或已知数量的违规

npx eslint --no-warn-ignored --rule 'guardrails/<rule-name>: error' .
npx eslint --no-warn-ignored --rule 'guardrails/<rule-name>: error' .

ast-grep: scan project

ast-grep:扫描整个项目

sg scan --config guardrails/sgconfig.yml
undefined
sg scan --config guardrails/sgconfig.yml
undefined

Phase 5: Install

阶段5:安装配置

Create the
guardrails/
directory structure if it doesn't exist:
guardrails/
  README.md              # Catalog of all custom rules
  index.js               # ESLint local plugin barrel (JS/TS projects)
  sgconfig.yml           # ast-grep config (if non-JS rules exist)
  rules/
    <rule-name>.js       # ESLint rule implementation
    <rule-name>.test.js  # ESLint RuleTester
    <rule-name>.yml      # ast-grep rule
ESLint integration (flat config, zero npm dependencies):
javascript
// guardrails/index.js
import noDirectDbImport from "./rules/no-direct-db-import.js";

export default {
  rules: {
    "no-direct-db-import": noDirectDbImport,
  },
};
javascript
// eslint.config.js — add to existing config
import guardrails from "./guardrails/index.js";

export default [
  // ... existing config
  {
    plugins: { guardrails },
    rules: {
      "guardrails/no-direct-db-import": "error",
    },
  },
];
ast-grep integration:
yaml
undefined
如果
guardrails/
目录结构不存在,则创建该结构:
guardrails/
  README.md              # 所有自定义规则的目录
  index.js               # ESLint本地插件入口文件(JS/TS项目)
  sgconfig.yml           # ast-grep配置文件(如果存在非JS规则)
  rules/
    <rule-name>.js       # ESLint规则实现
    <rule-name>.test.js  # ESLint RuleTester测试文件
    <rule-name>.yml      # ast-grep规则文件
ESLint集成(Flat config,零npm依赖):
javascript
// guardrails/index.js
import noDirectDbImport from "./rules/no-direct-db-import.js";

export default {
  rules: {
    "no-direct-db-import": noDirectDbImport,
  },
};
javascript
// eslint.config.js — 添加到现有配置中
import guardrails from "./guardrails/index.js";

export default [
  // ... 现有配置
  {
    plugins: { guardrails },
    rules: {
      "guardrails/no-direct-db-import": "error",
    },
  },
];
ast-grep集成:
yaml
undefined

guardrails/sgconfig.yml

guardrails/sgconfig.yml

ruleDirs:
  • rules
undefined
ruleDirs:
  • rules
undefined

Phase 6: Document

阶段6:文档更新

Update
guardrails/README.md
with:
markdown
undefined
更新
guardrails/README.md
,添加以下内容:
markdown
undefined

<rule-name>

<rule-name>

Engine: ESLint | ast-grep Pattern: <what it enforces> Rationale: <why — link ADR if exists> Auto-fix: yes | no Exceptions: <files/patterns excluded>
undefined
引擎: ESLint | ast-grep 规则模式: <规则强制执行的内容> 设计理由: <规则存在的原因——如有ADR请链接> 自动修复: 是 | 否 例外情况: <排除的文件/模式>
undefined

Output

输出结果

GUARDRAIL CREATED:
- Rule: guardrails/rules/<name>.<ext>
- Test: guardrails/rules/<name>.test.<ext>
- Engine: ESLint | ast-grep
- Violations found: N (in current codebase)
- Auto-fixable: yes | no
- Config updated: eslint.config.js | guardrails/sgconfig.yml
GUARDRAIL 已创建:
- 规则文件:guardrails/rules/<name>.<ext>
- 测试文件:guardrails/rules/<name>.test.<ext>
- 使用引擎:ESLint | ast-grep
- 已发现违规数量:N(当前代码库中)
- 是否支持自动修复:是 | 否
- 已更新配置:eslint.config.js | guardrails/sgconfig.yml

Anti-Patterns

反模式

  • Rules that fire on >20% of files (too broad, probably wrong constraint)
  • Rules without tests (defeats the purpose)
  • Rules without clear error messages (Claude can't self-correct from "error")
  • Duplicating built-in ESLint/Ruff rules (check first)
  • Over-specific rules that match one file (use CLAUDE.md instead)
  • 规则触发覆盖超过20%的文件(范围过宽,可能约束逻辑有误)
  • 无测试用例的规则(失去规则的意义)
  • 无清晰错误提示的规则(Claude无法仅通过“错误”提示自我修正)
  • 重复内置ESLint/Ruff规则的自定义规则(先检查内置规则)
  • 仅匹配单个文件的过度特定规则(建议使用CLAUDE.md替代)

Integration

集成场景

Consumed byHow
fast-feedback.py
Runs
eslint <file>
and
sg scan <file>
on every edit
/codify-learning
Routes "lint rule" target here
/done
Routes "lint rule" target here
/tune-repo
Discovers patterns, recommends
/guardrail
invocations
/check-quality
Audits
guardrails/
completeness
CI (GitHub Actions)Standard
eslint .
or
sg scan
in workflow
消费方集成方式
fast-feedback.py
在每次编辑时运行
eslint <file>
sg scan <file>
/codify-learning
将“lint规则”目标路由至此
/done
将“lint规则”目标路由至此
/tune-repo
发现模式,推荐调用
/guardrail
/check-quality
审核
guardrails/
目录的完整性
CI(GitHub Actions)在工作流中执行标准的
eslint .
sg scan