Claude Skill

dotnet-code-analysis

Use the free built-in .NET SDK analyzers and analysis levels with gradual Roslyn warning promotion. Use when a .NET repo needs first-party code analysis, `EnableNETAnalyzers`, `AnalysisLevel`, or warning-as-error policy wired into build and CI.

LLM Mart · 0 points · 0 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download postpartum-genushyacinthus29-dotnet-skills-skills_dotnet-code-analysis-bfa4ebd.zip · 8 KB
Part of postpartum-genushyacinthus29/dotnet-skills — 80 skills

Install

skills CLI npx skills add https://github.com/Postpartum-genushyacinthus29/dotnet-skills/tree/main/skills/dotnet-code-analysis
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install postpartum-genushyacinthus29-dotnet-skills@llmmart
Git git clone https://github.com/Postpartum-genushyacinthus29/dotnet-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole postpartum-genushyacinthus29/dotnet-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

.NET Code Analysis

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

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

Hard Rules for AI Agents

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.

Workflow

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.

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.

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.

Phase 1: Trivial Hygiene (start here)

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.

Phase 2: Code Quality (ask user which categories)

  • 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.

Phase 3: Security (always promote early)

Set in .editorconfig regardless of project maturity:

[*.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).

Phase 4: Full Coverage

Once all batches pass, transition to:

<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsNotAsErrors>CA1707</WarningsNotAsErrors> <!-- explicit exceptions only -->

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.

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.

Deliver

  • explicit, reviewable first-party analyzer policy
  • build-time analyzer execution for CI
  • warning promotion plan matching project maturity

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

Ralph Loop

  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.

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

Load References

  • 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?"
Files (dotnet-skills)
  • references
    • code-analysis.md 1.3 KB
      # .NET SDK Code Analysis
      
      ## Open/Free Status
      
      - first-party .NET SDK analyzers
      - free to use
      - included with the modern .NET SDK
      
      ## Install
      
      For projects targeting .NET 5 or later, built-in analyzers are included with the SDK and code analysis is enabled by default.
      
      For older or explicitly controlled projects, set analyzer properties in the project or `Directory.Build.props`:
      
      ```xml
      <PropertyGroup>
        <EnableNETAnalyzers>true</EnableNETAnalyzers>
        <AnalysisLevel>latest-recommended</AnalysisLevel>
      </PropertyGroup>
      ```
      
      ## Verify First
      
      Before adding anything, check whether the repo already set analyzer policy:
      
      ```bash
      rg -n "EnableNETAnalyzers|AnalysisLevel|AnalysisMode|TreatWarningsAsErrors" -g 'Directory.Build.*' -g '*.csproj' .
      ```
      
      ## Common Commands
      
      ```bash
      dotnet build MySolution.sln
      dotnet build MySolution.sln -warnaserror
      ```
      
      ## CI Fit
      
      - use `dotnet build` as the analyzer gate
      - keep `AnalysisLevel` explicit in MSBuild
      - keep rule severity in the repo-root `.editorconfig`
      
      ## When Not To Use
      
      - when you only need a formatter
      - when the repo specifically needs a framework or third-party analyzer set beyond the built-in SDK rules
      
      ## Sources
      
      - [Overview of .NET source code analysis](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/overview)
      
    • config.md 4.7 KB
      # MSBuild Properties and .editorconfig for Code Analysis
      
      ## MSBuild Properties
      
      Set in `Directory.Build.props` or project files.
      
      ### EnableNETAnalyzers
      
      ```xml
      <EnableNETAnalyzers>true</EnableNETAnalyzers>
      ```
      Default true in .NET 5+. Set explicitly to prevent accidental disabling.
      
      ### AnalysisLevel
      
      Values: `5.0`–`10.0` (specific SDK), `latest`, `latest-recommended`, `latest-minimum`, `latest-all`, `preview`.
      
      Combined syntax includes mode: `<AnalysisLevel>latest-recommended</AnalysisLevel>` equals `latest` + `Recommended` mode.
      
      ### AnalysisMode
      
      Values: `None` (all off), `Default`, `Minimum` (critical only), `Recommended` (start here), `All`.
      
      ### Category-Specific AnalysisMode
      
      ```xml
      <AnalysisLevel>latest-recommended</AnalysisLevel>
      <AnalysisModeSecurity>All</AnalysisModeSecurity>
      <AnalysisModeReliability>All</AnalysisModeReliability>
      ```
      Categories: Design, Documentation, Globalization, Interoperability, Maintainability, Naming, Performance, Reliability, Security, Usage.
      
      ### TreatWarningsAsErrors
      
      ```xml
      <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
      ```
      All warnings fail the build. Use for new projects or clean codebases. Agent rule: never disable to make a build pass.
      
      ### WarningsAsErrors (selective — preferred for legacy)
      
      ```xml
      <WarningsAsErrors>CS8019;CS0219;CS0168;CA2000;CA3001</WarningsAsErrors>
      ```
      Promote specific IDs to errors. Preferred for gradual adoption: add IDs as you fix each batch. Agent rule: never remove IDs from this list to make a build pass.
      
      ### WarningsNotAsErrors
      
      ```xml
      <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
      <WarningsNotAsErrors>CA1707</WarningsNotAsErrors>
      ```
      Explicit exceptions when using TreatWarningsAsErrors.
      
      ### NoWarn
      
      ```xml
      <NoWarn>$(NoWarn);CA1062</NoWarn>
      ```
      Disables warnings entirely. Use sparingly; prefer .editorconfig for visibility.
      
      ### EnforceCodeStyleInBuild
      
      ```xml
      <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
      ```
      Enables IDE code style rules during build (off by default for performance).
      
      ## .editorconfig
      
      Place at repo root. Rules cascade to subdirectories.
      
      ### Severity per rule
      
      ```editorconfig
      [*.cs]
      dotnet_diagnostic.CA2000.severity = error
      dotnet_diagnostic.CA1707.severity = none
      ```
      
      ### Severity per category (.NET 6+)
      
      ```editorconfig
      [*.cs]
      dotnet_analyzer_diagnostic.category-Security.severity = error
      dotnet_analyzer_diagnostic.category-Performance.severity = warning
      ```
      
      ### Scope patterns
      
      ```editorconfig
      [**/Tests/**/*.cs]
      dotnet_diagnostic.CA1707.severity = none
      dotnet_diagnostic.CA1062.severity = none
      
      [*.generated.cs]
      generated_code = true
      ```
      
      ### Code Style Settings
      
      ```editorconfig
      [*.cs]
      csharp_style_namespace_declarations = file_scoped:suggestion
      csharp_style_expression_bodied_methods = when_on_single_line:suggestion
      csharp_style_expression_bodied_properties = true:suggestion
      csharp_style_pattern_matching_over_as_with_null_check = true:warning
      csharp_style_pattern_matching_over_is_with_cast_check = true:warning
      csharp_style_prefer_null_check_over_type_check = true:suggestion
      csharp_style_var_for_built_in_types = true:suggestion
      csharp_style_var_when_type_is_apparent = true:suggestion
      csharp_style_var_elsewhere = true:suggestion
      ```
      
      ### Formatting Settings
      
      ```editorconfig
      [*.cs]
      indent_style = space
      indent_size = 4
      tab_width = 4
      csharp_new_line_before_open_brace = all
      csharp_new_line_before_else = true
      csharp_new_line_before_catch = true
      csharp_new_line_before_finally = true
      ```
      
      ## Recommended Starting Configuration
      
      ### Directory.Build.props
      
      ```xml
      <Project>
        <PropertyGroup>
          <EnableNETAnalyzers>true</EnableNETAnalyzers>
          <AnalysisLevel>latest-recommended</AnalysisLevel>
          <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
        </PropertyGroup>
      
        <PropertyGroup Condition="'$(Configuration)' == 'Release'">
          <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
        </PropertyGroup>
      </Project>
      ```
      
      ### .editorconfig (root)
      
      ```editorconfig
      root = true
      
      [*]
      indent_style = space
      indent_size = 4
      end_of_line = lf
      charset = utf-8
      trim_trailing_whitespace = true
      insert_final_newline = true
      
      [*.cs]
      dotnet_analyzer_diagnostic.category-Security.severity = error
      dotnet_analyzer_diagnostic.category-Reliability.severity = warning
      
      [**/Tests/**/*.cs]
      dotnet_diagnostic.CA1707.severity = none
      dotnet_diagnostic.CA1062.severity = none
      ```
      
      ## Verification
      
      ```bash
      dotnet build
      dotnet build /p:ReportAnalyzer=true
      ```
      
      ## References
      
      - [AnalysisLevel](https://learn.microsoft.com/en-us/dotnet/core/project-sdk/msbuild-props#analysislevel)
      - [Configuration options](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-options)
      - [EditorConfig](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-files)
      - [Suppress warnings](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/suppress-warnings)
      
    • rules.md 4.9 KB
      # SDK Analyzer Rule Categories
      
      This reference covers the built-in .NET SDK analyzer rule categories, their prefixes, and practical guidance for each.
      
      ## Rule Prefix Summary
      
      | Prefix | Category | Scope |
      |--------|----------|-------|
      | CA | Code Analysis | Design, reliability, security, performance, usage |
      | IDE | IDE Analyzers | Code style, simplification, formatting |
      | CS | C# Compiler Warnings | Language-level warnings promoted by analyzers |
      
      ## CA Rules: Code Analysis
      
      CA rules are the primary SDK analyzer rules. They cover correctness, performance, and security.
      
      ### CA1xxx: Design Rules
      
      - Ensure proper API design and naming.
      - Examples: CA1000 (do not declare static members on generic types), CA1010 (collections should implement generic interface).
      - High value for public APIs.
      
      ### CA2xxx: Usage and Reliability
      
      - Detect misuse of framework types and patterns.
      - Examples: CA2000 (dispose objects before losing scope), CA2007 (consider calling ConfigureAwait).
      - Enable these early; they catch real bugs.
      
      ### CA3xxx: Security
      
      - Identify security vulnerabilities.
      - Examples: CA3001 (SQL injection), CA3075 (insecure DTD processing).
      - Critical for any user-facing or network-connected code.
      
      ### CA5xxx: Security (Extended)
      
      - Extended security rules for cryptography, serialization, and input handling.
      - Examples: CA5350 (do not use weak cryptographic algorithms), CA5394 (do not use insecure randomness).
      - Enable for production systems handling sensitive data.
      
      ### CA18xx, CA19xx: Performance
      
      - Detect performance anti-patterns.
      - Examples: CA1802 (use literals where appropriate), CA1860 (avoid Length/Count zero checks).
      - High value for hot paths and resource-constrained environments.
      
      ## IDE Rules: Code Style
      
      IDE rules enforce consistency and simplify code.
      
      ### IDE0001-IDE0099: Code Simplification
      
      - Remove unnecessary code, simplify expressions.
      - Examples: IDE0001 (simplify name), IDE0017 (use object initializers).
      - Useful for codebase consistency.
      
      ### IDE0100-IDE0199: Language Feature Preferences
      
      - Prefer modern C# features.
      - Examples: IDE0160 (file-scoped namespace preference), IDE0161 (convert to block-scoped namespace).
      - Align with team style guide.
      
      ### IDE0200-IDE0299: Expression Preferences
      
      - Expression-bodied members, pattern matching, null checks.
      - Examples: IDE0200 (unnecessary lambda expression), IDE0270 (use coalesce expression).
      - Enforce via .editorconfig for consistency.
      
      ### IDE1xxx: Formatting
      
      - Whitespace, indentation, newlines.
      - Examples: IDE1005 (delegate invocation should be conditional).
      - Typically set to suggestion or silent; enforce in CI only when the team agrees.
      
      ## Severity Levels
      
      | Severity | Build Behavior | Use Case |
      |----------|----------------|----------|
      | error | Fails build | Critical correctness or security |
      | warning | Logged, may fail with TreatWarningsAsErrors | Important but deferrable |
      | suggestion | IDE hint only | Style preferences |
      | silent | Rule runs but no diagnostic | Rule disabled for output but still analyzed |
      | none | Rule disabled | Not applicable to this codebase |
      
      ## Suppression Strategies
      
      ### Inline Suppression
      
      ```csharp
      #pragma warning disable CA2000
      var resource = new Resource();
      #pragma warning restore CA2000
      ```
      
      Use sparingly. Always include a justification comment.
      
      ### GlobalSuppressions.cs
      
      ```csharp
      [assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope",
          Justification = "Ownership transferred to caller", Scope = "member",
          Target = "~M:MyClass.CreateResource")]
      ```
      
      Prefer for project-wide suppression of known false positives.
      
      ### .editorconfig
      
      ```editorconfig
      # Disable specific rule for all files
      dotnet_diagnostic.CA1062.severity = none
      
      # Disable for test files only
      [**/Tests/**/*.cs]
      dotnet_diagnostic.CA1707.severity = none
      ```
      
      Prefer for category-level or scope-based configuration.
      
      ## Rule Selection Guidance
      
      1. Start with `AnalysisMode = Recommended` to get the common high-value rules.
      2. Promote security rules (CA3xxx, CA5xxx) to error for production code.
      3. Treat CA2xxx reliability rules as warnings initially; promote to error as the codebase matures.
      4. Enforce IDE rules only when the team has agreed on style conventions.
      5. Do not enable all rules at maximum severity immediately; ramp up over time.
      
      ## Discovering Available Rules
      
      ```bash
      # List all analyzer diagnostics from a build
      dotnet build /p:ReportAnalyzer=true /v:d | grep "CA\|IDE"
      
      # Get rule documentation
      # https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/
      # https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/
      ```
      
      ## References
      
      - [Code quality rules](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/)
      - [Code style rules](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/)
      - [Configure analyzers](https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-files)
      
  • SKILL.md 7.6 KB
    ---
    name: dotnet-code-analysis
    version: "1.0.1"
    category: "Code Quality"
    description: "Use the free built-in .NET SDK analyzers and analysis levels with gradual Roslyn warning promotion. Use when a .NET repo needs first-party code analysis, `EnableNETAnalyzers`, `AnalysisLevel`, or warning-as-error policy wired into build and CI."
    compatibility: "Requires a .NET SDK-based repository; respects the repo's `AGENTS.md` commands first."
    ---
    
    # .NET Code Analysis
    
    ## 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
    
    ## 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
    
    ## Hard Rules for AI Agents
    
    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.
    
    ## 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.
    
    ## 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.
    
    ### 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.
    
    #### Phase 1: Trivial Hygiene (start here)
    
    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.
    
    #### Phase 2: Code Quality (ask user which categories)
    
    - 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.
    
    #### Phase 3: Security (always promote early)
    
    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).
    
    #### Phase 4: Full Coverage
    
    Once all batches pass, transition to:
    ```xml
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <WarningsNotAsErrors>CA1707</WarningsNotAsErrors> <!-- explicit exceptions only -->
    ```
    
    ### 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.
    
    ## 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`.
    
    ## Deliver
    
    - explicit, reviewable first-party analyzer policy
    - build-time analyzer execution for CI
    - warning promotion plan matching project maturity
    
    ## 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
    
    ## Ralph Loop
    
    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`.
    
    ### 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`
    
    ## Load References
    
    - `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?"
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related