Browse Source

Merge final cleanup/integration work.

- Remove retired RTL and orphan tests, activate POR regression.
- Add zipfile fallback to package_for_agent_analysis.py.
- Rebuild firmware packager with TD root binding, source-closure comparison, provenance, manifest v2.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Codex Resource Selftest 4 months ago
parent
commit
2e299534c8

+ 2 - 1
config/prod2u_p4_verification_targets_v1.json

@@ -37,7 +37,8 @@
       "host_watchdog_tb",
       "shared_500us_tick_tb",
       "startup_close_seek_tb",
-      "startup_motor_stop_tb"
+      "startup_motor_stop_tb",
+      "prod2u_por_tb"
     ],
     "verilator": ["prod2u_door_temp_top_lint"],
     "cocotb": ["prod2u_door_temp_uart_e2e"],

+ 166 - 59
package_for_agent_analysis.py

@@ -1017,6 +1017,109 @@ def _inspect_and_extract_unsupported_archive(
     return expanded_items, rebased_excluded, contains_sensitive
 
 
+def _inspect_and_extract_zip_archive(
+    item: PackageItem,
+    *,
+    temp_root: Path,
+    extra_exclusions: tuple[dict[str, str], ...],
+) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
+    archive_label = item.candidate.relative
+    try:
+        with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
+            file_members: list[zipfile.ZipInfo] = []
+            expected_bytes = 0
+            for info in archive.infolist():
+                normalized = info.filename.replace("\\", "/")
+                if (
+                    not normalized
+                    or normalized.startswith("/")
+                    or re.match(r"^[A-Za-z]:", normalized)
+                ):
+                    raise PackagingError(
+                        f"unsafe archive member path in {archive_label}"
+                    )
+                handoff.normalize_relative(normalized.split("/"))
+                if info.flag_bits & 0x1:
+                    raise PackagingError(
+                        f"encrypted archive member is unsupported in {archive_label}"
+                    )
+                member_mode = (info.external_attr >> 16) & 0xFFFF
+                member_type = stat.S_IFMT(member_mode)
+                if info.is_dir():
+                    if (
+                        info.file_size != 0
+                        or info.compress_size != 0
+                        or member_type not in {0, stat.S_IFDIR}
+                    ):
+                        raise PackagingError(
+                            f"unsafe archive member type in {archive_label}"
+                        )
+                    continue
+                if member_type not in {0, stat.S_IFREG}:
+                    raise PackagingError(
+                        f"unsafe archive member type in {archive_label}"
+                    )
+                file_members.append(info)
+                expected_bytes += info.file_size
+    except (OSError, zipfile.BadZipFile) as exc:
+        raise PackagingError(
+            f"unable to inspect source archive: {archive_label}"
+        ) from exc
+
+    token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
+    extract_root = temp_root / "expanded-archives" / token
+    extract_root.mkdir(parents=True, exist_ok=False)
+    actual_files: list[Path] = []
+    actual_bytes = 0
+    try:
+        with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
+            for info in file_members:
+                parts = info.filename.replace("\\", "/").split("/")
+                target_path = extract_root / Path(*parts)
+                target_path.parent.mkdir(parents=True, exist_ok=True)
+                with archive.open(info, "r") as source, target_path.open("wb") as destination:
+                    shutil.copyfileobj(source, destination, length=1024 * 1024)
+                actual_files.append(target_path)
+                actual_bytes += target_path.stat().st_size
+    except (OSError, zipfile.BadZipFile) as exc:
+        raise PackagingError(
+            f"unable to extract source archive: {archive_label}"
+        ) from exc
+
+    if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
+        raise PackagingError(
+            f"archive extraction inventory mismatch: {archive_label} "
+            f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
+        )
+    expanded_candidates, expanded_excluded, _ = scan_analysis_root(
+        extract_root,
+        extra_exclusions=extra_exclusions,
+    )
+    handoff.audit_candidates(expanded_candidates)
+    expanded_prefix = f"{archive_label}.expanded"
+    expanded_items = [
+        PackageItem(
+            candidate=_rebase_candidate(candidate, expanded_prefix),
+            category=item.category,
+            source_id=item.source_id,
+            original_path=f"{item.original_path}!/{candidate.relative}",
+            scan_archive=True,
+        )
+        for candidate in expanded_candidates
+    ]
+    rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
+    sensitive_rules = {
+        "credential_or_license_file",
+        "credential_configuration_file",
+        "private_key_file",
+        "secret_environment_file",
+        "cloud_credential_file",
+        "container_registry_credential_file",
+    }
+    contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
+    return expanded_items, rebased_excluded, contains_sensitive
+
+
 def prepare_unsupported_archives(
     items: tuple[PackageItem, ...],
     *,
@@ -1033,14 +1136,37 @@ def prepare_unsupported_archives(
         if archive_kind is None:
             prepared.append(item)
             continue
-        if seven_zip is None:
-            raise PackagingError("7-Zip is required to inspect source archives")
-        expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
-            item,
-            temp_root=temp_root,
-            seven_zip=seven_zip,
-            extra_exclusions=extra_exclusions,
-        )
+        if archive_kind == "zip":
+            expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
+                item,
+                temp_root=temp_root,
+                extra_exclusions=extra_exclusions,
+            )
+        elif seven_zip is None:
+            if _is_reference_item(item):
+                warnings.append(
+                    {
+                        "code": "unsupported_archive_without_7zip",
+                        "source_id": item.source_id,
+                        "path": item.candidate.relative,
+                        "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
+                    }
+                )
+                prepared.append(item._replace(scan_archive=False))
+                continue
+            if item.candidate.absolute.is_file():
+                raise PackagingError(
+                    "7-Zip is required to inspect unsupported source archives"
+                )
+            prepared.append(item._replace(scan_archive=False))
+            continue
+        else:
+            expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
+                item,
+                temp_root=temp_root,
+                seven_zip=seven_zip,
+                extra_exclusions=extra_exclusions,
+            )
         has_filtered_members = bool(expanded_excluded)
         if has_filtered_members:
             prepared.extend(expanded_items)
@@ -1241,57 +1367,40 @@ def _write_volume(
     )
     manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
     manifest_payload = handoff.json_bytes(manifest)
-    seven_zip = find_7z()
-    if seven_zip is None:
-        raise PackagingError("7-Zip is required to create the analysis ZIP")
-    stage_path = Path(tempfile.mkdtemp(prefix=f".{path.stem}.", dir=path.parent))
     written_inventory: list[dict[str, object]] = []
-    archive_renames: list[tuple[str, str]] = []
     try:
-        staging_args = [(item_number, item) for item_number, item in enumerate(items)]
-
-        def _stage_one(args: tuple[int, PackageItem]) -> tuple[int, dict[str, object]]:
-            item_number, item = args
-            staging_name = f"candidate-{item_number:08d}"
-            return item_number, _stage_package_item(stage_path, item, staging_name)
-
-        max_workers = os.cpu_count() or 1
-        with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
-            staged = list(executor.map(_stage_one, staging_args))
-
-        for item_number, actual in staged:
-            item = items[item_number]
-            expected = inventory_by_path[item.candidate.relative]
-            if actual["size"] != expected["size"] or actual["sha256"] != expected["sha256"]:
-                raise PackagingError(f"source changed while writing ZIP: {item.candidate.relative}")
-            written_inventory.append(actual)
-            archive_renames.append(
-                (
-                    f"CPLD/candidate-{item_number:08d}",
-                    f"CPLD/{item.candidate.relative}",
-                )
-            )
-        manifest_staging_path = stage_path / "CPLD" / "metadata-manifest"
-        manifest_staging_path.parent.mkdir(parents=True, exist_ok=True)
-        manifest_staging_path.write_bytes(manifest_payload)
-        archive_renames.append(("CPLD/metadata-manifest", manifest_name))
-        _run_7z(
-            seven_zip,
-            build_7zip_create_command(path, stage_path),
-            cwd=stage_path,
-        )
-        _rename_archive_entries(seven_zip, path, archive_renames)
-
-        expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
-        expected_names.add(manifest_name)
-        handoff.verify_archive(
-            path,
-            expected_names=expected_names,
-            inventory=written_inventory,
-            expected_payloads={manifest_name: manifest_payload},
-        )
-    finally:
-        shutil.rmtree(stage_path, ignore_errors=True)
+        with zipfile.ZipFile(
+            path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True
+        ) as archive:
+            for item in sorted(items, key=_item_sort_key):
+                expected = inventory_by_path[item.candidate.relative]
+                if item.scan_archive:
+                    actual = handoff.write_candidate(archive, item.candidate)
+                else:
+                    actual = _write_unscanned_candidate(archive, item)
+                if (
+                    actual["size"] != expected["size"]
+                    or actual["sha256"] != expected["sha256"]
+                ):
+                    raise PackagingError(
+                        f"source changed while writing ZIP: {item.candidate.relative}"
+                    )
+                written_inventory.append(actual)
+            with archive.open(
+                handoff.zip_info(manifest_name), "w", force_zip64=True
+            ) as target:
+                target.write(manifest_payload)
+    except (OSError, zipfile.BadZipFile) as exc:
+        raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
+
+    expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
+    expected_names.add(manifest_name)
+    handoff.verify_archive(
+        path,
+        expected_names=expected_names,
+        inventory=written_inventory,
+        expected_payloads={manifest_name: manifest_payload},
+    )
     return {
         "file": path.name,
         "volume_number": number,
@@ -1924,8 +2033,6 @@ def main(argv: list[str] | None = None) -> int:
             payload = explain_analysis_path(args.explain, repo_root=source_root, config=config)
         else:
             seven_zip = find_7z()
-            if seven_zip is None:
-                raise PackagingError("7-Zip is required for analysis packaging and archive inspection")
             _validate_package_name(package_name)
             output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
             with tempfile.TemporaryDirectory(prefix="ca-") as temporary:

+ 0 - 127
src/rtl/prod2u_p4_temperature_read.v

@@ -1,127 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_read (
-    input  wire        clk,
-    input  wire        rst_n,
-    input  wire        start,
-    output reg         busy,
-    output reg         done,
-    output reg         bus_error,
-    output wire        request_valid,
-    input  wire        request_ready,
-    output reg  [6:0]  device_addr,
-    output wire [7:0]  register,
-    input  wire        response_valid,
-    output wire        response_ready,
-    /* verilator lint_off UNUSEDSIGNAL */
-    input  wire [15:0] data,
-    /* verilator lint_on UNUSEDSIGNAL */
-    input  wire [3:0]  error,
-    output reg         wr_en,
-    output reg  [4:0]  wr_addr,
-    output reg  [7:0]  wr_data
-);
-    localparam [1:0] ST_IDLE = 2'd0;
-    localparam [1:0] ST_REQUEST = 2'd1;
-    localparam [1:0] ST_RESPONSE = 2'd2;
-    localparam [1:0] ST_COMPLETE = 2'd3;
-
-    (* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)
-    reg [1:0] state;
-    reg [1:0] sensor_index;
-    reg [3:0] register_index;
-    reg [4:0] slot_index;
-
-    wire fatal_error = (error >= 4'd4);
-    wire [8:0] integer_temperature = data[15:7];
-    wire [7:0] converted_temperature =
-        ((error != 4'd0) || data[15] || (integer_temperature > 9'd150)) ?
-        8'hff : integer_temperature[7:0];
-
-    assign request_valid = (state == ST_REQUEST);
-    assign response_ready = (state == ST_RESPONSE);
-    assign register = {4'd0, register_index};
-
-    always @* begin
-        case (sensor_index)
-            2'd0: device_addr = 7'h49;
-            2'd1: device_addr = 7'h48;
-            default: device_addr = 7'h4b;
-        endcase
-    end
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            state <= ST_IDLE;
-            sensor_index <= 2'd0;
-            register_index <= 4'd0;
-            slot_index <= 5'd0;
-            busy <= 1'b0;
-            done <= 1'b0;
-            bus_error <= 1'b0;
-            wr_en <= 1'b0;
-            wr_addr <= 5'd0;
-            wr_data <= 8'd0;
-        end else begin
-            done <= 1'b0;
-            bus_error <= 1'b0;
-            wr_en <= 1'b0;
-
-            case (state)
-                ST_IDLE: begin
-                    if (start) begin
-                        sensor_index <= 2'd0;
-                        register_index <= 4'd0;
-                        slot_index <= 5'd0;
-                        busy <= 1'b1;
-                        state <= ST_REQUEST;
-                    end
-                end
-
-                ST_REQUEST: begin
-                    if (request_ready) begin
-                        state <= ST_RESPONSE;
-                    end
-                end
-
-                ST_RESPONSE: begin
-                    if (response_valid) begin
-                        if (fatal_error) begin
-                            busy <= 1'b0;
-                            done <= 1'b1;
-                            bus_error <= 1'b1;
-                            state <= ST_IDLE;
-                        end else begin
-                            wr_en <= 1'b1;
-                            wr_addr <= slot_index;
-                            wr_data <= converted_temperature;
-                            if (slot_index == 5'd26) begin
-                                state <= ST_COMPLETE;
-                            end else begin
-                                slot_index <= slot_index + 5'd1;
-                                if (register_index == 4'd8) begin
-                                    register_index <= 4'd0;
-                                    sensor_index <= sensor_index + 2'd1;
-                                end else begin
-                                    register_index <= register_index + 4'd1;
-                                end
-                                state <= ST_REQUEST;
-                            end
-                        end
-                    end
-                end
-
-                ST_COMPLETE: begin
-                    busy <= 1'b0;
-                    done <= 1'b1;
-                    state <= ST_IDLE;
-                end
-
-                default: begin
-                    busy <= 1'b0;
-                    state <= ST_IDLE;
-                end
-            endcase
-        end
-    end
-endmodule

+ 0 - 36
src/rtl/prod2u_p4_us_tick.v

@@ -1,36 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_us_tick #(
-    parameter integer CLK_HZ = 25000000
-) (
-    input  wire clk,
-    input  wire rst_n,
-    output reg  tick_1us
-);
-    localparam integer CLKS_PER_US = CLK_HZ / 1000000;
-    localparam integer COUNTER_BITS = (CLKS_PER_US <= 1) ? 1 : $clog2(CLKS_PER_US);
-    localparam [31:0] LAST_COUNT_32 = CLKS_PER_US - 1;
-    localparam [COUNTER_BITS-1:0] LAST_COUNT = LAST_COUNT_32[COUNTER_BITS-1:0];
-    reg [COUNTER_BITS-1:0] counter;
-
-    generate
-        if ((CLK_HZ < 1000000) || ((CLK_HZ % 1000000) != 0) || (CLKS_PER_US > 65535)) begin : g_clock_must_divide_to_one_microsecond
-            prod2u_p4_clock_must_divide_to_one_microsecond u_clock_error();
-        end
-    endgenerate
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            counter <= {COUNTER_BITS{1'b0}};
-            tick_1us <= 1'b0;
-        end else begin
-            tick_1us <= 1'b0;
-            if (counter == LAST_COUNT) begin
-                counter <= {COUNTER_BITS{1'b0}};
-                tick_1us <= 1'b1;
-            end else begin
-                counter <= counter + 1'b1;
-            end
-        end
-    end
-endmodule

+ 0 - 150
src/rtl/uart_rx_8n1.v

@@ -1,150 +0,0 @@
-`timescale 1ns/1ps
-
-module uart_rx_8n1 #(
-    parameter integer CLKS_PER_BIT = 217,
-    parameter integer BREAK_BITS = 11
-) (
-    input  wire       clk,
-    input  wire       rst_n,
-    input  wire       rx_i,
-    output reg        rx_valid,
-    output reg [7:0]  rx_data,
-    input  wire       rx_ready,
-    output reg        framing_error,
-    output reg        break_detected,
-    output reg        overflow
-);
-
-    localparam [1:0] S_IDLE = 2'd0;
-    localparam [1:0] S_START = 2'd1;
-    localparam [1:0] S_DATA = 2'd2;
-    localparam [1:0] S_STOP = 2'd3;
-    localparam integer CLK_COUNT_BITS =
-        (CLKS_PER_BIT > 1) ? $clog2(CLKS_PER_BIT) : 1;
-    localparam [CLK_COUNT_BITS-1:0] CLK_COUNT_ZERO =
-        {CLK_COUNT_BITS{1'b0}};
-    localparam [CLK_COUNT_BITS-1:0] CLK_COUNT_ONE =
-        {{(CLK_COUNT_BITS-1){1'b0}}, 1'b1};
-    localparam [CLK_COUNT_BITS-1:0] CLKS_PER_BIT_COUNT =
-        CLKS_PER_BIT[CLK_COUNT_BITS-1:0];
-    localparam [CLK_COUNT_BITS-1:0] CLK_COUNT_LIMIT =
-        CLKS_PER_BIT_COUNT - CLK_COUNT_ONE;
-    localparam [CLK_COUNT_BITS-1:0] CLK_SAMPLE_POINT =
-        CLKS_PER_BIT[CLK_COUNT_BITS:1];
-    localparam integer BREAK_THRESHOLD = CLKS_PER_BIT * BREAK_BITS;
-    localparam integer LOW_COUNT_BITS =
-        (BREAK_THRESHOLD > 0) ? $clog2(BREAK_THRESHOLD + 1) : 1;
-    localparam [LOW_COUNT_BITS-1:0] LOW_COUNT_ZERO =
-        {LOW_COUNT_BITS{1'b0}};
-    localparam [LOW_COUNT_BITS-1:0] LOW_COUNT_ONE =
-        {{(LOW_COUNT_BITS-1){1'b0}}, 1'b1};
-    localparam [LOW_COUNT_BITS-1:0] BREAK_COUNT_LIMIT =
-        BREAK_THRESHOLD[LOW_COUNT_BITS-1:0];
-
-    reg [1:0] state;
-    reg [CLK_COUNT_BITS-1:0] clk_count;
-    reg [2:0] bit_index;
-    reg [7:0] shift_reg;
-    reg [LOW_COUNT_BITS-1:0] low_count;
-    reg stop_bit_ok;
-    (* async_reg = "true" *) reg [1:0] rx_sync_pipe;
-    wire rx_sync = rx_sync_pipe[1];
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            rx_sync_pipe <= 2'b11;
-        end else begin
-            rx_sync_pipe <= {rx_sync_pipe[0], rx_i};
-        end
-    end
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            rx_valid <= 1'b0;
-            rx_data <= 8'd0;
-            framing_error <= 1'b0;
-            break_detected <= 1'b0;
-            overflow <= 1'b0;
-            state <= S_IDLE;
-            clk_count <= CLK_COUNT_ZERO;
-            bit_index <= 3'd0;
-            shift_reg <= 8'd0;
-            low_count <= LOW_COUNT_ZERO;
-            stop_bit_ok <= 1'b0;
-        end else begin
-            if (rx_ready) begin
-                rx_valid <= 1'b0;
-            end
-
-            if (!rx_sync) begin
-                if (low_count < BREAK_COUNT_LIMIT) begin
-                    low_count <= low_count + LOW_COUNT_ONE;
-                end else begin
-                    break_detected <= 1'b1;
-                end
-            end else begin
-                low_count <= LOW_COUNT_ZERO;
-            end
-
-            if (state == S_IDLE) begin
-                clk_count <= CLK_COUNT_ZERO;
-                bit_index <= 3'd0;
-                stop_bit_ok <= 1'b0;
-                if (!rx_sync) begin
-                    state <= S_START;
-                    clk_count <= CLK_COUNT_ZERO;
-                end
-            end else if (state == S_START) begin
-                if (clk_count == CLK_SAMPLE_POINT) begin
-                    if (rx_sync) begin
-                        state <= S_IDLE;
-                    end
-                end
-                if (clk_count == CLK_COUNT_LIMIT) begin
-                    clk_count <= CLK_COUNT_ZERO;
-                    state <= S_DATA;
-                    bit_index <= 3'd0;
-                end else begin
-                    clk_count <= clk_count + CLK_COUNT_ONE;
-                end
-            end else if (state == S_DATA) begin
-                if (clk_count == CLK_SAMPLE_POINT) begin
-                    shift_reg[bit_index] <= rx_sync;
-                end
-                if (clk_count == CLK_COUNT_LIMIT) begin
-                    clk_count <= CLK_COUNT_ZERO;
-                    if (bit_index == 3'd7) begin
-                        state <= S_STOP;
-                        stop_bit_ok <= 1'b0;
-                    end else begin
-                        bit_index <= bit_index + 3'd1;
-                    end
-                end else begin
-                    clk_count <= clk_count + CLK_COUNT_ONE;
-                end
-            end else begin
-                if (clk_count == CLK_SAMPLE_POINT) begin
-                    stop_bit_ok <= rx_sync;
-                    if (!rx_sync) begin
-                        framing_error <= 1'b1;
-                    end
-                end
-                if (clk_count == CLK_COUNT_LIMIT) begin
-                    clk_count <= CLK_COUNT_ZERO;
-                    state <= rx_sync ? S_IDLE : S_START;
-                    if (stop_bit_ok) begin
-                        if (rx_valid && !rx_ready) begin
-                            overflow <= 1'b1;
-                        end
-                        rx_data <= shift_reg;
-                        rx_valid <= 1'b1;
-                    end
-                    stop_bit_ok <= 1'b0;
-                end else begin
-                    clk_count <= clk_count + CLK_COUNT_ONE;
-                end
-            end
-        end
-    end
-
-endmodule

+ 0 - 82
src/rtl/uart_tx_8n1.v

@@ -1,82 +0,0 @@
-`timescale 1ns/1ps
-
-module uart_tx_8n1 #(
-    parameter integer CLKS_PER_BIT = 217
-) (
-    input  wire       clk,
-    input  wire       rst_n,
-    input  wire       tx_valid,
-    input  wire [7:0] tx_data,
-    output wire       tx_ready,
-    output reg        tx_o,
-    output reg        busy
-);
-
-    localparam [1:0] S_IDLE = 2'd0;
-    localparam [1:0] S_START = 2'd1;
-    localparam [1:0] S_DATA = 2'd2;
-    localparam [1:0] S_STOP = 2'd3;
-    localparam integer CLK_COUNT_BITS =
-        (CLKS_PER_BIT > 1) ? $clog2(CLKS_PER_BIT) : 1;
-    localparam [CLK_COUNT_BITS-1:0] CLK_COUNT_ZERO =
-        {CLK_COUNT_BITS{1'b0}};
-    localparam [CLK_COUNT_BITS-1:0] CLK_COUNT_ONE =
-        {{(CLK_COUNT_BITS-1){1'b0}}, 1'b1};
-    localparam [CLK_COUNT_BITS-1:0] CLKS_PER_BIT_COUNT =
-        CLKS_PER_BIT[CLK_COUNT_BITS-1:0];
-    localparam [CLK_COUNT_BITS-1:0] CLK_COUNT_LIMIT =
-        CLKS_PER_BIT_COUNT - CLK_COUNT_ONE;
-
-    reg [1:0] state;
-    reg [CLK_COUNT_BITS-1:0] clk_count;
-    reg [2:0] bit_index;
-    reg [7:0] shift_reg;
-
-    assign tx_ready = !busy;
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            tx_o <= 1'b1;
-            busy <= 1'b0;
-            state <= S_IDLE;
-            clk_count <= CLK_COUNT_ZERO;
-            bit_index <= 3'd0;
-            shift_reg <= 8'd0;
-        end else begin
-            if (state == S_IDLE) begin
-                tx_o <= 1'b1;
-                busy <= 1'b0;
-                clk_count <= CLK_COUNT_ZERO;
-                bit_index <= 3'd0;
-                if (tx_valid) begin
-                    busy <= 1'b1;
-                    shift_reg <= tx_data;
-                    tx_o <= 1'b0;
-                    state <= S_START;
-                end
-            end else if (clk_count == CLK_COUNT_LIMIT) begin
-                clk_count <= CLK_COUNT_ZERO;
-                if (state == S_START) begin
-                    state <= S_DATA;
-                    bit_index <= 3'd0;
-                    tx_o <= shift_reg[0];
-                end else if (state == S_DATA) begin
-                    if (bit_index == 3'd7) begin
-                        state <= S_STOP;
-                        tx_o <= 1'b1;
-                    end else begin
-                        bit_index <= bit_index + 3'd1;
-                        tx_o <= shift_reg[bit_index + 3'd1];
-                    end
-                end else begin
-                    state <= S_IDLE;
-                    tx_o <= 1'b1;
-                    busy <= 1'b0;
-                end
-            end else begin
-                clk_count <= clk_count + CLK_COUNT_ONE;
-            end
-        end
-    end
-
-endmodule

+ 0 - 279
tests/sim/prod2u_p4_temperature_read_tb.v

@@ -1,279 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_read_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg start = 1'b0;
-    wire busy;
-    wire done;
-    wire bus_error;
-    wire request_valid;
-    reg request_ready = 1'b0;
-    wire [6:0] device_addr;
-    wire [7:0] register;
-    reg response_valid = 1'b0;
-    wire response_ready;
-    reg [15:0] data = 16'd0;
-    reg [3:0] error = 4'd0;
-    wire wr_en;
-    wire [4:0] wr_addr;
-    wire [7:0] wr_data;
-
-    reg [7:0] stored [0:26];
-    reg [26:0] wrote_mask;
-    integer write_count;
-    integer slot;
-    integer wait_cycles;
-    reg [15:0] raw_value;
-    reg [3:0] response_error_value;
-    reg [7:0] expected_value;
-
-    prod2u_p4_temperature_read dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .start(start),
-        .busy(busy),
-        .done(done),
-        .bus_error(bus_error),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .device_addr(device_addr),
-        .register(register),
-        .response_valid(response_valid),
-        .response_ready(response_ready),
-        .data(data),
-        .error(error),
-        .wr_en(wr_en),
-        .wr_addr(wr_addr),
-        .wr_data(wr_data)
-    );
-
-    always #5 clk = ~clk;
-
-    always @(posedge clk) begin
-        if (!rst_n) begin
-            wrote_mask <= 27'd0;
-            write_count <= 0;
-        end else if (wr_en) begin
-            if (wr_addr > 5'd26) begin
-                $display("WRITE_ADDRESS_OUT_OF_RANGE addr=%0d", wr_addr);
-                $fatal;
-            end
-            if (wrote_mask[wr_addr]) begin
-                $display("DUPLICATE_WRITE addr=%0d", wr_addr);
-                $fatal;
-            end
-            stored[wr_addr] <= wr_data;
-            wrote_mask[wr_addr] <= 1'b1;
-            write_count <= write_count + 1;
-        end
-    end
-
-    function [6:0] expected_device;
-        input integer index;
-        begin
-            if (index < 9) expected_device = 7'h49;
-            else if (index < 18) expected_device = 7'h48;
-            else expected_device = 7'h4b;
-        end
-    endfunction
-
-    function [7:0] expected_register;
-        input integer index;
-        begin
-            expected_register = index % 9;
-        end
-    endfunction
-
-    task pulse_start;
-        begin
-            @(negedge clk);
-            start = 1'b1;
-            @(posedge clk);
-            #1;
-            start = 1'b0;
-        end
-    endtask
-
-    task accept_request;
-        input integer index;
-        begin
-            wait_cycles = 0;
-            while (request_valid !== 1'b1 && wait_cycles < 20) begin
-                @(posedge clk);
-                #1;
-                wait_cycles = wait_cycles + 1;
-            end
-            if (!request_valid) begin
-                $display("REQUEST_TIMEOUT slot=%0d", index);
-                $fatal;
-            end
-            if (device_addr !== expected_device(index) ||
-                register !== expected_register(index)) begin
-                $display(
-                    "REQUEST_ORDER_MISMATCH slot=%0d addr=%02x/%02x reg=%02x/%02x",
-                    index,
-                    device_addr,
-                    expected_device(index),
-                    register,
-                    expected_register(index)
-                );
-                $fatal;
-            end
-
-            if (index == 0) begin
-                repeat (3) begin
-                    @(posedge clk);
-                    #1;
-                    if (!request_valid || device_addr !== 7'h49 || register !== 8'h00) begin
-                        $display("REQUEST_CHANGED_BEFORE_READY");
-                        $fatal;
-                    end
-                end
-            end
-
-            @(negedge clk);
-            request_ready = 1'b1;
-            @(posedge clk);
-            #1;
-            request_ready = 1'b0;
-        end
-    endtask
-
-    task return_response;
-        input [15:0] response_data_value;
-        input [3:0] response_error_code;
-        begin
-            wait_cycles = 0;
-            while (response_ready !== 1'b1 && wait_cycles < 20) begin
-                @(posedge clk);
-                #1;
-                wait_cycles = wait_cycles + 1;
-            end
-            if (!response_ready) begin
-                $display("RESPONSE_READY_TIMEOUT");
-                $fatal;
-            end
-            @(negedge clk);
-            data = response_data_value;
-            error = response_error_code;
-            response_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            response_valid = 1'b0;
-            error = 4'd0;
-        end
-    endtask
-
-    task wait_for_done;
-        input expected_bus_error;
-        begin
-            wait_cycles = 0;
-            while (done !== 1'b1 && wait_cycles < 30) begin
-                @(posedge clk);
-                #1;
-                wait_cycles = wait_cycles + 1;
-            end
-            if (!done || bus_error !== expected_bus_error) begin
-                $display(
-                    "DONE_MISMATCH done=%0d bus_error=%0d expected=%0d",
-                    done,
-                    bus_error,
-                    expected_bus_error
-                );
-                $fatal;
-            end
-            if (busy) begin
-                $display("BUSY_STILL_HIGH_AT_DONE");
-                $fatal;
-            end
-        end
-    endtask
-
-    initial begin
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-        pulse_start();
-        if (!busy) begin
-            $display("BUSY_NOT_ASSERTED_AFTER_START");
-            $fatal;
-        end
-
-        for (slot = 0; slot < 27; slot = slot + 1) begin
-            accept_request(slot);
-            response_error_value = 4'd0;
-            if (slot == 0) begin
-                raw_value = 16'h0000;
-                expected_value = 8'd0;
-            end else if (slot == 1) begin
-                raw_value = 16'd150 << 7;
-                expected_value = 8'd150;
-            end else if (slot == 2) begin
-                raw_value = 16'd151 << 7;
-                expected_value = 8'hff;
-            end else if (slot == 3) begin
-                raw_value = 16'hff80;
-                expected_value = 8'hff;
-            end else if (slot == 4) begin
-                raw_value = 16'h0000;
-                response_error_value = 4'd1;
-                expected_value = 8'hff;
-            end else if (slot == 5) begin
-                raw_value = 16'h0000;
-                response_error_value = 4'd2;
-                expected_value = 8'hff;
-            end else if (slot == 6) begin
-                raw_value = 16'h0000;
-                response_error_value = 4'd3;
-                expected_value = 8'hff;
-            end else begin
-                raw_value = slot[15:0] << 7;
-                expected_value = slot[7:0];
-            end
-            return_response(raw_value, response_error_value);
-
-            wait_cycles = 0;
-            while (!wrote_mask[slot] && wait_cycles < 5) begin
-                @(posedge clk);
-                #1;
-                wait_cycles = wait_cycles + 1;
-            end
-            if (!wrote_mask[slot] || stored[slot] !== expected_value) begin
-                $display(
-                    "STORE_VALUE_MISMATCH slot=%0d wrote=%0d data=%02x expected=%02x",
-                    slot,
-                    wrote_mask[slot],
-                    stored[slot],
-                    expected_value
-                );
-                $fatal;
-            end
-        end
-        wait_for_done(1'b0);
-        if (write_count !== 27 || wrote_mask !== {27{1'b1}}) begin
-            $display("WRITE_COUNT_MISMATCH count=%0d mask=%07x", write_count, wrote_mask);
-            $fatal;
-        end
-
-        @(negedge clk);
-        rst_n = 1'b0;
-        repeat (2) @(negedge clk);
-        rst_n = 1'b1;
-        pulse_start();
-        accept_request(0);
-        return_response(16'h1900, 4'd4);
-        wait_for_done(1'b1);
-        if (write_count !== 0 || request_valid || response_ready) begin
-            $display(
-                "FATAL_ERROR_DID_NOT_STOP count=%0d req=%0d response_ready=%0d",
-                write_count,
-                request_valid,
-                response_ready
-            );
-            $fatal;
-        end
-
-        $display("PASS: prod2u_p4_temperature_read_tb");
-        $finish;
-    end
-endmodule

+ 0 - 86
tests/sim/prod2u_p4_temperature_store_tb.v

@@ -1,86 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_store_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg wr_en = 1'b0;
-    reg [4:0] wr_addr = 5'd0;
-    reg [7:0] wr_data = 8'd0;
-    reg rd_req = 1'b0;
-    reg [4:0] rd_addr = 5'd0;
-    wire rd_valid;
-    wire [7:0] rd_data;
-    integer index;
-
-    prod2u_p4_temperature_store dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .wr_en(wr_en),
-        .wr_addr(wr_addr),
-        .wr_data(wr_data),
-        .rd_req(rd_req),
-        .rd_addr(rd_addr),
-        .rd_valid(rd_valid),
-        .rd_data(rd_data)
-    );
-
-    always #5 clk = ~clk;
-
-    task write_byte;
-        input [4:0] address;
-        input [7:0] value;
-        begin
-            @(negedge clk);
-            wr_addr = address;
-            wr_data = value;
-            wr_en = 1'b1;
-            @(posedge clk);
-            #1;
-            wr_en = 1'b0;
-        end
-    endtask
-
-    task read_and_check;
-        input [4:0] address;
-        input [7:0] expected;
-        begin
-            @(negedge clk);
-            rd_addr = address;
-            rd_req = 1'b1;
-            @(posedge clk);
-            #1;
-            rd_req = 1'b0;
-            if (!rd_valid || rd_data !== expected) begin
-                $display(
-                    "STORE_READ_MISMATCH addr=%0d valid=%0d data=%02x expected=%02x",
-                    address,
-                    rd_valid,
-                    rd_data,
-                    expected
-                );
-                $fatal;
-            end
-            @(posedge clk);
-            #1;
-            if (rd_valid) begin
-                $display("STORE_RD_VALID_NOT_ONE_CYCLE addr=%0d", address);
-                $fatal;
-            end
-        end
-    endtask
-
-    initial begin
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-
-        for (index = 0; index < 27; index = index + 1) begin
-            write_byte(index[4:0], 8'h80 + index[7:0]);
-        end
-        for (index = 0; index < 27; index = index + 1) begin
-            read_and_check(index[4:0], 8'h80 + index[7:0]);
-        end
-
-        $display("PASS: prod2u_p4_temperature_store_tb");
-        $finish;
-    end
-endmodule

+ 0 - 46
tests/sim/prod2u_p4_us_tick_tb.v

@@ -1,46 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_us_tick_tb;
-    reg clk;
-    reg rst_n;
-    wire tick_1us;
-    integer cycle;
-    integer pulse_count;
-
-    prod2u_p4_us_tick #(
-        .CLK_HZ(4000000)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(tick_1us)
-    );
-
-    initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
-
-    initial begin
-        rst_n = 1'b0;
-        pulse_count = 0;
-        repeat (3) @(negedge clk);
-        rst_n = 1'b1;
-        for (cycle = 1; cycle <= 20; cycle = cycle + 1) begin
-            @(posedge clk);
-            #1;
-            if (tick_1us) begin
-                pulse_count = pulse_count + 1;
-                if ((cycle % 4) != 0) begin
-                    $display("1 us tick arrived on wrong divide cycle=%0d", cycle);
-                    $fatal;
-                end
-            end
-        end
-        if (pulse_count !== 5) begin
-            $display("1 us tick count mismatch count=%0d", pulse_count);
-            $fatal;
-        end
-        $display("PASS: prod2u_p4_us_tick_tb");
-        $finish;
-    end
-endmodule

+ 0 - 195
tests/sim/uart_rx_error_tb.v

@@ -1,195 +0,0 @@
-`timescale 1ns/1ps
-
-module uart_rx_error_tb;
-    reg clk;
-    reg rst_n;
-    reg rx_i;
-    reg rx_ready;
-    wire rx_valid;
-    wire [7:0] rx_data;
-    wire framing_error;
-    wire break_detected;
-    wire overflow;
-    reg break_probe_i;
-    wire break0_detected;
-    wire break1_detected;
-    wire break15_detected;
-
-    uart_rx_8n1 #(
-        .CLKS_PER_BIT(4),
-        .BREAK_BITS(11)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_i(rx_i),
-        .rx_valid(rx_valid),
-        .rx_data(rx_data),
-        .rx_ready(rx_ready),
-        .framing_error(framing_error),
-        .break_detected(break_detected),
-        .overflow(overflow)
-    );
-
-    uart_rx_8n1 #(
-        .CLKS_PER_BIT(1),
-        .BREAK_BITS(0)
-    ) dut_break0 (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_i(break_probe_i),
-        .rx_valid(),
-        .rx_data(),
-        .rx_ready(1'b1),
-        .framing_error(),
-        .break_detected(break0_detected),
-        .overflow()
-    );
-
-    uart_rx_8n1 #(
-        .CLKS_PER_BIT(1),
-        .BREAK_BITS(1)
-    ) dut_break1 (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_i(break_probe_i),
-        .rx_valid(),
-        .rx_data(),
-        .rx_ready(1'b1),
-        .framing_error(),
-        .break_detected(break1_detected),
-        .overflow()
-    );
-
-    uart_rx_8n1 #(
-        .CLKS_PER_BIT(3),
-        .BREAK_BITS(5)
-    ) dut_break15 (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_i(break_probe_i),
-        .rx_valid(),
-        .rx_data(),
-        .rx_ready(1'b1),
-        .framing_error(),
-        .break_detected(break15_detected),
-        .overflow()
-    );
-
-    initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
-
-    task drive_bit;
-        input value;
-        integer i;
-        begin
-            rx_i = value;
-            for (i = 0; i < 4; i = i + 1) @(negedge clk);
-        end
-    endtask
-
-    task drive_bad_stop_frame;
-        integer bit_index;
-        begin
-            drive_bit(1'b0);
-            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                drive_bit(bit_index[0]);
-            end
-            drive_bit(1'b0);
-            drive_bit(1'b1);
-        end
-    endtask
-
-    initial begin
-        rst_n = 1'b0;
-        rx_i = 1'b1;
-        rx_ready = 1'b1;
-        break_probe_i = 1'b1;
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-
-        if ($bits(dut_break0.low_count) != 1 ||
-            $bits(dut_break1.low_count) != 1 ||
-            $bits(dut_break15.low_count) != 4) begin
-            $display(
-                "UART break counter widths mismatch zero=%0d one=%0d fifteen=%0d",
-                $bits(dut_break0.low_count),
-                $bits(dut_break1.low_count),
-                $bits(dut_break15.low_count)
-            );
-            $fatal;
-        end
-
-        drive_bad_stop_frame();
-        repeat (4) @(negedge clk);
-        if (!framing_error) begin
-            $display("UART RX should flag framing error on low stop bit");
-            $fatal;
-        end
-
-        rx_i = 1'b0;
-        repeat (4 * 12) @(negedge clk);
-        if (!break_detected) begin
-            $display("UART RX should flag break after long low level");
-            $fatal;
-        end
-
-        break_probe_i = 1'b0;
-        while (dut_break0.rx_sync !== 1'b0) @(negedge clk);
-        if (break0_detected || break1_detected || break15_detected) begin
-            $display("break asserted before the first synchronized-low sample");
-            $fatal;
-        end
-        @(posedge clk);
-        #1;
-        if (!break0_detected || break1_detected || break15_detected ||
-            dut_break1.low_count !== 1'd1 || dut_break15.low_count !== 4'd1) begin
-            $display(
-                "break first-low mismatch b0=%0b b1=%0b b15=%0b c1=%0d c15=%0d",
-                break0_detected,
-                break1_detected,
-                break15_detected,
-                dut_break1.low_count,
-                dut_break15.low_count
-            );
-            $fatal;
-        end
-        @(posedge clk);
-        #1;
-        if (!break1_detected || break15_detected || dut_break15.low_count !== 4'd2) begin
-            $display(
-                "break second-low mismatch b1=%0b b15=%0b c15=%0d",
-                break1_detected,
-                break15_detected,
-                dut_break15.low_count
-            );
-            $fatal;
-        end
-        repeat (13) begin
-            @(posedge clk);
-            #1;
-        end
-        if (break15_detected || dut_break15.low_count !== 4'd15) begin
-            $display(
-                "break threshold asserted early b15=%0b c15=%0d",
-                break15_detected,
-                dut_break15.low_count
-            );
-            $fatal;
-        end
-        @(posedge clk);
-        #1;
-        if (!break15_detected || dut_break15.low_count !== 4'd15) begin
-            $display(
-                "break threshold did not assert after threshold+1 low clocks b15=%0b c15=%0d",
-                break15_detected,
-                dut_break15.low_count
-            );
-            $fatal;
-        end
-
-        $display("PASS: uart_rx_error_tb");
-        $finish;
-    end
-endmodule

+ 141 - 35
tests/unit/test_build_firmware_package.py

@@ -5,6 +5,7 @@ from __future__ import annotations
 
 import json
 import shutil
+import subprocess
 import sys
 import tempfile
 import unittest
@@ -21,41 +22,78 @@ import build_firmware_package as builder
 ROOT = Path(__file__).resolve().parents[2]
 
 
+def _write_report(path: Path, *, bitstream_sha256: str | None = None, project_sha: str | None = None) -> None:
+    project_sha = project_sha or "cb5c95298ea850740da82657bfaf9bc6dc8a220fac3700d3e05b0024a40a2d18"
+    if bitstream_sha256 is None:
+        bitstream_sha256 = "2ce6b1913b339453da963d4528ceb09ff93a26e61c9c14626d316bbd91f7243f"
+    report = {
+        "run_id": "td-run-123",
+        "verification_run_id": "88888888888888888888888888888888",
+        "commit_full": "fe1a0a2a19622b6f290905ec14795bb6cce6899d",
+        "project_config_sha256": project_sha,
+        "td_source_manifest_sha256": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd",
+        "bitstream_sha256": bitstream_sha256,
+        "synthesis_input_manifest": {
+            "schema": "prod2u-simple-synthesis-inputs-v2",
+            "sha256": "aa9f59236f8ffb89df318eaa5ed5037523d7f46e8b838d45c1e3ab44b60bc423",
+            "inputs": {
+                "src/generated/prod2u_door_temp_params.vh": "ffcb0ffbaef92ef63f96ba7ed6a048cb85d3e9d8a1a5b553e458252446fc6950",
+                "projects/prod2u-door-temp/project.json": project_sha,
+                "src/generated/td-source-manifest.json": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd",
+            },
+        },
+        "timing": {
+            "fmax_mhz": 90.49,
+            "worst_setup_slack_ns": 28.949,
+            "worst_hold_slack_ns": 0.046,
+        },
+        "resources": {
+            "utilization": {
+                "lut": {"used": 1113},
+                "reg": {"used": 677},
+                "bram": {"used": 0},
+                "dsp": {"used": 0},
+            },
+            "packing": {"total_slices": 570},
+        },
+    }
+    path.write_text(json.dumps(report), encoding="utf-8")
+
+
 class BuildFirmwarePackageTests(unittest.TestCase):
+    def _make_td_root(self, tmp_path: Path, *, bitstream_sha256: str | None = None, project_sha: str | None = None) -> tuple[Path, Path, Path]:
+        td_root = tmp_path / "td_root"
+        bitstream = td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit"
+        bitstream.parent.mkdir(parents=True, exist_ok=True)
+        bitstream.write_bytes(b"FAKEBITS")
+        report = td_root / "report.json"
+        _write_report(report, bitstream_sha256=bitstream_sha256, project_sha=project_sha)
+        # Add a fake stage log to verify allowlist
+        (td_root / "td" / "prod2u_p4_normal_v3" / "syn").mkdir(parents=True, exist_ok=True)
+        (td_root / "td" / "prod2u_p4_normal_v3" / "syn" / "gate.qor").write_text("fake qor", encoding="utf-8")
+        return td_root, bitstream, report
+
+    def _commits(self) -> tuple[str, str, str]:
+        # Use the artifact commit for all three in tests so git comparison succeeds.
+        artifact = "fe1a0a2a19622b6f290905ec14795bb6cce6899d"
+        return (artifact, artifact, artifact)
+
     def test_build_with_fake_bitstream_and_report(self) -> None:
         with tempfile.TemporaryDirectory() as tmp:
             tmp_path = Path(tmp)
-            bitstream = tmp_path / "fake.bit"
-            bitstream.write_bytes(b"FAKEBITS")
-            report = tmp_path / "report.json"
-            report.write_text(
-                json.dumps(
-                    {
-                        "utilization": {
-                            "lut": {"used": 1113},
-                            "reg": {"used": 677},
-                            "bram": {"used": 0},
-                            "dsp": {"used": 0},
-                        },
-                        "packing": {"total_slices": 570},
-                        "timing": {
-                            "fmax_mhz": 90.49,
-                            "worst_setup_slack_ns": 28.949,
-                            "worst_hold_slack_ns": 0.046,
-                        },
-                    }
-                ),
-                encoding="utf-8",
-            )
+            td_root, bitstream, report = self._make_td_root(tmp_path)
             output_dir = tmp_path / "dist"
-            package = builder.build_firmware_package(
+            artifact, matrix, final_dev = self._commits()
+            package, sidecar = builder.build_firmware_package(
                 output_dir=output_dir,
                 package_name="test-firmware-package",
-                artifact_commit="fe1a0a2a19622b6f290905ec14795bb6cce6899d",
-                final_dev_commit="48defa6b591b3964fad9e4af637eb4ef4cc94110",
-                source_closure_unchanged=True,
+                td_root=td_root,
                 bitstream_path=bitstream,
                 td_report_path=report,
+                artifact_commit=artifact,
+                matrix_commit=matrix,
+                final_dev_commit=final_dev,
+                source_closure_unchanged=True,
             )
             self.assertTrue(package.is_file())
             with zipfile.ZipFile(package, "r") as zipf:
@@ -64,29 +102,97 @@ class BuildFirmwarePackageTests(unittest.TestCase):
                 self.assertIn("BITSTREAM-SHA256.txt", names)
                 self.assertIn("PACKAGE-MANIFEST.json", names)
                 self.assertIn("SHA256SUMS.txt", names)
-                self.assertIn("project.json", names)
-                self.assertIn("SOURCE-CLOSURE-UNCHANGED.txt", names)
+                self.assertIn("td/original-final_td_report.json", names)
+                self.assertIn("td/TD-PROVENANCE.json", names)
+                self.assertIn("evidence/SOURCE-CLOSURE-COMPARISON.json", names)
+                self.assertIn("td/syn/gate.qor", names)
                 manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
                 self.assertEqual(manifest["hardware_validation"], "not_run")
                 self.assertEqual(manifest["verification_scope"], "offline")
                 self.assertTrue(manifest["source_closure_unchanged"])
+                self.assertEqual(manifest["schema"], "prod2u-door-temp-final-package-manifest-v2")
                 sums = zipf.read("SHA256SUMS.txt").decode("utf-8")
                 self.assertIn("fw.bit", sums)
 
+    def test_bitstream_report_mismatch_blocks(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            tmp_path = Path(tmp)
+            td_root, bitstream, report = self._make_td_root(tmp_path, bitstream_sha256="0" * 64)
+            artifact, matrix, final_dev = self._commits()
+            with self.assertRaises(builder.PackagingError):
+                builder.build_firmware_package(
+                    output_dir=tmp_path / "dist",
+                    package_name="mismatch",
+                    td_root=td_root,
+                    bitstream_path=bitstream,
+                    td_report_path=report,
+                    artifact_commit=artifact,
+                    matrix_commit=matrix,
+                    final_dev_commit=final_dev,
+                    source_closure_unchanged=True,
+                )
+
+    def test_report_outside_td_root_blocks(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            tmp_path = Path(tmp)
+            td_root, bitstream, _ = self._make_td_root(tmp_path)
+            other_report = tmp_path / "other_report.json"
+            _write_report(other_report)
+            artifact, matrix, final_dev = self._commits()
+            with self.assertRaises(builder.PackagingError):
+                builder.build_firmware_package(
+                    output_dir=tmp_path / "dist",
+                    package_name="bad-root",
+                    td_root=td_root,
+                    bitstream_path=bitstream,
+                    td_report_path=other_report,
+                    artifact_commit=artifact,
+                    matrix_commit=matrix,
+                    final_dev_commit=final_dev,
+                    source_closure_unchanged=True,
+                )
+
+    def test_stale_td_logs_not_in_package(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            tmp_path = Path(tmp)
+            td_root, bitstream, report = self._make_td_root(tmp_path)
+            # Place an old log in repo td/ that should not be included
+            (ROOT / "td" / "td_20260630_134648.log").write_text("stale", encoding="utf-8")
+            try:
+                artifact, matrix, final_dev = self._commits()
+                package, _ = builder.build_firmware_package(
+                    output_dir=tmp_path / "dist",
+                    package_name="no-stale",
+                    td_root=td_root,
+                    bitstream_path=bitstream,
+                    td_report_path=report,
+                    artifact_commit=artifact,
+                    matrix_commit=matrix,
+                    final_dev_commit=final_dev,
+                    source_closure_unchanged=True,
+                )
+                with zipfile.ZipFile(package, "r") as zipf:
+                    self.assertNotIn("td/td_20260630_134648.log", set(zipf.namelist()))
+            finally:
+                (ROOT / "td" / "td_20260630_134648.log").unlink(missing_ok=True)
+
     def test_missing_bitstream_blocks(self) -> None:
         with tempfile.TemporaryDirectory() as tmp:
             tmp_path = Path(tmp)
-            report = tmp_path / "report.json"
-            report.write_text(json.dumps({"utilization": {}, "timing": {}}), encoding="utf-8")
+            td_root = tmp_path / "td_root"
+            td_root.mkdir(parents=True, exist_ok=True)
+            report = td_root / "report.json"
+            _write_report(report)
+            artifact, matrix, final_dev = self._commits()
             with self.assertRaises(FileNotFoundError):
                 builder.build_firmware_package(
                     output_dir=tmp_path / "dist",
-                    package_name="test",
-                    artifact_commit="a" * 40,
-                    final_dev_commit="b" * 40,
+                    package_name="missing",
+                    td_root=td_root,
+                    artifact_commit=artifact,
+                    matrix_commit=matrix,
+                    final_dev_commit=final_dev,
                     source_closure_unchanged=True,
-                    bitstream_path=tmp_path / "missing.bit",
-                    td_report_path=report,
                 )
 
 

+ 110 - 10
tests/unit/test_package_for_agent_analysis.py

@@ -211,7 +211,7 @@ class PackageForAgentAnalysisTests(unittest.TestCase):
             )
             self.assertEqual(excluded_by_path["unknown/evidence.bin"], "runtime_evidence_or_waveform")
 
-    def test_7zip_is_required_for_package_creation(self) -> None:
+    def test_package_builds_without_7zip(self) -> None:
         analyzer = load_analyzer(self)
         with tempfile.TemporaryDirectory() as tmp:
             temp = Path(tmp)
@@ -233,15 +233,115 @@ class PackageForAgentAnalysisTests(unittest.TestCase):
             )
 
             with mock.patch.object(analyzer, "find_7z", return_value=None):
-                with self.assertRaisesRegex(analyzer.PackagingError, "7-Zip"):
-                    analyzer.create_analysis_package(
-                        collection=collection,
-                        output_root=temp / "output",
-                        package_name="requires-7z",
-                        max_zip_bytes=1_000_000,
-                        target_zip_bytes=800_000,
-                        force=False,
-                    )
+                result = analyzer.create_analysis_package(
+                    collection=collection,
+                    output_root=temp / "output",
+                    package_name="no-7z-fixture",
+                    max_zip_bytes=1_000_000,
+                    target_zip_bytes=800_000,
+                    force=False,
+                )
+
+            package_dir = Path(result["output_dir"])
+            self.assertEqual(result["status"], "pass")
+            self.assertEqual(len(result["volumes"]), 1)
+            volume = package_dir / result["volumes"][0]["file"]
+            self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
+            self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
+            self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
+            with zipfile.ZipFile(volume) as archive:
+                self.assertIsNone(archive.testzip())
+                names = archive.namelist()
+                self.assertIn("CPLD/workspace-current/src/core.v", names)
+                self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", names)
+                self.assertEqual(
+                    archive.read("CPLD/workspace-current/src/core.v"),
+                    b"module core; endmodule\n",
+                )
+
+    def test_zip_archive_expands_without_7zip(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            archive = temp / "vendor.zip"
+            with zipfile.ZipFile(archive, "w") as zf:
+                zf.writestr("docs/readme.txt", b"safe\n")
+                zf.writestr("build/demo.bit", b"bitstream\n")
+            item = analyzer.make_package_item(
+                archive,
+                relative="external/vendor/vendor.zip",
+                category="hardware",
+                source_id="vendor",
+            )
+
+            prepared = analyzer.prepare_unsupported_archives(
+                (item,),
+                temp_root=temp / "expanded",
+                seven_zip=None,
+                extra_exclusions=(),
+            )
+
+            paths = {it.candidate.relative for it in prepared.items}
+            self.assertIn("external/vendor/vendor.zip.expanded/docs/readme.txt", paths)
+            self.assertNotIn("external/vendor/vendor.zip.expanded/build/demo.bit", paths)
+            self.assertTrue(
+                any(
+                    entry["path"] == "external/vendor/vendor.zip"
+                    and entry["rule"] == "archive_contains_excluded_members"
+                    for entry in prepared.excluded
+                )
+            )
+
+    def test_unsupported_reference_archive_warns_without_7zip(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            archive = temp / "ref.7z"
+            archive.write_bytes(b"dummy")
+            item = analyzer.make_package_item(
+                archive,
+                relative="reference/original/ref.7z",
+                category="core",
+                source_id="ref",
+            )
+
+            prepared = analyzer.prepare_unsupported_archives(
+                (item,),
+                temp_root=temp / "expanded",
+                seven_zip=None,
+                extra_exclusions=(),
+            )
+
+            self.assertEqual(len(prepared.items), 1)
+            self.assertEqual(prepared.items[0].candidate.relative, "reference/original/ref.7z")
+            self.assertFalse(prepared.items[0].scan_archive)
+            self.assertTrue(
+                any(
+                    warning["code"] == "unsupported_archive_without_7zip"
+                    for warning in prepared.warnings
+                )
+            )
+
+    def test_unsupported_core_archive_raises_without_7zip(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            archive = temp / "core.7z"
+            archive.write_bytes(b"dummy")
+            item = analyzer.make_package_item(
+                archive,
+                relative="core/archive.7z",
+                category="core",
+                source_id="core",
+            )
+
+            with self.assertRaisesRegex(analyzer.PackagingError, "7-Zip"):
+                analyzer.prepare_unsupported_archives(
+                    (item,),
+                    temp_root=temp / "expanded",
+                    seven_zip=None,
+                    extra_exclusions=(),
+                )
 
     def test_7zip_creation_command_forces_standard_deflate_level_nine(self) -> None:
         analyzer = load_analyzer(self)

+ 391 - 91
tools/build_firmware_package.py

@@ -1,13 +1,15 @@
 #!/usr/bin/env python3
 """Build the Prod2U door-temperature final firmware delivery package.
 
-This is a thin deterministic wrapper that collects:
-- the canonical bitstream (reused when the production source closure is unchanged),
-- final TD reports,
+This is a deterministic wrapper that collects:
+- the canonical bitstream from an explicit TD root,
+- original and provenance-augmented TD reports,
+- source-closure comparison across artifact/matrix/final dev commits,
+- selected TD stage evidence (syn/phy/bitgen reports and logs),
 - source/contracts/TD inputs,
 - generated host contract and golden vectors,
 - verification receipts (when available),
-- package manifest and SHA-256 sums.
+- package manifest, SHA-256 sums, and an external selftest sidecar.
 
 It does not access COM/JTAG or program hardware.
 """
@@ -17,23 +19,29 @@ import argparse
 import hashlib
 import json
 import shutil
+import subprocess
 import sys
 import zipfile
 from datetime import datetime, timezone
 from pathlib import Path
 from typing import Any
 
+
 ROOT = Path(__file__).resolve().parents[1]
-TD_PRIMARY = Path.home() / "CodexTemp" / "cpld-td-primary2"
-BITSTREAM = TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit"
-TD_REPORT = TD_PRIMARY / "report.json"
-REPORT_DIRS = [
-    ("syn", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "syn"),
-    ("phy", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "phy"),
-    ("bitgen", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "bitgen"),
+
+TD_STAGE_SUFFIXES = {".rpt", ".timing", ".area", ".qor", ".log", ".logw"}
+REPO_TD_INPUTS = [
+    "td/prod2u_p4_normal_v3.prj",
+    "td/syn/prod2u_p4_normal_v3.tcl",
+    "td/phy/prod2u_p4_normal_v3.tcl",
+    "td/bitgen/prod2u_p4_normal_v3.tcl",
 ]
 
 
+class PackagingError(RuntimeError):
+    """Raised when the firmware package cannot be produced safely."""
+
+
 def _sha256_file(path: Path) -> str:
     digest = hashlib.sha256()
     with path.open("rb") as stream:
@@ -42,63 +50,340 @@ def _sha256_file(path: Path) -> str:
     return digest.hexdigest()
 
 
+def _sha256_bytes(data: bytes) -> str:
+    return hashlib.sha256(data).hexdigest()
+
+
 def _read_json(path: Path) -> Any:
     return json.loads(path.read_text(encoding="utf-8-sig"))
 
 
-def _copy_into(dst: Path, src: Path, rel: str) -> None:
-    target = dst / rel
-    target.parent.mkdir(parents=True, exist_ok=True)
-    shutil.copy2(src, target)
+def _git_show_file(repo_root: Path, commit: str, relative_path: str) -> bytes:
+    """Return the contents of a tracked path at a specific commit."""
+    completed = subprocess.run(
+        ["git", "-C", str(repo_root), "show", f"{commit}:{relative_path}"],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+        check=False,
+    )
+    if completed.returncode != 0:
+        raise PackagingError(
+            f"git show failed for {commit}:{relative_path}: {completed.stderr.decode('utf-8', errors='ignore').strip()}"
+        )
+    return completed.stdout
+
+
+def _resolve_path(path: Path) -> Path:
+    return Path(path).expanduser().resolve()
+
+
+def _inside(root: Path, candidate: Path) -> bool:
+    """Return True if candidate is root or under root."""
+    root = _resolve_path(root)
+    candidate = _resolve_path(candidate)
+    try:
+        candidate.relative_to(root)
+        return True
+    except ValueError:
+        return False
+
+
+def _validate_td_root(
+    *,
+    td_root: Path,
+    bitstream_path: Path,
+    td_report_path: Path,
+) -> None:
+    """Ensure bitstream and report belong to the selected TD root."""
+    if not _inside(td_root, bitstream_path):
+        raise PackagingError(f"bitstream {bitstream_path} is outside selected td_root {td_root}")
+    if not _inside(td_root, td_report_path):
+        raise PackagingError(f"td report {td_report_path} is outside selected td_root {td_root}")
+
+
+def _bitstream_path_from_td_root(td_root: Path) -> Path:
+    return _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit")
+
+
+def _report_path_from_td_root(td_root: Path) -> Path:
+    return _resolve_path(td_root / "report.json")
+
 
+def generate_source_closure_comparison(
+    *,
+    td_report: dict[str, Any],
+    artifact_commit: str,
+    matrix_commit: str,
+    final_dev_commit: str,
+    repo_root: Path = ROOT,
+) -> dict[str, Any]:
+    """Compare synthesis inputs across artifact, matrix, and final dev commits."""
+    inputs = td_report.get("synthesis_input_manifest", {}).get("inputs", {})
+    if not inputs:
+        raise PackagingError("TD report has no synthesis_input_manifest.inputs")
+
+    entries: list[dict[str, Any]] = []
+    production_changed_paths: list[str] = []
+    all_same = True
+
+    for relative_path, artifact_sha in sorted(inputs.items()):
+        row: dict[str, Any] = {"path": relative_path, "artifact_expected_sha256": artifact_sha}
+        values: list[str | None] = []
+        for commit, key in [
+            (artifact_commit, "artifact_source_sha256"),
+            (matrix_commit, "matrix_commit_sha256"),
+            (final_dev_commit, "final_dev_commit_sha256"),
+        ]:
+            try:
+                content = _git_show_file(repo_root, commit, relative_path)
+                sha = _sha256_bytes(content)
+            except PackagingError:
+                sha = None
+            row[key] = sha
+            values.append(sha)
+
+        if values[0] == values[1] == values[2] and values[0] is not None:
+            row["status"] = "same"
+        else:
+            row["status"] = "different"
+            all_same = False
+            if values[0] != values[2]:
+                production_changed_paths.append(relative_path)
+
+        entries.append(row)
+
+    comparison_text = json.dumps(
+        {
+            "artifact_source_commit": artifact_commit,
+            "matrix_commit": matrix_commit,
+            "final_dev_commit": final_dev_commit,
+            "source_closure_equal": all_same,
+            "production_changed_paths": production_changed_paths,
+            "entries": entries,
+        },
+        sort_keys=True,
+    )
+    source_set_sha256 = _sha256_bytes(comparison_text.encode("utf-8"))
+
+    return {
+        "schema": "prod2u-source-closure-comparison-v1",
+        "artifact_source_commit": artifact_commit,
+        "matrix_commit": matrix_commit,
+        "final_dev_commit": final_dev_commit,
+        "source_closure_equal": all_same,
+        "production_changed_paths": production_changed_paths,
+        "source_set_sha256": source_set_sha256,
+        "inputs": entries,
+    }
+
+
+def generate_td_provenance(
+    *,
+    original_report: dict[str, Any],
+    artifact_commit: str,
+    source_closure_comparison_sha256: str,
+    bitstream_sha256: str,
+    matrix_run_id: str | None,
+) -> dict[str, Any]:
+    """Bind the original TD run to the current matrix and source closure."""
+    return {
+        "schema": "prod2u-td-provenance-v1",
+        "status": "bound_by_source_closure_comparison",
+        "artifact_source_commit": artifact_commit,
+        "original_td_run_id": original_report.get("run_id"),
+        "original_placeholder_verification_run_id": original_report.get("verification_run_id"),
+        "matrix_run_id": matrix_run_id,
+        "source_closure_comparison_sha256": source_closure_comparison_sha256,
+        "bitstream_sha256": bitstream_sha256,
+        "original_report_path": "td/original-final_td_report.json",
+        "project_config_sha256": original_report.get("project_config_sha256"),
+        "td_source_manifest_sha256": original_report.get("td_source_manifest_sha256"),
+        "synthesis_input_manifest_sha256": original_report.get("synthesis_input_manifest", {}).get("sha256"),
+    }
 
-def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str) -> None:
+
+def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str, sha256_entries: list[str]) -> None:
     zipf.write(src, arcname)
+    sha256_entries.append(f"{_sha256_file(src)}  {arcname}")
+
+
+def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str, sha256_entries: list[str]) -> None:
+    payload = text.encode("utf-8")
+    zipf.writestr(arcname, payload)
+    sha256_entries.append(f"{_sha256_bytes(payload)}  {arcname}")
 
 
-def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str) -> None:
-    zipf.writestr(arcname, text.encode("utf-8"))
+def _collect_td_stage_files(td_root: Path) -> list[tuple[Path, str]]:
+    """Collect allowed evidence files from the selected TD build stages."""
+    collected: list[tuple[Path, str]] = []
+    stages = ["syn", "phy", "bitgen"]
+    for stage in stages:
+        stage_dir = _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / stage)
+        if not stage_dir.is_dir():
+            continue
+        for item in stage_dir.iterdir():
+            if item.is_file() and item.suffix.casefold() in TD_STAGE_SUFFIXES:
+                collected.append((item, f"td/{stage}/{item.name}"))
+    return collected
+
+
+def _selftest_package(
+    *,
+    zip_path: Path,
+    expected_manifest: dict[str, Any],
+    td_root: Path,
+) -> dict[str, Any]:
+    """Verify the built firmware package before writing the sidecar."""
+    failures: list[str] = []
+    with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf:
+        names = set(zipf.namelist())
+        required = {
+            "fw.bit",
+            "BITSTREAM-SHA256.txt",
+            "ARTIFACT-SOURCE-COMMIT.txt",
+            "MATRIX-COMMIT.txt",
+            "FINAL-DEV-COMMIT.txt",
+            "SOURCE-CLOSURE-UNCHANGED.txt",
+            "PACKAGE-MANIFEST.json",
+            "SHA256SUMS.txt",
+            "td/original-final_td_report.json",
+            "td/TD-PROVENANCE.json",
+            "evidence/SOURCE-CLOSURE-COMPARISON.json",
+            "project.json",
+            "config/source_closure.json",
+        }
+        missing = sorted(required - names)
+        if missing:
+            failures.append(f"missing_required_files:{missing}")
+
+        bad = zipf.testzip()
+        if bad is not None:
+            failures.append(f"crc_failed:{bad}")
+
+        manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
+        if manifest["bitstream_sha256"] != expected_manifest["bitstream_sha256"]:
+            failures.append("bitstream_sha_manifest_mismatch")
+
+        # Detect stale repo TD logs from ROOT/td that should not be present
+        for name in names:
+            if name.startswith("td/") and "td_20260630" in name:
+                failures.append(f"stale_td_log_in_package:{name}")
+
+    return {
+        "status": "fail" if failures else "pass",
+        "failures": failures,
+        "package_path": str(zip_path),
+        "package_sha256": _sha256_file(zip_path),
+        "td_root": str(td_root),
+    }
 
 
 def build_firmware_package(
     *,
     output_dir: Path,
     package_name: str | None,
+    td_root: Path,
     artifact_commit: str,
+    matrix_commit: str,
     final_dev_commit: str,
     source_closure_unchanged: bool,
-    bitstream_path: Path = BITSTREAM,
-    td_report_path: Path = TD_REPORT,
-    evidence_dir: Path | None = None,
-) -> Path:
+    bitstream_path: Path | None = None,
+    td_report_path: Path | None = None,
+    matrix_receipt_path: Path | None = None,
+    matrix_run_id: str | None = None,
+) -> tuple[Path, Path]:
+    """Build and selftest the final firmware ZIP."""
+    td_root = _resolve_path(td_root)
+    if bitstream_path is None:
+        bitstream_path = _bitstream_path_from_td_root(td_root)
+    if td_report_path is None:
+        td_report_path = _report_path_from_td_root(td_root)
+    bitstream_path = _resolve_path(bitstream_path)
+    td_report_path = _resolve_path(td_report_path)
+
+    _validate_td_root(td_root=td_root, bitstream_path=bitstream_path, td_report_path=td_report_path)
+
     if not bitstream_path.is_file():
         raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
     if not td_report_path.is_file():
         raise FileNotFoundError(f"TD report not found: {td_report_path}")
 
+    td_report = _read_json(td_report_path)
     bitstream_sha256 = _sha256_file(bitstream_path)
-    name = package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}"
-    output_dir = Path(output_dir).resolve()
-    output_dir.mkdir(parents=True, exist_ok=True)
-    zip_path = output_dir / f"{name}.zip"
-    if zip_path.exists():
-        zip_path.unlink()
 
-    td_report = _read_json(td_report_path)
+    # Strong binding checks
+    report_bitstream_sha = td_report.get("bitstream_sha256")
+    if report_bitstream_sha and report_bitstream_sha != bitstream_sha256:
+        raise PackagingError(
+            f"TD report bitstream_sha256 {report_bitstream_sha} does not match actual {bitstream_sha256}"
+        )
+
+    report_commit = td_report.get("commit_full") or td_report.get("commit")
+    if report_commit and report_commit != artifact_commit:
+        raise PackagingError(
+            f"TD report commit {report_commit} does not match artifact_source_commit {artifact_commit}"
+        )
+
+    report_project_sha = td_report.get("project_config_sha256")
+    current_project_sha = _sha256_file(ROOT / "projects" / "prod2u-door-temp" / "project.json")
+    if report_project_sha and report_project_sha != current_project_sha:
+        raise PackagingError(
+            f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}"
+        )
+
+    comparison = generate_source_closure_comparison(
+        td_report=td_report,
+        artifact_commit=artifact_commit,
+        matrix_commit=matrix_commit,
+        final_dev_commit=final_dev_commit,
+        repo_root=ROOT,
+    )
+    if not source_closure_unchanged and comparison["source_closure_equal"]:
+        # Caller claimed changed but comparison says same: trust explicit flag
+        pass
+    if source_closure_unchanged and not comparison["source_closure_equal"]:
+        raise PackagingError(
+            f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}"
+        )
+
+    comparison_json = json.dumps(comparison, indent=2, sort_keys=True) + "\n"
+    comparison_sha256 = _sha256_bytes(comparison_json.encode("utf-8"))
+
+    provenance = generate_td_provenance(
+        original_report=td_report,
+        artifact_commit=artifact_commit,
+        source_closure_comparison_sha256=comparison_sha256,
+        bitstream_sha256=bitstream_sha256,
+        matrix_run_id=matrix_run_id,
+    )
+    provenance_json = json.dumps(provenance, indent=2, sort_keys=True) + "\n"
+    provenance_sha256 = _sha256_bytes(provenance_json.encode("utf-8"))
+
     timing = td_report.get("timing", {})
     resources_section = td_report.get("resources", {})
     utilization = resources_section.get("utilization", {})
 
     manifest: dict[str, Any] = {
-        "schema": "prod2u-door-temp-final-package-manifest-v1",
-        "package_name": name,
+        "schema": "prod2u-door-temp-final-package-manifest-v2",
+        "package_name": package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}",
+        "status": "VERIFIED_OFFLINE",
         "created_at": datetime.now(timezone.utc).isoformat(),
-        "artifact_source_commit": artifact_commit,
-        "final_dev_commit": final_dev_commit,
-        "source_closure_unchanged": source_closure_unchanged,
         "verification_scope": "offline",
         "hardware_validation": "not_run",
+        "artifact_source_commit": artifact_commit,
+        "matrix_commit": matrix_commit,
+        "final_dev_commit": final_dev_commit,
+        "td_run_id": td_report.get("run_id"),
+        "matrix_run_id": matrix_run_id,
+        "source_closure_unchanged": comparison["source_closure_equal"],
+        "project_config_sha256": current_project_sha,
+        "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"),
+        "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"),
+        "source_closure_comparison_sha256": comparison_sha256,
         "bitstream_sha256": bitstream_sha256,
+        "matrix_receipt_sha256": _sha256_file(matrix_receipt_path) if matrix_receipt_path and matrix_receipt_path.is_file() else None,
+        "original_td_receipt_sha256": _sha256_file(td_report_path),
+        "td_provenance_sha256": provenance_sha256,
         "resources": {
             "lut": utilization.get("lut", {}).get("used"),
             "register": utilization.get("reg", {}).get("used"),
@@ -113,104 +398,119 @@ def build_firmware_package(
         },
     }
 
-    sha256_entries: list[str] = []
-
-    def add_and_hash(src: Path, arcname: str) -> None:
-        _add_file(zipf, src, arcname)
-        sha256_entries.append(f"{_sha256_file(src)}  {arcname}")
+    output_dir = _resolve_path(output_dir)
+    output_dir.mkdir(parents=True, exist_ok=True)
+    name = manifest["package_name"]
+    zip_path = output_dir / f"{name}.zip"
+    if zip_path.exists():
+        zip_path.unlink()
 
-    def add_text_and_hash(text: str, arcname: str) -> None:
-        _add_text(zipf, text, arcname)
-        sha256_entries.append(f"{hashlib.sha256(text.encode('utf-8')).hexdigest()}  {arcname}")
+    sha256_entries: list[str] = []
 
-    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as zipf:
         # Bitstream and provenance
-        add_and_hash(bitstream_path, "fw.bit")
-        add_text_and_hash(bitstream_sha256, "BITSTREAM-SHA256.txt")
-        add_text_and_hash(artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt")
-        add_text_and_hash(final_dev_commit, "FINAL-DEV-COMMIT.txt")
-        add_text_and_hash(
-            "true" if source_closure_unchanged else "false",
-            "SOURCE-CLOSURE-UNCHANGED.txt",
-        )
+        _add_file(zipf, bitstream_path, "fw.bit", sha256_entries)
+        _add_text(zipf, bitstream_sha256, "BITSTREAM-SHA256.txt", sha256_entries)
+        _add_text(zipf, artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt", sha256_entries)
+        _add_text(zipf, matrix_commit, "MATRIX-COMMIT.txt", sha256_entries)
+        _add_text(zipf, final_dev_commit, "FINAL-DEV-COMMIT.txt", sha256_entries)
+        _add_text(zipf, "true" if comparison["source_closure_equal"] else "false", "SOURCE-CLOSURE-UNCHANGED.txt", sha256_entries)
 
-        # Final TD report and selected report files
-        add_and_hash(td_report_path, "td/final_td_report.json")
-        for stage, stage_dir in REPORT_DIRS:
-            if stage_dir.is_dir():
-                for item in stage_dir.iterdir():
-                    if item.is_file() and item.suffix.casefold() in {
-                        ".rpt", ".timing", ".area", ".qor", ".log"
-                    }:
-                        add_and_hash(item, f"td/{stage}/{item.name}")
+        # Original TD report and provenance
+        _add_file(zipf, td_report_path, "td/original-final_td_report.json", sha256_entries)
+        _add_text(zipf, provenance_json, "td/TD-PROVENANCE.json", sha256_entries)
+
+        # Selected TD stage evidence from the explicit TD root
+        for src, arcname in _collect_td_stage_files(td_root):
+            _add_file(zipf, src, arcname, sha256_entries)
 
         # Project contract and protocol
-        add_and_hash(ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json")
-        add_and_hash(ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md")
-        add_and_hash(ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md")
+        _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json", sha256_entries)
+        _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md", sha256_entries)
+        _add_file(zipf, ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md", sha256_entries)
 
         # Generated artifacts
         for gen in (ROOT / "src" / "generated").iterdir():
             if gen.is_file():
-                add_and_hash(gen, f"src/generated/{gen.name}")
+                _add_file(zipf, gen, f"src/generated/{gen.name}", sha256_entries)
 
-        # Constraints and TD inputs
+        # Constraints
         for adc in (ROOT / "constraints").iterdir():
             if adc.is_file():
-                add_and_hash(adc, f"constraints/{adc.name}")
-        for td_item in (ROOT / "td").rglob("*"):
-            if td_item.is_file():
-                rel = td_item.relative_to(ROOT / "td")
-                if rel.parts and rel.parts[0] == "build":
-                    continue
-                arcname = "td/" + "/".join(rel.parts)
-                add_and_hash(td_item, arcname)
+                _add_file(zipf, adc, f"constraints/{adc.name}", sha256_entries)
+
+        # Tracked TD inputs from the repo (not the build root)
+        for td_input in REPO_TD_INPUTS:
+            src = ROOT / td_input
+            if src.is_file():
+                _add_file(zipf, src, td_input, sha256_entries)
 
         # Source closure manifest
-        add_and_hash(ROOT / "config" / "source_closure.json", "config/source_closure.json")
+        _add_file(zipf, ROOT / "config" / "source_closure.json", "config/source_closure.json", sha256_entries)
 
-        # Optional verification/matrix evidence
-        if evidence_dir is not None and evidence_dir.is_dir():
-            for ev_file in evidence_dir.rglob("*"):
-                if ev_file.is_file():
-                    arcname = "evidence/" + "/".join(ev_file.relative_to(evidence_dir).parts)
-                    add_and_hash(ev_file, arcname)
+        # Source-closure comparison
+        _add_text(zipf, comparison_json, "evidence/SOURCE-CLOSURE-COMPARISON.json", sha256_entries)
+
+        # Optional matrix receipt
+        if matrix_receipt_path and matrix_receipt_path.is_file():
+            _add_file(zipf, matrix_receipt_path, "evidence/matrix-receipt.json", sha256_entries)
 
         # Manifest and SHA256SUMS
         manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
-        add_text_and_hash(manifest_text, "PACKAGE-MANIFEST.json")
-        add_text_and_hash("\n".join(sha256_entries) + "\n", "SHA256SUMS.txt")
+        _add_text(zipf, manifest_text, "PACKAGE-MANIFEST.json", sha256_entries)
+        _add_text(zipf, "\n".join(sha256_entries) + "\n", "SHA256SUMS.txt", sha256_entries)
+
+    selftest = _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=td_root)
+    if selftest["status"] != "pass":
+        zip_path.unlink(missing_ok=True)
+        raise PackagingError(f"firmware package selftest failed: {selftest['failures']}")
 
-    return zip_path
+    selftest["package_selftest_status"] = "pass"
+    selftest["manifest"] = manifest
+
+    sidecar_path = output_dir / f"{name}.selftest.json"
+    sidecar_path.write_text(json.dumps(selftest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    return zip_path, sidecar_path
 
 
 def main(argv: list[str] | None = None) -> int:
     parser = argparse.ArgumentParser(description=__doc__)
     parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
     parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
+    parser.add_argument("--td-root", type=Path, required=True)
+    parser.add_argument("--bitstream", type=Path, default=None)
+    parser.add_argument("--td-report", type=Path, default=None)
     parser.add_argument("--artifact-commit", required=True)
+    parser.add_argument("--matrix-commit", required=True)
     parser.add_argument("--final-dev-commit", required=True)
     parser.add_argument("--source-closure-unchanged", action="store_true")
-    parser.add_argument("--bitstream", type=Path, default=BITSTREAM)
-    parser.add_argument("--td-report", type=Path, default=TD_REPORT)
-    parser.add_argument("--evidence-dir", type=Path, default=None)
+    parser.add_argument("--matrix-receipt", type=Path, default=None)
+    parser.add_argument("--matrix-run-id", default=None)
     args = parser.parse_args(argv)
 
     try:
-        path = build_firmware_package(
+        zip_path, sidecar_path = build_firmware_package(
             output_dir=args.output_dir,
             package_name=args.package_name,
+            td_root=args.td_root,
             artifact_commit=args.artifact_commit,
+            matrix_commit=args.matrix_commit,
             final_dev_commit=args.final_dev_commit,
             source_closure_unchanged=args.source_closure_unchanged,
             bitstream_path=args.bitstream,
             td_report_path=args.td_report,
-            evidence_dir=args.evidence_dir,
+            matrix_receipt_path=args.matrix_receipt,
+            matrix_run_id=args.matrix_run_id,
         )
-    except FileNotFoundError as exc:
-        print(f"blocked: {exc}", file=sys.stderr)
+    except (FileNotFoundError, PackagingError) as exc:
+        print(f"error: {exc}", file=sys.stderr)
         return 1
-    print(json.dumps({"status": "pass", "package": str(path), "bitstream": str(BITSTREAM)}, indent=2))
+    print(
+        json.dumps(
+            {"status": "pass", "package": str(zip_path), "selftest": str(sidecar_path)},
+            indent=2,
+        )
+    )
     return 0