code-analysis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

.NET Code Analysis

.NET 代码分析

Trigger On

触发场景

  • the repo wants first-party .NET analyzers
  • CI should fail on analyzer warnings
  • the team needs
    AnalysisLevel
    or
    AnalysisMode
    guidance
  • the repo needs a gradual Roslyn warning promotion strategy
  • 仓库需要官方.NET分析器
  • CI需因分析器警告而失败
  • 团队需要
    AnalysisLevel
    AnalysisMode
    相关指导
  • 仓库需要Roslyn警告逐步升级策略

Do Not Use For

不适用场景

  • third-party analyzer selection by itself
  • formatting-only work
  • 仅选择第三方分析器
  • 仅做格式调整操作

Inputs

输入项

  • the nearest
    AGENTS.md
  • project files or
    Directory.Build.props
  • current analyzer severity policy
  • 最近的
    AGENTS.md
    文件
  • 项目文件或
    Directory.Build.props
  • 当前分析器严重性策略

Hard Rules for AI Agents

AI Agent 硬性规则

Non-negotiable. Violating these undermines the user's explicit intent.
  1. Never disable or remove
    TreatWarningsAsErrors
    or
    WarningsAsErrors
    if the project has set them. Do not comment them out, set to
    false
    , wrap in a condition, or add
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
    to make the build pass.
  2. Never add
    <NoWarn>
    or
    #pragma warning disable
    for warnings the user chose to treat as errors, unless the user explicitly approves the suppression.
  3. Never silently downgrade severity in
    .editorconfig
    (e.g.
    error
    to
    warning
    or
    none
    ) to make a build succeed.
  4. If warnings-as-errors breaks the build — fix the code. If the fix is too large, ask the user whether to defer that warning ID.
  5. If warning volume is too large to fix in one pass — report count and categories to the user and ask which to tackle first. Do not unilaterally disable the policy.
不可协商。违反这些规则会违背用户的明确意图。
  1. 如果项目已设置
    TreatWarningsAsErrors
    WarningsAsErrors
    ,绝不能禁用或移除它们。不要注释掉、设为
    false
    、添加条件包裹,或添加
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
    来让构建通过。
  2. 绝不能为用户选择视为错误的警告添加
    <NoWarn>
    #pragma warning disable
    ,除非用户明确批准抑制该警告。
  3. 绝不能在
    .editorconfig
    中悄悄降低严重性(例如从
    error
    改为
    warning
    none
    )来让构建成功。
  4. 如果“将警告视为错误”导致构建失败——修复代码。如果修复工作量太大,请询问用户是否推迟处理该警告ID。
  5. 如果警告数量过多,无法一次性修复——向用户报告警告数量和类别,询问优先处理哪些。不要单方面禁用该策略。

Workflow

工作流程

mermaid
flowchart TD
    A[Start] --> B{New or legacy project?}
    B -->|New| C[TreatWarningsAsErrors=true immediately]
    B -->|Legacy| D[dotnet build, count warnings by ID]
    D --> E{"< 30 warnings?"}
    E -->|Yes| F[Fix all, then enable TreatWarningsAsErrors]
    E -->|No| G[Report counts to user, ask which batch first]
    G --> H[Add selected IDs to WarningsAsErrors]
    H --> I[Fix that batch, verify build]
    I --> J{More batches?}
    J -->|Yes| G
    J -->|No| F
    C --> K[Set AnalysisLevel latest-recommended]
    F --> K
    K --> L[Promote security CA3xxx/CA5xxx to error in .editorconfig]
    L --> M[Validate: build + CI green]
  1. Start with SDK analyzers before third-party packages.
  2. Detect project maturity: new or existing/legacy.
  3. Enable
    EnableNETAnalyzers
    ,
    AnalysisLevel
    ,
    AnalysisMode
    in
    Directory.Build.props
    .
  4. Apply the right warning promotion strategy (see below).
  5. Per-rule severity goes in repo-root
    .editorconfig
    .
  6. dotnet build
    is the analyzer gate in CI.
mermaid
flowchart TD
    A[Start] --> B{New or legacy project?}
    B -->|New| C[TreatWarningsAsErrors=true immediately]
    B -->|Legacy| D[dotnet build, count warnings by ID]
    D --> E{"< 30 warnings?"}
    E -->|Yes| F[Fix all, then enable TreatWarningsAsErrors]
    E -->|No| G[Report counts to user, ask which batch first]
    G --> H[Add selected IDs to WarningsAsErrors]
    H --> I[Fix that batch, verify build]
    I --> J{More batches?}
    J -->|Yes| G
    J -->|No| F
    C --> K[Set AnalysisLevel latest-recommended]
    F --> K
    K --> L[Promote security CA3xxx/CA5xxx to error in .editorconfig]
    L --> M[Validate: build + CI green]
  1. 优先使用SDK分析器,再考虑第三方包。
  2. 检测项目成熟度:新项目还是已有/遗留项目。
  3. Directory.Build.props
    中启用
    EnableNETAnalyzers
    AnalysisLevel
    AnalysisMode
  4. 应用合适的警告升级策略(见下文)。
  5. 每条规则的严重性设置在仓库根目录的
    .editorconfig
    中。
  6. CI中使用
    dotnet build
    作为分析器检查关卡。

Warning Promotion Strategy

警告升级策略

New Projects

新项目

Set these in
Directory.Build.props
immediately:
  • TreatWarningsAsErrors
    = true
  • AnalysisLevel
    = latest-recommended
  • Security category = error in
    .editorconfig
Fix all warnings before merging.
立即在
Directory.Build.props
中设置以下内容:
  • TreatWarningsAsErrors
    = true
  • AnalysisLevel
    = latest-recommended
  • .editorconfig
    中将安全类别设为error
合并代码前修复所有警告。

Legacy Projects — Gradual Promotion

遗留项目——逐步升级

Blanket
TreatWarningsAsErrors
on a legacy codebase produces hundreds/thousands of errors. An agent cannot fix them all at once — context floods, fix quality drops. Promote in batches.
对遗留代码库全面启用
TreatWarningsAsErrors
会产生成百上千个错误。Agent无法一次性全部修复——上下文过载,修复质量下降。应分批升级。

Phase 1: Trivial Hygiene (start here)

阶段1:基础代码清理(从此开始)

Mechanical fixes, lowest effort:
  • CS8019 — unnecessary using directive (remove it)
  • CS0219 — variable assigned but never used (remove it)
  • CS0168 — variable declared but never used (remove it)
  • CS1591 — missing XML comment for public member (add comment or disable for internal code)
  • CS0612 — obsolete member used, no message (replace with non-obsolete API)
  • CS0618 — obsolete member used, with message (follow migration guidance)
Add to
WarningsAsErrors
:
CS8019;CS0219;CS0168
. Fix all, then Phase 2.
机械性修复,最低工作量:
  • CS8019 — 不必要的using指令(移除)
  • CS0219 — 变量已赋值但从未使用(移除)
  • CS0168 — 变量已声明但从未使用(移除)
  • CS1591 — 公共成员缺少XML注释(添加注释或对内部代码禁用该规则)
  • CS0612 — 使用了已过时成员,无提示信息(替换为非过时API)
  • CS0618 — 使用了已过时成员,有提示信息(遵循迁移指南)
将以下ID添加到
WarningsAsErrors
CS8019;CS0219;CS0168
。修复所有相关问题后进入阶段2。

Phase 2: Code Quality (ask user which categories)

阶段2:代码质量(询问用户选择哪些类别)

  • CA2000 — dispose objects before losing scope (Reliability)
  • CA1062 — validate public method arguments (Design)
  • CA1822 — mark members as static (Performance)
  • CA1860 — avoid Enumerable.Any() for length check (Performance)
  • CA1861 — avoid constant arrays as arguments (Performance)
  • CA2007 — consider calling ConfigureAwait (Reliability)
  • CS8600–CS8610 — nullable reference type warnings (Nullability)
Ask: "Which categories next — Nullability, Performance, or Reliability?" Add selected IDs to
WarningsAsErrors
, fix, repeat.
  • CA2000 — 失去对象作用域前释放对象(可靠性)
  • CA1062 — 验证公共方法参数(设计)
  • CA1822 — 将成员标记为static(性能)
  • CA1860 — 避免使用Enumerable.Any()检查长度(性能)
  • CA1861 — 避免将常量数组作为参数(性能)
  • CA2007 — 考虑调用ConfigureAwait(可靠性)
  • CS8600–CS8610 — 可空引用类型警告(空值安全性)
询问:“接下来处理哪个类别——空值安全性、性能还是可靠性?”将选中的ID添加到
WarningsAsErrors
,修复后重复该步骤。

Phase 3: Security (always promote early)

阶段3:安全(尽早升级)

Set in
.editorconfig
regardless of project maturity:
editorconfig
[*.cs]
dotnet_analyzer_diagnostic.category-Security.severity = error
Covers CA3001 (SQL injection), CA3002 (XSS), CA3003 (path injection), CA3075 (insecure DTD), CA5350/CA5351 (weak crypto), CA5394 (insecure randomness).
无论项目成熟度如何,在
.editorconfig
中设置:
editorconfig
[*.cs]
dotnet_analyzer_diagnostic.category-Security.severity = error
涵盖CA3001(SQL注入)、CA3002(XSS)、CA3003(路径注入)、CA3075(不安全DTD)、CA5350/CA5351(弱加密)、CA5394(不安全随机数)。

Phase 4: Full Coverage

阶段4:全面覆盖

Once all batches pass, transition to:
xml
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>CA1707</WarningsNotAsErrors> <!-- explicit exceptions only -->
所有批次通过后,过渡到:
xml
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>CA1707</WarningsNotAsErrors> <!-- 仅显式例外情况 -->

Interaction Protocol (legacy codebases)

遗留代码库交互协议

  1. Run
    dotnet build
    , count warnings by ID.
  2. Report summary: "Found 47 CS8019, 23 CA1822, 12 CA2000, 8 CS8600."
  3. Ask which batch to tackle. Recommend starting with Phase 1.
  4. Fix selected batch, verify build.
  5. Add those IDs to
    WarningsAsErrors
    .
  6. Report back, ask about next batch.
Never skip the ask step. The user decides the pace.
  1. 运行
    dotnet build
    ,按ID统计警告数量。
  2. 报告摘要:“发现47个CS8019、23个CA1822、12个CA2000、8个CS8600。”
  3. 询问优先处理哪个批次。建议从阶段1开始。
  4. 修复选中的批次,验证构建。
  5. 将这些ID添加到
    WarningsAsErrors
  6. 反馈结果,询问下一个批次。
绝不能跳过询问步骤。用户决定进度。

Bootstrap When Missing

缺失时的初始化配置

  1. Detect current state:
    • dotnet --info
    • rg -n "EnableNETAnalyzers|AnalysisLevel|AnalysisMode|TreatWarningsAsErrors|WarningsAsErrors" -g '*.csproj' -g 'Directory.Build.*' .
    • dotnet build SOLUTION_OR_PROJECT 2>&1
      — count warnings by ID
  2. Classify: new (few/zero warnings) vs legacy (many warnings).
  3. Enable
    EnableNETAnalyzers
    ,
    AnalysisLevel
    ,
    AnalysisMode
    in MSBuild config.
  4. Apply promotion strategy matching project maturity.
  5. Per-rule severity in repo-root
    .editorconfig
    .
  6. Run
    dotnet build
    , return
    status: configured
    or
    status: improved
    .
  7. If repo defers analyzer policy to another build layer, return
    status: not_applicable
    .
  1. 检测当前状态:
    • dotnet --info
    • rg -n "EnableNETAnalyzers|AnalysisLevel|AnalysisMode|TreatWarningsAsErrors|WarningsAsErrors" -g '*.csproj' -g 'Directory.Build.*' .
    • dotnet build SOLUTION_OR_PROJECT 2>&1
      — 按ID统计警告数量
  2. 分类:新项目(少量/无警告) vs 遗留项目(大量警告)。
  3. 在MSBuild配置中启用
    EnableNETAnalyzers
    AnalysisLevel
    AnalysisMode
  4. 应用与项目成熟度匹配的升级策略。
  5. 在仓库根目录的
    .editorconfig
    中设置每条规则的严重性。
  6. 运行
    dotnet build
    ,返回
    status: configured
    status: improved
  7. 如果仓库将分析器策略委托给其他构建层,返回
    status: not_applicable

Deliver

交付成果

  • explicit, reviewable first-party analyzer policy
  • build-time analyzer execution for CI
  • warning promotion plan matching project maturity
  • 明确的、可审核的官方分析器策略
  • CI中执行构建时分析器检查
  • 与项目成熟度匹配的警告升级计划

Validate

验证

  • analyzer behavior driven by repo config, not IDE defaults
  • CI reproduces same warnings/errors locally
  • no
    TreatWarningsAsErrors
    ,
    WarningsAsErrors
    , or severity settings removed/weakened without user approval
  • promoted warnings produce build errors, not just IDE hints
  • 分析器行为由仓库配置驱动,而非IDE默认设置
  • CI中的警告/错误与本地一致
  • 未经用户批准,不得移除/弱化
    TreatWarningsAsErrors
    WarningsAsErrors
    或严重性设置
  • 升级后的警告会导致构建错误,而非仅IDE提示

Ralph Loop

Ralph 循环

  1. Plan: analyze state, define target, constraints, risks, execution plan, validation steps.
  2. Execute one step, produce concrete delta.
  3. Review result, capture findings.
  4. Apply fixes in small batches, rerun checks.
  5. Update plan after each iteration.
  6. Repeat until acceptable or only explicit exceptions remain.
  7. Missing dependency: bootstrap or return
    status: not_applicable
    .
  1. 规划:分析状态,定义目标、约束、风险、执行计划和验证步骤。
  2. 执行一步操作,产生具体变更。
  3. 审查结果,记录发现。
  4. 小批量应用修复,重新运行检查。
  5. 每次迭代后更新计划。
  6. 重复直到达到可接受状态或仅剩下显式例外情况。
  7. 缺失依赖项:初始化配置或返回
    status: not_applicable

Required Result Format

要求的结果格式

  • status
    :
    complete
    |
    clean
    |
    improved
    |
    configured
    |
    not_applicable
    |
    blocked
  • plan
    : concise plan and current step
  • actions_taken
    : concrete changes
  • validation_skills
    : final skills run or skipped with reasons
  • verification
    : commands, checks, or review evidence
  • remaining
    : unresolved items or
    none
  • status
    :
    complete
    |
    clean
    |
    improved
    |
    configured
    |
    not_applicable
    |
    blocked
  • plan
    : 简洁的计划和当前步骤
  • actions_taken
    : 具体变更内容
  • validation_skills
    : 最终运行的技能或跳过的原因
  • verification
    : 命令、检查或审查证据
  • remaining
    : 未解决项或
    none

Load References

参考资料

  • references/rules.md
  • references/config.md
  • references/code-analysis.md
  • references/rules.md
  • references/config.md
  • references/code-analysis.md

Example Requests

请求示例

  • "Turn on built-in .NET analyzers."
  • "Make analyzer warnings fail the build."
  • "Set the right AnalysisLevel for this repo."
  • "Start treating unused usings and unused variables as errors."
  • "Help me gradually promote Roslyn warnings in my legacy project."
  • "Which warnings should I promote to errors next?"
  • "启用内置的.NET分析器。"
  • "让分析器警告导致构建失败。"
  • "为这个仓库设置合适的AnalysisLevel。"
  • "开始将未使用的using和未使用的变量视为错误。"
  • "帮助我逐步升级遗留项目中的Roslyn警告。"
  • "接下来我应该将哪些警告升级为错误?"