Payload/scripts/harness-invoke.ps1

#Requires -Version 5.1
<#
.SYNOPSIS
    Public PowerShell entry point for harness commands.

.DESCRIPTION
    This is the only general harness command agents and operator DNA teach:

        pwsh -File scripts/harness-invoke.ps1 <script.ps1> [args...]

    It strips a leading control character from the first remaining argument
    (Windows terminal injection), prefers PowerShell 7 when the current host is
    below 7 and pwsh is on PATH, guards the script filename, then delegates to
    the shared harness relay.

.EXAMPLE
    pwsh -File scripts/harness-invoke.ps1 harness-turn-start.ps1 -Feature harness-single-entry -Slice prefer-pwsh7-reexec -Phase RED
#>


[CmdletBinding()]
param(
    [Parameter(ValueFromRemainingArguments = $true)]
    [string[]]$RemainingArgs
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if ($RemainingArgs.Count -eq 0) {
    Write-Error 'Usage: pwsh -File scripts/harness-invoke.ps1 <script.ps1> [args...]'
    exit 91
}

$scriptName = [string]$RemainingArgs[0]
if ($scriptName.Length -gt 0 -and [char]::IsControl($scriptName[0])) {
    $scriptName = $scriptName.Substring(1)
    $tail = @()
    if ($RemainingArgs.Count -gt 1) {
        $tail = @($RemainingArgs[1..($RemainingArgs.Count - 1)])
    }
    $RemainingArgs = @($scriptName) + $tail
}

# Prefer PowerShell 7 when this process is below 7 and pwsh is launchable.
# Accept PATH names pwsh and pwsh.exe. Windows PowerShell 5.1 remains the fallback.
if ($PSVersionTable.PSVersion.Major -lt 7) {
    $pwshCmd = Get-Command pwsh -ErrorAction SilentlyContinue
    if (-not $pwshCmd) {
        $pwshCmd = Get-Command pwsh.exe -ErrorAction SilentlyContinue
    }
    if ($pwshCmd) {
        & $pwshCmd.Source -NoProfile -ExecutionPolicy Bypass -File $PSCommandPath @RemainingArgs
        exit [int]$LASTEXITCODE
    }
}

if (-not ($scriptName -match '\.ps1$') -or $scriptName -match '[/\\]' -or $scriptName -match '\.\.') {
    Write-Error "harness-invoke.ps1: invalid script name '$scriptName'. Must be a plain .ps1 filename in scripts/ or repo-root."
    exit 92
}

$relayPath = Join-Path $PSScriptRoot 'harness\harness-relay.ps1'
if (-not (Test-Path -LiteralPath $relayPath)) {
    $relayPath = Join-Path (Split-Path $PSScriptRoot -Parent) 'harness\harness-relay.ps1'
}
if (-not (Test-Path -LiteralPath $relayPath)) {
    Write-Error "harness-invoke.ps1: relay not found: $relayPath"
    exit 93
}

& $relayPath @RemainingArgs
exit [int]$LASTEXITCODE