src/assess/engine/Invoke-Rule.ps1

#Requires -Version 7.0
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# Defined once at file scope, not inside Invoke-Rule: a function defined in a function body is
# re-created on every call (~1.3 ms of a ~2.5 ms manual-rule evaluation, measured), and Invoke-Rule
# runs once per rule per assessment.
# ---- data-completeness helpers (issue #104) --------------------------------------------------
#
# THE PRODUCT RULE: a check must never Pass or Fail on data that was only partly read; it reads
# NotAssessed with the reason. Three mechanisms enforce it, all declared as data:
#
# assert.gate the dataset is closed unless it was read AT ALL (or, for the all-or-nothing
# flags such as governance.policyAssignmentsAvailable, read in FULL).
# assert.completeGate the dataset must have been read in FULL, but only for the outcome that
# unread rows could overturn -- see Get-ScoutUnsoundOutcome.
# _meta.failedQueries a typed Resource Graph query that failed: every rule whose query (or join, or
# denominator) starts at a dataset path listed there reads NotAssessed.

# True when the gate path says "go ahead". The same rule the original gate used: a path that matches
# nothing is closed, and so is a single boolean token that is false. Anything else (rows, a string)
# is "present". Throws when the path itself is invalid -- the caller turns that into an Error finding.
function Test-ScoutGateOpen {
    param($Collect, $QueryContext, [string] $Path)
    # NOT wrapped in @(): Resolve-JsonPath already returns its (possibly empty) array via
    # `Write-Output -NoEnumerate`; wrapping it again nests it, so .Count is never 0.
    $gateMatches = Resolve-JsonPath -InputObject $Collect -QueryContext $QueryContext -Path $Path
    if (@($gateMatches).Count -eq 0) { return $false }
    if (@($gateMatches).Count -eq 1) {
        try { if ($gateMatches[0].ToObject([bool]) -eq $false) { return $false } }
        catch { Write-Verbose "Gate value for '$Path' is not a boolean token -- presence alone means the gate is open." }
    }
    return $true
}

# The plain-words reason a closed gate reads NotAssessed. A flag such as `...sqlTdeComplete`,
# `...policyAssignmentsAvailable` or `...Collected` is followed by a sibling carrying the reason the
# collector wrote (`...sqlTdeReason`, `...policyAssignmentsReason`, `...Reason`); counts and dataset
# names only. A path with no such sibling falls back to a generic sentence, so a NotAssessed finding
# is never silent about why.
#
# Cause tells a renderer which of three situations this is:
# Partial the collector wrote a reason: the dataset was read in part, or not at all, and says how much
# NotCollected a flag is closed and nothing says why
# NoData the gate was "does anything of this kind exist" and nothing did -- not a collection problem
function Get-ScoutGateReason {
    # -Complete: the closed path belongs to a completeGate. An array-shaped completeGate path (a per-type diagnostic-coverage
    # row that says `complete == true`) matches nothing because the dataset was read in part, never because there is nothing
    # to assess, so it is Partial and takes the dataset's own sentence.
    param($Collect, $QueryContext, [string] $Path, [switch] $Complete)
    $reasonPath = $null
    if ($Complete -and $Path -match '^\$\.opsPosture\.diagnosticCoverage\[') { $reasonPath = '$.opsPosture.diagnosticCoverageReason' }
    # `...sqlTdeComplete` -> `...sqlTdeReason`; the all-lower-case flags (`finops.complete`) -> `finops.reason`.
    if ($Path -match '^(?<stem>\$\..+?)(?<flag>Available|Measured|Complete)$') {
        $reasonPath = $Matches['stem'] + $(if ($Matches['flag'] -cmatch '^[a-z]') { 'reason' } else { 'Reason' })
    }
    elseif ($Path -match '^(?<stem>\$\.(?:.+\.)?)Collected$') { $reasonPath = $Matches['stem'] + 'Reason' }
    if ($reasonPath) {
        try {
            $reasonMatches = Resolve-JsonPath -InputObject $Collect -QueryContext $QueryContext -Path $reasonPath
            foreach ($token in @($reasonMatches)) {
                if ($null -eq $token) { continue }
                $text = if ($token -is [Newtonsoft.Json.Linq.JValue]) { [string]$token.Value } else { [string]$token }
                if (-not [string]::IsNullOrWhiteSpace($text)) { return [pscustomobject]@{ Reason = $text; Cause = 'Partial' } }
            }
        }
        catch { Write-Verbose "Reason path '$reasonPath' could not be resolved: $($_.Exception.Message)" }
        return [pscustomobject]@{ Reason = 'The data this check needs was not collected, or was only partly read, in this run.'; Cause = 'NotCollected' }
    }
    if ($Complete -and $Path -match '\]$') { return [pscustomobject]@{ Reason = 'The data this check needs was only partly read in this run.'; Cause = 'Partial' } }
    if ($Path -match '\]$') { return [pscustomobject]@{ Reason = 'Nothing this check applies to was found in the collected data.'; Cause = 'NoData' } }
    return [pscustomobject]@{ Reason = 'The data this check needs was not collected in this run.'; Cause = 'NotCollected' }
}

# Which outcomes could be overturned by rows that were never read. A rule says "pass when there are no
# violating rows" or "pass when at least one good row exists"; partial data can only make the first
# kind pass wrongly and the second kind fail wrongly. Found rows are real either way, so the outcome
# they prove stays reportable.
# notExists, countLessThan Pass can flip to Fail when more rows turn up -> gate Pass
# countEquals 0 same -> gate Pass
# countEquals N (N > 0) more rows can break an exact count either way -> gate Pass and Fail
# exists, countGreaterThan Fail can flip to Pass when more rows turn up -> gate Fail
# percentageAtLeast numerator and denominator are both partial -> gate every score
function Get-ScoutUnsoundOutcome {
    param([string] $AssertType, $Value)
    switch ($AssertType) {
        'notExists'         { return @('Pass') }
        'countLessThan'     { return @('Pass') }
        'countEquals'       { if ($null -ne $Value -and [double]$Value -eq 0) { return @('Pass') } else { return @('Pass', 'Fail') } }
        'exists'            { return @('Fail') }
        'countGreaterThan'  { return @('Fail') }
        'percentageAtLeast' { return @('Pass', 'Partial', 'Fail') }
        default             { return @() }
    }
}

# The dataset a JSONPath starts at, as dotted paths without the leading `$.`: everything before the
# first filter or wildcard. `$.domains.databases.sqlDefenderPricing[?(@.x)]` -> domains.databases.sqlDefenderPricing.
# A bracketed name list (`$.a.b['c','d'][?(...)]`) yields one path per name.
function Get-ScoutRuleRootPath {
    param([string] $Path)
    if ([string]::IsNullOrWhiteSpace($Path) -or -not $Path.StartsWith('$.')) { return @() }
    # \x27 is a single quote: the pattern stays in single quotes so `$(` is not read as a subexpression.
    $m = [regex]::Match($Path, '^\$((?:\.[A-Za-z0-9_]+)+)(?:\[\s*(?<names>\x27[^\]]+\x27)\s*\])?')
    if (-not $m.Success) { return @() }
    $prefix = $m.Groups[1].Value.TrimStart('.')
    if ($m.Groups['names'].Success) {
        return @([regex]::Matches($m.Groups['names'].Value, "'([^']+)'") | ForEach-Object { '{0}.{1}' -f $prefix, $_.Groups[1].Value })
    }
    return @($prefix)
}

# path (lower case) -> reason, for every typed query Invoke-Collect recorded as failed. Built once per
# query context: the rule loop calls this for every rule.
function Get-ScoutFailedQueryMap {
    param($Collect, $QueryContext)
    if ($QueryContext -is [System.Collections.IDictionary] -and $QueryContext.Contains('FailedQueryMap')) { return $QueryContext['FailedQueryMap'] }
    $map = @{}
    $records = Resolve-JsonPath -InputObject $Collect -QueryContext $QueryContext -Path '$._meta.failedQueries[*]'
    foreach ($record in @($records)) {
        if ($null -eq $record -or $record -isnot [Newtonsoft.Json.Linq.JObject]) { continue }
        $reason = [string]$record['Reason']
        foreach ($p in @($record['Paths'])) {
            $key = ([string]$p).ToLowerInvariant()
            if ($key -and -not $map.ContainsKey($key)) { $map[$key] = $reason }
        }
    }
    if ($QueryContext -is [System.Collections.IDictionary]) { $QueryContext['FailedQueryMap'] = $map }
    return $map
}

function Get-ScoutRuleRowKey {
    param($Row, [string]$Path)
    $current = $Row
    foreach ($segment in @($Path -split '\.')) {
        if ($null -eq $current) { return $null }
        if ($current -is [Newtonsoft.Json.Linq.JObject]) {
            $current = $current.GetValue($segment, [System.StringComparison]::OrdinalIgnoreCase)
            if ($null -eq $current) { return $null }
        }
        elseif ($current -is [System.Collections.IDictionary]) {
            if (-not $current.Contains($segment)) { return $null }
            $current = $current[$segment]
        }
        else {
            $property = if ($current.PSObject) { $current.PSObject.Properties[$segment] } else { $null }
            if (-not $property) { return $null }
            $current = $property.Value
        }
    }
    if ($null -eq $current) { return $null }
    return ([string]$current).Trim().ToLowerInvariant()
}

<#
.SYNOPSIS
    Evaluate a single rule against the collect object, returning a finding.
 
.NOTES
    Supports the seven assert types. Tracks ADO Story AB#5030.
 
    AB#6826 (Feature AB#6749, Epic AB#6454) added an eighth, orthogonal concept: an optional
    `assert.gate` JSONPath. When present, the rule's Status is 'NotAssessed' (and the normal
    query/assert evaluation never runs) whenever the gate resolves to NO matches at all, OR
    resolves to a single scalar boolean token whose value is `false` -- for a data source that
    is gated behind a permission system Scout's ordinary Reader role does not satisfy (the
    FinOps EA/MCA billing gate, Azure DevOps access not granted), a `countEquals: 0` or
    `exists` assert cannot tell "the source was blocked" apart from "the source was checked
    and found clean", and collapsing the two into a Pass or a Fail is exactly the false read
    AB#6793 already fixed once for Azure Policy compliance state. `gate` is evaluated with the
    SAME Resolve-JsonPath a rule's own `query` uses -- write it as a plain scalar path to a
    boolean field the collect pipeline computes (`$.finops.available`, `$.devops.available`),
    NOT a `[?()]` array filter: Newtonsoft JSONPath's `[?()]` iterates an array's ELEMENTS, and
    `finops`/`devops` are single objects, not arrays, so `$.finops[?(@.available == true)]`
    silently matches nothing in EITHER state -- found by this feature's own manual gate test,
    not by a live run.
 
    Issue #104 added the rest of one rule: a check never Passes or Fails on data that was only
    partly read. `assert.completeGate` (a path or a list) is the second kind of gate -- it is read
    AFTER the rule is evaluated and closes only the outcome that unread rows could overturn (see
    Get-ScoutUnsoundOutcome): a violation that was found stays a Fail, "no violation found" is not
    a Pass. `_meta.failedQueries` makes every rule whose query, join or denominator starts at a
    failed typed query's dataset NotAssessed. A NotAssessed finding carries `NotAssessedReason`
    (the collector's own words: counts and dataset names) and `NotAssessedCause` (Partial,
    NotCollected or NoData).
#>

function Invoke-Rule {
    param(
        [Parameter(Mandatory)] $Rule,
        [Parameter(Mandatory)] $Collect,
        [string] $Area,
        [string] $Framework,
        $QueryContext
    )

    if ($null -eq $QueryContext) { $QueryContext = New-ScoutQueryContext -InputObject $Collect }

    # $evidenceTruncated is initialised HERE, not at the assignment site. A manual rule (and the
    # early-return error path) never reaches the query block, so reading it at the emitter would
    # throw "the variable has not been set" under Set-StrictMode -Version Latest -- the same class
    # this file's other guards exist for, and it takes down the whole render, not one finding.
    $status = 'Unknown'; $evidenceCount = 0; $evidence = @(); $evidenceTruncated = $false
    $notAssessedReason = $null; $notAssessedCause = $null

    # AB#6892. Initialised here, not at the point of use, because the early `return`s below
    # (gate failure, query failure, not-assessed) build their own finding object and every one of
    # them must still be able to say what it was going to look for. $null means "not applicable
    # to this rule", which is distinct from 0.
    $denominator = $null

    # A rule carries EITHER a `query` (one dataset, filtered) or a `join` (two datasets,
    # correlated) -- never both. Resolve this before any early return so every finding can
    # expose the same schema, including gate/query errors and NotAssessed results.
    $hasJoin = if ($Rule -is [hashtable]) { $Rule.ContainsKey('join') -and $null -ne $Rule.join }
               elseif ($Rule -is [System.Collections.IDictionary]) { $Rule.Contains('join') -and $null -ne $Rule['join'] }
               else { $null -ne $Rule.PSObject.Properties['join'] -and $null -ne $Rule.join }
    $searchedPath = if ($hasJoin) { '(join)' } else { [string]$Rule.query }
    $assertType = if ($Rule.assert) { [string]$Rule.assert.type } else { $null }
    $numeratorKey = $null
    $denominatorKey = $null
    if ($Rule.assert -is [hashtable]) {
        if ($Rule.assert.ContainsKey('numeratorKey')) { $numeratorKey = [string]$Rule.assert.numeratorKey }
        if ($Rule.assert.ContainsKey('denominatorKey')) { $denominatorKey = [string]$Rule.assert.denominatorKey }
    }
    elseif ($Rule.assert) {
        if ($Rule.assert.PSObject.Properties['numeratorKey']) { $numeratorKey = [string]$Rule.assert.numeratorKey }
        if ($Rule.assert.PSObject.Properties['denominatorKey']) { $denominatorKey = [string]$Rule.assert.denominatorKey }
    }

    # ---- AB#6826: optional gate, checked before manual/query evaluation ----
    # `gate` is one JSONPath, or a LIST of them that must ALL be open: a rule that needs two
    # independent datasets (an Entra identity read AND the Azure resource it protects) cannot
    # express that with one path, and a single path would read Fail on an estate where one of
    # the two was never collected.
    $gateValue = $null
    if ($Rule.assert -is [hashtable]) {
        if ($Rule.assert.ContainsKey('gate')) { $gateValue = $Rule.assert.gate }
    }
    elseif ($Rule.assert -and $Rule.assert.PSObject.Properties['gate']) {
        $gateValue = $Rule.assert.gate
    }
    $gatePaths = @($gateValue | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | ForEach-Object { [string]$_ })
    foreach ($gatePath in $gatePaths) {
        # A single scalar boolean token (the intended shape: `$.finops.available`,
        # `$.devops.available`) closes the gate when its value is exactly `false`; no match at all
        # closes it too. Any other shape (a row, a string, ...) is "present" -- the gate is a
        # data-availability check, not a second assert. See Test-ScoutGateOpen.
        $gateOpen = $true
        try { $gateOpen = Test-ScoutGateOpen -Collect $Collect -QueryContext $QueryContext -Path $gatePath }
        catch {
            Write-Warning "Rule $($Rule.id): gate query '$gatePath' failed: $_"
            return [pscustomobject]@{
                Id = $Rule.id; Title = $Rule.title; Framework = $Framework; Area = $Area
                Severity = $Rule.severity; Status = 'Error'; EvidenceCount = 0; Evidence = @()
                EvidenceTruncated = $false; SearchedPath = $searchedPath; AssertType = $assertType
                Denominator = $null; Remediation = $Rule.remediation; Manual = [bool]$Rule.manual
                NotAssessedReason = $null; NotAssessedCause = $null
            }
        }
        if (-not $gateOpen) {
            $closedGate = Get-ScoutGateReason -Collect $Collect -QueryContext $QueryContext -Path $gatePath
            return [pscustomobject]@{
                Id = $Rule.id; Title = $Rule.title; Framework = $Framework; Area = $Area
                Severity = $Rule.severity; Status = 'NotAssessed'; EvidenceCount = 0; Evidence = @()
                EvidenceTruncated = $false; SearchedPath = $searchedPath; AssertType = $assertType
                Denominator = $null; Remediation = $Rule.remediation; Manual = [bool]$Rule.manual
                NotAssessedReason = $closedGate.Reason; NotAssessedCause = $closedGate.Cause
            }
        }
    }

    # ---- issue #104: optional completeGate ----
    # Listed separately from `gate` because it closes only ONE outcome (see Get-ScoutUnsoundOutcome)
    # and only after the rule has been evaluated: a found violation is a real Fail even when part
    # of the estate could not be read, while "no violation found" is not a Pass.
    $completeGateValue = $null
    if ($Rule.assert -is [hashtable]) {
        if ($Rule.assert.ContainsKey('completeGate')) { $completeGateValue = $Rule.assert.completeGate }
    }
    elseif ($Rule.assert -and $Rule.assert.PSObject.Properties['completeGate']) {
        $completeGateValue = $Rule.assert.completeGate
    }
    $completeGatePaths = @($completeGateValue | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_) } | ForEach-Object { [string]$_ })
    if ($Rule.manual -or $Rule.assert.type -eq 'manual') {
        # pre-fill with any evidence the scan DID find, then hand to the human
        if ($Rule.query) {
            try { $manualMatches = Resolve-JsonPath -InputObject $Collect -QueryContext $QueryContext -Path $Rule.query }
            catch {
                Write-Warning "Rule $($Rule.id): manual query '$($Rule.query)' failed: $_"
                return [pscustomobject]@{
                    Id = $Rule.id; Title = $Rule.title; Framework = $Framework; Area = $Area
                    Severity = $Rule.severity; Status = 'Error'; EvidenceCount = 0; Evidence = @()
                    EvidenceTruncated = $false; SearchedPath = $searchedPath; AssertType = $assertType
                    Denominator = $null; Remediation = $Rule.remediation; Manual = [bool]$Rule.manual
                    NotAssessedReason = $null; NotAssessedCause = $null
                }
            }
            $evidenceCount = @($manualMatches).Count
            $evidence = @($manualMatches | Select-Object -First 25 | ForEach-Object {
                # A selected token holds its parent/root tree. Keep only this evidence subtree
                # so findings cannot retain the complete query index (AB#9304).
                if ($_ -is [Newtonsoft.Json.Linq.JToken]) {
                    Write-Output -NoEnumerate -InputObject ($_.DeepClone())
                }
                else { $_ }
            })
            $evidenceTruncated = $evidenceCount -gt 25
        }
        $status = 'Manual'
    }
    else {
        # ---- issue #104: a typed query that failed -----------------------------------------------
        # Invoke-Collect records every Resource Graph query that did not answer in
        # `_meta.failedQueries`, with the dataset paths it feeds. A failed query hands the rules an
        # EMPTY array, which a countEquals:0 or notExists rule would score as a Pass -- so a rule whose
        # query, join or denominator starts at one of those paths is not assessed.
        $queryRoots = @(
            if ($hasJoin) {
                $joinSpec = $Rule.join
                foreach ($side in 'left', 'right') {
                    $sidePath = if ($joinSpec -is [System.Collections.IDictionary]) { if ($joinSpec.Contains($side)) { [string]$joinSpec[$side] } else { '' } }
                                elseif ($joinSpec.PSObject.Properties[$side]) { [string]$joinSpec.$side } else { '' }
                    Get-ScoutRuleRootPath -Path $sidePath
                }
            }
            else { Get-ScoutRuleRootPath -Path ([string]$Rule.query) }
            $denominatorPath = if ($Rule.assert -is [System.Collections.IDictionary]) { if ($Rule.assert.Contains('denominatorQuery')) { [string]$Rule.assert['denominatorQuery'] } else { '' } }
                               elseif ($Rule.assert -and $Rule.assert.PSObject.Properties['denominatorQuery']) { [string]$Rule.assert.denominatorQuery } else { '' }
            Get-ScoutRuleRootPath -Path $denominatorPath
        )
        if ($queryRoots.Count -gt 0) {
            $failedQueryMap = $null
            try { $failedQueryMap = Get-ScoutFailedQueryMap -Collect $Collect -QueryContext $QueryContext }
            catch { Write-Verbose "Rule $($Rule.id): the failed-query list could not be read: $($_.Exception.Message)" }
            if ($null -ne $failedQueryMap -and $failedQueryMap.Count -gt 0) {
                foreach ($root in $queryRoots) {
                    $rootKey = $root.ToLowerInvariant()
                    if ($failedQueryMap.ContainsKey($rootKey)) {
                        return [pscustomobject]@{
                            Id = $Rule.id; Title = $Rule.title; Framework = $Framework; Area = $Area
                            Severity = $Rule.severity; Status = 'NotAssessed'; EvidenceCount = 0; Evidence = @()
                            EvidenceTruncated = $false; SearchedPath = $searchedPath; AssertType = $assertType
                            Denominator = $null; Remediation = $Rule.remediation; Manual = [bool]$Rule.manual
                            NotAssessedReason = [string]$failedQueryMap[$rootKey]; NotAssessedCause = 'Partial'
                        }
                    }
                }
            }
        }
        try {
            # Assigned INSIDE each branch, not from the `if` as an expression. `$x = if (...) { @() }`
            # returns $null, not an empty array -- the if's output stream enumerates and an empty
            # array enumerates to nothing -- and the very next line reads `.Count`, which then
            # throws under StrictMode. A join that legitimately found no unmatched rows (the PASS
            # case, and the common one) hit that on every rule.
            $ruleMatches = $null
            if ($hasJoin) {
                $ruleMatches = @(Resolve-RuleJoin -Rule $Rule -Collect $Collect -QueryContext $QueryContext)
            } else {
                $ruleMatches = Resolve-JsonPath -InputObject $Collect -QueryContext $QueryContext -Path $Rule.query
            }
        }
        catch {
            # A query that threw (unsupported/invalid JSONPath, or a malformed join block) is an
            # Error, never a silent Pass on countEquals:0 (AB#5083). Surface it so it's visible.
            Write-Warning "Rule $($Rule.id): $(if ($hasJoin) { 'join' } else { "query '$($Rule.query)'" }) failed: $_"
            return [pscustomobject]@{
                Id = $Rule.id; Title = $Rule.title; Framework = $Framework; Area = $Area
                Severity = $Rule.severity; Status = 'Error'; EvidenceCount = 0; Evidence = @()
                EvidenceTruncated = $false; SearchedPath = $searchedPath; AssertType = $assertType
                Denominator = $null; Remediation = $Rule.remediation; Manual = [bool]$Rule.manual
                NotAssessedReason = $null; NotAssessedCause = $null
            }
        }
        # AB#6864. The payload is capped so a rule matching thousands of resources does not carry
        # them all into every artefact -- but the cap has to be VISIBLE. Before this, a finding
        # with 198 matches and one with 26 both shipped 25 evidence rows and looked identical, so
        # a renderer walking Evidence silently under-reported and nothing said it had.
        #
        # EvidenceCount already held the true total; EvidenceTruncated is what lets a renderer
        # tell "these are all of them" from "these are the first 25 of many". Same class as the
        # empty-cell-versus-None-found problem the audit called out: the omission was invisible.
        if (-not [string]::IsNullOrWhiteSpace($numeratorKey)) {
            $distinctMatches = [System.Collections.Generic.List[object]]::new()
            $seenNumeratorKeys = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
            foreach ($match in @($ruleMatches)) {
                $key = Get-ScoutRuleRowKey -Row $match -Path $numeratorKey
                if (-not [string]::IsNullOrWhiteSpace($key) -and $seenNumeratorKeys.Add($key)) {
                    $distinctMatches.Add($match)
                }
            }
            $ruleMatches = $distinctMatches.ToArray()
        }
        $evidenceCount = @($ruleMatches).Count
        $evidenceCap = 25
        # @(...) wrap is load-bearing (AB#6938). `$ruleMatches | Select-Object -First N` is a PIPE:
        # when a rule's query matches exactly ONE row, Select-Object emits that ONE object and a
        # bare `$evidence = ...` assignment of a single-item pipeline collapses it from a 1-element
        # array down to the bare element itself -- here, a live run's element is a raw Newtonsoft
        # JObject/JArray token (Resolve-JsonPath's own output shape), not a deserialized
        # PSCustomObject. A bare JObject stored as Evidence is a ticking bomb three layers down:
        # Export-React's Get-ReactSafeProp reads it back out via a plain `return $cur`, and
        # PowerShell's own pipeline/output semantics enumerate ANY IEnumerable object crossing a
        # return/output boundary -- INCLUDING a .NET type nobody asked to have enumerated. JObject
        # implements IEnumerable<JToken> (its own child JProperty tokens), so returning the bare
        # JObject silently exploded one NSG-rule finding into five orphan one-field rows (nsg=...,
        # rule=..., sourceAddressPrefix=..., ...) instead of the single named resource it actually
        # was -- the "40% named" evidence-identity defect. `@(...)` around the whole pipeline
        # forces the (possibly single) result back into a real array BEFORE it is ever stored on
        # the finding, so every later stage that hands it through a `return`/pipeline boundary
        # keeps unwrapping one array level at a time instead of reaching all the way into a single
        # match's own fields. Same class of bug as the join-assignment guard immediately above.
        $evidence = @($ruleMatches | Select-Object -First $evidenceCap | ForEach-Object {
                # A selected token holds its parent/root tree. Keep only this evidence subtree
                # so findings cannot retain the complete query index (AB#9304).
                if ($_ -is [Newtonsoft.Json.Linq.JToken]) {
                    Write-Output -NoEnumerate -InputObject ($_.DeepClone())
                }
                else { $_ }
            })
        $evidenceTruncated = $evidenceCount -gt $evidenceCap
        # ConvertFrom-Yaml returns `assert:` as a Hashtable (test fixtures often use a
        # pscustomobject instead), and 'exists'/'notExists' rules legitimately omit a
        # `value:` key. Accessing a missing key/property via dot-notation throws
        # PropertyNotFoundException under Set-StrictMode -Version Latest, so only read
        # .value when it's actually present — the exists/notExists cases below never
        # reference $v. Handle both Hashtable and pscustomobject assert shapes.
        $v = $null
        if ($Rule.assert -is [hashtable]) {
            if ($Rule.assert.ContainsKey('value')) { $v = $Rule.assert.value }
        }
        elseif ($Rule.assert.PSObject.Properties['value']) {
            $v = $Rule.assert.value
        }

        switch ($Rule.assert.type) {
            'countGreaterThan'  { $status = ($evidenceCount -gt  $v) ? 'Pass' : 'Fail' }
            'countEquals'       { $status = ($evidenceCount -eq  $v) ? 'Pass' : 'Fail' }
            'countLessThan'     { $status = ($evidenceCount -lt  $v) ? 'Pass' : 'Fail' }
            'exists'            { $status = ($evidenceCount -gt   0) ? 'Pass' : 'Fail' }
            'notExists'         { $status = ($evidenceCount -eq   0) ? 'Pass' : 'Fail' }
            'percentageAtLeast' {
                try {
                    $denominatorMatches = Resolve-JsonPath -InputObject $Collect -QueryContext $QueryContext -Path $Rule.assert.denominatorQuery
                    if (-not [string]::IsNullOrWhiteSpace($denominatorKey)) {
                        $denominatorKeys = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
                        foreach ($match in @($denominatorMatches)) {
                            $key = Get-ScoutRuleRowKey -Row $match -Path $denominatorKey
                            if (-not [string]::IsNullOrWhiteSpace($key)) { $null = $denominatorKeys.Add($key) }
                        }
                        $denom = $denominatorKeys.Count
                    }
                    else { $denom = @($denominatorMatches).Count }
                }
                catch {
                    Write-Warning "Rule $($Rule.id): denominator query '$($Rule.assert.denominatorQuery)' failed: $_"
                    $status = 'Error'
                    break
                }
                # AB#6892: surfaced on the finding so a renderer can say "17 of 198", which is the
                # supporting number the reference deliverable carries on every risk row. Without
                # it the reader gets a percentage with nothing behind it.
                $denominator = $denom
                # No denominator = nothing exists to measure for this dimension -> NotAssessed,
                # NOT a 0% Fail, which would be misleading (AB#5085).
                if ($denom -le 0) { $status = 'NotAssessed' }
                else {
                    $pct = $evidenceCount / $denom * 100
                    $status = ($pct -ge $v) ? 'Pass' : (($pct -gt 0) ? 'Partial' : 'Fail')
                }
            }
            default {
                Write-Warning "Rule $($Rule.id): unknown assert type '$($Rule.assert.type)'"
                $status = 'Error'
            }
        }

        # ---- issue #104: completeGate -- the data behind an outcome that could be wrong ----------
        # Only the outcome that rows nobody read could overturn is held back; the other one is proven
        # by the rows that WERE read. Closed (or invalid) reads NotAssessed with the collector's
        # reason (counts of what failed, never names).
        if ($completeGatePaths.Count -gt 0 -and $status -in @('Pass', 'Partial', 'Fail') -and
            ($status -in (Get-ScoutUnsoundOutcome -AssertType ([string]$Rule.assert.type) -Value $v))) {
            foreach ($completePath in $completeGatePaths) {
                $completeOpen = $true
                try { $completeOpen = Test-ScoutGateOpen -Collect $Collect -QueryContext $QueryContext -Path $completePath }
                catch {
                    Write-Warning "Rule $($Rule.id): completeGate query '$completePath' failed: $_"
                    $status = 'Error'
                    break
                }
                if (-not $completeOpen) {
                    $status = 'NotAssessed'
                    $closedGate = Get-ScoutGateReason -Collect $Collect -QueryContext $QueryContext -Path $completePath -Complete
                    $notAssessedReason = $closedGate.Reason
                    $notAssessedCause = $closedGate.Cause
                    break
                }
            }
        }
    }

    # AB#6892 -- WHAT WAS SEARCHED, always, even when nothing was found.
    #
    # Phase 0 measured that 42 of 57 FAILING controls carried zero evidence, and no report named a
    # single Azure resource across three real tenants. That is not a renderer defect. An `exists`
    # rule fails precisely BECAUSE its query returned nothing, so its evidence list is empty by
    # construction -- there is no resource to name, and there never will be.
    #
    # What makes such a finding actionable is not a resource list but the SCOPE: what was looked
    # for, where, and how many candidates existed. "No Purview account was found in any of the 9
    # subscriptions scanned" is actionable. "Data governance coverage: Fail" is decoration.
    #
    # So every finding now carries the query it ran and the assertion it applied, and the
    # percentage rules carry their denominator. Renderers can state the scope of a nil result
    # instead of rendering an empty table.
    [pscustomobject]@{
        Id            = $Rule.id
        Title         = $Rule.title
        Framework     = $Framework
        Area          = $Area
        Severity      = $Rule.severity
        Status        = $status
        EvidenceCount = $evidenceCount
        Evidence      = $evidence
        # AB#6864: true when Evidence holds only the first N of EvidenceCount matches, so a
        # renderer can say "25 of 198 shown" instead of presenting 25 as the whole set.
        EvidenceTruncated = $evidenceTruncated
        SearchedPath  = $searchedPath
        AssertType    = $assertType
        Denominator   = $denominator
        Remediation   = $Rule.remediation
        Manual        = [bool]$Rule.manual
        # Issue #104: why a NotAssessed outcome came from partial data; $null for every other status.
        NotAssessedReason = $notAssessedReason
        NotAssessedCause  = $notAssessedCause
    }
}