Engineering labs · C# and Copilot Studio

Gardenality × Microsoft Copilot Studio

Build a Plant Finder that can say “no match.” Wire a bounded C# catalog action into a Studio topic and verify the controls before opening access.

Sample-data C# prototype. Hosted Copilot Studio and Aurora integration are not verified. Reproduce the local tests →

gardenality-copilot-studio-1.0

By Chason Arthur

Gardenality
01

Trace the request

Gardeners can use the ordinary Gardenality plant library directly. The optional conversation collects a whole-number hardiness zone, light and soil moisture, then calls one read-only operation. A completed response cites the matching catalog records and explains any tradeoff.

  1. Microsoft Copilot Studio

    Confirm the criteria and invoke the topic tool.

  2. Plant Finder API

    Authenticate, validate and reserve an admission before lookup.

  3. Catalog reader

    Fixture in the lab. Approved private Aurora view in a future integration.

  4. Grounded response

    Return up to three named matches, a reason and a source link per match.

The Studio icon identifies the proposed runtime. Microsoft Power Platform icon guidance

Checkpoint Trace an incomplete request to a follow-up question and a valid request to a catalog lookup. The plain search path remains usable during a pause or outage.

02

Set up the lab

ModeYou needEvidence produced
Local review.NET 10 SDK, PowerShell 7, Python 3, a browser and the source ZIP. Node.js 20+ is optional for the original browser fixture.Loopback HTTP, contract and admission tests using synthetic rows. No cloud account required.
Native fixture pilotExisting approved Copilot Studio test environment, maker access, private pilot audience, end-user connector credentials and an approved HTTPS endpoint for the same fixture API.Actual custom connector input mapping, transport, identity and output behavior.
Gardenality integrationData owner approval, real schema and engine mapping, private routing, a durable gate, delegated identity and separately approved release window.Catalog access, public-source mapping, security and operational evidence in the approved environment.

Download the source pack, extract it to a fresh folder, and open PowerShell in its root. The archive includes the source shown below, a runnable test harness, the connector definition, original browser fixture logic, and the hosted integration runbook. This page embeds the core sources; the source pack runs locally.

Confirm the local runtimes before building. Expected .NET 10.x, PowerShell 7.5+ and Python 3.
Terminal · source rootPowerShell
dotnet --version
$PSVersionTable.PSVersion
python --version

Checkpoint dotnet --version reports a 10.x SDK, Python 3 launches and PlantFinder.Api/PlantFinder.Api.csproj exists. The kit was tested on .NET SDK 10.0.400.

03

Bound the catalog

The sample requires zone 1–13, light sun or shade, and soil dry or wet. The candidate must fit all three and have known mature height. Optional size, native and fall affect rank. The sample scores two points for each desired tag and one point for meeting the preferred height. Public ID breaks ties. The response states a height tradeoff explicitly.

BoundaryAllowed fields
Private reader projectionPublished public plant ID, approved public display name and canonical record URL, hardiness zone bounds, normalized light and soil, mature height in feet, approved native and fall-interest flags.
Response per matchid, name, source and deterministic reason. Maximum three records.

Before wiring Aurora, document the database engine and record owner. Reconcile the public library and recovered ASPX behavior against dated evidence. Compare filter names, OR within a group, AND across groups, pagination, empty states and public links. The sample deliberately has fewer categories. Decide how to normalize zones such as 7A and 7B, multi-value exposure, moisture versus soil texture, and native tags by region before mapping live rows. Permit only a curated, published view and grant the API login SELECT on that view. Restrict the source URL to the approved HTTPS Gardenality host and record path. Exclude member, commerce, private collections, raw notes and internal fields from both the projection and API logs. Keep the database private, use TLS with hostname verification and pin the approved CA trust bundle.

Review the SQL and runbook appendix for a PostgreSQL-shaped example. The original public platform had MySQL, and the current Aurora engine and exact schema remain to be confirmed by the owner. Gardenality project history · Aurora reader endpoint behavior

Synthetic catalog included in the sample
SourceZoneLightSoilHeightTags
G-103 · Fixture shrub A6–8shadewet6 ftnative, fall
G-104 · Fixture shrub B7–9shadewet4 ftnative
G-105 · Fixture groundcover5–8shadedryunknown
G-106 · Fixture perennial6–8sunwet3 ftfall
Define strict inputs, rank only complete matches, and project four public fields. Expected G-103 ranks first on the match case and G-105 is filtered out of dry shade.
PlantFinder.Api/FixtureCatalog.csC#
using System.Globalization;
using System.Text.Json.Serialization;

[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
internal sealed record FindPlantsRequest(
    int? Zone,
    string? Light,
    string? Soil,
    decimal? Size,
    bool Native = false,
    bool Fall = false)
{
    public string? ValidationMessage()
    {
        if (Zone is null || string.IsNullOrEmpty(Light) || string.IsNullOrEmpty(Soil))
        {
            return "Provide a hardiness zone, light setting, and soil moisture.";
        }
        if (Zone is < 1 or > 13 || Light is not ("sun" or "shade") || Soil is not ("dry" or "wet"))
        {
            return "Use a whole-number zone from 1 to 13, sun or shade, and dry or wet soil.";
        }
        return Size is < 1 or > 200 ? "Set the optional mature height from 1 to 200 feet." : null;
    }
}

internal sealed class FixtureCatalog(IConfiguration configuration)
{
    private static readonly CatalogRow[] Rows =
    [
        new("G-103", "Fixture shrub A", 6, 8, "shade", "wet", 6, Native: true, Fall: true),
        new("G-104", "Fixture shrub B", 7, 9, "shade", "wet", 4, Native: true, Fall: false),
        new("G-105", "Fixture groundcover", 5, 8, "shade", "dry", null, Native: null, Fall: null),
        new("G-106", "Fixture perennial", 6, 8, "sun", "wet", 3, Native: false, Fall: true)
    ];

    public PlantResponse Find(FindPlantsRequest input)
    {
        if (configuration.GetValue<bool>("PlantFinder:SimulateCatalogUnavailable"))
        {
            throw new InvalidOperationException("Fixture catalog unavailable.");
        }

        var matches = Rows
            .Where(row => row.HeightFeet is > 0 && input.Zone >= row.ZoneMin && input.Zone <= row.ZoneMax
                && input.Light == row.Light && input.Soil == row.Soil)
            .OrderByDescending(row => Score(row, input))
            .ThenBy(row => row.Id, StringComparer.Ordinal)
            .Take(3)
            .Select(row => Project(row, input))
            .ToArray();

        return matches.Length == 0
            ? new("no-match", "No complete fixture record matches the required conditions.", matches)
            : new("match", $"{matches.Length} fixture matches. Review their reasons and source records.", matches);
    }

    private static int Score(CatalogRow row, FindPlantsRequest input)
    {
        var native = input.Native && row.Native == true ? 2 : 0;
        var fall = input.Fall && row.Fall == true ? 2 : 0;
        var size = input.Size is { } preferredHeight && row.HeightFeet <= preferredHeight ? 1 : 0;
        return native + fall + size;
    }

    private static PlantMatch Project(CatalogRow row, FindPlantsRequest input)
    {
        var reason = FormattableString.Invariant(
            $"Fits the requested zone, light and soil. Mature height {row.HeightFeet} ft.");
        if (input.Size is { } preferredHeight && row.HeightFeet > preferredHeight)
        {
            reason += $" This exceeds the preferred {preferredHeight.ToString("G29", CultureInfo.InvariantCulture)} ft.";
        }
        if (input.Native && row.Native == true)
        {
            reason += " Native tag.";
        }
        if (input.Fall && row.Fall == true)
        {
            reason += " Fall interest tag.";
        }
        return new PlantMatch(row.Id, row.Name, "#" + row.Id, reason);
    }

    private sealed record CatalogRow(
        string Id, string Name, int ZoneMin, int ZoneMax, string Light, string Soil,
        int? HeightFeet, bool? Native, bool? Fall);
}

internal sealed record PlantResponse(string Kind, string Message, PlantMatch[] Matches);
internal sealed record PlantMatch(string Id, string Name, string Source, string Reason);

Checkpoint For Zone 7 wet shade, with native, fall and five-foot preferences, G-103 ranks ahead of G-104 and discloses its six-foot height. For Zone 7 dry shade, the incomplete G-105 produces zero eligible matches.

04

Run the C# API

Open PowerShell in the extracted source root and launch the helper. It starts Kestrel on loopback and runs the smoke requests with a new ephemeral credential. The full HTTP test suite in Step 10 runs independently.

Build and exercise the fixture on 127.0.0.1. Pass -Port 5081 if 5080 is busy. Expected Three successful checks for lookup, replay and no match.
Terminal · source rootPowerShell
pwsh -File ./smoke.ps1

Expected output includes HTTP 200 for the first lookup, G-103 and G-104 in that order, a replay of the same result and an empty no-match response for dry shade. The script restores its process environment and stops its server when it exits.

Connect strict parsing, caller authentication, the gate and the fixture. Expected A new admitted lookup returns a bounded payload. A denial returns a traceable problem document.
PlantFinder.Api/Program.csC#
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;

var builder = WebApplication.CreateBuilder(args);
var settings = PlantSettings.Load(builder.Configuration);
builder.WebHost.ConfigureKestrel(options => options.Limits.MaxRequestBodySize = 4096);
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.NumberHandling = JsonNumberHandling.Strict;
    options.SerializerOptions.AllowDuplicateProperties = false;
    options.SerializerOptions.PropertyNameCaseInsensitive = false;
});
builder.Services.AddSingleton(settings);
builder.Services.AddSingleton(CallerRegistry.Load(builder.Configuration));
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<TrafficGate>();
builder.Services.AddSingleton<FixtureCatalog>();

var app = builder.Build();
app.MapGet("/healthz", () => Results.Ok(new { status = "ok", catalog = "offline-fixture" }));
app.MapPost("/v1/plants/find", FindPlants);
app.Run();

static async Task<IResult> FindPlants(
    HttpContext context,
    PlantSettings settings,
    CallerRegistry callers,
    TrafficGate gate,
    FixtureCatalog catalog,
    IOptions<JsonOptions> jsonOptions,
    ILogger<Program> logger)
{
    var traceId = Activity.Current?.TraceId.ToString() ?? context.TraceIdentifier;
    context.Response.Headers["X-Request-Id"] = traceId;
    context.Response.Headers.CacheControl = "no-store";
    using var scope = logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = traceId });

    var remoteAddress = context.Connection.RemoteIpAddress;
    var loopback = remoteAddress is not null && IPAddress.IsLoopback(
        remoteAddress.IsIPv4MappedToIPv6 ? remoteAddress.MapToIPv4() : remoteAddress);
    if (!context.Request.IsHttps && !loopback && !settings.AllowRemoteHttp)
    {
        return Problem(403, "https_required", "HTTPS is required outside the local review.");
    }

    var subject = callers.Authenticate(context.Request.Headers);
    if (subject is null)
    {
        context.Response.Headers.WWWAuthenticate = "PlantFinderKey";
        return Problem(401, "unauthorized", "A valid Plant Finder connection key is required.");
    }

    var key = context.Request.Headers["Idempotency-Key"];
    if (key.Count != 1 || !TrafficGate.IsValidKey(key[0]))
    {
        return Problem(400, "invalid_idempotency_key", "Provide one valid Idempotency-Key header.");
    }

    if (!MediaTypeHeaderValue.TryParse(context.Request.ContentType, out var contentType)
        || !string.Equals(contentType.MediaType.Value, "application/json", StringComparison.OrdinalIgnoreCase)
        || (contentType.Charset.HasValue
            && !string.Equals(contentType.Charset.Value?.Trim('"'), "utf-8", StringComparison.OrdinalIgnoreCase)))
    {
        return Problem(415, "unsupported_media_type", "Send an application/json request body encoded in UTF-8.");
    }

    FindPlantsRequest? input;
    try
    {
        input = await JsonSerializer.DeserializeAsync<FindPlantsRequest>(
            context.Request.Body, jsonOptions.Value.SerializerOptions, context.RequestAborted);
    }
    catch (JsonException)
    {
        return Problem(400, "invalid_request", "Send a JSON object containing only documented fields and types.");
    }
    catch (BadHttpRequestException error) when (error.StatusCode == StatusCodes.Status413PayloadTooLarge)
    {
        return Problem(413, "payload_too_large", "The JSON body may contain at most 4096 bytes.");
    }

    var validationMessage = input is null ? "Send a JSON object." : input.ValidationMessage();
    if (validationMessage is not null)
    {
        return Problem(400, "invalid_request", validationMessage);
    }

    var admission = gate.Admit(subject, key[0]!, input!);
    if (admission.Denial is { } denial)
    {
        if (denial.RetryAfterSeconds is { } seconds)
        {
            context.Response.Headers.RetryAfter = seconds.ToString(CultureInfo.InvariantCulture);
        }

        return Problem(denial.Status, denial.Code, denial.Message);
    }

    var entry = admission.Entry!;
    if (!admission.OwnsReservation)
    {
        context.Response.Headers["Idempotency-Replayed"] = "true";
        var replay = await entry.Result.WaitAsync(context.RequestAborted);
        logger.LogInformation("Idempotent outcome replayed ({Outcome})", replay.Response?.Kind ?? "catalog_unavailable");
        return ToHttp(replay);
    }

    // Reservations count even when the catalog fails. Finish a reserved lookup if its caller disconnects.
    CatalogOutcome outcome;
    logger.LogInformation("Catalog lookup started");
    try
    {
        var response = catalog.Find(input!);
        outcome = new CatalogOutcome(response);
        logger.LogInformation("Catalog lookup finished ({Outcome}, {MatchCount})", response.Kind, response.Matches.Length);
    }
    catch (Exception error)
    {
        outcome = new CatalogOutcome(null);
        logger.LogError("Catalog lookup failed closed ({FailureType})", error.GetType().Name);
    }

    entry.Complete(outcome);
    return ToHttp(outcome);

    IResult ToHttp(CatalogOutcome outcome) => outcome.Response is { } response
        ? Results.Ok(response)
        : Problem(503, "catalog_unavailable", "The catalog lookup failed. No recommendation was made.");

    IResult Problem(int status, string code, string detail)
    {
        logger.LogInformation("Plant Finder returned {Status} ({Code})", status, code);
        return Results.Problem(
            statusCode: status,
            title: code.Replace('_', ' '),
            detail: detail,
            extensions: new Dictionary<string, object?> { ["code"] = code, ["traceId"] = traceId });
    }
}

Checkpoint Review the route and response writer below. The handler calls the catalog only for an admitted owner of an idempotency record.

05

Authenticate and rotate

Use a separate pilot access key per approved reviewer. Generate 32 cryptographically random bytes and encode them as lowercase hex. The lab stores the SHA-256 digest of the ASCII hex key and an opaque, stable subject. The key header is transmitted only over TLS beyond loopback. Each reviewer creates their own Power Platform connection. A maker-provided shared credential would collapse all requests into one subject and breaks the per-user check.

For the lab, the smoke helper constructs and discards credentials in process memory. For the pilot, issue the raw key into an approved private credential store and deliver it through the organization’s secret distribution process to the individual who creates the connection. Put approved subject/digest mappings in separate environment app settings or Key Vault references. Grant the app’s managed identity permission to read the referenced secrets. Keep keys out of OpenAPI, topic variables, screenshots, Git, HTTP history and logs. Restrict connection sharing and trace access. Key Vault references for App Service · End-user credentials in Studio

  1. Generate a replacement key and add its digest under a second config entry for the same subject. Deploy or refresh the approved config with both entries present.
  2. During the overlap, issue a search using the old connection. Create a new private connection under the same reviewer and confirm the same logical search replays and shares quota in the same process. Confirm another reviewer uses a different subject. The fixture registry loads at startup and the in-memory ledger clears on restart. Use the durable design to preserve these guarantees across releases.
  3. Remove the old digest and refresh or restart as required. Verify old-key HTTP 401, new-key HTTP 200 and no credential in server logs. On a compromise remove the suspect digest immediately and pause the action while verifying containment.

The tutorial pilot uses API-key connections. For a durable release, register separate tenant-scoped API and connector-client apps with delegated PlantFinder.Read. Configure the generated connector redirect as the client’s exact Web redirect and store the connector client secret in its approved connection configuration. Require API v2 tokens, validate signature, expiry, issuer and API audience, enforce tenant and authorized connector client, check the scope and use verified tid + oid for the ledger subject. Deliberately test wrong audience, wrong tenant and missing scope. Rotate the client secret with an overlap, reconnect and verify before removing the old instance. The supplied C# pilot implements key validation. Delegated token validation and the Entra settings require a separate owner-run acceptance test. Entra connector authentication · Entra access token claims

Resolve a connection key to a configured opaque subject. Expected Unknown keys return no subject. Two approved digests can map to one reviewer.
PlantFinder.Api/CallerRegistry.csC#
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

internal sealed class CallerRegistry
{
    private const string Header = "X-Plant-Finder-Key";
    private static readonly Regex SubjectPattern = new(@"\A[a-zA-Z0-9_-]{1,64}\z", RegexOptions.CultureInvariant);
    private readonly Caller[] callers;

    private CallerRegistry(Caller[] callers)
    {
        this.callers = callers;
    }

    public static CallerRegistry Load(IConfiguration configuration)
    {
        var entries = configuration.GetSection("PlantFinder:Callers").GetChildren().ToArray();
        if (entries.Length > 64)
        {
            throw new InvalidOperationException("Configure at most 64 fixture key entries.");
        }

        var knownHashes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        var callers = new List<Caller>();
        foreach (var entry in entries)
        {
            var subject = entry["Subject"];
            var digest = entry["KeySha256"];
            if (subject is null || !SubjectPattern.IsMatch(subject) || digest is null
                || digest.Length != 64 || !digest.All(Uri.IsHexDigit) || !knownHashes.Add(digest))
            {
                throw new InvalidOperationException("Each fixture key entry needs a subject and a unique SHA-256 digest.");
            }

            callers.Add(new Caller(subject, Convert.FromHexString(digest)));
        }

        return new CallerRegistry(callers.ToArray());
    }

    public string? Authenticate(IHeaderDictionary headers)
    {
        var values = headers[Header];
        var key = values.Count == 1 ? values[0] : null;
        if (key is null || key.Length != 64 || !key.All(IsLowercaseHex))
        {
            return null;
        }

        var digest = SHA256.HashData(Encoding.ASCII.GetBytes(key));
        string? subject = null;
        foreach (var caller in callers)
        {
            if (CryptographicOperations.FixedTimeEquals(digest, caller.Digest))
            {
                subject = caller.Subject;
            }
        }

        return subject;
    }

    private static bool IsLowercaseHex(char character) =>
        character is >= '0' and <= '9' or >= 'a' and <= 'f';

    private sealed record Caller(string Subject, byte[] Digest);
}

Checkpoint Unknown credentials return 401 before any catalog call. The overlap test verifies that both credentials resolve to the same quota subject.

06

Reserve quota before calls

The fixture uses explicit teaching limits of four new lookups per subject per UTC day, 12 globally per UTC day, and ten authenticated valid attempts per subject per UTC minute. The atomic admission lock covers the switch check, request-attempt limit, idempotency check and the two quota reservations. Validate before admission. An accepted new request reserves both quotas before the catalog read. Replays do not debit daily quotas, but consume a request attempt. A key reused with different normalized criteria returns 409. The app retains the original result, including an unavailable result, for 24 hours and shares it with an in-flight duplicate. Failed or cancelled client work is conservatively charged against the fixture counters. Bound the catalog timeout, and avoid a second automatic outbound call.

Set the configuration switch to disabled to deny any new attempt and block replays. An already admitted call can finish. The local counters and replay ledger reside in one process and clear at restart. Stop the pilot if a replica or restart would break a claim about continuity. For production, move the policy, counters and idempotency state into a durable shared transaction before connecting a real provider. Use database time and an atomic reservation keyed by verified identity and logical request. Deduct both quotas and insert the dispatch record together. Limit idempotency retention, reserve estimated fixed units if enforcing spend, and fail closed if the ledger is unreachable or the dispatch result is uncertain. The hosted appendix describes crash and concurrency handling.

ControlWhere it takes effect
Plant Finder application gateBefore the catalog read. It controls this API’s admissions after a Studio activity reaches it.
Companion entry gateBefore any Gardenality-supplied gateway sends a metered Studio turn. Reserve per-user and global budget before the first provider operation for that turn. Keep Direct Line secrets and tokens server-side and bind each conversation to the verified reviewer. Expose only this entry point to the governed audience and test blocked requests emit zero provider calls.
Power Platform agent controlsPPAC shows credit consumption and supports agent off and monthly limits. Verify tenant licensing, reporting delay, current enforcement and scope before opening use. Separate agent flow capacity can apply.
Azure Cost Management budgetBudget alerts report cost and can notify operators or trigger configured automation. Creation of a budget alone leaves resources running.

For a governed custom website, enforce its allowlist and reservation before starting a provider conversation or sending the user activity. Relay approved replies and connection setup through the backend. Direct Teams, demo and other native access bypass that application boundary. Treat a native design-pilot run as separate and limit it to the approved testers. Model a turn quota as a dispatch quota unless you can establish and reserve a defensible upper bound for credit consumption. Use plain search when the app lacks identity, quota or provider health. Studio web-channel security · Direct Line send activity · Studio billing and enforcement · Azure budgets

Apply fixed-window limits and a circuit switch while serializing reservations and in-flight replay ownership. Expected Only one caller owns a matching reservation. An exhausted quota returns 429 before the catalog.
PlantFinder.Api/TrafficGate.csC#
using System.Text.RegularExpressions;

internal sealed class TrafficGate(
    PlantSettings settings,
    IConfiguration configuration,
    TimeProvider timeProvider)
{
    private static readonly Regex KeyPattern = new(@"\A[a-zA-Z0-9_.:-]{8,128}\z", RegexOptions.CultureInvariant);
    private static readonly TimeSpan Retention = TimeSpan.FromHours(24);
    private readonly object sync = new();
    private readonly Dictionary<string, int> minuteAttempts = new(StringComparer.Ordinal);
    private readonly Dictionary<string, int> dailyReservations = new(StringComparer.Ordinal);
    private readonly Dictionary<(string Subject, string Key), PendingLookup> history = new();
    private long activeMinute = long.MinValue;
    private long activeDay = long.MinValue;
    private int globalDailyReservations;
    private DateTimeOffset nextSweep = DateTimeOffset.MinValue;

    public static bool IsValidKey(string? key) => key is not null && KeyPattern.IsMatch(key);

    public Admission Admit(string subject, string key, FindPlantsRequest input)
    {
        lock (sync)
        {
            // Missing or malformed runtime control fails closed.
            if (!bool.TryParse(configuration["PlantFinder:Enabled"], out var enabled) || !enabled)
            {
                return Reject(503, "disabled", "The Plant Finder action is paused.");
            }

            var now = timeProvider.GetUtcNow();
            var unixSecond = now.ToUnixTimeSeconds();
            var minute = unixSecond / 60;
            var day = unixSecond / 86_400;
            if (minute > activeMinute)
            {
                minuteAttempts.Clear();
                activeMinute = minute;
            }
            if (day > activeDay)
            {
                dailyReservations.Clear();
                globalDailyReservations = 0;
                activeDay = day;
            }

            var attempts = minuteAttempts.GetValueOrDefault(subject);
            if (attempts >= settings.PerUserRequestsPerMinute)
            {
                return Reject(429, "rate_limit", "The request rate limit was reached.",
                    SecondsUntil((activeMinute + 1) * 60));
            }
            minuteAttempts[subject] = attempts + 1;

            if (now >= nextSweep)
            {
                foreach (var expired in history.Where(item => item.Value.HasExpired(now)).ToArray())
                {
                    history.Remove(expired.Key);
                }
                nextSweep = now.AddMinutes(1);
            }
            var lookupKey = (subject, key);
            if (history.TryGetValue(lookupKey, out var previous))
            {
                if (!previous.HasExpired(now))
                {
                    return previous.Input == input
                        ? new Admission(previous, OwnsReservation: false, Denial: null)
                        : Reject(409, "idempotency_conflict", "Use a new key for changed input.");
                }
                history.Remove(lookupKey);
            }

            var reserved = dailyReservations.GetValueOrDefault(subject);
            if (reserved >= settings.PerUserDailyQuota)
            {
                return Reject(429, "per_user_quota", "The daily user lookup quota was reached.",
                    SecondsUntil((activeDay + 1) * 86_400));
            }
            if (globalDailyReservations >= settings.GlobalDailyQuota)
            {
                return Reject(429, "global_quota", "The daily shared lookup quota was reached.",
                    SecondsUntil((activeDay + 1) * 86_400));
            }

            // Publish the reservation and pending outcome together before the caller touches the catalog.
            var entry = new PendingLookup(input, now + Retention);
            history.Add(lookupKey, entry);
            dailyReservations[subject] = reserved + 1;
            globalDailyReservations++;
            return new Admission(entry, OwnsReservation: true, Denial: null);

            int SecondsUntil(long futureUnixSecond) => (int)Math.Clamp(futureUnixSecond - unixSecond, 1, int.MaxValue);
        }
    }

    private static Admission Reject(int status, string code, string message, int? retryAfterSeconds = null) =>
        new(Entry: null, OwnsReservation: false, new Denial(status, code, message, retryAfterSeconds));
}

internal sealed class PendingLookup(FindPlantsRequest input, DateTimeOffset expiresAt)
{
    private readonly TaskCompletionSource<CatalogOutcome> completion =
        new(TaskCreationOptions.RunContinuationsAsynchronously);

    public FindPlantsRequest Input { get; } = input;
    public Task<CatalogOutcome> Result => completion.Task;
    public bool HasExpired(DateTimeOffset now) => now >= expiresAt && Result.IsCompleted;
    public void Complete(CatalogOutcome outcome) => completion.SetResult(outcome);
}

internal sealed record Admission(PendingLookup? Entry, bool OwnsReservation, Denial? Denial);
internal sealed record Denial(int Status, string Code, string Message, int? RetryAfterSeconds);
internal sealed record CatalogOutcome(PlantResponse? Response);
Load and bound the teaching limits before starting the host. Expected The process fails startup if configured limits are out of range.
PlantFinder.Api/PlantSettings.csC#
internal sealed record PlantSettings(
    int PerUserRequestsPerMinute,
    int PerUserDailyQuota,
    int GlobalDailyQuota,
    bool AllowRemoteHttp)
{
    public static PlantSettings Load(IConfiguration configuration)
    {
        var section = configuration.GetSection("PlantFinder");
        return new(
            ReadLimit("PerUserRequestsPerMinute", 10, 600),
            ReadLimit("PerUserDailyQuota", 4, 10_000),
            ReadLimit("GlobalDailyQuota", 12, 10_000),
            section.GetValue("AllowRemoteHttp", false));

        int ReadLimit(string key, int fallback, int maximum)
        {
            var value = section.GetValue(key, fallback);
            if (value < 1 || value > maximum)
            {
                throw new InvalidOperationException($"Set PlantFinder:{key} from 1 to {maximum}.");
            }
            return value;
        }
    }
}
Use this local configuration template. The smoke script creates ephemeral pilot mappings in the child process environment. Expected The local sample uses 10 attempts/minute, four lookups/subject/day and 12 lookups/day across all callers.
PlantFinder.Api/appsettings.jsonJSON
{
  "PlantFinder": {
    "Enabled": true,
    "AllowRemoteHttp": false,
    "SimulateCatalogUnavailable": false,
    "PerUserRequestsPerMinute": 10,
    "PerUserDailyQuota": 4,
    "GlobalDailyQuota": 12
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    },
    "Console": {
      "FormatterName": "json",
      "FormatterOptions": {
        "IncludeScopes": true,
        "UseUtcTimestamp": true,
        "TimestampFormat": "yyyy-MM-ddTHH:mm:ss.fffZ"
      }
    }
  }
}

Checkpoint Exhaust the user and global counters independently. Verify a switch-off request or unknown ledger state leaves the managed outbound call count unchanged.

07

Inspect HTTP and OpenAPI

Studio only needs POST /v1/plants/find. The credential belongs in the saved connection and the idempotency key belongs to the logical lookup. The smoke script sends this shape over local HTTP. The bracketed key below stands for the ephemeral value.

Send the same shape as the local smoke script with a placeholder key for display. Expected HTTP 200 and the observed JSON below.
smoke.ps1 · request on the wireHTTP
POST /v1/plants/find HTTP/1.1
Host: 127.0.0.1:5080
Content-Type: application/json
X-Plant-Finder-Key: [ephemeral local key]
Idempotency-Key: 96eaf466-872d-468c-9519-4f215b787301

{"zone":7,"light":"shade","soil":"wet","size":5,"native":true,"fall":true}
Inspect the actual success payload from the loopback run. Expected Two source anchors and the exact six-foot tradeoff on G-103.
verification/loopback-smoke.txt · observed response JSONJSON
{
  "kind": "match",
  "message": "2 fixture matches. Review their reasons and source records.",
  "matches": [
    {
      "id": "G-103",
      "name": "Fixture shrub A",
      "source": "#G-103",
      "reason": "Fits the requested zone, light and soil. Mature height 6 ft. This exceeds the preferred 5 ft. Native tag. Fall interest tag."
    },
    {
      "id": "G-104",
      "name": "Fixture shrub B",
      "source": "#G-104",
      "reason": "Fits the requested zone, light and soil. Mature height 4 ft. Native tag."
    }
  ]
}
HTTPExpected behavior
200match or no-match with a bounded array. An idempotent replay includes Idempotency-Replayed: true.
400 / 401Correct the submitted criteria or authenticate with an issued connection.
409Keep the original search for a retry. Start a fresh logical search with a new request ID when criteria changed.
429Attempt limit, per-user quota or global quota. Respect Retry-After where supplied and use plain search.
503Paused or unavailable. Offer plain search and preserve the operator’s correlation ID.

Use the embedded Swagger 2.0 definition. Replace its host placeholder with the approved pilot hostname and keep https and /v1. Microsoft Power Platform custom connectors import OpenAPI 2.0 files under 1 MB. OpenAPI operations expose metadata and schemas. Studio may route a non-2xx connector action to its system error topic. Power Platform OpenAPI import · Studio connector errors

Import this contract into the Power Platform custom connector. Expected FindPlants accepts an authenticated bounded criteria request. Official Swagger schema and local contract checks passed. Tenant import is pending.
connector/plant-finder.swagger.jsonJSON
{
  "swagger": "2.0",
  "info": {
    "title": "Gardenality Plant Finder (fixture pilot)",
    "version": "1.0.0",
    "description": "Search a bounded synthetic plant catalog using zone, light, and soil."
  },
  "host": "plant-finder-pilot.example.invalid",
  "basePath": "/v1",
  "schemes": ["https"],
  "consumes": ["application/json"],
  "produces": ["application/json", "application/problem+json"],
  "securityDefinitions": {
    "plantFinderKey": {
      "type": "apiKey", "in": "header", "name": "X-Plant-Finder-Key",
      "description": "Per-caller fixture connection credential. Enter the 64-character lowercase hexadecimal key when creating the connection."
    }
  },
  "security": [{"plantFinderKey": []}],
  "paths": {
    "/plants/find": {
      "post": {
        "operationId": "FindPlants",
        "summary": "Find catalog plants",
        "description": "Return at most three evidence-backed matches for complete required inputs. Optional preferences affect rank only. Reuse the request key only for a retry of the same search.",
        "x-ms-summary": "Find catalog plants",
        "parameters": [
          {
            "name": "Idempotency-Key", "in": "header", "type": "string", "required": true,
            "minLength": 8, "maxLength": 128, "pattern": "^[A-Za-z0-9_.:-]+$",
            "x-ms-summary": "Request key", "x-ms-visibility": "important",
            "description": "Opaque request identifier generated once for this search."
          },
          {"name": "criteria", "in": "body", "required": true, "schema": {"$ref": "#/definitions/PlantCriteria"}}
        ],
        "responses": {
          "200": {
            "description": "Catalog result",
            "headers": {
              "Idempotency-Replayed": {"type": "string", "enum": ["true"], "description": "Present when a stored result was reused."},
              "X-Request-Id": {"type": "string", "description": "Request correlation ID."}
            },
            "schema": {"$ref": "#/definitions/PlantResult"}
          },
          "400": {"description": "Invalid criteria or request key", "schema": {"$ref": "#/definitions/Problem"}},
          "401": {
            "description": "Missing or unknown connection credential",
            "headers": {"WWW-Authenticate": {"type": "string", "enum": ["PlantFinderKey"]}},
            "schema": {"$ref": "#/definitions/Problem"}
          },
          "403": {"description": "HTTPS required for remote requests", "schema": {"$ref": "#/definitions/Problem"}},
          "409": {"description": "Idempotency conflict", "schema": {"$ref": "#/definitions/Problem"}},
          "413": {"description": "Request body exceeds 4096 bytes", "schema": {"$ref": "#/definitions/Problem"}},
          "415": {"description": "Request body needs a JSON media type", "schema": {"$ref": "#/definitions/Problem"}},
          "429": {
            "description": "Rate limit or quota reached",
            "headers": {
              "Retry-After": {"type": "integer", "format": "int32", "description": "Seconds until the applicable UTC window resets."},
              "X-Request-Id": {"type": "string", "description": "Request correlation ID."}
            },
            "schema": {"$ref": "#/definitions/Problem"}
          },
          "503": {
            "description": "Action disabled or catalog unavailable",
            "headers": {"Idempotency-Replayed": {"type": "string", "enum": ["true"], "description": "Present when a stored catalog failure was reused."}},
            "schema": {"$ref": "#/definitions/Problem"}
          },
          "default": {"description": "Request failed", "schema": {"$ref": "#/definitions/Problem"}}
        }
      }
    }
  },
  "definitions": {
    "PlantCriteria": {
      "type": "object", "required": ["zone", "light", "soil"], "additionalProperties": false,
      "properties": {
        "zone": {"type": "integer", "format": "int32", "minimum": 1, "maximum": 13, "x-ms-summary": "Hardiness zone"},
        "light": {"type": "string", "enum": ["sun", "shade"], "x-ms-summary": "Light"},
        "soil": {"type": "string", "enum": ["dry", "wet"], "x-ms-summary": "Soil moisture"},
        "size": {"type": "number", "format": "double", "minimum": 1, "maximum": 200, "x-ms-summary": "Preferred maximum height in feet"},
        "native": {"type": "boolean", "x-ms-summary": "Prefer native tag"},
        "fall": {"type": "boolean", "x-ms-summary": "Prefer fall interest"}
      }
    },
    "PlantResult": {
      "type": "object", "required": ["kind", "message", "matches"], "additionalProperties": false,
      "properties": {
        "kind": {"type": "string", "enum": ["match", "no-match"]},
        "message": {"type": "string"},
        "matches": {"type": "array", "maxItems": 3, "items": {"$ref": "#/definitions/PlantMatch"}}
      }
    },
    "PlantMatch": {
      "type": "object", "required": ["id", "name", "source", "reason"], "additionalProperties": false,
      "properties": {
        "id": {"type": "string"}, "name": {"type": "string"},
        "source": {"type": "string", "description": "Offline fixture reference, such as #G-103."},
        "reason": {"type": "string"}
      }
    },
    "Problem": {
      "type": "object", "required": ["title", "status", "detail", "code", "traceId"],
      "description": "Plant Finder error returned as application/problem+json.",
      "properties": {
        "type": {"type": "string"},
        "title": {"type": "string"}, "status": {"type": "integer", "format": "int32"},
        "detail": {"type": "string"}, "code": {"type": "string"},
        "traceId": {"type": "string", "description": "Matches the X-Request-Id response header."}
      }
    }
  }
}

Checkpoint Match the Swagger path, request properties, result properties and security header against the running endpoint and observed responses.

08

Build the Studio action

Use a standard-harness agent in the approved test environment. The connector cloud runtime needs a reachable approved HTTPS hostname. A maker’s localhost address and the .invalid host in the import file are review placeholders. Complete the isolated fixture hosting procedure in Step 11 before trying a native connection.

  1. In the same environment in Power Apps, open Solutions, create or open a connector-only solution, and select New → Automation → Custom connector → Import an OpenAPI file. Import connector/plant-finder.swagger.json with the pilot host. In General confirm HTTPS host and /v1. In Security confirm API Key, label Plant Finder pilot key, parameter name X-Plant-Finder-Key, location Header. In Definition verify FindPlants, then save.
  2. Open the connector’s Test tab, create a connection using your own issued credential, and select Test operation. Supply the payload from Step 7 and a freshly generated request key. Confirm the response and a matching API trace. In Studio, select Agents → [test agent] → Tools → Add a tool, find the saved connector, and add Find catalog plants. Keep End user credentials and turn off Allow agent to decide dynamically when to use the tool for this exercise.
  3. Enable the approved agent sign-in setting. Under Topics → Add a topic → From blank, create Find a plant with a trigger such as find a plant. Add Question nodes for hardiness zone, light and soil. Store a number and two normalized strings. Refuse an unsupported value and ask for the missing or corrected criterion. Capture optional numeric height and Boolean preferences only when supplied. For the fixture match test set height to 5 and both preferences to true via questions or author-controlled preset variables.
  4. Use + → Variable management → Set a variable value to set Topic.requestId to Text(GUID()) using the Formula tab. Run that node once when a search starts. Any explicit retry of that same search must pass the existing value.
  5. Use + → Add a tool → Connector and select the action. Map its Request key custom value to Topic.requestId. Map each exposed field to Topic.zone, Topic.light, Topic.soil, Topic.size, Topic.preferNative, and Topic.preferFall. Keep optional fields unset when omitted. If Studio exposes one criteria record, use the following Formula-tab record for the demonstrated fully specified case. For the required-only path supply a record containing only zone, light and soil. If optional values are rendered as blanks, check the emitted request in the tenant and omit them or normalize them before sending.
Bind the fully specified example to the action’s body record. Expected The keys match the API request in Step 7. Evaluation inside Studio is pending.
Studio · Find a plant · criteria inputPower Fx
{ zone: Topic.zone, light: Topic.light, soil: Topic.soil,
  size: Topic.size, native: Topic.preferNative, fall: Topic.preferFall }
  1. Save the connector output to a topic variable or use the action-generated output variables. Add a condition on the kind field. A match path formats each returned match from matches using its name, reason and source. Use the ordered fixture list during review and label fixture links by ID, since the returned fragments resolve to the local tutorial rows. A no-match path returns the API’s message and offers ordinary search. Keep the topic grounded in the tool output. Disable ungrounded replies for this path.
  2. Under Topics → System → On Error, use a safe message that offers ordinary plant search for a failed request. Keep a correlation code for the operator and restrict detailed errors to makers. In the Test pane, inspect the non-2xx behavior before declaring the error path ready. An auth connection card may ask for credentials before the operation is invoked.

The exact rendering of action inputs and output variables is tenant verification. The Power Fx above is documented authoring syntax. It has not been evaluated inside Studio. Connector action authoring · Configure tool inputs · Power Fx GUID · System topics

Checkpoint The native pilot must show action FindPlants with the same six criteria as Step 7 and one server-side admission for its request key.

09

Test conversations

In Studio, open Test your agent. For a topic, turn on topic tracking and inspect its variables. Under generative orchestration, inspect the activity map and confirm the tool was invoked once. Start a fresh session after modifying an action or connection. Use approved test identities A and B and save only redacted evidence. If you have one test identity, record the second-user test as pending. Test a Studio agent

Test input or eventExpected reply and tool behavior
Wet shade, Zone 7, preferred height 5 ft, native and fallOne call. G-103 first with the six-foot tradeoff. G-104 second. Both include fixture sources.
“My spot is shady and wet.”Ask for zone. Zero action calls until the user supplies it.
Dry shade, Zone 7One call. Empty no-match array. G-105 remains excluded.
Wet shade, Zone 20Clarify supported zone range. Zero topic action calls. A direct API test produces 400.
Paused action or simulated catalog outageThe API produces 503. The Studio safe error path sends the plain-search link and no plant claims.
Many distinct valid requests and replay429 at the configured limits. Same key with same normalized criteria reuses the response. Same key with changed criteria produces 409.
Two reviewers and credential rotationEach connection maps to its own subject. A rotated key retains subject limits. An old or revoked credential fails with 401.

Checkpoint Keep separate timestamps and evidence for original browser fixture, HTTP tests, connector test tab, Studio topic and authenticated channel. Mark each unrun case as pending.

10

Inspect diagnostics and run tests

Run the verification harness against loopback from the source root. It builds the C# project and starts fresh isolated API processes with synthetic configuration. It makes no calls to Studio or Aurora.

Run local HTTP regressions, plus the optional separate browser-fixture logic tests. Expected 13 Python harness cases and five original JavaScript cases pass.
Terminal · source rootPowerShell
python ./tests/verify.py
node --test ./original-fixture/fixture.test.mjs
Compare your HTTP run to this observed summary. Expected The exact duration can vary.
verification/http-tests.txt · observed summaryOutput
Ran 13 tests in 5.148s

OK

Use the API’s trace ID to join a reviewed status event to the request time, then compare admissions and actual catalog calls. Collect low-cardinality counts for outcome, new reservations, replays, rate limit, per-user quota, global quota, switch-off, and backend failure. Add latency and in-flight metrics at the boundary for a hosted release. Verify that platform request tracing, dependency instrumentation and any reverse proxy omit request bodies, query text, raw keys, tokens and authorization headers. Keep subjects and full request IDs out of metric labels. The sample tests inspect the fixture’s structured events and response shape.

Read these three actual tests for concurrent replay and separate per-user and global limits. The complete harness is downloadable. Expected Each assertion passed against the local Kestrel process.
tests/verify.py · lines 281–309Python
    def test_concurrent_replays_reserve_once(self):
        with LabProcess(PerUserDailyQuota=1, GlobalDailyQuota=1) as app:
            idem = str(uuid.uuid4())
            responses = fire_concurrently(lambda value: app.find(idem=value), [idem] * 24)
            self.assertTrue(all(response[0] == 200 for response in responses), responses)
            self.assertTrue(all(response[2] == responses[0][2] for response in responses))
            originals = [response for response in responses if "idempotency-replayed" not in response[1]]
            self.assertEqual(len(originals), 1)
        self.assert_lookups(app, 1)

    def test_concurrent_per_user_quota_does_not_limit_another_user(self):
        with LabProcess(PerUserDailyQuota=3, GlobalDailyQuota=40) as app:
            responses = fire_concurrently(app.find, ["a"] * 24)
            self.assertEqual(sum(response[0] == 200 for response in responses), 3)
            for response in responses:
                if response[0] != 200:
                    self.assert_problem(response, 429, "per_user_quota")
            self.assertEqual(app.find(caller="b")[0], 200)
        self.assert_lookups(app, 4)

    def test_concurrent_global_quota_is_shared_before_catalog_lookup(self):
        with LabProcess(PerUserDailyQuota=30, GlobalDailyQuota=5) as app:
            responses = fire_concurrently(app.find, ["a", "b"] * 12)
            self.assertEqual(sum(response[0] == 200 for response in responses), 5)
            for response in responses:
                if response[0] != 200:
                    self.assert_problem(response, 429, "global_quota")
        self.assert_lookups(app, 5)

Checkpoint A burst cannot overspend either counter. Denials add zero catalog calls. In a failure the API reports an outage, and its bounded response carries an operator trace without credentials.

11

Stage the release

Build a local release ZIP first. Its root contains the published application files. Hash the ZIP and record the SDK, source revision and fixture test results. These commands only build and archive locally.

Create a deployable Release ZIP and hash it locally. Expected A ZIP with the API DLL, dependencies and settings at its root. A separately built ZIP was unpacked and smoke-tested locally.
Terminal · source rootPowerShell
pwsh -File ./package-api.ps1

For an approved fixture-only pilot, use an existing organization-controlled App Service with .NET 10 and an isolated deployment slot. Before any cloud command, have the owner record the exact subscription, resource group, app, slot, approved inbound HTTPS route, fixture-only config and permission to use the tenant’s pilot capacity. Set TLS-only ingress, one API instance, distinct pilot secrets, slot-sticky configuration and PlantFinder__Enabled=false. Capture the previous package and solution versions. Deploy to the approved slot and confirm its disabled action path before enabling a narrow reviewer window. Use the illustrative command below only in that approved slot. App Service .NET runtime and ZIP · Deployment slots

Use only after the operator supplies the approved existing target variables. This command has been checked against Microsoft documentation. Expected A deployment record for the intended slot and a startup smoke check. Hosted execution remains pending.
Azure CLI · approved slot onlyPowerShell
az webapp deploy --resource-group $env:PLANT_LAB_RESOURCE_GROUP `
  --name $env:PLANT_LAB_WEB_APP --slot $env:PLANT_LAB_SLOT `
  --src-path ./PlantFinder.Api.zip --type zip
  1. Confirm the fixture slot’s health endpoint and probe a request with a synthetic approved connection. Once temporarily enabled, compare a successful request and replay to the loopback baseline. Pause after the smoke test if the review window has ended.
  2. Review Power Platform data policies with the owner. Allow only the bounded connector and approved host on the intended environment and channel under the applicable policy. Move the connector-only solution first, create the target connection for import, then import the agent and connection-reference solution. Confirm every tester creates their own end-user connection. Connector solution lifecycle · Studio solution import and export · Studio data policies
  3. Save the agent and run Step 9 in the Test pane. Only with the approved audience and capacity evidence, publish to the restricted authenticated pilot channel. Publishing applies to connected channels. Confirm enabled channels and reviewer access before publishing, then test in a fresh authenticated session. Keep the pilot synthetic until the actual phased integration has passed private-network, data-owner and ledger checks. Studio publish and channels

Checkpoint The local release artifact has a SHA-256, the test slot evidence identifies the exact build and the scoped channel has been confirmed by its owner. Azure and Studio steps here are operator instructions with execution pending.

12

Verify and roll back

  1. Verify identity and data. Check two independent connections, allowed fields and sources, zero calls for a missing criterion, and no credentials or raw payload in telemetry. For the future Aurora cutover, capture a redacted allowlisted view contract, sample-size evidence for approved public links, verification of TLS and private routes, and a denied base-table read and write using the service identity in authorized staging.
  2. Verify admissions. Exercise the per-user and global counters, replay, conflict, rate limit and paused or failed provider. Confirm denial before either metered boundary that the release is claiming. For the companion gateway, compare outbound dispatch counts and provider-side telemetry during the zero-dispatch tests.
  3. Pause on a bad release. Set the shared gate off in a durable implementation. In the isolated sample slot, set PlantFinder__Enabled=false and wait for the setting change and restart to take effect. Verify 503 with an authorized fresh key and zero new catalog starts. Keep the plain-search link operating. Revoke a compromised key promptly and stop pilot channel exposure if needed.
  4. Restore the previous package and topic. Redeploy the saved, hashed pilot ZIP to the same disabled slot. If an approved swap was performed, reverse it using the recorded slot pair and confirm both gate settings. Restore the reviewed connector/topic/solution components and republish to the approved channel only as needed. Start a new test session and retest fallback while paused. Re-enable only after the owner accepts the corrected evidence.

Record the operator, UTC time, artifact SHA-256, solution and connector version, scope, expected and observed outcomes, redacted correlation IDs and decision. Native Studio evidence, actual Aurora mapping and a durable multi-replica gate are still pending.

Checkpoint A reviewer can reproduce the local result now. An owner can use the release checklist to collect the separate hosted and live evidence.

Hosted integration notes

This runbook is for a future authorized staging deployment. The C# lab runs against four synthetic records on localhost. The hosted commands and database adapter design below were reviewed against official documentation. The Lab evidence covers the local fixture and HTTP app. Record Azure, Copilot Studio, private networking and Aurora evidence separately before claiming those integrations.

1. Separate the catalog, action and metered entry point

Use ordinary Gardenality filtering as the default user path. It can still incur infrastructure costs, but it uses no Copilot credits. For the connected pilot, allow only approved accounts. Use an end-user connector connection and derive the caller from a validated principal. In the fixture, a unique random key resolves to a server-controlled subject. For an Entra deployment, validate the bearer token issuer, signing key, audience, expiry, allowed tenant, delegated scope and approved connector application, then enforce the pilot allowlist and subject key using tid plus oid. A shared connection obscures individual identity and is incompatible with per-user quota enforcement.

Apply one gate before a metered operation your own backend dispatches. A Plant Finder gate controls calls to that adapter. A Studio agent turn can start incurring usage before it invokes the connector. To enforce an application-level limit on that turn, restricted users must enter through the controlled backend entry point with the same authenticated identity, and that backend must acquire a permit before submitting the turn. A directly reachable Studio channel is a separate path. Environment billing and cost alerts are monitoring and administrative controls. Review their separately documented behavior and measure any metered units before adopting a spend claim. Copilot Studio billing and licensing

Optional server-only Studio companion

This is a design for a future staging harness. The offline fixture has no Microsoft client or metered calls. Keep the native connector test separate from the companion gateway test. Have the channel owner verify that the chosen Copilot Studio standard-harness channel supports the required user authentication and connection-card flow, including the application's end-user authorization. Use ordinary search if those prerequisites or a bounded charge model cannot be verified.

Proposed application operation Direct Line v3 operation, invoked by the backend
POST /v1/assistant/conversations Reserve and claim admission before POST /v3/directline/conversations. Opening a conversation can trigger agent initialization. Store the returned conversation ID and credentials server-side.
POST /v1/assistant/conversations/{handle}/turns Authenticate the caller, check handle ownership, and require an idempotency key. Reserve and claim a permit before POST /v3/directline/conversations/{conversationId}/activities. Send a single bounded message activity, with from.id supplied by the server. Store the returned provider activity ID on the receipt.
GET /v1/assistant/conversations/{handle}/turns/{receipt} Verify the same caller/handle/receipt ownership. Poll with deadlines and a stored watermark using GET /v3/directline/conversations/{conversationId}/activities?watermark=…. Keep access to unneeded activities and tokens inside the companion. A status read never submits another activity.

Use the documented Direct Line base URL for the agent region. Enable Settings → Security → Web channel security → Require secured access. Send Bearer credentials server-to-server. Store the Direct Line secret in the vault and wait for the setting to take effect, then verify an unauthorized request fails. If using conversation-scoped tokens, use POST /v3/directline/tokens/generate and POST /v3/directline/tokens/refresh from the backend. Use a random dl_ channel identity per conversation and map it to the application's authenticated subject in your store. Keep the channel secret, conversation credentials and WebSocket stream URL server-side. The channel credential and user ID have separate jobs from end-user sign-in. Do not accept a browser-supplied Microsoft conversation ID, user ID or target URL. Disable or restrict direct channels the pilot audience could use to bypass admission and verify that they cannot start a turn outside the companion. Direct Line v3 reference · Copilot Studio channel security · Direct Line token parameters · Agent user authentication

Route any operation that can trigger agent work through the same admission and outcome protocol, including application-driven custom events. A Direct Line activity identifier is a receipt, not evidence of end-to-end idempotency or final billing. On a lost reply, timeout, or uncertain response, keep the reservation, put the receipt in an unknown state and offer ordinary Plant Finder. Reconcile it with provider activity and approved usage evidence. Automated resubmissions stay disabled. Set and verify allowlist, per-user and global admission, bounded message sizes and polling, and a kill switch before trial turns. Track provider billing separately from exact application admission counts.

2. Keep Aurora private and read only

  1. Ask the database owner to record the actual Aurora engine and version, private reader endpoint, port, server CA, current published-record predicate and canonical Gardenality URL contract. The PostgreSQL example below is conditional on an Aurora PostgreSQL target. An Aurora MySQL target needs an engine-specific adapter, privilege script and execution evidence.
  2. Give the connector a reviewed HTTPS ingress for the bounded API. Confirm the correct Power Platform datacenter and apply the documented regional connector egress rules at the API ingress. Regional App Service VNet integration handles outbound traffic. Separately, use an approved routed private link between the Azure VNet and AWS VPC, such as a compatible site-to-site IPsec connection. The network owner must verify non-overlapping CIDRs, return routes, failover, firewall rules and DNS resolution from the running app. Allow only the app's expected source range and catalog port at Aurora. Prefer the real Aurora DNS hostname for TLS name verification. Leave the RDS instance private. Connector egress ranges · App Service access restrictions · App Service VNet integration · AWS Site-to-Site VPN · Azure site-to-site setup
  3. Create a dedicated login with no base-table rights, elevated memberships, ownership or write grants. Give it schema USAGE and SELECT on one owner-approved view. Use the Aurora reader endpoint where appropriate. It can route to the writer when no replicas exist, so the database grants remain the permission boundary. Require TLS and Npgsql SSL Mode=VerifyFull with the AWS CA bundle. Set connection, statement and request timeouts. Aurora PostgreSQL permissions and TLS · Aurora reader endpoints · Npgsql TLS
  4. Map only reviewed fields: catalog ID, public display name, zone minimum and maximum, normalized light and soil, known mature height, approved geography-qualified native tag, fall-interest tag and canonical public URL. Treat missing values as unknown. Return up to three matching records with grounded reasons, including a size tradeoff when relevant. Select columns explicitly and validate every returned URL against the owner-approved host and path. Keep free-form notes, user accounts, contact details, provenance internals and unpublished entries outside the projection. Match legacy ASPX filter names, combination rules, sorts, pagination, empty states and public links independently before claiming parity. The fixture covers one narrow matching contract.

Conditional PostgreSQL example

The schema, role and column names are placeholders. The two SQL blocks passed a local PostgreSQL 19.0 check in PGlite 0.6.1 against synthetic records. Ranked order, no match, exact projected fields, unpublished record exclusion, denied base reads and denied view updates passed under SET ROLE. A real login and Aurora network/TLS remain release checks. The view owner needs appropriate base-table access. Audit rights inherited via PUBLIC or other role memberships. Keep this login out of unrelated databases or schemas with public access. The catalog role is separate from the writable quota store.

Runbook example. Expected See the verification scope beside this example.
hosted-boundaries.md, line 34SQL
CREATE ROLE plant_finder_view_owner NOLOGIN;
CREATE ROLE plant_finder_catalog LOGIN;
CREATE SCHEMA lab_api AUTHORIZATION plant_finder_view_owner;
REVOKE ALL ON SCHEMA lab_api FROM PUBLIC;

GRANT USAGE ON SCHEMA approved_source TO plant_finder_view_owner;
GRANT SELECT (catalog_id, display_name, zone_min, zone_max, light_code,
              soil_code, mature_height_ft, native_region_tag, fall_interest,
              canonical_public_url, is_published)
ON approved_source.plants TO plant_finder_view_owner;

SET ROLE plant_finder_view_owner;
CREATE VIEW lab_api.public_plants WITH (security_barrier = true) AS
SELECT catalog_id, display_name, zone_min, zone_max, light_code,
       soil_code, mature_height_ft, native_region_tag, fall_interest,
       canonical_public_url
FROM approved_source.plants
WHERE is_published IS TRUE;
REVOKE ALL ON lab_api.public_plants FROM PUBLIC;
RESET ROLE;

GRANT USAGE ON SCHEMA lab_api TO plant_finder_catalog;
GRANT SELECT ON lab_api.public_plants TO plant_finder_catalog;
ALTER ROLE plant_finder_catalog SET default_transaction_read_only = on;
ALTER ROLE plant_finder_catalog SET statement_timeout = '2s';

Set the login's secret outside SQL history or use already approved short-lived identity. The following query uses typed parameters in this order: required zone, light and soil, then optional preferred height, qualifying native-region tag and fall interest. Use the ranking rule only after verifying the approved native tag's meaning. The SQL returns facts for the app to validate and serialize. It leaves provenance and reasons to the app.

Runbook example. Expected See the verification scope beside this example.
hosted-boundaries.md, line 64SQL
PREPARE find_plants(integer, text, text, numeric, text, boolean) AS
SELECT catalog_id, display_name, zone_min, zone_max, light_code, soil_code,
       mature_height_ft, native_region_tag, fall_interest, canonical_public_url
FROM lab_api.public_plants
WHERE $1 BETWEEN zone_min AND zone_max
  AND light_code = $2
  AND soil_code = $3
  AND mature_height_ft IS NOT NULL
  AND canonical_public_url IS NOT NULL
ORDER BY (
    CASE WHEN native_region_tag = $5 THEN 2 ELSE 0 END
  + CASE WHEN $6 IS TRUE AND fall_interest IS TRUE THEN 2 ELSE 0 END
  + CASE WHEN mature_height_ft <= $4 THEN 1 ELSE 0 END
) DESC, catalog_id::text COLLATE "C" ASC
LIMIT 3;

As the real login, verify one fixture-safe SELECT succeeds, forbidden base access and a write attempted in a rollback-only transaction fail, and an unpublished sentinel cannot be returned. Inspect query plans and the public JSON response before accepting the adapter. PostgreSQL view security · PostgreSQL GRANT · PostgreSQL PREPARE

3. Make paid-call reservations durable before scaling

The local lab serializes a process-local admission decision. Its counters and receipt history reset when that process restarts. Keep paid paths disabled during a single-process synthetic staging exercise. For connected usage or multiple replicas, use a transactional writable store separate from Gardenality. Implement the following sequence with a short PostgreSQL transaction or an equivalent primitive. Use UTC windows from the authoritative server clock and a singleton gate-control row per operation. All callers, workers and control writes share the lock order below. PostgreSQL row locks · PostgreSQL transaction isolation

Store record Key and contents
Control Operation. Enabled state, positive limits, version and approval reference.
Bucket Operation, UTC window and kind, stable opaque user ID or reserved global identifier. Used units.
Receipt Operation, authenticated subject, idempotency key. Canonical payload hash, captured window, reserved units, dispatch state, bounded response and safe correlation ID.
  1. Authenticate and validate first. Apply request rate limits per user at ingress, including replay traffic, so retries cannot flood the store. Use bounded, expiring rate counters and edge rate limits in addition to authenticated limits. Begin a transaction. Lock the control row with SELECT ... FOR UPDATE. Stop with unavailable if control is disabled, unreadable or unreachable. Check the same subject's idempotency receipt and hash. Replay a completed matching receipt and reject a conflicting hash. A pending receipt must never create a second outbound attempt.
  2. Initialize and lock that UTC day's global bucket followed by the user's bucket. Reject if either would exceed its configured positive limit. If an operation can bill variable units, reserve a measured worst-case bound and enforce corresponding upstream bounds. Increment both counters and insert the unique receipt in the same transaction. Return a permit only after commit succeeds. A lost commit acknowledgement must be resolved by looking up the receipt. A renewed key is not a safe recovery from an unknown commit.
  3. The single egress path takes the control lock, rechecks the kill switch, and conditionally moves one receipt from reserved to dispatch_claimed. Commit before attempting the bounded provider call. Disable automatic paid-call retries unless the provider supplies an enforceable idempotency contract and the reserved units cover every charge. Keep the same key inside the provider request when supported. A crash or timeout after a claim is an unknown outcome. Keep the reservation, reconcile against provider evidence, and never resend automatically. Complete or record failure with a conditional state change on that receipt. Do not hold a database transaction open across a remote call.
  4. Disable by updating the locked control row. Unclaimed reservations cannot dispatch after the committed switch. A claim that committed before the switch may still be in flight or between claim and send. For a strict blackout, disable the application gate and block new egress at the dispatch gateway, then drain in-flight operations. A managed agent channel that can bypass that gateway must also be disabled for the blackout to cover it. Reconcile claimed receipts before re-enabling.
  5. Keep receipts for an explicit retry horizon that crosses day rollover. A request retried after the horizon can consume a new allowance, so reject expired reused keys or make the horizon visible to clients. Delete terminal receipts by bounded retention job and retain unknown outcomes until reconciled. Verify raced duplicates, the last global permit from two replicas, UTC rollover, store outage, worker crash after claim, and kill-switch behavior with a fake dispatch target before exposing any paid path.

4. Stage, verify and roll back

  1. In an approved non-production Azure subscription, select the existing web app and slot reserved for the exercise. Confirm the supported runtime matches net10.0 before packaging. Use only the synthetic catalog for this pilot. Turn off paid provider dispatch and keep the production site outside the pilot route. Record the version, slot, connector operation ID, scenario run and intended team before starting. App Service .NET configuration
  2. From the source pack root, create a compiled ZIP with the publish directory contents at its root. The local publish and ZIP commands ran with .NET SDK 10.0.400. The extracted portable DLL started on loopback. It returned 200 from /healthz, 401 for a request without credentials, and 200 with G-103 then G-104 for the authenticated match. A repeated key returned an identical 200 response and the replay header. The commands targeting Azure were documentation-checked. They reference pre-existing named resources via environment variables and require an authorized tenant session.
Runbook example. Expected See the verification scope beside this example.
hosted-boundaries.md, line 105PowerShell
dotnet publish ./PlantFinder.Api/PlantFinder.Api.csproj -c Release `
  --no-self-contained -p:UseAppHost=false -o ./publish
Compress-Archive -Path ./publish/* -DestinationPath ./PlantFinder.Api.zip -Force
Get-FileHash ./PlantFinder.Api.zip -Algorithm SHA256
az webapp list-runtimes --os linux --output table
az webapp deploy --resource-group $env:PLANT_LAB_RESOURCE_GROUP `
  --name $env:PLANT_LAB_WEB_APP --slot staging `
  --src-path ./PlantFinder.Api.zip --type zip
  1. Enforce HTTPS at the hosting edge. On Linux, start with dotnet PlantFinder.Api.dll if the app needs an explicit startup command. Under the staging slot's environment variables, use slot-sticky PlantFinder__Enabled, PlantFinder__SimulateCatalogUnavailable, PlantFinder__PerUserRequestsPerMinute, PlantFinder__PerUserDailyQuota, PlantFinder__GlobalDailyQuota, and one PlantFinder__Callers__0__Subject plus PlantFinder__Callers__0__KeySha256 mapping per key with successive indexes. Set the fixture enabled only for controlled scenario runs. Use a Key Vault reference for each stored caller digest. Leave PlantFinder__AllowRemoteHttp false unless you have verified that the edge terminates HTTPS and clients cannot reach the HTTP backend directly. App Service forwards HTTPS state to ASP.NET Core on supported hosting paths. Configure no database or paid provider in the fixture deployment. Use slot-sticky Key Vault references with the slot's managed identity granted only secret retrieval, plus separate role assignments and credentials for each environment. App Service resolves unversioned references to the latest version and may cache them for up to 24 hours. Force a reference refresh or a planned restart when rotation must take effect immediately, then verify without printing values. App Service .NET configuration · ZIP deployment · Key Vault references
  2. Rotate with overlap. Issue a new key for the same synthetic caller and add its digest as a second mapping. Reconnect the user's Power Platform connection with the new key. Verify the same limits apply across both keys and a successful action uses the new connection. Remove the old mapping, refresh or roll the app as needed, and verify the old key is rejected. The lab counter is process-local, so a restart during this pilot resets its counts. For Entra or database secrets, separately rotate the relevant credential and verify a fresh connection before retiring the old version. Keep credentials out of exported solutions, logs, screenshots and ZIP files.
  3. Test stage HTTPS /healthz and /v1/plants/find with synthetic credentials and the provided expected scenarios. From the approved Power Platform environment, test the connector operation and a fresh Studio agent conversation separately. Record the return code, scenario output and correlation ID. Check that nonmembers fail, the action enforces both limits, replay creates no new downstream call, unsupported input gives a clear message and an outage returns the fallback. Stay in staging for this review.
  4. During a later approved release, record the production preimage (application ZIP/hash, settings keys, solution exports, connection-reference bindings and channel status). Verify the target routes, environment identity, quotas and kill-switch state. Use App Service slot-swap only if the hosting owner approved that path and the current build is valid with the target slot settings. A successful swap places the old build in staging. Leave it available until verification is complete. Then import the approved connector and agent solutions in dependency order, bind the target connections, and publish only the approved channel. Run fresh end-to-end checks on the published version. App Service slots · Copilot Studio solution import and export
  5. On rollback, turn the action/dispatch switch off and confirm the ordinary search link works. Keep the incident evidence. If the app was swapped, swap the same two slots again to restore the earlier build, with sticky environment settings intact. If production was never swapped, restore the last verified staging ZIP. Restore or remove the changed tool/topic and publish the earlier reviewed configuration to the approved channel. Verify a fresh session and normal search, then re-enable only after the release owner clears the fault. Restore app/agent behavior without erasing the cap ledger or replay receipts.

The CLI command for a later approved forward swap and for its immediate reversal is the same. Verify that staging still contains the correct release before using it. The command was documentation-checked. The lab made no swap.

Runbook example. Expected See the verification scope beside this example.
hosted-boundaries.md, line 124PowerShell
az webapp deployment slot swap --resource-group $env:PLANT_LAB_RESOURCE_GROUP `
  --name $env:PLANT_LAB_WEB_APP --slot staging --target-slot production

Source and verification notes

The original offline Gardenality browser fixture supplied the scenario and four synthetic catalog rows. Its five logic checks and this package’s HTTP suite were run independently.

The five displayed C# files contribute 272 distinct default-visible source lines. The count removes duplicates after whitespace normalization and excludes blank, comment-only and punctuation-only lines, plus commands, generated materials and output. The executable path and passing assertions establish the depth of the lesson.

Brand marks are sourced from the existing Zyel Lab bundle, the Gardenality asset retained by Zyel, and the official Power Platform icon kit. Microsoft’s icon appears with the product name in the architecture. Preserved Gardenality mark · Microsoft icon kit

Download the lesson files

Download complete source and tests ZIP

Preserve the archive paths when extracting. ZIP SHA-256 cbe56a96772c8b2dc286930f8d0d5f4c1b2fb42cf927fe221f45b95d7aa79af6