File: Agents\AgentInstructionsFile.cs
Web Access
Project: src\src\Aspire.Cli\Aspire.Cli.csproj (aspire)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using System.Globalization;
using System.Text;
using System.Text.Json;
using Aspire.Cli.Configuration;
using Aspire.Cli.Interaction;
using Aspire.Cli.Projects;
using Aspire.Cli.Resources;
using Aspire.Cli.Utils;
using Aspire.Hosting.Utils;
using Spectre.Console;
 
namespace Aspire.Cli.Agents;
 
/// <summary>
/// How <see cref="AgentInstructionsFile.WriteAsync"/> changed the agent instructions file.
/// </summary>
internal enum AgentInstructionsFileChange
{
    Created,
    Appended,
    Updated,
    Unchanged,
 
    /// <summary>
    /// The file has a start marker without a matching, closed end marker, so the extent of the
    /// Aspire section is unknown and the file is left untouched.
    /// </summary>
    SkippedMalformedSection,
 
    /// <summary>
    /// The file is a symbolic link to a file outside the directory, which other repositories can share,
    /// so it is left untouched rather than given this AppHost's start flow.
    /// </summary>
    SkippedExternalLinkTarget,
 
    /// <summary>
    /// The file is neither UTF-8 nor UTF-16 or UTF-32 with a byte order mark, so it can't be rewritten without
    /// losing text and is left untouched. Text holding a NUL character, such as UTF-16 saved without a byte
    /// order mark, counts as an unrecognized encoding.
    /// </summary>
    SkippedUnsupportedEncoding,
 
    /// <summary>
    /// The file's markers follow a code fence that is never closed, so they may belong to an example rather than
    /// the Aspire section, and replacing the text between them could delete the user's text. The file is left
    /// untouched unless the section there is already up to date.
    /// </summary>
    SkippedUnclosedCodeFence
}
 
/// <summary>
/// Writes the Aspire section of the <c>AGENTS.md</c> file that <c>aspire new</c> and
/// <c>aspire agent init</c> place beside the <c>aspire.config.json</c> of an Aspire application.
/// </summary>
/// <remarks>
/// <para>
/// Coding agents read <c>AGENTS.md</c> on every turn without any plugin, skill or MCP setup
/// (https://agents.md). The section gives the start flow for this AppHost in order: start it, list
/// its resources with <c>aspire describe</c>, then <c>aspire wait</c> on the ones the task needs.
/// It deliberately names no individual skills: they are delivered through the Aspire skills plugin, whose installed
/// version can differ from any list written here, and the agent harness already lists the skills it loaded.
/// </para>
/// <para>
/// An existing file is never overwritten. The Aspire section is delimited by HTML comment markers, which
/// markdown renderers hide, each at the start of its own line. When the file has no section, one is appended
/// after the existing content; when it has one, only the text between the markers is replaced, so a later
/// <c>aspire agent init</c> can add its plugin note to the section <c>aspire new</c> wrote.
/// </para>
/// </remarks>
internal static class AgentInstructionsFile
{
    internal const string FileName = "AGENTS.md";
 
    // Matching uses only the marker prefixes, followed by a token boundary (see FindMarker), so the
    // explanatory text after them can change without orphaning sections written by earlier CLIs.
    internal const string SectionStartMarkerPrefix = "<!-- aspire:begin";
    internal const string SectionEndMarkerPrefix = "<!-- aspire:end";
 
    private const string SectionStartMarker = SectionStartMarkerPrefix +
        " (generated by the Aspire CLI; `aspire new` and `aspire agent init` replace the text up to aspire:end) -->";
    private const string SectionEndMarker = SectionEndMarkerPrefix + " -->";
    private const string CommentStart = "<!--";
    private const string CommentEnd = "-->";
 
    /// <summary>
    /// Reads the AppHost path that the <c>aspire.config.json</c> in <paramref name="directory"/> configures.
    /// </summary>
    /// <returns>The full AppHost path, or <see langword="null"/> when no AppHost is configured or the file can't be read.</returns>
    internal static string? GetConfiguredAppHostPath(DirectoryInfo directory)
    {
        try
        {
            if (AspireConfigFile.Load(directory.FullName)?.AppHost?.Path is { Length: > 0 } path)
            {
                // Stored paths use '/' separators on every platform and are relative to the config file.
                return PathNormalizer.NormalizePathForCurrentPlatform(Path.Combine(directory.FullName, path));
            }
        }
        catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or ArgumentException)
        {
            // ArgumentException covers a configured path with characters Path.GetFullPath rejects, such as
            // an escaped NUL ("\u0000"), which is valid JSON. An unreadable config file or unusable path only
            // means the start flow can't be described; template creation and agent setup report the config
            // problem themselves when they need the file.
        }
 
        return null;
    }
 
    /// <summary>
    /// Finds the AppHost in <paramref name="directory"/> when the directory holds exactly one.
    /// </summary>
    /// <returns>The full AppHost path, or <see langword="null"/> when the directory holds none or several.</returns>
    /// <remarks>
    /// This covers apps created from custom templates, which can produce an AppHost without the
    /// <c>aspire.config.json</c> that names it. The start flow is optional, so several AppHosts are not worth a
    /// selection prompt: the file is skipped as when there is none. Detection is static, without building the
    /// projects, and <see cref="AppHostDiscoveryScope.ExplicitDirectory"/> keeps the search inside the directory.
    /// </remarks>
    internal static async Task<string?> FindSingleAppHostPathAsync(IProjectLocator projectLocator, DirectoryInfo directory, CancellationToken cancellationToken)
    {
        // A template can succeed without creating its output directory, for example when it only adds files
        // elsewhere, and an unreadable subdirectory only means the start flow can't be described.
        if (!directory.Exists)
        {
            return null;
        }
 
        try
        {
            var candidates = await projectLocator.FindAppHostProjectFilesAsync(
                directory, AppHostDiscoveryScope.ExplicitDirectory, cancellationToken, skipValidation: true);
            return candidates is [var appHost] && IsInDirectory(appHost.FullName, directory) ? appHost.FullName : null;
        }
        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
        {
            return null;
        }
    }
 
    /// <summary>
    /// Creates the Aspire section, including its markers, without a trailing line break.
    /// </summary>
    /// <param name="appHostPath">The AppHost path relative to the directory of the instructions file.</param>
    /// <param name="aspireSkillsPluginRegistered">Whether <c>aspire agent init</c> registered the Aspire skills plugin.</param>
    /// <param name="newLine">The line break to use.</param>
    internal static string CreateSection(string appHostPath, bool aspireSkillsPluginRegistered, string newLine)
    {
        // Every command passes --apphost so it targets this app, rather than prompting or failing in a
        // non-interactive session, when other AppHosts are running.
        var appHostArgument = QuoteShellArgument(appHostPath);
        var start = CodeSpan($"aspire start --apphost {appHostArgument} --non-interactive --isolated");
        var describe = CodeSpan($"aspire describe --apphost {appHostArgument}");
        var wait = CodeSpan($"aspire wait <resource-name> --apphost {appHostArgument}");
        var logs = CodeSpan($"aspire logs <resource-name> --apphost {appHostArgument}");
        var traces = CodeSpan($"aspire otel traces -n 15 --search \"duration:>500\" --apphost {appHostArgument}");
        var builder = new StringBuilder();
        void Line(string text = "") => builder.Append(text).Append(newLine);
 
        Line(SectionStartMarker);
        Line("## Aspire");
        Line();
        Line($"This is an Aspire application. Its AppHost is {CodeSpan(appHostPath)}.");
        // The shell resolves --apphost against its working directory, while the path is relative to AGENTS.md
        // (kept relative so the committed file works in every clone), so agents are told where to run from.
        Line("That path is relative to the directory holding AGENTS.md, so run the commands below from there.");
        Line();
        Line("### Run it");
        Line($"1. Start it: {start}.");
        // Lines break right after the commands because their length depends on the AppHost path.
        Line($"2. {describe} lists every resource of the running app");
        Line("   with its state, health and endpoint URLs. That list names the resources to wait on.");
        Line($"3. {wait} for each resource the task needs,");
        Line("   with `<resource-name>` taken from that list. It returns when the resource is healthy.");
        Line();
        Line($"{logs} prints that resource's console output.");
        Line();
        Line("### When it is slow");
        Line($"Start with {traces}");
        Line("(milliseconds; lower the threshold if nothing comes back), before reading code or timing requests by hand.");
 
        if (aspireSkillsPluginRegistered)
        {
            Line();
            // The plugin can be installed or removed later without touching this file, so the note says what
            // `aspire agent init` did and stays true whether or not the plugin is still installed.
            Line("`aspire agent init` registered the `microsoft/aspire-skills` plugin for Aspire skills; while it is installed, the harness lists them.");
        }
 
        builder.Append(SectionEndMarker);
        return builder.ToString();
    }
 
    /// <summary>
    /// Creates <c>AGENTS.md</c> in <paramref name="directory"/>, or adds or refreshes its Aspire section.
    /// </summary>
    /// <param name="directory">The directory that receives the file.</param>
    /// <param name="appHostPath">The full path of the AppHost the start flow targets.</param>
    /// <param name="aspireSkillsPluginRegistered">Whether <c>aspire agent init</c> registered the Aspire skills plugin.</param>
    /// <param name="cancellationToken">A cancellation token.</param>
    internal static async Task<AgentInstructionsFileChange> WriteAsync(
        DirectoryInfo directory,
        string appHostPath,
        bool aspireSkillsPluginRegistered,
        CancellationToken cancellationToken)
    {
        // Agents run the commands from the directory holding AGENTS.md, so the path is relative to it.
        // Forward slashes work in every shell the commands are pasted into.
        var relativeAppHostPath = PathNormalizer.NormalizePathForStorage(GetRelativeAppHostPath(directory.FullName, appHostPath));
        var filePath = Path.Combine(directory.FullName, FileName);
 
        // AGENTS.md is often a link to another agent's instructions file (AGENTS.md -> CLAUDE.md) so every
        // agent reads one file. Work on the link's final target so a dangling link gets its target created,
        // and the link kept, instead of failing to read through it. A target outside the directory can be
        // shared by several repositories, each of which would replace the others' AppHost commands, so only
        // links that stay inside the directory are followed.
        if (new FileInfo(filePath).LinkTarget is not null &&
            File.ResolveLinkTarget(filePath, returnFinalTarget: true) is { } linkTarget)
        {
            if (!IsInDirectory(linkTarget.FullName, directory))
            {
                return AgentInstructionsFileChange.SkippedExternalLinkTarget;
            }
 
            filePath = linkTarget.FullName;
        }
 
        if (!File.Exists(filePath))
        {
            var newLine = Environment.NewLine;
            var content = $"# Agent instructions{newLine}{newLine}{CreateSection(relativeAppHostPath, aspireSkillsPluginRegistered, newLine)}{newLine}";
            await CreateFileAsync(filePath, content, cancellationToken);
            return AgentInstructionsFileChange.Created;
        }
 
        if (await ReadTextAsync(filePath, cancellationToken) is not (var existing, var encoding))
        {
            return AgentInstructionsFileChange.SkippedUnsupportedEncoding;
        }
 
        var lineBreak = existing.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
        var section = CreateSection(relativeAppHostPath, aspireSkillsPluginRegistered, lineBreak);
 
        var fencedCodeBlocks = FindFencedCodeBlocks(existing, out var unclosedFenceStart);
        var start = FindMarker(existing, SectionStartMarkerPrefix, 0, fencedCodeBlocks);
        if (start < 0)
        {
            var separator = existing.Length == 0
                ? string.Empty
                : existing.EndsWith('\n') ? lineBreak : lineBreak + lineBreak;
            // The file holds the user's own instructions, so it is replaced atomically: a failed or
            // cancelled write must not leave it truncated.
            await ConfigurationHelper.WriteTextFileAtomicallyAsync(filePath, existing + separator + section + lineBreak, encoding, cancellationToken);
            return AgentInstructionsFileChange.Appended;
        }
 
        // Both markers must be closed comments. When either is unclosed, as in
        //   <!-- aspire:begin
        //   Keep this team rule.
        //   <!-- aspire:end -->
        // or
        //   <!-- aspire:end
        //   Keep this team rule.
        //   <!-- unrelated note -->
        // the next "-->" belongs to another comment, so treat the section as malformed rather
        // than deleting the user's text and that comment. The end marker is only searched for
        // after the begin marker's "-->".
        var startClose = FindCommentClose(existing, start, SectionStartMarkerPrefix);
        var endMarker = startClose < 0
            ? -1
            : FindMarker(existing, SectionEndMarkerPrefix, startClose + CommentEnd.Length, fencedCodeBlocks);
        var endMarkerClose = endMarker < 0
            ? -1
            : FindCommentClose(existing, endMarker, SectionEndMarkerPrefix);
 
        // A second begin marker before the end marker means the first one is not the start of this section,
        // for example an unterminated section above a complete one. Pairing the first begin marker with the
        // later end marker would delete the user's text between them, so the section is treated as malformed.
        if (endMarkerClose >= 0 &&
            FindMarker(existing, SectionStartMarkerPrefix, start + SectionStartMarkerPrefix.Length, fencedCodeBlocks) is >= 0 and var nextStart &&
            nextStart < endMarker)
        {
            endMarkerClose = -1;
        }
 
        // Markers after the opening of a code fence that is never closed are ambiguous. They can be the section
        // this CLI appended after that fence, or a team example such as
        //   ```markdown
        //   <!-- aspire:begin -->
        //   Team validation steps.
        //   <!-- aspire:end -->
        // that the missing closing fence keeps from being recognized. Replacing the text between them could delete
        // the example, so the file is only reported as unchanged when that text already is this section. The end
        // marker decides when there is one, so a pair that straddles the fence's opening line is ambiguous too.
        var followsUnclosedFence = unclosedFenceStart >= 0 && (endMarker >= 0 ? endMarker : start) > unclosedFenceStart;
 
        if (endMarkerClose < 0)
        {
            return followsUnclosedFence
                ? AgentInstructionsFileChange.SkippedUnclosedCodeFence
                : AgentInstructionsFileChange.SkippedMalformedSection;
        }
 
        // The section ends with the "-->" that closes the end marker; anything after it, including
        // text on the same line such as "<!-- aspire:end --> Keep this team rule.", is the user's.
        var end = endMarkerClose + CommentEnd.Length;
        var updated = string.Concat(existing.AsSpan(0, start), section, existing.AsSpan(end));
        if (string.Equals(updated, existing, StringComparison.Ordinal))
        {
            return AgentInstructionsFileChange.Unchanged;
        }
 
        if (followsUnclosedFence)
        {
            return AgentInstructionsFileChange.SkippedUnclosedCodeFence;
        }
 
        await ConfigurationHelper.WriteTextFileAtomicallyAsync(filePath, updated, encoding, cancellationToken);
        return AgentInstructionsFileChange.Updated;
    }
 
    /// <summary>
    /// Writes the file like <see cref="WriteAsync"/> and reports the change to the user.
    /// </summary>
    /// <returns><see langword="false"/> when the file could not be written.</returns>
    internal static async Task<bool> WriteAndReportAsync(
        IInteractionService interactionService,
        DirectoryInfo directory,
        string appHostPath,
        bool aspireSkillsPluginRegistered,
        CancellationToken cancellationToken)
    {
        var displayPath = Path.Combine(directory.FullName, FileName).EscapeMarkup();
        AgentInstructionsFileChange change;
        string? externalLinkTarget = null;
        try
        {
            change = await WriteAsync(directory, appHostPath, aspireSkillsPluginRegistered, cancellationToken);
            if (change is AgentInstructionsFileChange.SkippedExternalLinkTarget)
            {
                // WriteAsync followed the link to decide this, so it resolves again to name the target.
                externalLinkTarget = File.ResolveLinkTarget(Path.Combine(directory.FullName, FileName), returnFinalTarget: true)?.FullName;
            }
        }
        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
        {
            interactionService.DisplayError(string.Format(CultureInfo.CurrentCulture,
                SharedCommandStrings.AgentInstructionsFileWriteFailed, displayPath, ex.Message.EscapeMarkup()));
            return false;
        }
 
        // {1} is only used by the formats that name a second path or marker.
        var (emoji, format, detail) = change switch
        {
            AgentInstructionsFileChange.Created => (KnownEmojis.PageFacingUp, SharedCommandStrings.AgentInstructionsFileCreated, null),
            AgentInstructionsFileChange.Appended => (KnownEmojis.PageFacingUp, SharedCommandStrings.AgentInstructionsFileAppended, null),
            AgentInstructionsFileChange.Updated => (KnownEmojis.PageFacingUp, SharedCommandStrings.AgentInstructionsFileUpdated, null),
            AgentInstructionsFileChange.SkippedMalformedSection => (KnownEmojis.PoliceCarLight, SharedCommandStrings.AgentInstructionsFileSkippedMalformedSection, SectionEndMarker),
            AgentInstructionsFileChange.SkippedExternalLinkTarget => (KnownEmojis.PoliceCarLight, SharedCommandStrings.AgentInstructionsFileSkippedExternalLinkTarget, externalLinkTarget ?? string.Empty),
            AgentInstructionsFileChange.SkippedUnsupportedEncoding => (KnownEmojis.PoliceCarLight, SharedCommandStrings.AgentInstructionsFileSkippedUnsupportedEncoding, null),
            AgentInstructionsFileChange.SkippedUnclosedCodeFence => (KnownEmojis.PoliceCarLight, SharedCommandStrings.AgentInstructionsFileSkippedUnclosedCodeFence, null),
            _ => (default(KnownEmoji), (string?)null, (string?)null)
        };
 
        if (format is not null)
        {
            interactionService.DisplayMessage(emoji, string.Format(CultureInfo.CurrentCulture, format, displayPath, detail?.EscapeMarkup()));
        }
 
        return true;
    }
 
    /// <summary>
    /// Quotes <paramref name="value"/> so it stays one literal argument when an agent pastes the command
    /// into a POSIX shell (bash, zsh) on macOS or Linux, or into PowerShell on Windows.
    /// </summary>
    /// <remarks>
    /// <para>
    /// Single quotes keep every character literal in both POSIX shells
    /// (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_02_02) and PowerShell
    /// (https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_quoting_rules), so they
    /// are used for any value outside a conservative set of characters that neither shell treats specially.
    /// </para>
    /// <para>
    /// An apostrophe can't be escaped the same way in both shells inside single quotes: POSIX shells have no escape
    /// there and PowerShell doubles it. Such a value is double-quoted instead, which keeps it literal in both as long
    /// as it has none of the characters either shell expands inside double quotes. A value with an apostrophe and one
    /// of those characters gets POSIX quoting, the one form that remains, which PowerShell doesn't parse.
    /// PowerShell also accepts the typographic quotes U+2018-U+201B and U+201C-U+201E as quote characters.
    /// cmd.exe doesn't treat single quotes as quotes; agents on Windows run PowerShell.
    /// </para>
    /// </remarks>
    private static string QuoteShellArgument(string value)
    {
        if (value.Length > 0 && value.All(c => char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-' or '/' or '+' or ':' or '='))
        {
            return value;
        }
 
        if (value.IndexOfAny(['\'', '\u2018', '\u2019', '\u201A', '\u201B']) < 0)
        {
            return $"'{value}'";
        }
 
        // '!' is expanded inside double quotes by interactive bash and zsh history expansion.
        if (value.IndexOfAny(['$', '`', '"', '\\', '!', '\u201C', '\u201D', '\u201E']) < 0)
        {
            return $"\"{value}\"";
        }
 
        return $"'{value.Replace("'", "'\\''")}'";
    }
 
    /// <summary>
    /// Wraps <paramref name="text"/> in a Markdown code span.
    /// </summary>
    /// <remarks>
    /// A backtick in <paramref name="text"/> would end a single-backtick span early, so the span then uses a backtick
    /// fence longer than any run in the text, padded with a space that renderers strip
    /// (https://spec.commonmark.org/0.31.2/#code-spans).
    /// </remarks>
    private static string CodeSpan(string text)
    {
        var longestRun = 0;
        var run = 0;
        foreach (var c in text)
        {
            run = c == '`' ? run + 1 : 0;
            longestRun = Math.Max(longestRun, run);
        }
 
        if (longestRun == 0)
        {
            return $"`{text}`";
        }
 
        var fence = new string('`', longestRun + 1);
        return $"{fence} {text} {fence}";
    }
 
    /// <summary>
    /// Returns the AppHost path relative to <paramref name="directory"/>.
    /// </summary>
    /// <remarks>
    /// AppHost discovery returns paths with symbolic links resolved, while the directory can be given through a link,
    /// as with macOS temporary folders under <c>/var</c>, which links to <c>/private/var</c>. Relating the two
    /// lexically then climbs out through the link, as in
    /// <c>../../../../private/var/folders/…/ws/App/apphost.cs</c>. The operating system resolves <c>..</c> against
    /// the physical directory, so that path doesn't exist, and it would tie a committed file to one machine. A lexical
    /// path that stays inside the directory is kept, so an AppHost configured through a linked subfolder keeps that
    /// folder's name; a path that climbs out is computed from both locations with links resolved instead.
    /// </remarks>
    private static string GetRelativeAppHostPath(string directory, string appHostPath)
    {
        var lexical = Path.GetRelativePath(directory, appHostPath);
        if (!IsOutsideDirectory(lexical))
        {
            return lexical;
        }
 
        return Path.GetRelativePath(PathNormalizer.ResolveSymlinks(directory), PathNormalizer.ResolveSymlinks(appHostPath));
    }
 
    /// <summary>
    /// Returns whether <paramref name="path"/> is <paramref name="directory"/> or lies below it.
    /// </summary>
    /// <remarks>
    /// AppHost discovery and link targets use paths with links resolved, while the directory can be given through
    /// a link (for example macOS /var -> /private/var), so both sides are resolved before comparing.
    /// </remarks>
    internal static bool IsInDirectory(string path, DirectoryInfo directory) =>
        !IsOutsideDirectory(Path.GetRelativePath(PathNormalizer.ResolveSymlinks(directory.FullName), PathNormalizer.ResolveSymlinks(path)));
 
    // GetRelativePath returns an absolute path when the two have no common root, such as different drives.
    // It compares paths case-insensitively on Windows and macOS, matching their default file systems.
    private static bool IsOutsideDirectory(string relativePath) =>
        Path.IsPathRooted(relativePath) ||
        relativePath == ".." ||
        relativePath.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal);
 
    /// <summary>
    /// Reads <paramref name="filePath"/> and returns its text with the encoding to write it back in, or
    /// <see langword="null"/> when the bytes can't be decoded without loss.
    /// </summary>
    /// <remarks>
    /// A byte order mark selects UTF-8, UTF-16 or UTF-32 (https://www.unicode.org/faq/utf_bom.html#bom4), and the
    /// returned encoding writes the same mark back. Without one the file must be valid UTF-8: decoding a file saved
    /// in a legacy code page as UTF-8, such as Windows-1252 where e-acute is the single byte 0xE9, replaces those
    /// bytes with U+FFFD, and writing the result back would destroy the team's text.
    /// </remarks>
    private static async Task<(string Text, Encoding Encoding)?> ReadTextAsync(string filePath, CancellationToken cancellationToken)
    {
        var bytes = await File.ReadAllBytesAsync(filePath, cancellationToken);
        // UTF-32 LE is checked before UTF-16 LE because its mark starts with the UTF-16 LE mark.
        Encoding encoding = bytes switch
        {
            [0xEF, 0xBB, 0xBF, ..] => new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true),
            [0xFF, 0xFE, 0x00, 0x00, ..] => new UTF32Encoding(bigEndian: false, byteOrderMark: true, throwOnInvalidCharacters: true),
            [0x00, 0x00, 0xFE, 0xFF, ..] => new UTF32Encoding(bigEndian: true, byteOrderMark: true, throwOnInvalidCharacters: true),
            [0xFF, 0xFE, ..] => new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true),
            [0xFE, 0xFF, ..] => new UnicodeEncoding(bigEndian: true, byteOrderMark: true, throwOnInvalidBytes: true),
            _ => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)
        };
 
        var preambleLength = encoding.Preamble.Length;
        try
        {
            var text = encoding.GetString(bytes, preambleLength, bytes.Length - preambleLength);
            // Markdown never holds U+0000, but a UTF-16 or UTF-32 file saved without a BOM decodes as
            // valid UTF-8 when its text is ASCII: "# A" in UTF-16 LE is the bytes 23 00 20 00 41 00, which
            // UTF-8 reads as "#\0 \0A\0". Appending UTF-8 text to it would mix two encodings in one file,
            // so a NUL means the encoding was not recognized and the file is left alone. Guessing the
            // encoding from the NUL positions instead would misread files that are simply not text.
            if (text.Contains('\0'))
            {
                return null;
            }
 
            return (text, encoding);
        }
        catch (DecoderFallbackException)
        {
            return null;
        }
    }
 
    /// <summary>
    /// Returns the index of the first section marker starting with <paramref name="prefix"/> at or after
    /// <paramref name="startIndex"/> that begins a line outside a fenced code block, or -1 when there is none.
    /// </summary>
    /// <remarks>
    /// <para>
    /// <see cref="CreateSection"/> writes each marker at the start of its own line. Users also mention the
    /// markers in their own instructions, inline or in an example block, as in
    /// </para>
    /// <code>
    /// Never remove `&lt;!-- aspire:begin --&gt;` or the team validation steps before `&lt;!-- aspire:end --&gt;`.
    ///
    /// ```markdown
    /// &lt;!-- aspire:begin --&gt;
    /// ...
    /// &lt;!-- aspire:end --&gt;
    /// ```
    /// </code>
    /// <para>
    /// and treating those mentions as markers would replace the user's text. A marker is therefore only
    /// recognized at the start of a line, after at most three spaces as for a CommonMark HTML block
    /// (https://spec.commonmark.org/0.31.2/#html-blocks); four spaces make an indented code block.
    /// </para>
    /// <para>
    /// The marker token must also end at a boundary: whitespace, the "-->" that closes the comment, or the end
    /// of the text. The text after the token can change between CLI versions, so all of
    /// </para>
    /// <code>
    /// &lt;!-- aspire:begin (generated by the Aspire CLI; ...) --&gt;
    /// &lt;!-- aspire:begin --&gt;
    /// &lt;!-- aspire:begin--&gt;
    /// </code>
    /// <para>
    /// are begin markers, while user comments such as <c>&lt;!-- aspire:beginner --&gt;</c> or
    /// <c>&lt;!-- aspire:endnotes --&gt;</c> are not.
    /// </para>
    /// </remarks>
    private static int FindMarker(string text, string prefix, int startIndex, List<(int Start, int End)> fencedCodeBlocks)
    {
        for (var lineStart = 0; lineStart < text.Length;)
        {
            var lineEnd = text.IndexOf('\n', lineStart);
            var nextLineStart = lineEnd < 0 ? text.Length : lineEnd + 1;
            var markerIndex = lineStart + CountIndentation(text, lineStart);
            if (markerIndex >= startIndex &&
                markerIndex - lineStart <= 3 &&
                text.AsSpan(markerIndex).StartsWith(prefix, StringComparison.Ordinal) &&
                IsMarkerTokenBoundary(text.AsSpan(markerIndex + prefix.Length)) &&
                !fencedCodeBlocks.Exists(block => markerIndex >= block.Start && markerIndex < block.End))
            {
                return markerIndex;
            }
 
            lineStart = nextLineStart;
        }
 
        return -1;
    }
 
    private static bool IsMarkerTokenBoundary(ReadOnlySpan<char> afterToken) =>
        afterToken.IsEmpty || char.IsWhiteSpace(afterToken[0]) || afterToken.StartsWith(CommentEnd, StringComparison.Ordinal);
 
    /// <summary>
    /// Returns the index of the "-->" that closes the marker comment at <paramref name="markerIndex"/>, or -1
    /// when the comment is unclosed, including when another "&lt;!--" opens before the next "-->": that "-->"
    /// then closes the other comment, not the marker.
    /// </summary>
    private static int FindCommentClose(string text, int markerIndex, string prefix)
    {
        var searchStart = markerIndex + prefix.Length;
        var close = text.IndexOf(CommentEnd, searchStart, StringComparison.Ordinal);
        if (close < 0 || text.AsSpan(searchStart, close - searchStart).Contains(CommentStart, StringComparison.Ordinal))
        {
            return -1;
        }
 
        return close;
    }
 
    /// <summary>
    /// Returns the spans of the closed fenced code blocks in <paramref name="text"/>, from the start of the
    /// opening fence line to the end of the closing fence line.
    /// </summary>
    /// <remarks>
    /// <para>
    /// A fence is a line of at least three backticks or tildes after at most three spaces, optionally followed
    /// by an info string, which can't contain a backtick for a backtick fence. The block ends at a line of at
    /// least as many of the same character followed only by whitespace
    /// (https://spec.commonmark.org/0.31.2/#fenced-code-blocks).
    /// </para>
    /// <para>
    /// A fence can also open the content of a list item on the bullet's line, with its body and closing fence
    /// indented to that content, as in
    /// </para>
    /// <code>
    /// - ```markdown
    ///   &lt;!-- aspire:begin --&gt;
    ///   Team notes.
    ///   &lt;!-- aspire:end --&gt;
    ///   ```
    /// </code>
    /// <para>
    /// Its markers start lines with two spaces, which <see cref="FindMarker"/> accepts, so the fence must be found
    /// for them to be ignored (https://spec.commonmark.org/0.31.2/#list-items). A closing fence may then be
    /// indented up to three spaces past the item's content, as a top-level one may be past the line start.
    /// </para>
    /// <para>
    /// CommonMark runs an unclosed fence to the end of the document. Such a fence is not in the returned list:
    /// without markers the section is appended after it, and ignoring markers after it would append another
    /// section on every run. Its opening offset is returned in <paramref name="unclosedFenceStart"/> instead, -1
    /// when every fence is closed, so markers after it can be treated as ambiguous.
    /// </para>
    /// </remarks>
    private static List<(int Start, int End)> FindFencedCodeBlocks(string text, out int unclosedFenceStart)
    {
        var blocks = new List<(int Start, int End)>();
        var openStart = -1;
        var fenceChar = '\0';
        var fenceLength = 0;
        var closingIndentationLimit = 3;
        for (var lineStart = 0; lineStart < text.Length;)
        {
            var lineEnd = text.IndexOf('\n', lineStart);
            var nextLineStart = lineEnd < 0 ? text.Length : lineEnd + 1;
            var line = text.AsSpan(lineStart, nextLineStart - lineStart);
            var indentation = CountIndentation(text, lineStart);
            if (openStart < 0)
            {
                if (indentation <= 3)
                {
                    var listItemContent = GetListItemContentOffset(line, indentation);
                    var runLength = ReadFenceRun(line[(listItemContent >= 0 ? listItemContent : indentation)..], out var runChar, out var rest);
                    if (runLength >= 3 && (runChar == '~' || !rest.Contains('`')))
                    {
                        openStart = lineStart;
                        fenceChar = runChar;
                        fenceLength = runLength;
                        closingIndentationLimit = (listItemContent >= 0 ? listItemContent : 0) + 3;
                    }
                }
            }
            else if (indentation <= closingIndentationLimit)
            {
                var runLength = ReadFenceRun(line[indentation..], out var runChar, out var rest);
                if (runChar == fenceChar && runLength >= fenceLength && rest.IsWhiteSpace())
                {
                    blocks.Add((openStart, nextLineStart));
                    openStart = -1;
                }
            }
 
            lineStart = nextLineStart;
        }
 
        unclosedFenceStart = openStart;
        return blocks;
    }
 
    // Returns the length of the run of fence characters (backticks or tildes) that starts text, 0 when there is
    // none, with the run's character and the rest of the line after it.
    private static int ReadFenceRun(ReadOnlySpan<char> text, out char runChar, out ReadOnlySpan<char> rest)
    {
        runChar = text.Length > 0 ? text[0] : '\0';
        var runLength = runChar is '`' or '~' ? text.Length - text.TrimStart(runChar).Length : 0;
        rest = text[runLength..];
        return runLength;
    }
 
    /// <summary>
    /// Returns the offset in <paramref name="line"/> of the content of a list item that the line opens after
    /// <paramref name="indentation"/> spaces, or -1 when it opens none.
    /// </summary>
    /// <remarks>
    /// A list item opens with a bullet ("-", "*" or "+") or an ordered marker of one to nine digits followed by
    /// "." or ")", then one to four spaces before its content: "- ```", "1. ```", "2) ```"
    /// (https://spec.commonmark.org/0.31.2/#list-items). With five spaces or more, the content would be an indented
    /// code block, so the line isn't treated as opening a fence.
    /// </remarks>
    private static int GetListItemContentOffset(ReadOnlySpan<char> line, int indentation)
    {
        var index = indentation;
        if (index < line.Length && line[index] is '-' or '*' or '+')
        {
            index++;
        }
        else
        {
            var digits = 0;
            while (index < line.Length && digits < 9 && char.IsAsciiDigit(line[index]))
            {
                index++;
                digits++;
            }
 
            if (digits == 0 || index >= line.Length || line[index] is not ('.' or ')'))
            {
                return -1;
            }
 
            index++;
        }
 
        var spaces = 0;
        while (index + spaces < line.Length && line[index + spaces] == ' ')
        {
            spaces++;
        }
 
        return spaces is >= 1 and <= 4 ? index + spaces : -1;
    }
 
    private static int CountIndentation(string text, int lineStart)
    {
        var index = lineStart;
        while (index < text.Length && text[index] == ' ')
        {
            index++;
        }
 
        return index - lineStart;
    }
 
    private static async Task CreateFileAsync(string filePath, string content, CancellationToken cancellationToken)
    {
        // CreateNew fails rather than overwrite a file created after the existence check.
        await using var stream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
        await using var writer = new StreamWriter(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
        await writer.WriteAsync(content.AsMemory(), cancellationToken);
    }
}