Payload/scripts/kaden/harness/reviewer-stop.ps1

<#
.SYNOPSIS
    Copilot subagentStop hook: remind the parent after a paired reviewer finishes.

.DESCRIPTION
    Reads the finished agent from Copilot subagentStop stdin. A paired reviewer
    emits the same parent reminder the Cursor reviewer-stop hook already writes,
    on Copilot's modifiedResponse field so the parent can read it. Any other
    finish stays quiet. Reception by a live parent session is probe evidence.

.EXAMPLE
    '{"agent_type":"spec-writer-reviewer"}' | pwsh -File ./scripts/kaden/harness/reviewer-stop.ps1
#>

#Requires -Version 5.1
[CmdletBinding()]
param()

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

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

$inputRaw = [Console]::In.ReadToEnd()
if ([string]::IsNullOrWhiteSpace($inputRaw)) {
    Write-Output '{}'
    exit 0
}

try {
    $payload = $inputRaw | ConvertFrom-Json
} catch {
    Write-Output '{}'
    exit 0
}

$agentType = ''
foreach ($name in @('agent_type', 'agentType', 'subagent_type', 'agent_name', 'agentName')) {
    $property = $payload.PSObject.Properties[$name]
    if ($null -eq $property) {
        continue
    }
    $value = [string]$property.Value
    if (-not [string]::IsNullOrWhiteSpace($value)) {
        $agentType = $value
        break
    }
}

if ($agentType -notmatch 'reviewer') {
    Write-Output '{}'
    exit 0
}

$repoRoot = Get-HarnessRepoRoot -StartPath $PSScriptRoot
$cursorScript = Join-HarnessPath -Root $repoRoot -Child '.cursor/hooks/reviewer-stop.ps1'
$normalized = @{ subagent_type = $agentType } | ConvertTo-Json -Compress
$followupRaw = $normalized | & pwsh -NoProfile -ExecutionPolicy Bypass -File $cursorScript
if ($LASTEXITCODE -ne 0) {
    Write-Output '{}'
    exit 0
}

try {
    $parsed = $followupRaw | ConvertFrom-Json
} catch {
    Write-Output '{}'
    exit 0
}

$followup = ''
if ($null -ne $parsed -and $null -ne $parsed.PSObject.Properties['followup_message']) {
    $followup = [string]$parsed.followup_message
}
if ([string]::IsNullOrWhiteSpace($followup)) {
    Write-Output '{}'
    exit 0
}

$original = ''
foreach ($name in @('last_assistant_message', 'response')) {
    $property = $payload.PSObject.Properties[$name]
    if ($null -eq $property) {
        continue
    }
    $value = [string]$property.Value
    if (-not [string]::IsNullOrWhiteSpace($value)) {
        $original = $value
        break
    }
}

$delivered = if ([string]::IsNullOrWhiteSpace($original)) {
    $followup
} else {
    $original.TrimEnd() + "`n`n" + $followup
}

Write-Output (@{
        decision         = 'allow'
        modifiedResponse = $delivered
    } | ConvertTo-Json -Compress)
exit 0