Private/Compliance/Merge-GovernancePreflight.ps1

function Get-GovernanceCommonPathPrefix {
    # The longest common '\'-segment prefix of a set of area paths, keeping the
    # leading '\' when the inputs have one. '' when they share nothing.
    param([string[]]$Paths)
    $split = @($Paths | ForEach-Object { , @(([string]$_).Trim('\') -split '\\') })
    if ($split.Count -eq 0) { return '' }
    $common = [System.Collections.Generic.List[string]]::new()
    for ($i = 0; $i -lt $split[0].Count; $i++) {
        $seg = $split[0][$i]
        if (@($split | Where-Object { $_.Count -le $i -or $_[$i] -ne $seg }).Count -gt 0) { break }
        $common.Add($seg)
    }
    if ($common.Count -eq 0) { return '' }
    $lead = if (([string]$Paths[0]).StartsWith('\')) { '\' } else { '' }
    return $lead + ($common -join '\')
}

function Merge-GovernancePreflightData {
    <#
        .SYNOPSIS
        Combines the gathered data documents of several preflight nodes into
        ONE data document for a combined report (sources.yaml `reports:`).

        Facts only, merged without judgement, so the same pure analysis that
        runs per node can run once more over the whole and every number in the
        combined report is still copied from a file:

          workItems, tags, iterations summed — each node's query selects its
                                        own area, so the work items are disjoint
          areas, unmappedAreas, repos concatenated (repos de-duplicated)
          authored, population unioned (the first node wins a clash)
          source.areaPath the members' common root; their own
                                        roots are kept in source.roots so a
                                        renderer never mistakes one for a sub-area
          gathered the OLDEST member's date — the combined
                                        facts are only as fresh as their stalest part
          parts one row per member, for the report header

        Throws when the members do not share a source and target organisation
        and project: a combined report across those would compare unlike things.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Code,
        [Parameter(Mandatory)][object[]]$Data,     # member data documents, in report order
        [string]$Name = ''
    )

    if ($Data.Count -lt 2) { throw "Merge-GovernancePreflightData: '$Code' needs at least two member data documents, got $($Data.Count)." }
    foreach ($d in $Data) {
        if ([string]$d.schema -ne 'nkdagility.governance.preflight-data/1') { throw "Merge-GovernancePreflightData: member '$($d.node)' is not a preflight data document this engine understands (schema '$($d.schema)')." }
    }
    foreach ($k in 'org', 'project') {
        $vals = @($Data | ForEach-Object { [string]$_.source[$k] } | Sort-Object -Unique)
        if ($vals.Count -ne 1) { throw "Merge-GovernancePreflightData: '$Code' members come from different source ${k}s ($($vals -join ', ')); a combined report needs one." }
        $vals = @($Data | ForEach-Object { [string]$_.target[$k] } | Sort-Object -Unique)
        if ($vals.Count -ne 1) { throw "Merge-GovernancePreflightData: '$Code' members go to different target ${k}s ($($vals -join ', ')); a combined report needs one." }
    }
    $programs = @($Data | ForEach-Object { [string]$_.program } | Sort-Object -Unique)
    if ($programs.Count -ne 1) { throw "Merge-GovernancePreflightData: '$Code' members belong to different programs ($($programs -join ', '))." }

    $inv = [System.Globalization.CultureInfo]::InvariantCulture
    $asDate = { param($v) if ($v -is [datetime]) { ([datetime]$v).ToUniversalTime() } else { [datetime]::Parse([string]$v, $inv, [System.Globalization.DateTimeStyles]::AdjustToUniversal) } }
    $oldest = @($Data | ForEach-Object { & $asDate $_.gathered } | Sort-Object)[0]

    $sum = {
        param($maps)
        $out = [ordered]@{}
        foreach ($m in $maps) { if ($m) { foreach ($k in @($m.Keys)) { $out[[string]$k] = [long]$(if ($out.Contains([string]$k)) { $out[[string]$k] } else { 0 }) + [long]$m[$k] } } }
        $sorted = [ordered]@{}
        foreach ($k in @($out.Keys | Sort-Object)) { $sorted[$k] = $out[$k] }
        $sorted
    }
    $union = {
        param($lists, [scriptblock]$key)
        $seen = @{}; $out = [System.Collections.Generic.List[object]]::new()
        foreach ($l in $lists) { foreach ($x in @($l | Where-Object { $_ })) { $k = & $key $x; if (-not $seen.ContainsKey($k)) { $seen[$k] = $true; $out.Add($x) } } }
        , @($out)
    }

    $roots = @($Data | ForEach-Object { [string]$_.source.areaPath })
    $population = [ordered]@{}
    foreach ($d in $Data) { if ($d.population) { foreach ($k in @($d.population.Keys)) { if (-not $population.Contains([string]$k)) { $population[[string]$k] = $d.population[$k] } } } }
    $repoIncl = @($Data | Where-Object { $null -ne $_.source.repoInclude } | ForEach-Object { @($_.source.repoInclude) })

    $queries = foreach ($d in $Data) {
        if ($d.scope -and $d.scope.query) { "-- $($d.node)$(if ($d.scope.label) { ": $($d.scope.label)" })`n$(([string]$d.scope.query).Trim())" }
    }

    # Access review: a person's grants on each member's area and repos are
    # gathered separately, so they are joined per person; groups stay one row
    # per grant. Repo claims are joined; the unclaimed list is the same
    # program-wide list in every member, kept while any member has not answered.
    $access = $null
    $withAccess = @($Data | Where-Object { $_.Contains('access') -and $_.access -and $_.access.today })
    if ($withAccess.Count) {
        $people = [ordered]@{}
        foreach ($d in $withAccess) {
            foreach ($p in @($d.access.today.people)) {
                $u = [string]$p.upn
                if (-not $people.Contains($u)) { $people[$u] = [ordered]@{ upn = $u; name = [string]$p.name; grants = [System.Collections.Generic.List[object]]::new() } }
                foreach ($g in @($p.grants)) { $people[$u].grants.Add($g) }
            }
        }
        $access = [ordered]@{
            today = [ordered]@{
                broadThreshold = $withAccess[0].access.today.broadThreshold
                people = @(foreach ($u in @($people.Keys | Sort-Object)) { $people[$u] })
                groups = @($withAccess | ForEach-Object { @($_.access.today.groups) } | Where-Object { $_ })
            }
            after        = (& $union @($withAccess | ForEach-Object { , @($_.access.after) }) { param($m) "$($m.upn)|$($m.group)" })
            notMigrating = (& $union @($withAccess | ForEach-Object { , @($_.access.notMigrating) }) { param($m) [string]$m.upn })
        }
    }
    $repoReview = $null
    $withRepos = @($Data | Where-Object { $_.Contains('repoReview') -and $_.repoReview })
    if ($withRepos.Count) {
        $notAsked = @($withRepos | Where-Object { -not $_.repoReview.asked })
        $repoReview = [ordered]@{
            asked     = ($notAsked.Count -eq 0)
            claims    = @($withRepos | ForEach-Object { @($_.repoReview.claims) } | Where-Object { $_ })
            unclaimed = if ($notAsked.Count) { @($notAsked[0].repoReview.unclaimed) } else { $null }
        }
    }

    return [ordered]@{
        access     = $access
        repoReview = $repoReview
        schema   = 'nkdagility.governance.preflight-data/1'
        gathered = $oldest.ToString('o', $inv)
        program  = $programs[0]
        node     = $Code
        title    = $Name
        parts    = @(foreach ($d in $Data) {
            [ordered]@{
                node       = [string]$d.node
                sourceRoot = [string]$d.source.areaPath
                targetRoot = [string]$d.target.root
                workItems  = [long]$d.workItems.count
                label      = if ($d.scope) { [string]$d.scope.label } else { '' }
                gathered   = (& $asDate $d.gathered).ToString('o', $inv)
            }
        })
        target   = [ordered]@{
            org     = [string]$Data[0].target.org
            project = [string]$Data[0].target.project
            root    = (Get-GovernanceCommonPathPrefix -Paths @($Data | ForEach-Object { [string]$_.target.root }))
        }
        source   = [ordered]@{
            org         = [string]$Data[0].source.org
            project     = [string]$Data[0].source.project
            areaPath    = (Get-GovernanceCommonPathPrefix -Paths $roots)
            roots       = $roots
            teams       = @($Data | ForEach-Object { @($_.source.teams | Where-Object { $_ }) } | Sort-Object -Unique)
            repoInclude = if ($repoIncl.Count) { @($repoIncl | Sort-Object -Unique) } else { $null }
        }
        scope    = [ordered]@{
            label = (@($Data | ForEach-Object { if ($_.scope -and $_.scope.label) { "$($_.node): $($_.scope.label)" } }) -join '; ')
            query = ($queries -join "`n`n")
        }
        workItems     = [ordered]@{ count = [long](($Data | ForEach-Object { [long]$_.workItems.count } | Measure-Object -Sum).Sum) }
        areas         = (& $union @($Data | ForEach-Object { , @($_.areas) }) { param($a) [string]$a.source })
        unmappedAreas = (& $union @($Data | ForEach-Object { , @($_.unmappedAreas) }) { param($a) [string]$a.source })
        tags          = (& $sum @($Data | ForEach-Object { $_.tags }))
        iterations    = (& $sum @($Data | ForEach-Object { $_.iterations }))
        repos         = @($Data | ForEach-Object { @($_.repos | Where-Object { $_ }) } | Sort-Object -Unique)
        population    = $population
        authored      = [ordered]@{
            members    = (& $union @($Data | ForEach-Object { , @($_.authored.members) })    { param($m) "$($m.upn)|$($m.group)" })
            teamAdmins = (& $union @($Data | ForEach-Object { , @($_.authored.teamAdmins) }) { param($m) "$($m.upn)|$($m.team)" })
        }
    }
}

function Merge-GovernancePreflightSlice {
    <#
        .SYNOPSIS
        The resolved-model slice a combined report is analysed against: the
        union of its members' slices (Select-GovernanceSubtree), so the area,
        tag and repo evaluators see every target path any member lands on.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Code,
        [Parameter(Mandatory)][object[]]$Slices
    )
    $byKey = {
        param($items, [scriptblock]$key)
        $seen = @{}
        @(foreach ($x in $items) { if ($null -eq $x) { continue }; $k = & $key $x; if (-not $seen.ContainsKey($k)) { $seen[$k] = $true; $x } })
    }
    return @{
        Code       = $Code
        TargetRoot = (Get-GovernanceCommonPathPrefix -Paths @($Slices | ForEach-Object { [string]$_.TargetRoot }))
        Teams      = (& $byKey @($Slices | ForEach-Object { @($_.Teams) }) { param($t) [string]$t.codePath })
        AreaPaths  = (& $byKey @($Slices | ForEach-Object { @($_.AreaPaths) }) { param($a) [string]$a.path })
        Repos      = (& $byKey @($Slices | ForEach-Object { @($_.Repos) }) { param($r) [string]$r.name })
        Tags       = $Slices[0].Tags
    }
}