ln-640-pattern-evolution-auditor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Pattern Evolution Auditor

模式演进审核器

L2 Coordinator that analyzes implemented architectural patterns against current best practices, tracks evolution over time, and creates Stories for improvements.
一款L2协调工具,用于对照当前最佳实践分析已实现的架构模式,跟踪其随时间的演进情况,并创建用于改进的Story。

Purpose & Scope

目标与范围

  • Maintain
    docs/project/patterns_catalog.md
    with implemented patterns
  • Research best practices via MCP Ref, Context7, WebSearch
  • Audit layer boundaries via ln-642 (detect violations, check coverage)
  • Calculate 4 scores per pattern via ln-641
  • Create Stories for patterns with score < 70% via ln-220
  • Track quality trends over time (improving/stable/declining)
  • 维护
    docs/project/patterns_catalog.md
    文档,记录已实现的模式
  • 通过MCP Ref、Context7、WebSearch研究最佳实践
  • 通过ln-642审核层边界(检测违规情况,检查覆盖范围)
  • 通过ln-641为每个模式计算4项评分
  • 通过ln-220为评分<70%的模式创建Story
  • 跟踪质量趋势(提升/稳定/下降)

4-Score Model

4项评分模型

ScoreWhat it measuresThreshold
ComplianceIndustry standards, ADR/Guide, naming, layer boundaries70%
CompletenessAll components, error handling, tests, docs70%
QualityReadability, maintainability, no smells, SOLID, no duplication70%
ImplementationCode exists, production use, integrated, monitored70%
评分项衡量内容阈值
合规性行业标准、ADR/指南、命名规范、层边界70%
完整性所有组件、错误处理、测试、文档70%
质量可读性、可维护性、无代码异味、SOLID原则、无重复代码70%
实现度代码已存在、投入生产使用、已集成、已监控70%

Worker Invocation

工作单元调用

CRITICAL: All delegations use Task tool with
subagent_type: "general-purpose"
for context isolation.
WorkerPurposePhase
ln-641-pattern-analyzerCalculate 4 scores per patternPhase 4
ln-642-layer-boundary-auditorDetect layer violationsPhase 3
ln-643-api-contract-auditorAudit API contracts, DTOs, layer leakagePhase 4
ln-220-story-coordinatorCreate refactor StoriesPhase 6
Prompt template:
Task(description: "[Audit/Create] via ln-6XX",
     prompt: "Execute {skill-name}. Read skill from {skill-name}/SKILL.md. Pattern: {pattern}",
     subagent_type: "general-purpose")
Anti-Patterns:
  • ❌ Direct Skill tool invocation without Task wrapper
  • ❌ Any execution bypassing subagent context isolation
关键注意事项: 所有委托任务必须使用Task工具,并设置
subagent_type: "general-purpose"
以实现上下文隔离。
工作单元目标阶段
ln-641-pattern-analyzer为每个模式计算4项评分阶段4
ln-642-layer-boundary-auditor检测层违规情况阶段3
ln-643-api-contract-auditor审核API契约、DTO、层泄漏问题阶段4
ln-220-story-coordinator创建重构Story阶段6
提示模板:
Task(description: "[Audit/Create] via ln-6XX",
     prompt: "Execute {skill-name}. Read skill from {skill-name}/SKILL.md. Pattern: {pattern}",
     subagent_type: "general-purpose")
反模式:
  • ❌ 不使用Task包装器直接调用Skill工具
  • ❌ 任何绕过子代理上下文隔离的执行操作

Workflow

工作流程

Phase 1: Discovery

阶段1:发现

1. Load docs/project/patterns_catalog.md
   IF missing → create from shared/templates/patterns_template.md

2. Load docs/reference/adrs/*.md → link patterns to ADRs
   Load docs/reference/guides/*.md → link patterns to Guides

3. Auto-detect undocumented patterns
   Use patterns from common_patterns.md "Pattern Detection" table
   IF found but not in catalog → add as "Undocumented"
1. 加载docs/project/patterns_catalog.md
   若文件缺失 → 从shared/templates/patterns_template.md创建

2. 加载docs/reference/adrs/*.md → 将模式与ADR关联
   加载docs/reference/guides/*.md → 将模式与指南关联

3. 自动检测未记录的模式
   使用common_patterns.md中"Pattern Detection"表格里的模式
   若在代码中发现但未在目录中记录 → 标记为"未记录"

Phase 2: Best Practices Research

阶段2:最佳实践研究

FOR EACH pattern WHERE last_audit > 30 days OR never:

  # MCP Ref + Context7 + WebSearch
  ref_search_documentation("{pattern} best practices {tech_stack}")
  IF pattern.library: query-docs(library_id, "{pattern}")
  WebSearch("{pattern} implementation best practices 2026")

  → Store: contextStore.bestPractices[pattern]
FOR EACH pattern WHERE last_audit > 30 days OR never:

  # MCP Ref + Context7 + WebSearch
  ref_search_documentation("{pattern} best practices {tech_stack}")
  IF pattern.library: query-docs(library_id, "{pattern}")
  WebSearch("{pattern} implementation best practices 2026")

  → 存储至: contextStore.bestPractices[pattern]

Phase 3: Layer Boundary Audit

阶段3:层边界审核

Task(ln-642-layer-boundary-auditor)
  Input: architecture_path, codebase_root, skip_violations
  Output: violations[], coverage{}
Task(ln-642-layer-boundary-auditor)
  Input: architecture_path, codebase_root, skip_violations
  Output: violations[], coverage{}

Apply deductions to affected patterns (per scoring_rules.md)

根据scoring_rules.md对受影响的模式扣分

FOR EACH violation IN violations: affected_pattern = match_violation_to_pattern(violation) affected_pattern.issues.append(violation) affected_pattern.compliance_deduction += get_deduction(violation)
undefined
FOR EACH violation IN violations: affected_pattern = match_violation_to_pattern(violation) affected_pattern.issues.append(violation) affected_pattern.compliance_deduction += get_deduction(violation)
undefined

Phase 4: Pattern Analysis Loop

阶段4:模式分析循环

undefined
undefined

Analyze individual patterns

分析单个模式

FOR EACH pattern IN catalog: Task(ln-641-pattern-analyzer) Input: pattern, locations, adr_reference, bestPractices Output: scores{}, issues[], gaps{}
FOR EACH pattern IN catalog: Task(ln-641-pattern-analyzer) Input: pattern, locations, adr_reference, bestPractices Output: scores{}, issues[], gaps{}

Analyze API contracts (always, in parallel with patterns)

分析API契约(始终与模式分析并行执行)

Task(ln-643-api-contract-auditor) Input: pattern="API Contracts", locations=[service_dirs, api_dirs], bestPractices Output: scores{}, issues[], gaps{}
Worker Output Contract:
  • ln-641 returns:
    {overall_score: X.X, scores: {compliance, completeness, quality, implementation}, issues: [], gaps: {}}
  • ln-642 returns:
    {category, score, total_issues, critical, high, medium, low, findings: []}
  • ln-643 returns:
    {overall_score: X.X, scores: {compliance, completeness, quality, implementation}, issues: [], gaps: {}}

Merge layer violations from Phase 3

pattern.issues += layer_violations.filter(v => v.pattern == pattern) pattern.scores.compliance -= compliance_deduction pattern.scores.quality -= quality_deduction
undefined
Task(ln-643-api-contract-auditor) Input: pattern="API Contracts", locations=[service_dirs, api_dirs], bestPractices Output: scores{}, issues[], gaps{}
工作单元输出契约:
  • ln-641返回:
    {overall_score: X.X, scores: {compliance, completeness, quality, implementation}, issues: [], gaps: {}}
  • ln-642返回:
    {category, score, total_issues, critical, high, medium, low, findings: []}
  • ln-643返回:
    {overall_score: X.X, scores: {compliance, completeness, quality, implementation}, issues: [], gaps: {}}

合并阶段3的层违规情况

pattern.issues += layer_violations.filter(v => v.pattern == pattern) pattern.scores.compliance -= compliance_deduction pattern.scores.quality -= quality_deduction
undefined

Phase 5: Gap Analysis

阶段5:差距分析

gaps = {
  undocumentedPatterns: found in code but not in catalog,
  implementationGaps: ADR decisions not implemented,
  layerViolations: code in wrong architectural layers,
  consistencyIssues: conflicting patterns
}
gaps = {
  undocumentedPatterns: 在代码中发现但未在目录中记录的模式,
  implementationGaps: 未实现的ADR决策,
  layerViolations: 位于错误架构层的代码,
  consistencyIssues: 冲突的模式
}

Phase 6: Story Creation (via ln-220)

阶段6:Story创建(通过ln-220)

REFACTORING PRINCIPLE (MANDATORY):
Stories MUST include: "Zero Legacy / Zero Backward Compatibility" — no compatibility hacks, clean architecture is priority.
refactorItems = patterns WHERE any_score < 70%

IF refactorItems.length > 0:
  # Auto-detect Epic (Architecture/Refactoring/Technical Debt)
  targetEpic = find_epic(["Architecture", "Refactoring", "Technical Debt"])
  IF not found → AskUserQuestion

  FOR EACH pattern IN refactorItems:
    Task(ln-220-story-coordinator)
      Create Story with AC from issues list
      MANDATORY AC: Zero Legacy principle
重构原则(强制要求):
Story必须包含:"零遗留/零向后兼容" — 不允许兼容性 hack,优先考虑整洁架构。
refactorItems = patterns WHERE any_score < 70%

IF refactorItems.length > 0:
  # 自动检测Epic(Architecture/Refactoring/Technical Debt)
  targetEpic = find_epic(["Architecture", "Refactoring", "Technical Debt"])
  若未找到 → 询问用户

  FOR EACH pattern IN refactorItems:
    Task(ln-220-story-coordinator)
      根据问题列表创建包含验收标准(AC)的Story
      强制验收标准:零遗留原则

Aggregation Algorithm

聚合算法

undefined
undefined

Step 1: Get all worker scores (0-10 scale)

步骤1:获取所有工作单元的评分(0-10分)

pattern_scores = [p.overall_score for p in ln641_results] # Each 0-10 layer_score = ln642_result.score # 0-10 api_score = ln643_result.overall_score # 0-10
pattern_scores = [p.overall_score for p in ln641_results] # 每项0-10分 layer_score = ln642_result.score # 0-10分 api_score = ln643_result.overall_score # 0-10分

Step 2: Calculate architecture_health_score

步骤2:计算架构健康评分

all_scores = pattern_scores + [layer_score, api_score] architecture_health_score = round(average(all_scores) * 10) # 0-100 scale
all_scores = pattern_scores + [layer_score, api_score] architecture_health_score = round(average(all_scores) * 10) # 转换为0-100分制

Status mapping:

状态映射:

>= 80: "healthy"

>= 80: "健康"

70-79: "warning"

70-79: "警告"

< 70: "critical"

< 70: "严重"

undefined
undefined

Phase 7: Report + Trend Analysis

阶段7:报告 + 趋势分析

1. Update patterns_catalog.md:
   - Pattern scores, dates, Story links
   - Layer Boundary Status section
   - Quick Wins section
   - Patterns Requiring Attention section

2. Calculate trend: compare current vs previous scores

3. Output summary (see Return Result below)
1. 更新patterns_catalog.md:
   - 模式评分、日期、Story链接
   - 层边界状态章节
   - 快速改进项章节
   - 需要关注的模式章节

2. 计算趋势:对比当前评分与历史评分

3. 输出摘要(见下方返回结果)

Phase 7: Return Result

阶段7:返回结果

json
{
  "audit_date": "2026-02-04",
  "architecture_health_score": 78,
  "trend": "improving",
  "patterns_analyzed": 5,
  "layer_audit": {
    "architecture_type": "Layered",
    "violations_total": 5,
    "violations_by_severity": {"high": 2, "medium": 3, "low": 0},
    "coverage": {"http_abstraction": 85, "error_centralization": true}
  },
  "patterns": [
    {
      "name": "Job Processing",
      "scores": {"compliance": 72, "completeness": 85, "quality": 68, "implementation": 90},
      "avg_score": 79,
      "status": "warning",
      "issues_count": 3,
      "story_created": "LIN-123"
    }
  ],
  "quick_wins": [
    {"pattern": "Caching", "issue": "Add TTL config", "effort": "2h", "impact": "+10 completeness"}
  ],
  "requires_attention": [
    {"pattern": "Event-Driven", "avg_score": 58, "critical_issues": ["No DLQ", "No schema versioning"]}
  ],
  "stories_created": ["LIN-123", "LIN-124"]
}
json
{
  "audit_date": "2026-02-04",
  "architecture_health_score": 78,
  "trend": "improving",
  "patterns_analyzed": 5,
  "layer_audit": {
    "architecture_type": "Layered",
    "violations_total": 5,
    "violations_by_severity": {"high": 2, "medium": 3, "low": 0},
    "coverage": {"http_abstraction": 85, "error_centralization": true}
  },
  "patterns": [
    {
      "name": "Job Processing",
      "scores": {"compliance": 72, "completeness": 85, "quality": 68, "implementation": 90},
      "avg_score": 79,
      "status": "warning",
      "issues_count": 3,
      "story_created": "LIN-123"
    }
  ],
  "quick_wins": [
    {"pattern": "Caching", "issue": "Add TTL config", "effort": "2h", "impact": "+10 completeness"}
  ],
  "requires_attention": [
    {"pattern": "Event-Driven", "avg_score": 58, "critical_issues": ["No DLQ", "No schema versioning"]}
  ],
  "stories_created": ["LIN-123", "LIN-124"]
}

Critical Rules

关键规则

  • MCP Ref first: Always research best practices before analysis
  • Layer audit first: Run ln-642 before ln-641 pattern analysis
  • 4 scores mandatory: Never skip any score calculation
  • Layer deductions: Apply scoring_rules.md deductions for violations
  • ln-220 for Stories: Create Stories, not standalone tasks
  • Zero Legacy: Refactor Stories must include "no backward compatibility" AC
  • Auto-detect Epic: Only ask user if cannot determine automatically
  • 优先使用MCP Ref: 分析前必须先研究最佳实践
  • 先审核层边界: 运行ln-642后再执行ln-641模式分析
  • 必须计算4项评分: 不得跳过任何一项评分计算
  • 层违规扣分: 根据scoring_rules.md对违规情况扣分
  • 通过ln-220创建Story: 创建Story而非独立任务
  • 零遗留原则: 重构Story必须包含"无向后兼容"的验收标准
  • 自动检测Epic: 仅在无法自动确定时询问用户

Definition of Done

完成定义

  • Pattern catalog loaded or created
  • Best practices researched for all patterns needing audit
  • Layer boundaries audited via ln-642 (violations detected, coverage calculated)
  • All patterns analyzed via ln-641 (4 scores with layer deductions applied)
  • Gaps identified (undocumented, unimplemented, layer violations, inconsistent)
  • Stories created via ln-220 for patterns with score < 70%
  • Catalog updated with scores, dates, Layer Boundary Status, Story links
  • Trend analysis completed
  • Summary report output
  • 已加载或创建模式目录
  • 已为所有需要审核的模式研究最佳实践
  • 已通过ln-642审核层边界(检测到违规情况,计算了覆盖范围)
  • 已通过ln-641分析所有模式(应用层违规扣分后的4项评分)
  • 已识别差距(未记录、未实现、层违规、不一致)
  • 已通过ln-220为评分<70%的模式创建Story
  • 已更新目录,包含评分、日期、层边界状态、Story链接
  • 已完成趋势分析
  • 已输出摘要报告

Reference Files

参考文件

  • Task delegation pattern:
    shared/references/task_delegation_pattern.md
  • Pattern catalog template:
    shared/templates/patterns_template.md
  • Common patterns detection:
    references/common_patterns.md
  • Scoring rules:
    references/scoring_rules.md
  • Pattern analysis:
    ../ln-641-pattern-analyzer/SKILL.md
  • Layer boundary audit:
    ../ln-642-layer-boundary-auditor/SKILL.md
  • API contract audit:
    ../ln-643-api-contract-auditor/SKILL.md
  • Story creation:
    ../ln-220-story-coordinator/SKILL.md

Version: 1.1.0 Last Updated: 2026-01-29
  • 任务委托模式:
    shared/references/task_delegation_pattern.md
  • 模式目录模板:
    shared/templates/patterns_template.md
  • 常见模式检测:
    references/common_patterns.md
  • 评分规则:
    references/scoring_rules.md
  • 模式分析:
    ../ln-641-pattern-analyzer/SKILL.md
  • 层边界审核:
    ../ln-642-layer-boundary-auditor/SKILL.md
  • API契约审核:
    ../ln-643-api-contract-auditor/SKILL.md
  • Story创建:
    ../ln-220-story-coordinator/SKILL.md

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