mcpField
S
sc-principles

sc-principles

github.com/tony363测试与质量2096 次安装30 周前更新
代码仓库

关于 sc-principles

sc-principles 是用于验证 Python 代码的技能,检查 KISS、Functional Core/Imperative Shell、SOLID 和 Let It Crash 原则。它提供可配置阈值、单项检查和 JSON 报告,适用于开发工作流。

主要功能

  1. 01检查四项工程原则
  2. 02衡量复杂度与代码结构
  3. 03检测 I/O 和错误处理模式
  4. 04可配置检查项与阈值
  5. 05支持 JSON 报告和提交前检查

适用场景

  1. 01检查 Python 代码的原则违规
  2. 02重构时运行选定检查
  3. 03阻止未通过验证的提交
  4. 04生成机器可读的验证报告

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/tony363/superclaude --skill sc-principles

安装后在 Claude Code 中输入/sc-principles确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

scripts/
__init__.py
shared.py
validate_crash.py
validate_kiss.py
validate_purity.py
validate_solid.py
tests/
__init__.py
test_shared.py
test_validate_crash.py
test_validate_kiss.py
test_validate_purity.py
test_validate_solid.py

详细介绍

/sc:principles - 代码原则验证器

强制验证技能,用于执行四项基本软件工程原则:

  1. KISS(保持简单,傻瓜) - 代码应尽可能简单
  2. 函数式核心,命令式外壳 - 业务逻辑必须是纯函数;I/O 应放在边界处
  3. SOLID - 单一职责、开闭原则、里氏替换、接口隔离、依赖倒置
  4. 崩溃即止 - 对 Bug 快速失败;在边界处显式处理错误

快速开始

# Full validation (all four principles)
/sc:principles src/

# KISS only validation
/sc:principles src/ --kiss-only

# Purity only validation
/sc:principles src/ --purity-only

# SOLID only validation
/sc:principles src/ --solid-only

# Let It Crash only validation
/sc:principles src/ --crash-only

# Strict mode (warnings become errors)
/sc:principles src/ --strict

# Generate detailed report
/sc:principles src/ --report

行为流程

1. INITIALIZE
   ├── Detect scope root
   ├── Find changed Python files (git diff)
   └── Determine file contexts (core vs shell)

2. ANALYZE
   ├── Parse AST for each file
   ├── Calculate complexity metrics (KISS)
   ├── Detect I/O patterns (Purity)
   ├── Check structural patterns (SOLID)
   └── Analyze error handling (Let It Crash)

3. VALIDATE
   ├── Compare against thresholds
   ├── Classify violations (error vs warning)
   └── Apply context rules (core stricter than shell)

4. REPORT/BLOCK
   ├── Output violations with locations
   ├── Generate actionable recommendations
   └── Exit 0 (pass) or 2 (blocked)

验证规则

KISS 检查关卡
指标阈值严重性描述
圈复杂度> 10错误代码中的独立路径数量
圈复杂度> 7警告复杂度增长的早期预警
认知复杂度> 15错误加权复杂度(嵌套结构的权重更高)
函数长度> 50 行错误每个函数的代码行数(包含首尾行)
嵌套深度> 4 层错误If/for/while/with/try 嵌套
参数数量> 5警告函数参数

认知复杂度与圈复杂度的区别:

  • 圈复杂度统计决策点(分支)
  • 认知复杂度对嵌套结构赋予更高权重:每个控制结构按 1 + nesting_depth 计
  • 示例:if (if (if ...)) 的圈复杂度较低,但认知复杂度较高(难以阅读)
纯度检查关卡

“函数式核心,命令式外壳”模式:

层路径模式是否允许 I/O严重性
核心*/domain/*、*/logic/*、*/services/*、*/utils/*、*/core/*否错误
外壳*/handlers/*、*/adapters/*、*/api/*、*/cli/*、*/scripts/*、*/tests/*是警告

注意: */archive/*、*/examples/*、*/benchmarks/*、conftest.py、setup.py 和 *__main__.py 中的文件均视为外壳(允许 I/O)。

检测到的 I/O 模式:

类别示例
文件 I/Oopen()、read()、write()、Path.read_text()
网络requests.get()、httpx、urllib、socket
数据库execute()、query()、session.add()、cursor
子进程subprocess.run()、os.system()、Popen
全局状态global、nonlocal 关键字
副作用print()、logging.*、logger.*
异步 I/Oasync def、await、async for、async with
SOLID 检查关卡

检测 SOLID 设计原则的结构性违规。

原则检测方式严重性描述
SRP文件 >300 行、类包含 >5 个公有方法警告单一职责——只有一个变更原因
OCP基于类型的 if/elif 链、isinstance 级联警告开闭原则——扩展而非修改
LSP重写方法引发 NotImplementedError错误里氏替换原则——遵守契约
ISP接口/协议包含 >7 个方法警告接口隔离——保持接口精简
DIP在业务逻辑中直接实例化警告依赖倒置——依赖抽象

需标记的代码异味:

异味原则建议的修复方式
文件 >300 行SRP将职责提取到多个模块中
if/else 类型链OCP使用策略模式或注册表
重写方法抛出异常LSP遵守基类契约或不要继承
接口包含 10 个以上方法ISP拆分为职责明确的多个接口
逻辑中使用 new Service()DIP依赖注入
Let It Crash 门禁

根据 “Let It Crash” 理念检测错误处理中的反模式。

模式严重性描述
裸 except:error捕获所有异常,包括 KeyboardInterrupt
except Exception:(不重新引发)warning未处理错误便将其吞掉
except: passerror静默失败,给调试带来极大困难
嵌套 try/except 回退warning错误处理路径复杂,难以调试

适合 Let It Crash 的场景:

  • 验证失败 → 以明确的错误崩溃
  • 编程错误 → 立即暴露
  • 内部操作 → 让其失败

需要处理错误的场景(规则的例外):

  • 数据持久化 → 防止数据丢失
  • 外部 API → 重试、回退、优雅降级
  • 资源清理 → RAII、finally 块
  • 面向用户的操作 → 提供友好的错误消息

不会标记(恰当的处理方式):

  • */adapters/*、*/api/*、*/cli/* 路径中的错误处理
  • 吞掉错误前明确记录日志
  • 记录日志后重新引发

标志

标志类型默认值描述
--kiss-onlyboolfalse仅运行 KISS 验证
--purity-onlyboolfalse仅运行纯度验证
--solid-onlyboolfalse仅运行 SOLID 验证
--crash-onlyboolfalse仅运行 Let It Crash 验证
--no-kissboolfalse跳过 KISS 验证
--no-purityboolfalse跳过纯度验证
--no-solidboolfalse跳过 SOLID 验证
--no-crashboolfalse跳过 Let It Crash 验证
--thresholdint10圈复杂度上限
--max-cognitiveint15认知复杂度上限
--max-linesint50函数行数上限
--max-depthint4嵌套深度上限
--max-paramsint5参数数量上限
--max-file-linesint300文件行数上限(SRP)
--max-interface-methodsint7接口方法数量上限(ISP)
--strictboolfalse将所有警告视为错误
--core-onlyboolfalse仅验证核心层文件
--allboolfalse分析所有文件,而不只是已更改的文件
--reportboolfalse生成详细的 JSON 报告

集成标志

供其他技能和 pre-commit 钩子使用:

标志描述
--pre-commit作为 pre-commit 钩子运行(失败时阻止提交)
--inline实现期间进行实时验证
--json输出 JSON 格式,供程序使用

退出代码

代码含义操作
0验证通过继续
2检测到违规已阻止——需要重构
3验证错误需要人工介入

激活的角色

  • code-warden - 原则执行的主要审查者
  • optimizer - 提供复杂重构指导
  • guardian - 用于指标集成

验证器脚本

位于 scripts/ 目录中:

validate_kiss.py
python .claude/skills/sc-principles/scripts/validate_kiss.py \
  --scope-root . \
  --threshold 10 \
  --max-lines 50 \
  --json
validate_purity.py
python .claude/skills/sc-principles/scripts/validate_purity.py \
  --scope-root . \
  --core-only \
  --json

Pre-commit 集成

添加到 .pre-commit-config.yaml:

repos:
  - repo: local
    hooks:
      - id: kiss-check
        name: KISS Validation
        entry: python .claude/skills/sc-principles/scripts/validate_kiss.py --scope-root . --json
        language: python
        types: [python]
        pass_filenames: false

      - id: purity-check
        name: Purity Validation
        entry: python .claude/skills/sc-principles/scripts/validate_purity.py --scope-root . --json
        language: python
        types: [python]
        pass_filenames: false

重构指导

检测到违规时,应用以下模式:

针对复杂度违规
  1. 提取方法 - 将大型函数拆分为更小且命名明确的部分
  2. 保护子句 - 用提前返回替换嵌套的 if/else
  3. 策略模式 - 用多态替换复杂的 switch/if-else
  4. 分解条件 - 将复杂条件命名为能清楚说明其含义的变量

之前:

def process(data, config, user):
    if data:
        if config.enabled:
            if user.has_permission:
                for item in data:
                    if item.valid:
                        # deep logic here

之后:

def process(data, config, user):
    if not can_process(data, config, user):
        return None
    return process_items(data)

def can_process(data, config, user):
    return data and config.enabled and user.has_permission

def process_items(data):
    return [process_item(item) for item in data if item.valid]
针对纯度违规
  1. 依赖注入 - 将依赖作为参数传入
  2. 仓储模式 - 隔离数据库操作
  3. 适配器模式 - 封装外部 API
  4. 返回而非打印 - 返回值,由调用方处理输出

之前:

# In domain/calculator.py (CORE - should be pure)
def calculate_discount(user_id):
    user = db.query(User).get(user_id)  # I/O in core!
    print(f"Calculating for {user.name}")  # Side effect!
    return 0.2 if user.is_premium else 0.1

之后:

# In domain/calculator.py (CORE - now pure)
def calculate_discount(user: User) -> float:
    """Pure function - no I/O, just logic."""
    return 0.2 if user.is_premium else 0.1

# In adapters/discount_service.py (SHELL - I/O allowed)
def get_user_discount(user_id: int) -> float:
    user = user_repository.get(user_id)
    discount = calculate_discount(user)
    logger.info(f"Discount for {user.name}: {discount}")
    return discount
针对 SOLID 违规
  1. SRP(单一职责) - 拆分为多个模块
  2. OCP(开闭原则) - 使用策略模式或注册表
  3. LSP(里氏替换原则) - 遵守基类契约
  4. ISP(接口隔离原则) - 拆分臃肿的接口
  5. DIP(依赖倒置原则) - 注入依赖

之前(违反 OCP):

def process_payment(payment_type, amount):
    if payment_type == "credit":
        return process_credit(amount)
    elif payment_type == "debit":
        return process_debit(amount)
    elif payment_type == "crypto":  # New type = code change!
        return process_crypto(amount)

之后(符合 OCP):

PROCESSORS = {
    "credit": process_credit,
    "debit": process_debit,
    "crypto": process_crypto,  # Add here, no function change
}

def process_payment(payment_type, amount):
    processor = PROCESSORS.get(payment_type)
    if not processor:
        raise ValueError(f"Unknown payment type: {payment_type}")
    return processor(amount)
针对“任其崩溃”违规
  1. 移除兜底捕获代码块 - 让 Bug 暴露出来
  2. 移除防御性守卫 - 改为在边界处进行验证
  3. 简化 try/except - 在边界处处理,而不是到处处理

之前(兜底捕获反模式):

def get_user(user_id):
    try:
        user = db.query(User).get(user_id)
        return user
    except:  # BAD: catches everything, hides bugs
        return None

之后(任其崩溃):

def get_user(user_id):
    # Let database errors surface - they indicate real problems
    return db.query(User).get(user_id)

# Handle at the boundary (API layer)
@app.get("/users/{user_id}")
def api_get_user(user_id: int):
    try:
        return get_user(user_id)
    except DBError as e:
        logger.error("Database error", error=e, user_id=user_id)
        raise HTTPException(500, "Database unavailable")

示例

示例 1:完整验证
$ /sc:principles src/ --report

KISS Validation: BLOCKED
Files analyzed: 12
Errors: 3, Warnings: 5

Violations:
  [ERROR] src/services/order.py:45 process_order: complexity = 15 (max: 10)
  [ERROR] src/utils/parser.py:12 parse_data: length = 78 (max: 50)
  [WARNING] src/domain/calc.py:8 calculate: parameters = 7 (max: 5)

Purity Validation: BLOCKED
Core violations: 2, Shell warnings: 1

Violations:
  [ERROR] src/domain/user.py:23 get_status: database - db.query (context: core)
  [ERROR] src/services/report.py:56 generate: file_io - open (context: core)

Recommendations:
  - COMPLEXITY: Extract helper functions, use early returns
  - DATABASE: Use repository pattern. Business logic receives data, not queries
  - FILE I/O: Move file operations to adapter layer
示例 2:仅 KISS
$ /sc:principles src/ --kiss-only --threshold 8

KISS Validation: PASSED
Files analyzed: 12
Errors: 0, Warnings: 2
示例 3:严格模式
$ /sc:principles src/ --strict

# All warnings become errors
# Any warning will block

质量集成

此技能与 SuperClaude 质量门禁集成:

  • 为 simplicity 维度做出贡献(权重:0.08)
  • 为 purity 维度做出贡献(权重:0.02)
  • 当 simplicity < 70 时触发 simplification 策略
  • 当 purity < 70 时触发 purification 策略

相关技能

  • /sc:improve --type principles - 自动重构以符合原则
  • /sc:implement - 默认包含原则验证
  • /sc:analyze - 代码分析包含原则指标

测试覆盖率

验证器拥有全面的测试覆盖率(4 个测试套件共 59 项测试):

纯度验证器测试(16 项):

  • 异步函数检测(async def)
  • await 表达式检测
  • 异步 for 循环检测
  • 异步 with 上下文管理器检测
  • 区分 Shell 与核心部分的严重程度
  • 误报回归测试(set.add、parser.add_argument、asyncio.run、callback.call)
  • 边界情况(语法错误、Unicode、空文件)

KISS 验证器测试(15 项):

  • 函数长度(包含计数)
  • 圈复杂度
  • 认知复杂度
  • 嵌套深度
  • 参数数量
  • 边界情况(语法错误、Unicode、空文件)

SOLID 验证器测试(15 项):

  • SRP:文件长度、类方法数量、不计私有方法
  • OCP:isinstance 级联判断
  • LSP:具体类重写方法中的 NotImplementedError,不包括 ABC/Protocol
  • ISP:臃肿的 Protocol 和 ABC 接口
  • DIP:核心路径中直接实例化服务
  • 边界情况(语法错误、空文件)

崩溃验证器测试(13 项):

  • 裸 except 检测
  • except: pass 检测
  • 核心路径中吞掉异常
  • 重新抛出异常(正常)
  • 处理特定异常(正常)
  • 嵌套 try/except 深度
  • 放宽 Shell 路径规则(适配器、api)
  • 边界情况(语法错误、空文件、try/finally)

运行测试:

python -m pytest .claude/skills/sc-principles/tests/ -v

版本:2.1.0 验证器:validate_kiss.py、validate_purity.py、validate_solid.py、validate_crash.py 共享:shared.py(通用的 find_python_files 工具) Agent:code-warden 特性:principles-enforced 测试:59 项通过(全部 4 个验证器)

评论

支持 Markdown