ln-641-pattern-analyzer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Pattern Analyzer

模式分析器

L3 Worker that analyzes a single architectural pattern against best practices and calculates 4 scores.
一款L3 Worker,用于对照最佳实践分析单一架构模式并计算4项评分。

Purpose & Scope

目标与范围

  • Analyze ONE pattern per invocation (receives pattern name, locations, best practices from coordinator)
  • Find all implementations in codebase (Glob/Grep)
  • Validate implementation exists and works
  • Calculate 4 scores: compliance, completeness, quality, implementation
  • Identify gaps and issues with severity and effort estimates
  • Return structured analysis result to coordinator
  • 每次调用仅分析一种模式(从协调器接收模式名称、位置、最佳实践)
  • 在代码库中查找所有实现(使用Glob/Grep)
  • 验证实现是否存在且可用
  • 计算4项评分:合规性、完整性、质量、实现度
  • 识别差距与问题,并标注严重程度和工作量估算
  • 向协调器返回结构化分析结果

Input (from ln-640 coordinator)

输入(来自ln-640协调器)

- pattern: string          # Pattern name (e.g., "Job Processing")
- locations: string[]      # Known file paths/directories
- adr_reference: string    # Path to related ADR (if exists)
- bestPractices: object    # Best practices from MCP Ref/Context7/WebSearch
- pattern: string          # Pattern name (e.g., "Job Processing")
- locations: string[]      # Known file paths/directories
- adr_reference: string    # Path to related ADR (if exists)
- bestPractices: object    # Best practices from MCP Ref/Context7/WebSearch

Workflow

工作流程

Phase 1: Find Implementations

阶段1:查找实现

undefined
undefined

Use locations from coordinator + additional search

Use locations from coordinator + additional search

files = [] files.append(Glob(locations))
files = [] files.append(Glob(locations))

Expand search using common_patterns.md grep patterns

Expand search using common_patterns.md grep patterns

IF pattern == "Job Processing": files.append(Grep("Queue|Worker|Job|Bull|BullMQ", "/*.{ts,js,py}")) IF pattern == "Event-Driven": files.append(Grep("EventEmitter|publish|subscribe|on\(", "/*.{ts,js,py}"))
IF pattern == "Job Processing": files.append(Grep("Queue|Worker|Job|Bull|BullMQ", "/*.{ts,js,py}")) IF pattern == "Event-Driven": files.append(Grep("EventEmitter|publish|subscribe|on\(", "/*.{ts,js,py}"))

... etc

... etc

deduplicate(files)
undefined
deduplicate(files)
undefined

Phase 2: Read and Analyze Code

阶段2:读取并分析代码

FOR EACH file IN files (limit: 10 key files):
  Read(file)
  Extract:
    - Components implemented
    - Patterns used
    - Error handling approach
    - Logging/observability
    - Tests coverage
FOR EACH file IN files (limit: 10 key files):
  Read(file)
  Extract:
    - Components implemented
    - Patterns used
    - Error handling approach
    - Logging/observability
    - Tests coverage

Phase 3: Calculate 4 Scores

阶段3:计算4项评分

Compliance Score (0-100):
score = 0
合规性评分(0-100):
score = 0

Detection: ADR documentation exists

Detection: ADR documentation exists

IF Glob("docs/adr/{pattern}.md") OR Glob("docs/architecture/*.md" contains pattern): +20
IF Glob("docs/adr/{pattern}.md") OR Glob("docs/architecture/*.md" contains pattern): +20

Detection: Standard naming conventions

Detection: Standard naming conventions

IF Grep("class.*{Pattern}(Service|Handler|Worker|Processor)", files): +15 IF file names follow pattern (e.g., job_processor.py, event_handler.ts): +15
IF Grep("class.*{Pattern}(Service|Handler|Worker|Processor)", files): +15 IF file names follow pattern (e.g., job_processor.py, event_handler.ts): +15

Detection: No anti-patterns

Detection: No anti-patterns

IF NOT Grep("(callback hell|Promise.all without error|global state)", files): +20
IF NOT Grep("(callback hell|Promise\.all without error|global state)", files): +20

Detection: Industry standard structure

Detection: Industry standard structure

IF pattern == "Job Processing": IF Grep("(queue|worker|job|processor)", files) AND Grep("(retry|backoff|dlq)", files): +30 IF pattern == "Event-Driven": IF Grep("(EventEmitter|publish|subscribe|emit)", files) AND Grep("(schema|validate)", files): +30

**Completeness Score (0-100):**
score = 0
IF pattern == "Job Processing": IF Grep("(queue|worker|job|processor)", files) AND Grep("(retry|backoff|dlq)", files): +30 IF pattern == "Event-Driven": IF Grep("(EventEmitter|publish|subscribe|emit)", files) AND Grep("(schema|validate)", files): +30

**完整性评分(0-100):**
score = 0

Detection: Required components present

Detection: Required components present

component_patterns = bestPractices[pattern].required_components # from coordinator FOR EACH component IN component_patterns: IF Grep(component.grep_pattern, files): +component.weight # Total: 40 points
component_patterns = bestPractices[pattern].required_components # from coordinator FOR EACH component IN component_patterns: IF Grep(component.grep_pattern, files): +component.weight # Total: 40 points

Detection: Error handling

Detection: Error handling

IF Grep("(try|catch|except|error|Error|Exception)", files): +10 IF Grep("(retry|backoff|circuit.?breaker)", files): +10
IF Grep("(try|catch|except|error|Error|Exception)", files): +10 IF Grep("(retry|backoff|circuit.?breaker)", files): +10

Detection: Logging/observability

Detection: Logging/observability

IF Grep("(logger|logging|log\.|console\.log|structlog)", files): +10 IF Grep("(metrics|prometheus|statsd|trace)", files): +5
IF Grep("(logger|logging|log\.|console\.log|structlog)", files): +10 IF Grep("(metrics|prometheus|statsd|trace)", files): +5

Detection: Tests exist

Detection: Tests exist

IF Glob("/test*{pattern}*") OR Glob("/{pattern}.test.*"): +15
IF Glob("/test*{pattern}*") OR Glob("/{pattern}.test.*"): +15

Detection: Documentation

Detection: Documentation

IF Grep("docstring|@param|@returns|"""", files): +10

**Quality Score (0-100):**
score = 0
IF Grep("docstring|@param|@returns|"""", files): +10

**质量评分(0-100):**
score = 0

Detection: Short methods (<50 lines)

Detection: Short methods (<50 lines)

method_lengths = analyze_method_lengths(files) IF average(method_lengths) < 30: +25 ELIF average(method_lengths) < 50: +15
method_lengths = analyze_method_lengths(files) IF average(method_lengths) < 30: +25 ELIF average(method_lengths) < 50: +15

Detection: Low cyclomatic complexity

Detection: Low cyclomatic complexity

IF NOT Grep("(if.*if.*if|for.*for.*for|switch.*case.*case.*case)", files): +25
IF NOT Grep("(if.*if.*if|for.*for.*for|switch.*case.*case.*case)", files): +25

Detection: No code smells

Detection: No code smells

IF NOT Grep("(TODO|FIXME|HACK|XXX|REFACTOR)", files): +10 IF NOT Grep("(magic number|hardcoded)", files): +10
IF NOT Grep("(TODO|FIXME|HACK|XXX|REFACTOR)", files): +10 IF NOT Grep("(magic number|hardcoded)", files): +10

Detection: SOLID principles

Detection: SOLID principles

IF Grep("(interface|abstract|Protocol|ABC)", files): # Dependency Inversion +15
IF Grep("(interface|abstract|Protocol|ABC)", files): # Dependency Inversion +15

Detection: Performance patterns

Detection: Performance patterns

IF Grep("(async|await|asyncio|Promise)", files): # Non-blocking +10 IF Grep("(cache|memoize|lru_cache)", files): +5

**Implementation Score (0-100):**
score = 0
IF Grep("(async|await|asyncio|Promise)", files): # Non-blocking +10 IF Grep("(cache|memoize|lru_cache)", files): +5

**实现度评分(0-100):**
score = 0

Detection: Code compiles/runs

Detection: Code compiles/runs

IF no syntax errors in files: +30
IF no syntax errors in files: +30

Detection: Used in production (imported elsewhere)

Detection: Used in production (imported elsewhere)

imports = Grep("from.{pattern}|import.{pattern}", codebase_root, exclude=files) IF len(imports) > 0: +25
imports = Grep("from.{pattern}|import.{pattern}", codebase_root, exclude=files) IF len(imports) > 0: +25

Detection: No dead code

Detection: No dead code

unused_exports = find_unused_exports(files) IF len(unused_exports) == 0: +15
unused_exports = find_unused_exports(files) IF len(unused_exports) == 0: +15

Detection: Integrated with other patterns

Detection: Integrated with other patterns

IF Grep("(dependency.?injection|@inject|container)", files): +10 IF Grep("(config|settings|env)", files): +5
IF Grep("(dependency.?injection|@inject|container)", files): +10 IF Grep("(config|settings|env)", files): +5

Detection: Monitored

Detection: Monitored

IF Grep("(health.?check|readiness|liveness|/health)", files): +10 IF Grep("(alert|alarm|notification)", files): +5
undefined
IF Grep("(health.?check|readiness|liveness|/health)", files): +10 IF Grep("(alert|alarm|notification)", files): +5
undefined

Phase 4: Identify Issues and Gaps

阶段4:识别问题与差距

issues = []
FOR EACH bestPractice IN bestPractices:
  IF NOT implemented:
    issues.append({
      severity: "HIGH" | "MEDIUM" | "LOW",
      category: "compliance" | "completeness" | "quality" | "implementation",
      issue: description,
      suggestion: how to fix,
      effort: estimate ("2h", "4h", "1d", "3d")
    })

gaps = {
  undocumented: aspects not in ADR,
  unimplemented: ADR decisions not in code
}

recommendations = [
  "Create ADR for X",
  "Update existing ADR with Y",
  "Refactor Z to match pattern"
]
issues = []
FOR EACH bestPractice IN bestPractices:
  IF NOT implemented:
    issues.append({
      severity: "HIGH" | "MEDIUM" | "LOW",
      category: "compliance" | "completeness" | "quality" | "implementation",
      issue: description,
      suggestion: how to fix,
      effort: estimate ("2h", "4h", "1d", "3d")
    })

gaps = {
  undocumented: aspects not in ADR,
  unimplemented: ADR decisions not in code
}

recommendations = [
  "Create ADR for X",
  "Update existing ADR with Y",
  "Refactor Z to match pattern"
]

Phase 5: Calculate Overall Score

阶段5:计算总体评分

overall_score = average(compliance, completeness, quality, implementation) / 10
Example: (72 + 85 + 68 + 90) / 4 / 10 = 7.9
overall_score = average(compliance, completeness, quality, implementation) / 10
Example: (72 + 85 + 68 + 90) / 4 / 10 = 7.9

Phase 6: Return Result

阶段6:返回结果

json
{
  "pattern": "Job Processing",
  "overall_score": 7.9,
  "scores": {
    "compliance": 72,
    "completeness": 85,
    "quality": 68,
    "implementation": 90
  },
  "checks": [
    {"id": "compliance_check", "name": "Compliance Check", "status": "passed", "details": "ADR exists, standard naming, no anti-patterns"},
    {"id": "completeness_check", "name": "Completeness Check", "status": "warning", "details": "Missing retry logic documentation"},
    {"id": "quality_check", "name": "Quality Check", "status": "failed", "details": "Average method length 45 lines, TODO comments found"},
    {"id": "implementation_check", "name": "Implementation Check", "status": "passed", "details": "Code compiles, used in production, integrated with DI"}
  ],
  "codeReferences": [
    "src/jobs/processor.ts",
    "src/workers/base.ts"
  ],
  "issues": [
    {
      "severity": "HIGH",
      "category": "quality",
      "issue": "No dead letter queue",
      "suggestion": "Add Bull DLQ configuration",
      "effort": "4h"
    }
  ],
  "gaps": {
    "undocumented": ["Error recovery strategy"],
    "unimplemented": ["Job prioritization from ADR"]
  },
  "recommendations": [
    "Create ADR for dead letter queue strategy"
  ]
}
json
{
  "pattern": "Job Processing",
  "overall_score": 7.9,
  "scores": {
    "compliance": 72,
    "completeness": 85,
    "quality": 68,
    "implementation": 90
  },
  "checks": [
    {"id": "compliance_check", "name": "Compliance Check", "status": "passed", "details": "ADR exists, standard naming, no anti-patterns"},
    {"id": "completeness_check", "name": "Completeness Check", "status": "warning", "details": "Missing retry logic documentation"},
    {"id": "quality_check", "name": "Quality Check", "status": "failed", "details": "Average method length 45 lines, TODO comments found"},
    {"id": "implementation_check", "name": "Implementation Check", "status": "passed", "details": "Code compiles, used in production, integrated with DI"}
  ],
  "codeReferences": [
    "src/jobs/processor.ts",
    "src/workers/base.ts"
  ],
  "issues": [
    {
      "severity": "HIGH",
      "category": "quality",
      "issue": "No dead letter queue",
      "suggestion": "Add Bull DLQ configuration",
      "effort": "4h"
    }
  ],
  "gaps": {
    "undocumented": ["Error recovery strategy"],
    "unimplemented": ["Job prioritization from ADR"]
  },
  "recommendations": [
    "Create ADR for dead letter queue strategy"
  ]
}

Critical Rules

关键规则

  • One pattern only: Analyze only the pattern passed by coordinator
  • Read before score: Never score without reading actual code
  • Effort estimates: Always provide realistic effort for each issue
  • Best practices comparison: Use bestPractices from coordinator, not assumptions
  • Code references: Always include file paths for findings
  • 单一模式: 仅分析协调器传入的模式
  • 先读取再评分: 绝不在未读取实际代码的情况下进行评分
  • 工作量估算: 始终为每个问题提供符合实际的工作量估算
  • 对照最佳实践: 使用协调器提供的最佳实践,而非主观假设
  • 代码引用: 始终为发现的问题包含文件路径

Definition of Done

完成定义

  • All implementations found via Glob/Grep
  • Key files read and analyzed
  • 4 scores calculated with justification
  • Issues identified with severity, category, suggestion, effort
  • Gaps documented (undocumented, unimplemented)
  • Recommendations provided
  • Structured result returned to coordinator
  • 通过Glob/Grep找到所有实现
  • 读取并分析关键文件
  • 计算4项评分并提供依据
  • 识别问题并标注严重程度、类别、建议与工作量
  • 记录差距(未文档化、未实现)
  • 提供改进建议
  • 向协调器返回结构化结果

Reference Files

参考文件

  • Scoring rules:
    ../ln-640-pattern-evolution-auditor/references/scoring_rules.md
  • Common patterns:
    ../ln-640-pattern-evolution-auditor/references/common_patterns.md

Version: 1.0.0 Last Updated: 2026-01-29
  • 评分规则:
    ../ln-640-pattern-evolution-auditor/references/scoring_rules.md
  • 常见模式:
    ../ln-640-pattern-evolution-auditor/references/common_patterns.md

版本: 1.0.0 最后更新: 2026-01-29