Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install msbuild@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin msbuild v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install msbuild

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/msbuild/

Extract the ZIP to .github/skills/ in your repo. The folder name must match msbuild for Copilot to auto-discover it.

Skill Files (13)

SKILL.md 16.1 KB
---
name: msbuild
description: "Use before MSBuild custom-target or incremental-generation repairs, XML/import/hook review, .binlog capture/replay, or assessing supported/unsupported build-speedup claims and controlled timings, even without a checkout. For MSBuild authoring itself, activate before reviewing/editing .proj/.props/.targets/.csproj/.fsproj/.vbproj or Directory.Build files, including no-change import reviews. Framework/API/.NET/ASP.NET upgrade plans and working non-SDK-to-SDK/packages.config conversions are migrations, even if they mention .csproj/NuGet: DO NOT activate. A failing assertion after a successful build is code/test debugging: DO NOT activate. Check Import/Exists, required and NuGet build/buildTransitive/nuspec imports, conditions, Inputs/Outputs, stale outputs and incorrect skips. Build checks use copies; source inputs stay read-only. Diagnose failed dotnet build/restore/pack/publish or slow evaluation/compilation/copying. Exclude SDK installation alone, C# refactoring, runtime CPU profiling and non-MSBuild builds."
license: MIT
---

# MSBuild troubleshooting

For advice or static review, answer from the supplied XML, package facts, or measurements when
they settle the question: no reference reads, checkout discovery, commands, or invented verification.
For requested work, start at the supplied project or artifact; discover only what the next decision
needs. Read a reference only for a specific unresolved question. References are not invocable skills.

## Start with the task and evidence

Before editing, follow repository instructions and inspect the project/imports. Preserve the original
command, working directory, SDK, configuration, target framework, runtime identifier, global properties,
and target. Ask only for consequential information that cannot be discovered.

An existing `.binlog` can be the only available artifact. Analyze it before requesting a new
build; paths inside it do not prove a checkout exists locally.

For a mixed request, fix correctness before measuring successful builds, and keep authoring review
separate from a performance experiment. A failing test assertion after a successful build is not
an MSBuild failure.

**Capture only:** choose an unused artifact path under the supplied workspace, unless the user
specified another artifact directory. Do not put the only deliverable in a shared/global
temporary directory where workspace artifact collection will miss it, or stage/commit the log.
Append the binary logger to the exact supplied command, run it once, and save its original
exit code before checking the new log is nonempty.
Report the artifact path and original exit code, then stop: no replay, diagnosis, or repair.
Read [capture details](references/binlog-generation.md) only for an unresolved wrapper,
logger-option, toolset, or privacy question.

## 1. Troubleshoot build issues

**Goal:** identify the independent root causes and make the smallest repair, not a broad cleanup.

| Situation | Reference if needed | Action |
| --- | --- | --- |
| A build failed and a binary log exists | [binlog-failure-analysis](references/binlog-failure-analysis.md) | Replay the log with MSBuild; connect errors to the responsible project instance, target, and task. Separate root causes from cascading failures. |
| The failure needs evidence and no matching log exists | [binlog-generation](references/binlog-generation.md), then [failure analysis](references/binlog-failure-analysis.md) | Capture the original invocation once and verify the artifact. Analyze it only when requested. |
| A project/build file has incorrect conditions, items, properties, or output paths | [msbuild-antipatterns](references/msbuild-antipatterns.md) | Select the relevant catalog entries and check their exceptions before changing anything. |
| Imports or build hooks are missing, overwritten, or run in the wrong order | [extension-points](references/extension-points.md) | Inspect the import contract, discovery order, and packed NuGet layout rather than hiding a required failure. |
| Outputs are stale or required work is skipped | [incremental-build](references/incremental-build.md) | Track input-set membership as well as file timestamps; apply the repair contract below. |

For build-wiring-only work, generator and source inputs are **read-only throughout**, not restored
after tests; edit the original only as the requested repair requires.
Allocate disposable scratch as a uniquely named directory **outside the project tree**, normally
the OS temporary directory from `mktemp -d`; a copy inside the project can be matched by SDK
default globs and break the later confirming build. Print the path once and write every copy, log,
and hash under it: no fixed leaf names, pointer files, pre-deleting, or globbing to recover it.
After the checks, remove exactly that path (never a pattern) and keep it in the report.
Copy the project/input tree and required imports; run every scenario that adds, deletes, empties,
or retimes inputs, or deletes `obj`/outputs, with **the copy as working directory**. A backup is not
a verification copy, nor is an original project already under a temporary path. Compare original
hashes before/after; equal final hashes do not excuse intermediate mutation. A confirming build of
the repaired original must not delete outputs. If the copy cannot reproduce the environment, report
blocked checks.

For input-set changes, prefer a persisted membership list written with `WriteLinesToFile` and
`WriteOnlyWhenDifferent`, plus actual files in `Inputs`. A path list is not a content hash.
Verify first/unchanged builds, deletion, older addition, empty inputs, and missing-output recovery
on the copy. End the repair report, however brief, with three labeled explanations, not only a checklist:

- **Cause:** state both blind spots: a deleted input vanishes from the timestamp comparison; an
  added input older than the output never looks newer; either skips required regeneration.
- **Mechanism:** identify the membership artifact and how its changes invalidate the output.
  Unchanged membership preserves skips; actual file timestamps still catch ordinary edits.
- **Checks:** list passed, failed, and not-run separately with the command or path used. "None
  failed" requires every command to exit 0; an errored script, even if fixed and rerun, is listed
  failed with its cause. If the main scenario passed but a later assertion failed, report both;
  never summarize as verified.

After a repair, rerun the original failing scenario and check affected dependents. If only a log
is available, provide an evidence-backed proposed fix and say it was not applied or rebuilt.
Do not turn a targeted failure investigation into solution-wide authoring cleanup.

## 2. Diagnose and improve build performance

**Goal:** measure the original workload, not an easier replacement.

For advice, give the verdict, decisive facts, and a concrete next step with equivalent successful
builds and required outputs. Do not re-prove a supplied timeline or read references to restate it.
Do not infer warm/no-op state or assign any part of a confounded timing gap to restore, cache, or
setting effects without isolating that cause.

| Supplied evidence | Decision | Smallest useful follow-up |
| --- | --- | --- |
| Parallel target totals include overlapping dependency waits | Keep required references and parallelism. Cumulative waits can exceed both wall time and the duration of one dependency task; they do not prove CPU utilization or healthy scheduling. | Follow the supplied timeline to the dependency task holding up consumers. For `Csc`, inspect compiler inputs and invocation, analyzer/source-generator timing, and whether compilation was expected for this workload. Measure CPU/node utilization or I/O contention if unknown; do not infer them from wait totals. Validate any change with equivalent successful builds and required outputs. |
| Commands, restore policy, or starting input/output states differ | Reject attribution to the setting, not the possibility of a real gain. | Give one matched old-setting/new-setting experiment below, not a menu of different workloads or an invented setting name. |
| Repeated successful runs have matched conditions and outputs | Accept the observed improvement for that workload; use the same summary statistic for both arms: `100 * (old - new) / old`. | Report sample count and observed elapsed-time ranges, not an invented percentage uncertainty interval. Then state residual limits: small sample, one workload/machine/SDK, what restored starting state does and does not control, and no independent rerun. Do not require a checkout to acknowledge the supplied result. |

When a minimal attribution experiment is needed, return **one two-arm table**, not alternatives:

1. Bind the treatment to the user's identified setting and old/new values. If unidentified, retain
   literal `<setting>`, `<old>`, `<new>` placeholders. Differing commands are confounds, not setting names.
   Never substitute restore policy, Build/Rebuild, or cache state for an unidentified setting.
2. Expand the **full original baseline command in both arms**. Only an explicitly identified
   command-line treatment may change its own argument; otherwise vary its configured value.

| Arm | Treatment, supplied or placeholder | Controlled invocation and workload |
| --- | --- | --- |
| A | `<setting> = <old>` | Full original baseline command; input and starting outputs exactly as supplied |
| B | `<setting> = <new>` | Same full command, input, and starting outputs; only the named treatment differs |

3. Match non-treatment SDK, machine, configuration, instrumentation, target, restore policy,
   and input/output state exactly as supplied. Add no source edit the original workload lacked
   (keep one it had in both arms). **Matching both arms is not enough if both replace the original
   workload.** When they are controls, retain supplied Rebuild and timed restore; do not prime,
   warm, or move work outside the timer unless the original workload already did.
4. Alternate matched pairs; compare wall-time medians and observed ranges; check required outputs
   and diagnostics. Scope the result to that workload. The table is the only experiment; the last
   sentence states a validity check or residual limit, not an offer or variant.

For optimization work, establish the relevant successful baseline before changing one supported cause:

| Unresolved measurement | Reference if needed |
| --- | --- |
| Cold-output, changed-input, no-change, restore/cache state, or Build versus Rebuild | [build-perf-baseline](references/build-perf-baseline.md) |
| Unknown task cost, compiler/analyzer/reference/restore work, or overlapping waits | [build-perf-diagnostics](references/build-perf-diagnostics.md) |
| Pre-target globs, imports, property evaluation, or excess project instances | [eval-performance](references/eval-performance.md) |
| Copies/output I/O, unchanged copies, or a modified destination | [copy-to-output-directory](references/copy-to-output-directory.md) |
| Unexpected regeneration/skips, added/removed inputs, or missing outputs | [incremental-build](references/incremental-build.md) |

Stop when the suspected bottleneck is not supported by evidence, results fall within noise, or
correctness regresses. Report missing measurements rather than manufacturing a complete baseline.

## 3. Review build authoring

**Goal:** preserve build contracts, not implicitly migrate frameworks, packages, languages, or project systems.

**Check evaluation phases, not just import order.** Outside targets, properties/imports are
evaluated before items. A framework set in the project body can be unavailable to an early
property condition in `Directory.Build.props` but available to an item condition in that same
file. Move only the premature property assignment after its dependency; do not relocate an
intentionally project-owned framework or a working item declaration. Preserve F# compile order
and inspect SDK defaults before adding switches to suppress supposedly duplicated items.

| Requested change | Reference if needed | Preserve |
| --- | --- | --- |
| Review/clean up project files, shared properties, item declarations, or custom targets | [msbuild-antipatterns](references/msbuild-antipatterns.md) | Intentional overrides, F# source order, required imports, package assets, and actual input/output contracts. |
| Review/improve hooks, imports, shared-file discovery, or NuGet build extensions | [extension-points](references/extension-points.md) | Prior hooks, evaluation order, direct/transitive consumer behavior, and the packed layout. |
| Restructure generation or copying as part of cleanup | [incremental-build](references/incremental-build.md) and [copy-to-output-directory](references/copy-to-output-directory.md), as applicable | First-build and no-change behavior, invalidation, generated-item registration, and output completeness. |

Record the existing contract; a matching catalog pattern alone is not a defect. Leave correct code
alone. Validate authorized changes against original configurations, consumers, and affected build behavior.

Keep optional and required imports distinct, including inside aggregation files:

```xml
<Import Project="optional.targets" Condition="Exists('optional.targets')" />
<Import Project="required.targets" />
```

The required import must load or fail, not silently skip. Explain why a condition on an entire
mixed path list can suppress a valid required import; semicolon-separated imports themselves
are supported. Check optional present/absent crossed with required present/absent, preserving
order when both exist. When checks run, report the observed order and failure cases, not only
"verification passed." Do not replace configurable paths with hard-coded values unnecessarily.

For a packaged forwarder, keep these bindings separate:

| Binding | Meaning |
| --- | --- |
| `NuspecFile` | Selects the XML manifest, possibly outside the project; not a payload mapping. |
| `NuspecBasePath` | Base directory for the manifest's `file src` lookups on disk; it neither locates nor selects the manifest. |
| Mapping `src` / `target` | Reads the source file and emits its mapped archive path; does not implicitly ship the source path too. |
| Consumer import | Resolves from the importing file inside the **package**, not source, feed, or the consumer's framework. |

Do not substitute the manifest path for a mapping's `src`. For a no-change verdict, explain how
`NuspecFile` selection, `NuspecBasePath` src lookup, mapping, packed target, and relative import connect, and why guarding
a required import would hide a broken package. If supplied package facts settle this, stop:
no `Exists` guard, reorganization, or confirmatory rebuild/repack. Inspect artifacts only when
verification is requested or contents remain unknown.

## Shared evidence and safety

- For analysis, use [MSBuild replay](references/binlog-failure-analysis.md#replay-a-binary-log),
  never binary-file text parsing. Replay success and replay duration are not the recorded
  build's result or duration.
- Resolve these files relative to this skill. Do not load the original plugin's skills or search
  other installations/checkouts. After a failed reference read, allow one listing of `references`
  to distinguish a missing bundled file from a present-but-unreadable tool integration failure.
  Report the error and reduced coverage; do not retry through shell commands or other readers,
  and do not pretend unread guidance was followed. Never work around a policy denial.
- Do not clean outputs/caches, stop shared build servers, disable diagnostics, change SDKs, or
  serialize builds as generic fixes. Scope any necessary destructive experiment to approved,
  owned outputs. Keep binary and replayed logs local unless sharing is authorized.
- Distinguish recorded facts from hypotheses. Missing source, log detail, tools, or platform
  support must be reported explicitly, not replaced with assumed values or invented verification.

## Completion

Advice: verdict, decisive evidence, necessary next measurement; no manufactured verification.
Repository work: cause/decision, minimal change (or no change), and exact successful, failed,
and not-run checks. Performance claims also need comparable measurements and uncertainty.
Scale length to the task, but never drop a required report field.
references/antipatterns/
additional-antipatterns.md 12.8 KB
# Additional MSBuild anti-patterns

This continues the original catalog with AP-16 through AP-23. The same rule applies:
verify the behavior and exceptions before changing a pattern.

## AP-16: Exec for string or path operations

**Smell:** invoking a shell or another runtime for simple transformations.

**Impact:** platform dependence, process overhead, and awkward property capture.

```xml
<!-- BAD: a shell pipeline for a simple transformation. -->
<Target Name="GetCleanVersion">
  <Exec Command="echo $(Version) | sed 's/-preview//'" ConsoleToMSBuild="true">
    <Output TaskParameter="ConsoleOutput" PropertyName="CleanVersion" />
  </Exec>
</Target>

<!-- GOOD: property functions, where the transformation is the intended contract. -->
<PropertyGroup>
  <CleanVersion>$(Version.Replace('-preview', ''))</CleanVersion>
  <HasPrerelease>$(Version.Contains('-'))</HasPrerelease>
  <LowerName>$(AssemblyName.ToLowerInvariant())</LowerName>
  <NormalizedOutput>$([MSBuild]::NormalizeDirectory('$(OutputPath)'))</NormalizedOutput>
  <ToolPath>$([MSBuild]::NormalizePath('$(MSBuildThisFileDirectory)', 'tools', 'mytool.exe'))</ToolPath>
</PropertyGroup>
```

Preserve transformation semantics and evaluation timing. This does not mean arbitrary external
tools or stateful operations should become property functions.

## AP-17: Updating an item before it exists

**Smell:** `Update` is evaluated before the intended item is included.

**Impact:** the metadata change matches no existing item.

```xml
<!-- BAD: no matching item exists at the update. -->
<ItemGroup>
  <Extra Update="external.dat" Visible="false" />
  <Extra Include="external.dat" />
</ItemGroup>

<!-- GOOD: Include then Update in the SAME group is valid. -->
<ItemGroup>
  <Extra Include="external.dat" />
  <Extra Update="external.dat" Visible="false" />
</ItemGroup>
```

The original catalog incorrectly treated mixing Include and Update in one ItemGroup as a
defect. Order and existence are what matter; splitting groups is neither necessary nor a fix
for an update that still precedes its include.

## AP-18: Apparently redundant transitive project references

**Smell:** `App` references both `Core` and `Utils`, and `Core` also references `Utils`.

**Impact:** a truly unnecessary edge can add coupling or resolution work, but transitive
reachability alone does not prove redundancy or an ordering bug.

```xml
<!-- Candidate for review, not automatically incorrect. -->
<ItemGroup>
  <ProjectReference Include="..\Core\Core.csproj" />
  <ProjectReference Include="..\Utils\Utils.csproj" />
</ItemGroup>
```

Keep `App -> Utils` if App uses its API directly, needs its metadata/build-order contract, or
repository policy requires explicit dependencies. Remove an edge only after verifying equivalent
compile/runtime/pack behavior and supported SDK/framework configurations. Removing this edge does
not itself shorten the required `App -> Core -> Utils` reference chain.
Use [build-perf-baseline](../build-perf-baseline.md) for a measured graph experiment.

## AP-19: Side effects during evaluation

**Smell:** property evaluation writes files, mutates state, or performs network operations.

**Impact:** evaluation can repeat during IDE/design-time and graph discovery, making side effects
unpredictable. Some such functions are not permitted by default; do not loosen restrictions to
make a side-effecting property expression work.

```xml
<!-- BAD, and not a generally permitted property function. -->
<PropertyGroup>
  <Timestamp>$([System.IO.File]::WriteAllText('stamp.txt', 'built'))</Timestamp>
</PropertyGroup>

<!-- Execution-time work belongs in a properly scheduled target. -->
<Target Name="WriteTimestamp" BeforeTargets="Build">
  <WriteLinesToFile File="stamp.txt" Lines="built" Overwrite="true" />
</Target>
```

Moving work to a target still requires deciding its inputs, outputs, and whether it must run
every time. For evaluation-time read/CPU cost, use [eval-performance](../eval-performance.md).

## AP-20: Platform-specific Exec without a platform contract

**Smell:** `chmod`, `cmd /c`, or a platform-specific executable is invoked on every OS.

**Impact:** the wrong shell/tool or path syntax fails on another platform.

```xml
<Target Name="MakeExecutable" AfterTargets="Build"
        Condition="!$([MSBuild]::IsOSPlatform('Windows'))">
  <Exec Command="chmod +x &quot;$([MSBuild]::NormalizePath('$(OutputPath)', 'mytool'))&quot;" />
</Target>
```

Prefer a portable built-in task when equivalent. Otherwise gate supported platforms, quote
paths, and confirm that skipping the operation on other systems preserves their required behavior.
An OS condition is not a substitute for implementing a capability the other platform also needs.

## AP-21: An early property condition reads TargetFramework too soon

**Smell:** a PropertyGroup or property in an early `.props` file conditions on a framework that
the project body has not set yet.

**Impact:** a single-targeted project can silently miss the assignment. A multi-targeted inner
build may instead receive TargetFramework globally; distinguish those cases.

```xml
<!-- BAD in an early Directory.Build.props when the project sets TargetFramework later. -->
<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0'">
  <DefineConstants>$(DefineConstants);MY_FEATURE</DefineConstants>
</PropertyGroup>

<!-- The same assignment can be placed after the project defines the framework,
     for example in Directory.Build.targets for a single-targeted/inner build. -->
<PropertyGroup Condition="'$(TargetFramework)' == 'net8.0'">
  <DefineConstants>$(DefineConstants);MY_FEATURE</DefineConstants>
</PropertyGroup>
```

An outer cross-targeting build may still have no single TargetFramework. Check the intended
instance, and preserve existing constants rather than replacing them.

Move the dependent assignment, not an intentionally project-owned framework, and confirm its
consumer has not already used the value before the new location. For unknown evaluated values,
use the [property/item queries](../eval-performance.md), retaining the original global properties;
preprocessed XML alone does not prove which conditions selected properties or items.

**Item conditions are different:** items are evaluated after properties. These early-file
patterns can be correct and must not be flagged merely for using TargetFramework:

```xml
<!-- Valid in Directory.Build.props when the project later sets this framework. -->
<ItemGroup Condition="'$(TargetFramework)' == 'net472'">
  <PackageReference Include="System.Memory" />
</ItemGroup>

<!-- Valid per-framework package version selection. -->
<ItemGroup Condition="'$(TargetFramework)' == 'net8.0'">
  <PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.11" />
</ItemGroup>
```

Target conditions are evaluated at execution time. Do not move all item/target conditions just
because an early **property** condition is wrong.

## AP-22: Project instances with path-neutral global properties

**Smell:** an MSBuild task builds/publishes the same project, or a referenced project, with an
extra global property that does not isolate its output paths.

```xml
<!-- Both shapes can create a distinct instance sharing existing bin/obj paths. -->
<MSBuild Projects="$(MSBuildProjectFullPath)" Targets="Publish" Properties="_IsPublishing=true" />
<MSBuild Projects="..\tool\tool.csproj" Targets="Publish" Properties="_IsPublishing=true" />
```

**Impact:** instance identity includes the project path and global properties. Distinct instances
can write the same assemblies, PDBs, assets files, or generated files, producing duplicated work
and intermittent parallel-build locks.

Confirm the actual global-property differences and evaluated output/intermediate paths using
[replayed build evidence](../binlog-failure-analysis.md). A property difference alone is not a
collision if every relevant output is isolated.

**Repair choices depend on the build contract:**

1. Remove an unnecessary second invocation/property discriminator.
2. For work that belongs to one instance, schedule a suitable target in that instance, after
   checking its dependency graph for cycles.
3. Make a producer own its artifacts, and have consumers sequence and consume them rather than
   re-publishing the same project under a different property set.
4. If different instances are intentional, isolate all relevant outputs/intermediate paths
   early enough for SDK and NuGet consumers, and use matching restore/build settings.

**Publish-on-build needs special care.** The original example used a private `_IsPublishing`
guard and `AfterTargets="Build" DependsOnTargets="Publish"`. That can work through `dotnet build`
and `dotnet publish` yet produce `MSB4006` through `dotnet msbuild -t:Publish`, because Publish
already depends on Build. It is not a universal repair.

Prefer an explicit publish operation when publish is the requested outcome, choosing an unused
log name first:

```powershell
dotnet publish .\Tool\Tool.csproj -c Release "-bl:publish-01.binlog"
```

If a repository genuinely needs publish-on-build orchestration, validate its target graph and
all supported entry commands; do not blindly substitute private SDK flags or add a cycle.
A build-order-only reference can sequence a producer:

```xml
<ProjectReference Include="..\Tool\Tool.csproj" ReferenceOutputAssembly="false" />
```

That reference schedules the producer's **build**, not automatically its Publish target.
The producer's actual artifact workflow must still exist. Retest the original parallel/graph
scenario; serialization or repeated cleaning is not a permanent collision fix.

## AP-23: Re-injecting a single-targeted project's own framework

**Smell:** a reference injects the TFM that a single-targeted project already declares.

```xml
<!-- Tool already declares TargetFramework=net8.0. -->
<ProjectReference Include="..\Tool\Tool.csproj" SetTargetFramework="TargetFramework=net8.0" />
```

**Impact:** a globally supplied TargetFramework can create an instance different from the ordinary
build, even though both resolve to the same framework output paths. Confirm that duplicate
instances actually share paths before attributing file-lock failures to this metadata.

```xml
<!-- Remove the redundant injection when the tool should build as declared. -->
<ProjectReference Include="..\Tool\Tool.csproj" />
```

Do not remove legitimate framework selection:

- Selecting one TFM of a multi-targeted reference can be intentional.
- Overriding a single-targeted reference to a **different** framework can be intentional if the
  project, dependencies, restore, and output paths support that contract.
- Different frameworks/configurations do not guarantee isolation when custom paths omit their
  discriminators; inspect actual paths.

### Build-only references across incompatible frameworks

An incompatible assembly cannot become a compiler reference. A build-order-only tool reference
may need both `ReferenceOutputAssembly="false"` and `SkipGetTargetFrameworkProperties="true"`.
Bypassing negotiation can also let the caller's global TargetFramework leak into the tool.

To build a single-targeted tool as declared:

```xml
<ProjectReference Include="..\Tool\Tool.csproj"
                  SkipGetTargetFrameworkProperties="true"
                  UndefineProperties="TargetFramework"
                  ReferenceOutputAssembly="false" />
```

When an explicit TFM must be selected instead, use `SetTargetFramework` with the intended value.
Do not simultaneously set and remove the same property. Do not apply this bypass to ordinary
compatible assembly references, and verify the tool's actual framework/output in the log.

## Quick-reference checklist

| Source | Check first | Typical concern |
| --- | --- | --- |
| AP-02 | Unsafe string conditions | Parsing/correctness |
| AP-19 | Evaluation side effects | Repeated or unsafe work |
| AP-21 | Early framework-dependent properties | Silent missing settings |
| AP-22, AP-23 | Distinct instances sharing outputs | Duplicate builds/races |
| AP-03 | Machine-specific paths | Portability |
| AP-06 | Legacy package HintPaths | Dependency migration |
| AP-07 | Unwanted consumer dependencies/assets | Package contract |
| AP-11 | Incomplete generation inputs/outputs | Stale or repeated work |
| AP-13 | Optional versus required imports | Missing dependency behavior |
| AP-05 | Duplicate source items versus language/order exceptions | Item correctness |
| AP-04 | Proven redundant defaults versus intentional pins | Maintainability |
| AP-08, AP-09 | Shared settings or unintended version drift | Consistency |
| AP-01, AP-16 | Shell operations replaceable by built-ins | Portability/overhead |
| AP-14, AP-20 | Actual path consumer and platform support | Cross-platform behavior |
| AP-10 | Mixed target responsibilities | Scheduling/incrementality |
| AP-12, AP-15 | Assignment timing and intended overrides | Property contracts |
| AP-17 | Update before Include, not merely a shared ItemGroup | Missing metadata |
| AP-18 | Real direct dependencies versus redundant edges | Graph/asset contracts |
incremental-build-inputs-outputs.md 3.0 KB
# Incremental inputs and outputs on custom targets

Expensive artifact-producing targets need complete inputs and real outputs. This is not a rule
that every validation/orchestration target must have a stamp file.

The original catalog's project-file-only example was incomplete when generation depended on
`$(Version)`: a command-line property can change without touching the project file. A stable
value-input file can represent that dependency while a separate target registers outputs even
when generation is skipped:

```xml
<Target Name="WriteBuildInfoInputs">
  <ItemGroup>
    <FileWrites Include="$(IntermediateOutputPath)BuildInfo.inputs" />
  </ItemGroup>
  <MakeDir Directories="$(IntermediateOutputPath)" />
  <WriteLinesToFile File="$(IntermediateOutputPath)BuildInfo.inputs"
                    Lines="$(Version)" Overwrite="true" WriteOnlyWhenDifferent="true" />
</Target>

<Target Name="GenerateBuildInfo"
        DependsOnTargets="WriteBuildInfoInputs"
        Inputs="$(MSBuildProjectFullPath);$(MSBuildAllProjects);$(IntermediateOutputPath)BuildInfo.inputs"
        Outputs="$(IntermediateOutputPath)BuildInfo.g.cs">
  <WriteLinesToFile File="$(IntermediateOutputPath)BuildInfo.g.cs"
                    Lines="// Generated for $(Version)" Overwrite="true" />
</Target>

<Target Name="RegisterBuildInfo"
        BeforeTargets="CoreCompile"
        DependsOnTargets="GenerateBuildInfo">
  <ItemGroup>
    <Compile Include="$(IntermediateOutputPath)BuildInfo.g.cs" />
    <FileWrites Include="$(IntermediateOutputPath)BuildInfo.g.cs" />
  </ItemGroup>
</Target>
```

This illustrates a simple version-dependent producer. Adapt it to the actual generator:

- Add its templates, tools, configuration, and source files to the inputs.
- Serialize every relevant non-file value into a stable fingerprint without losing distinctions.
  Git/clock/network state is not tracked merely by listing the project file.
- Keep outputs in stable, configuration/framework/runtime-isolated intermediate paths.
- Ensure generated compile items are registered exactly once on both first and skipped builds.
  Intermediate files are normally excluded from SDK default source globs.
- Register the state file in its producer before generation can fail, so failed-build cleanup
  records its ownership too. Register generated outputs on successful and skipped generation.
  FileWrites is not a substitute for incremental inputs/outputs or compiler item inclusion.
- Timestamp checks do not remember a removed wildcard input. Track input-set membership and
  remove obsolete owned outputs when the generator's contract requires it.

Verify first build, identical second build, a relevant file/property change, removed inputs,
deleted output, successful-build Clean, and failed-generation Clean. Do not assume a timestamp-only
model can distinguish arbitrary same-timestamp mutations. Keep mutation/cleanup experiments confined
to approved disposable outputs. See [incremental-build](../incremental-build.md) for the full workflow
and IDE checks.
private-assets.md 1.5 KB
# PrivateAssets for analyzers and build tools

Use `PrivateAssets="all"` when a package is an implementation-only build dependency and must not
become a dependency of consumers of the produced package.

```xml
<!-- These packages are intended to remain local to this project's build. -->
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556" PrivateAssets="all" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="all" />
<PackageReference Include="MinVer" Version="5.0.0" PrivateAssets="all" />
```

Typical candidates from the original catalog include:

- Analyzer and code-fix packages.
- Source generators intended to run only in the producer.
- SourceLink providers.
- Versioning tools such as MinVer or Nerdbank.GitVersioning.
- Build-only compatibility/checking tools.

Do not infer a leak merely from a missing literal attribute. Inspect evaluated metadata,
`IncludeAssets`/`ExcludeAssets`, package contents, generated restore assets, and the packed
dependency contract. PackageReference's default private-asset categories already restrict some
asset flow, while `buildTransitive` and other dependencies can have different effects.

An analyzer or build extension deliberately distributed to consumers is not a private
implementation detail. Do not suppress intentional transitive behavior, hide required runtime
dependencies, or treat `PrivateAssets` as a way to skip building a project.
Verify the produced package and a representative consumer before declaring the change safe.
references/
binlog-failure-analysis.md 4.8 KB
# Analyzing MSBuild failures with binary logs

Based on the original `binlog-failure-analysis` skill. Use MSBuild's built-in replay to diagnose
an existing `.binlog`, including when the original checkout is unavailable.

## Before analysis

- Reuse a log that records the relevant invocation. If none exists and the build can be reproduced,
  follow [binlog-generation](binlog-generation.md) with the original arguments.
- A `.binlog` is binary. Do not use a text reader, `strings`, or text search directly on it.
- Recorded paths identify the original build; they are not permission to search unrelated
  checkouts or proof that source/project files exist locally.
- Synthesize findings as evidence emerges. Stop once actionable causes and remaining uncertainty
  are clear rather than spending the whole investigation collecting unrelated events.

## Replay a binary log

Choose unused text-log filenames, substitute the supplied binary-log path, and replay it:

```powershell
dotnet msbuild ".\build.binlog" -noconlog -fl "-flp:logfile=full-01.log;verbosity=diagnostic;PerformanceSummary" -fl1 "-flp1:logfile=errors-01.log;errorsonly" -fl2 "-flp2:logfile=warnings-01.log;warningsonly"
```

Quote each complete semicolon-delimited logger argument, especially in PowerShell. The command
reads the recorded build; it does not restore or rebuild its projects. A compatible `MSBuild.exe`
can replace `dotnet msbuild`; no analysis server or extra package is required.

Confirm the command completed and the diagnostic log is nonempty. Errors-only or warnings-only
logs can legitimately be empty. If the installed MSBuild cannot read the binary-log format,
report that blocker and the need for compatible tooling instead of pretending analysis succeeded.

Replay success is **not** proof that the recorded build succeeded. Replay duration is **not**
the recorded build's elapsed time. The same replay mechanics serve
[performance diagnostics](build-perf-diagnostics.md): use recorded events and the Project,
Target, and Task Performance Summaries, not the time spent converting the log.

## Inspect the replayed text

Start with errors, then search the diagnostic text around the actual codes, targets, and projects:

```powershell
Get-Content -LiteralPath .\errors-01.log
Select-String -LiteralPath .\full-01.log -Pattern 'CS0246', 'CoreCompile', 'Build FAILED' -Context 2
```

The patterns above are examples, not a filter that should discard other error codes. Inspect the
recorded evidence needed to explain the failure:

- Build errors and warnings, including custom task errors.
- Project-instance identity, configuration, target framework, and global properties.
- Property assignments and item/reference metadata visible in the log.
- Evaluation, import, target, and task execution or skip messages.

Text replay cannot manufacture data that was not recorded and does not guarantee extraction of
embedded project/import source. Read source only when it is available in the current checkout.
If the responsible definition is absent from both local source and replayed text, state that
limitation and request the specific missing evidence; do not invent an exact edit location.

## Find independent causes

1. Associate each error with its project **instance**, target, and task. The same project path
   under different global properties can represent distinct builds.
2. Follow producer/consumer dependencies. Parallel log order is not causal order: a missing
   referenced assembly may be downstream of a failed producer, while another project has an
   independent failure.
3. Inspect the actual values seen by the failing task rather than assuming the project body's
   value won. Check conditions, imports, item metadata, and command-line global properties.
4. Connect each root cause to a minimal repair. A namespace error alone does not prove which
   package should be added; confirm the relevant references and target framework.

Use [msbuild-antipatterns](msbuild-antipatterns.md) for a demonstrated authoring defect,
[extension-points](extension-points.md) for imports/hooks or packed-layout issues, and
[incremental-build](incremental-build.md) for stale outputs or incorrect skip decisions.
Do not turn failure diagnosis into an unrequested modernization pass.

## Verify and report

If source can be changed, rerun the original failing scenario with a new binary log, preserving
its configuration/framework/properties. Confirm the independent root errors and their cascades
are resolved, and exercise affected dependents. Check a no-change build when targets/items/outputs
were changed.

For artifact-only analysis, provide proposed changes and explicitly say they were not applied
or rebuilt. Report the evidence, root causes versus downstream failures, minimal repair, and
actual verification status. Treat replayed text as sensitive diagnostic data just like its binlog.
binlog-generation.md 3.3 KB
# Generate binary logs

Based on the original `binlog-generation` skill, reduced to capture, verification, and retention.
Capture a log for the build being investigated, not as an unconditional rule for every .NET task.
If a matching log already exists, use [MSBuild replay](binlog-failure-analysis.md#replay-a-binary-log)
instead of rerunning the build.

## Preserve the operation

Append the binary logger switch to the existing MSBuild invocation. Keep its entry point, working
directory, target, configuration, framework, runtime, restore behavior, and global properties.
Do not replace a repository wrapper with a bare `dotnet build` unless the wrapper's equivalent
invocation is known.

Choose an unused filename before each invocation. The examples below assume these paths do not
already exist:

```powershell
dotnet build App.sln -c Release --no-restore "-bl:build-01.binlog"
dotnet msbuild App.csproj -t:Pack "-bl:pack-01.binlog"
```

Retain the user's actual arguments rather than substituting these project names or adding
`--no-restore`. Every comparison or retry needs a different log path; do not use bare `-bl`,
which reuses `msbuild.binlog`.

Automatic `{}` filenames are optional and toolset-dependent. Do not assume every .NET 8 SDK
supports expansion. If support is confirmed, quote the complete argument in PowerShell, such as
`"-bl:build-{}.binlog"`, and verify that the resulting name actually expanded. Explicit unused
names avoid that compatibility issue and also work for CI uploaders needing a known path.

`dotnet build`, `restore`, `pack`, and `publish` accept MSBuild logger switches. Test runners and
wrapper scripts differ: only forward `-bl` through a supported MSBuild argument surface. A
Microsoft.Testing.Platform-native invocation or `dotnet test --no-build` is not automatically a
request to capture a new build.

## Verify the artifact, including on failure

Record the command's exit code and locate the newly created, nonempty `.binlog` before starting
analysis:

```powershell
Get-ChildItem -File *.binlog | Select-Object Name, Length, LastWriteTime
```

An intentional failing build can still produce a useful log. Failure before MSBuild starts
(missing SDK, invalid command-line arguments, wrapper rejection) may produce none. Report that
condition; do not invent a path or repeatedly rebuild without addressing it.

Keep the path, original exit code, and scenario together. For a capture-only request, this is the
deliverable. Otherwise continue to [failure analysis](binlog-failure-analysis.md) or
[performance diagnostics](build-perf-diagnostics.md).

## Privacy and retention

Binary logs can contain command lines, environment/property values, credentials, paths, and
embedded project/import contents. Replayed text logs can expose the same sensitive values.
Keep both local by default and out of commits. Preserve existing logs during any approved cleanup;
do not use a repository-wide clean to prepare capture.

If embedding imported files is inappropriate, use a quoted logger argument such as:

```powershell
dotnet build App.csproj "-bl:build-02.binlog;ProjectImports=None"
```

`ProjectImports=None` reduces embedded source coverage; it does **not** redact secrets from
properties, environment values, task arguments, or messages. Explain the diagnostic tradeoff,
and review/redact artifacts before any authorized sharing.
build-perf-baseline.md 19.0 KB
# Build Performance Baseline & Optimization

Source: original `build-perf-baseline` skill.

## Overview

Before optimizing a build, you need a **baseline**. Without measurements,
optimization is guesswork. This reference covers establishing baselines and
applying systematic, measured optimization techniques.

**Related references:**
- [Build performance diagnostics](build-perf-diagnostics.md) - binlog-based bottleneck identification
- [Incremental builds](incremental-build.md) - Inputs/Outputs and up-to-date checks
- [Parallel build tuning](#step-6-parallel-build-tuning) - parallelism and critical paths
- [Evaluation performance](eval-performance.md) - glob and import-chain optimization

## Step 1: Establish a Performance Baseline

Measure three scenarios to understand where time is spent. Reuse matching existing
artifacts first; use [binlog generation](binlog-generation.md) for capture and
privacy guidance. Discover the repository's actual build entry point and retain
its configuration, TFM/RID, properties, SDK/toolset, node count, and restore policy
in the examples below.

The binlog filenames below are illustrative. Choose an unused explicit filename
for every capture; do not overwrite existing evidence.

Record those settings, source revision/local changes, machine resources, cache
state, and exact input edit. Compare successful builds of the same scenario, not
a failed build, a smaller solution, or differently instrumented runs.

For an advisory before/after claim, first assess the supplied measurements. A
`Rebuild` including restore and an unchanged ordinary build without restore do
not isolate an MSBuild setting. The corrective experiment compares the **old
setting value with the new value**, keeping the invocation, restore policy,
input edit, starting output state, and instrumentation equivalent in both arms.
Do not infer the unspecified setting from a command-line difference.

Conversely, accept comparable repeated measurements as evidence for their
stated workload, with sample-size and noise limits. A checkout, a fresh binlog,
or measurements of every other build scenario are not prerequisites for
answering a self-contained advisory question.

### Cold Build (First Build)

No previous output exists for the selected build. An end-to-end cold-output
measurement includes restore, compilation, and all required work.

Use an agreed disposable workspace or explicitly authorized cleanup of known
generated paths. Inspect custom Clean behavior and shared outputs first. Do not
recursively delete every directory named `bin` or `obj`, clear shared NuGet caches,
or stop shared build servers. If safe preparation is unavailable, report the cold
scenario as unmeasured.

```powershell
# After preparing the agreed cold-output state
dotnet build -m "-bl:cold-build.binlog"
```

Record whether packages, compiler servers, and filesystem caches are already
warm. Removing build outputs does not make those caches cold.

### Warm Build (Incremental Build)

Build output exists and some files have changed. This measures how well
incremental building handles a specific change.

```powershell
dotnet build -m
if ($LASTEXITCODE -ne 0) { throw "Initial build failed; no valid warm baseline." }

# Make one recorded, reversible source/input change, then build normally
dotnet build -m "-bl:warm-build.binlog"
```

A timestamp-only touch, implementation edit, and public-API edit can propagate
differently. Use the same kind of change before and after an optimization.

### No-Op Build (Nothing Changed)

Build output exists and nothing has changed. Expensive work whose inputs and
outputs are up to date should skip. A slow no-op can still be caused by
evaluation, restore checks, reference resolution, or orchestration rather than
broken compilation incrementality.

```powershell
dotnet build -m
if ($LASTEXITCODE -ne 0) { throw "Initial build failed; no valid no-op baseline." }

dotnet build -m "-bl:noop-build.binlog"
```

Label this **warm no-change** scenario separately from a warm changed-input build.
Do not use `Rebuild`, `-t:Rebuild`, or `--no-incremental` for the second build:
forced full work is a separate benchmark, not a no-op or proof of cold caches.

### What Good Looks Like

| Scenario | Expected behavior |
| --- | --- |
| Cold build | Complete required outputs, including compilation and required generation. This is the full-work baseline for the recorded cache state. |
| Warm build | Changed inputs and affected dependencies invalidate the appropriate work; unrelated recompilation needs explanation. |
| No-op build | Up-to-date expensive compilation/generation skips. Under roughly 5 seconds for small repositories or 30 seconds for large ones can be useful triage hints, not universal budgets. |

**Red flags to investigate, not automatic diagnoses:**
- No-op build over 30 seconds: distinguish evaluation, restore, copying, and
  unexpected execution before applying [incremental fixes](incremental-build.md).
- Warm build recompiles everything: inspect the input/API change and dependency
  chain; do not assume every downstream rebuild is unnecessary.
- Long cold restore: investigate feed/network work and cache state, not just
  package-cache problems.

### Recording Baselines

Prefer repeated measurements, such as three runs per scenario, and report their
median and spread. Re-establish the correct cold or warm state before each run.
Do not mix cold and warmed timings or silently discard inconvenient outliers.

| Scenario | Before median [range] | After median [range] | Improvement |
| --- | --- | --- | --- |
| Cold build, restore included/excluded | Not measured | Not measured | Seconds and percent |
| Warm build, named input edit | Not measured | Not measured | Seconds and percent |
| No-op build, unchanged command | Not measured | Not measured | Seconds and percent |

Fill this table with actual results and artifact paths. Percentage improvement is
`(before - after) / before * 100`; a negative result is a regression. Change one
variable at a time and retain the same success/output checks. Use distinct log
names for each run and for before/after results so baseline evidence is not
overwritten.

## Step 2: Artifacts Output Layout

`UseArtifactsOutput`, introduced in **.NET SDK 8**, centralizes output layout.
It can address output-management and collision problems and simplify CI caching;
it does not itself make compilation faster or validate a cache.

### Enabling Artifacts Output

```xml
<!-- Directory.Build.props -->
<PropertyGroup>
  <UseArtifactsOutput>true</UseArtifactsOutput>
</PropertyGroup>
```

### Before vs After

Illustrative single-target layout:

```text
# Traditional layout
src\
  MyLib\
    bin\Debug\net8.0\MyLib.dll
    obj\Debug\net8.0\...
  MyApp\
    bin\Debug\net8.0\MyApp.dll

# Artifacts layout
artifacts\
  bin\MyLib\debug\MyLib.dll
  bin\MyApp\debug\MyApp.dll
  obj\MyLib\debug\...
  obj\MyApp\debug\...
```

### Benefits

- **Separated outputs:** project/configuration pivots reduce accidental overlap;
  check duplicate project names and custom path/pivot overrides.
- **Easier cache management:** a common artifacts root is easier to collect,
  but cache keys must still cover the relevant inputs, options, SDK, and platform.
- **Simpler ignore rules:** the generated artifacts root can be ignored centrally.
- **Multi-targeting:** SDK pivots distinguish TFMs/RIDs where needed; inspect the
  evaluated paths instead of assuming one fixed subdirectory pattern.

### Customizing

```xml
<PropertyGroup>
  <ArtifactsPath>$(MSBuildThisFileDirectory)output</ArtifactsPath>
</PropertyGroup>
```

The CLI's `--artifacts-path` also requires SDK 8+. Keep restore, build, test,
pack/publish, scripts, and cleanup consistent with the new locations. Verify the
supported configuration/TFM/RID matrix and file ownership before adopting the
layout. A target framework change alone does not enable this SDK feature.

## Step 3: Deterministic Builds

Deterministic compilation produces identical compiler outputs for identical
compiler inputs. This supports caching and reproducibility, but does not make
every custom build step or package reproducible automatically.

### Enabling Deterministic Builds

```xml
<!-- Directory.Build.props -->
<PropertyGroup>
  <!-- Already enabled by default in modern .NET SDK projects -->
  <Deterministic>true</Deterministic>
  <ContinuousIntegrationBuild Condition="'$(CI)' == 'true'">true</ContinuousIntegrationBuild>
</PropertyGroup>
```

Use the repository's actual CI signal; not every runner supplies `CI=true`.

### What Deterministic Affects

- Removes time-dependent variation from compiler output; it does not simply zero
  every PE timestamp field.
- Makes compiler outputs repeatable for the same complete inputs.
- Works with source/path normalization for reproducible PDBs; deterministic
  compilation alone does not normalize arbitrary machine-specific paths.

### Why It Matters for Performance

- **Build caching:** deterministic outputs can be reused when the complete cache
  key and required artifacts are correct.
- **CI optimization:** correct input tracking can avoid rebuilding unchanged work.
- **Distributed builds:** cross-machine reuse also requires compatible toolsets,
  paths, options, dependencies, and generated content.

Verify reproducibility of the required artifacts. Neither these properties nor
NuGet lock files create a compiled-output cache or excuse untracked inputs.

## Step 4: Dependency Graph Trimming

Removing genuinely unnecessary references can reduce graph/resolution work and,
when it removes a critical dependency, shorten the critical path.

### Audit the Dependency Graph

Inspect existing binlogs for project references, global-property variants, build
times, and waits. If a new capture is needed:

```powershell
dotnet build "-bl:graph.binlog"
```

Use [local replay](binlog-failure-analysis.md#replay-a-binary-log) and
[performance diagnostics](build-perf-diagnostics.md) to follow the actual work.
Inclusive `ResolveProjectReferences` time includes waiting for dependencies; it
is not all reference-resolution CPU work.

### Techniques

#### Remove Redundant Transitive References

```xml
<!-- Before: Core also references Utils -->
<ItemGroup>
  <ProjectReference Include="..\Core\Core.csproj" />
  <ProjectReference Include="..\Utils\Utils.csproj" />
</ItemGroup>

<!-- Candidate only after proving the direct Utils edge is unnecessary -->
<ItemGroup>
  <ProjectReference Include="..\Core\Core.csproj" />
</ItemGroup>
```

Transitive reachability alone is insufficient. A direct reference may express
direct API use, repository policy, or important metadata. Verify compile/runtime
dependencies and pack/publish behavior across supported TFMs/configurations.
Removing `App -> Utils` does not necessarily shorten `App -> Core -> Utils`.

#### Build-Order-Only References

When a project must build first but its assembly is not a compiler reference:

```xml
<ProjectReference Include="..\CodeGen\CodeGen.csproj"
                  ReferenceOutputAssembly="false" />
```

This preserves the build-order dependency. It does **not** remove the scheduling
edge or make the projects independent.

#### Prevent Transitive Asset Flow

When a dependency is an implementation detail that should not be exposed through
the relevant NuGet asset/pack contract:

```xml
<ProjectReference Include="..\InternalHelpers\InternalHelpers.csproj"
                  PrivateAssets="all" />
```

Inspect restored assets, generated package dependencies, and consuming projects.
`PrivateAssets` is not a generic "do not build" or "remove the compiler reference"
switch, and this metadata alone does not establish a performance improvement.

#### Disable Transitive Project References

For deliberately explicit-only dependency management in supporting SDK builds:

```xml
<PropertyGroup>
  <DisableTransitiveProjectReferences>true</DisableTransitiveProjectReferences>
</PropertyGroup>
```

**Caution:** this requires explicit references to consumed dependencies. Consider
it only for measured transitive-closure overhead, with consumer validation. It
does not eliminate required project build ordering.

## Step 5: Static Graph Builds (`/graph`)

Static graph mode constructs the project graph before building, allowing
scheduling from the declared dependencies.

### Enabling Graph Build

```powershell
dotnet build -graph
dotnet build -graph "-bl:graph-build.binlog"
```

### Benefits

- **Scheduling:** knowing the complete graph can improve parallel scheduling.
- **Isolation:** project isolation is a separate contract, selected with
  `-isolateProjects`; `/graph` alone does not guarantee it.
- **Caching potential:** results-cache options are separate features with their
  own isolation/correctness requirements, not an automatic graph-build cache.

### When to Use

| Scenario | Recommendation |
| --- | --- |
| Large multi-project solution, for example 20+ projects | Measure graph mode as a candidate; project count is not proof of a benefit. |
| Small solution, for example fewer than 5 projects | Extra graph construction may outweigh scheduling gains; measure rather than assume. |
| CI builds | Try when dependencies are statically discoverable and output isolation is sound. |
| Local development | Compare both modes in the same cold, changed-input, or no-change scenario. |

### Troubleshooting Graph Build

All relevant project dependencies must be statically discoverable. References
created inside targets or hidden in programmatic `MSBuild` calls can violate
that model. Inspect the actual emitted error rather than assuming one error code.

Declare `ProjectReference` items during evaluation where that preserves their
semantics. Do not move execution-dependent logic blindly, drop dependencies, or
disable dependency builds to make graph construction pass. If the graph cannot
represent the build correctly, retain the normal build.

## Step 6: Parallel Build Tuning

### MaxCpuCount

```powershell
# Permit up to the logical processor count
dotnet build -m

# Explicit budget, useful on shared CI agents
dotnet build -m:4

# MSBuild.exe syntax
msbuild -m:8 .\MySolution.sln
```

Raw MSBuild defaults to one node without `-m`; the `dotnet build` driver can
supply switches itself. Inspect the actual invocation and record an explicit
budget when comparing runs. Respect memory limits, CPU quotas, and other users.

### Identifying Parallelism Bottlenecks

In recorded project-instance and scheduling evidence, look for:
- **Long sequential chains:** projects waiting on required predecessors.
- **Uneven load:** idle nodes while others remain busy.
- **Single-project bottleneck:** one long project on the critical path.

Name the chain with durations, for example `Core -> Api -> Web -> Tests`.
Aggregate target/task summaries alone cannot establish node utilization: totals
can overlap, nest, or include waits. If replay lacks sufficient scheduling detail,
report that gap rather than inventing utilization percentages.

For independent requests in a custom orchestration target, enable parallelism
on the `MSBuild` task as well as providing multiple nodes:

```xml
<MSBuild Projects="@(ProjectsToBuild)" Targets="Build" BuildInParallel="true" />
```

### Reducing the Critical Path

1. Split a measured large bottleneck only if the resulting work can run independently.
2. Remove proven unnecessary references using Step 4's compatibility checks.
3. Use `ReferenceOutputAssembly="false"` only for genuine build-order-only intent;
   it can reduce assembly-reference work, not the dependency wait itself.
4. Consider a shared base library only if the resulting graph is better; a new
   common prerequisite can also lengthen the serial chain.

More nodes cannot parallelize a required dependency chain and can worsen
memory- or I/O-bound workloads.

## Step 7: Additional Quick Wins

Treat these as candidates selected by evidence, not a list to apply wholesale.

### Separate Restore from Build

```powershell
dotnet restore
if ($LASTEXITCODE -ne 0) { throw "Restore failed; do not use stale assets." }
dotnet build --no-restore -m
if ($LASTEXITCODE -ne 0) { throw "Build failed; do not test stale outputs." }
dotnet test --no-build
```

Use matching configuration/TFM/RID and restore-affecting properties in each stage.
`--no-restore` requires current assets; `--no-build` requires successfully built
matching test outputs. Keep restore-inclusive and build-only timings separate.

### Skip Unnecessary Targets

For an explicitly agreed development scenario where these outputs/checks are
optional:

```powershell
dotnet build -p:GenerateDocumentationFile=false
dotnet build -p:RunAnalyzers=false
```

Measure their actual cost first. Preserve required XML documentation in packages,
required analyzer diagnostics in CI, and generator-produced code.
[Analyzer diagnostics](build-perf-diagnostics.md#2-roslyn-analyzers-and-source-generators)
covers conditional policy and global analyzer references. Do not silently call
disabled validation behavior-preserving.

### Use Project-Level Filtering

```powershell
dotnet build .\src\MyApp\MyApp.csproj
```

Build the project and its dependencies when that is the intended inner loop.
Solution filters can similarly select a supported subset. A smaller selection
is a different scenario, not proof that the full solution became faster; retain
the required integration and test coverage.

### Binary Log for All Investigations

Start with an existing matching binlog or capture through
[binlog generation](binlog-generation.md):

```powershell
dotnet build -m "-bl:perf.binlog"
```

Then use [build performance diagnostics](build-perf-diagnostics.md) to identify
the bottleneck before applying a change.

## Optimization Decision Tree

```text
Is the no-op build slow?
  YES -> Classify evaluation, restore, copies, and executed work first.
         Unexpected execution -> incremental-build.md.
         Slow evaluation -> eval-performance.md.
  NO / after classification:
    Is the cold build slow?
      Restore -> investigate feeds/cache/inputs; compare restore separately.
      Compilation -> diagnose analyzers/generators and critical-path work.
      Other targets -> inspect their recorded reasons and task costs.
    Is the warm changed-input build slow?
      Unexpected propagation -> incremental-build.md and dependency analysis.
      Required serial work -> inspect critical path and parallelism above.
    Are all scenarios healthy for the actual workload?
      Stop. Do not change healthy configuration just to apply a tuning flag.
```

Use the linked [incremental](incremental-build.md),
[evaluation](eval-performance.md), and [diagnostics](build-perf-diagnostics.md)
references for those branches.

## Validation and Results

Repeat the same scenario and input change with the same instrumentation. Verify
required outputs, downstream consumers, diagnostics, and relevant tests or
pack/publish behavior. For tracking changes, exercise input addition/change/removal
and missing outputs as described in [incremental builds](incremental-build.md).
For copy changes, verify [copy-mode semantics](copy-to-output-directory.md).

Report the command/environment, before/after median and spread, artifact paths,
one causal change, correctness checks, and unmeasured scenarios. Stop or revert
only your own experimental change if the benefit is within noise, the comparison
cannot succeed, or correctness regresses.
build-perf-diagnostics.md 13.9 KB
# Diagnosing MSBuild Build Performance

Source: original `build-perf-diagnostics` skill.

## Performance Analysis Methodology

1. Establish the relevant cold, warm changed-input, or no-change
   [baseline](build-perf-baseline.md). Keep `Rebuild` and ordinary `Build` distinct.
2. Use an existing matching binlog first. If one is missing, follow
   [binlog generation](binlog-generation.md) without changing the reported scenario.
3. [Replay the binary log](binlog-failure-analysis.md#replay-a-binary-log) locally
   to a diagnostic text log with a performance summary. The searches below assume
   that log is named `full-01.log`, as in the replay command; use its actual path.
4. Find expensive projects, targets, and tasks, then inspect the corresponding
   instance, execution reason, inputs, and dependency waits. Select one cause
   for a controlled change, not every plausible optimization.

Performance summaries report cumulative/inclusive durations, not additive shares
of elapsed wall time or CPU usage. Parallel work overlaps; orchestration targets
and tasks can include child work and waits.

In particular, **`ResolveProjectReferences` can mostly represent waiting for
dependent builds**, while a yielded node performs other work. Do not optimize it
solely because it tops the target summary. Follow the dependencies to actual
`Csc`, `ResolveAssemblyReference`, `Copy`, or custom-task work. Even `MSBuild`
task duration can include child builds rather than exclusive self-time.

## Key Metrics and Thresholds

Use these as investigation hints, not universal budgets or proof of a cause:

- **Build duration:** historical rough examples are under 10 seconds for a small
  workload, 60 seconds for a medium one, and 5 minutes for a large one. Compare
  the repository's actual scenario and machine, not labels alone.
- **Node utilization:** activity below roughly 80% warrants checking dependency
  waits, limited parallel work, and resource contention. Text-summary totals
  alone cannot establish utilization.
- **Single-target domination:** investigate a target near or above 50% of elapsed
  build time, but separate inclusive waits and nested work.
- **Analyzer versus compiler time:** around 30% or more of `Csc` time deserves
  investigation. Analyzer timings can overlap; do not add them as wall time or
  remove diagnostics solely to reach a percentage.
- **RAR time:** over 5 seconds per project, especially over 15 seconds, merits
  examination of reference count, paths, and resolution work.

## Common Bottlenecks

### 1. ResolveAssemblyReference (RAR) Slowness

- **Symptoms:** substantial `ResolveAssemblyReference` task time, for example
  over 5 seconds per affected project.
- **Root causes:** many assembly references, network-based paths, or expensive
  assembly search paths.
- **Fixes:** remove demonstrated unused references/search paths and avoid
  unnecessary network resolution, preserving all consumers.
- **Diagnostic guardrail:** `DesignTimeBuild`, `ResolveAssemblyReferencesSilent`,
  and `ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch` affect build or
  diagnostic behavior; changing them is not an established RAR performance fix.
- **Key insight:** RAR can legitimately execute on no-change builds to account
  for external resolution state, including installed targeting packs or GAC
  assemblies. Do not force it to skip using an incomplete freshness check.
- **Reduce transitive references carefully:** `DisableTransitiveProjectReferences`
  is a last resort requiring explicit references to consumed dependencies.
  `ReferenceOutputAssembly="false"` is appropriate when only build ordering is
  needed, but still retains that ordering. Trim only unused package references.
  Use the [dependency-graph audit](build-perf-baseline.md#step-4-dependency-graph-trimming).

### 2. Roslyn Analyzers and Source Generators

- **Symptoms:** `Csc` takes much longer than a comparable compilation, sometimes
  more than twice a measured compiler-only scenario.
- **Diagnosis:** inspect `Csc` and analyzer/generator timing in the replayed log.
  If timing detail is absent, obtain compiler-supported diagnostic timing rather
  than guessing from package count. A controlled `-p:RunAnalyzers=false`
  comparison must compile the same inputs on both sides, not compare a no-op
  against forced compilation.
- **Conditional development policy:** after measuring and agreeing the policy,
  examples include:

  ```xml
  <PropertyGroup>
    <RunAnalyzers Condition="'$(ContinuousIntegrationBuild)' != 'true'">false</RunAnalyzers>
    <EnforceCodeStyleInBuild Condition="'$(ContinuousIntegrationBuild)' == 'true'">true</EnforceCodeStyleInBuild>
  </PropertyGroup>
  ```

- **Per-configuration:** if development Debug builds are the intended scope, also
  guard the CI case, for example
  `Condition="'$(Configuration)' == 'Debug' and '$(ContinuousIntegrationBuild)' != 'true'"`.
  CI can build Debug too.
- **Rule/package scope:** configure genuinely redundant or expensive diagnostics
  appropriately, including `.editorconfig` severity policy, instead of blindly
  removing analyzer packages.
- **Key principle:** preserve required analyzer enforcement in CI. Verify effective
  properties and that the pipeline actually sets the CI signal. A conditional
  assignment does not undo an earlier or later unconditional override.
- **Source generators:** do not assume `RunAnalyzers=false` disables or measures
  every generator. Preserve required generated code and inspect generator-specific
  evidence.
- **GlobalPackageReference:** examine the project, `Directory.Build.props`,
  `Directory.Packages.props`, and package imports. Active global analyzer
  references can affect production and test projects; a declaration alone does
  not prove restoration or inclusion in the compiler's analyzer list.
- **EnforceCodeStyleInBuild:** when enabled it adds code-style checks to compiler
  execution; it does not mean analyzers execute when compilation itself skips.
  Conditionalize only under an agreed development/CI policy.

### 3. Serialization Bottlenecks (Single-threaded Targets)

- **Symptoms:** one project dominates while other nodes are idle or waiting.
- **Common culprits:** a long dependency chain, a critical-path project, or custom
  orchestration issuing independent project requests sequentially.
- **Fixes:** optimize the measured critical path, remove false dependencies, or
  split a bottleneck only when it exposes independent work. In custom `MSBuild`
  tasks, `BuildInParallel="true"` also needs multiple available nodes.
- Follow [parallel build tuning](build-perf-baseline.md#step-6-parallel-build-tuning).
  More nodes cannot parallelize required serial dependencies.

### 4. Excessive File I/O (Copy Tasks)

- **Symptoms:** high Copy aggregate time or excessive copy invocations.
- **Root causes:** thousands of unnecessary files, network destinations, or
  accidental per-item task batching instead of an appropriate item batch.
- **First fixes:** inspect item metadata, source/destination paths, and invocation
  counts. Reduce only unnecessary copies and choose the correct
  [copy mode](copy-to-output-directory.md); replacing `Always` blindly with
  `PreserveNewest` can leave mutated destination files stale.
- **Skip unchanged files:** inspect whether the actual target consumes
  `SkipCopyUnchangedFiles`; it may already be true. Custom `Copy` tasks expose
  `SkipUnchangedFiles`. Neither setting is a content-hash comparison.
- **Hardlinks:** identify the hot copy target in the binlog, then set only the
  property that target passes to `Copy.UseHardlinksIfPossible`:
  `CreateHardLinksForCopyFilesToOutputDirectoryIfPossible` for primary build
  outputs, `CreateHardLinksForAdditionalFilesIfPossible` for content/additional
  files, or `CreateHardLinksForCopyLocalIfPossible` for copy-local references.
  Custom `Copy` tasks need their own `UseHardlinksIfPossible` value. Hardlinks
  can help compatible same-volume, immutable-file workloads. A destination
  mutation through a hardlink can modify its source, so do not use this for
  writable/resettable content.
- **Shared layout:** `UseCommonOutputDirectory=true` assumes a genuinely shared,
  collision-free output layout. Verify ownership and consumers first.
  [Artifacts output](build-perf-baseline.md#step-2-artifacts-output-layout), including
  `--artifacts-path`, requires SDK 8+ and is a separate measured layout change.
- **Dev Drive:** on supported Windows development or self-hosted CI machines,
  evaluate Dev Drive for a measured I/O bottleneck. Do not promise automatic
  copy-on-write gains for every task or disable security tooling for a benchmark.

### 5. Evaluation Overhead

- **Symptoms:** significant startup/evaluation time before target execution.
- **Root causes:** expensive `Directory.Build.props` logic, globs traversing
  large trees, imports, or SDK-resolution overhead. NuGet-based SDK resolver
  latency depends on the toolset and environment; historical timings are not a
  fixed per-project cost.
- **Fixes:** simplify only measured costly logic and narrow offending globs.
  `EnableDefaultItems=false` is a last resort requiring complete intentional item
  lists, not the first optimization. Changing SDK resolution must preserve the
  build's actual SDK contract.
- Use [evaluation performance](eval-performance.md) for focused evidence and fixes.

### 6. NuGet Restore in Build

- **Symptoms:** restore contributes substantial work repeatedly. Distinguish an
  up-to-date check from actual repeated network/dependency-resolution work.
- **Separate restore from build:** successfully restore matching inputs, then
  use `dotnet build --no-restore`. Keep build-only and restore-inclusive baselines
  distinct; dependency changes require fresh assets.
- **Static graph restore:** `RestoreUseStaticGraphEvaluation=true` in
  `Directory.Build.props` is a candidate for a measured large restore graph.
  Validate equivalent resolved assets and toolset support. It is distinct from
  graph build and its benefit is workload-dependent.
- Investigate changing inputs and feed/cache behavior rather than purging shared
  package caches.

### 7. Large Project Count and Graph Shape

- **Symptoms:** many tiny projects add evaluation/invocation overhead, or deep
  dependency chains serialize otherwise parallelizable work.
- **Consider:** graph mode for scheduling, consolidating small leaves for measured
  overhead, or splitting a large bottleneck into independent pieces. These are
  different remedies for different evidence.
- **Graph shape matters:** wide independent branches expose parallelism; a long
  required chain remains serial regardless of node count.
- **Actions:** identify the exact unnecessary edge or costly project. Preserve
  direct API/metadata contracts and compare the resulting critical path.
  [Static graph builds](build-perf-baseline.md#step-5-static-graph-builds-graph)
  do not automatically provide isolation or a cache.

## Using Binlog Replay for Performance Analysis

1. [Replay the existing binlog](binlog-failure-analysis.md#replay-a-binary-log)
   with diagnostic verbosity and a performance summary.
2. Read the target/task summaries, usually near the end of the replayed log:

   ```powershell
   Select-String -Path .\full-01.log -Pattern 'Target Performance Summary|Task Performance Summary' -Context 0,50
   ```

   Use the cumulative timings to select candidates, not to compute additive
   percentages of elapsed build time.
3. Find per-project timings and instances:

   ```powershell
   Select-String -Path .\full-01.log -Pattern 'Done Building Project|Project Performance Summary' -Context 0,20
   ```

4. Inspect recorded scheduling evidence:

   ```powershell
   Select-String -Path .\full-01.log -Pattern 'node.*assigned|building with|scheduler'
   ```

   These messages alone are not a utilization measurement. Report missing
   scheduling/timestamp detail rather than inferring an exact timeline.
5. Check analyzer timing, when the original capture contains it:

   ```powershell
   Select-String -Path .\full-01.log -Pattern 'Total analyzer execution time|analyzer.*elapsed|CompilerAnalyzerDriver'
   ```

6. Drill into the relevant project's slow target and its tasks:

   ```powershell
   Select-String -Path .\full-01.log -Pattern 'Target "CoreCompile"|Target "ResolveAssemblyReferences"' -Context 0,20
   ```

## Quick Wins Checklist

Choose only items supported by the diagnosis, one experiment at a time:

- [ ] Confirm the intended `-m` node budget rather than assuming host defaults.
- [ ] Separate restore and build only with current matching assets.
- [ ] Measure static graph restore and verify equivalent assets.
- [ ] Consider hardlinks only for compatible immutable-file workloads.
- [ ] Scope analyzer changes to an agreed development policy; retain CI enforcement.
- [ ] Inspect `ProduceReferenceAssembly` before enabling it; many SDK configurations
  already enable it. Verify implementation-only and public-API changes downstream.
- [ ] Check [incremental behavior](incremental-build.md) on an ordinary second build.
- [ ] Inspect evaluated output/intermediate paths for collisions between projects,
  configurations, TFMs, and RIDs; do not just give everything one common directory.
- [ ] Measure graph mode for a statically discoverable multi-project build.
- [ ] Evaluate SDK 8+ artifacts layout only with its path-consumer checks.
- [ ] Consider a separate Dev Drive environment experiment for Windows I/O limits.

## Impact Categorization

- **HIGH IMPACT:** a verified critical-path cost above roughly 10% of elapsed
  build time, or substantial real work behind a target reported above 50%.
- **MEDIUM IMPACT:** verified costs around 2-10%.
- **QUICK WINS:** low-effort changes with demonstrated modest benefit, not
  unmeasured property toggles.

Report the project/TFM, target/task, evidence, one targeted change, and a
same-scenario before/after comparison with spread. Verify required artifacts,
diagnostics, and relevant tests/consumers. Stop if the result is unmeasured, within
noise, or breaks correctness; do not claim success from disabled validation or
inclusive timing arithmetic.
copy-to-output-directory.md 8.0 KB
# Choosing a CopyToOutputDirectory Mode

Source: original `copy-to-output-directory` skill.

## Overview

`CopyToOutputDirectory` metadata controls whether an item such as `Content`,
`None`, `EmbeddedResource`, or `Compile` is copied next to the build output.
`CopyToPublishDirectory` controls the corresponding publish selection. Picking
the wrong mode can leave stale files or add recurring copy work.

As of **MSBuild 17.13 / .NET SDK 9.0.2xx**, the common build targets support four
values. Check the publishing SDK separately for publish behavior.

| Mode | Copies when | Incremental cost | Typical use |
| --- | --- | --- | --- |
| `Never` | Never through this copy pipeline | None | Files not needed in that output |
| `PreserveNewest` | Source is newer than destination, or destination is missing | Timestamp checks | Normal source-edited content |
| `Always` | Every build that reaches the copy target, unless a skip-unchanged override is enabled | Repeated copies in classic mode | A real unconditional-copy/reset requirement |
| `IfDifferent` | Timestamp or size differs in either direction, or destination is missing | Timestamp and size checks | Destination may be mutated between builds |

Omitted metadata commonly means `Never`, but SDKs/imports can supply item-specific
defaults. Inspect effective metadata before assuming omission disables copying.

The following `Include` examples are for explicitly included files. When an SDK
already includes a file, use `Update` on its actual item type instead; for example,
a web SDK can classify `appsettings.json` as `Content`, not `None`.

```xml
<ItemGroup>
  <None Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
  <None Include="testdata\seed.db" CopyToOutputDirectory="IfDifferent" />
</ItemGroup>
```

The child-element form is equivalent:

```xml
<None Include="testdata\seed.db">
  <CopyToOutputDirectory>IfDifferent</CopyToOutputDirectory>
</None>
```

## Why `Always` Is Usually the Wrong Choice

Classic `Always` re-copies files whenever that copy pipeline executes, including
otherwise no-change MSBuild builds. Many or large content files can make this a
measurable recurring cost. An IDE up-to-date check that skips MSBuild entirely is
a separate decision.

Historically, `Always` addressed a specific scenario: **the destination changes
between builds**. Tests or applications might mutate a database, state file, or
configuration file. With `PreserveNewest`, a newer destination is not reset
because the source is no longer newer. `Always` forces a reset, but pays for it
even when the destination has not changed.

Do not replace `Always` solely because it appears in project text. First measure
copy work and establish whether unconditional copying is part of the required
behavior.

## `IfDifferent`: Copy When Different, in Either Direction

`IfDifferent` restores the source when the destination is missing or its timestamp
or size differs, whether the destination is newer or older. It skips unchanged
files according to that metadata comparison.

`_CopyDifferingSourceItemsToOutputDirectory` uses the `Copy` task with
`SkipUnchangedFiles="true"`. This is a **timestamp-and-size heuristic, not a content
hash**. A destination edited to the same size and last-write timestamp is treated
as unchanged and is not restored.

Use `IfDifferent` when:

- Tests or the application mutate copied databases, state/storage files, or
  editable configuration, and the metadata-based reset meets the contract.
- `Always` was used only to synchronize a drifting destination, not because
  every build must perform a fresh copy.

```xml
<ItemGroup>
  <!-- For an explicitly included fixture; use Update if already included -->
  <None Include="fixtures\catalog.db" CopyToOutputDirectory="IfDifferent" />
</ItemGroup>
```

If same-size/same-timestamp mutations must also be reset, retain genuine
unconditional copying or a separately verified content-based mechanism.

## Globally Softening `Always` with `$(SkipUnchangedFilesOnCopyAlways)`

For a codebase with many legacy `Always` items, a bulk opt-in is:

```xml
<PropertyGroup>
  <SkipUnchangedFilesOnCopyAlways>true</SkipUnchangedFilesOnCopyAlways>
</PropertyGroup>
```

The common `Always` copy target then passes `SkipUnchangedFiles="true"` to `Copy`,
giving those items the same timestamp/size skip heuristic as `IfDifferent`.

- Unset/default behavior is effectively `false`: classic `Always` copying.
- Setting it in `Directory.Build.props` can affect the entire repository.
- Prefer per-item intent when practical. A bulk property avoids individual item
  edits, but still changes behavior and requires checking every affected reset
  contract.
- Do not assume this build-target property governs every publish copy task.

## How the Modes Flow Through the Build

`GetCopyToOutputDirectoryItems` buckets items by their metadata. The common
`_CopySourceItemsToOutputDirectory` pipeline, invoked by
`CopyFilesToOutputDirectory`, uses:

- `_CopyOutOfDateSourceItemsToOutputDirectory` for `PreserveNewest`, with
  `Inputs`/`Outputs` timestamp checks.
- `_CopyOutOfDateSourceItemsToOutputDirectoryAlways` for `Always`, with the
  skip-unchanged property controlling its `Copy` task.
- `_CopyDifferingSourceItemsToOutputDirectory` for `IfDifferent`, with
  `SkipUnchangedFiles="true"`.

These standard build copies register `FileWrites` for the normal Clean pipeline.
Custom tasks and publish outputs can have different tracking; inspect ownership
and use only approved, scoped cleanup.

**Transitive copy:** copyable items can flow to referencing projects through
`ProjectReference`, including `_CopyToOutputDirectoryTransitiveItems`; `Never`
does not participate in that copy pipeline. Verify consumers as well as the
defining project. Supporting targets also collect `IfDifferent` for ClickOnce;
test the publishing mode and supported toolset actually used by the repository.

## Version Requirement

`IfDifferent` and `SkipUnchangedFilesOnCopyAlways` require **MSBuild 17.13+**
(**.NET SDK 9.0.2xx+ / Visual Studio 2022 17.13+**) for the common build-target
behavior described here. Older common targets can silently omit an item whose
mode they do not recognize.

Check the actual SDK/MSBuild host and the minimum supported toolset, not the
target framework. Gate usage or require a compatible SDK through `global.json`,
and check Visual Studio/MSBuild.exe hosts too. On older hosts, retaining `Always`
can preserve required reset behavior; substituting `PreserveNewest` may not.
An unsupported skip-unchanged property is not evidence of a speedup.

`CopyToPublishDirectory` is implemented by publishing targets. Verify recognition,
transitive collection, and reset behavior on the selected publishing SDK rather
than inferring support from the common build-target version alone.

## Quick Decision Guide

- Not needed in this output: explicitly choose `Never` when defaults might copy it.
- Normal source-edited file: `PreserveNewest`.
- Mutated destination should reset when metadata differs: `IfDifferent`.
- Fresh copy required on every pipeline execution, including metadata-identical
  changes: `Always`, without a skip-unchanged override.
- Many compatible legacy `Always` items: consider
  `SkipUnchangedFilesOnCopyAlways=true` after checking the same behavioral limits.

## Verify the Choice

In an approved disposable workspace or on explicitly scoped files, check an
ordinary no-change build, a source edit, a missing destination, and destination
mutations with newer and older timestamps. Check same-size/same-timestamp mutation
when strict reset matters. Also test source addition/removal and the intended
stale-output policy: copy metadata alone does not guarantee obsolete destinations
are deleted.

Check build, referencing projects, runtime use, and relevant publish/ClickOnce
outputs. Do not hardlink writable/resettable outputs to sources: writes through a
hardlink can change the source. Compare copy counts and same-scenario timings
using the [baseline](build-perf-baseline.md); preserve the output contract rather
than claiming success merely because fewer files were copied.
eval-performance.md 8.4 KB
# Diagnosing MSBuild Evaluation Performance

Source: original `eval-performance` skill.

Evaluation is work MSBuild does before executing targets: reading project files,
processing imports, expanding globs, and establishing definitions. Find and
confirm the bottleneck first; recommend a change only when measurements justify it.

## Confirm the Problem Before Changing Anything

Engage only when evaluation is **measurably** costly. Do not act when:

- **Slowness is in compilation or target execution.** Use
  [build performance diagnostics](build-perf-diagnostics.md).
- **The complaint is unnecessary rebuilding.** Use
  [incremental-build diagnosis](incremental-build.md).
- **There is no measurement.** Reuse a matching binlog or timing summary, or
  collect one through [binlog generation](binlog-generation.md). Do not infer
  slowness solely from project syntax.
- **A pattern below appears but evaluation is already fast.** Broad globs, deep
  imports, and item-default settings are not reasons to rewrite healthy builds.

Report unmeasured patterns as observations, not causes. Prefer the smallest
targeted change; never disable SDK defaults as the first move.

## MSBuild Evaluation Phases

1. **Initial properties:** environment variables, global properties, and reserved properties.
2. **Imports and properties:** process imports and property groups in evaluation order.
3. **Item definitions:** establish metadata defaults.
4. **Items:** process `Include`, `Remove`, `Update`, and glob expansion.
5. **UsingTask definitions:** register task implementations.
6. **Target definitions:** establish targets for subsequent execution.

Evaluation precedes execution for a project instance. It can be expensive even
when compilation later skips; a source generator running in `Csc` is execution,
not project evaluation.

## Diagnosing Evaluation Performance

### Using Binlog Replay

1. [Replay the existing binary log](binlog-failure-analysis.md#replay-a-binary-log)
   locally with diagnostic verbosity and performance summaries. The search below uses that
   command's `full-01.log`; substitute the actual path if you chose another name.
2. Look for evaluation timing and instance information:

   ```powershell
   Select-String -Path .\full-01.log -Pattern 'Project Evaluation Performance Summary|Evaluation started|Evaluation finished|Project evaluation' -Context 0,20
   ```

3. Record the expensive project instance, global properties, configuration,
   TFM/RID, and invocation purpose. Distinct instances may be expected rather
   than duplicate work.
4. Inspect its imports and property/item definitions. If the capture lacks
   detailed evaluation timing, do not fabricate it from the number of imports.
   On supporting MSBuild versions, `-profileEvaluation:eval.tsv` provides a
   focused profile; record the extra instrumentation separately.

### Using /pp (Preprocess)

```powershell
dotnet msbuild .\MyProject.csproj "-pp:full.xml"
```

- Supply the same configuration/TFM/global properties as the affected instance.
- `/pp` inlines imports and shows their boundaries and definitions.
- It does **not** fully expand every property/item value or measure evaluation cost.
- Over 10,000 lines can be a clue to inspect, not proof of heavy evaluation.

For evaluated values, **MSBuild 17.8+** also supports queries such as:

```powershell
dotnet msbuild .\MyProject.csproj -p:TargetFramework=net8.0 -getProperty:Configuration,TargetFramework -getItem:Compile
```

Without a target request, this evaluates rather than builds. On older hosts, use
the available diagnostic evidence instead of assuming these query switches exist.

### Using /clp:PerformanceSummary

Add `-clp:PerformanceSummary` to the same build invocation for evaluation,
project, target, and task summaries. Keep evaluation separate from execution,
and remember that cumulative/nested/parallel durations are not additive wall time.

## Expensive Glob Patterns

Pursue these remedies only when item evaluation is slow and the globs are the
measured cause; a custom glob over a small intended tree is fine.

- Broad patterns such as `**\*.cs` can traverse large trees.
- SDK default globs have exclusions; custom globs may not share them.
- Watch for unexpected traversal of `node_modules`, `.git`, and generated
  `bin`/`obj` trees, not just the text of the pattern.
- Append appropriate `DefaultItemExcludes` rather than replacing existing
  exclusions. A custom item must actually consume the exclusion property.
- Narrow roots/file types where equivalent, such as `src\**\*.cs`.
- `EnableDefaultItems=false` is a last resort requiring an intentional
  replacement for compile/resource/content discovery and future file changes.
- Inspect evaluated `Compile` and other affected items for unexpected files.

For an offending custom item, adapt exclusions and paths to the intended input set:

```xml
<PropertyGroup>
  <DefaultItemExcludes>$(DefaultItemExcludes);**\node_modules\**;**\.git\**</DefaultItemExcludes>
</PropertyGroup>
<ItemGroup>
  <AdditionalFiles Include="src\**\*.json" Exclude="$(DefaultItemExcludes)" />
</ItemGroup>
```

Verify item equivalence and file addition/removal behavior, not just a faster scan.

## Import Chain Analysis

- Deep chains, for example over 20 levels, are candidates to inspect, not
  inherently slow builds.
- Imports require reading, parsing, and evaluation; measure the costly portion.
- Common sources include package `.props`/`.targets`, framework SDK imports,
  and `Directory.Build` chains.
- Use `/pp` import-boundary comments and file paths to understand ownership and
  nesting; do not depend on one exact comment phrase.
- Consolidate/remove imports or package-provided build content only when the
  chain is measurably costly and all property/item/target consumers are preserved.

## Multiple Evaluations

- The same project path can legitimately have multiple evaluations.
- Different global-property sets, TFM/RID/configurations, outer/inner
  multi-targeting builds, restore, and design-time builds can require distinct
  instances.
- Compare instance identity and call purpose, not just an evaluation count or a
  rule of "one evaluation per project per TFM."
- Investigate callers that introduce accidental global-property differences.
  Normalize only differences that do not change intended behavior.
- [Graph build](build-perf-baseline.md#step-5-static-graph-builds-graph) is an
  experiment for compatible graphs, not a guarantee of evaluation deduplication.

## TreatAsLocalProperty

- Allows listed global properties to be overridden within the current project.
- A local override is not automatically forwarded as a new global value to
  child projects. For example, a command-line value can still reach a child even
  though the parent locally changed that property.
- It is therefore not a blanket mechanism for removing inherited properties
  from child builds. Use explicit `MSBuild` task property controls, such as
  `Properties` or `RemoveProperties`, when that is the intended contract.
- Use it when local override semantics are genuinely needed. The number of names
  listed is not by itself evidence of measurable evaluation overhead.

## Property Function Cost

- Property functions used during evaluation run at evaluation time; expressions
  inside targets instead run when that execution reaches them.
- Most string operations are cheap.
- `$([System.IO.File]::ReadAllText(...))` can repeat file I/O on each evaluation.
- Network access and heavy computations can be costly; measure the actual
  function rather than declaring every file read a bottleneck.
- Keep evaluation-time functions fast and side-effect-free. Move work into a
  correctly incremental target only if evaluation-time consumers do not need
  its result.

## Optimization Checklist

- [ ] Inspect `/pp` definitions/imports without treating line count as timing.
- [ ] Explain evaluation counts by project-instance identity.
- [ ] Exclude large unintended directories from measured costly globs.
- [ ] Reduce measured unnecessary evaluation-time I/O.
- [ ] Simplify expensive import chains while preserving consumers.
- [ ] Compare graph mode only where statically discoverable and relevant.
- [ ] Remove `UsingTask` declarations only if their consumers and measurable cost
  justify it.

Repeat the same build scenario and evaluate the same intended item/property sets.
Check additions, changes, removals, affected configurations, and downstream
behavior. Report timing and evidence before/after; leave configuration unchanged
when evaluation is cheap, unmeasured, or the apparent gain is within noise.
extension-points.md 13.4 KB
# MSBuild extension points

Based on the original `extension-points` skill: import hooks, wildcard extensions, control
properties, NuGet build assets, import guards, and Directory.Build discovery.
Use it for a specific import/hook failure or requested authoring modernization.

## Optional versus required imports

Guard **optional** imports; a required import must load or fail explicitly when missing:

```xml
<Import Project="optional.targets" Condition="Exists('optional.targets')" />
<Import Project="required.targets" />
```

Do not let a mixed-list condition or a copied optional-file guard suppress a required import.
Test all four optional-present/absent and required-present/absent combinations, including
import order when both exist. An aggregation file must preserve the same distinction.

## CustomBefore / CustomAfter hooks

Common MSBuild targets expose hooks such as:

```xml
<PropertyGroup>
  <CustomBeforeMicrosoftCommonTargets Condition="'$(CustomBeforeMicrosoftCommonTargets)' == ''">
    $(MSBuildExtensionsPath)\v$(MSBuildToolsVersion)\Custom.Before.Microsoft.Common.targets
  </CustomBeforeMicrosoftCommonTargets>
</PropertyGroup>

<Import Project="$(CustomBeforeMicrosoftCommonTargets)"
        Condition="'$(CustomBeforeMicrosoftCommonTargets)' != '' and Exists('$(CustomBeforeMicrosoftCommonTargets)')" />
<Import Project="$(CustomAfterMicrosoftCommonTargets)"
        Condition="'$(CustomAfterMicrosoftCommonTargets)' != '' and Exists('$(CustomAfterMicrosoftCommonTargets)')" />
```

Inspect the actual importing file and version; do not assume every targets file exposes the same
hooks. Although `Import` supports semicolon-separated paths, the surrounding `Exists()` tests
the whole property before the import runs. If any optional path in the list is absent, the
guard can skip the entire import, including a valid new hook. Do not append a new path blindly
to `CustomBeforeMicrosoftCommonTargets`.

For a hook with one existing optional path, use an aggregation file. In an early
`Directory.Build.props`, before the common targets consume the hook, preserve that path (or
its optional installed default) and set the hook to the aggregation file:

```xml
<PropertyGroup>
  <_RepoPreviousCommonTargetsHook>$(CustomBeforeMicrosoftCommonTargets)</_RepoPreviousCommonTargetsHook>
  <_RepoPreviousCommonTargetsHook Condition="'$(_RepoPreviousCommonTargetsHook)' == ''">$(MSBuildExtensionsPath)\v$(MSBuildToolsVersion)\Custom.Before.Microsoft.Common.targets</_RepoPreviousCommonTargetsHook>
  <CustomBeforeMicrosoftCommonTargets>$(MSBuildThisFileDirectory)BuildHooks.targets</CustomBeforeMicrosoftCommonTargets>
</PropertyGroup>
```

Place `BuildHooks.targets` and the required `MyExtension.targets` beside that props file:

```xml
<!-- BuildHooks.targets -->
<Project>
  <Import Project="$(_RepoPreviousCommonTargetsHook)"
          Condition="'$(_RepoPreviousCommonTargetsHook)' != '' and Exists('$(_RepoPreviousCommonTargetsHook)')" />
  <Import Project="$(MSBuildThisFileDirectory)MyExtension.targets" />
</Project>
```

The optional prior hook has its own guard; its absence cannot suppress the new required hook.
If the prior value is already a list, inspect its contract and give each optional import its
own guard in the aggregation file instead of passing that list to a single `Exists()`.
Verify both the present and absent optional-hook cases, preserving the intended import order.

Defaults that refer to installed MSBuild extensions can include a toolset/version segment for
side-by-side installations. Do not overwrite a configured hook or disable all imports to hide
one bad file.

For target execution rather than file imports, prefer uniquely named targets with
`BeforeTargets`/`AfterTargets`, or extend a documented `...DependsOn` property while preserving its
existing value. Define the list before a hook extends it, and check for dependency cycles.

## Wildcard import directories

Wildcard imports are sorted by filename:

```xml
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Imports\Microsoft.Common.props\ImportBefore\*"
        Condition="'$(ImportByWildcardBeforeMicrosoftCommonProps)' == 'true'
                   and Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Imports\Microsoft.Common.props\ImportBefore')" />
```

| Property | Typical location | Scope |
| --- | --- | --- |
| `MSBuildUserExtensionsPath` | Per-user MSBuild extension directory | User-specific |
| `MSBuildExtensionsPath` | MSBuild installation | Machine/toolset |
| `MSBuildProjectExtensionsPath` | Intermediate directory, normally `obj` | Project/NuGet |

Use names such as `01-defaults.props` and `02-overrides.props` when order is part of the contract.
Check the expanded imports. A machine- or user-wide extension affects more than the current repo.

## Import gating and control properties

Standard extension/discovery points use control properties with defaults such as:

```xml
<PropertyGroup>
  <ImportByWildcardBeforeMicrosoftCommonProps
      Condition="'$(ImportByWildcardBeforeMicrosoftCommonProps)' == ''">true</ImportByWildcardBeforeMicrosoftCommonProps>
  <ImportDirectoryBuildProps
      Condition="'$(ImportDirectoryBuildProps)' == ''">true</ImportDirectoryBuildProps>
</PropertyGroup>
```

| Property | Controlled behavior |
| --- | --- |
| `ImportDirectoryBuildProps` | Directory.Build.props discovery/import |
| `ImportDirectoryBuildTargets` | Directory.Build.targets discovery/import |
| `ImportProjectExtensionProps` | Generated project-extension props, including NuGet |
| `ImportProjectExtensionTargets` | Generated project-extension targets, including NuGet |
| `ImportByWildcardBefore*` | Matching ImportBefore extension point |
| `ImportByWildcardAfter*` | Matching ImportAfter extension point |

Set a control property before its consumer evaluates. These switches change build behavior:
disabling NuGet-generated imports or shared settings is not a general correctness/performance fix.

## NuGet package build extension layout

Automatically imported entry files use the package ID as their basename:

```text
MyPackage\
  build\
    MyPackage.props
    MyPackage.targets
  buildTransitive\
    MyPackage.props
    MyPackage.targets
```

- `build` serves direct consumers.
- `buildTransitive` can flow to transitive consumers with PackageReference.
- `buildMultiTargeting` serves the outer cross-targeting build, not ordinary per-TFM execution.
- Props are imported early and targets late. Framework-specific files can be placed in TFM
  subdirectories; NuGet selects compatible assets rather than necessarily an exact TFM match.
- A differently named entry file can cause `NU5129` and not be imported. Supporting files can
  have other names when an entry file explicitly imports them. Inspect the generated
  `*.nuget.g.props`/`*.nuget.g.targets` and restored assets to confirm discovery.

Package build files must not redefine restore inputs such as `TargetFramework`, `PackageReference`,
or `PackageVersion`. See the
[NuGet build-file conventions](https://learn.microsoft.com/en-us/nuget/concepts/msbuild-props-and-targets).

### Forwarding chain

When sharing implementation, keep a clear `buildTransitive -> build -> shared` chain instead of
duplicating direct/transitive logic or forwarding blindly to `buildMultiTargeting`.
For per-TFM layouts, include the matched asset folder segment. Derive it from the importing file,
not the consumer's `TargetFramework`: a `net10.0` project may consume the package's `net8.0` folder.

```xml
<!-- Inside packed buildTransitive/<tfm>/MyPackage.props. -->
<Import Project="$(MSBuildThisFileDirectory)..\..\build\$([System.IO.Path]::GetFileName($([System.IO.Path]::GetDirectoryName('$(MSBuildThisFileDirectory)'))))\MyPackage.props" />
```

Only use that path for that actual packed layout. Non-TFM-specific assets need a different
relative path, not an invented framework directory.

## Source tree vs packed layout

A source folder is not necessarily the layout of its `.nupkg`. Before reporting a missing
`build` or `buildTransitive` import:

1. Inspect the effective `NuspecFile`, `NuspecBasePath`, and `NuspecProperties` for the original
   pack configuration, including imported assignments and command-line global properties.
   Follow the configured relative or absolute `NuspecFile` even when it is outside the project
   directory and its parent. Resolve its `<file src="..." target="...">` mappings using the
   effective base path and property substitutions. An unavailable configured file is missing
   evidence, not proof that the packed import is absent.
2. When no custom nuspec is configured, inspect `.nuspec` files in the project directory and its
   **immediate parent** as a bounded discovery fallback; do not search unrelated ancestors.
3. Inspect the project's `Pack`/`PackagePath` item metadata and SDK packaging properties such as
   `BuildOutputTargetFolder` and `IncludeBuildOutput`.
4. Project the destination paths, including renamed files and per-TFM copies. Prefer inspecting
   the actual package when one is available.
5. Flag the import only if its target is absent from both the applicable source layout and the
   packed contract. A required file guaranteed by packaging must not gain an `Exists()` guard
   that would silently hide a broken package.

One shared source can be packed to multiple framework-specific destinations:

```xml
<files>
  <file src="buildTransitive\common\MyAdapter.props" target="buildTransitive\net462\MyAdapter.props" />
  <file src="buildTransitive\common\MyAdapter.props" target="buildTransitive\net8.0\MyAdapter.props" />
</files>
```

Equivalent SDK pack metadata can place the same source at each destination:

```xml
<ItemGroup>
  <None Include="buildTransitive\common\MyAdapter.props"
        Pack="true" PackagePath="buildTransitive\net462\MyAdapter.props" />
  <None Include="buildTransitive\common\MyAdapter.props"
        Pack="true" PackagePath="buildTransitive\net8.0\MyAdapter.props" />
</ItemGroup>
```

The absence of those TFM directories in source is not a missing-import defect. Preserve required
package contracts; do not add an existence guard to silently conceal a broken published layout.
See [msbuild-antipatterns](msbuild-antipatterns.md) AP-13.

## Import guard pattern

An imported file can record successful initialization:

```xml
<!-- At the end of the relevant props initialization. -->
<PropertyGroup>
  <MicrosoftCommonPropsHasBeenImported>true</MicrosoftCommonPropsHasBeenImported>
</PropertyGroup>

<!-- In the corresponding targets file. -->
<Import Project="Microsoft.Common.props"
        Condition="'$(MicrosoftCommonPropsHasBeenImported)' != 'true'" />
```

This pattern supports projects that enter through the targets file. Do not set another SDK's
guard to pretend its initialization happened; custom SDKs should use their own guard property.

## Directory.Build discovery

Only the nearest `Directory.Build.props` and nearest `Directory.Build.targets` are discovered
automatically. Nested files must explicitly import parents when inheritance is intended:

```xml
<Project>
  <PropertyGroup>
    <_ParentPropsPath>$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)..\'))</_ParentPropsPath>
  </PropertyGroup>
  <Import Project="$(_ParentPropsPath)" Condition="'$(_ParentPropsPath)' != ''" />
</Project>
```

Start the search above the current file to avoid recursion. Whether an absent parent is optional
is a repository contract; fail if it is required. Defaults belong before their consumers, while
values depending on project-defined properties must be evaluated late enough to see them.
In particular, early property conditions and later item conditions differ; see AP-21 in
[additional anti-patterns](antipatterns/additional-antipatterns.md).

## Creating your own extension point

For a custom SDK whose required `MySDK.props` sets `MySDKPropsImported`, a targets file can expose
before/after imports and target hooks:

```xml
<Project>
  <Import Project="$(MSBuildThisFileDirectory)MySDK.props"
          Condition="'$(MySDKPropsImported)' != 'true'" />
  <PropertyGroup>
    <CustomBeforeMySDK Condition="'$(CustomBeforeMySDK)' == ''">$(MSBuildProjectDirectory)\MySDK.Before.targets</CustomBeforeMySDK>
    <CustomAfterMySDK Condition="'$(CustomAfterMySDK)' == ''">$(MSBuildProjectDirectory)\MySDK.After.targets</CustomAfterMySDK>
    <MySDKBuildDependsOn Condition="'$(MySDKBuildDependsOn)' == ''">BeforeMySDKBuild;CoreMySDKBuild;AfterMySDKBuild</MySDKBuildDependsOn>
  </PropertyGroup>
  <Import Project="$(CustomBeforeMySDK)" Condition="Exists('$(CustomBeforeMySDK)')" />
  <Target Name="MySDKBuild" DependsOnTargets="$(MySDKBuildDependsOn)" />
  <Target Name="BeforeMySDKBuild" />
  <Target Name="CoreMySDKBuild" />
  <Target Name="AfterMySDKBuild" />
  <Import Project="$(CustomAfterMySDK)" Condition="Exists('$(CustomAfterMySDK)')" />
</Project>
```

Initialize the dependency list **before** importing extensions so a before-hook's appended
targets are not overwritten afterward. An extension can preserve the list and add its own
target, or use a uniquely named `BeforeTargets`/`AfterTargets` hook. Test that prior extensions,
the core work, and the new work all remain scheduled.

## Verify the extension

Check the import graph (a preprocessed project can show import ordering), evaluated values, and
target execution with the original scenario. Preprocessing is not a substitute for evaluated
property/item values. Exercise both single-targeted and multi-targeted consumers when affected,
and direct/transitive consumers of package assets. Confirm pre-existing hooks still run, new hooks
run exactly where intended, and optional versus required missing files behave differently.
incremental-build.md 17.2 KB
# Optimizing MSBuild Incremental Builds

Source: original `incremental-build` skill.

## How MSBuild Incremental Build Works

MSBuild can skip targets whose outputs are up to date, reducing work on subsequent
ordinary builds.

- **`Inputs` and `Outputs`:** file-producing targets use file timestamps to
  determine freshness. Outputs must exist and be at least as new as the relevant
  inputs. One-to-one item transforms can support partial incremental execution
  rather than requiring every output to be rebuilt.
- **Without file-based checks:** a target with neither attribute has no such
  freshness test when reached. It can still be skipped by conditions or because
  it already ran for that project instance. Cheap orchestration or discovery
  targets may correctly execute on every invocation that reaches them.
- **No `Incremental` target attribute:** `Incremental="false"` is not a valid
  MSBuild `Target` attribute. Do not add it to force execution.
- **Timestamps, not hashes:** touching an input can invalidate the target even
  without content changes. Conversely, unchanged timestamps can hide changes.

```xml
<!-- A one-to-one input/output mapping -->
<Target Name="Transform"
        Inputs="@(TransformFiles)"
        Outputs="@(TransformFiles->'$(OutputPath)%(Filename).out')">
  <!-- Existing transformation task goes here -->
</Target>

<!-- No file-based freshness check when this target is invoked -->
<Target Name="PrintMessage">
  <Message Text="This runs when the target is reached" />
</Target>
```

Give transformed outputs distinct paths if inputs can have duplicate basenames.
Do not add fictitious output files merely to skip necessary work.

## Why Incremental Builds Break (Top Causes)

1. **Missing Inputs/Outputs on file-producing custom targets.** Declare meaningful
   file dependencies for expensive repeatable work, not indiscriminately for every
   orchestration target.
2. **Volatile output paths.** Timestamps, build counters, or GUIDs in a path prevent
   finding the prior output.
3. **Writes outside declared Outputs.** A target may skip even when an undeclared
   generated file is missing or stale; track all required outputs.
4. **Missing FileWrites registration.** Standard Clean tracking may miss custom
   generated files. Merely putting a file under `obj` does not register it.
5. **Glob changes.** Additions and removals alter item membership, but general
   timestamp checks do not remember the previous set. Removing an input, or
   adding an older input, need not invalidate a custom target. Use appropriate
   input-set tracking and obsolete-output cleanup when the output depends on
   membership.
6. **Property changes.** MSBuild does not automatically compare prior property
   values used by a generator. Track relevant values explicitly. Changed
   configuration/TFM/RID paths can select missing outputs, but returning to an
   already-built configuration can reuse its isolated output set.
7. **NuGet package updates.** Assets and resolved reference changes can correctly
   invalidate compilation and resolution work. Preserve necessary invalidation.
8. **Compiler-server state.** A recycled `VBCSCompiler` can make a compilation that
   executes slower. It does not by itself explain why an up-to-date `CoreCompile`
   ran; separate execution decisions from compiler warm-up.

## Diagnosing "Why Did This Rebuild?"

Use binlogs to identify exactly why a target executed instead of skipping.

### Step-by-Step Using Binlog

1. Reuse matching first/second-build artifacts if available. Otherwise follow
   [binlog generation](binlog-generation.md) and capture two ordinary builds:

   Choose unused explicit names for both logs; the names below are illustrative.

   ```powershell
   dotnet build "-bl:first.binlog"
   if ($LASTEXITCODE -ne 0) { throw "First build failed; no valid incremental baseline." }
   dotnet build "-bl:second.binlog"
   ```

   Keep configuration, TFM/RID, properties, restore policy, and inputs unchanged.
   Analyze the second successful build. `Rebuild` and `--no-incremental` force
   full work and cannot establish a no-change skip result.
2. [Replay the second binlog](binlog-failure-analysis.md#replay-a-binary-log)
   locally with diagnostic verbosity and a performance summary, substituting `second.binlog`
   for `build.binlog`. The searches below use that command's `full-01.log`; substitute the
   actual path if you chose another name. Replay the first build to a different file when comparing.
3. Find executed/skipped targets and the accompanying reasons:

   ```powershell
   Select-String -Path .\full-01.log -Pattern 'Building target|Skipping target|was not skipped|is newer than output' -Context 0,5
   ```

4. Interpret messages in context (`...` stands for the target name):
   - **`Building target "..." completely.`:** full target execution; read the reason
     instead of assuming all outputs were missing.
   - **`Building target "..." partially, because some output files are out of date
     with respect to their input files.`:** partial execution for an applicable
     input/output mapping.
   - **`Skipping target "..." because all output files are up-to-date with respect
     to the input files.`:** freshness checks permitted a skip; verify the declared
     dependency set is complete.
5. Record the precise input/output path, timestamp, missing output, or condition
   responsible, for the correct project/global-property instance.

### Additional Diagnostic Techniques

- Compare the two replayed logs for changed properties, items, paths, and reasons.
- Find expensive second-build targets:

  ```powershell
  Select-String -Path .\full-01.log -Pattern 'Target Performance Summary|Task Performance Summary' -Context 0,30
  ```

- Aggregate/nested timings are not additive wall time. Follow orchestration waits
  to actual task work using [performance diagnostics](build-perf-diagnostics.md).
- A zero-duration target that runs is not automatically a defect. Inspect its
  dependencies and actual cost before changing it.
- If evaluation dominates while compilation correctly skips, use
  [evaluation performance](eval-performance.md), not a fake incremental shortcut.

## FileWrites and Clean Build

`FileWrites` lets the standard Clean infrastructure track build-generated files.
It is separate from target freshness and compiler inclusion.

- **`FileWrites`:** register owned generated files so the normal Clean pipeline
  can discover them.
- **`FileWritesShareable`:** do not assume reference-counted ownership or protection
  because another project still uses a file. Inspect the selected Clean targets,
  locations, and shared-file ownership before relying on it.
- **Missing registration:** files can accumulate, leaving stale inputs or outputs.
  A directory named `obj` is not automatic per-file tracking.

### Pattern for Registering Generated Files

For a generator with declared input files and generated line content:

```xml
<Target Name="MyGenerator"
        Inputs="$(MSBuildProjectFullPath);@(GeneratorInput)"
        Outputs="$(IntermediateOutputPath)generated.cs">
  <WriteLinesToFile File="$(IntermediateOutputPath)generated.cs"
                    Lines="@(GeneratedLines)"
                    Overwrite="true" />
  <ItemGroup>
    <FileWrites Include="$(IntermediateOutputPath)generated.cs" />
  </ItemGroup>
</Target>
```

Ensure the directory exists and that all settings/tool/template dependencies are
modeled; project-file timestamps do not track arbitrary property values. Use
`Overwrite="true"` when replacing generated content rather than appending it.

An `ItemGroup` inside a target with an up-to-date skip can still be evaluated by
**output inference**. Thus the source pattern of registering `FileWrites` and
`Compile` inside that target is valid when the paths/items can be inferred.
Do not move it solely because the task skipped. If an item depends only on task
output that cannot be inferred, make that item's definition available separately.

Use only authorized, scoped Clean operations. Never register user-authored files
or another project's outputs merely to make cleanup more aggressive.

## Visual Studio Fast Up-to-Date Check

Visual Studio's Fast Up-to-Date Check (FUTDC) is distinct from MSBuild's
`Inputs`/`Outputs`: it can skip invoking MSBuild entirely.

- **Fast checks:** the project system examines known inputs, outputs, copy items,
  and timestamps without a full build.
- **Custom work:** custom targets, generated files, or nonstandard/dynamic items
  may not be visible to that check.
- **Diagnostic comparison:** temporarily force MSBuild checks when investigating
  a Visual Studio-only discrepancy:

  ```xml
  <PropertyGroup>
    <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck>
  </PropertyGroup>
  ```

  Do not leave FUTDC disabled as a default performance fix.
- **Logging:** in Visual Studio's **Tools > Options > Projects and Solutions >
  SDK-Style Projects**, enable verbose up-to-date-check logging and inspect the
  Output window for the actual file/reason.
- **Common cases:** unregistered custom build actions, items added only during
  target execution, and changed `Content`/`None` copy items. Diagnose FUTDC's
  decision separately from MSBuild target skip reasons.

## Making Custom Targets Incremental

The following example combines C# templates under `config\$(ConfigFlavor)` into a
generated compilation input. The small state file tracks both the selected flavor
and input membership; a plain timestamp list would miss some changes to either.
Adapt the generator step and declared dependencies to the repository's real tool.

```xml
<PropertyGroup>
  <ConfigFlavor Condition="'$(ConfigFlavor)' == ''">Default</ConfigFlavor>
</PropertyGroup>
<ItemGroup>
  <ConfigInput Include="config\$(ConfigFlavor)\*.cs.in" />
</ItemGroup>

<Target Name="WriteConfigInputs">
  <MakeDir Directories="$(IntermediateOutputPath)" />
  <WriteLinesToFile File="$(IntermediateOutputPath)config.inputs"
                    Lines="Flavor=$(ConfigFlavor);@(ConfigInput->'%(FullPath)')"
                    Overwrite="true"
                    WriteOnlyWhenDifferent="true" />
  <ItemGroup>
    <FileWrites Include="$(IntermediateOutputPath)config.inputs" />
  </ItemGroup>
</Target>

<Target Name="GenerateConfig"
        DependsOnTargets="WriteConfigInputs"
        Inputs="$(MSBuildProjectFullPath);@(ConfigInput);$(IntermediateOutputPath)config.inputs"
        Outputs="$(IntermediateOutputPath)config.generated.cs"
        BeforeTargets="CoreCompile">
  <ReadLinesFromFile File="%(ConfigInput.Identity)"
                     Condition="'@(ConfigInput)' != ''">
    <Output TaskParameter="Lines" ItemName="_ConfigLines" />
  </ReadLinesFromFile>
  <WriteLinesToFile File="$(IntermediateOutputPath)config.generated.cs"
                    Lines="@(_ConfigLines)"
                    Overwrite="true" />
  <ItemGroup>
    <FileWrites Include="$(IntermediateOutputPath)config.generated.cs" />
    <Compile Include="$(IntermediateOutputPath)config.generated.cs" />
  </ItemGroup>
</Target>
```

**Key points:**

- The project file, actual input files, and state file participate in freshness.
  Also declare imported generator logic, tool binaries, templates, and relevant
  settings when they affect the real generator.
- `WriteOnlyWhenDifferent` prevents the **state file** from causing churn on every
  build. Include every relevant property/input-set value in an unambiguous,
  stable representation. Materialize valid state even when the initial input set
  is empty; comparing two empty strings must not suppress a missing state file.
- This state file records input identities and settings, not input contents.
  Keep the actual files in `Inputs` for normal timestamp-based edit detection.
  Do not describe a membership manifest as detecting content edits whose
  timestamps were preserved. Use content hashing only when that is the required
  contract; avoid a custom temporary-file/compare/copy scheme when
  `WriteOnlyWhenDifferent` already supplies the needed behavior.
- Generated output is overwritten when regeneration is necessary. If a real
  generator preserves output timestamps for identical content, use appropriate
  completion-state tracking so newer inputs do not make it execute forever;
  still detect missing real outputs.
- `IntermediateOutputPath` should isolate configurations/TFMs/RIDs; inspect custom
  overrides. `FileWrites`, not the directory name, supplies clean registration.
- `BeforeTargets="CoreCompile"` makes the file available before compilation.
  `Compile` inclusion and `FileWrites` registration can be inferred on a skip.
- Do not duplicate the generated item or rely on an evaluation-time glob to find
  a file that does not yet exist.
- For per-input generated outputs, detect removal and clean obsolete **owned**
  outputs as well as updating the input-set state.

Verify initial generation, an unchanged skip, ordinary edits, older-file additions,
removals, missing outputs, and the contract's empty-input behavior. Run every
destructive check on a disposable copy of the project and its required imports,
never on the original inputs, even if they would be restored afterward. Make the
copy byte-for-byte; `Get-Content`/`Set-Content` round-trips can change encodings
and line endings. If the copy cannot reproduce the build, report those checks as
blocked. Compare original hashes before and after as a final confirmation, not as
permission to mutate them.
Explain separately what the manifest tracks and what the file timestamps track.

### Common Mistakes to Avoid

```xml
<!-- Expensive generation without file-based freshness checks -->
<Target Name="BadTarget" BeforeTargets="CoreCompile">
  <Exec Command="generate-code.exe" />
</Target>

<!-- Volatile output path: the next invocation cannot reuse it -->
<Target Name="BadTarget2"
        Inputs="@(Compile)"
        Outputs="$(OutputPath)gen_$([System.DateTime]::Now.Ticks).cs">
  <Exec Command="generate-code.exe" />
</Target>

<!-- Stable-output pattern; declare the real tool/configuration inputs too -->
<Target Name="GoodTarget"
        Inputs="$(MSBuildProjectFullPath);@(GeneratorInput)"
        Outputs="$(IntermediateOutputPath)generated.cs"
        BeforeTargets="CoreCompile">
  <Exec Command="generate-code.exe -o &quot;$(IntermediateOutputPath)generated.cs&quot;" />
  <ItemGroup>
    <FileWrites Include="$(IntermediateOutputPath)generated.cs" />
    <Compile Include="$(IntermediateOutputPath)generated.cs" />
  </ItemGroup>
</Target>
```

These external-tool patterns assume the actual generator exists and produces the
declared file. Add property/input-set tracking when needed, as in the full example.
Do not include generated outputs in their own input set.

## Performance Summary and Preprocess

- **`-clp:PerformanceSummary`:** identifies cumulative project/target/task costs:

  ```powershell
  dotnet build -clp:PerformanceSummary
  ```

  Compare the relevant second-build work; inclusive durations are not exclusive
  CPU time.
- **`-pp:preprocess.xml`:** expands imports to locate definitions and their origin:

  ```powershell
  dotnet msbuild .\MyProject.csproj "-pp:preprocess.xml"
  ```

  It is not a dump of fully evaluated property/item values. Find the definitions
  of `Inputs`, `Outputs`, and imports, then inspect the matching build instance.
- Use the summary for what ran and `/pp` for where it was defined, together with
  replayed skip reasons.

## Common Fixes

- **Declare meaningful Inputs/Outputs** for repeatable file-producing work,
  including missing-output recovery and all real dependencies.
- **Use stable intermediate paths** while preserving configuration/TFM/RID
  isolation and avoiding output collisions.
- **Register owned generated files in FileWrites**; validate the applicable
  scoped Clean behavior rather than assuming every intermediate file is tracked.
- **Avoid unnecessary volatile data.** If per-build timestamps are required,
  preserve that contract and isolate their downstream impact. For Git revision
  state, a project-file timestamp or `.git\HEAD` alone is insufficient: branch
  refs can change without either changing. Use the repository's reliable state
  mechanism or a cheap probe that writes only changed content; report probe
  failures instead of freezing a stale value.
- **Use Returns for return-only item collections.** These are alternative
  definitions, not two targets to install together:

  ```xml
  <!-- Outputs also participates in file-based freshness -->
  <Target Name="GetFiles" Outputs="@(DiscoveredFiles)" />

  <!-- Returns supplies items without a file-based freshness contract -->
  <Target Name="GetFiles" Returns="@(DiscoveredFiles)" />
  ```

- **Choose copy metadata deliberately** using
  [CopyToOutputDirectory modes](copy-to-output-directory.md), especially when
  consumers mutate copied files.

## Validation

Compare equivalent ordinary builds using the
[baseline](build-perf-baseline.md). In an authorized disposable/scoped workspace,
verify: a no-change second build; input modification, addition, and removal;
property/template/tool changes; deletion of a real generated output; downstream
compilation and required diagnostics; relevant configuration/TFM/RID variants;
and approved Clean behavior. For copied content, include destination mutation.

Report the target/project instance, exact reason/file evidence, the correction,
before/after timings, and checks actually completed. A faster build that misses
required regeneration, leaves stale outputs, or changes an agreed metadata
contract is not a successful incremental-build fix.
msbuild-antipatterns.md 16.4 KB
# MSBuild anti-pattern catalog

Based on the original `msbuild-antipatterns` skill. The numbered catalog retains its
smell, impact, and correction structure. Use relevant entries for troubleshooting or an
explicit authoring review, not as a mandate to rewrite every matching pattern.

Confirm evaluated behavior and exceptions before editing. Preserve framework/package versions,
intentional overrides, item metadata, and public/output contracts. Legacy project-system
migration is a separate task, not an automatic consequence of finding verbose XML.

For framework-conditioned shared XML, check
[property versus item evaluation in AP-21](antipatterns/additional-antipatterns.md#ap-21-an-early-property-condition-reads-targetframework-too-soon)
before treating an early import as proof that both conditions are wrong.

## AP-01: Exec for operations with built-in tasks

**Smell:** shell `mkdir`, `copy`, or `del` commands in a target.

**Impact:** shell-specific syntax, weak file-level logging, and more difficult incremental
tracking. Built-in tasks integrate with MSBuild, but using one does not automatically make the
containing target incremental.

```xml
<!-- BAD: shell-dependent file operations. -->
<Target Name="PrepareOutput">
  <Exec Command="mkdir $(OutputPath)logs" />
  <Exec Command="copy config.json $(OutputPath)" />
  <Exec Command="del $(IntermediateOutputPath)*.tmp" />
</Target>

<!-- GOOD: preserve the intended operation with built-in tasks. -->
<Target Name="PrepareOutput">
  <MakeDir Directories="$(OutputPath)logs" />
  <Copy SourceFiles="config.json" DestinationFolder="$(OutputPath)" />
  <ItemGroup>
    <TempFiles Include="$(IntermediateOutputPath)*.tmp" />
  </ItemGroup>
  <Delete Files="@(TempFiles)" />
</Target>
```

| Shell operation | MSBuild task |
| --- | --- |
| `mkdir` | `MakeDir` |
| `copy` / `cp` / recursive copy | `Copy`, with the intended item set |
| `del` / `rm` | `Delete`, scoped to known owned files |
| `move` / `mv` | `Move` |
| Write text | `WriteLinesToFile` |
| Update a timestamp | `Touch` |

Keep real external tools as tools, with correct quoting, platform support, and error handling.
Preserve copy/reset semantics and never widen the deletion scope during this conversion.

## AP-02: Unquoted string comparisons

**Smell:** `Condition="$(Foo) == Bar"`.

**Impact:** empty values or values containing spaces/special characters can change parsing.

```xml
<!-- BAD -->
<PropertyGroup Condition="$(Configuration) == Release">
  <Optimize>true</Optimize>
</PropertyGroup>

<!-- GOOD -->
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
  <Optimize>true</Optimize>
</PropertyGroup>
```

Quote both string operands. Do not flag valid boolean/function conditions merely because they
are not string comparisons.

## AP-03: Hardcoded absolute paths

**Smell:** machine-specific tool or import paths.

**Impact:** builds fail on another checkout, machine, or operating system.

```xml
<!-- BAD -->
<PropertyGroup>
  <ToolPath>C:\tools\mytool\mytool.exe</ToolPath>
</PropertyGroup>
<Import Project="C:\repos\shared\common.props" />

<!-- GOOD: RepoRoot must be defined by the repository. -->
<PropertyGroup>
  <ToolPath>$(MSBuildThisFileDirectory)tools\mytool\mytool.exe</ToolPath>
</PropertyGroup>
<Import Project="$(RepoRoot)eng\common.props" />
```

| Property/function | Meaning |
| --- | --- |
| `MSBuildThisFileDirectory` | Directory of the file defining the current import/logic |
| `MSBuildProjectDirectory` | Directory of the project being built |
| `GetDirectoryNameOfFileAbove` / `GetPathOfFileAbove` | Find a repository marker or parent file |
| `NormalizePath` / `NormalizeDirectory` | Combine and normalize path segments |

Resolve relative paths against the intended owner, not an incidental caller working directory.

## AP-04: Restating SDK defaults

**Smell:** properties repeat the selected SDK's defaults.

**Impact:** noise can obscure real overrides and accidentally pin behavior across SDK changes.

```xml
<!-- Potentially redundant for a library named MyLib with these SDK defaults. -->
<PropertyGroup>
  <OutputType>Library</OutputType>
  <EnableDefaultItems>true</EnableDefaultItems>
  <EnableDefaultCompileItems>true</EnableDefaultCompileItems>
  <RootNamespace>MyLib</RootNamespace>
  <AssemblyName>MyLib</AssemblyName>
  <AppendTargetFrameworkToOutputPath>true</AppendTargetFrameworkToOutputPath>
</PropertyGroup>

<!-- Keep the settings that actually express the project's contract. -->
<PropertyGroup>
  <TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
```

Verify the actual SDK/imports, configurations, naming, and intentional pins first. A setting that
matches today's default can still deliberately preserve behavior; do not remove it blindly.

## AP-05: Redundant file lists in SDK-style projects

**Smell:** explicit C#/VB source includes duplicate enabled SDK default items.

**Impact:** duplicate items, merge noise, and source additions that can be missed when defaults
have instead been disabled.

```xml
<!-- BAD when default Compile items already contain these files. -->
<ItemGroup>
  <Compile Include="Program.cs" />
  <Compile Include="Services\MyService.cs" />
</ItemGroup>

<!-- GOOD: keep only intentional exclusions or metadata. -->
<ItemGroup>
  <Compile Remove="LegacyCode\**" />
  <Compile Update="Services\MyService.cs" Visible="false" />
</ItemGroup>
```

**Exceptions:** legacy projects, projects with default items intentionally disabled, linked files
outside default globs, generated files, and items with special metadata need their actual contract
preserved. `Update` modifies an existing item; it does not add a missing one.

**F# is order-dependent.** Keep explicit `.fsproj` compile items in dependency order. An `.fsi`
signature must immediately precede its matching `.fs`; the entry point is last. Do not apply C#
implicit-glob cleanup to F#.

The standard F# SDK already disables default compile items. Do not prescribe
`EnableDefaultCompileItems=false` as a required repair without evidence that the selected
SDK/imports actually enable unwanted defaults.

## AP-06: Package DLL HintPaths instead of package references

**Smell:** package assemblies referenced through a legacy `packages` directory.

**Impact:** the project depends on a fixed restored layout instead of PackageReference asset
selection. This is a migration candidate, not proof that existing packages.config restore is broken.

```xml
<!-- Legacy package reference. -->
<Reference Include="Newtonsoft.Json">
  <HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\netstandard2.0\Newtonsoft.Json.dll</HintPath>
</Reference>

<!-- PackageReference replacement, when migration is authorized and compatible. -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
```

Preserve package versions, conditions, content/build assets, and restore behavior. Do not remove
GAC, local, or vendor assembly references just because they use `Reference` or `HintPath`.

## AP-07: Build-only packages exposed to consumers

**Smell:** a local analyzer/tool becomes an unwanted dependency or build asset of consumers.

**Impact:** consumers can receive implementation-only dependencies or transitive build behavior.
Inspect effective metadata and package assets; absence of a literal `PrivateAssets` attribute
does not prove all analyzer assets propagate.

Use `PrivateAssets="all"` for dependencies intended to remain entirely private. Preserve
intentionally public/transitive build contracts. See
[private-assets.md](antipatterns/private-assets.md) for examples and exceptions.

## AP-08: Copy-pasted shared properties

**Smell:** the same property block is repeated across several projects.

**Impact:** inconsistent updates and unclear ownership.

```xml
<!-- Directory.Build.props at the intended shared scope. -->
<Project>
  <PropertyGroup>
    <Nullable>enable</Nullable>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>
```

Move only genuinely shared values. Preserve project overrides and property evaluation timing.
Only the nearest Directory.Build file is automatically discovered; see
[extension-points](extension-points.md#directorybuild-discovery) before changing hierarchy.

## AP-09: Unintended package-version drift

**Smell:** projects unintentionally use different versions of the same package.

**Impact:** divergent behavior, conflicts, and difficult dependency maintenance.

```xml
<!-- ProjectA.csproj -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<!-- ProjectB.csproj -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
```

Central Package Management can consolidate versions when that migration is requested; see
[the NuGet guidance](https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management).
Keep intentional framework/project differences. Do not silently upgrade packages or centralize
the whole repository while fixing an unrelated build.

## AP-10: Monolithic targets

**Smell:** one target mixes generation, copying, signing, and other unrelated operations.

**Impact:** the steps cannot be scheduled, diagnosed, or skipped independently.

```xml
<!-- BAD: unrelated work in one target. -->
<Target Name="PrepareRelease" BeforeTargets="Build">
  <WriteLinesToFile File="version.txt" Lines="$(Version)" Overwrite="true" />
  <Copy SourceFiles="LICENSE" DestinationFolder="$(OutputPath)" />
  <Exec Command="signtool sign /f cert.pfx $(OutputPath)*.dll" />
</Target>

<!-- GOOD: separate responsibilities with their own contracts. -->
<Target Name="WriteVersionFile" BeforeTargets="CoreCompile">
  <MakeDir Directories="$(IntermediateOutputPath)" />
  <WriteLinesToFile File="$(IntermediateOutputPath)version.txt"
                    Lines="$(Version)" Overwrite="true" WriteOnlyWhenDifferent="true" />
  <ItemGroup>
    <FileWrites Include="$(IntermediateOutputPath)version.txt" />
  </ItemGroup>
</Target>
<Target Name="CopyLicense" AfterTargets="CopyFilesToOutputDirectory">
  <Copy SourceFiles="LICENSE" DestinationFolder="$(OutputPath)" SkipUnchangedFiles="true">
    <Output TaskParameter="CopiedFiles" ItemName="FileWrites" />
  </Copy>
</Target>
<Target Name="SignAssemblies" AfterTargets="Build" DependsOnTargets="CopyLicense"
        Condition="'$(SignAssemblies)' == 'true'">
  <ItemGroup>
    <AssemblyFiles Include="$(OutputPath)*.dll" />
  </ItemGroup>
  <Error Condition="'@(AssemblyFiles)' == ''"
         Text="Signing was requested, but no assemblies were found in '$(OutputPath)'." />
  <Exec Command="signtool sign /f cert.pfx &quot;%(AssemblyFiles.Identity)&quot;" />
</Target>
```

The cheap version writer intentionally checks the value each build: `Version` can change through
global properties without any project-file timestamp changing. A project-file-only `Inputs`
declaration would incorrectly reuse stale content. For expensive generation, model value changes
with a stable input fingerprint as in [AP-11's example](antipatterns/incremental-build-inputs-outputs.md).

Preserve original target order, supported platforms, required tools, and copy semantics.
`SkipUnchangedFiles` is appropriate only when its timestamp/size heuristic satisfies the contract.
Register the copied destinations in `FileWrites` before MSBuild records them for a subsequent
`Clean`. Hooking `CopyLicense` after `CopyFilesToOutputDirectory` does this even for unchanged
copies; registering them in an `AfterTargets="Build"` target would be too late.
Discover the assemblies inside the signing target, after the build has produced them, rather
than with an evaluation-time glob. This retains the original output-directory DLL selection.

## AP-11: Untracked artifact-producing targets

**Smell:** expensive file generation runs on every no-change build because its inputs/outputs are
not modeled, or skips despite a relevant change.

**Impact:** repeated work or stale outputs. Inputs must cover actual files and relevant property,
configuration, generator, and import changes.

See [incremental-build-inputs-outputs.md](antipatterns/incremental-build-inputs-outputs.md) for a
correctness-oriented example, and [incremental-build](incremental-build.md) for full diagnosis.
Cheap validation, orchestration, and item-discovery targets may legitimately run without
file-based outputs; do not invent a stamp to suppress necessary work.

## AP-12: Defaults defined after their consumers

**Smell:** a default is set in a late import after another file already used it.

**Impact:** consumers observe an empty or unintended earlier value.

```xml
<!-- custom.props: an early, overridable default. -->
<PropertyGroup>
  <MyToolVersion Condition="'$(MyToolVersion)' == ''">2.0</MyToolVersion>
</PropertyGroup>

<!-- custom.targets: execution using that setting. -->
<Target Name="RunMyTool">
  <Exec Command="mytool --version $(MyToolVersion)" />
</Target>
```

`.props` normally carries early defaults; `.targets` normally carries later build logic.
Timing matters more than the suffix: a value depending on a project-defined property must not
move earlier than that property exists. See AP-21 in
[additional anti-patterns](antipatterns/additional-antipatterns.md).

## AP-13: Missing guards on optional imports

**Smell:** an optional developer/environment override is imported unconditionally.

**Impact:** a fresh checkout fails because a file that is optional by contract is absent.

```xml
<!-- Guard an optional override. -->
<Import Project="$(RepoRoot)eng\local.props"
        Condition="Exists('$(RepoRoot)eng\local.props')" />
```

**Required imports must fail when missing.** Do not add an existence guard to hide a missing SDK,
required build file, or broken package contract.

**NuGet forwarders need a packed-layout check.** Files in `build`/`buildTransitive` can import
paths that do not exist in source but are created by `.nuspec` mappings, `PackagePath` metadata,
or SDK pack conventions. First inspect the effective `NuspecFile`, `NuspecBasePath`, and
`NuspecProperties`, including imports and global-property overrides. Follow the configured
nuspec even outside the project tree and resolve its mappings with those settings. Only when
no custom nuspec is configured, inspect nearby `.nuspec` files in the project and its immediate
parent as a bounded fallback. Inspect the project's packaging items too; do not search unrelated
ancestors or treat an unavailable configured nuspec as proof of a broken import.

Only flag the target if it is absent from both applicable source and projected package layouts.
See [source tree vs packed layout](extension-points.md#source-tree-vs-packed-layout).
For per-TFM forwarders, derive the matched folder from the file's own location rather than the
consumer's `TargetFramework`; see the [forwarding chain](extension-points.md#forwarding-chain).

## AP-14: Backslashes where path normalization does not apply

**Smell:** Windows separators in a path intended to reach a non-MSBuild consumer on another OS.

**Correctness issue:** raw shell strings, generated source/response files, or custom tasks that
use OS APIs directly may interpret backslashes differently.

**Not automatically a correctness issue:** `Import` paths, item globs, and file paths consumed by
built-in tasks use MSBuild path handling. An ordinary backslash-style import is not, by itself,
a Linux failure.

```xml
<!-- A raw Windows shell/tool path needs actual platform support and quoting. -->
<Exec Command="$(MSBuildThisFileDirectory)tools\release\sign.exe $(OutputPath)" />

<!-- MSBuild handles this import path. Do not report a defect solely for its separators. -->
<Import Project="$(MSBuildThisFileDirectory)..\..\build\common.props" />
```

Trace the consumer before assigning severity. `MSBuildThisFileDirectory` already ends with a
separator; use path functions when constructing paths rather than concatenating arbitrary strings.

## AP-15: Unexpected property overrides across scopes

**Smell:** a shared value is unexpectedly replaced by another unconditional assignment.

**Impact:** last-write behavior is difficult to explain and can alter output paths or options.

```xml
<!-- Directory.Build.props: a default that permits an existing value. -->
<PropertyGroup>
  <OutputPath Condition="'$(OutputPath)' == ''">bin\custom\</OutputPath>
</PropertyGroup>
```

Trace assignments and consumers first. A project overriding a repository default can be
intentional, and command-line global properties have different override semantics. Do not add
conditions everywhere or change path-defining properties too late for their SDK/NuGet consumers.

For AP-16 through AP-23 and the quick-reference checklist, read
[additional-antipatterns.md](antipatterns/additional-antipatterns.md).

License (MIT)

View full license text
The MIT License (MIT)

Copyright (c) .NET Foundation and Contributors

All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.