Private/Write-KadenOperatorModelOutcome.ps1

function Write-KadenOperatorModelOutcome {
    <#
    .SYNOPSIS
        Record the apply outcome, and copy it beside a completed transaction only.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Private outcome writer. The public apply command owns ShouldProcess.')]
    param(
        [Parameter(Mandatory = $true)][string]$ChildRoot,
        [Parameter(Mandatory = $true)]$Outcome,
        [switch]$SkipBesideJournal
    )
    $latest = Join-Path $ChildRoot (Join-Path '.kaden' 'operator-model-apply.json')
    Write-KadenJsonAtomic -LiteralPath $latest -Object $Outcome
    if ($SkipBesideJournal) { return }

    $txnRoot = Join-Path $ChildRoot (Join-Path '.kaden' 'transactions')
    if (-not (Test-Path -LiteralPath $txnRoot)) { return }
    $chosen = $null
    $chosenWritten = [datetime]::MinValue
    foreach ($dir in @(Get-ChildItem -LiteralPath $txnRoot -Directory -ErrorAction SilentlyContinue)) {
        $journalPath = Join-Path $dir.FullName 'journal.json'
        if (-not (Test-Path -LiteralPath $journalPath -PathType Leaf)) { continue }
        try {
            $doc = Get-Content -LiteralPath $journalPath -Raw | ConvertFrom-Json
        } catch {
            continue
        }
        if ([string]$doc.status -ne 'completed') { continue }
        $written = (Get-Item -LiteralPath $journalPath).LastWriteTimeUtc
        if ($null -eq $chosen -or $written -gt $chosenWritten) {
            $chosen = $dir.FullName
            $chosenWritten = $written
        }
    }
    if ($null -eq $chosen) { return }
    $beside = Join-Path $chosen 'operator-model-apply.json'
    Write-KadenJsonAtomic -LiteralPath $beside -Object $Outcome
}