#!/usr/bin/env python3 """Remote collector and package tests for the converged CPLD project.""" from __future__ import annotations import json import shutil import subprocess import tempfile import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[2] class RemoteScriptTests(unittest.TestCase): def test_remote_tools_only_expose_latest_real_fan_ptc_collector(self) -> None: scripts = sorted(path.name for path in (ROOT / "tools" / "remote").glob("*.ps1")) self.assertEqual(scripts, ["collect-j6-host-sensor-real-fan-ptc.ps1"]) self.assertFalse((ROOT / "tools" / "serial_debug_capture.py").exists()) self.assertFalse((ROOT / "tools" / "windows_serial_validation.py").exists()) def test_collect_j6_host_sensor_real_fan_ptc_is_static_allowlisted_host_writer_and_debug_reader(self) -> None: script = (ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1").read_text( encoding="utf-8" ) for marker in [ "System.IO.Ports.SerialPort", "[ValidatePattern('^COM[0-9]+$')]", "HostPort", "DebugPort", 'if (-not $SelfTest -and $HostPort -eq $DebugPort)', 'if (-not $SelfTest -and $HostPort -ne "COM8")', 'if (-not $SelfTest -and $DebugPort -ne "COM7")', "BaudRate = 115200", "DebugBaud = 921600", "DtrEnable = $false", "RtsEnable = $false", "host-port-raw.bin", "host-port-escaped.txt", "debug-uart-raw.bin", "debug-uart-escaped.txt", "bmc-raw-replay.bin", "host-sensor-report.json", "debug-frame-stream.json", "host-command-transcript.json", "j6-host-sensor-real-fan-ptc-capture-manifest.json", "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-receipt-draft.json", "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP", "SENS", "DIMM", "PTCCH", "FANCH", "SET PTC 01 10", "SET PTC 24 20", "SET FAN 01 40", "SET FAN 04 30", "SET PID ENABLE", "GET STATUS", "GET MAP", "GET SENSOR", "SET PID DISABLE", "DISABLE", "host_port_writes_to_serial", "debug_port_writes_to_serial", "driver_install_attempted = $false", "enumerates_com_ports = $false", "opens_unknown_com_ports = $false", "AssumeManualSramProgrammed", "PROGRAM_SRAM", "SelfTest", "startup-preflight.json", "READY", "J6READY", "preflight", "blocked_waiting_for_ready_epoch", ]: self.assertIn(marker, script) self.assertIn("$hostSerial.Write", script) self.assertNotIn("$debugSerial.Write", script) for forbidden in [ "SET PTC 00", "SET FAN 00", "SET FAN 05", "SET FAN 06", "GetPortNames", "Win32_SerialPort", "Get-CimInstance", "Get-WmiObject", "pip install", "pyserial", "python", "pnputil", "devcon", "install-driver", "add-windowsdriver", "driverquery", "PROGRAM_FLASH", "ERASE_FLASH", "PROGRAM_SPIBIN", "DIRECT_FLASH_WRITE", "blocked_edit_required", ]: self.assertNotIn(forbidden.lower(), script.lower()) def test_collect_j6_host_sensor_real_fan_ptc_has_startup_preflight_selftest(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" result = subprocess.run( [ powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script_path), "-SelfTest", ], cwd=ROOT, text=True, capture_output=True, check=False, ) output = result.stderr + result.stdout self.assertEqual(result.returncode, 0, output) for marker in [ "selftest=pass", "ready_line=READY profile=temp-uart-ptc-remap seq=00000000", "j6ready_line=J6READY profile=temp-uart-ptc-remap", "epoch_locked=pass", "pre_sram_noise=OK seq=0000000D cmd=STATUS", "post_j6ready_raw_replay=pass", "formal_ack=OK seq=00000001 cmd=PTCCH", "stale_ack_isolated=pass", "tail_drain=pass", "post_j6stat_tail_bytes=04", "complete_unterminated_j6raw=pass", "incomplete_final_line=J6RAW s=0004", ]: self.assertIn(marker, output) def test_collect_j6_host_sensor_real_fan_ptc_accepts_native_bool_argument_shape(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" result = subprocess.run( [ powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(script_path), "-SelfTest", "-AssumeManualSramProgrammed", "$true", ], cwd=ROOT, text=True, capture_output=True, check=False, ) output = result.stderr + result.stdout self.assertEqual(result.returncode, 0, output) self.assertIn("selftest=pass", output) def test_collect_j6_host_sensor_real_fan_ptc_handles_discarded_ack_arrays(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8-sig") helper_start = script.index("function Read-HostPortAvailableLines") helper_end = script.index("function Invoke-StartupPreflight") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" probe_path.write_text( helpers + """ $hostRaw = New-Object System.Collections.Generic.List[byte] $hostWindow = New-Object System.Text.StringBuilder $hostReports = New-Object System.Collections.Generic.List[object] $queue = New-Object System.Collections.Generic.Queue[object] $queue.Enqueue([ordered]@{ ack_line = "OK seq=00000001 cmd=STATUS" raw = "OK seq=00000001 cmd=STATUS" token = "OK seq=00000001 cmd=STATUS" class = "ok" seq = 1 cmd = "STATUS" ack_offset = 1 response_offset = 1 delimiter = "CR" timestamp = (Get-Date).ToUniversalTime().ToString("o") }) | Out-Null $queue.Enqueue([ordered]@{ ack_line = "OK seq=00000001 cmd=PTCCH" raw = "OK seq=00000001 cmd=PTCCH" token = "OK seq=00000001 cmd=PTCCH" class = "ok" seq = 1 cmd = "PTCCH" ack_offset = 10 response_offset = 10 delimiter = "CR" timestamp = (Get-Date).ToUniversalTime().ToString("o") }) | Out-Null $serial = [pscustomobject]@{ BytesToRead = 0 } $ack = Read-HostAckLine $serial $hostRaw $hostWindow $hostReports $queue 5 200 1 "PTCCH" if ($ack.ack_line -ne "OK seq=00000001 cmd=PTCCH") { throw "candidate ack not returned: $($ack.ack_line)" } if ($ack.discarded_acks.Count -ne 1) { throw "discarded ack count was $($ack.discarded_acks.Count)" } if (-not $ack.discarded_acks[0].stale) { throw "discarded ack was not marked stale" } """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) def test_collect_j6_host_sensor_real_fan_ptc_epoch_lock_discards_pre_sram_ack_noise(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8-sig") helper_start = script.index("function Read-HostPortAvailableLines") helper_end = script.index("function Invoke-CollectorSelfTest") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" probe_path.write_text( helpers + """ $preflight = New-StartupPreflightRecord $ackQueue = New-Object System.Collections.Generic.Queue[object] $ackQueue.Enqueue([ordered]@{ ack_line = "OK seq=0000000D cmd=STATUS" raw = "OK seq=0000000D cmd=STATUS" token = "OK seq=0000000D cmd=STATUS" class = "ok" seq = 13 cmd = "STATUS" ack_offset = 25 response_offset = 25 delimiter = "CR" timestamp = (Get-Date).ToUniversalTime().ToString("o") }) | Out-Null $preReadyDiscard = @(Clear-HostAckQueue $ackQueue) Add-PreSramNoise $preflight "ack" $preReadyDiscard[0] $hostReady = [ordered]@{ kind = "ready"; raw = "READY profile=temp-uart-ptc-remap seq=00000000"; fields = [ordered]@{} } $debugReady = [ordered]@{ kind = "j6ready"; raw = "J6READY profile=temp-uart-ptc-remap"; fields = [ordered]@{} } Update-PreflightEpochReady $preflight $hostReady 100 200 Update-PreflightEpochReady $preflight $debugReady 300 400 Complete-StartupPreflightRecord $preflight if ($preflight.status -ne "pass") { throw "preflight status was $($preflight.status)" } if (-not $preflight.epoch_locked) { throw "epoch was not locked" } if ($preflight.sync_ack_seen) { throw "preflight incorrectly accepted sync ack" } if ($preflight.pre_sram_noise_count -ne 1) { throw "pre_sram_noise_count was $($preflight.pre_sram_noise_count)" } if ($preflight.pre_sram_noise[0].ack_line -ne "OK seq=0000000D cmd=STATUS") { throw "wrong pre_sram noise ack" } if ($preflight.epoch_locked_at_host_offset -ne 100) { throw "wrong host epoch offset" } if ($preflight.epoch_locked_at_debug_offset -ne 400) { throw "wrong debug epoch offset" } $ackQueue.Enqueue([ordered]@{ ack_line = "OK seq=00000001 cmd=PTCCH" raw = "OK seq=00000001 cmd=PTCCH" token = "OK seq=00000001 cmd=PTCCH" class = "ok" seq = 1 cmd = "PTCCH" ack_offset = 150 response_offset = 150 delimiter = "CR" timestamp = (Get-Date).ToUniversalTime().ToString("o") }) | Out-Null $serial = [pscustomobject]@{ BytesToRead = 0 } $hostRaw = New-Object System.Collections.Generic.List[byte] $hostWindow = New-Object System.Text.StringBuilder $hostReports = New-Object System.Collections.Generic.List[object] $ack = Read-HostAckLine $serial $hostRaw $hostWindow $hostReports $ackQueue 120 200 1 "PTCCH" if ($ack.ack_line -ne "OK seq=00000001 cmd=PTCCH") { throw "formal ack not returned: $($ack.ack_line)" } if (-not $ack.seq_match -or -not $ack.cmd_match) { throw "formal ack mismatch" } """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) def test_collect_j6_host_sensor_real_fan_ptc_marks_clear_queue_results_as_pre_sram_noise(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8-sig") helper_start = script.index("function Clear-HostAckQueue") helper_end = script.index("function Update-PreflightEpochReady") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" probe_path.write_text( helpers + """ $preflight = New-StartupPreflightRecord $ackQueue = New-Object System.Collections.Generic.Queue[object] $ackQueue.Enqueue([ordered]@{ ack_line = "OK seq=0000000D cmd=STATUS" raw = "OK seq=0000000D cmd=STATUS" token = "OK seq=0000000D cmd=STATUS" class = "ok" seq = 13 cmd = "STATUS" ack_offset = 25 response_offset = 25 delimiter = "CR" timestamp = (Get-Date).ToUniversalTime().ToString("o") }) | Out-Null $moreStale = @(Clear-HostAckQueue $ackQueue) foreach ($ack in $moreStale) { Set-AckMetadata $ack "pre_sram_noise" $true Add-PreSramNoise $preflight "ack" $ack } if ($moreStale.Count -ne 1) { throw "unexpected stale count $($moreStale.Count)" } if ($moreStale[0] -is [array]) { throw "stale ack was nested array" } if (-not $moreStale[0].pre_sram_noise) { throw "pre_sram_noise was not set" } if ($preflight.pre_sram_noise_count -ne 1) { throw "preflight noise count was $($preflight.pre_sram_noise_count)" } if ($preflight.pre_sram_noise[0].ack_line -ne "OK seq=0000000D cmd=STATUS") { throw "wrong pre_sram noise ack" } """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) def test_collect_j6_host_sensor_real_fan_ptc_handles_timeout_discarded_ack_arrays(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8-sig") helper_start = script.index("function Read-HostPortAvailableLines") helper_end = script.index("function Invoke-StartupPreflight") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" probe_path.write_text( helpers + """ $hostRaw = New-Object System.Collections.Generic.List[byte] $hostWindow = New-Object System.Text.StringBuilder $hostReports = New-Object System.Collections.Generic.List[object] $queue = New-Object System.Collections.Generic.Queue[object] $queue.Enqueue([ordered]@{ ack_line = "OK seq=00000001 cmd=STATUS" raw = "OK seq=00000001 cmd=STATUS" token = "OK seq=00000001 cmd=STATUS" class = "ok" seq = 1 cmd = "STATUS" ack_offset = 1 response_offset = 1 delimiter = "CR" timestamp = (Get-Date).ToUniversalTime().ToString("o") }) | Out-Null $serial = [pscustomobject]@{ BytesToRead = 0 } $ack = Read-HostAckLine $serial $hostRaw $hostWindow $hostReports $queue 5 100 1 "PTCCH" if ($ack.class -ne "timeout") { throw "ack class was $($ack.class)" } if ($ack.discarded_acks.Count -ne 1) { throw "discarded ack count was $($ack.discarded_acks.Count)" } if (-not $ack.discarded_acks[0].stale) { throw "discarded ack was not marked stale" } """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) def test_collect_j6_host_sensor_real_fan_ptc_preserves_empty_raw_replay_byte_array(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8") helper_start = script.index("function Convert-HexToBytes") helper_end = script.index("$out =") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" out_path = Path(tmp) / "empty-replay.bin" probe_path.write_text( helpers + f""" $events = New-Object System.Collections.Generic.List[object] $rawReplayArray = New-BmcRawReplay $events if ($null -eq $rawReplayArray) {{ throw "raw replay array was null" }} if ($rawReplayArray.GetType().FullName -ne "System.Byte[]") {{ throw "raw replay array type was $($rawReplayArray.GetType().FullName)" }} if ($rawReplayArray.Length -ne 0) {{ throw "raw replay array length was $($rawReplayArray.Length)" }} [System.IO.File]::WriteAllBytes("{out_path}", $rawReplayArray) """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) self.assertTrue(out_path.exists()) self.assertEqual(out_path.stat().st_size, 0) def test_collect_j6_host_sensor_real_fan_ptc_parses_hex_fields_without_losing_payload_width(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8") helper_start = script.index("function Convert-TokenValue") helper_end = script.index("function Convert-BytesToEscapedText") replay_helper_start = script.index("function Convert-HexToBytes") replay_helper_end = script.index("function Get-LastFieldOrDefault") helpers = script[helper_start:helper_end] + script[replay_helper_start:replay_helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" probe_path.write_text( helpers + """ $events = New-Object System.Collections.Generic.List[object] $events.Add((Convert-FrameLine "J6PWM seq=0000000A src=hm pid=disabled timeout=1 ptc01=00 ptc24=00 fan01=1E fan04=1E" @("J6PWM"))) | Out-Null $events.Add((Convert-FrameLine "J6TEMP seq=00000003 status=valid valid=1E missing=00 fault=0 host_report_drop=00000000" @("J6TEMP"))) | Out-Null $events.Add((Convert-FrameLine "J6RAW seq=00000001 off=00000000 len=02 sum=0031 data=0031" @("J6RAW"))) | Out-Null $events.Add((Convert-FrameLine "J6RAW s=002A o=00000100 l=04 u=000A d=01020304" @("J6RAW"))) | Out-Null $events.Add((Convert-FrameLine "J6EVT s=06 cmd=PID_E c=01 p=000 ok=1 e=0 to=0" @("J6EVT"))) | Out-Null $events.Add((Convert-FrameLine "DIMM i=10 t=00 m=1" @("DIMM"))) | Out-Null foreach ($probe in @( @($events[0].fields.fan01, "fan01"), @($events[0].fields.timeout, "timeout"), @($events[1].fields.valid, "valid"), @($events[1].fields.missing, "missing"), @($events[2].fields.len, "len"), @($events[2].fields.sum, "sum"), @($events[3].fields.seq, "compact_seq"), @($events[3].fields.off, "compact_off"), @($events[3].fields.len, "compact_len"), @($events[3].fields.sum, "compact_sum"), @($events[4].fields.ch, "compact_ch"), @($events[4].fields.pct, "compact_pct"), @($events[4].fields.err, "compact_err") )) { if ($probe[0].GetType().FullName -ne "System.Int64") { throw "$($probe[1]) parsed as $($probe[0].GetType().FullName)" } } if ([int64]$events[0].fields.fan01 -ne 30) { throw "fan01 was $($events[0].fields.fan01)" } if ([int64]$events[0].fields.timeout -ne 1) { throw "timeout was $($events[0].fields.timeout)" } if ([int64]$events[1].fields.valid -ne 30) { throw "valid was $($events[1].fields.valid)" } if ([int64]$events[1].fields.missing -ne 0) { throw "missing was $($events[1].fields.missing)" } if ([int64]$events[2].fields.len -ne 2) { throw "len was $($events[2].fields.len)" } if ([int64]$events[2].fields.sum -ne 49) { throw "sum was $($events[2].fields.sum)" } if ([int64]$events[3].fields.seq -ne 42) { throw "compact seq was $($events[3].fields.seq)" } if ([int64]$events[3].fields.off -ne 256) { throw "compact off was $($events[3].fields.off)" } if ([int64]$events[3].fields.len -ne 4) { throw "compact len was $($events[3].fields.len)" } if ([int64]$events[3].fields.sum -ne 10) { throw "compact sum was $($events[3].fields.sum)" } if ($events[2].fields.data.GetType().FullName -ne "System.String") { throw "data parsed as $($events[2].fields.data.GetType().FullName)" } if ($events[2].fields.data -ne "0031") { throw "data was $($events[2].fields.data)" } if ($events[3].fields.data -ne "01020304") { throw "compact data was $($events[3].fields.data)" } if ([int64]$events[4].fields.ch -ne 1) { throw "compact ch was $($events[4].fields.ch)" } if ([int64]$events[4].fields.pct -ne 0) { throw "compact pct was $($events[4].fields.pct)" } if ([int64]$events[4].fields.err -ne 0) { throw "compact err was $($events[4].fields.err)" } if ([int64]$events[5].fields.id -ne 16) { throw "dimm id was $($events[5].fields.id)" } $replay = New-BmcRawReplay $events $replayHex = (($replay | ForEach-Object { $_.ToString("X2") }) -join "") if ($replayHex -ne "003101020304") { throw "replay was $replayHex" } """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) def test_collect_j6_host_sensor_real_fan_ptc_keeps_command_tokens_as_strings(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") script_path = ROOT / "tools" / "remote" / "collect-j6-host-sensor-real-fan-ptc.ps1" script = script_path.read_text(encoding="utf-8") helper_start = script.index("function Convert-TokenValue") helper_end = script.index("function Convert-BytesToEscapedText") helpers = script[helper_start:helper_end] with tempfile.TemporaryDirectory() as tmp: probe_path = Path(tmp) / "probe.ps1" probe_path.write_text( helpers + """ $events = New-Object System.Collections.Generic.List[object] $events.Add((Convert-FrameLine "J6CMD seq=00000001 cmd=raw text=ipmitool" @("J6CMD"))) | Out-Null $events.Add((Convert-FrameLine "J6EVT seq=00000002 ok=1 err=0 type=PTCCH ch=01 pct=0A" @("J6EVT"))) | Out-Null $events.Add((Convert-FrameLine "OK seq=00000003 cmd=FANCH" @("OK"))) | Out-Null if ($events[0].fields.cmd -ne "raw") { throw "cmd was $($events[0].fields.cmd)" } if ($events[1].fields.type -ne "PTCCH") { throw "type was $($events[1].fields.type)" } if ($events[1].fields.ch.GetType().FullName -ne "System.Int64") { throw "ch type was $($events[1].fields.ch.GetType().FullName)" } if ([int64]$events[1].fields.ch -ne 1) { throw "ch was $($events[1].fields.ch)" } if ([int64]$events[1].fields.pct -ne 10) { throw "pct was $($events[1].fields.pct)" } if ($events[2].fields.cmd -ne "FANCH") { throw "ack cmd was $($events[2].fields.cmd)" } """, encoding="utf-8", ) result = subprocess.run( [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(probe_path)], cwd=ROOT, text=True, capture_output=True, check=False, ) self.assertEqual(result.returncode, 0, result.stderr + result.stdout) def test_j6_host_sensor_real_fan_ptc_package_script_creates_temp_profile_package(self) -> None: script = (ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1").read_text( encoding="utf-8" ) for marker in [ "START-HERE.zh-CN.md", "tools\\remote\\collect-j6-host-sensor-real-fan-ptc.ps1", "tools\\bmc_replay_uart.py", "bitstreams", "td-receipts", "commands", "bmc-replay", "pin_inventory.fcb_fpga_mcu0611.json", "sha256-inventory.json", "Compress-Archive", ".zip.sha256.txt", "j6-bmc-replay", "j6tmp.bit", "collect.ps1", "capture-bmc.ps1", "replay-bmc.ps1", "td.json", "debug-photo-uart-bmc-replay", "formal-uart1-bmc-replay", "pc_replay_from_real_bmc_capture", "startup-preflight.json", "collector first, then PROGRAM_SRAM", "tail drain", "ForceOverwrite", "FormalBlocked", "FORMAL-BLOCKED.zh-CN.md", "SET PTC 01 10", "SET PTC 24 20", "SET FAN 01 40", "SET FAN 04 30", "excluded_self_referential_file", ]: self.assertIn(marker, script) self.assertNotIn("Set-ExecutionPolicy", script) self.assertNotIn("-AssumeManualSramProgrammed $true", script) for marker in [ "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-tailfix", "debug115", "swapped", "-ManualSramAttestation", "$att.status", "blocked_edit_required", "collect-com8-host-com7-debug.ps1", r"-Bitstream .\bitstreams\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_primary.bit", "SET PTC 00", "SET FAN 00", "SET FAN 05", "SET FAN 06", "pip install", "pyserial", ]: self.assertNotIn(marker.lower(), script.lower()) def test_j6_host_sensor_real_fan_ptc_package_output_contains_bmc_replay_profile_artifacts(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") with tempfile.TemporaryDirectory() as tmp: bitstream = Path(tmp) / "fake.bit" td_receipt = Path(tmp) / "td-receipt.json" bitstream.write_bytes(b"fake-sram-bitstream") td_receipt.write_text( json.dumps( { "schema": "td-build-receipt-v1", "status": "pass", "programming_mode": "SRAM-only", "bitstream": {"sha256": "0" * 64}, } ), encoding="utf-8", ) for profile, package_name, expected in [ ( "debug-photo-uart-bmc-replay", "j6-bmc-replay-debug-test", { "host_ports": "-HostPort COM8 -DebugPort COM7 -BmcReplayPort COM9", "bmc_tx": "T4", "bmc_rx": "R5", "hardware_access_status": "photo_visible_header", "ptc_note": "PTC03/PTC04/PTC17/PTC18/PTC21/PTC22", }, ), ( "formal-uart1-bmc-replay", "j6-bmc-replay-formal-test", { "host_ports": "-HostPort COM8 -DebugPort COM7 -BmcReplayPort COM9", "bmc_tx": "L10", "bmc_rx": "M9", "hardware_access_status": "blocked_waiting_for_uart1_uart2_access", "ptc_note": "HEAT/PTC/FAN", }, ), ]: with self.subTest(profile=profile): result = subprocess.run( [ powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1"), "-OutputDir", tmp, "-PackageName", package_name, "-Profile", profile, "-Bitstream", str(bitstream), "-TdReceipt", str(td_receipt), ], cwd=ROOT, capture_output=True, check=False, ) output = (result.stderr or b"").decode("utf-8", errors="replace") + ( result.stdout or b"" ).decode("utf-8", errors="replace") self.assertEqual(result.returncode, 0, output) stage = Path(tmp) / package_name short_bit = stage / "j6tmp.bit" short_collect = stage / "collect.ps1" short_td = stage / "td.json" self.assertTrue((stage / "START-HERE.zh-CN.md").is_file()) self.assertTrue(short_bit.is_file()) self.assertTrue(short_collect.is_file()) self.assertTrue(short_td.is_file()) self.assertTrue((stage / "collector" / "collect-j6-host-sensor-real-fan-ptc.ps1").is_file()) self.assertTrue((stage / "bmc-replay" / "bmc_replay_uart.py").is_file()) self.assertTrue((stage / "capture-bmc.ps1").is_file()) self.assertTrue((stage / "replay-bmc.ps1").is_file()) self.assertTrue((stage / "bmc-replay-payload.example.json").is_file()) self.assertTrue((stage / "commands" / "collect-template.ps1").is_file()) self.assertTrue((stage / "bitstreams" / bitstream.name).is_file()) self.assertTrue((stage / "td-receipts" / td_receipt.name).is_file()) self.assertEqual(short_bit.read_bytes(), bitstream.read_bytes()) self.assertEqual(json.loads(short_td.read_text(encoding="utf-8-sig"))["status"], "pass") self.assertLess(len(str(short_bit)), 100) self.assertTrue((stage / "config" / "pin_inventory.fcb_fpga_mcu0611.json").is_file()) self.assertTrue((stage / "schemas" / "real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json").is_file()) self.assertFalse((stage / "blocked").exists()) self.assertTrue((Path(tmp) / f"{package_name}.zip").is_file()) self.assertTrue((Path(tmp) / f"{package_name}.zip.sha256.txt").is_file()) start_here = (stage / "START-HERE.zh-CN.md").read_text(encoding="utf-8-sig") self.assertIn("PROGRAM_SRAM", start_here) self.assertIn("先准备并启动 BMC replay", start_here) self.assertIn("再启动 collector", start_here) self.assertIn("collector first, then PROGRAM_SRAM", start_here) self.assertIn(f"-Profile {profile}", start_here) self.assertIn(expected["host_ports"], start_here) self.assertIn("pc_replay_from_real_bmc_capture", start_here) self.assertIn("collector_protocol_profile=temp-uart-ptc-remap", start_here) self.assertIn(expected["bmc_tx"], start_here) self.assertIn(expected["bmc_rx"], start_here) self.assertIn("capture-bmc.ps1", start_here) self.assertIn("replay-bmc.ps1", start_here) self.assertLess(start_here.index("replay-bmc.ps1"), start_here.index("collect.ps1")) self.assertLess(start_here.index("collect.ps1"), start_here.index("PROGRAM_SRAM")) self.assertIn("bmc-replay-payload.example.json", start_here) self.assertIn("Python", start_here) self.assertIn("does not install Python/pip/driver", start_here) self.assertIn(expected["ptc_note"], start_here) if profile == "formal-uart1-bmc-replay": self.assertNotIn("PTC03/PTC04/PTC17/PTC18/PTC21/PTC22 使用临时", start_here) self.assertIn(".\\j6tmp.bit", start_here) self.assertIn(".\\td.json", start_here) self.assertIn("-File .\\collect.ps1", start_here) self.assertIn("Cannot open file", start_here) self.assertIn("bitstreams", start_here) self.assertNotIn(f".\\bitstreams\\{bitstream.name}", start_here) self.assertNotIn(f".\\td-receipts\\{td_receipt.name}", start_here) self.assertIn("powershell.exe -NoProfile -ExecutionPolicy Bypass -File", start_here) self.assertIn("-HostPort COM8 -DebugPort COM7", start_here) self.assertIn("tail drain", start_here) self.assertIn("[中文 runbook](docs/j6-host-sensor-real-fan-ptc-debug921-runbook.zh-CN.md)", start_here) self.assertIn("[collector 脚本](collector/collect-j6-host-sensor-real-fan-ptc.ps1)", start_here) self.assertIn("[SHA256 inventory](sha256-inventory.json)", start_here) self.assertNotIn("Set-ExecutionPolicy", start_here) self.assertNotIn("-AssumeManualSramProgrammed", start_here) self.assertNotIn("先手动刷 SRAM", start_here) self.assertNotIn("刷完 SRAM 后采集", start_here) collect_template = (stage / "commands" / "collect-template.ps1").read_text( encoding="utf-8-sig" ) self.assertNotIn("Set-ExecutionPolicy", collect_template) self.assertNotIn("-AssumeManualSramProgrammed", collect_template) self.assertIn("-NoProfile", collect_template) self.assertIn("-ExecutionPolicy Bypass", collect_template) self.assertIn("-File .\\collect.ps1", collect_template) shortcut = short_collect.read_text(encoding="utf-8-sig") self.assertIn("$PSHOME", shortcut) self.assertIn("$PSScriptRoot", shortcut) self.assertIn('"-File"', shortcut) self.assertIn('Join-Path $packageRoot "collector\\collect-j6-host-sensor-real-fan-ptc.ps1"', shortcut) self.assertIn('[string]$Bitstream = ".\\j6tmp.bit"', shortcut) self.assertIn('[string]$TdReceipt = ".\\td.json"', shortcut) self.assertIn('"-Bitstream"', shortcut) self.assertIn('"-TdReceipt"', shortcut) self.assertIn("[switch]$SelfTest", shortcut) self.assertNotIn("Set-ExecutionPolicy", shortcut) self.assertNotIn("-AssumeManualSramProgrammed", shortcut) self.assertNotIn("blocked_pin_conflict_with_locked_debug_uart", start_here) manifest = json.loads((stage / "manifest.json").read_text(encoding="utf-8-sig")) self.assertEqual(manifest["status"], "pass") self.assertEqual(manifest["pin_profile"], profile) self.assertIn("j6-bmc-replay", manifest["package_name"]) self.assertEqual(manifest["collector"]["user_profile_argument"], profile) self.assertEqual(manifest["collector"]["collector_protocol_profile"], "temp-uart-ptc-remap") self.assertEqual(manifest["collector"]["ready_profile_string"], "temp-uart-ptc-remap") self.assertEqual(manifest["bmc_source"], "pc_replay_from_real_bmc_capture") self.assertEqual(manifest["live_bmc_link_status"], "not_used") self.assertIn("Python", manifest["remote_dependencies"]) self.assertIn("no pip setup", manifest["remote_dependencies"]) self.assertIn("no driver", manifest["remote_dependencies"]) self.assertEqual(manifest["pin_map"]["hardware_access_status"], expected["hardware_access_status"]) self.assertEqual(manifest["pin_map"]["uart_assignments"]["bmc_replay_uart_tx"]["fpga_ball"], expected["bmc_tx"]) self.assertEqual(manifest["pin_map"]["uart_assignments"]["bmc_replay_uart_rx"]["fpga_ball"], expected["bmc_rx"]) self.assertEqual(manifest["programming_mode"], "PROGRAM_SRAM") self.assertEqual(manifest["bitstream"]["path"], "j6tmp.bit") self.assertEqual(manifest["td_receipt"]["path"], "td.json") self.assertEqual(manifest["short_path_aliases"]["bitstream"]["source"], f"bitstreams/{bitstream.name}") self.assertEqual(manifest["short_path_aliases"]["td_receipt"]["source"], f"td-receipts/{td_receipt.name}") self.assertIn("host_control_commands", manifest) self.assertIn("pin_map", manifest) self.assertIn("bmc_replay", manifest) self.assertIn("tail_drain", manifest) self.assertNotIn("pin_conflicts", manifest) inventory = json.loads((stage / "sha256-inventory.json").read_text(encoding="utf-8-sig")) self.assertEqual(inventory["self_hash_policy"], "excluded_self_referential_file") inventory_paths = {item["path"] for item in inventory["inventory"]} self.assertIn("manifest.json", inventory_paths) self.assertIn("START-HERE.zh-CN.md", inventory_paths) self.assertIn("j6tmp.bit", inventory_paths) self.assertIn("collect.ps1", inventory_paths) self.assertIn("td.json", inventory_paths) self.assertIn("collector/collect-j6-host-sensor-real-fan-ptc.ps1", inventory_paths) self.assertIn("bmc-replay/bmc_replay_uart.py", inventory_paths) self.assertIn("capture-bmc.ps1", inventory_paths) self.assertIn("replay-bmc.ps1", inventory_paths) self.assertIn("bmc-replay-payload.example.json", inventory_paths) self.assertIn("commands/collect-template.ps1", inventory_paths) self.assertNotIn("sha256-inventory.json", inventory_paths) def test_j6_host_sensor_real_fan_ptc_package_script_creates_formal_blocked_package_without_bitstream(self) -> None: powershell = shutil.which("powershell") if powershell is None: self.skipTest("PowerShell is not available") with tempfile.TemporaryDirectory() as tmp: td_receipt = Path(tmp) / "td-formal-fail.json" td_receipt.write_text( json.dumps( { "schema": "td-build-receipt-v1", "status": "fail", "top": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921", "pin_profile": "formal-uart1-bmc-replay", "phy": {"log_has_error": True}, "bitstream": None, } ), encoding="utf-8", ) result = subprocess.run( [ powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(ROOT / "tools" / "package_j6_host_sensor_real_fan_ptc_debug921.ps1"), "-OutputDir", tmp, "-PackageName", "j6-bmc-replay-formal-blocked-test", "-Profile", "formal-uart1-bmc-replay", "-TdReceipt", str(td_receipt), "-FormalBlocked", ], cwd=ROOT, capture_output=True, check=False, ) output = (result.stderr or b"").decode("utf-8", errors="replace") + ( result.stdout or b"" ).decode("utf-8", errors="replace") self.assertEqual(result.returncode, 0, output) stage = Path(tmp) / "j6-bmc-replay-formal-blocked-test" self.assertTrue(stage.is_dir()) self.assertFalse((stage / "j6tmp.bit").exists()) self.assertFalse((stage / "collect.ps1").exists()) self.assertTrue((stage / "FORMAL-BLOCKED.zh-CN.md").is_file()) self.assertTrue((stage / "START-HERE.zh-CN.md").is_file()) self.assertTrue((stage / "td.json").is_file()) self.assertTrue((Path(tmp) / "j6-bmc-replay-formal-blocked-test.zip").is_file()) start_here = (stage / "START-HERE.zh-CN.md").read_text(encoding="utf-8-sig") self.assertIn("blocked_td_mslice_over_limit", start_here) self.assertIn("1137", start_here) self.assertIn("1131", start_here) self.assertIn("1120", start_here) self.assertIn("不能刷机", start_here) self.assertNotIn("PROGRAM_SRAM", start_here) self.assertNotIn("j6tmp.bit", start_here) manifest = json.loads((stage / "manifest.json").read_text(encoding="utf-8-sig")) self.assertEqual(manifest["status"], "blocked_td_mslice_over_limit") self.assertEqual(manifest["pin_profile"], "formal-uart1-bmc-replay") self.assertEqual(manifest["bitstream"], None) self.assertEqual(manifest["real_fan_ptc_hardware_status"], "not_run") self.assertEqual(manifest["bmc_source"], "pc_replay_from_real_bmc_capture") self.assertEqual(manifest["blocked_reason"]["latest_attempt_mslices"], 1137) self.assertEqual(manifest["blocked_reason"]["best_observed_mslices"], 1131) self.assertEqual(manifest["pin_map"]["uart_assignments"]["debug_uart_tx"]["fpga_ball"], "N14") self.assertEqual(manifest["pin_map"]["uart_assignments"]["debug_uart_rx"]["fpga_ball"], "P15") inventory = json.loads((stage / "sha256-inventory.json").read_text(encoding="utf-8-sig")) inventory_paths = {item["path"] for item in inventory["inventory"]} self.assertIn("FORMAL-BLOCKED.zh-CN.md", inventory_paths) self.assertIn("td.json", inventory_paths) self.assertNotIn("j6tmp.bit", inventory_paths) def test_j6_host_sensor_real_fan_ptc_runbook_is_chinese_copy_paste_ready_with_english_paths(self) -> None: runbook = (ROOT / "docs" / "j6-host-sensor-real-fan-ptc-debug921-runbook.zh-CN.md").read_text( encoding="utf-8" ) for marker in [ "J6 Host Sensor Real FAN/PTC Debug921", "START-HERE.zh-CN.md", "temp-uart-ptc-remap", "PROGRAM_SRAM", "collector first, then PROGRAM_SRAM", "COM8", "COM7", "PTC03", "PTC04", "PTC17", "PTC18", "PTC21", "PTC22", "SET PTC 01 10", "SET PTC 24 20", "SET FAN 01 40", "SET FAN 04 30", "SET PID ENABLE", "GET SENSOR", "SET PID DISABLE", "DISABLE", "PTCCH", "FANCH", "1-based", "SENS", "DIMM", "J6TEMP", "J6RAW", "host-port-escaped.txt", "debug-uart-escaped.txt", "host-sensor-report.json", "bmc-raw-replay.bin", "不安装驱动", "不枚举未知 COM", "不写 DebugPort", "blocked_pin_conflict_with_locked_debug_uart", ]: self.assertIn(marker, runbook) for forbidden in [ "debug115", "Manual SRAM attestation status must be pass", "blocked_edit_required", "当前不要刷机", "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force", "先手动刷 SRAM", "确认 SRAM 下载完成后", r".\commands\collect-com8-host-com7-debug.ps1", r"bitstreams\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_primary.bit", "collector/collect-j6-host-sensor-real-fan-ptc.ps1", "SET PTC 00", "SET FAN 00", "SET FAN 05", "SET FAN 06", r".\collector\采集", ]: self.assertNotIn(forbidden, runbook) def test_j6_host_sensor_real_fan_ptc_schema_requires_sensor_pwm_pid_pinmap_and_debug_artifacts(self) -> None: schema = json.loads( (ROOT / "schemas" / "real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json").read_text( encoding="utf-8" ) ) layers = schema["properties"]["layers"]["properties"] self.assertEqual(schema["properties"]["diagnostic_scope"], {"const": "host_sensor_real_fan_ptc_debug921"}) for layer in [ "host_command_sequence", "host_control_transcript", "host_sensor_reports", "debug_frame_capture", "bmc_raw_sampling", "pid_boundary", "timeout_evidence", "pin_map", "real_fan_ptc_hardware_status", "artifact_hashes", ]: self.assertIn(layer, layers) commands = layers["host_command_sequence"]["properties"]["commands"]["prefixItems"] self.assertEqual(commands[0], {"const": "SET PTC 01 10"}) self.assertEqual(commands[1], {"const": "SET PTC 24 20"}) self.assertEqual(commands[2], {"const": "SET FAN 01 40"}) self.assertEqual(commands[3], {"const": "SET FAN 04 30"}) self.assertIn("host_sensor_report", layers["host_sensor_reports"]["required"]) self.assertIn("debug_frame_stream", layers["debug_frame_capture"]["required"]) self.assertIn("raw_replay", layers["debug_frame_capture"]["required"]) self.assertEqual(layers["pin_map"]["properties"]["ptc_count"], {"const": 24}) self.assertEqual(layers["pin_map"]["properties"]["fan_count"], {"const": 4}) if __name__ == "__main__": unittest.main()