Skip to content

Latest commit

 

History

History
336 lines (280 loc) · 21.3 KB

AGENTS.md

File metadata and controls

336 lines (280 loc) · 21.3 KB

CLI Agent Instructions

Guidance for changes under src/Cli.

SDK process entry points

SDK-owned CLI code has three process entry points of equal importance:

Entry point Source Host and lifecycle
Managed CLI dotnet/Program.cs CoreCLR calls Program.Main. The process ends after the command completes.
Native AOT CLI dotnet-aot/NativeEntryPoint.cs The native host calls the exported dotnet_execute. Unsupported operations can continue in the managed CLI.
MSBuild logger dotnet/Commands/MSBuild/MSBuildLogger.cs MSBuild loads the SDK assembly as an INodeLogger. MSBuildForwardingApp adds the -distributedlogger argument. The logger can run in the CLI process, a child process, or a persistent server.

Treat the logger as an independent entry point. Do not assume that it runs after managed Program.Main or the Native AOT bootstrap. Initialize process-wide telemetry and tracing when MSBuild loads the logger directly. Start request-specific state at BuildStarted, record the result at BuildFinished, and keep the activity open until Shutdown because MSBuild emits final telemetry after BuildFinished. Shutdown completes one logger instance. It does not necessarily end the process. Refresh the environment and trace context for each persistent-server request.

Managed and Native AOT command execution use Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs as the shared owner of Ctrl+C, SIGTERM, and process-exit cancellation. The managed entry point initializes it for the process lifetime; the Native AOT entry point initializes it only while handling a command in-process and unregisters it before managed fallback. Merely launching a child through ProcessReaper.cs must not initialize CLI lifecycle handling in library hosts.

Pass the lifecycle token through System.CommandLine invocation and command operations. Process-launch and forwarding helpers must require callers to supply a cancellation token; do not add tokenless overloads or optional cancellation-token parameters. The first Ctrl+C requests cooperative cancellation and permits 200 milliseconds for cleanup; expiration of that deadline requests forceful cancellation, gives observers a bounded window to terminate and reap child processes, and then exits with the signal-derived exit code. A second Ctrl+C or SIGTERM exits immediately. Transaction rollback and other critical operations may use OverrideSoftCancellationTimeout to extend or suspend the automatic deadline, but the override must never suppress an explicit forceful signal. Child processes observe cooperative signals directly and are killed only when forceful cancellation is requested. While a lifecycle-managed external process is running, Command suspends the automatic soft-cancellation deadline so the child can finish gracefully; a second Ctrl+C or SIGTERM still forces termination. System.CommandLine may wrap the lifecycle token before it reaches a command action, so process termination must use lifecycle initialization state rather than token identity to distinguish lifecycle cancellation from standalone library callers. On Unix, forward SIGTERM to the child before bounded forceful termination. ProcessReaper.cs owns child-process signal forwarding and cleanup; do not add a competing command-line termination handler for those signals. MSBuild operations use a two-second soft-cancellation override so submissions and loggers, including binary loggers, can finish cancellation cleanup; a second Ctrl+C or SIGTERM still bypasses it.

Cancellation and cleanup

Forward-operation cancellation must not prevent transaction rollback. MSI manifest and pack rollback create a distinct cancellation scope inside each rollback callback, never linked to the cancelled forward token; keep the original cancellation exception after cleanup. The deterministic installer seams are exercised by GivenMsiCancellation. Only roll back MSIs whose installation this transaction actually attempted; mark the attempt before native execution so partial installs still roll back, but cancellation before installation and already-installed no-ops cannot remove existing manifests.

Console.In synchronizes ReadLineAsync as well as ReadLine. The run-api command uses Console.OpenStandardInputHandle() with FileStream/StreamReader instead. Keep the cancellable wait: Unix file I/O cannot interrupt an already blocked read, so at most one runtime worker can remain until process exit. Keep its regression out of process with a real open stdin pipe; see RunApiCancellationTests. On Linux, its helper waits for /proc/self/task/*/syscall to report a blocked read(0, ...) before cancelling; an incomplete task alone does not establish that the runtime worker has started the read.

Three-project command split

A dotnet command or option spans three cooperating projects:

  • Microsoft.DotNet.Cli.Definitions — the AOT-safe command tree. Shared option factories live in Common/CommonOptions.cs.
  • src/Cli/dotnet — the managed implementation: handlers, validation, MSBuild/NuGet integration, runtime messages.
  • src/Cli/dotnet-aot + src/Cli/dn — the NativeAOT bridge (see src/Cli/dotnet-aot/DESIGN.md).

The same definition tree is parsed by both the managed and AOT hosts, so parser/option/description changes flow to AOT and --help automatically. Keep heavy deps out of Definitions. In the managed CLI, code that isn't AOT-safe is excluded from the AOT build with #if !CLI_AOT (the AOT project links files from dotnet and compiles with CLI_AOT defined).

MSBuildRuntimeReference.targets supplies the packaged MSBuild command-line assembly to dotnet and Microsoft.DotNet.Cli.Utils. Internal parser APIs are accessible to the signed dotnet assembly through MSBuild's InternalsVisibleTo; keep those calls managed-only rather than introducing MSBuild dependencies into Definitions.

CLI-owned path options (such as --output, --artifacts-path, --packages, and VSTest --settings) keep their default, unescaped forwarding in the definitions for consumers such as dotnet-watch. The managed command parsers replace it through MSBuildOptionExtensions, which uses MSBuildPropertyEscaping to escape literal paths with MSBuild's API before adding command-line quotes. When adding a path option, forward it with ForwardAsPathProperty/ForwardAsOutputPath in the definition and wire the ForwardAsLiteral* override in the managed parser. Keep explicit -p: values on their existing MSBuild-syntax path; they are not literals.

When changing AOT-linked commands, resources, dependencies, or first-run behavior, follow the size and trimming contracts.

Where things live

src/Cli is a set of projects, not one app. The three above carry commands; the rest are supporting libraries:

Project Role
dotnet Primary managed executable — every command's handler lives here under Commands/.
Microsoft.DotNet.Cli.Definitions AOT-safe command tree (parsed by both hosts).
Microsoft.DotNet.Cli.InternalMicrosoft AOT-safe Microsoft-internal classification, probes, and cache. It does not emit telemetry.
dotnet-aot + dn NativeAOT shared library + native host exe.
Microsoft.DotNet.Cli.Utils MSBuild/NuGet/process/system abstractions used across the CLI.
Microsoft.DotNet.Cli.CoreUtils Low-level version/file/env-variable parsing and the shared string-resource runtime used by generated CLI accessors.
Microsoft.DotNet.Cli.Resources.Generator Analyzer-only RESX generator; emits cached accessors against the CoreUtils resource runtime.
Microsoft.DotNet.Cli.CommandLine Local extensions over System.CommandLine.
Microsoft.DotNet.Configurer First-run experience and NuGet/config setup.
Microsoft.DotNet.InternalAbstractions File-system/env abstractions for testability.
Microsoft.DotNet.FileBasedPrograms Support for file-based programs.
Microsoft.TemplateEngine.Cli dotnet new integration layer.

Inside src/Cli/dotnet

  • Program.cs / Parser.cs — entry point and parser construction.
  • Commands/ — one folder per command (Build, Restore, New, Tool, Workload, …), plus CliCommandStrings.resx and xlf/.
  • CommandFactory/ — command resolution strategies.
  • BuildServer/ — MSBuild / VBCSCompiler / Razor build-server providers.
  • ToolPackage/, ToolManifest/, ShellShim/, NugetPackageDownloader/, NugetSearch/ — dotnet tool install/run plumbing.

Inside Microsoft.DotNet.Cli.Definitions

  • Commands/ — one definition class per command; DotNetCommandDefinition.cs is the registry that imports them all.
  • Common/ — shared option/argument factories.
  • Help/ — help builder and localization.

String resources

CLI resource owners select Generator="Microsoft.DotNet.Cli.Resources" and reference the analyzer-only Microsoft.DotNet.Cli.Resources.Generator project. The generated accessors use the runtime under Microsoft.DotNet.Cli.CoreUtils/Resources; do not add another runtime assembly or a package/buildTransitive dependency. Current-SDK builds use the CLI generator, while multi-targeted owners retain the existing Microsoft generator for .NET Framework targets.

Per-command services

CommandServices holds immutable service dependencies. CommandBase retains them per instance. Build-family factories require callers to provide services explicitly; pass the same instance to subordinate commands, as RestoringCommand does for separate restore. CLI entry points that do not receive services create the production defaults explicitly.

For in-process LLM tests, inject a detector through these services rather than changing the process environment or adding ambient overrides. Keep command-path tests entering through the real factory; see GivenCommandServices. Test the detector's environment-variable mapping separately with an IEnvironmentProvider. For subprocess tests, set environment variables on the child process instead.

Verify (approval) snapshot tests

Many CLI tests use Verify ([UsesVerify] / VerifyMSTest):

  • The expected output is checked in as <Test>.<Method>[.<OS>].verified.txt.
  • On mismatch the runner writes a git-ignored *.received.txt. Never commit *.received.txt.
  • When you intentionally change CLI output, promote the new *.received.txt over the matching *.verified.txt.
  • Volatile lines (paths, timings, versions) are scrubbed via settings.ScrubLinesContaining(...) — scrub rather than hard-code them.

MTP build preparation

MSBuildSession owns the single-node build and project collection for targets MTP invokes directly: restore, device discovery, deployment and run-argument computation. Honor explicit -mt / -multiThreaded values using MSBuild's precedence and environment defaults, without adding automatic response-file discovery.

A strict MT session owns the process current directory until it ends; do not restore that directory between MT requests. MSBuildUtility runs intervening builds and restores out-of-process through RestoringCommand, using the captured invocation directory so relative arguments and logs retain their meaning. Keep one coherent preparation binlog, target-produced project state, and the session's success/failure cleanup. Cover these boundaries in GivenDotnetTestProducesBinaryLog.

In --solution runs, device selection applies only to MTP test applications (IsTestingPlatformApplication); IsTestProject is a VSTest concept and must not opt a project in. App and library projects, such as MAUI heads, can import ComputeAvailableDevices in their inner builds and must not prompt for a device. The single-project path evaluates before restore, so it must not apply this NuGet-dependent gate.

Parent-process operations must also use the captured invocation directory: pass it through background workload updates to both global.json discovery and NuGet configuration, and initialize absolute MTP trace paths before starting the session. Changing only a child process's directory is insufficient.

MTP process completion

TestApplicationHandler distinguishes TestHost completion from orchestrator-only completion. An exit-0 RefreshMappingsOrchestrator in collection mode or RunAffectedTestsOrchestrator in affected-run mode can finish without a TestHost; legacy collection can omit handshakes entirely. Missing/unknown capabilities, controller-only or mixed partial handshakes, and explicit handshake rejections must not gain that exemption. Rejection and partial-handshake state must survive later accepted handshakes. Keep these boundaries covered by TestApplicationHandlerTests.

TerminalTestReporter renders a neutral no-selection status for a successful affected-run orchestrator that never starts a TestHost, without inventing skipped tests. Run summaries use the final aggregate exit code from MicrosoftTestingPlatformTestCommand, including session failures and ignored-exit policies, instead of upstream's in-process failure callback. A successful run with zero tests uses neutral "Zero tests ran" wording, not a green "Passed!" verdict.

MTP module identity

Keep the assembly target framework separate from its executing runtime. TestApplicationHandler prefers the evaluated project's TargetFramework, then optional handshake TargetFramework metadata (field 21). Missing target metadata stays unknown; never infer it from the runtime or output directory. Project metadata takes precedence; when it is absent, a first test-host TFM can refine a provisional orchestrator TFM before retries begin. Handshake Framework (field 2) remains runtime information, and Architecture identifies the executing process, not the assembly's AnyCPU setting.

The SDK advertises TestInProgressSupported=true (field 22) on accepted handshake replies: its serializer and handler support those messages even with protocol 1.0. Test hosts must not send them when this optional capability is absent or false, because older 1.0 SDKs cannot decode them. Older hosts that do not send progress retain module-only heartbeat.

For parallel Azure Pipelines runs, the SDK associates each host's ordinary output with its module while preserving workflow-command lines verbatim. Keep same-name modules with the same target distinguishable without changing their artifact identities. The SDK asks compatible hosts to disable live Azure DevOps groups; older hosts may still emit overlapping groups. After the bounded stream drain, contextual forwarding closes before the final summary and warns if output may have been truncated. See TestApplication and TestApplicationHandler.

The shared TestFrameworkDisplay keeps matching runs compact (net481|x64) and labels a differing runtime separately (net472|x64, runtime: net481). Ignore modern .NET servicing patches and target platform suffixes only for comparison; preserve the full target in output and distinguish net48 from net481. Unknown targets use an explicit runtime annotation, not a runtime-derived target. Keep start, results, completion, recaps and progress consistent, and omit secondary runtime information before primary identity in narrow cursor frames.

ArtifactPostProcessingManager can learn capabilities from a controller before the target is known. Fill only a missing target when later handshake metadata arrives, even if capabilities are not repeated; preserve an already known target.

MTP coverage summaries

Keep coverage scoped by execution, instance, session, and producer. Never add counts or percentages across test applications: they can cover the same assembly. The coverage reporter reserves Total for a single source or an accepted, complete merged artifact with explicit input provenance. Failed, partial, unsupported, or cancelled processing must not fabricate a run total.

Track complete execution/instance/session tuples and balanced starts/ends; matching separate identity sets or input-file counts is insufficient. Preserve source origins independently of artifact-list replacement, reject ambiguous path reuse, and invalidate previous coverage metadata when a processed output path is replaced.

Unresolved measurement origins and selected applications that fail to launch also make coverage incomplete, even when their exit codes are ignored. The application queue must preserve that state when an exception prevents the normal handshake/session completion path.

Controller coverage can arrive after TestSessionEnd; accept it until process completion. Negotiate coverage-summary support independently of the base protocol, without enabling the unimplemented 1.4 server-control channel. Keep producer, wire, artifact-acceptance, and managed/Native AOT behavior aligned. See the coverage contract and output format.

MTP collection and diagnostics

Collection has a separate parent lifecycle: its bounded progress counts completed module attempts, and its final status follows the existing aggregate exit code without synthesizing test outcomes from discovery or mapping counts. Keep collection progress independent of TestHost handshakes, since suppression is intentional. Interrupted sessions label live counts as incomplete; never add recovered TRX counts to those live results.

Artifact workers inherit only configuration and diagnostic options from the elected application, including response-file and launch-profile sources. Preserve --diagnostic with its directory, verbosity, prefix, and synchronous-write settings; do not weaken MTP validation or forward test-selection/retry/timeout arguments. Reporting degradation remains separate from the test verdict, with original artifacts retained.

Required artifact processing is a per-invocation promise: advertise field 19 only when the SDK will honor field 18 singleton jobs and provide an authoritative, policy-aware runSummary. Preserve per-module fallback for opt-out, help/discovery/collection, and unsupported transports. Snapshot logical live counts after final test policies, before workers run; keep selected modules without fragments in the denominator. Preserve the handshake's producing-module identity separately from an apphost launch path, and never use a running framework as proof of the artifact's target framework. See the contract decision and real-worker regressions. Join worker reporting before applying outputs; a legal null result or a worker failure does not change test policy. Bound worker cancellation without expanding general test-host cancellation plumbing.

The vendored non-cursor renderer measures visible-output silence, not silence between test completions. Its totals include completed modules after their worker slots are freed. Captured per-test stdout and stderr default to failed-only output independently of result visibility. Resolve explicit stream modes from each module's effective arguments and configuration, not just the parent command line; raw test-host process output is unaffected. The SDK owns these rendered defaults, so its dynamic platform-option help must describe them even when older test applications supply different defaults in their help metadata. See MicrosoftTestingPlatformTestCommand and its help renderer. Resolve parent progress from every selected module's effective arguments and working directory; any effective opt-out disables the shared heartbeat and slow-test display. Collection status must not override discovery formatting. Keep optional timer and warning writes exception-safe, without recounting an operation when its warning cannot be written. Keep SDK final-exit-code authority when reconciling upstream terminal code, and update eng/vendored-files.json with exact upstream blob identities.