Private/Stop-OurStaleBun.ps1

# Internal helper -- kill OUR previous bun (by PID file) only, never VS Code's bun.
# Bot X (VS Code) and Bot Y (CLI) are different tokens -- no 409 collision possible
# between them. We only clean up stale Bot Y pollers from a prior CLI run.

function Stop-OurStaleBun {
    param(
        [Parameter(Mandatory)][string]$StateDir,
        [Parameter(Mandatory)][string]$LogFile
    )
    $pidFile = Join-Path $StateDir 'bot.pid'
    if (-not (Test-Path $pidFile)) { return }
    $raw = (Get-Content $pidFile -Raw -ErrorAction SilentlyContinue).Trim()
    if ($raw -match '^\d+$') {
        $proc = Get-Process -Id ([int]$raw) -ErrorAction SilentlyContinue
        if ($proc -and $proc.ProcessName -eq 'bun') {
            Stop-Process -Id ([int]$raw) -Force -ErrorAction SilentlyContinue
            Write-LogLine -Message "Killed stale CLI bun PID=$raw from prior session (NOT VS Code's bun)" -Level 'INFO' -LogFile $LogFile
            Start-Sleep 2
        }
    }
}