ln-624-code-quality-auditor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Quality Auditor (L3 Worker)

代码质量审计器(L3工作器)

Specialized worker auditing code complexity, method signatures, algorithms, and constants management.
专注于审计代码复杂度、方法签名、算法和常量管理的工作器。

Purpose & Scope

目的与范围

  • Worker in ln-620 coordinator pipeline - invoked by ln-620-codebase-auditor
  • Audit code quality (Categories 5+6+NEW: Medium Priority)
  • Check complexity metrics, method signature quality, algorithmic efficiency, constants management
  • Return structured findings with severity, location, effort, recommendations
  • Calculate compliance score (X/10) for Code Quality category
  • ln-620协调器流水线中的工作器 - 由ln-620-codebase-auditor调用
  • 审计代码质量(第5+6类+新增:中等优先级)
  • 检查复杂度指标、方法签名质量、算法效率、常量管理情况
  • 返回包含严重程度、位置、修复工作量和建议的结构化检测结果
  • 计算代码质量类别的合规得分(X/10)

Inputs (from Coordinator)

输入(来自协调器)

MANDATORY READ: Load
shared/references/task_delegation_pattern.md#audit-coordinator--worker-contract
for contextStore structure.
Receives
contextStore
with:
tech_stack
,
best_practices
,
principles
,
codebase_root
.
Domain-aware: Supports
domain_mode
+
current_domain
(see
audit_output_schema.md#domain-aware-worker-output
).
必读: 加载
shared/references/task_delegation_pattern.md#audit-coordinator--worker-contract
以了解contextStore结构。
接收包含以下字段的
contextStore
tech_stack
best_practices
principles
codebase_root
领域感知: 支持
domain_mode
+
current_domain
(详见
audit_output_schema.md#domain-aware-worker-output
)。

Workflow

工作流程

  1. Parse context — extract fields, determine
    scan_path
    (domain-aware if specified)
  2. Scan codebase for violations
    • All Grep/Glob patterns use
      scan_path
      (not codebase_root)
    • Example:
      Grep(pattern="if.*if.*if", path=scan_path)
      for nesting detection
  3. Collect findings with severity, location, effort, recommendation
    • Tag each finding with
      domain: domain_name
      (if domain-aware)
  4. Calculate score using penalty algorithm
  5. Return JSON result to coordinator
    • Include
      domain
      and
      scan_path
      fields (if domain-aware)
  1. 解析上下文 — 提取字段,确定
    scan_path
    (若指定则采用领域感知路径)
  2. 扫描代码库以查找违规项
    • 所有Grep/Glob模式均使用
      scan_path
      (而非codebase_root)
    • 示例:使用
      Grep(pattern="if.*if.*if", path=scan_path)
      检测嵌套情况
  3. 收集包含严重程度、位置、修复工作量和建议的检测结果
    • 若为领域感知模式,为每个检测结果添加
      domain: domain_name
      标签
  4. 使用惩罚算法计算得分
  5. 向协调器返回JSON结果
    • 若为领域感知模式,包含
      domain
      scan_path
      字段

Audit Rules (Priority: MEDIUM)

审计规则(优先级:中等)

1. Cyclomatic Complexity

1. 圈复杂度

What: Too many decision points in single function (> 10)
Detection:
  • Count if/else, switch/case, ternary, &&, ||, for, while
  • Use tools:
    eslint-plugin-complexity
    ,
    radon
    (Python),
    gocyclo
    (Go)
Severity:
  • HIGH: Complexity > 20 (extremely hard to test)
  • MEDIUM: Complexity 11-20 (refactor recommended)
  • LOW: Complexity 8-10 (acceptable but monitor)
Recommendation: Split function, extract helper methods, use early returns
Effort: M-L (depends on complexity)
说明: 单个函数中的决策点过多(>10)
检测方式:
  • 统计if/else、switch/case、三元运算符、&&、||、for、while的数量
  • 使用工具:
    eslint-plugin-complexity
    radon
    (Python)、
    gocyclo
    (Go)
严重程度:
  • 高: 复杂度>20(极难测试)
  • 中: 复杂度11-20(建议重构)
  • 低: 复杂度8-10(可接受但需监控)
建议: 拆分函数、提取辅助方法、提前返回
修复工作量: M-L(取决于复杂度)

2. Deep Nesting (> 4 levels)

2. 深层嵌套(>4层)

What: Nested if/for/while blocks too deep
Detection:
  • Count indentation levels
  • Pattern: if { if { if { if { if { ... } } } } }
Severity:
  • HIGH: > 6 levels (unreadable)
  • MEDIUM: 5-6 levels
  • LOW: 4 levels
Recommendation: Extract functions, use guard clauses, invert conditions
Effort: M (refactor structure)
说明: if/for/while块嵌套过深
检测方式:
  • 统计缩进层级
  • 模式:if { if { if { if { if { ... } } } } }
严重程度:
  • 高: >6层(难以阅读)
  • 中: 5-6层
  • 低: 4层
建议: 提取函数、使用卫语句、反转条件
修复工作量: M(重构结构)

3. Long Methods (> 50 lines)

3. 过长方法(>50行)

What: Functions too long, doing too much
Detection:
  • Count lines between function start and end
  • Exclude comments, blank lines
Severity:
  • HIGH: > 100 lines
  • MEDIUM: 51-100 lines
  • LOW: 40-50 lines (borderline)
Recommendation: Split into smaller functions, apply Single Responsibility
Effort: M (extract logic)
说明: 函数过长,职责过多
检测方式:
  • 统计函数起始与结束之间的行数
  • 排除注释、空行
严重程度:
  • 高: >100行
  • 中: 51-100行
  • 低: 40-50行(临界值)
建议: 拆分为更小的函数,遵循单一职责原则
修复工作量: M(提取逻辑)

4. God Classes/Modules (> 500 lines)

4. 上帝类/模块(>500行)

What: Files with too many responsibilities
Detection:
  • Count lines in file (exclude comments)
  • Check number of public methods/functions
Severity:
  • HIGH: > 1000 lines
  • MEDIUM: 501-1000 lines
  • LOW: 400-500 lines
Recommendation: Split into multiple files, apply separation of concerns
Effort: L (major refactor)
说明: 文件职责过多
检测方式:
  • 统计文件行数(排除注释)
  • 检查公共方法/函数的数量
严重程度:
  • 高: >1000行
  • 中: 501-1000行
  • 低: 400-500行
建议: 拆分为多个文件,遵循关注点分离原则
修复工作量: L(重大重构)

5. Too Many Parameters (> 5)

5. 参数过多(>5个)

What: Functions with excessive parameters
Detection:
  • Count function parameters
  • Check constructors, methods
Severity:
  • MEDIUM: 6-8 parameters
  • LOW: 5 parameters (borderline)
Recommendation: Use parameter object, builder pattern, default parameters
Effort: S-M (refactor signature + calls)
说明: 函数参数数量过多
检测方式:
  • 统计函数参数数量
  • 检查构造函数、方法
严重程度:
  • 中: 6-8个参数
  • 低: 5个参数(临界值)
建议: 使用参数对象、构建器模式、默认参数
修复工作量: S-M(重构签名及调用方)

6. O(n²) or Worse Algorithms

6. O(n²)或更差的算法

What: Inefficient nested loops over collections
Detection:
  • Nested for loops:
    for (i) { for (j) { ... } }
  • Nested array methods:
    arr.map(x => arr.filter(...))
Severity:
  • HIGH: O(n²) in hot path (API request handler)
  • MEDIUM: O(n²) in occasional operations
  • LOW: O(n²) on small datasets (n < 100)
Recommendation: Use hash maps, optimize with single pass, use better data structures
Effort: M (algorithm redesign)
说明: 针对集合的低效嵌套循环
检测方式:
  • 嵌套for循环:
    for (i) { for (j) { ... } }
  • 嵌套数组方法:
    arr.map(x => arr.filter(...))
严重程度:
  • 高: 热点路径(API请求处理器)中存在O(n²)
  • 中: 偶尔执行的操作中存在O(n²)
  • 低: 小数据集(n<100)中存在O(n²)
建议: 使用哈希表、单遍优化、更优的数据结构
修复工作量: M(算法重设计)

7. N+1 Query Patterns

7. N+1查询模式

What: ORM lazy loading causing N+1 queries
Detection:
  • Find loops with database queries inside
  • Check ORM patterns:
    users.forEach(u => u.getPosts())
Severity:
  • CRITICAL: N+1 in API endpoint (performance disaster)
  • HIGH: N+1 in frequent operations
  • MEDIUM: N+1 in admin panel
Recommendation: Use eager loading, batch queries, JOIN
Effort: M (change ORM query)
说明: ORM延迟加载导致的N+1查询
检测方式:
  • 查找内部包含数据库查询的循环
  • 检查ORM模式:
    users.forEach(u => u.getPosts())
严重程度:
  • 关键: API端点中存在N+1查询(性能灾难)
  • 高: 频繁执行的操作中存在N+1查询
  • 中: 管理面板中存在N+1查询
建议: 使用预加载、批量查询、JOIN
修复工作量: M(修改ORM查询)

8. Constants Management (NEW)

8. 常量管理(新增)

What: Magic numbers/strings, decentralized constants, duplicates
Detection:
IssuePatternExample
Magic numbersHardcoded numbers in conditions/calculations
if (status === 2)
Magic stringsHardcoded strings in comparisons
if (role === 'admin')
DecentralizedConstants scattered across files
MAX_SIZE = 100
in 5 files
DuplicatesSame value multiple times
STATUS_ACTIVE = 1
in 3 places
No central fileMissing
constants.ts
or
config.py
No single source of truth
Severity:
  • HIGH: Magic numbers in business logic (payment amounts, statuses)
  • MEDIUM: Duplicate constants (same value defined 3+ times)
  • MEDIUM: No central constants file
  • LOW: Magic strings in logging/debugging
Recommendation:
  • Create central constants file (
    constants.ts
    ,
    config.py
    ,
    constants.go
    )
  • Extract magic numbers to named constants:
    const STATUS_ACTIVE = 1
  • Consolidate duplicates, import from central file
  • Use enums for related constants
Effort: M (extract constants, update imports, consolidate)
说明: 魔术数字/字符串、分散的常量、重复定义
检测方式:
问题模式示例
魔术数字条件/计算中使用硬编码数字
if (status === 2)
魔术字符串比较中使用硬编码字符串
if (role === 'admin')
分散定义常量分散在多个文件中5个文件中均定义
MAX_SIZE = 100
重复定义同一值多次定义3个位置均定义
STATUS_ACTIVE = 1
无中心文件缺少
constants.ts
config.py
无单一可信源
严重程度:
  • 高: 业务逻辑中使用魔术数字(支付金额、状态等)
  • 中: 重复定义的常量(同一值定义3次以上)
  • 中: 无中心常量文件
  • 低: 日志/调试中使用魔术字符串
建议:
  • 创建中心常量文件(
    constants.ts
    config.py
    constants.go
  • 将魔术数字提取为命名常量:
    const STATUS_ACTIVE = 1
  • 合并重复定义,从中心文件导入
  • 对相关常量使用枚举
修复工作量: M(提取常量、更新导入、合并定义)

9. Method Signature Quality

9. 方法签名质量

What: Poor method contracts reducing readability and maintainability
Detection:
IssuePatternExample
Boolean flag params>=2 boolean params in signature
def process(data, is_async: bool, skip_validation: bool)
Too many optional params>=3 optional params with defaults
def query(db, limit=10, offset=0, sort="id", order="asc")
Inconsistent verb namingDifferent verbs for same operation type in one module
get_user()
vs
fetch_account()
vs
load_profile()
Unclear return type
-> dict
,
-> Any
,
-> tuple
without TypedDict/NamedTuple
def get_stats() -> dict
instead of
-> StatsResponse
Severity:
  • MEDIUM: Boolean flag params (use enum/strategy), unclear return types
  • LOW: Too many optional params, inconsistent naming
Recommendation:
  • Boolean flags: replace with enum, strategy pattern, or separate methods
  • Optional params: group into config/options dataclass
  • Naming: standardize verb conventions per module (
    get_
    for sync,
    fetch_
    for async, etc.)
  • Return types: use TypedDict, NamedTuple, or dataclass instead of raw dict/tuple
Effort: S-M (refactor signatures + callers)
说明: 方法契约设计不佳,降低可读性和可维护性
检测方式:
问题模式示例
布尔标志参数签名中包含>=2个布尔参数
def process(data, is_async: bool, skip_validation: bool)
可选参数过多>=3个带默认值的可选参数
def query(db, limit=10, offset=0, sort="id", order="asc")
动词命名不一致同一模块中同一操作类型使用不同动词
get_user()
vs
fetch_account()
vs
load_profile()
返回类型不明确
-> dict
-> Any
-> tuple
未使用TypedDict/NamedTuple
def get_stats() -> dict
而非
-> StatsResponse
严重程度:
  • 中: 布尔标志参数(使用枚举/策略模式)、返回类型不明确
  • 低: 可选参数过多、命名不一致
建议:
  • 布尔标志:替换为枚举、策略模式或拆分方法
  • 可选参数:分组到配置/选项数据类中
  • 命名:按模块标准化动词约定(
    get_
    用于同步,
    fetch_
    用于异步等)
  • 返回类型:使用TypedDict、NamedTuple或数据类替代原始dict/tuple
修复工作量: S-M(重构签名及调用方)

Scoring Algorithm

评分算法

See
shared/references/audit_scoring.md
for unified formula and score interpretation.
统一公式及得分说明详见
shared/references/audit_scoring.md

Output Format

输出格式

Return JSON to coordinator:
Global mode output:
json
{
  "category": "Code Quality",
  "score": 6,
  "total_issues": 12,
  "critical": 1,
  "high": 3,
  "medium": 5,
  "low": 3,
  "checks": [
    {"id": "cyclomatic_complexity", "name": "Cyclomatic Complexity", "status": "failed", "details": "2 functions exceed threshold"},
    {"id": "deep_nesting", "name": "Deep Nesting", "status": "warning", "details": "1 function with 5 levels"},
    {"id": "long_methods", "name": "Long Methods", "status": "passed", "details": "No methods exceed 50 lines"},
    {"id": "magic_numbers", "name": "Magic Numbers", "status": "failed", "details": "5 magic numbers found"}
  ],
  "findings": [...]
}
Domain-aware mode output (NEW):
json
{
  "category": "Code Quality",
  "score": 7,
  "domain": "orders",
  "scan_path": "src/orders",
  "total_issues": 8,
  "critical": 0,
  "high": 2,
  "medium": 4,
  "low": 2,
  "checks": [
    {"id": "cyclomatic_complexity", "name": "Cyclomatic Complexity", "status": "failed", "details": "1 function exceeds threshold"},
    {"id": "deep_nesting", "name": "Deep Nesting", "status": "passed", "details": "No deep nesting detected"},
    {"id": "long_methods", "name": "Long Methods", "status": "passed", "details": "No methods exceed 50 lines"},
    {"id": "magic_numbers", "name": "Magic Numbers", "status": "warning", "details": "1 magic number found"}
  ],
  "findings": [
    {
      "severity": "HIGH",
      "location": "src/orders/services/OrderService.ts:120",
      "issue": "Cyclomatic complexity 22 (threshold: 10)",
      "principle": "Code Complexity / Maintainability",
      "recommendation": "Split into smaller methods",
      "effort": "M",
      "domain": "orders"
    },
    {
      "severity": "MEDIUM",
      "location": "src/orders/controllers/OrderController.ts:45",
      "issue": "Magic number '3' used for order status",
      "principle": "Constants Management",
      "recommendation": "Extract: const ORDER_STATUS_SHIPPED = 3",
      "effort": "S",
      "domain": "orders"
    }
  ]
}
向协调器返回JSON:
全局模式输出:
json
{
  "category": "Code Quality",
  "score": 6,
  "total_issues": 12,
  "critical": 1,
  "high": 3,
  "medium": 5,
  "low": 3,
  "checks": [
    {"id": "cyclomatic_complexity", "name": "Cyclomatic Complexity", "status": "failed", "details": "2 functions exceed threshold"},
    {"id": "deep_nesting", "name": "Deep Nesting", "status": "warning", "details": "1 function with 5 levels"},
    {"id": "long_methods", "name": "Long Methods", "status": "passed", "details": "No methods exceed 50 lines"},
    {"id": "magic_numbers", "name": "Magic Numbers", "status": "failed", "details": "5 magic numbers found"}
  ],
  "findings": [...]
}
领域感知模式输出(新增):
json
{
  "category": "Code Quality",
  "score": 7,
  "domain": "orders",
  "scan_path": "src/orders",
  "total_issues": 8,
  "critical": 0,
  "high": 2,
  "medium": 4,
  "low": 2,
  "checks": [
    {"id": "cyclomatic_complexity", "name": "Cyclomatic Complexity", "status": "failed", "details": "1 function exceeds threshold"},
    {"id": "deep_nesting", "name": "Deep Nesting", "status": "passed", "details": "No deep nesting detected"},
    {"id": "long_methods", "name": "Long Methods", "status": "passed", "details": "No methods exceed 50 lines"},
    {"id": "magic_numbers", "name": "Magic Numbers", "status": "warning", "details": "1 magic number found"}
  ],
  "findings": [
    {
      "severity": "HIGH",
      "location": "src/orders/services/OrderService.ts:120",
      "issue": "Cyclomatic complexity 22 (threshold: 10)",
      "principle": "Code Complexity / Maintainability",
      "recommendation": "Split into smaller methods",
      "effort": "M",
      "domain": "orders"
    },
    {
      "severity": "MEDIUM",
      "location": "src/orders/controllers/OrderController.ts:45",
      "issue": "Magic number '3' used for order status",
      "principle": "Constants Management",
      "recommendation": "Extract: const ORDER_STATUS_SHIPPED = 3",
      "effort": "S",
      "domain": "orders"
    }
  ]
}

Critical Rules

关键规则

  • Do not auto-fix: Report only
  • Domain-aware scanning: If
    domain_mode="domain-aware"
    , scan ONLY
    scan_path
    (not entire codebase)
  • Tag findings: Include
    domain
    field in each finding when domain-aware
  • Context-aware: Small functions (n < 100) with O(n²) may be acceptable
  • Constants detection: Exclude test files, configs, examples
  • Metrics tools: Use existing tools when available (ESLint complexity plugin, radon, gocyclo)
  • 禁止自动修复: 仅报告问题
  • 领域感知扫描:
    domain_mode="domain-aware"
    ,仅扫描
    scan_path
    (而非整个代码库)
  • 检测结果打标签: 领域感知模式下,每个检测结果需包含
    domain
    字段
  • 上下文感知: 小数据集(n<100)中的O(n²)函数可能是可接受的
  • 常量检测排除项: 排除测试文件、配置、示例
  • 指标工具: 优先使用现有工具(ESLint复杂度插件、radon、gocyclo)

Definition of Done

完成标准

  • contextStore parsed (including domain_mode and current_domain)
  • scan_path determined (domain path or codebase root)
  • All 9 checks completed (scoped to scan_path):
    • complexity, nesting, length, god classes, parameters, O(n²), N+1, constants, method signatures
  • Findings collected with severity, location, effort, recommendation, domain
  • Score calculated
  • JSON returned to coordinator with domain metadata
  • 已解析contextStore(包括domain_mode和current_domain)
  • 已确定scan_path(领域路径或代码库根目录)
  • 已完成全部9项检查(限定在scan_path范围内):
    • 复杂度、嵌套、长度、上帝类、参数、O(n²)、N+1、常量、方法签名
  • 已收集包含严重程度、位置、修复工作量、建议、领域的检测结果
  • 已计算得分
  • 已向协调器返回包含领域元数据的JSON

Reference Files

参考文件

  • Audit scoring formula:
    shared/references/audit_scoring.md
  • Audit output schema:
    shared/references/audit_output_schema.md
  • Code quality rules: references/code_quality_rules.md

Version: 3.0.0 Last Updated: 2025-12-23
  • 审计评分公式:
    shared/references/audit_scoring.md
  • 审计输出 schema:
    shared/references/audit_output_schema.md
  • 代码质量规则:references/code_quality_rules.md

版本: 3.0.0 最后更新: 2025-12-23