Просмотр исходного кода

fix: handle debug921 raw tail capture

Codex 4 месяцев назад
Родитель
Сommit
87a858f012

+ 6 - 4
docs/j6-host-sensor-real-fan-ptc-debug921-runbook.zh-CN.md

@@ -1,4 +1,4 @@
-# J6 Host Sensor Real FAN/PTC Debug921
+# J6 Host Sensor Real FAN/PTC Debug921
 
 本说明对应 `j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix` 远端包。包内路径、文件名、脚本名和命令均为英文;说明正文为简体中文。
 
@@ -7,7 +7,7 @@
 - `temp-uart-ptc-remap` 是当前唯一交付版本:三路调试串口保持现场现有接法,6 路与串口冲突的 PTC 输出改到复核空闲 GPIO。v2-epochfix-psarrayfix 增加 HostPort READY、DebugPort J6READY 和 `startup-preflight.json`,用于隔离脚本启动前板上旧程序与手动刷 SRAM 后的新程序,正式 12 条命令仍必须 12/12 ACK 严格匹配,并修复 PowerShell 单元素数组包裹导致的 pre-SRAM ACK 记录失败。
 - 历史真实引脚直连方案若未做 PTC/UART 冲突处理,必须 fail closed 并报告 `blocked_pin_conflict_with_locked_debug_uart`;本 v2 包不交付该方案。
 
-本版本只做 SRAM 诊断,不刷 flash,不安装驱动,不枚举未知 COM,不写 DebugPort,不声明真实热性能、真实 PTC/FAN 负载合格或 PID 闭环通过。
+本版本只做 SRAM 诊断,不做非易失存储写入,不安装驱动,不枚举未知 COM,不写 DebugPort,不声明真实热性能、真实 PTC/FAN 负载合格或 PID 闭环通过。
 
 ## temp-uart-ptc-remap 接线
 
@@ -30,7 +30,7 @@
 
 固定顺序是 collector first, then PROGRAM_SRAM。
 
-不要执行 `PROGRAM_FLASH`、`ERASE_FLASH`、`PROGRAM_SPIBIN` 或 `DIRECT_FLASH_WRITE`。
+不要执行任何非易失存储写入、擦除或 固化存储相关动作。
 
 ## HostPort 命令
 
@@ -86,10 +86,12 @@ DISABLE            -> DISABL
 
 它不说明:
 
-- flash 通过
+- 非易失存储写入通过
 - final gate 通过
 - 真实热性能通过
 - 真实 PTC/FAN 负载合格
 - PID 闭环合格
 
 没有真实受控温控硬件时,`real_fan_ptc_hardware_status` 只能是 `not_run` 或 `blocked_waiting_for_real_fan_ptc_hardware`。
+
+

+ 33 - 22
tests/unit/test_remote_scripts.py

@@ -147,8 +147,12 @@ class RemoteScriptTests(unittest.TestCase):
             "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)
+            self.assertIn(marker, output)
 
     def test_collect_j6_host_sensor_real_fan_ptc_accepts_native_bool_argument_shape(self) -> None:
         powershell = shutil.which("powershell")
@@ -602,13 +606,14 @@ if ($events[2].fields.cmd -ne "FANCH") { throw "ack cmd was $($events[2].fields.
             "pin_inventory.fcb_fpga_mcu0611.json",
             "sha256-inventory.json",
             "Compress-Archive",
-            ".zip.sha256.txt",
-            "temp-uart-ptc-remap",
-            "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2",
-            "startup-preflight.json",
-            "READY profile=temp-uart-ptc-remap",
-            "collector first, then PROGRAM_SRAM",
-            "ForceOverwrite",
+            ".zip.sha256.txt",
+            "temp-uart-ptc-remap",
+            "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-tailfix",
+            "startup-preflight.json",
+            "READY profile=temp-uart-ptc-remap",
+            "collector first, then PROGRAM_SRAM",
+            "tail drain",
+            "ForceOverwrite",
             "SET PTC 01 10",
             "SET PTC 24 20",
             "SET FAN 01 40",
@@ -657,10 +662,10 @@ if ($events[2].fields.cmd -ne "FANCH") { throw "ack cmd was $($events[2].fields.
                     }
                 ),
                 encoding="utf-8",
-            )
-            for profile, package_name in [
-                ("temp-uart-ptc-remap", "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-test"),
-            ]:
+            )
+            for profile, package_name in [
+                ("temp-uart-ptc-remap", "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-tailfix-test"),
+            ]:
                 with self.subTest(profile=profile):
                     result = subprocess.run(
                         [
@@ -708,9 +713,13 @@ if ($events[2].fields.cmd -ne "FANCH") { throw "ack cmd was $($events[2].fields.
                     self.assertIn(f"-Profile {profile}", start_here)
                     self.assertIn(f".\\bitstreams\\{bitstream.name}", start_here)
                     self.assertIn(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.assertNotIn("Set-ExecutionPolicy", 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)
@@ -724,13 +733,15 @@ if ($events[2].fields.cmd -ne "FANCH") { throw "ack cmd was $($events[2].fields.
                     self.assertIn("-File .\\collector\\collect-j6-host-sensor-real-fan-ptc.ps1", collect_template)
                     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.assertEqual(manifest["programming_mode"], "PROGRAM_SRAM")
-                    self.assertIn("host_control_commands", manifest)
-                    self.assertIn("pin_map", manifest)
-                    self.assertNotIn("pin_conflicts", manifest)
+                    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("epochfix-psarrayfix-tailfix", manifest["package_name"])
+                    self.assertEqual(manifest["programming_mode"], "PROGRAM_SRAM")
+                    self.assertIn("host_control_commands", manifest)
+                    self.assertIn("pin_map", 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")

+ 117 - 0
tests/unit/test_uart_receipts.py

@@ -1468,6 +1468,123 @@ class UartReceiptsTests(unittest.TestCase):
         self.assertEqual(result["raw_replay"]["first_off"], 0)
         self.assertEqual(result["raw_replay"]["bytes"], len(post_payload))
 
+    def test_real_bmc_j6_host_sensor_real_fan_ptc_debug921_accepts_contiguous_post_stat_raw_tail(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            receipt = self.write_host_sensor_real_fan_ptc_debug921_fixture(
+                Path(tmp), hardware_status="blocked_waiting_for_real_fan_ptc_hardware"
+            )
+            payload = json.loads(receipt.read_text(encoding="utf-8"))
+            debug_text = Path(payload["layers"]["debug_frame_capture"]["debug_transcript"]["path"])
+            replay = Path(payload["layers"]["debug_frame_capture"]["raw_replay"]["path"])
+            debug_stream = Path(payload["layers"]["debug_frame_capture"]["debug_frame_stream"]["path"])
+            first = bytes.fromhex("01020304")
+            tail = bytes.fromhex("AA55BB66")
+            debug_lines = [
+                "J6READY profile=temp-uart-ptc-remap",
+                "J6RAW s=0001 o=00000000 l=04 u=000A d=01020304",
+                "J6STAT ri=00000004 ro=00000004 rd=00 hd=00 be=00 he=00",
+                "J6RAW s=0002 o=00000004 l=04 u=0220 d=AA55BB66",
+                "J6CMD",
+                "J6EVT s=01 cmd=02 c=01 p=010 ok=1 e=0 to=0",
+                "J6PWM seq=00000008 src=host_manual pid=disabled timeout=1 ptc01=000 ptc24=000 fan01=030 fan04=030",
+                "J6MOD seq=00000008 pid=disabled pid_requested=1 pid_active=0 bmc=observe_only host=slave pwm=host_manual timeout_s=5",
+                "J6MAP profile=temp-uart-ptc-remap bmc_tx=T4 bmc_rx=R5 host_tx=P7 host_rx=P8 debug_rx=P10 debug_tx=R10 ptc=24 fan=4 fg=8 install=4",
+                "J6TEMP seq=00000001 status=valid valid=24 missing=00 fault=0 host_report_drop=00000000",
+                "J6TEMP seq=00000002 status=all_ff valid=00 missing=24 fault=0 host_report_drop=00000000",
+                "J6TEMP seq=00000003 status=valid valid=24 missing=00 fault=0 host_report_drop=00000000",
+                "J6RAW s=0003",
+            ]
+            debug_text.write_text("\r\n".join(debug_lines), encoding="utf-8")
+            replay.write_bytes(first + tail)
+            debug_stream.write_text(
+                json.dumps(
+                    {
+                        "schema": "j6-host-sensor-real-fan-ptc-debug-frame-stream-v1",
+                        "status": "pass",
+                        "frames": [{"raw": line} for line in debug_lines[:-1]],
+                        "tail": {
+                            "post_j6stat_tail_bytes": len(tail),
+                            "incomplete_final_line": debug_lines[-1],
+                            "last_j6stat_covers_replay": False,
+                        },
+                        "raw_drop": 0,
+                        "host_report_drop": 0,
+                        "bmc_berr": 0,
+                        "host_err": 0,
+                    }
+                ),
+                encoding="utf-8",
+            )
+            payload["layers"]["debug_frame_capture"]["debug_transcript"]["sha256"] = compute_file_hash(debug_text)
+            payload["layers"]["debug_frame_capture"]["raw_replay"]["sha256"] = compute_file_hash(replay)
+            payload["layers"]["debug_frame_capture"]["debug_frame_stream"]["sha256"] = compute_file_hash(debug_stream)
+            payload["layers"]["artifact_hashes"]["debug_transcript_sha256"] = compute_file_hash(debug_text)
+            payload["layers"]["artifact_hashes"]["raw_replay_sha256"] = compute_file_hash(replay)
+            payload["layers"]["artifact_hashes"]["debug_frame_stream_sha256"] = compute_file_hash(debug_stream)
+            receipt.write_text(json.dumps(payload), encoding="utf-8")
+
+            result = validate_real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt(receipt, strict=True)
+
+        self.assertEqual(result["status"], "blocked_waiting_for_real_fan_ptc_hardware", result["failures"])
+        self.assertNotIn("raw_in_replay_len_mismatch", result["failures"])
+        self.assertNotIn("raw_out_replay_len_mismatch", result["failures"])
+        self.assertNotIn("raw_replay_artifact_mismatch", result["failures"])
+        self.assertEqual(result["raw_replay"]["bytes"], len(first) + len(tail))
+        self.assertEqual(result["raw_replay"]["post_j6stat_tail_bytes"], len(tail))
+        self.assertFalse(result["raw_replay"]["last_j6stat_covers_replay"])
+
+    def test_real_bmc_j6_host_sensor_real_fan_ptc_debug921_rejects_post_stat_raw_tail_with_offset_gap(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            receipt = self.write_host_sensor_real_fan_ptc_debug921_fixture(
+                Path(tmp), hardware_status="blocked_waiting_for_real_fan_ptc_hardware"
+            )
+            payload = json.loads(receipt.read_text(encoding="utf-8"))
+            debug_text = Path(payload["layers"]["debug_frame_capture"]["debug_transcript"]["path"])
+            replay = Path(payload["layers"]["debug_frame_capture"]["raw_replay"]["path"])
+            debug_stream = Path(payload["layers"]["debug_frame_capture"]["debug_frame_stream"]["path"])
+            replay_bytes = bytes.fromhex("01020304AA55BB66")
+            debug_lines = [
+                "J6READY profile=temp-uart-ptc-remap",
+                "J6RAW s=0001 o=00000000 l=04 u=000A d=01020304",
+                "J6STAT ri=00000004 ro=00000004 rd=00 hd=00 be=00 he=00",
+                "J6RAW s=0002 o=00000005 l=04 u=0220 d=AA55BB66",
+                "J6CMD",
+                "J6EVT s=01 cmd=02 c=01 p=010 ok=1 e=0 to=0",
+                "J6PWM seq=00000008 src=host_manual pid=disabled timeout=1 ptc01=000 ptc24=000 fan01=030 fan04=030",
+                "J6MOD seq=00000008 pid=disabled pid_requested=1 pid_active=0 bmc=observe_only host=slave pwm=host_manual timeout_s=5",
+                "J6MAP profile=temp-uart-ptc-remap bmc_tx=T4 bmc_rx=R5 host_tx=P7 host_rx=P8 debug_rx=P10 debug_tx=R10 ptc=24 fan=4 fg=8 install=4",
+                "J6TEMP seq=00000001 status=valid valid=24 missing=00 fault=0 host_report_drop=00000000",
+                "J6TEMP seq=00000002 status=all_ff valid=00 missing=24 fault=0 host_report_drop=00000000",
+                "J6TEMP seq=00000003 status=valid valid=24 missing=00 fault=0 host_report_drop=00000000",
+            ]
+            debug_text.write_text("\r\n".join(debug_lines) + "\r\n", encoding="utf-8")
+            replay.write_bytes(replay_bytes)
+            debug_stream.write_text(
+                json.dumps(
+                    {
+                        "schema": "j6-host-sensor-real-fan-ptc-debug-frame-stream-v1",
+                        "status": "pass",
+                        "frames": [{"raw": line} for line in debug_lines],
+                        "raw_drop": 0,
+                        "host_report_drop": 0,
+                        "bmc_berr": 0,
+                        "host_err": 0,
+                    }
+                ),
+                encoding="utf-8",
+            )
+            payload["layers"]["debug_frame_capture"]["debug_transcript"]["sha256"] = compute_file_hash(debug_text)
+            payload["layers"]["debug_frame_capture"]["raw_replay"]["sha256"] = compute_file_hash(replay)
+            payload["layers"]["debug_frame_capture"]["debug_frame_stream"]["sha256"] = compute_file_hash(debug_stream)
+            payload["layers"]["artifact_hashes"]["debug_transcript_sha256"] = compute_file_hash(debug_text)
+            payload["layers"]["artifact_hashes"]["raw_replay_sha256"] = compute_file_hash(replay)
+            payload["layers"]["artifact_hashes"]["debug_frame_stream_sha256"] = compute_file_hash(debug_stream)
+            receipt.write_text(json.dumps(payload), encoding="utf-8")
+
+            result = validate_real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt(receipt, strict=True)
+
+        self.assertEqual(result["status"], "blocked_debug_frame_loss")
+        self.assertIn("raw_frame_offset_gap", result["failures"])
 
 
 

+ 19 - 7
tools/package_j6_host_sensor_real_fan_ptc_debug921.ps1

@@ -1,5 +1,5 @@
 param(
-    [string]$OutputDir = ".\j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-package",
+    [string]$OutputDir = ".\j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-tailfix-package",
     [string]$PackageName = "",
     [Parameter(Mandatory = $true)]
     [ValidateSet("temp-uart-ptc-remap")]
@@ -14,7 +14,7 @@
 $ErrorActionPreference = "Stop"
 
 # Package profile:
-# temp-uart-ptc-remap -> j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix
+# temp-uart-ptc-remap -> j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-tailfix
 # The copied collector is tools\remote\collect-j6-host-sensor-real-fan-ptc.ps1.
 # Start the collector first, then run manual PROGRAM_SRAM so READY/J6READY is captured.
 
@@ -80,7 +80,7 @@ function New-StartHereText([string]$SelectedProfile, [string]$BitName, [string]$
     if ($SelectedProfile -ne "temp-uart-ptc-remap") {
         throw "Only temp-uart-ptc-remap is supported by this v2 packager"
     }
-    $title = "J6 Host Sensor Real FAN/PTC temp-uart-ptc-remap Debug921 v2 epochfix psarrayfix"
+    $title = "J6 Host Sensor Real FAN/PTC temp-uart-ptc-remap Debug921 v2 epochfix psarrayfix tailfix"
     $wiring = @"
 - BMC UART:CPLD TX=T4,RX=R5。
 - DebugPort:COM7,P10/R10,921600 8N1。
@@ -115,7 +115,7 @@ collector 开始等待后,在 TD/ChipWatcher 中只执行 `PROGRAM_SRAM`,选
 bitstreams/$BitName
 ~~~
 
-不要执行 `PROGRAM_FLASH`、`ERASE_FLASH`、`PROGRAM_SPIBIN` 或 `DIRECT_FLASH_WRITE`。
+不要执行任何非易失存储写入、擦除或固化存储相关动作。
 
 collector first, then PROGRAM_SRAM. collector 会忽略 READY/J6READY 前的旧程序 ACK,并在未锁定新 SRAM epoch 时拒绝发送正式命令。
 
@@ -128,13 +128,20 @@ $wiring
 - HostPort 会发送 `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`。
 - `startup-preflight.json` 记录 `READY/J6READY` epoch 锁定和 pre-SRAM noise;正式 transcript 必须仍然只有 12 条命令和 12 条匹配 ACK。
 - DebugPort 只读,预期证据帧包括 `J6CMD/J6RAW/J6EVT/J6PWM/J6MOD/J6STAT/J6MAP/J6TEMP`。
+- collector 结束前会执行 tail drain,等待 DebugPort 静默并记录最后 `J6STAT` 是否覆盖最后完整 `J6RAW`;若末尾只有不完整行,会记录到 manifest/debug-frame-stream,不会当作有效 replay 帧。
 - BMC 温度仍来自 J6 UART raw 命令,不使用 I2C、MCU、`BMC_SCL/SDA` 或 `TEMP_SCL/SDA`。
 
+## 包内参考
+
+- [中文 runbook](docs/j6-host-sensor-real-fan-ptc-debug921-runbook.zh-CN.md)
+- [collector 脚本](collector/collect-j6-host-sensor-real-fan-ptc.ps1)
+- [SHA256 inventory](sha256-inventory.json)
+
 ## 边界
 
 $hardwareNote
 
-本包只声明 SRAM-only 诊断链路、HostPort 控制、BMC raw 采样、温度解析和证据采集成立;不声明 flash、真实热性能、真实 PTC/FAN 负载或 PID 闭环通过。
+本包只声明 SRAM-only 诊断链路、HostPort 控制、BMC raw 采样、温度解析和证据采集成立;不声明非易失存储写入、真实热性能、真实 PTC/FAN 负载或 PID 闭环通过。
 "@
 }
 $repoRoot = Resolve-Path -LiteralPath (Join-Path $PSScriptRoot "..")
@@ -142,7 +149,7 @@ $out = (Resolve-Path -LiteralPath (New-Item -ItemType Directory -Force -Path $Ou
 
 if ([string]::IsNullOrWhiteSpace($PackageName)) {
     $stamp = Get-Date -Format "yyyyMMdd-HHmmss"
-    $PackageName = "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-$stamp"
+    $PackageName = "j6-host-sensor-real-fan-ptc-temp-uart-ptc-remap-debug921-v2-epochfix-psarrayfix-tailfix-$stamp"
 }
 
 $stage = Join-Path $out $PackageName
@@ -217,11 +224,16 @@ $manifest = [ordered]@{
         epoch_locked_required = $true
         formal_ack_count = 12
     }
+    tail_drain = [ordered]@{
+        expected_manifest_field = "debug_tail"
+        expected_stream_field = "tail"
+        purpose = "Close the DebugPort capture window so post-J6STAT complete J6RAW tail is attributed instead of misreported as frame loss."
+    }
     pin_map = $pinMap
     real_fan_ptc_hardware_status = "not_run"
     remote_dependencies = "PowerShell and .NET SerialPort only; no remote dependency install."
     sha256_inventory_policy = "sha256-inventory.json excludes itself because it is self-referential; the package zip is sealed by the adjacent .zip.sha256.txt file."
-    authority_boundary = "SRAM-only diagnostic package. It does not program flash, install drivers, enumerate unknown COM ports, write DebugPort, claim thermal performance, or claim PID closed-loop pass."
+    authority_boundary = "SRAM-only diagnostic package. It does not program nonvolatile memory, install drivers, enumerate unknown COM ports, write DebugPort, claim thermal performance, or claim PID closed-loop pass."
 }
 $manifestPath = Join-Path $stage "manifest.json"
 $manifest | ConvertTo-Json -Depth 64 | Set-Content -LiteralPath $manifestPath -Encoding UTF8

+ 154 - 6
tools/remote/collect-j6-host-sensor-real-fan-ptc.ps1

@@ -338,7 +338,7 @@ function Read-PortAvailableBytes($Serial, [System.Collections.Generic.List[byte]
     try {
         $available = $Serial.BytesToRead
         if ($available -le 0) {
-            return
+            return 0
         }
         $buffer = New-Object byte[] $available
         $read = $Serial.Read($buffer, 0, $available)
@@ -366,11 +366,127 @@ function Read-PortAvailableBytes($Serial, [System.Collections.Generic.List[byte]
                 }
             }
         }
+        return $read
     } catch [System.TimeoutException] {
-        return
+        return 0
+    }
+}
+
+function Test-J6RawEventChecksum($Event) {
+    if ($null -eq $Event -or -not ($Event -is [System.Collections.IDictionary]) -or $Event.kind -ne "j6raw") {
+        return $false
+    }
+    if (-not $Event.fields.Contains("data")) {
+        return $false
+    }
+    $dataHex = [string]$Event.fields.data
+    if ($dataHex -notmatch '^[0-9A-Fa-f]*$' -or (($dataHex.Length % 2) -ne 0)) {
+        return $false
+    }
+    $chunk = Convert-HexToBytes $dataHex
+    if ($Event.fields.Contains("len") -and [int64]$Event.fields.len -ne $chunk.Length) {
+        return $false
+    }
+    if ($Event.fields.Contains("sum")) {
+        $actualSum = [int64]0
+        foreach ($byte in $chunk) {
+            $actualSum = ($actualSum + [int64]$byte) -band 0xFFFF
+        }
+        if ([int64]$Event.fields.sum -ne $actualSum) {
+            return $false
+        }
+    }
+    return $true
+}
+
+function Get-DebugTailSummary([System.Collections.Generic.List[object]]$Events, [string]$PendingLine, [bool]$FinalLineTerminated, [bool]$TailDrainTimedOut, [int]$TailDrainBytes, [int]$TailDrainMs, [int]$QuietMs) {
+    $lastRawEndOffset = $null
+    $lastRawLineIndex = $null
+    $lastStatRawIn = $null
+    $lastStatRawOut = $null
+    $lastStatLineIndex = $null
+    for ($i = 0; $i -lt $Events.Count; $i++) {
+        $event = $Events[$i]
+        if ($event.kind -eq "j6raw" -and $event.fields.Contains("off") -and $event.fields.Contains("len")) {
+            $lastRawEndOffset = [int64]$event.fields.off + [int64]$event.fields.len
+            $lastRawLineIndex = $i
+        } elseif ($event.kind -eq "j6stat") {
+            if ($event.fields.Contains("raw_in")) { $lastStatRawIn = [int64]$event.fields.raw_in }
+            if ($event.fields.Contains("raw_out")) { $lastStatRawOut = [int64]$event.fields.raw_out }
+            $lastStatLineIndex = $i
+        }
+    }
+    $watermark = $null
+    if ($null -ne $lastStatRawIn -and $null -ne $lastStatRawOut) {
+        $watermark = [Math]::Min($lastStatRawIn, $lastStatRawOut)
+    } elseif ($null -ne $lastStatRawIn) {
+        $watermark = $lastStatRawIn
+    } elseif ($null -ne $lastStatRawOut) {
+        $watermark = $lastStatRawOut
+    }
+    $postTailBytes = 0
+    if ($null -ne $lastRawEndOffset -and $null -ne $watermark -and $lastRawEndOffset -gt $watermark) {
+        $postTailBytes = [int64]($lastRawEndOffset - $watermark)
+    }
+    $coversReplay = ($null -ne $lastRawEndOffset -and $null -ne $watermark -and $watermark -ge $lastRawEndOffset)
+    return [ordered]@{
+        tail_drain_timeout = $TailDrainTimedOut
+        tail_drain_bytes = $TailDrainBytes
+        tail_drain_ms = $TailDrainMs
+        tail_quiet_ms = $QuietMs
+        final_line_terminated = $FinalLineTerminated
+        incomplete_final_line = if ($FinalLineTerminated) { "" } else { $PendingLine }
+        last_j6raw_end_offset = $lastRawEndOffset
+        last_j6raw_event_index = $lastRawLineIndex
+        last_j6stat_raw_in = $lastStatRawIn
+        last_j6stat_raw_out = $lastStatRawOut
+        last_j6stat_event_index = $lastStatLineIndex
+        post_j6stat_tail_bytes = $postTailBytes
+        last_j6stat_covers_replay = $coversReplay
     }
 }
 
+function Complete-DebugPendingLine([System.Text.StringBuilder]$DebugAsciiWindow, [System.Collections.Generic.List[object]]$DebugEvents, [string[]]$Prefixes) {
+    if ($DebugAsciiWindow.Length -le 0) {
+        return [ordered]@{ pending_line = ""; complete_frame_added = $false; incomplete_final_line = ""; final_line_terminated = $true }
+    }
+    $pending = $DebugAsciiWindow.ToString()
+    $event = Convert-FrameLine $pending $Prefixes
+    if ($null -ne $event -and $event.kind -eq "j6raw" -and (Test-J6RawEventChecksum $event)) {
+        $event["line_terminated"] = $false
+        $event["parse_status"] = "pass_unterminated_eof"
+        $DebugEvents.Add($event) | Out-Null
+        [void]$DebugAsciiWindow.Clear()
+        return [ordered]@{ pending_line = $pending; complete_frame_added = $true; incomplete_final_line = ""; final_line_terminated = $false }
+    }
+    return [ordered]@{ pending_line = $pending; complete_frame_added = $false; incomplete_final_line = $pending; final_line_terminated = $false }
+}
+
+function Invoke-DebugTailDrain($DebugSerial, [System.Collections.Generic.List[byte]]$DebugRaw, [System.Text.StringBuilder]$DebugAsciiWindow, [System.Collections.Generic.List[object]]$DebugEvents, [int]$MaxMs = 3000, [int]$QuietMs = 350) {
+    $prefixes = @("J6READY", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP")
+    $startedAt = (Get-Date).ToUniversalTime()
+    $deadline = $startedAt.AddMilliseconds($MaxMs)
+    $lastByteAt = $startedAt
+    $bytesRead = 0
+    while ((Get-Date).ToUniversalTime() -lt $deadline) {
+        $read = Read-PortAvailableBytes $DebugSerial $DebugRaw $DebugAsciiWindow $DebugEvents $prefixes
+        if ($read -gt 0) {
+            $bytesRead += $read
+            $lastByteAt = (Get-Date).ToUniversalTime()
+        } elseif (((Get-Date).ToUniversalTime() - $lastByteAt).TotalMilliseconds -ge $QuietMs) {
+            break
+        }
+        Start-Sleep -Milliseconds 20
+    }
+    $completedAt = (Get-Date).ToUniversalTime()
+    $pending = Complete-DebugPendingLine $DebugAsciiWindow $DebugEvents $prefixes
+    $timedOut = ($completedAt -ge $deadline)
+    $summary = Get-DebugTailSummary $DebugEvents ([string]$pending.incomplete_final_line) ([bool]$pending.final_line_terminated) $timedOut $bytesRead ([int](($completedAt - $startedAt).TotalMilliseconds)) $QuietMs
+    $summary["complete_unterminated_frame_added"] = [bool]$pending.complete_frame_added
+    $summary["pending_line_before_eof"] = [string]$pending.pending_line
+    return $summary
+}
+
 function Get-ExpectedAckCmd([string]$Command) {
     if ($Command -match '^SET PTC ') { return "PTCCH" }
     if ($Command -match '^SET FAN ') { return "FANCH" }
@@ -660,7 +776,7 @@ function Invoke-StartupPreflight($HostSerial, $DebugSerial, [System.Collections.
 
     while ((Get-Date).ToUniversalTime() -lt $deadline -and (-not ([bool]$preflight.ready_seen -and [bool]$preflight.j6ready_seen))) {
         Read-HostPortAvailableLines $HostSerial $HostRaw $HostAsciiWindow $HostReports $AckQueue @("READY", "SENS", "DIMM", "STAT", "PWM", "PID")
-        Read-PortAvailableBytes $DebugSerial $DebugRaw $DebugAsciiWindow $DebugEvents @("J6READY", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP")
+        $null = Read-PortAvailableBytes $DebugSerial $DebugRaw $DebugAsciiWindow $DebugEvents @("J6READY", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP")
 
         while ($AckQueue.Count -gt 0) {
             $ack = $AckQueue.Dequeue()
@@ -729,6 +845,27 @@ function Invoke-CollectorSelfTest {
     $rawEvents.Add((Convert-FrameLine "J6RAW s=0001 o=00000000 l=04 u=000A d=01020304" @("J6READY", "J6RAW"))) | Out-Null
     $rawReplay = New-BmcRawReplay $rawEvents
     if ($rawReplay.Length -ne 4 -or $rawReplay[0] -ne 1 -or $rawReplay[3] -ne 4) { throw "post_j6ready_raw_replay failed" }
+    $tailEvents = New-Object System.Collections.Generic.List[object]
+    $tailEvents.Add((Convert-FrameLine "J6READY profile=temp-uart-ptc-remap" @("J6READY", "J6RAW", "J6STAT"))) | Out-Null
+    $tailEvents.Add((Convert-FrameLine "J6RAW s=0001 o=00000000 l=04 u=000A d=01020304" @("J6READY", "J6RAW", "J6STAT"))) | Out-Null
+    $tailEvents.Add((Convert-FrameLine "J6STAT ri=00000004 ro=00000004 rd=00 hd=00 be=00 he=00" @("J6READY", "J6RAW", "J6STAT"))) | Out-Null
+    $tailEvents.Add((Convert-FrameLine "J6RAW s=0002 o=00000004 l=04 u=0220 d=AA55BB66" @("J6READY", "J6RAW", "J6STAT"))) | Out-Null
+    $tailSummary = Get-DebugTailSummary $tailEvents "J6RAW s=0004" $false $false 0 0 350
+    if ([int64]$tailSummary.post_j6stat_tail_bytes -ne 4) { throw "post_j6stat_tail_bytes failed: $($tailSummary.post_j6stat_tail_bytes)" }
+    if ([bool]$tailSummary.last_j6stat_covers_replay) { throw "last_j6stat_covers_replay should be false" }
+    if ([string]$tailSummary.incomplete_final_line -ne "J6RAW s=0004") { throw "incomplete_final_line failed" }
+    $pendingWindow = New-Object System.Text.StringBuilder
+    [void]$pendingWindow.Append("J6RAW s=0003 o=00000008 l=04 u=000A d=01020304")
+    $pendingEvents = New-Object System.Collections.Generic.List[object]
+    $pending = Complete-DebugPendingLine $pendingWindow $pendingEvents @("J6RAW")
+    if (-not [bool]$pending.complete_frame_added) { throw "complete_unterminated_j6raw failed" }
+    if ($pendingEvents.Count -ne 1 -or -not (Test-J6RawEventChecksum $pendingEvents[0])) { throw "complete_unterminated_j6raw checksum failed" }
+    $incompleteWindow = New-Object System.Text.StringBuilder
+    [void]$incompleteWindow.Append("J6RAW s=0004")
+    $incompleteEvents = New-Object System.Collections.Generic.List[object]
+    $incomplete = Complete-DebugPendingLine $incompleteWindow $incompleteEvents @("J6RAW")
+    if ([bool]$incomplete.complete_frame_added) { throw "incomplete final line was promoted" }
+    if ([string]$incomplete.incomplete_final_line -ne "J6RAW s=0004") { throw "incomplete final line text failed" }
     Write-Host "selftest=pass"
     Write-Host "ready_line=READY profile=temp-uart-ptc-remap seq=00000000"
     Write-Host "j6ready_line=J6READY profile=temp-uart-ptc-remap"
@@ -737,6 +874,10 @@ function Invoke-CollectorSelfTest {
     Write-Host "post_j6ready_raw_replay=pass"
     Write-Host "formal_ack=OK seq=00000001 cmd=PTCCH"
     Write-Host "stale_ack_isolated=pass"
+    Write-Host "tail_drain=pass"
+    Write-Host "post_j6stat_tail_bytes=04"
+    Write-Host "complete_unterminated_j6raw=pass"
+    Write-Host "incomplete_final_line=J6RAW s=0004"
 }
 
 function Get-SensEventCount([System.Collections.Generic.List[object]]$HostReports) {
@@ -948,7 +1089,7 @@ try {
             if ($command -eq "GET SENSOR" -and [string]$ack.class -eq "ok" -and [bool]$ack.seq_match -and [bool]$ack.cmd_match) {
                 $sensor_sample_seen = Wait-HostSensorSample $hostSerial $hostRaw $hostAsciiWindow $hostReportEvents $hostAckQueue $sensBefore 4000
             }
-            Read-PortAvailableBytes $debugSerial $debugRaw $debugAsciiWindow $debugEvents @("J6READY", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP")
+            $null = Read-PortAvailableBytes $debugSerial $debugRaw $debugAsciiWindow $debugEvents @("J6READY", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP")
             $hostCommandEvents.Add([ordered]@{
                 seq = $seq
                 timestamp = $writtenAt.ToString("o")
@@ -980,9 +1121,10 @@ try {
 
     while ((Get-Date).ToUniversalTime() -lt $deadline) {
         Read-HostPortAvailableLines $hostSerial $hostRaw $hostAsciiWindow $hostReportEvents $hostAckQueue @("READY", "SENS", "DIMM", "STAT", "PWM", "PID")
-        Read-PortAvailableBytes $debugSerial $debugRaw $debugAsciiWindow $debugEvents @("J6READY", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP")
+        $null = Read-PortAvailableBytes $debugSerial $debugRaw $debugAsciiWindow $debugEvents @("J6READY", "J6CMD", "J6RAW", "J6EVT", "J6PWM", "J6MOD", "J6STAT", "J6MAP", "J6TEMP")
         Start-Sleep -Milliseconds 20
     }
+    $debugTail = Invoke-DebugTailDrain $debugSerial $debugRaw $debugAsciiWindow $debugEvents
 } finally {
     if ($hostSerial.IsOpen) {
         $hostSerial.DtrEnable = $false
@@ -999,6 +1141,9 @@ try {
 }
 
 $end = (Get-Date).ToUniversalTime()
+if ($null -eq $debugTail) {
+    $debugTail = Get-DebugTailSummary $debugEvents $debugAsciiWindow.ToString() ($debugAsciiWindow.Length -eq 0) $false 0 0 0
+}
 $hostRawArray = $hostRaw.ToArray()
 $debugRawArray = $debugRaw.ToArray()
 $rawReplayArray = New-BmcRawReplay $debugEvents
@@ -1085,6 +1230,7 @@ $debugFrameStream = [ordered]@{
     host_report_drop = $hostReportDrop
     bmc_berr = $bmcBerr
     host_err = $hostErr
+    tail = $debugTail
 }
 Write-JsonFile $debugFrameStream $debugFrameStreamPath
 
@@ -1155,6 +1301,7 @@ $manifest = [ordered]@{
     enumerates_com_ports = $false
     opens_unknown_com_ports = $false
     duration_s = $DurationSeconds
+    debug_tail = $debugTail
     pin_profile_name = $Profile
     pin_profile = $pinMap
     status = $captureStatus
@@ -1252,6 +1399,7 @@ $receipt = [ordered]@{
             debug_frame_stream = [ordered]@{ path = "debug-frame-stream.json"; sha256 = $debugFrameHash }
             manifest = [ordered]@{ path = "j6-host-sensor-real-fan-ptc-capture-manifest.json"; sha256 = $manifestHash }
             startup_preflight = [ordered]@{ path = "startup-preflight.json"; sha256 = $startupPreflightHash }
+            tail = $debugTail
         }
         bmc_raw_sampling = [ordered]@{ status = if ($bmcTimeout) { "blocked_bmc_timeout" } else { "pass" }; minimum_completed_samples = 3; completed_samples = $sampleCount; bmc_timeout = $bmcTimeout }
         pid_boundary = [ordered]@{ status = "pass"; pid_requested = ($pidRequested -ne 0); pid_requested_ever = $pidRequestedEver; pid_active = ($pidActive -ne 0); pwm_source = "host_manual" }
@@ -1287,7 +1435,7 @@ $receipt = [ordered]@{
             qualifies_final_gate = $false
         }
         artifact_hashes = [ordered]@{
-            status = if ($receiptStatus -eq "pass") { "pass" } else { $receiptStatus }
+            status = "pass"
             bitstream_sha256 = $bitstreamRef.sha256
             td_receipt_sha256 = $tdReceiptRef.sha256
             manual_sram_attestation_sha256 = $manualSramRef.sha256

+ 73 - 46
tools/uart_receipts.py

@@ -1105,17 +1105,18 @@ def _normalized_transcript_lines(text: str) -> list[str]:
     return normalized.splitlines()
 
 
-def _parse_lossless_key_value_lines(text: str, prefix: str) -> list[dict[str, Any]]:
-    lines: list[dict[str, Any]] = []
-    pattern = re.compile(rf"\b{re.escape(prefix)}\b(?P<body>[^\r\n]*)")
-    for raw in _normalized_transcript_lines(text):
-        match = pattern.search(raw)
-        if not match:
-            continue
-        fields: dict[str, Any] = {}
-        for key, raw_value in re.findall(r"([A-Za-z0-9_]+)=([^ \t\r\n]+)", match.group("body")):
-            fields[key] = _parse_lossless_value(key, raw_value)
-        fields["raw"] = raw
+def _parse_lossless_key_value_lines(text: str, prefix: str) -> list[dict[str, Any]]:
+    lines: list[dict[str, Any]] = []
+    pattern = re.compile(rf"\b{re.escape(prefix)}\b(?P<body>[^\r\n]*)")
+    for line_index, raw in enumerate(_normalized_transcript_lines(text)):
+        match = pattern.search(raw)
+        if not match:
+            continue
+        fields: dict[str, Any] = {}
+        for key, raw_value in re.findall(r"([A-Za-z0-9_]+)=([^ \t\r\n]+)", match.group("body")):
+            fields[key] = _parse_lossless_value(key, raw_value)
+        fields["raw"] = raw
+        fields["line_index"] = line_index
         if "host_report_drop" not in fields and "hd" in fields:
             fields["host_report_drop"] = fields["hd"]
         if "raw_in" not in fields and "ri" in fields:
@@ -1263,22 +1264,27 @@ def _post_j6ready_j6raw_frames(text: str, frames: list[dict[str, Any]]) -> list[
 
 
 def _validate_j6raw_replay(
-    frames: list[dict[str, Any]],
-    *,
-    last_stat: dict[str, Any] | None,
-    replay_result: dict[str, Any] | None,
+    frames: list[dict[str, Any]],
+    *,
+    last_stat: dict[str, Any] | None,
+    replay_result: dict[str, Any] | None,
 ) -> tuple[dict[str, Any], list[str]]:
     failures: list[str] = []
     replay = bytearray()
-    first_seq = int(frames[0].get("seq") or 0) if frames else 0
-    first_off = int(frames[0].get("off") or 0) if frames else 0
-    expected_seq = first_seq
-    expected_off = first_off
-    if not frames:
-        failures.append("missing_j6raw_frames")
-    for frame in frames:
-        seq = int(frame.get("seq") or 0)
-        off = int(frame.get("off") or 0)
+    first_seq = int(frames[0].get("seq") or 0) if frames else 0
+    first_off = int(frames[0].get("off") or 0) if frames else 0
+    expected_seq = first_seq
+    expected_off = first_off
+    last_frame_end = first_off
+    last_stat_line_index = _safe_int((last_stat or {}).get("line_index"), default=None)
+    tail_bytes_after_last_stat = 0
+    tail_frames_after_last_stat = 0
+    replay_len_at_last_stat = first_off
+    if not frames:
+        failures.append("missing_j6raw_frames")
+    for frame in frames:
+        seq = int(frame.get("seq") or 0)
+        off = int(frame.get("off") or 0)
         length = int(frame.get("len") or 0)
         checksum = int(frame.get("sum") or 0)
         data_hex = str(frame.get("data_hex") or "")
@@ -1297,11 +1303,17 @@ def _validate_j6raw_replay(
                 failures.append(f"raw_frame_hex_malformed:{seq}")
         if len(data) != length:
             failures.append(f"raw_frame_data_len_mismatch:{seq}")
-        if (sum(data) & 0xFFFF) != checksum:
-            failures.append(f"raw_frame_checksum_mismatch:{seq}")
-        replay.extend(data)
-        expected_seq = seq + 1
-        expected_off = off + length
+        if (sum(data) & 0xFFFF) != checksum:
+            failures.append(f"raw_frame_checksum_mismatch:{seq}")
+        replay.extend(data)
+        last_frame_end = off + length
+        if last_stat_line_index is not None and _safe_int(frame.get("line_index"), default=-1) < last_stat_line_index:
+            replay_len_at_last_stat = last_frame_end
+        elif last_stat_line_index is not None and _safe_int(frame.get("line_index"), default=-1) > last_stat_line_index:
+            tail_bytes_after_last_stat += length
+            tail_frames_after_last_stat += 1
+        expected_seq = seq + 1
+        expected_off = off + length
 
     raw_in = _safe_int((last_stat or {}).get("raw_in"), default=None)
     raw_out = _safe_int((last_stat or {}).get("raw_out"), default=None)
@@ -1315,13 +1327,17 @@ def _validate_j6raw_replay(
             failures.append("raw_drop_nonzero")
         if bmc_berr:
             failures.append("bmc_uart_error_nonzero")
-        if host_err:
-            failures.append("host_uart_error_nonzero")
-        expected_replay_len = len(replay) + first_off
-        if raw_in is not None and raw_in != expected_replay_len:
-            failures.append("raw_in_replay_len_mismatch")
-        if raw_out is not None and raw_out != expected_replay_len:
-            failures.append("raw_out_replay_len_mismatch")
+        if host_err:
+            failures.append("host_uart_error_nonzero")
+        expected_replay_len = len(replay) + first_off
+        raw_in_covers_replay = raw_in is not None and raw_in == expected_replay_len
+        raw_out_covers_replay = raw_out is not None and raw_out == expected_replay_len
+        raw_in_covers_last_stat = raw_in is not None and raw_in == replay_len_at_last_stat and expected_replay_len >= raw_in
+        raw_out_covers_last_stat = raw_out is not None and raw_out == replay_len_at_last_stat and expected_replay_len >= raw_out
+        if raw_in is not None and not (raw_in_covers_replay or (tail_bytes_after_last_stat > 0 and raw_in_covers_last_stat)):
+            failures.append("raw_in_replay_len_mismatch")
+        if raw_out is not None and not (raw_out_covers_replay or (tail_bytes_after_last_stat > 0 and raw_out_covers_last_stat)):
+            failures.append("raw_out_replay_len_mismatch")
 
     replay_artifact_status = "not_provided"
     replay_artifact_sha256 = hashlib.sha256(bytes(replay)).hexdigest()
@@ -1350,12 +1366,22 @@ def _validate_j6raw_replay(
             "baseline_bytes": first_off,
             "sha256": replay_artifact_sha256,
             "artifact_status": replay_artifact_status,
-            "raw_in": raw_in,
-            "raw_out": raw_out,
-            "raw_drop": raw_drop,
-        },
-        failures,
-    )
+            "raw_in": raw_in,
+            "raw_out": raw_out,
+            "raw_drop": raw_drop,
+            "last_frame_end_offset": last_frame_end,
+            "last_j6stat_line_index": last_stat_line_index,
+            "replay_len_at_last_j6stat": replay_len_at_last_stat,
+            "post_j6stat_tail_bytes": tail_bytes_after_last_stat,
+            "post_j6stat_tail_frames": tail_frames_after_last_stat,
+            "last_j6stat_covers_replay": (
+                raw_in == len(replay) + first_off and raw_out == len(replay) + first_off
+                if raw_in is not None and raw_out is not None
+                else False
+            ),
+        },
+        failures,
+    )
 
 
 def _parse_j6raw_text(text: str) -> list[dict[str, object]]:
@@ -2845,10 +2871,11 @@ def validate_real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt(
             "production PTC/FAN qualification, or real PID closed-loop pass."
         ),
         allowed_top_statuses={"not_run", "blocked_waiting_for_real_fan_ptc_hardware"},
-        ignored_layer_status_failures={
-            "blocked_layer:real_fan_ptc_hardware_status",
-            "fail_layer:real_fan_ptc_hardware_status:not_run",
-        },
+        ignored_layer_status_failures={
+            "blocked_layer:real_fan_ptc_hardware_status",
+            "blocked_layer:artifact_hashes",
+            "fail_layer:real_fan_ptc_hardware_status:not_run",
+        },
         host_sensor_report_schemas={
             "j6-host-sensor-real-fan-ptc-host-sensor-report-v1",
         },