sc-principles

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

/sc:principles - Code Principles Validator

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

Mandatory validation skill enforcing four fundamental software engineering principles:
  1. KISS (Keep It Simple, Stupid) - Code should be as simple as possible
  2. Functional Core, Imperative Shell - Business logic must be pure; I/O belongs at edges
  3. SOLID - Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, Dependency Inversion
  4. Let It Crash - Fail fast for bugs; handle errors explicitly at boundaries
强制验证技能,实施四项核心软件工程原则:
  1. KISS (Keep It Simple, Stupid) - 代码应尽可能简洁
  2. 函数核心,命令式外壳 - 业务逻辑必须是纯函数;I/O操作应放在代码边缘
  3. SOLID - 单一职责、开闭原则、里氏替换、接口隔离、依赖反转
  4. Let It Crash - 针对bug快速失败;在边界处显式处理错误

Quick Start

快速开始

bash
undefined
bash
undefined

Full validation (all four principles)

完整验证(涵盖四项原则)

/sc:principles src/
/sc:principles src/

KISS only validation

仅执行KISS验证

/sc:principles src/ --kiss-only
/sc:principles src/ --kiss-only

Purity only validation

仅执行纯函数验证

/sc:principles src/ --purity-only
/sc:principles src/ --purity-only

SOLID only validation

仅执行SOLID验证

/sc:principles src/ --solid-only
/sc:principles src/ --solid-only

Let It Crash only validation

仅执行Let It Crash验证

/sc:principles src/ --crash-only
/sc:principles src/ --crash-only

Strict mode (warnings become errors)

严格模式(警告视为错误)

/sc:principles src/ --strict
/sc:principles src/ --strict

Generate detailed report

生成详细报告

/sc:principles src/ --report
undefined
/sc:principles src/ --report
undefined

Behavioral Flow

行为流程

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)
1. 初始化
   ├── 检测作用域根目录
   ├── 查找变更的Python文件(git diff)
   └── 确定文件上下文(核心层 vs 外壳层)

2. 分析
   ├── 解析每个文件的AST
   ├── 计算复杂度指标(KISS)
   ├── 检测I/O模式(纯函数验证)
   ├── 检查结构模式(SOLID)
   └── 分析错误处理(Let It Crash)

3. 验证
   ├── 与阈值进行对比
   ├── 分类违规类型(错误 vs 警告)
   └── 应用上下文规则(核心层比外壳层更严格)

4. 报告/拦截
   ├── 输出带位置信息的违规内容
   ├── 生成可执行的建议
   └── 返回0(通过)或2(拦截)的退出码

Validation Rules

验证规则

KISS Gate

KISS验证关卡

MetricThresholdSeverityDescription
Cyclomatic Complexity> 10errorNumber of independent paths through code
Cyclomatic Complexity> 7warningEarly warning for growing complexity
Cognitive Complexity> 15errorWeighted complexity (nested structures count more)
Function Length> 50 lineserrorLines of code per function (inclusive count)
Nesting Depth> 4 levelserrorIf/for/while/with/try nesting
Parameter Count> 5warningFunction parameters
Cognitive vs Cyclomatic Complexity:
  • Cyclomatic counts decision points (branches)
  • Cognitive weights nested structures more heavily:
    1 + nesting_depth
    per control structure
  • Example:
    if (if (if ...))
    has low cyclomatic but high cognitive (hard to read)
指标阈值严重程度描述
圈复杂度> 10错误代码中独立路径的数量
圈复杂度> 7警告复杂度上升的早期预警
认知复杂度> 15错误加权复杂度(嵌套结构权重更高)
函数长度> 50行错误每个函数的代码行数(包含所有计数)
嵌套深度> 4层错误If/for/while/with/try的嵌套层级
参数数量> 5警告函数参数个数
认知复杂度 vs 圈复杂度:
  • 圈复杂度统计决策点(分支)的数量
  • 认知复杂度对嵌套结构赋予更高权重:每个控制结构按
    1 + 嵌套深度
    计算
  • 示例:
    if (if (if ...))
    的圈复杂度低,但认知复杂度高(难以阅读)

Purity Gate

纯函数验证关卡

The "Functional Core, Imperative Shell" pattern:
LayerPath PatternsI/O AllowedSeverity
Core
*/domain/*
,
*/logic/*
,
*/services/*
,
*/utils/*
,
*/core/*
NOerror
Shell
*/handlers/*
,
*/adapters/*
,
*/api/*
,
*/cli/*
,
*/scripts/*
,
*/tests/*
YESwarning
Note: Files in
*/archive/*
,
*/examples/*
,
*/benchmarks/*
,
conftest.py
,
setup.py
, and
*__main__.py
are treated as shell (I/O allowed).
Detected I/O Patterns:
CategoryExamples
File I/O
open()
,
read()
,
write()
,
Path.read_text()
Network
requests.get()
,
httpx
,
urllib
,
socket
Database
execute()
,
query()
,
session.add()
,
cursor
Subprocess
subprocess.run()
,
os.system()
,
Popen
Global State
global
,
nonlocal
keywords
Side Effects
print()
,
logging.*
,
logger.*
Async I/O
async def
,
await
,
async for
,
async with
遵循「函数核心,命令式外壳」模式:
层级路径模式是否允许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/O
open()
,
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/O
async def
,
await
,
async for
,
async with

SOLID Gate

SOLID验证关卡

Detects structural violations of SOLID design principles.
PrincipleDetectionSeverityDescription
SRPFile >300 lines, class with >5 public methodswarningSingle Responsibility - one reason to change
OCP
if/elif
chains on type,
isinstance
cascades
warningOpen-Closed - extend, don't modify
LSPOverride that raises
NotImplementedError
errorLiskov Substitution - honor contracts
ISPInterface/protocol with >7 methodswarningInterface Segregation - small interfaces
DIPDirect instantiation in business logicwarningDependency Inversion - depend on abstractions
Code Smells to Flag:
SmellPrincipleRecommended Fix
File >300 linesSRPExtract responsibilities into modules
if/else type chainsOCPStrategy pattern or registry
Override that throwsLSPHonor base contract or don't inherit
10+ method interfaceISPSplit into focused interfaces
new Service()
in logic
DIPDependency injection
检测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 Gate

Let It Crash验证关卡

Detects anti-patterns in error handling based on the "Let It Crash" philosophy.
PatternSeverityDescription
Bare
except:
errorCatches all exceptions including KeyboardInterrupt
except Exception:
(no re-raise)
warningSwallows errors without handling
except: pass
errorSilent failure, debugging nightmare
Defensive
if not x: return
chains
warningMasks root cause of bugs
Nested try/except fallbackswarningComplex error paths, hard to debug
When to Let It Crash:
  • Validation failures → crash with clear error
  • Programming errors → surface immediately
  • Internal operations → let them fail
When to Handle Errors (exceptions to rule):
  • Data persistence → protect against data loss
  • External APIs → retry, fallback, graceful degradation
  • Resource cleanup → RAII, finally blocks
  • User-facing operations → graceful error messages
Not Flagged (appropriate handling):
  • Error handling in
    */adapters/*
    ,
    */api/*
    ,
    */cli/*
    paths
  • Explicit logging before swallowing
  • Re-raise after logging
基于「Let It Crash」理念检测错误处理的反模式。
模式严重程度描述
except:
错误捕获所有异常,包括KeyboardInterrupt
except Exception:
(未重新抛出)
警告吞掉错误而不处理
except: pass
错误静默失败,调试噩梦
防御性的
if not x: return
警告掩盖bug的根本原因
嵌套的try/except回退警告复杂的错误路径,难以调试
何时应Let It Crash:
  • 验证失败 → 抛出清晰的错误并终止
  • 编程错误 → 立即暴露问题
  • 内部操作 → 让其失败
何时应处理错误(规则例外):
  • 数据持久化 → 防止数据丢失
  • 外部API → 重试、回退、优雅降级
  • 资源清理 → RAII、finally块
  • 面向用户的操作 → 优雅的错误提示
不会标记的情况(合理处理方式):
  • */adapters/*
    ,
    */api/*
    ,
    */cli/*
    路径中的错误处理
  • 吞掉错误前显式记录日志
  • 记录日志后重新抛出异常

Flags

标志位

FlagTypeDefaultDescription
--kiss-only
boolfalseRun only KISS validation
--purity-only
boolfalseRun only purity validation
--solid-only
boolfalseRun only SOLID validation
--crash-only
boolfalseRun only Let It Crash validation
--no-kiss
boolfalseSkip KISS validation
--no-purity
boolfalseSkip purity validation
--no-solid
boolfalseSkip SOLID validation
--no-crash
boolfalseSkip Let It Crash validation
--threshold
int10Max cyclomatic complexity
--max-cognitive
int15Max cognitive complexity
--max-lines
int50Max function line count
--max-depth
int4Max nesting depth
--max-params
int5Max parameter count
--max-file-lines
int300Max file line count (SRP)
--max-interface-methods
int7Max interface methods (ISP)
--strict
boolfalseTreat all warnings as errors
--core-only
boolfalseOnly validate core layer files
--all
boolfalseAnalyze all files, not just changed
--report
boolfalseGenerate detailed JSON report
标志位类型默认值描述
--kiss-only
boolfalse仅运行KISS验证
--purity-only
boolfalse仅运行纯函数验证
--solid-only
boolfalse仅运行SOLID验证
--crash-only
boolfalse仅运行Let It Crash验证
--no-kiss
boolfalse跳过KISS验证
--no-purity
boolfalse跳过纯函数验证
--no-solid
boolfalse跳过SOLID验证
--no-crash
boolfalse跳过Let It Crash验证
--threshold
int10最大圈复杂度
--max-cognitive
int15最大认知复杂度
--max-lines
int50函数最大行数
--max-depth
int4最大嵌套深度
--max-params
int5最大参数数量
--max-file-lines
int300文件最大行数(SRP)
--max-interface-methods
int7接口最大方法数(ISP)
--strict
boolfalse将所有警告视为错误
--core-only
boolfalse仅验证核心层文件
--all
boolfalse分析所有文件,而非仅变更的文件
--report
boolfalse生成详细的JSON报告

Integration Flags

集成标志位

For use by other skills and pre-commit hooks:
FlagDescription
--pre-commit
Run as pre-commit hook (blocks commit on failure)
--inline
Real-time validation during implementation
--json
Output JSON format for programmatic use
供其他技能和提交前钩子使用:
标志位描述
--pre-commit
作为提交前钩子运行(失败时阻止提交)
--inline
实现过程中的实时验证
--json
输出JSON格式供程序调用

Exit Codes

退出码

CodeMeaningAction
0Validation passedProceed
2Violations detectedBlocked - refactor required
3Validation errorManual intervention needed
代码含义操作
0验证通过继续执行
2检测到违规拦截 - 需要重构
3验证错误需要人工干预

Personas Activated

激活的角色

  • code-warden - Primary reviewer for principles enforcement
  • refactoring-expert - For complex refactoring guidance
  • quality-engineer - For metrics integration
  • code-warden - 原则执行的主要审核者
  • refactoring-expert - 提供复杂重构指导
  • quality-engineer - 负责指标集成

Validator Scripts

验证器脚本

Located in
scripts/
directory:
位于
scripts/
目录下:

validate_kiss.py

validate_kiss.py

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

validate_purity.py

validate_purity.py

bash
python .claude/skills/sc-principles/scripts/validate_purity.py \
  --scope-root . \
  --core-only \
  --json
bash
python .claude/skills/sc-principles/scripts/validate_purity.py \
  --scope-root . \
  --core-only \
  --json

Pre-commit Integration

提交前钩子集成

Add to
.pre-commit-config.yaml
:
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
添加到
.pre-commit-config.yaml
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

Refactoring Guidance

重构指导

When violations are detected, apply these patterns:
检测到违规时,应用以下模式:

For Complexity Violations

针对复杂度违规

  1. Extract Method - Split large functions into smaller, named pieces
  2. Guard Clauses - Replace nested if/else with early returns
  3. Strategy Pattern - Replace complex switch/if-else with polymorphism
  4. Decompose Conditional - Name complex conditions as explaining variables
Before:
python
def process(data, config, user):
    if data:
        if config.enabled:
            if user.has_permission:
                for item in data:
                    if item.valid:
                        # deep logic here
After:
python
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. 卫语句 - 用提前返回替代嵌套if/else
  3. 策略模式 - 用多态替代复杂的switch/if-else
  4. 分解条件 - 将复杂条件命名为解释性变量
重构前:
python
def process(data, config, user):
    if data:
        if config.enabled:
            if user.has_permission:
                for item in data:
                    if item.valid:
                        # 深层逻辑
重构后:
python
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]

For Purity Violations

针对纯函数违规

  1. Dependency Injection - Pass dependencies as arguments
  2. Repository Pattern - Isolate database operations
  3. Adapter Pattern - Wrap external APIs
  4. Return Don't Print - Return values, let callers handle output
Before:
python
undefined
  1. 依赖注入 - 将依赖作为参数传入
  2. 仓库模式 - 隔离数据库操作
  3. 适配器模式 - 封装外部API
  4. 返回而非打印 - 返回值,由调用者处理输出
重构前:
python
undefined

In domain/calculator.py (CORE - should be pure)

在domain/calculator.py(核心层 - 应为纯函数)

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

**After:**
```python
def calculate_discount(user_id): user = db.query(User).get(user_id) # 核心层存在I/O操作! print(f"Calculating for {user.name}") # 存在副作用! return 0.2 if user.is_premium else 0.1

**重构后:**
```python

In domain/calculator.py (CORE - now pure)

在domain/calculator.py(核心层 - 现在是纯函数)

def calculate_discount(user: User) -> float: """Pure function - no I/O, just logic.""" return 0.2 if user.is_premium else 0.1
def calculate_discount(user: User) -> float: """纯函数 - 无I/O,仅包含逻辑。""" return 0.2 if user.is_premium else 0.1

In adapters/discount_service.py (SHELL - I/O allowed)

在adapters/discount_service.py(外壳层 - 允许I/O)

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
undefined
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
undefined

For SOLID Violations

针对SOLID违规

  1. SRP (Single Responsibility) - Extract into modules
  2. OCP (Open-Closed) - Use strategy pattern or registry
  3. LSP (Liskov Substitution) - Honor base contracts
  4. ISP (Interface Segregation) - Split fat interfaces
  5. DIP (Dependency Inversion) - Inject dependencies
Before (OCP violation):
python
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)
After (OCP compliant):
python
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. SRP(单一职责) - 将职责拆分到多个模块
  2. OCP(开闭原则) - 使用策略模式或注册机制
  3. LSP(里氏替换) - 遵守基类契约
  4. ISP(接口隔离) - 拆分大接口
  5. DIP(依赖反转) - 注入依赖
重构前(违反OCP):
python
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":  # 新增类型需要修改代码!
        return process_crypto(amount)
重构后(符合OCP):
python
PROCESSORS = {
    "credit": process_credit,
    "debit": process_debit,
    "crypto": process_crypto,  # 在此添加,无需修改函数
}

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)

For Let It Crash Violations

针对Let It Crash违规

  1. Remove catch-all blocks - Let bugs surface
  2. Remove defensive guards - Validate at boundaries instead
  3. Flatten try/except - Handle at edges, not everywhere
Before (catch-all anti-pattern):
python
def get_user(user_id):
    try:
        user = db.query(User).get(user_id)
        return user
    except:  # BAD: catches everything, hides bugs
        return None
After (let it crash):
python
def get_user(user_id):
    # Let database errors surface - they indicate real problems
    return db.query(User).get(user_id)
  1. 移除全局捕获块 - 让bug暴露出来
  2. 移除防御性检查 - 改为在边界处验证
  3. 扁平化try/except - 在边缘处理,而非到处处理
重构前(全局捕获反模式):
python
def get_user(user_id):
    try:
        user = db.query(User).get(user_id)
        return user
    except:  # 错误:捕获所有异常,隐藏bug
        return None
重构后(Let It Crash):
python
def get_user(user_id):
    # 让数据库错误暴露出来 - 它们代表真实的问题
    return db.query(User).get(user_id)

Handle at the boundary (API layer)

在边界处处理(API层)

@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")
undefined
@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")
undefined

Examples

示例

Example 1: Full Validation

示例1:完整验证

bash
$ /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
bash
$ /sc:principles src/ --report

KISS验证:拦截
分析文件数:12
错误数:3,警告数:5

违规内容:
  [错误] src/services/order.py:45 process_order: 复杂度 = 15(最大值:10)
  [错误] src/utils/parser.py:12 parse_data: 长度 = 78(最大值:50)
  [警告] src/domain/calc.py:8 calculate: 参数 = 7(最大值:5)

纯函数验证:拦截
核心层违规数:2,外壳层警告数:1

违规内容:
  [错误] src/domain/user.py:23 get_status: 数据库 - db.query(上下文:核心层)
  [错误] src/services/report.py:56 generate: 文件I/O - open(上下文:核心层)

建议:
  - 复杂度:提取辅助函数,使用提前返回
  - 数据库:使用仓库模式。业务逻辑接收数据,而非直接查询
  - 文件I/O:将文件操作移至适配器层

Example 2: KISS Only

示例2:仅KISS验证

bash
$ /sc:principles src/ --kiss-only --threshold 8

KISS Validation: PASSED
Files analyzed: 12
Errors: 0, Warnings: 2
bash
$ /sc:principles src/ --kiss-only --threshold 8

KISS验证:通过
分析文件数:12
错误数:0,警告数:2

Example 3: Strict Mode

示例3:严格模式

bash
$ /sc:principles src/ --strict
bash
$ /sc:principles src/ --strict

All warnings become errors

所有警告均视为错误

Any warning will block

任何警告都会拦截提交

undefined
undefined

Quality Integration

质量集成

This skill integrates with SuperClaude quality gates:
  • Contributes to
    simplicity
    dimension (weight: 0.08)
  • Contributes to
    purity
    dimension (weight: 0.02)
  • Triggers
    simplification
    strategy when simplicity < 70
  • Triggers
    purification
    strategy when purity < 70
本技能与SuperClaude质量关卡集成:
  • 贡献于
    简洁性
    维度(权重:0.08)
  • 贡献于
    纯函数
    维度(权重:0.02)
  • 当简洁性 < 70时触发
    简化
    策略
  • 当纯函数得分 < 70时触发
    纯净化
    策略

Related Skills

相关技能

  • /sc:improve --type principles
    - Auto-refactor for principles compliance
  • /sc:implement
    - Includes principles validation by default
  • /sc:analyze
    - Code analysis includes principles metrics

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

Test Coverage

测试覆盖率

The validators have comprehensive test coverage (27 tests):
Purity Validator Tests:
  • Async function detection (
    async def
    )
  • Await expression detection
  • Async for loop detection
  • Async with context manager detection
  • Shell vs core severity differentiation
  • Edge cases (syntax errors, unicode, empty files)
KISS Validator Tests:
  • Function length (inclusive count)
  • Cyclomatic complexity
  • Cognitive complexity
  • Nesting depth
  • Parameter count
  • Edge cases (syntax errors, unicode, empty files)
Run tests:
bash
python -m pytest .claude/skills/sc-principles/tests/ -v

Version: 2.0.0 Validators:
validate_kiss.py
,
validate_purity.py
,
validate_solid.py
(heuristic),
validate_crash.py
(heuristic) Agent:
code-warden
Traits:
solid-aligned
,
crash-resilient
Tests: 27 passing (KISS + Purity)
验证器具有全面的测试覆盖率(27个测试用例):
纯函数验证器测试:
  • 异步函数检测(
    async def
  • Await表达式检测
  • 异步for循环检测
  • 异步with上下文管理器检测
  • 外壳层与核心层的严重程度区分
  • 边缘情况(语法错误、Unicode、空文件)
KISS验证器测试:
  • 函数长度(包含性计数)
  • 圈复杂度
  • 认知复杂度
  • 嵌套深度
  • 参数数量
  • 边缘情况(语法错误、Unicode、空文件)
运行测试:
bash
python -m pytest .claude/skills/sc-principles/tests/ -v

版本: 2.0.0 验证器:
validate_kiss.py
,
validate_purity.py
,
validate_solid.py
(启发式),
validate_crash.py
(启发式) Agent:
code-warden
特性:
solid-aligned
,
crash-resilient
测试: 27个通过(KISS + 纯函数)