python-quality-gate

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python Quality Gate Skill

Python质量门禁Skill

Operator Context

操作场景

This skill operates as an operator for Python code quality validation workflows, configuring Claude's behavior for automated quality assurance. It runs four tools in deterministic order: ruff, pytest, mypy, bandit.
该Skill作为Python代码质量验证工作流的操作器,用于配置Claude的自动化质量保证行为。它会按确定顺序运行四款工具:ruff、pytest、mypy、bandit。

Hardcoded Behaviors (Always Apply)

硬编码行为(始终生效)

  • CLAUDE.md Compliance: Read and follow repository CLAUDE.md before execution
  • Over-Engineering Prevention: Only validate code. Never add tools, features, or flexibility not requested
  • Run all available quality tools in fixed order: ruff check, ruff format, mypy, pytest, bandit
  • Show complete command output with exact file paths and line numbers (never summarize)
  • Exit with non-zero status if any critical check fails
  • Categorize issues by severity: critical, high, medium, low
  • CLAUDE.md合规性:执行前阅读并遵循仓库中的CLAUDE.md文件
  • 避免过度设计:仅验证代码,绝不添加未被请求的工具、功能或灵活性
  • 按固定顺序运行所有可用的质量工具:ruff check、ruff format、mypy、pytest、bandit
  • 展示包含准确文件路径和行号的完整命令输出(绝不摘要)
  • 若任何关键检查失败,以非零状态退出
  • 按严重程度对问题分类:critical(严重)、high(高)、medium(中)、low(低)

Default Behaviors (ON unless disabled)

默认行为(除非禁用否则开启)

  • Report Facts: Show command output rather than describing it. No self-congratulation.
  • Temporary File Cleanup: Remove intermediate outputs at completion. Keep final report only if requested.
  • Group errors by type and file for readability
  • Show suggested auto-fix commands when available
  • Calculate and display quality metrics (error counts, coverage percentages)
  • Check formatting compliance with ruff format
  • 事实报告:展示命令输出而非描述输出内容,不添加自夸性表述
  • 临时文件清理:完成后移除中间输出,仅在被请求时保留最终报告
  • 按类型和文件分组错误以提升可读性
  • 展示可用的建议自动修复命令
  • 计算并展示质量指标(错误数量、覆盖率百分比)
  • 通过ruff format检查格式合规性

Optional Behaviors (OFF unless enabled)

可选行为(除非启用否则关闭)

  • Auto-fix issues with
    --fix
    flag (requires explicit request)
  • Install missing quality tools automatically
  • Modify pyproject.toml or configuration files
  • Save report to file with
    --output {file}
    flag
  • Skip specific tools with
    --skip-mypy
    ,
    --skip-bandit
    ,
    --skip-tests
    flags
  • 使用
    --fix
    标志自动修复问题(需要明确的用户请求)
  • 自动安装缺失的质量工具
  • 修改pyproject.toml或配置文件
  • 使用
    --output {file}
    标志将报告保存到文件
  • 使用
    --skip-mypy
    --skip-bandit
    --skip-tests
    标志跳过特定工具

What This Skill CAN Do

该Skill能做什么

  • Run all four quality tools in deterministic order with structured output
  • Categorize issues by severity and provide auto-fix commands
  • Generate structured markdown reports with actionable suggestions
  • Calculate pass/fail status based on configurable thresholds
  • Detect project configuration from pyproject.toml
  • 按确定顺序运行四款质量工具并生成结构化输出
  • 按严重程度分类问题并提供自动修复命令
  • 生成包含可操作建议的结构化Markdown报告
  • 基于可配置阈值判断整体通过/失败状态
  • 从pyproject.toml中检测项目配置

What This Skill CANNOT Do

该Skill不能做什么

  • Debug runtime bugs (use systematic-debugging)
  • Refactor code or make architectural changes (use systematic-refactoring)
  • Replace running a single tool when that is all the user needs
  • Auto-fix without explicit user confirmation

  • 调试运行时bug(请使用systematic-debugging)
  • 重构代码或进行架构变更(请使用systematic-refactoring)
  • 替代单一工具的运行(当用户仅需要单个工具时直接运行对应工具即可)
  • 未经用户明确确认就自动修复问题

Prerequisites

前置条件

Required Tools

必需工具

bash
pip install ruff pytest pytest-cov
bash
pip install ruff pytest pytest-cov

Optional Tools (recommended)

可选工具(推荐安装)

bash
pip install mypy bandit
bash
pip install mypy bandit

Expected Project Structure

预期项目结构

project/
├── pyproject.toml          # Ruff, pytest, mypy config
├── src/ or app/            # Source code
│   └── *.py
├── tests/ or test/         # Test files
│   └── test_*.py
└── .python-version         # Optional Python version
See
references/pyproject-template.toml
for complete configuration template.

project/
├── pyproject.toml          # Ruff、pytest、mypy的配置文件
├── src/ or app/            # 源代码目录
│   └── *.py
├── tests/ or test/         # 测试文件目录
│   └── test_*.py
└── .python-version         # 可选的Python版本文件
完整配置模板请参考
references/pyproject-template.toml

Instructions

操作步骤

Phase 1: Detection and Setup

阶段1:检测与设置

Step 1: Detect project configuration
bash
ls -la pyproject.toml setup.py setup.cfg mypy.ini .python-version 2>/dev/null
Identify Python version target, ruff config, pytest config, mypy config from pyproject.toml.
Step 2: Detect source and test directories
bash
ls -d src/ app/ lib/ 2>/dev/null || echo "Source: current directory"
ls -d tests/ test/ 2>/dev/null || echo "Tests: not found"
Step 3: Verify tool availability
bash
ruff --version
pytest --version
mypy --version || echo "mypy not installed (optional)"
bandit --version || echo "bandit not installed (optional)"
If ruff or pytest are missing, STOP. These are required:
ERROR: Required tool not found: {tool_name}
Install with: pip install ruff pytest pytest-cov
Gate: ruff and pytest available. Project structure identified. Proceed only when gate passes.
步骤1:检测项目配置
bash
ls -la pyproject.toml setup.py setup.cfg mypy.ini .python-version 2>/dev/null
从pyproject.toml中识别目标Python版本、ruff配置、pytest配置、mypy配置。
步骤2:检测源代码和测试目录
bash
ls -d src/ app/ lib/ 2>/dev/null || echo "Source: current directory"
ls -d tests/ test/ 2>/dev/null || echo "Tests: not found"
步骤3:验证工具可用性
bash
ruff --version
pytest --version
mypy --version || echo "mypy not installed (optional)"
bandit --version || echo "bandit not installed (optional)"
若缺失ruff或pytest,立即停止操作。这两款工具是必需的:
ERROR: Required tool not found: {tool_name}
Install with: pip install ruff pytest pytest-cov
门禁条件:ruff和pytest可用,项目结构已识别。仅当门禁通过时才可继续。

Phase 2: Execute Quality Checks

阶段2:执行质量检查

Run all checks in order, capturing full output for each.
Step 1: Ruff linting
bash
ruff check . --output-format=grouped
Step 2: Ruff formatting check
bash
ruff format --check .
Step 3: Type checking with mypy (if installed)
bash
mypy . --ignore-missing-imports --show-error-codes
Skip and note in report if mypy is not installed.
Step 4: Run test suite
bash
pytest -v --tb=short --cov=src --cov-report=term-missing
If no tests directory exists, skip and note in report.
Step 5: Security scanning with bandit (if installed)
bash
bandit -r src/ -ll --format=screen
Skip and note in report if bandit is not installed.
Gate: All available tools have been run. Full output captured. Proceed to analysis.
按顺序运行所有检查,捕获每个工具的完整输出。
步骤1:Ruff代码检查
bash
ruff check . --output-format=grouped
步骤2:Ruff格式检查
bash
ruff format --check .
步骤3:使用mypy进行类型检查(若已安装)
bash
mypy . --ignore-missing-imports --show-error-codes
若未安装mypy,跳过并在报告中注明。
步骤4:运行测试套件
bash
pytest -v --tb=short --cov=src --cov-report=term-missing
若不存在测试目录,跳过并在报告中注明。
步骤5:使用bandit进行安全扫描(若已安装)
bash
bandit -r src/ -ll --format=screen
若未安装bandit,跳过并在报告中注明。
门禁条件:所有可用工具已运行,完整输出已捕获。进入分析阶段。

Phase 3: Categorize and Analyze

阶段3:分类与分析

Step 1: Categorize issues by severity
See
references/tool-commands.md
for complete severity classification tables.
Summary of severity levels:
  • Critical: F errors (pyflakes), E9xx (syntax), undefined names, test failures, high-severity security
  • High: E501, E711/E712, F841, N8xx, arg-type/assignment mypy errors
  • Medium: W warnings, C4xx, no-untyped-def mypy errors
  • Low: SIM suggestions, UP upgrade suggestions
Step 2: Count auto-fixable issues
bash
ruff check . --statistics
Issues marked with
[*]
are auto-fixable.
Step 3: Determine overall status
FAIL if:
  • Any ruff F errors or test failures
  • Any high-severity bandit issues
  • Mypy errors exceed 10 (configurable)
  • Test coverage below 80% (if coverage enabled)
PASS otherwise.
Gate: All issues categorized. Pass/fail determined. Proceed to report.
步骤1:按严重程度分类问题
完整的严重程度分类表请参考
references/tool-commands.md
严重程度等级摘要:
  • Critical(严重):F类错误(pyflakes)、E9xx类(语法错误)、未定义名称、测试失败、高严重度安全问题
  • High(高):E501、E711/E712、F841、N8xx、mypy的arg-type/assignment类错误
  • Medium(中):W类警告、C4xx类、mypy的no-untyped-def类错误
  • Low(低):SIM类建议、UP类升级建议
步骤2:统计可自动修复的问题数量
bash
ruff check . --statistics
标记有
[*]
的问题可自动修复。
步骤3:确定整体状态
以下情况标记为FAIL(失败):
  • 存在任何ruff F类错误或测试失败
  • 存在任何高严重度bandit问题
  • mypy错误数量超过10个(可配置)
  • 测试覆盖率低于80%(若启用覆盖率统计)
其他情况标记为PASS(通过)。
门禁条件:所有问题已分类,通过/失败状态已确定。进入报告阶段。

Phase 4: Generate Report

阶段4:生成报告

Format a structured markdown report. See
references/report-template.md
for the full template.
The report MUST include:
  1. Overall PASS/FAIL status
  2. Summary table (each tool's status and issue count)
  3. Total issues and auto-fixable count
  4. Detailed results per tool (issues grouped by severity)
  5. Critical issues requiring attention with file:line references
  6. Auto-fix commands section
Print the complete report to stdout. Never summarize or truncate.
If
--output {file}
flag provided, also write report to file.
Gate: Report generated and displayed. Task complete.

生成结构化Markdown报告。完整模板请参考
references/report-template.md
报告必须包含:
  1. 整体PASS/FAIL状态
  2. 摘要表格(每个工具的状态和问题数量)
  3. 总问题数和可自动修复问题数
  4. 按工具分组的详细结果(问题按严重程度排序)
  5. 需要关注的严重问题,包含文件:行号引用
  6. 自动修复命令部分
将完整报告打印到标准输出,绝不摘要或截断内容。
若提供了
--output {file}
标志,同时将报告写入指定文件。
门禁条件:报告已生成并展示。任务完成。

Auto-Fix Mode

自动修复模式

When user explicitly requests auto-fix:
bash
ruff check . --fix
ruff format .
After auto-fix, show diff and re-run quality gate to verify:
bash
git diff
ALWAYS warn that auto-fix modifies files in place.

当用户明确请求自动修复时:
bash
ruff check . --fix
ruff format .
自动修复后,展示差异并重新运行质量门禁以验证:
bash
git diff
必须警告用户:自动修复会直接修改文件内容。

Examples

示例

Example 1: Pre-Merge Quality Check

示例1:合并前质量检查

User says: "Run quality checks before I merge this PR" Actions:
  1. Detect project config and available tools (Phase 1)
  2. Run ruff check, ruff format, mypy, pytest, bandit in order (Phase 2)
  3. Categorize 12 issues: 0 critical, 3 high, 9 medium (Phase 3)
  4. Generate report showing PASSED with 3 high-priority suggestions (Phase 4) Result: Structured report with actionable fix commands
用户请求:“在我合并这个PR前运行质量检查” 操作:
  1. 检测项目配置和可用工具(阶段1)
  2. 按顺序运行ruff check、ruff format、mypy、pytest、bandit(阶段2)
  3. 分类12个问题:0个严重、3个高、9个中(阶段3)
  4. 生成显示PASSED(通过)的报告,包含3个高优先级建议(阶段4) 结果:包含可操作修复命令的结构化报告

Example 2: Quality Gate Failure

示例2:质量门禁失败

User says: "Check code quality on the payments module" Actions:
  1. Detect config, find src/payments/ directory (Phase 1)
  2. Run all tools -- pytest shows 2 failures, ruff finds F401 errors (Phase 2)
  3. Categorize: 2 critical (test failures), 1 critical (undefined name), 5 medium (Phase 3)
  4. Generate FAILED report with critical issues listed first (Phase 4) Result: FAILED status with prioritized fix list, auto-fix commands for 5 medium issues

用户请求:“检查支付模块的代码质量” 操作:
  1. 检测配置,找到src/payments/目录(阶段1)
  2. 运行所有工具——pytest显示2个失败,ruff发现F401错误(阶段2)
  3. 分类问题:2个严重(测试失败)、1个严重(未定义名称)、5个中(阶段3)
  4. 生成显示FAILED(失败)的报告,优先列出严重问题(阶段4) 结果:FAILED状态报告,包含优先级修复列表,以及5个中等问题的自动修复命令

Error Handling

错误处理

Error: "ruff: command not found"

错误:“ruff: command not found”

Cause: Ruff is not installed in the current environment Solution: Install with
pip install ruff
. Do not proceed without ruff -- exit with status 2.
原因:当前环境中未安装Ruff 解决方案:使用
pip install ruff
安装。若无Ruff则无法继续——以状态码2退出。

Error: "Tests failed with exit code 1"

错误:“Tests failed with exit code 1”

Cause: pytest found test failures Solution: This is expected behavior, not a tool error. Parse output, include failure details in report, mark overall status as FAILED, continue with remaining checks.
原因:pytest发现测试失败 解决方案:这是预期行为,并非工具错误。解析输出,将失败细节包含在报告中,标记整体状态为FAILED,继续运行剩余检查。

Error: "No Python files found"

错误:“No Python files found”

Cause: Running from wrong directory or not a Python project Solution: Verify location with
ls pyproject.toml src/ tests/
. Run from project root.
原因:在错误的目录运行,或当前目录不是Python项目 解决方案:使用
ls pyproject.toml src/ tests/
验证位置,从项目根目录运行。

Error: "Mypy cache corruption"

错误:“Mypy cache corruption”

Cause: Stale or corrupted .mypy_cache directory Solution: Clear cache with
rm -rf .mypy_cache
and retry. If mypy continues to fail, skip type checking and note in report.

原因:.mypy_cache目录过期或损坏 解决方案:使用
rm -rf .mypy_cache
清除缓存并重试。若mypy仍失败,跳过类型检查并在报告中注明。

Anti-Patterns

反模式

Anti-Pattern 1: Auto-Fix Without Review

反模式1:未审查就自动修复

What it looks like: Running
ruff --fix
blindly without reviewing changes Why wrong: Auto-fix can change code semantics (import removal, reformatting) Do instead: Run check-only first, review issues, confirm auto-fix, then
git diff
表现:盲目运行
ruff --fix
而不审查变更 危害:自动修复可能改变代码语义(比如移除正在使用的导入、修改格式) 正确做法:先运行仅检查模式,审查问题,确认自动修复,然后使用
git diff
查看变更

Anti-Pattern 2: Ignoring Critical Issues for Style Fixes

反模式2:忽略严重问题优先修复风格问题

What it looks like: Fixing line lengths while undefined names exist Why wrong: Critical issues (F errors, test failures) break functionality; style issues do not Do instead: Fix critical first, high second, use auto-fix for bulk style issues
表现:在存在未定义名称的情况下先修复行长度问题 危害:严重问题(F类错误、测试失败)会破坏功能;风格问题不会 正确做法:先修复严重问题,再处理高优先级问题,使用自动修复批量处理风格问题

Anti-Pattern 3: Skipping Tests to "Make Gate Pass"

反模式3:跳过测试以“通过门禁”

What it looks like: Using
--skip-tests
to get a passing status Why wrong: Tests verify functionality. Skipping them hides broken code. Do instead: Fix failing tests. Only skip optional tools (mypy, bandit) if genuinely unneeded.
表现:使用
--skip-tests
标志获取通过状态 危害:测试用于验证功能,跳过测试会隐藏损坏的代码 正确做法:修复失败的测试。仅在确实不需要时跳过可选工具(mypy、bandit)

Anti-Pattern 4: Wrong Tool for the Job

反模式4:用错工具

What it looks like: Running quality gate to debug a runtime bug Why wrong: Linting finds style issues, not logical bugs Do instead: Use systematic-debugging for runtime bugs, quality gate for pre-commit validation

表现:运行质量门禁来调试运行时bug 危害:代码检查(linting)只能发现风格问题,无法发现逻辑bug 正确做法:使用systematic-debugging处理运行时bug,质量门禁仅用于提交前验证

References

参考资料

This skill uses these shared patterns:
  • Anti-Rationalization - Prevents shortcut rationalizations
  • Verification Checklist - Pre-completion checks
该Skill使用以下共享模式:
  • Anti-Rationalization - 防止找借口走捷径
  • Verification Checklist - 完成前检查

Domain-Specific Anti-Rationalization

领域特定的反合理化

RationalizationWhy It's WrongRequired Action
"Linting passed, code is correct"Linting finds style issues, not logic bugsRun tests too
"Tests pass, no need for type checking"Tests check behavior, types check contractsRun mypy if available
"Auto-fix is safe, just run it"Auto-fix can remove used imports, change semanticsReview changes with git diff
"Only style issues, skip the report"Style issues hide real problems in noiseGenerate full report, prioritize by severity
合理化借口错误原因要求操作
"代码检查通过了,代码肯定没问题"代码检查只能发现风格问题,无法发现逻辑bug同时运行测试
"测试通过了,不需要类型检查"测试检查行为,类型检查检查契约若有mypy则运行
"自动修复是安全的,直接运行就行"自动修复可能移除正在使用的导入、改变语义用git diff查看变更
"只有风格问题,跳过报告吧"风格问题会在噪声中隐藏真正的问题生成完整报告,按严重程度排序

Reference Files

参考文件

  • ${CLAUDE_SKILL_DIR}/references/tool-commands.md
    : Severity classifications, expected output formats, CLI flags
  • ${CLAUDE_SKILL_DIR}/references/report-template.md
    : Full structured report template
  • ${CLAUDE_SKILL_DIR}/references/pyproject-template.toml
    : Complete ruff, pytest, mypy, bandit configuration
  • ${CLAUDE_SKILL_DIR}/references/tool-commands.md
    :严重程度分类、预期输出格式、CLI标志
  • ${CLAUDE_SKILL_DIR}/references/report-template.md
    :完整的结构化报告模板
  • ${CLAUDE_SKILL_DIR}/references/pyproject-template.toml
    :完整的ruff、pytest、mypy、bandit配置