Payload/scripts/harness/harness-relay.ps1

#Requires -Version 5.1
<#
.SYNOPSIS
    Stable argument relay for the public PowerShell harness entry.

.DESCRIPTION
    harness-invoke.ps1 forwards PowerShell arguments to this relay via
    PowerShell -File mode. When the caller is a shell that already tokenizes
    arguments, tokens pass through. When quotes were already stripped (agent
    PowerShell Shell), remaining tokens after -SkipRationale / -Summary are glued
    until the next -Flag so a rationale like "Walking-skeleton MO save" cannot
    bind leftover MO as -FeaturePhase.

    First argument is the target script name -- a plain .ps1 filename in scripts/.
    Remaining arguments are glued (SkipRationale/Summary) then forwarded as a
    hashtable splat so -Feature/-Phase bind by name.

    Do NOT invoke this script directly; use:
    pwsh -File scripts/harness-invoke.ps1 <script.ps1> [args...]

.EXAMPLE
    pwsh -File scripts/harness-invoke.ps1 harness-turn-start.ps1 -Feature my-feature -Slice s1 -Phase RED -ModelSlug gpt-5.3
#>


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

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

$scriptName = [string]$args[0]

# Guard: plain .ps1 filename only -- no path separators, no traversal.
if (-not ($scriptName -match '\.ps1$') -or $scriptName -match '[/\\]' -or $scriptName -match '\.\.') {
    Write-Error "harness-relay: invalid script name '$scriptName'. Must be a plain .ps1 filename in the scripts/ directory (no path components)."
    exit 92
}

$scriptPath = Join-Path $PSScriptRoot $scriptName
# Allow root-level entry points (e.g. verify-local.ps1) to be resolved from scripts/ root.
# The path-traversal guard above ensures $scriptName is a plain filename with no separators.
if (-not (Test-Path -LiteralPath $scriptPath)) {
    $parentScriptPath = Join-Path (Split-Path $PSScriptRoot -Parent) $scriptName
    if (Test-Path -LiteralPath $parentScriptPath) {
        $scriptPath = $parentScriptPath
    }
}
if (-not (Test-Path -LiteralPath $scriptPath)) {
    Write-Error "harness-relay: script not found: $scriptPath"
    exit 93
}

Import-Module (Join-Path $PSScriptRoot 'lib\HarnessContract.psm1') -Force

# Scripts that write JSON and return without `exit` leave LASTEXITCODE unset.
# StrictMode then throws in the wrapper and invoke reports FAIL after a successful write.
$global:LASTEXITCODE = 0
if ($args.Count -gt 1) {
    $forward = @($args | Select-Object -Skip 1 | Where-Object { $null -ne $_ })
    $forward = @(Repair-HarnessInvokeForwardedArgs -Tokens $forward)
    if ($forward.Count -eq 0) {
        & $scriptPath
    }
    else {
        $splat = ConvertTo-HarnessInvokeNamedSplat -Tokens $forward
        & $scriptPath @splat
    }
}
else {
    & $scriptPath
}
exit ([int]$LASTEXITCODE)