Snippet

Prepare in a tool, commit only from a button

A complete C# confirmation authority: the model can prepare a proposal, but only the owner's structured action commits it, after revalidation and one conditional write.

csharpNov 6, 2026MIT

AI-generated, human-reviewed: the first draft was generated by an AI agent; I fact-checked, tested, and edited it. AI use policy

What it does#

Holds one ledger of proposals per conversation, bound to the signed-in owner.

  • PrepareAsync is what your prepare_transfer tool calls. It validates the recipient, amount, and currency, supersedes any card still waiting for a decision, and writes a prepared proposal. It cannot commit.
  • ConfirmAsync is what your API calls for a structured Confirm or Cancel action from the card buttons. It re-reads the stored proposal, revalidates expiry, policy version, recipient snapshot, cap, and currency, and records exactly one outcome with a compare-and-swap write. A committed proposal gets a MOCK- receipt.
  • Repeating a decision returns the stored outcome. Eight duplicate clicks still make one receipt.
  • Every method returns a ProposalView, which leaves out the destination and the snapshot versions. The full ProposalCard stays in the ledger, so a tool that returns the result to the model cannot leak the destination.
  • AuthorityUnavailableException means the outcome is unknown, not failed. A store read or write that throws becomes this exception, because a write that timed out may still have landed. Retry the same confirmation ID. Cancellation requested by the caller is passed through unchanged.

You need#

  • .NET 10 (the in-memory store uses System.Threading.Lock)
  • A durable store with conditional writes for production, for example a document database item replaced with an If-Match ETag; implement ILedgerStore over it, returning false only for an ETag conflict and throwing for anything else
  • A validated owner key from the caller’s token, never from chat text or tool arguments
  • Your own recipient directory behind IRecipientDirectory

Where it goes#

Register ConfirmationAuthority as a singleton next to your store and directory. Give the model a prepare_transfer tool that calls PrepareAsync. Call ConfirmAsync only from the API path that receives {"action": {"kind": "confirm", "confirmationId": "..."}} with no message, and run the model afterward only to explain the outcome.

ConfirmationAuthority.cs
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Sarang Datye
using System.Globalization;

/// <summary>One synthetic recipient as the host's directory knows it. The model never sees Destination.</summary>
public sealed record Recipient(
    string Id, string DisplayName, string Destination, string Version, bool Active, bool TransferEligible);

public interface IRecipientDirectory
{
    string Version { get; }
    Recipient? Exact(string id);
}

/// <summary>An immutable, server-held proposal. Only the host changes its status. It never leaves the authority.</summary>
public sealed record ProposalCard(
    string ConfirmationId, string Status, long AmountMinor, string Currency,
    string RecipientId, string RecipientName, string Destination, string RecipientVersion,
    string PolicyVersion, DateTimeOffset ExpiresAt, string? ReceiptId = null, DateTimeOffset? CommittedAt = null);

/// <summary>What the model, the browser, and the caller see: no destination and no snapshot versions.</summary>
public sealed record ProposalView(
    string ConfirmationId, string Status, long AmountMinor, string Currency,
    string RecipientId, string RecipientName, DateTimeOffset ExpiresAt,
    string? ReceiptId = null, DateTimeOffset? CommittedAt = null);

/// <summary>One ledger per conversation, bound to the signed-in owner that created it.</summary>
public sealed record ProposalLedger(string ConversationId, string OwnerKey, IReadOnlyList<ProposalCard> Proposals);

public sealed record LedgerVersion(ProposalLedger Ledger, string ETag);

/// <summary>Durable authority. WriteAsync returns false only for a known compare-and-swap conflict.</summary>
public interface ILedgerStore
{
    Task<LedgerVersion?> ReadAsync(string conversationId, CancellationToken cancellationToken);
    Task<bool> WriteAsync(ProposalLedger ledger, string? etag, CancellationToken cancellationToken);
}

public sealed class ProposalValidationException(string message) : Exception(message);

/// <summary>The write outcome is unknown, not failed. Keep the confirmation ID and retry it.</summary>
public sealed class AuthorityUnavailableException(Exception? innerException = null)
    : Exception("Authority unavailable; retry the same confirmation ID.", innerException);

/// <summary>
/// The model may prepare a proposal through a tool. Only ConfirmAsync, called for a structured
/// button action from the owner, can record an effect, and it revalidates everything first.
/// </summary>
public sealed class ConfirmationAuthority(
    ILedgerStore store, IRecipientDirectory directory, TimeProvider clock,
    long maximumAmountMinor = 500_000, int lifetimeSeconds = 300)
{
    private const int MaximumProposals = 32;

    public string PolicyVersion =>
        $"mock-v1:{directory.Version}:{maximumAmountMinor.ToString(CultureInfo.InvariantCulture)}";

    public async Task<ProposalView> PrepareAsync(string ownerKey, string conversationId,
        string recipientId, long amountMinor, string currency, CancellationToken cancellationToken)
    {
        var recipient = directory.Exact(recipientId);
        if (recipient is null || !recipient.Active || !recipient.TransferEligible ||
            amountMinor <= 0 || amountMinor > maximumAmountMinor || currency != "USD")
            throw new ProposalValidationException("Use an eligible recipient and a positive USD amount within the cap.");

        var card = new ProposalCard(Guid.NewGuid().ToString("N"), "prepared", amountMinor, "USD",
            recipient.Id, recipient.DisplayName, recipient.Destination, recipient.Version,
            PolicyVersion, clock.GetUtcNow().AddSeconds(lifetimeSeconds));
        for (var attempt = 0; attempt < 5; attempt++)
        {
            var version = await ReadOwnedAsync(ownerKey, conversationId, cancellationToken);
            var ledger = version?.Ledger ?? new ProposalLedger(conversationId, ownerKey, []);
            if (ledger.Proposals.Count >= MaximumProposals)
                throw new ProposalValidationException("Proposal limit reached; start a new conversation.");

            // A newer proposal supersedes any card that is still waiting for a decision.
            var next = ledger with
            {
                Proposals = ledger.Proposals
                    .Select(p => p.Status == "prepared" ? p with { Status = "superseded" } : p)
                    .Append(card).ToList(),
            };
            if (await WriteStoreAsync(next, version?.ETag, cancellationToken)) return View(card);
        }
        throw new AuthorityUnavailableException();
    }

    public async Task<ProposalView> ConfirmAsync(string ownerKey, string conversationId,
        string confirmationId, string action, CancellationToken cancellationToken)
    {
        if (!Guid.TryParseExact(confirmationId, "N", out _) || action is not ("confirm" or "cancel"))
            throw new ProposalValidationException("Invalid confirmation action.");

        for (var attempt = 0; attempt < 5; attempt++)
        {
            var version = await ReadOwnedAsync(ownerKey, conversationId, cancellationToken)
                ?? throw new ProposalValidationException("Confirmation unavailable.");
            var card = version.Ledger.Proposals.SingleOrDefault(p => p.ConfirmationId == confirmationId)
                ?? throw new ProposalValidationException("Confirmation unavailable.");

            // Repeating a decision returns the stored outcome, including the original receipt.
            if (card.Status != "prepared") return View(card);

            var recipient = directory.Exact(card.RecipientId);
            var status = action == "cancel" ? "cancelled"
                : card.ExpiresAt <= clock.GetUtcNow() ? "expired"
                : card.PolicyVersion != PolicyVersion || card.Currency != "USD" ||
                  card.AmountMinor <= 0 || card.AmountMinor > maximumAmountMinor ||
                  recipient is null || !recipient.Active || !recipient.TransferEligible ||
                  recipient.Version != card.RecipientVersion || recipient.Destination != card.Destination
                    ? "stale" : "committed";
            var decided = card with
            {
                Status = status,
                ReceiptId = status == "committed" ? "MOCK-" + card.ConfirmationId : null,
                CommittedAt = status == "committed" ? clock.GetUtcNow() : null,
            };
            var next = version.Ledger with
            {
                Proposals = version.Ledger.Proposals.Select(p => p.ConfirmationId == confirmationId ? decided : p).ToList(),
            };

            // Exactly one conditional write wins; a losing writer re-reads and returns the winner's outcome.
            if (await WriteStoreAsync(next, version.ETag, cancellationToken)) return View(decided);
        }
        throw new AuthorityUnavailableException();
    }

    public async Task<ProposalView[]> StatusAsync(string ownerKey, string conversationId, CancellationToken cancellationToken)
    {
        var version = await ReadOwnedAsync(ownerKey, conversationId, cancellationToken);
        return version?.Ledger.Proposals
            .Select(p => View(p.Status == "prepared" && p.ExpiresAt <= clock.GetUtcNow() ? p with { Status = "expired" } : p))
            .ToArray() ?? [];
    }

    private static ProposalView View(ProposalCard card) => new(
        card.ConfirmationId, card.Status, card.AmountMinor, card.Currency, card.RecipientId,
        card.RecipientName, card.ExpiresAt, card.ReceiptId, card.CommittedAt);

    private async Task<LedgerVersion?> ReadOwnedAsync(string ownerKey, string conversationId, CancellationToken cancellationToken)
    {
        LedgerVersion? version;
        try
        {
            version = await store.ReadAsync(conversationId, cancellationToken);
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
        catch (Exception exception) { throw new AuthorityUnavailableException(exception); }

        if (version is not null && (version.Ledger.ConversationId != conversationId || version.Ledger.OwnerKey != ownerKey))
            throw new ProposalValidationException("Confirmation unavailable.");
        return version;
    }

    // A write that throws may still have landed, so its outcome is unknown rather than failed.
    private async Task<bool> WriteStoreAsync(ProposalLedger ledger, string? etag, CancellationToken cancellationToken)
    {
        try
        {
            return await store.WriteAsync(ledger, etag, cancellationToken);
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
        catch (Exception exception) { throw new AuthorityUnavailableException(exception); }
    }
}

/// <summary>For tests and local runs only. Production uses a durable store with ETag writes.</summary>
public sealed class InMemoryLedgerStore : ILedgerStore
{
    private readonly Dictionary<string, LedgerVersion> _ledgers = [];
    private readonly Lock _gate = new();
    private long _etag;

    public int Writes { get; private set; }

    public Task<LedgerVersion?> ReadAsync(string conversationId, CancellationToken cancellationToken)
    {
        lock (_gate) return Task.FromResult(_ledgers.GetValueOrDefault(conversationId));
    }

    public Task<bool> WriteAsync(ProposalLedger ledger, string? etag, CancellationToken cancellationToken)
    {
        lock (_gate)
        {
            var current = _ledgers.GetValueOrDefault(ledger.ConversationId);
            if (current?.ETag != etag) return Task.FromResult(false);
            _ledgers[ledger.ConversationId] = new LedgerVersion(ledger, (++_etag).ToString(CultureInfo.InvariantCulture));
            Writes++;
            return Task.FromResult(true);
        }
    }
}

Check that it works#

With InMemoryLedgerStore and a fixed clock, prepare one proposal and call ConfirmAsync eight times in parallel. Every call returns committed with the same ReceiptId, and store.Writes is 2: one prepare, one commit. Advance the clock past the lifetime before confirming and you get expired instead.