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

refactor: remove legacy package and protocol contracts

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

+ 0 - 287
config/prod2u_p4_normal_host_contract_v4.json

@@ -1,287 +0,0 @@
-{
-  "schema": "prod2u-p4-normal-host-contract-v4",
-  "profile": "prod2u-p4-normal-actuator-binary921-v3",
-  "profile_id": 4,
-  "protocol": "binary921-v3",
-  "version_source": "lowercase_git_sha8",
-  "wire": {
-    "magic_hex": "A55A",
-    "version": 2,
-    "seq": 0,
-    "timestamp_tick": 0,
-    "header_offsets": {
-      "magic": [0, 1],
-      "version": 2,
-      "profile_id": 3,
-      "frame_type": 4,
-      "seq_u32_le": [5, 8],
-      "timestamp_tick_u32_le": [9, 12],
-      "payload_length_u8": 13,
-      "payload": [14, "14+payload_length-1"],
-      "crc16_le": ["14+payload_length", "15+payload_length"]
-    },
-    "crc16": {
-      "name": "CRC-16/CCITT-FALSE",
-      "polynomial": 4129,
-      "initial": 65535,
-      "reflect_input": false,
-      "reflect_output": false,
-      "xor_output": 0,
-      "coverage": "version_through_payload_inclusive",
-      "wire_byte_order": "little-endian"
-    },
-    "request_compatibility": "BYTE_EXACT_FROZEN",
-    "ordinary_response_order": ["HOST_ACK"],
-    "motor_status_response_order": ["HOST_ACK", "MOTION_STATUS"],
-    "temperature_response_order": ["TEMPERATURE_SHORT"],
-    "unsolicited_frames": false
-  },
-  "frame_types": {
-    "HOST_CMD": 5,
-    "HOST_ACK": 6,
-    "HOST_BATCH_CMD": 7,
-    "TEMPERATURE_SHORT": 16,
-    "MOTION_CMD": 17,
-    "MOTION_STATUS": 18
-  },
-  "commands": {
-    "get_status": {
-      "frame_type": 5,
-      "command": 36,
-      "payload_length": 4,
-      "payload_hex": "24 00 00 00",
-      "response": "HOST_ACK",
-      "always_accepted": true
-    },
-    "disable": {
-      "frame_type": 5,
-      "command": 38,
-      "payload_length": 4,
-      "payload_hex": "26 00 00 00",
-      "response": "HOST_ACK",
-      "always_accepted": true,
-      "effect": "IMMEDIATE_SAFE_NON_MOTOR_OUTPUTS",
-      "motor_effect": "NONE",
-      "non_motor_effect": "IMMEDIATE_SAFE_OUTPUTS"
-    },
-    "get_temperatures": {
-      "frame_type": 5,
-      "command": 40,
-      "payload_length": 4,
-      "request_payload_hex": "28 00 00 00",
-      "success_response": "TEMPERATURE_SHORT_ONLY_NO_ACK",
-      "powerup_under_one_second": "ALL_FF_NO_I2C",
-      "nack_policy": "CURRENT_VALUE_FF_CONTINUE",
-      "bus_error_status": "TEMPERATURE_BUS_ERROR",
-      "bus_error_status_code": 10,
-      "read_order": ["U6", "U24", "U25"],
-      "addresses": [73, 72, 75],
-      "registers": [0, 1, 2, 3, 4, 5, 6, 7, 8]
-    },
-    "set_output_snapshot": {
-      "frame_type": 7,
-      "command": 42,
-      "payload_length": 34,
-      "full_frame_length": 50,
-      "input_layout": "2A flags PTC1..24 FAN1..4 solenoid X Y Z",
-      "ptc_range": [0, 100],
-      "fan_range": [0, 100],
-      "binary_values": [0, 100],
-      "xyz_range": [0, 255],
-      "xyz_policy": "IGNORE_ANY_U8_NO_MOTOR_EFFECT",
-      "motor_effect": "NONE",
-      "ptc_fan_commit_when_motion_busy": true,
-      "solenoid_change_when_any_xy_busy": "ALWAYS_COMMIT",
-      "axis_policy": "IGNORE_ANY_U8_NO_MOTOR_EFFECT",
-      "response": "HOST_ACK"
-    },
-    "jog": {
-      "frame_type": 17,
-      "command": 53,
-      "payload_length": 8,
-      "full_frame_length": 24,
-      "input_layout": "35 axis raw_dir speed_code steps_u16_le 00 00",
-      "axes": {"X": 0, "Y": 1, "Z_PROTOCOL_ONLY": 2},
-      "cli_axes": ["X", "Y"],
-      "reserved_z_status": "BAD_VALUE",
-      "direction": {"OPEN_UP": 0, "CLOSE_DOWN": 1},
-      "speed_codes": [0, 1, 2, 3],
-      "step_range": [1, 65535],
-      "step_field_policy": "RAW_U16_TRUSTED_HOST_NO_CPLD_CAP",
-      "fast_path_policy": "RX_FAST_JOG_BYPASSES_NORMAL_REQUEST_SLOT",
-      "executed_step_cap": null,
-      "over_cap_status": "NOT_APPLICABLE",
-      "over_cap_behavior": "EXECUTE_REQUESTED_U16_STEPS",
-      "speed_field_policy": "VALIDATE_0_TO_3_THEN_IGNORE",
-      "effective_step_rate_hz": 1000,
-      "ack_semantics": "FIRST_STEP_EMITTED",
-      "arms_watchdog": false,
-      "same_axis_active_policy": "IMMEDIATE_RELOAD_AND_RESTART_DIR_SETUP",
-      "same_axis_host_rule": "HOST_MUST_NOT_REPEAT_SAME_AXIS_BEFORE_COMPLETION",
-      "same_axis_violation_policy": "LATEST_COMMAND_WINS_OLD_ACK_NOT_GUARANTEED",
-      "multiple_pending_policy": "NONE",
-      "replacement_dir_setup_us": 1000,
-      "limit_policy": "IGNORE_ALL_INPUTS",
-      "rejects_busy": false,
-      "admission_ignores": [
-        "AXIS_ACTIVE",
-        "SNAPSHOT_VALID",
-        "LIMIT_INPUTS",
-        "WATCHDOG_TIMEOUT"
-      ],
-      "watchdog_timeout_recovery": "NOT_APPLICABLE_TIMEOUT_HAS_NO_MOTOR_EFFECT",
-      "peer_axis_busy_does_not_block": true,
-      "completion_event": "NONE_HOST_TRACKS_TIME",
-      "response": "HOST_ACK"
-    },
-    "mark_closed": {
-      "frame_type": 17,
-      "command": 54,
-      "payload_length": 8,
-      "input_layout_preserved": true,
-      "status": "UNSUPPORTED_IN_PROFILE",
-      "status_code": 1,
-      "changes_state": false
-    },
-    "get_motor_status": {
-      "frame_type": 17,
-      "command": 55,
-      "payload_length": 8,
-      "payload_hex": "37 00 00 00 00 00 00 00",
-      "responses": ["HOST_ACK", "MOTION_STATUS"],
-      "always_accepted": true,
-      "refreshes_watchdog_only_when_armed": true
-    }
-  },
-  "unsupported_commands": {
-    "0x29": {
-      "request_payload_hex": "29 00 00 00",
-      "status": "UNSUPPORTED_IN_PROFILE",
-      "status_code": 1,
-      "changes_state": false,
-      "arms_watchdog": false
-    },
-    "0x36": {
-      "status": "UNSUPPORTED_IN_PROFILE",
-      "status_code": 1,
-      "changes_state": false,
-      "arms_watchdog": false
-    }
-  },
-  "responses": {
-    "host_ack": {
-      "frame_type": 6,
-      "payload_length": 8,
-      "full_frame_length": 24,
-      "byte_offsets": {
-        "ok": 14,
-        "command": 15,
-        "status": 16,
-        "detail": 17,
-        "state_hash16": [18, 19],
-        "response_type": 20,
-        "result_flags": 21,
-        "crc": [22, 23]
-      },
-      "state_hash16": {
-        "algorithm": "CRC-16/CCITT-FALSE",
-        "encoding": "u16_le",
-        "input_order": ["applied_PTC1..24", "applied_FAN1..4", "applied_solenoid"],
-        "semantic": "ACTUAL_APPLIED_SYNCHRONOUS_OUTPUTS"
-      },
-      "snapshot_detail_bits": {"all_bits": "ZERO"},
-      "snapshot_result_flag_bits": {
-        "ptc_fan_solenoid_committed": 0,
-        "axis_bits_3_to_1": "ZERO"
-      },
-      "status_codes": {
-        "OK": 0,
-        "UNSUPPORTED_IN_PROFILE": 1,
-        "BAD_FLAGS": 2,
-        "BAD_LENGTH": 3,
-        "BAD_VALUE": 5,
-        "BUSY": 9,
-        "TEMPERATURE_BUS_ERROR": 10,
-        "PARTIAL": 22
-      }
-    },
-    "temperature_short": {
-      "frame_type": 16,
-      "payload_length": 27,
-      "full_frame_length": 35,
-      "layout": "A5 5A 02 04 10 1B values[27] crc16_le",
-      "crc_coverage": "02 04 10 1B values[27]",
-      "value_order": [
-        "U6.local",
-        "U6.remote1..8",
-        "U24.local",
-        "U24.remote1..8",
-        "U25.local",
-        "U25.remote1..8"
-      ]
-    },
-    "motion_status": {
-      "frame_type": 18,
-      "payload_length": 10,
-      "full_frame_length": 26,
-      "layout": "flags valid_mask busy_mask current_xyz target_xyz fault_mask",
-      "position_values": {"UNKNOWN": 255},
-      "position_valid_mask": 0,
-      "current_xyz": [255, 255, 255],
-      "target_xyz": [255, 255, 255],
-      "busy_mask": 0,
-      "busy_semantic": "ALWAYS_ZERO",
-      "busy_role": "RESERVED_CONSTANT_ZERO",
-      "enable_active": 1,
-      "fault_mask": 0,
-      "z_current_target": 255,
-      "z_valid_busy_fault": 0
-    }
-  },
-  "motion": {
-    "axes": ["X", "Y"],
-    "execution": "TWO_INDEPENDENT_PARALLEL_EXECUTORS",
-    "motor_driving_commands": ["0x35"],
-    "jog_ack_semantics": "FIRST_STEP_EMITTED",
-    "same_axis_jog_while_active": "IMMEDIATE_RELOAD_AND_RESTART_DIR_SETUP",
-    "peer_axis_may_start": true,
-    "dir_setup_us": 1000,
-    "effective_step_rate_hz": 1000,
-    "normal_step_stop": "NEW_SAME_AXIS_JOG_MAY_TRUNCATE_OLD_STEP",
-    "motor_stop_sources": ["RESET", "POWER_LOSS", "RECONFIGURATION"]
-  },
-  "limit": {
-    "axes": ["X", "Y"],
-    "polarity": "ACTIVE_HIGH",
-    "open_voltage_v": 0.0,
-    "closed_voltage_v": 3.3,
-    "synchronizer_stages": 0,
-    "pins_retained": true,
-    "logic_consumer": "NONE",
-    "used_only_for": "RETAINED_PINS_NO_LOGIC_CONSUMER",
-    "motion_effect": "NONE",
-    "dir0_jog_ignores_limit": true,
-    "dir1_jog_ignores_limit": true,
-    "position_memory": false,
-    "direction_learning": false
-  },
-  "watchdog": {
-    "timeout_seconds": 5,
-    "accepted_output_arms": true,
-    "accepted_motion_arms": false,
-    "armed_get_motor_status_refreshes": true,
-    "status_query_cannot_arm_or_revive": true,
-    "expiry_beats_same_cycle_refresh": true,
-    "expiry_requires_disable_before_rearm": false,
-    "next_valid_output_clears_timeout_and_rearms": true,
-    "motor_effect": "NONE",
-    "non_motor_effect": "SAFE_OUTPUTS"
-  },
-  "programming": {
-    "operation": "PROGRAM_SRAM",
-    "speed_hz": 200000,
-    "attempt_limit": 1,
-    "automatic_retry": false,
-    "flash_allowed": false
-  }
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 116
config/prod2u_p4_normal_v3_hw_binding.json


+ 0 - 32
config/prod2u_p4_normal_v3_resource_baseline.json

@@ -1,32 +0,0 @@
-{
-  "schema": "prod2u-p4-normal-v3-resource-baseline-v3",
-  "profile": "prod2u_p4_normal_v3",
-  "runtime_profile": "prod2u-p4-normal-actuator-binary921-v3",
-  "device": "EF2L45BG256B",
-  "status": "pending_measurement",
-  "policy": {
-    "mode": "advisory_only",
-    "affects_build_status": false
-  },
-  "architecture": {
-    "io": 43,
-    "dsp": 0,
-    "bram9k": 1,
-    "bram32k": 0,
-    "bram128k": 0,
-    "bram256k": 0
-  },
-  "measurement": {
-    "required_clean_builds": 2,
-    "aggregation": "min_max_envelope",
-    "reason": "remeasure_after_on_demand_temperature_b1",
-    "candidate_contract": "RAW_U16_TRUSTED_HOST_NO_CPLD_CAP",
-    "temperature_resource_variant": "B1_COMPACT_BYTE_CRC",
-    "advisory_estimate_provenance": "single_clean_resource_candidate_pending_required_second_build",
-    "advisory_estimate": {
-      "lut": [2234, 2234],
-      "ff": [1810, 1810],
-      "packed_slices": [1237, 1237]
-    }
-  }
-}

Разница между файлами не показана из-за своего большого размера
+ 0 - 362
schemas/prod2u_p4_normal_host_contract_v4.schema.json


+ 1 - 1
schemas/prod2u_p4_normal_v3_offline_gate_receipt.schema.json

@@ -14,7 +14,7 @@
     "commit": {"type": "string", "pattern": "^[0-9a-f]{8}$"},
     "source_state": {"type": "object"},
     "profile": {"const": "prod2u_p4_normal_v3"},
-    "runtime_profile": {"const": "prod2u-p4-normal-actuator-binary921-v3"},
+    "runtime_profile": {"const": "prod2u-door-temp-115200-v1"},
     "required_layers": {
       "const": ["source_integrity", "unit", "hdl_sim", "formal"]
     },

+ 0 - 58
schemas/prod2u_p4_normal_v3_resource_baseline.schema.json

@@ -1,58 +0,0 @@
-{
-  "$schema": "https://json-schema.org/draft/2020-12/schema",
-  "$id": "prod2u-p4-normal-v3-resource-baseline-v3",
-  "type": "object",
-  "additionalProperties": false,
-  "required": [
-    "schema",
-    "profile",
-    "runtime_profile",
-    "device",
-    "status",
-    "policy",
-    "architecture",
-    "measurement"
-  ],
-  "properties": {
-    "schema": {"const": "prod2u-p4-normal-v3-resource-baseline-v3"},
-    "profile": {"const": "prod2u_p4_normal_v3"},
-    "runtime_profile": {"const": "prod2u-p4-normal-actuator-binary921-v3"},
-    "device": {"const": "EF2L45BG256B"},
-    "status": {"enum": ["pending_measurement", "measured"]},
-    "policy": {
-      "const": {"mode": "advisory_only", "affects_build_status": false}
-    },
-    "architecture": {
-      "type": "object",
-      "required": ["io", "dsp", "bram9k", "bram32k", "bram128k", "bram256k"],
-      "properties": {
-        "io": {"const": 43},
-        "dsp": {"type": "integer", "minimum": 0},
-        "bram9k": {"type": "integer", "minimum": 0},
-        "bram32k": {"type": "integer", "minimum": 0},
-        "bram128k": {"type": "integer", "minimum": 0},
-        "bram256k": {"type": "integer", "minimum": 0}
-      },
-      "additionalProperties": false
-    },
-    "measurement": {
-      "type": "object",
-      "required": ["required_clean_builds", "aggregation", "reason"],
-      "properties": {
-        "required_clean_builds": {"const": 2},
-        "aggregation": {"const": "min_max_envelope"},
-        "reason": {"type": "string", "minLength": 1}
-      },
-      "additionalProperties": true
-    },
-    "measured_commit": {"type": "string", "pattern": "^[0-9a-f]{8}$"},
-    "synthesis_input_hash": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
-    "envelope": {"type": "object"}
-  },
-  "allOf": [
-    {
-      "if": {"properties": {"status": {"const": "measured"}}},
-      "then": {"required": ["measured_commit", "synthesis_input_hash", "envelope"]}
-    }
-  ]
-}

+ 1 - 1
schemas/prod2u_p4_normal_v3_td_build_receipt.schema.json

@@ -16,7 +16,7 @@
     "top_module": {"const": "prod2u_p4_normal_v3_top"},
     "pin_profile": {"const": "prod2u-p4-normal-v3"},
     "profile": {"const": "prod2u_p4_normal_v3"},
-    "runtime_profile": {"const": "prod2u-p4-normal-actuator-binary921-v3"},
+    "runtime_profile": {"const": "prod2u-door-temp-115200-v1"},
     "verification_run_id": {"type": "string", "pattern": "^[0-9a-f]{32}$"},
     "run_id": {"type": "string", "pattern": "^[0-9a-f]{32}$"},
     "work_root": {"type": "string", "pattern": "^[A-Za-z]:[\\\\/]"},

+ 0 - 325
schemas/prod2u_program_sram_receipt.schema.json

@@ -1,325 +0,0 @@
-{
-  "$schema": "https://json-schema.org/draft/2020-12/schema",
-  "$id": "prod2u-program-sram-receipt-v1",
-  "title": "Prod2U PROGRAM_SRAM receipt",
-  "type": "object",
-  "required": [
-    "schema",
-    "status",
-    "run_id",
-    "request",
-    "bitstream",
-    "staging",
-    "execution",
-    "parser",
-    "safety",
-    "tool",
-    "mutex",
-    "process_cleanup",
-    "artifacts",
-    "authority_boundary"
-  ],
-  "properties": {
-    "schema": {"const": "prod2u-program-sram-receipt-v1"},
-    "status": {"enum": ["pass", "fail", "fail_forbidden_action"]},
-    "run_id": {"type": "string", "minLength": 1},
-    "request": {
-      "type": "object",
-      "required": ["operation", "target_chip", "cable_index", "speed_code", "speed_hz", "attempt_limit", "power_cycle_allowed"],
-      "properties": {
-        "operation": {"const": "PROGRAM_SRAM"},
-        "target_chip": {"const": "EF2L45"},
-        "cable_index": {"const": 0},
-        "speed_code": {"const": 2},
-        "speed_hz": {"const": 200000},
-        "attempt_limit": {"const": 1},
-        "power_cycle_allowed": {"const": false}
-      },
-      "additionalProperties": true
-    },
-    "bitstream": {
-      "type": "object",
-      "required": ["path", "sha256", "commit"],
-      "properties": {
-        "path": {"type": "string", "minLength": 1},
-        "sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
-        "commit": {"type": "string", "pattern": "^[0-9a-f]{8}$"}
-      },
-      "additionalProperties": true
-    },
-    "staging": {
-      "type": "object",
-      "required": ["expected_path", "observed_path", "matches_expected_path"],
-      "properties": {
-        "expected_path": {"type": "string"},
-        "observed_path": {"type": "string"},
-        "matches_expected_path": {"type": "boolean"}
-      },
-      "additionalProperties": true
-    },
-    "execution": {
-      "type": "object",
-      "required": ["exit_code", "timed_out", "attempt_count", "retry_count", "power_cycle_count", "command_execution_attempted", "timeout_seconds", "started_at", "finished_at", "duration_seconds"],
-      "properties": {
-        "exit_code": {"type": "integer"},
-        "timed_out": {"type": "boolean"},
-        "attempt_count": {"const": 1},
-        "retry_count": {"const": 0},
-        "power_cycle_count": {"const": 0},
-        "command_execution_attempted": {"type": "boolean"},
-        "timeout_seconds": {"const": 60},
-        "started_at": {"type": "string", "minLength": 1},
-        "finished_at": {"type": "string", "minLength": 1},
-        "duration_seconds": {"type": "number", "minimum": 0}
-      },
-      "additionalProperties": true
-    },
-    "parser": {
-      "type": "object",
-      "required": ["status", "exit_code_trusted", "ordered_markers", "ordered_markers_complete", "observed_markers", "observed_marker_lines", "error_markers", "failures", "transcript_sha256"],
-      "properties": {
-        "status": {"enum": ["pass", "fail"]},
-        "exit_code_trusted": {"const": false},
-        "ordered_markers": {"const": ["download_start", "chip_validation", "bit_to_vec_start", "bit_to_vec_finish", "program_start", "program_finish", "download_finish"]},
-        "ordered_markers_complete": {"type": "boolean"},
-        "observed_markers": {"type": "array", "items": {"type": "string"}},
-        "observed_marker_lines": {"type": "array", "items": {"type": "integer", "minimum": 1}},
-        "error_markers": {"type": "array", "items": {"type": "string"}},
-        "failures": {"type": "array", "items": {"type": "string"}},
-        "transcript_sha256": {"$ref": "#/$defs/nonEmptySha256"}
-      },
-      "additionalProperties": true
-    },
-    "safety": {
-      "type": "object",
-      "required": ["flash_attempted", "programs_nonvolatile", "power_cycle_attempted", "driver_install_attempted", "toggles_dtr_rts", "real_ptc_fan_action_attempted", "external_programming_command_executed"],
-      "properties": {
-        "flash_attempted": {"type": "boolean"},
-        "programs_nonvolatile": {"type": "boolean"},
-        "power_cycle_attempted": {"const": false},
-        "driver_install_attempted": {"const": false},
-        "toggles_dtr_rts": {"const": false},
-        "real_ptc_fan_action_attempted": {"const": false},
-        "external_programming_command_executed": {"type": "boolean"}
-      },
-      "additionalProperties": true
-    },
-    "tool": {
-      "type": "object",
-      "required": ["path", "td_root", "td_bin"],
-      "properties": {
-        "path": {"type": "string", "minLength": 1},
-        "td_root": {"type": "string", "minLength": 1},
-        "td_bin": {"type": "string", "minLength": 1}
-      },
-      "additionalProperties": true
-    },
-    "mutex": {
-      "type": "object",
-      "required": ["name", "acquired"],
-      "properties": {
-        "name": {"const": "Global\\Prod2UProgramSram"},
-        "acquired": {"const": true}
-      },
-      "additionalProperties": true
-    },
-    "process_cleanup": {
-      "type": "object",
-      "required": [
-        "status",
-        "td_root",
-        "identity_audit_completed_before_action",
-        "ownership_policy",
-        "discovered_processes",
-        "harness_owned_processes",
-        "blocking_processes",
-        "graceful_close_requested",
-        "forced_terminated",
-        "wait_seconds",
-        "remaining",
-        "post_action_audit_completed",
-        "post_action_discovered_processes",
-        "post_action_harness_owned_processes",
-        "post_action_blocking_processes",
-        "residual_processes",
-        "post_action_errors",
-        "errors"
-      ],
-      "properties": {
-        "status": {"enum": ["pass", "fail"]},
-        "td_root": {"type": "string", "minLength": 1},
-        "identity_audit_completed_before_action": {"const": true},
-        "ownership_policy": {"$ref": "#/$defs/processOwnershipPolicy"},
-        "discovered_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}},
-        "harness_owned_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}},
-        "blocking_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
-        "graceful_close_requested": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}},
-        "forced_terminated": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}},
-        "wait_seconds": {"const": 5.0},
-        "remaining": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
-        "post_action_audit_completed": {"const": true},
-        "post_action_discovered_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
-        "post_action_harness_owned_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
-        "post_action_blocking_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
-        "residual_processes": {"type": "array", "items": {"$ref": "#/$defs/processIdentity"}, "maxItems": 0},
-        "post_action_errors": {"type": "array", "items": {"type": "string"}, "maxItems": 0},
-        "errors": {"type": "array", "items": {"type": "string"}, "maxItems": 0}
-      },
-      "additionalProperties": true
-    },
-    "artifacts": {
-      "type": "object",
-      "required": ["tcl", "stdout", "stderr", "log_delta", "log_delta_sources"],
-      "properties": {
-        "tcl": {"$ref": "#/$defs/artifact"},
-        "stdout": {"$ref": "#/$defs/artifact"},
-        "stderr": {"$ref": "#/$defs/artifact"},
-        "log_delta": {"$ref": "#/$defs/artifact"},
-        "log_delta_sources": {
-          "type": "array",
-          "items": {
-            "type": "object",
-            "required": ["path", "start_offset", "byte_count", "sha256"],
-            "properties": {
-              "path": {"type": "string", "minLength": 1, "pattern": "(^|[\\\\/])bw_[^\\\\/]+\\.log$"},
-              "start_offset": {"type": "integer", "minimum": 0},
-              "byte_count": {"type": "integer", "minimum": 1},
-              "sha256": {"$ref": "#/$defs/nonEmptySha256"}
-            },
-            "additionalProperties": true
-          }
-        }
-      },
-      "additionalProperties": true
-    },
-    "authority_boundary": {"type": "string", "minLength": 1}
-  },
-  "additionalProperties": true,
-  "allOf": [
-    {
-      "if": {
-        "properties": {"status": {"const": "pass"}},
-        "required": ["status"]
-      },
-      "then": {
-        "properties": {
-          "staging": {
-            "properties": {"matches_expected_path": {"const": true}}
-          },
-          "execution": {
-            "properties": {
-              "exit_code": {"const": 0},
-              "timed_out": {"const": false},
-              "attempt_count": {"const": 1},
-              "retry_count": {"const": 0},
-              "power_cycle_count": {"const": 0},
-              "command_execution_attempted": {"const": true},
-              "timeout_seconds": {"const": 60}
-            }
-          },
-          "parser": {
-            "properties": {
-              "status": {"const": "pass"},
-              "ordered_markers_complete": {"const": true},
-              "observed_markers": {"const": ["download_start", "chip_validation", "bit_to_vec_start", "bit_to_vec_finish", "program_start", "program_finish", "download_finish"]},
-              "error_markers": {"maxItems": 0},
-              "failures": {"maxItems": 0}
-            }
-          },
-          "artifacts": {
-            "properties": {
-              "log_delta": {
-                "properties": {
-                  "size": {"type": "integer", "minimum": 1},
-                  "sha256": {"$ref": "#/$defs/nonEmptySha256"}
-                }
-              },
-              "log_delta_sources": {"minItems": 1, "maxItems": 1}
-            }
-          },
-          "safety": {
-            "properties": {
-              "flash_attempted": {"const": false},
-              "programs_nonvolatile": {"const": false},
-              "power_cycle_attempted": {"const": false},
-              "driver_install_attempted": {"const": false},
-              "toggles_dtr_rts": {"const": false},
-              "real_ptc_fan_action_attempted": {"const": false},
-              "external_programming_command_executed": {"const": true}
-            }
-          },
-          "process_cleanup": {
-            "properties": {
-              "status": {"const": "pass"},
-              "identity_audit_completed_before_action": {"const": true},
-              "blocking_processes": {"maxItems": 0},
-              "remaining": {"maxItems": 0},
-              "post_action_audit_completed": {"const": true},
-              "residual_processes": {"maxItems": 0},
-              "post_action_errors": {"maxItems": 0},
-              "errors": {"maxItems": 0}
-            }
-          }
-        }
-      }
-    }
-  ],
-  "$defs": {
-    "processIdentity": {
-      "type": "object",
-      "required": ["pid", "name", "path", "user", "session_id", "parent_pid", "command_line", "start_time", "exe_sha256"],
-      "properties": {
-        "pid": {"type": "integer", "minimum": 1},
-        "name": {"enum": ["td.exe", "td_commands_prompt.exe", "bw.exe", "bw_commands_prompt.exe", "hwserver.exe"]},
-        "path": {"type": "string", "minLength": 1},
-        "user": {"type": "string", "minLength": 1},
-        "session_id": {"type": "integer", "minimum": 0},
-        "parent_pid": {"type": "integer", "minimum": 0},
-        "command_line": {"type": "string", "minLength": 1},
-        "start_time": {"type": "string", "minLength": 1},
-        "exe_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
-      },
-      "additionalProperties": false
-    },
-    "processOwnershipPolicy": {
-      "type": "object",
-      "required": ["owner", "session_id", "parent_pid", "approved_binaries", "command_line"],
-      "properties": {
-        "owner": {"type": "string", "minLength": 1},
-        "session_id": {"type": "integer", "minimum": 0},
-        "parent_pid": {"type": "integer", "minimum": 1},
-        "approved_binaries": {
-          "type": "array",
-          "minItems": 1,
-          "items": {
-            "type": "object",
-            "required": ["name", "path", "exe_sha256"],
-            "properties": {
-              "name": {"enum": ["bw_commands_prompt.exe"]},
-              "path": {"type": "string", "minLength": 1},
-              "exe_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
-            },
-            "additionalProperties": false
-          }
-        },
-        "command_line": {"type": "string", "minLength": 1}
-      },
-      "additionalProperties": false
-    },
-    "nonEmptySha256": {
-      "type": "string",
-      "pattern": "^[0-9a-f]{64}$",
-      "not": {"const": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}
-    },
-    "artifact": {
-      "type": "object",
-      "required": ["path", "size", "sha256"],
-      "properties": {
-        "path": {"type": "string", "minLength": 1},
-        "size": {"type": "integer", "minimum": 0},
-        "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
-      },
-      "additionalProperties": true
-    }
-  }
-}

+ 0 - 841
tools/package_prod2u_p4_normal_v3.ps1

@@ -1,841 +0,0 @@
-param(
-    [Parameter(Mandatory = $true)][string]$OutputDir,
-    [Parameter(Mandatory = $true)][string]$NormalBitstream,
-    [Parameter(Mandatory = $true)][string]$TdReceipt,
-    [Parameter(Mandatory = $true)][ValidatePattern('^[0-9a-f]{32}$')][string]$VerificationRunId,
-    [AllowEmptyString()][string]$ConfirmationTdReceipt = "",
-    [string[]]$ValidationReceipt = @(),
-    [string]$HostContract = "",
-    [string]$Commit = "",
-    [string]$WheelhouseRoot = "",
-    [ValidateSet("python", "icarus", "verilator", "cocotb", "formal", "td_confirmation")]
-    [string[]]$RunningValidationLayer = @(),
-    [switch]$UrgentSingleTd
-)
-
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-
-$repo = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
-$packageScriptRelative = "tools/package_prod2u_p4_normal_v3.ps1"
-$readmeSourceRelative = "docs/prod2u-p4-normal-v3-runbook.zh-CN.md"
-$hostContractSchemaRelative = "schemas/prod2u_p4_normal_host_contract_v4.schema.json"
-$hardwareBindingRelative = "config/prod2u_p4_normal_v3_hw_binding.json"
-$verificationTargetsRelative = "config/prod2u_p4_verification_targets_v1.json"
-$tdReceiptSchema = "prod2u-p4-normal-v3-td-build-receipt-v2"
-$validationLayerNames = @(
-    "python", "icarus", "verilator", "cocotb", "formal",
-    "td_primary", "td_confirmation", "td_primary_artifacts",
-    "td_confirmation_artifacts", "td_confirmation_bitstream",
-    "td_confirmation_synthesis", "td_confirmation_manifest",
-    "resource_primary", "resource_confirmation", "package_selftest"
-)
-$verificationEvidenceLayers = @(
-    "python", "icarus", "verilator", "cocotb", "formal",
-    "td_primary", "td_confirmation", "td_primary_artifacts",
-    "td_confirmation_artifacts", "td_confirmation_bitstream",
-    "td_confirmation_synthesis", "td_confirmation_manifest",
-    "resource_primary", "resource_confirmation"
-)
-$templateRelatives = @(
-    "tools/package_templates/bootstrap.ps1",
-    "tools/package_templates/selftest.ps1",
-    "tools/package_templates/run.ps1",
-    "tools/package_templates/SEND_HEX.ps1",
-    "tools/package_templates/INITIALIZE_DISABLE.ps1",
-    "tools/package_templates/PROGRAM_SRAM.ps1"
-)
-if (-not $HostContract) {
-    $HostContract = Join-Path $repo "config\prod2u_p4_normal_host_contract_v4.json"
-}
-
-function Assert-File([string]$Path, [string]$Label) {
-    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
-        throw "$Label is missing: $Path"
-    }
-}
-
-function Assert-NonEmptyFile([string]$Path, [string]$Label) {
-    Assert-File $Path $Label
-    if ((Get-Item -LiteralPath $Path).Length -le 0) {
-        throw "$Label is empty: $Path"
-    }
-}
-
-function Resolve-Git {
-    $git = Get-Command git.exe -ErrorAction SilentlyContinue
-    if (-not $git) { $git = Get-Command git -ErrorAction SilentlyContinue }
-    if (-not $git) { throw "Git is required to bind the package commit" }
-    return $git.Source
-}
-
-function Resolve-Commit([string]$Requested) {
-    $git = Resolve-Git
-    $headFull = (& $git -C $repo rev-parse HEAD).Trim().ToLowerInvariant()
-    if ($LASTEXITCODE -ne 0 -or $headFull -cnotmatch '^[0-9a-f]{40}$') {
-        throw "Unable to resolve package commit"
-    }
-    $headShort = $headFull.Substring(0, 8)
-    if ($Requested) {
-        $requestedCommit = $Requested
-        if ($requestedCommit -cnotmatch '^[0-9a-f]{8}$') {
-            throw "Commit must be an 8-digit lowercase Git object id"
-        }
-        if ($requestedCommit -cne $headShort) {
-            throw "Explicit Commit does not match repository HEAD"
-        }
-    }
-    return [ordered]@{
-        full = $headFull
-        short = $headShort
-    }
-}
-
-function Resolve-RepoRelativePath([string]$Path, [string]$Label) {
-    $repoFull = [System.IO.Path]::GetFullPath($repo).TrimEnd('\') + '\'
-    $pathFull = [System.IO.Path]::GetFullPath($Path)
-    if (-not $pathFull.StartsWith($repoFull, [System.StringComparison]::OrdinalIgnoreCase)) {
-        throw "$Label must be inside the repository and tracked by HEAD"
-    }
-    return $pathFull.Substring($repoFull.Length).Replace('\', '/')
-}
-
-function Assert-CleanCommittedSources(
-    [string]$Git,
-    [string]$ResolvedCommit,
-    [string[]]$Relatives
-) {
-    & $Git -C $repo diff --quiet --exit-code $ResolvedCommit -- . ":(exclude).planning/**"
-    $diffExit = $LASTEXITCODE
-    if ($diffExit -eq 1) { throw "repository has tracked source changes outside .planning/" }
-    if ($diffExit -ne 0) { throw "unable to verify repository tracked source state" }
-    $statusLines = @(& $Git -C $repo status --porcelain=v1 --untracked-files=all)
-    if ($LASTEXITCODE -ne 0) { throw "unable to verify repository untracked source state" }
-    $unexpected = @(
-        $statusLines | Where-Object {
-            $relative = ([string]$_).Substring(3).Replace('\', '/')
-            -not ($relative -eq ".planning" -or $relative.StartsWith(".planning/"))
-        }
-    )
-    if ($unexpected.Count -gt 0) {
-        throw ("repository has untracked or modified files outside .planning/: " + ($unexpected -join ", "))
-    }
-    foreach ($relative in $Relatives) {
-        $saved = $ErrorActionPreference
-        $ErrorActionPreference = "SilentlyContinue"
-        & $Git -C $repo cat-file -e "$ResolvedCommit`:$relative" 2>$null
-        $objectExit = $LASTEXITCODE
-        $ErrorActionPreference = $saved
-        if ($objectExit -ne 0) {
-            throw "package source file is not tracked by HEAD: $relative"
-        }
-    }
-}
-
-function Assert-PrimaryPinBinding([object]$Receipt) {
-    $gate = Get-PropertyValue $Receipt "post_route_pin_gate"
-    if ($null -eq $gate -or [string](Get-PropertyValue $gate "status") -ne "pass") {
-        throw "Primary TD pin gate is not pass"
-    }
-    if ([int](Get-PropertyValue $gate "row_count") -ne 43) {
-        throw "Primary TD pin gate row count is not 43"
-    }
-    $failures = @(Get-PropertyValue $gate "failures")
-    if ($failures.Count -ne 0) {
-        throw "Primary TD pin gate contains failures"
-    }
-    $observed = Get-PropertyValue $gate "observed"
-    $expected = [ordered]@{
-        motor_en_n = @("A10", "OUTPUT", "LVCMOS33", "NONE")
-        x_step = @("C11", "OUTPUT", "LVCMOS33", "NONE")
-        x_dir = @("B12", "OUTPUT", "LVCMOS33", "NONE")
-        y_step = @("D15", "OUTPUT", "LVCMOS33", "NONE")
-        y_dir = @("H14", "OUTPUT", "LVCMOS33", "NONE")
-        x_limit_raw = @("B9", "INPUT", "LVCMOS33", "PULLUP")
-        y_limit_raw = @("A11", "INPUT", "LVCMOS33", "PULLUP")
-    }
-    foreach ($name in $expected.Keys) {
-        $record = Get-PropertyValue $observed $name
-        if ($null -eq $record -or
-            [string](Get-PropertyValue $record "location") -ne $expected[$name][0] -or
-            [string](Get-PropertyValue $record "direction") -ne $expected[$name][1] -or
-            [string](Get-PropertyValue $record "io_standard") -ne $expected[$name][2] -or
-            [string](Get-PropertyValue $record "pull_type") -ne $expected[$name][3]) {
-            throw "Primary TD pin binding mismatch: $name"
-        }
-    }
-    foreach ($property in @($observed.PSObject.Properties)) {
-        if ([string](Get-PropertyValue $property.Value "location") -eq "A5") {
-            throw "Primary TD pin gate assigns forbidden pin A5"
-        }
-    }
-}
-
-function Assert-PrimaryReceiptBinding(
-    [object]$Receipt,
-    [string]$ResolvedCommit,
-    [string]$BitstreamSha256
-) {
-    if ([string](Get-PropertyValue $Receipt "schema") -ne $tdReceiptSchema) {
-        throw "Primary TD receipt schema mismatch"
-    }
-    $sourceState = Get-PropertyValue $Receipt "source_state"
-    if ($null -eq $sourceState -or
-        (Get-PropertyValue $sourceState "clean") -ne $true -or
-        [string](Get-PropertyValue $sourceState "commit") -ne $ResolvedCommit) {
-        throw "Primary TD receipt source state is not clean and commit-bound"
-    }
-    $sourceBinding = Get-PropertyValue $Receipt "source_binding_gate"
-    if ($null -eq $sourceBinding -or
-        [string](Get-PropertyValue $sourceBinding "status") -ne "pass") {
-        throw "Primary TD receipt source binding gate is not pass"
-    }
-    $bindingGate = Get-PropertyValue $Receipt "binding_gate"
-    if ($null -eq $bindingGate -or
-        [string](Get-PropertyValue $bindingGate "status") -ne "pass") {
-        throw "Primary TD receipt device binding gate is not pass"
-    }
-    $synthesisInputHash = [string](Get-PropertyValue $Receipt "synthesis_input_hash")
-    if ($synthesisInputHash -notmatch '^[0-9a-f]{64}$') {
-        throw "Primary TD receipt synthesis input hash is invalid"
-    }
-    $manifest = Get-PropertyValue $Receipt "synthesis_input_manifest"
-    $manifestHash = [string](Get-PropertyValue $manifest "sha256")
-    $manifestInputs = Get-PropertyValue $manifest "inputs"
-    if ($null -eq $manifest -or $manifestHash -ne $synthesisInputHash -or
-        $null -eq $manifestInputs -or @($manifestInputs.PSObject.Properties).Count -eq 0) {
-        throw "Primary TD receipt synthesis manifest is not hash-bound"
-    }
-
-    $candidates = @()
-    $direct = Get-PropertyValue $Receipt "bitstream"
-    if ($null -ne $direct) { $candidates += $direct }
-    $measurements = Get-PropertyValue $Receipt "measurement_artifacts"
-    $measured = Get-PropertyValue $measurements "bitstream"
-    if ($null -ne $measured) { $candidates += $measured }
-    $artifactBound = $false
-    foreach ($candidate in $candidates) {
-        $path = [string](Get-PropertyValue $candidate "path")
-        $declaredHash = [string](Get-PropertyValue $candidate "sha256")
-        $declaredSize = Get-PropertyValue $candidate "size"
-        if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { continue }
-        $item = Get-Item -LiteralPath $path
-        if ($item.Length -le 0) { continue }
-        if ($null -ne $declaredSize -and [int64]$declaredSize -ne $item.Length) { continue }
-        if ($declaredHash -and $declaredHash -ne $BitstreamSha256) { continue }
-        if ((Get-Sha256 $path) -eq $BitstreamSha256) {
-            $artifactBound = $true
-            break
-        }
-    }
-    if (-not $artifactBound) {
-        throw "Primary TD receipt bitstream artifact is not hash-bound"
-    }
-}
-
-function New-CommitSourceSnapshot(
-    [string]$Git,
-    [string]$ResolvedCommit,
-    [string[]]$Relatives,
-    [string]$Destination
-) {
-    $archive = "$Destination.zip"
-    $arguments = @(
-        "-C", $repo,
-        "archive", "--format=zip", "--output=$archive",
-        $ResolvedCommit, "--"
-    ) + @($Relatives)
-    & $Git @arguments
-    if ($LASTEXITCODE -ne 0) { throw "unable to materialize package sources from HEAD" }
-    New-Item -ItemType Directory -Force -Path $Destination | Out-Null
-    Expand-Archive -LiteralPath $archive -DestinationPath $Destination -Force
-    Remove-Item -LiteralPath $archive -Force
-}
-
-function Get-Sha256([string]$Path) {
-    return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant()
-}
-
-function Write-Utf8NoBom([string]$Path, [string]$Text) {
-    $parent = Split-Path -Parent $Path
-    if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
-    [System.IO.File]::WriteAllText($Path, $Text, [System.Text.UTF8Encoding]::new($false))
-}
-
-function Write-Json([string]$Path, [object]$Value) {
-    $text = $Value | ConvertTo-Json -Depth 20
-    Write-Utf8NoBom $Path ($text + "`n")
-}
-
-function Read-Json([string]$Path, [string]$Label) {
-    Assert-File $Path $Label
-    try {
-        return Get-Content -LiteralPath $Path -Raw -Encoding UTF8 | ConvertFrom-Json
-    } catch {
-        throw "$Label is not valid JSON: $Path"
-    }
-}
-
-function Get-PropertyValue([object]$Value, [string]$Name) {
-    if ($null -eq $Value) { return $null }
-    $property = $Value.PSObject.Properties[$Name]
-    if ($null -eq $property) { return $null }
-    return $property.Value
-}
-
-function Normalize-ValidationStatus([object]$Value) {
-    $status = [string]$Value
-    if ($status -eq "pass") { return "pass" }
-    if ($status -eq "running") { return "running" }
-    if ($status -eq "not_run" -or $status -eq "skipped" -or $status.StartsWith("blocked")) {
-        return "not_run"
-    }
-    return "fail"
-}
-
-function Get-ValidationStatusRank([string]$Status) {
-    switch ($Status) {
-        "fail" { return 4 }
-        "running" { return 3 }
-        "not_run" { return 2 }
-        "pass" { return 1 }
-        default { return 4 }
-    }
-}
-
-function New-ValidationLayer([string]$Status, [string]$Source, [object]$OriginalStatus) {
-    return [ordered]@{
-        status = $Status
-        source = $Source
-        original_status = if ($null -eq $OriginalStatus) { $null } else { [string]$OriginalStatus }
-    }
-}
-
-function Set-ValidationLayer(
-    [System.Collections.IDictionary]$Layers,
-    [string]$Name,
-    [object]$Status,
-    [string]$Source
-) {
-    $newLayer = New-ValidationLayer (Normalize-ValidationStatus $Status) $Source $Status
-    $existing = $Layers[$Name]
-    if ($null -eq $existing -or
-        [string]$existing.source -eq "not_provided" -or
-        ([string]$existing.source -eq "declared_running" -and $Source -ne "declared_running")) {
-        $Layers[$Name] = $newLayer
-        return
-    }
-    if ((Get-ValidationStatusRank $newLayer.status) -gt
-        (Get-ValidationStatusRank ([string]$existing.status))) {
-        $Layers[$Name] = $newLayer
-    }
-}
-
-function Test-VerificationComplete(
-    [System.Collections.IDictionary]$Layers,
-    [string]$DeliveryMode
-) {
-    if ($DeliveryMode -ne "normal_dual_td") { return $false }
-    foreach ($name in $verificationEvidenceLayers) {
-        if ([string]$Layers[$name].status -ne "pass") { return $false }
-    }
-    return $true
-}
-
-function Get-ValidationSummaryStatus([System.Collections.IDictionary]$Layers) {
-    $statuses = @($Layers.Values | ForEach-Object { [string]$_.status })
-    if ($statuses -contains "fail") { return "fail" }
-    if ($statuses -contains "running") { return "running" }
-    if ($statuses -contains "not_run") { return "not_run" }
-    return "pass"
-}
-
-function Merge-ValidationReceipt(
-    [System.Collections.IDictionary]$Layers,
-    [object]$Receipt,
-    [string]$Source
-) {
-    $schema = [string](Get-PropertyValue $Receipt "schema")
-    if ($schema -eq "prod2u-p4-normal-v3-strict-offline-gate-v1") {
-        $children = Get-PropertyValue $Receipt "layers"
-        if ($null -ne $children) {
-            $unit = Get-PropertyValue $children "unit"
-            if ($null -ne $unit) {
-                Set-ValidationLayer $Layers "python" (Get-PropertyValue $unit "status") $Source
-            }
-            $formal = Get-PropertyValue $children "formal"
-            if ($null -ne $formal) {
-                Set-ValidationLayer $Layers "formal" (Get-PropertyValue $formal "status") $Source
-            }
-            $hdl = Get-PropertyValue $children "hdl_sim"
-            if ($null -ne $hdl) {
-                $backendResults = Get-PropertyValue $hdl "backend_results"
-                foreach ($backend in @("icarus", "verilator", "cocotb")) {
-                    $child = Get-PropertyValue $backendResults $backend
-                    if ($null -ne $child) {
-                        Set-ValidationLayer $Layers $backend (Get-PropertyValue $child "status") $Source
-                    }
-                }
-            }
-        }
-        return
-    }
-
-    $layer = [string](Get-PropertyValue $Receipt "verification_layer")
-    $status = Get-PropertyValue $Receipt "status"
-    if ($layer -eq "formal") {
-        Set-ValidationLayer $Layers "formal" $status $Source
-    } elseif ($layer -eq "unit") {
-        Set-ValidationLayer $Layers "python" $status $Source
-    } elseif ($layer -eq "hdl_sim") {
-        $backend = [string](Get-PropertyValue $Receipt "backend")
-        if ($backend -in @("icarus", "verilator", "cocotb")) {
-            Set-ValidationLayer $Layers $backend $status $Source
-        } elseif ($backend -eq "all") {
-            $backendResults = Get-PropertyValue $Receipt "backend_results"
-            foreach ($name in @("icarus", "verilator", "cocotb")) {
-                $child = Get-PropertyValue $backendResults $name
-                if ($null -ne $child) {
-                    Set-ValidationLayer $Layers $name (Get-PropertyValue $child "status") $Source
-                }
-            }
-        }
-    } elseif ($schema -eq "prod2u-p4-normal-v3-package-selftest-v1") {
-        Set-ValidationLayer $Layers "package_selftest" $status $Source
-    }
-}
-
-function Get-ResourceStatus([object]$Receipt) {
-    $structural = Get-PropertyValue $Receipt "structural_gate"
-    $resources = Get-PropertyValue $structural "resources"
-    $status = Get-PropertyValue $resources "status"
-    if ($null -ne $status) { return $status }
-    $resourceGate = Get-PropertyValue $Receipt "resource_gate"
-    $status = Get-PropertyValue $resourceGate "status"
-    if ($null -ne $status) { return $status }
-    return "not_run"
-}
-
-function Get-ComparisonStatus([object]$Observed, [object]$Expected) {
-    if ($null -eq $Observed -or [string]$Observed -eq "") { return "not_run" }
-    if ([string]$Observed -eq [string]$Expected) { return "pass" }
-    return "fail"
-}
-
-function Get-TdBitstreamBindingStatus([object]$Receipt) {
-    $digest = [string](Get-PropertyValue $Receipt "bitstream_sha256")
-    if (-not $digest) { return "not_run" }
-    if ($digest -notmatch '^[0-9a-f]{64}$') { return "fail" }
-    $candidates = @()
-    $direct = Get-PropertyValue $Receipt "bitstream"
-    if ($null -ne $direct) { $candidates += $direct }
-    $measurements = Get-PropertyValue $Receipt "measurement_artifacts"
-    $measured = Get-PropertyValue $measurements "bitstream"
-    if ($null -ne $measured) { $candidates += $measured }
-    foreach ($candidate in $candidates) {
-        $path = [string](Get-PropertyValue $candidate "path")
-        $expected = [string](Get-PropertyValue $candidate "sha256")
-        if ($expected -ne $digest) { continue }
-        if (Test-Path -LiteralPath $path -PathType Leaf) {
-            if ((Get-Sha256 $path) -eq $digest) { return "pass" }
-        }
-    }
-    return "fail"
-}
-
-function Copy-TdArtifacts(
-    [object]$Receipt,
-    [string]$Destination,
-    [string]$PackageRelativeRoot
-) {
-    New-Item -ItemType Directory -Force -Path $Destination | Out-Null
-    $records = [ordered]@{}
-    $artifacts = Get-PropertyValue $Receipt "measurement_artifacts"
-    if ($null -eq $artifacts) { return $records }
-    foreach ($property in @($artifacts.PSObject.Properties)) {
-        $name = [string]$property.Name
-        if ($name -eq "bitstream") { continue }
-        $metadata = $property.Value
-        $source = [string](Get-PropertyValue $metadata "path")
-        $expectedHash = [string](Get-PropertyValue $metadata "sha256")
-        $record = [ordered]@{
-            status = "fail"
-            source_path = $source
-            expected_sha256 = $expectedHash
-            package_path = $null
-            observed_sha256 = $null
-        }
-        if (Test-Path -LiteralPath $source -PathType Leaf) {
-            $observed = Get-Sha256 $source
-            $record.observed_sha256 = $observed
-            if ($expectedHash -match '^[0-9a-f]{64}$' -and $observed -eq $expectedHash) {
-                $safeName = ($name -replace '[^A-Za-z0-9_.-]', '_')
-                $extension = [System.IO.Path]::GetExtension($source)
-                if (-not $extension) { $extension = ".bin" }
-                $fileName = "$safeName$extension"
-                $target = Join-Path $Destination $fileName
-                Copy-Item -LiteralPath $source -Destination $target
-                $record.status = "pass"
-                $record.package_path = "$PackageRelativeRoot/$fileName"
-            }
-        }
-        $records[$name] = $record
-    }
-    return $records
-}
-
-function Get-ArtifactValidationStatus([System.Collections.IDictionary]$Records) {
-    if ($Records.Count -eq 0) { return "not_run" }
-    foreach ($record in $Records.Values) {
-        if ([string]$record.status -ne "pass") { return "fail" }
-    }
-    return "pass"
-}
-
-function Copy-TdPinGate(
-    [object]$Receipt,
-    [string]$Destination,
-    [string]$PackageRelativePath
-) {
-    $pinGate = Get-PropertyValue $Receipt "post_route_pin_gate"
-    if ($null -eq $pinGate) {
-        return [ordered]@{ status = "not_run"; package_path = $null; sha256 = $null }
-    }
-    Write-Json $Destination $pinGate
-    return [ordered]@{
-        status = "pass"
-        package_path = $PackageRelativePath
-        sha256 = Get-Sha256 $Destination
-    }
-}
-
-function Get-PackageFileHashes([string]$Root) {
-    $result = [ordered]@{}
-    Get-ChildItem -LiteralPath $Root -Recurse -File | Sort-Object FullName | ForEach-Object {
-        $relative = $_.FullName.Substring($Root.Length).TrimStart('\').Replace('\', '/')
-        if ($relative -notin @("package-info.json", "evidence/package-selftest-result.json")) {
-            $result[$relative] = Get-Sha256 $_.FullName
-        }
-    }
-    return $result
-}
-
-function Invoke-FolderSelftest([string]$Root) {
-    $savedErrorActionPreference = $ErrorActionPreference
-    $ErrorActionPreference = "Continue"
-    try {
-        $output = & powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Root "selftest.ps1") 2>&1 | Out-String
-        $returnCode = $LASTEXITCODE
-    } catch {
-        $output = $_ | Out-String
-        $returnCode = if ($LASTEXITCODE) { $LASTEXITCODE } else { 1 }
-    } finally {
-        $ErrorActionPreference = $savedErrorActionPreference
-    }
-    return [ordered]@{
-        schema = "prod2u-p4-normal-v3-package-selftest-result-v1"
-        status = if ($returnCode -eq 0) { "pass" } else { "fail" }
-        returncode = $returnCode
-        output = $output.Trim()
-    }
-}
-
-Assert-NonEmptyFile $NormalBitstream "Normal bitstream"
-Assert-File $TdReceipt "Primary TD build receipt"
-$deliveryMode = if ($UrgentSingleTd) { "urgent_single_td" } else { "normal_dual_td" }
-$confirmationTdPresent = -not [string]::IsNullOrWhiteSpace($ConfirmationTdReceipt)
-if ($UrgentSingleTd) {
-    if ($confirmationTdPresent) {
-        throw "Urgent single-TD mode must not include a Confirmation TD build receipt"
-    }
-} else {
-    if (-not $confirmationTdPresent) {
-        throw "Confirmation TD build receipt is required in normal dual-TD mode"
-    }
-    Assert-File $ConfirmationTdReceipt "Confirmation TD build receipt"
-}
-Assert-File $HostContract "Normal v3 host contract"
-foreach ($receipt in $ValidationReceipt) {
-    Assert-File $receipt "Validation receipt"
-}
-
-$hostContractRelative = Resolve-RepoRelativePath $HostContract "Normal v3 host contract"
-$sourceRelatives = @(
-    $packageScriptRelative,
-    $readmeSourceRelative,
-    $hostContractSchemaRelative,
-    $hostContractRelative,
-    $hardwareBindingRelative,
-    $verificationTargetsRelative
-) + $templateRelatives | Sort-Object -Unique
-foreach ($relative in $sourceRelatives) {
-    Assert-File (Join-Path $repo $relative) "Package source $relative"
-}
-
-$commitBinding = Resolve-Commit $Commit
-$resolvedFullCommit = [string]$commitBinding.full
-$resolvedCommit = [string]$commitBinding.short
-$git = Resolve-Git
-Assert-CleanCommittedSources $git $resolvedFullCommit $sourceRelatives
-
-$bitstreamSha256 = Get-Sha256 $NormalBitstream
-$tdPrimary = Read-Json $TdReceipt "Primary TD build receipt"
-if ([string](Get-PropertyValue $tdPrimary "commit") -ne $resolvedCommit) {
-    throw "Primary TD receipt commit does not match package commit"
-}
-if ([string](Get-PropertyValue $tdPrimary "verification_run_id") -ne $VerificationRunId) {
-    throw "Primary TD receipt verification_run_id mismatch"
-}
-if ([string](Get-PropertyValue $tdPrimary "bitstream_sha256") -ne $bitstreamSha256) {
-    throw "Primary TD receipt bitstream hash does not match package bitstream"
-}
-Assert-PrimaryReceiptBinding $tdPrimary $resolvedCommit $bitstreamSha256
-Assert-PrimaryPinBinding $tdPrimary
-$synthesisInputHash = [string](Get-PropertyValue $tdPrimary "synthesis_input_hash")
-$primaryManifest = Get-PropertyValue $tdPrimary "synthesis_input_manifest"
-$primaryManifestSha256 = Get-PropertyValue $primaryManifest "sha256"
-$tdConfirmation = $null
-$confirmationBitstreamSha256 = $null
-$confirmationSynthesisInputHash = $null
-$confirmationManifestSha256 = $null
-if ($confirmationTdPresent) {
-    $tdConfirmation = Read-Json $ConfirmationTdReceipt "Confirmation TD build receipt"
-    $confirmationCommit = [string](Get-PropertyValue $tdConfirmation "commit")
-    if ($confirmationCommit -ne $resolvedCommit) {
-        throw "Confirmation TD receipt commit does not match package commit"
-    }
-    if ([string](Get-PropertyValue $tdConfirmation "verification_run_id") -ne $VerificationRunId) {
-        throw "Confirmation TD receipt verification_run_id mismatch"
-    }
-    $confirmationBitstreamSha256 = Get-PropertyValue $tdConfirmation "bitstream_sha256"
-    if ($confirmationBitstreamSha256 -and
-        [string]$confirmationBitstreamSha256 -ne $bitstreamSha256) {
-        throw "Confirmation TD receipt bitstream hash does not match primary"
-    }
-    $confirmationSynthesisInputHash = Get-PropertyValue $tdConfirmation "synthesis_input_hash"
-    $confirmationManifest = Get-PropertyValue $tdConfirmation "synthesis_input_manifest"
-    $confirmationManifestSha256 = Get-PropertyValue $confirmationManifest "sha256"
-    $primaryRunId = [string](Get-PropertyValue $tdPrimary "run_id")
-    $confirmationRunId = [string](Get-PropertyValue $tdConfirmation "run_id")
-    if ($primaryRunId -notmatch '^[0-9a-f]{32}$' -or
-        $confirmationRunId -notmatch '^[0-9a-f]{32}$' -or
-        $primaryRunId -eq $confirmationRunId) {
-        throw "Primary and confirmation TD run_id must differ"
-    }
-    $primaryWorkRoot = [string](Get-PropertyValue $tdPrimary "work_root")
-    $confirmationWorkRoot = [string](Get-PropertyValue $tdConfirmation "work_root")
-    if ([string]::IsNullOrWhiteSpace($primaryWorkRoot) -or
-        [string]::IsNullOrWhiteSpace($confirmationWorkRoot) -or
-        $primaryWorkRoot -cnotmatch '^[A-Za-z]:[\\/]' -or
-        $confirmationWorkRoot -cnotmatch '^[A-Za-z]:[\\/]' -or
-        [string]::Equals(
-            [System.IO.Path]::GetFullPath($primaryWorkRoot).TrimEnd('\'),
-            [System.IO.Path]::GetFullPath($confirmationWorkRoot).TrimEnd('\'),
-            [System.StringComparison]::OrdinalIgnoreCase
-        )) {
-        throw "Primary and confirmation TD work_root must differ"
-    }
-}
-
-$outFull = [System.IO.Path]::GetFullPath($OutputDir)
-$commitRoot = Join-Path $outFull $resolvedCommit
-New-Item -ItemType Directory -Force -Path $commitRoot | Out-Null
-$packageName = "prod2u-p4-normal-$resolvedCommit-$($bitstreamSha256.Substring(0, 16))"
-$final = Join-Path $commitRoot $packageName
-if (Test-Path -LiteralPath $final) { throw "Package folder already exists: $final" }
-$stage = Join-Path $commitRoot (".prod2u-p4-normal-stage-" + [Guid]::NewGuid().ToString("N"))
-New-Item -ItemType Directory -Path $stage | Out-Null
-
-try {
-    $sourceSnapshot = Join-Path $stage ".source-snapshot"
-    New-CommitSourceSnapshot $git $resolvedFullCommit $sourceRelatives $sourceSnapshot
-
-    $configDir = Join-Path $stage "config"
-    $evidenceDir = Join-Path $stage "evidence"
-    $validationDir = Join-Path $evidenceDir "validation"
-    $schemaDir = Join-Path $stage "schemas"
-    foreach ($directory in @($configDir, $evidenceDir, $validationDir, $schemaDir)) {
-        New-Item -ItemType Directory -Force -Path $directory | Out-Null
-    }
-
-    $packagedBitstream = Join-Path $stage "fw.bit"
-    $packagedPrimaryReceipt = Join-Path $evidenceDir "td-primary-receipt.json"
-    $packagedConfirmationReceipt = Join-Path $evidenceDir "td-confirmation-receipt.json"
-    Copy-Item -LiteralPath $NormalBitstream -Destination $packagedBitstream
-    Copy-Item -LiteralPath $TdReceipt -Destination $packagedPrimaryReceipt
-    if ($confirmationTdPresent) {
-        Copy-Item -LiteralPath $ConfirmationTdReceipt -Destination $packagedConfirmationReceipt
-    }
-    Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hostContractRelative) -Destination (Join-Path $configDir "host-contract.json")
-    Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hardwareBindingRelative) -Destination (Join-Path $configDir "prod2u_p4_normal_v3_hw_binding.json")
-    Copy-Item -LiteralPath (Join-Path $sourceSnapshot $verificationTargetsRelative) -Destination (Join-Path $configDir "prod2u_p4_verification_targets_v1.json")
-    Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hostContractSchemaRelative) -Destination (Join-Path $schemaDir "host-contract.schema.json")
-
-    $templateRoot = Join-Path $sourceSnapshot "tools\package_templates"
-    foreach ($template in @(
-        "bootstrap.ps1",
-        "selftest.ps1",
-        "run.ps1",
-        "SEND_HEX.ps1",
-        "INITIALIZE_DISABLE.ps1",
-        "PROGRAM_SRAM.ps1"
-    )) {
-        Copy-Item -LiteralPath (Join-Path $templateRoot $template) -Destination (Join-Path $stage $template)
-    }
-
-    $readme = [System.IO.File]::ReadAllText(
-        (Join-Path $sourceSnapshot $readmeSourceRelative),
-        [System.Text.Encoding]::UTF8
-    )
-    Write-Utf8NoBom (Join-Path $stage "README.zh-CN.md") ($readme + "`r`n")
-    Remove-Item -LiteralPath $sourceSnapshot -Recurse -Force
-
-    $layers = [ordered]@{}
-    foreach ($name in $validationLayerNames) {
-        $layers[$name] = New-ValidationLayer "not_run" "not_provided" "not_run"
-    }
-    foreach ($name in $RunningValidationLayer) {
-        Set-ValidationLayer $layers $name "running" "declared_running"
-    }
-    Set-ValidationLayer $layers "td_primary" (Get-PropertyValue $tdPrimary "status") "evidence/td-primary-receipt.json"
-    Set-ValidationLayer $layers "resource_primary" (Get-ResourceStatus $tdPrimary) "evidence/td-primary-receipt.json"
-    if ($confirmationTdPresent) {
-        Set-ValidationLayer $layers "td_confirmation" (Get-PropertyValue $tdConfirmation "status") "evidence/td-confirmation-receipt.json"
-        Set-ValidationLayer $layers "resource_confirmation" (Get-ResourceStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
-        Set-ValidationLayer $layers "td_confirmation_bitstream" (Get-TdBitstreamBindingStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
-        Set-ValidationLayer $layers "td_confirmation_synthesis" (Get-ComparisonStatus $confirmationSynthesisInputHash $synthesisInputHash) "evidence/td-confirmation-receipt.json"
-        Set-ValidationLayer $layers "td_confirmation_manifest" (Get-ComparisonStatus $confirmationManifestSha256 $primaryManifestSha256) "evidence/td-confirmation-receipt.json"
-    }
-
-    $primaryArtifacts = Copy-TdArtifacts $tdPrimary (Join-Path $evidenceDir "td-primary") "evidence/td-primary"
-    $primaryPinGate = Copy-TdPinGate $tdPrimary (Join-Path $evidenceDir "td-primary\pin-gate.json") "evidence/td-primary/pin-gate.json"
-    $primaryArtifacts["pin_gate"] = $primaryPinGate
-    $layers["td_primary"]["artifacts"] = $primaryArtifacts
-    Set-ValidationLayer $layers "td_primary_artifacts" (Get-ArtifactValidationStatus $primaryArtifacts) "evidence/td-primary"
-    if ($confirmationTdPresent) {
-        $confirmationArtifacts = Copy-TdArtifacts $tdConfirmation (Join-Path $evidenceDir "td-confirmation") "evidence/td-confirmation"
-        $confirmationPinGate = Copy-TdPinGate $tdConfirmation (Join-Path $evidenceDir "td-confirmation\pin-gate.json") "evidence/td-confirmation/pin-gate.json"
-        $confirmationArtifacts["pin_gate"] = $confirmationPinGate
-        $layers["td_confirmation"]["artifacts"] = $confirmationArtifacts
-        Set-ValidationLayer $layers "td_confirmation_artifacts" (Get-ArtifactValidationStatus $confirmationArtifacts) "evidence/td-confirmation"
-    }
-
-    $validationSources = @()
-    $validationIndex = 0
-    foreach ($receiptPath in $ValidationReceipt) {
-        $validationIndex += 1
-        $receipt = Read-Json $receiptPath "Validation receipt"
-        $receiptCommit = Get-PropertyValue $receipt "commit"
-        if ($null -ne $receiptCommit -and [string]$receiptCommit -ne $resolvedCommit) {
-            throw "Validation receipt commit does not match package commit"
-        }
-        if ([string](Get-PropertyValue $receipt "verification_run_id") -ne $VerificationRunId) {
-            throw "Validation receipt verification_run_id mismatch"
-        }
-        $base = [System.IO.Path]::GetFileNameWithoutExtension($receiptPath) -replace '[^A-Za-z0-9_.-]', '_'
-        $fileName = ("{0:D2}-{1}.json" -f $validationIndex, $base)
-        $target = Join-Path $validationDir $fileName
-        Copy-Item -LiteralPath $receiptPath -Destination $target
-        $relative = "evidence/validation/$fileName"
-        $validationSources += [ordered]@{
-            path = $relative
-            sha256 = Get-Sha256 $target
-            schema = Get-PropertyValue $receipt "schema"
-            status = Get-PropertyValue $receipt "status"
-            verification_run_id = $VerificationRunId
-        }
-        Merge-ValidationReceipt $layers $receipt $relative
-    }
-
-    $verificationComplete = Test-VerificationComplete $layers $deliveryMode
-
-    $validationSummaryPath = Join-Path $evidenceDir "validation-summary.json"
-    $validationSummary = [ordered]@{
-        schema = "prod2u-p4-normal-v3-validation-summary-v1"
-        verification_run_id = $VerificationRunId
-        commit = $resolvedCommit
-        bitstream_sha256 = $bitstreamSha256
-        delivery_mode = $deliveryMode
-        verification_complete = $verificationComplete
-        confirmation_td_present = $confirmationTdPresent
-        layers = $layers
-        sources = @($validationSources)
-        policy = [ordered]@{
-            image_created_when_bitstream_nonempty = $true
-            validation_failures_block_package = $false
-            allowed_statuses = @("pass", "fail", "running", "not_run")
-        }
-    }
-    Write-Json $validationSummaryPath $validationSummary
-
-    $selftestResultPath = Join-Path $evidenceDir "package-selftest-result.json"
-    $provisionalSelftest = [ordered]@{
-        schema = "prod2u-p4-normal-v3-package-selftest-result-v1"
-        status = "not_run"
-        returncode = $null
-        output = ""
-    }
-    Write-Json $selftestResultPath $provisionalSelftest
-
-    $packageInfoPath = Join-Path $stage "package-info.json"
-    $packageInfo = [ordered]@{
-        schema = "prod2u-p4-normal-v3-folder-package-info-v3"
-        profile = "prod2u-p4-normal-actuator-binary921-v3"
-        verification_run_id = $VerificationRunId
-        commit = $resolvedCommit
-        bitstream_sha256 = $bitstreamSha256
-        delivery_mode = $deliveryMode
-        verification_complete = $verificationComplete
-        confirmation_td_present = $confirmationTdPresent
-        confirmation_bitstream_sha256 = $confirmationBitstreamSha256
-        td_receipt_sha256 = Get-Sha256 $packagedPrimaryReceipt
-        confirmation_td_receipt_sha256 = if ($confirmationTdPresent) { Get-Sha256 $packagedConfirmationReceipt } else { $null }
-        validation_summary_sha256 = Get-Sha256 $validationSummaryPath
-        package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
-        synthesis_input_hash = $synthesisInputHash
-        confirmation_synthesis_input_hash = $confirmationSynthesisInputHash
-        file_sha256 = Get-PackageFileHashes $stage
-    }
-    Write-Json $packageInfoPath $packageInfo
-
-    $selftestResult = Invoke-FolderSelftest $stage
-    Set-ValidationLayer $layers "package_selftest" $selftestResult.status "evidence/package-selftest-result.json"
-    Write-Json $validationSummaryPath $validationSummary
-    Write-Json $selftestResultPath $selftestResult
-    $packageInfo.validation_summary_sha256 = Get-Sha256 $validationSummaryPath
-    $packageInfo.package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
-    $packageInfo.file_sha256 = Get-PackageFileHashes $stage
-    Write-Json $packageInfoPath $packageInfo
-
-    $finalSelftest = Invoke-FolderSelftest $stage
-    if ($finalSelftest.status -ne "pass") {
-        Set-ValidationLayer $layers "package_selftest" "fail" "evidence/package-selftest-result.json"
-        Write-Json $validationSummaryPath $validationSummary
-        Write-Json $selftestResultPath $finalSelftest
-        $packageInfo.validation_summary_sha256 = Get-Sha256 $validationSummaryPath
-        $packageInfo.package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
-        $packageInfo.file_sha256 = Get-PackageFileHashes $stage
-        Write-Json $packageInfoPath $packageInfo
-        $selftestResult = $finalSelftest
-    }
-
-    Move-Item -LiteralPath $stage -Destination $final
-    $stage = $null
-    [ordered]@{
-        schema = "prod2u-p4-normal-v3-folder-package-v3"
-        status = "pass"
-        package = $final
-        verification_run_id = $VerificationRunId
-        commit = $resolvedCommit
-        bitstream_sha256 = $bitstreamSha256
-        delivery_mode = $deliveryMode
-        verification_complete = $verificationComplete
-        confirmation_td_present = $confirmationTdPresent
-        validation_status = Get-ValidationSummaryStatus $layers
-        package_selftest_status = $selftestResult.status
-    } | ConvertTo-Json -Compress
-} finally {
-    if ($stage -and (Test-Path -LiteralPath $stage)) {
-        Remove-Item -LiteralPath $stage -Recurse -Force
-    }
-}

+ 0 - 14
tools/package_templates/INITIALIZE_DISABLE.ps1

@@ -1,14 +0,0 @@
-param(
-    [string]$Port = "COM5",
-    [int]$Baud = 921600
-)
-
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-$root = Split-Path -Parent $MyInvocation.MyCommand.Path
-Write-Warning "DANGER: DISABLE DOES NOT STOP an active JOG in this temporary image. Only RESET, POWER-OFF, or CPLD RECONFIGURATION can STOP the motor."
-& powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $root "SEND_HEX.ps1") `
-    -Port $Port `
-    -Baud $Baud `
-    -Hex "A55A02040500000000000000000426000000C4AE"
-exit $LASTEXITCODE

+ 0 - 57
tools/package_templates/PROGRAM_SRAM.ps1

@@ -1,57 +0,0 @@
-param(
-    [Parameter(Mandatory = $true)]
-    [ValidateSet("PROGRAM_SRAM")]
-    [string]$Confirm,
-    [string]$TdRoot = "C:\Anlogic\TD_Release_2026.1_SP1.198.412"
-)
-
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-$root = Split-Path -Parent $MyInvocation.MyCommand.Path
-$infoPath = Join-Path $root "package-info.json"
-$source = Join-Path $root "fw.bit"
-$info = Get-Content -LiteralPath $infoPath -Raw -Encoding UTF8 | ConvertFrom-Json
-$observed = (Get-FileHash -Algorithm SHA256 -LiteralPath $source).Hash.ToLowerInvariant()
-if ($observed -ne [string]$info.bitstream_sha256) { throw "bitstream hash mismatch" }
-if ([string]$info.commit -cnotmatch '^[0-9a-f]{8}$') { throw "package commit is invalid" }
-
-$active = @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
-    $_.ProcessName -in @("td", "bw", "bw_commands_prompt")
-})
-if ($active.Count -ne 0) {
-    throw "TD or BitWriter process is already running; close it manually before programming"
-}
-
-$stage = Join-Path "C:\P2U" ([string]$info.commit)
-New-Item -ItemType Directory -Force -Path $stage | Out-Null
-$stagedBitstream = Join-Path $stage "fw.bit"
-Copy-Item -LiteralPath $source -Destination $stagedBitstream -Force
-if ((Get-FileHash -Algorithm SHA256 -LiteralPath $stagedBitstream).Hash.ToLowerInvariant() -ne $observed) {
-    throw "staged bitstream hash mismatch"
-}
-
-$tcl = Join-Path $stage "program-sram.tcl"
-$log = Join-Path $stage "program-sram-console.log"
-$bitPath = $stagedBitstream.Replace('\', '/')
-[System.IO.File]::WriteAllText(
-    $tcl,
-    "connect_cable -allink`n" +
-    "download -bit {$bitPath} -mode jtag -spd 2 -cable 0`n" +
-    "exit`n",
-    [System.Text.Encoding]::ASCII
-)
-$writer = Join-Path $TdRoot "bin\bw_commands_prompt.exe"
-if (-not (Test-Path -LiteralPath $writer -PathType Leaf)) { throw "BitWriter executable is missing" }
-
-$output = & $writer $tcl 2>&1 | Out-String
-[System.IO.File]::WriteAllText($log, $output, [System.Text.UTF8Encoding]::new($false))
-if ($LASTEXITCODE -ne 0) { throw "PROGRAM_SRAM failed; no retry was attempted" }
-[ordered]@{
-    status = "pass"
-    attempt_count = 1
-    commit = [string]$info.commit
-    bitstream_sha256 = $observed
-    speed_hz = 200000
-    next_command = ".\INITIALIZE_DISABLE.ps1"
-    log = $log
-} | ConvertTo-Json -Compress

+ 0 - 282
tools/package_templates/SEND_HEX.ps1

@@ -1,282 +0,0 @@
-param(
-    [Parameter(Mandatory = $true)][string]$Hex,
-    [string]$Port = "COM5",
-    [int]$Baud = 921600,
-    [int]$TimeoutMs = 750
-)
-
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-
-function Convert-HexToBytes([string]$Value) {
-    $normalized = ($Value -replace '[^0-9A-Fa-f]', '').ToUpperInvariant()
-    if (-not $normalized -or ($normalized.Length % 2) -ne 0) {
-        throw "Hex must contain a nonempty even number of hexadecimal digits"
-    }
-    $bytes = [byte[]]::new($normalized.Length / 2)
-    for ($index = 0; $index -lt $bytes.Length; $index++) {
-        $bytes[$index] = [Convert]::ToByte($normalized.Substring($index * 2, 2), 16)
-    }
-    return $bytes
-}
-
-function Convert-BytesToHex([byte[]]$Bytes) {
-    return (($Bytes | ForEach-Object { "{0:X2}" -f $_ }) -join '')
-}
-
-function Get-Crc16([byte[]]$Bytes, [int]$Offset, [int]$Count) {
-    [uint32]$crc = 0xFFFF
-    for ($index = 0; $index -lt $Count; $index++) {
-        $crc = ($crc -bxor ([uint32]$Bytes[$Offset + $index] -shl 8)) -band 0xFFFF
-        for ($bit = 0; $bit -lt 8; $bit++) {
-            if (($crc -band 0x8000) -ne 0) {
-                $crc = (($crc -shl 1) -bxor 0x1021) -band 0xFFFF
-            } else {
-                $crc = ($crc -shl 1) -band 0xFFFF
-            }
-        }
-    }
-    return [uint16]$crc
-}
-
-function Convert-BinaryFrames([byte[]]$Bytes, [string]$Label) {
-    $frames = [System.Collections.Generic.List[object]]::new()
-    $offset = 0
-    while ($offset -lt $Bytes.Length) {
-        $remaining = $Bytes.Length - $offset
-        if ($remaining -lt 16) {
-            throw "$Label truncated frame"
-        }
-        if ($Bytes[$offset] -ne 0xA5 -or $Bytes[$offset + 1] -ne 0x5A) {
-            throw "$Label envelope mismatch: magic"
-        }
-        if ($Bytes[$offset + 2] -ne 2) {
-            throw "$Label envelope mismatch: version"
-        }
-        if ($Bytes[$offset + 3] -ne 4) {
-            throw "$Label envelope mismatch: profile"
-        }
-        for ($index = 5; $index -le 8; $index++) {
-            if ($Bytes[$offset + $index] -ne 0) {
-                throw "$Label envelope mismatch: seq must be zero"
-            }
-        }
-        for ($index = 9; $index -le 12; $index++) {
-            if ($Bytes[$offset + $index] -ne 0) {
-                throw "$Label envelope mismatch: timestamp must be zero"
-            }
-        }
-
-        $payloadLength = [int]$Bytes[$offset + 13]
-        $frameLength = 16 + $payloadLength
-        if ($remaining -lt $frameLength) {
-            throw "$Label truncated frame"
-        }
-        $frame = [byte[]]::new($frameLength)
-        [Array]::Copy($Bytes, $offset, $frame, 0, $frameLength)
-        $expectedCrc = Get-Crc16 $frame 2 ($frameLength - 4)
-        $actualCrc = [uint16]([uint32]$frame[$frameLength - 2] -bor ([uint32]$frame[$frameLength - 1] -shl 8))
-        if ($actualCrc -ne $expectedCrc) {
-            throw "$Label CRC mismatch"
-        }
-
-        $payload = [byte[]]::new($payloadLength)
-        if ($payloadLength -gt 0) {
-            [Array]::Copy($frame, 14, $payload, 0, $payloadLength)
-        }
-        [void]$frames.Add([pscustomobject]@{
-            Type = [int]$frame[4]
-            PayloadLength = $payloadLength
-            Payload = $payload
-            Raw = $frame
-        })
-        $offset += $frameLength
-    }
-    return $frames.ToArray()
-}
-
-function Get-RequestOpcode([byte[]]$Request) {
-    $requestFrames = @(Convert-BinaryFrames -Bytes $Request -Label "Request")
-    if ($requestFrames.Count -ne 1) {
-        throw "Request must contain exactly one binary921-v3 frame"
-    }
-    $requestFrame = $requestFrames[0]
-    if ($requestFrame.Type -notin @(0x05, 0x07, 0x11)) {
-        throw ("Request frame type 0x{0:X2} is not a host request" -f $requestFrame.Type)
-    }
-    if ($requestFrame.PayloadLength -lt 1) {
-        throw "Request payload has no command opcode"
-    }
-    return [int]$requestFrame.Payload[0]
-}
-
-function Get-ResponseTimeoutMs(
-    [byte[]]$Request,
-    [int]$RequestedTimeoutMs
-) {
-    if ($RequestedTimeoutMs -le 0) {
-        throw "RequestedTimeoutMs must be positive"
-    }
-    $opcode = Get-RequestOpcode -Request $Request
-    if ($opcode -eq 0x35) {
-        return [Math]::Max($RequestedTimeoutMs, 3000)
-    }
-    return $RequestedTimeoutMs
-}
-
-function Get-StatusName([int]$Status) {
-    switch ($Status) {
-        0x00 { return "OK" }
-        0x01 { return "UNSUPPORTED_IN_PROFILE" }
-        0x02 { return "BAD_FLAGS" }
-        0x03 { return "BAD_LENGTH" }
-        0x05 { return "BAD_VALUE" }
-        0x09 { return "BUSY" }
-        0x16 { return "PARTIAL" }
-        default { throw ("HOST_ACK contains unknown status 0x{0:X2}" -f $Status) }
-    }
-}
-
-function Assert-ResponseContract([byte[]]$Request, [byte[]]$ResponseBytes) {
-    $requestOpcode = Get-RequestOpcode -Request $Request
-    $frames = @(Convert-BinaryFrames -Bytes $ResponseBytes -Label "Response")
-    if ($frames.Count -eq 0) {
-        throw "Missing HOST_ACK"
-    }
-    if ($frames[0].Type -ne 0x06) {
-        throw "First response is not HOST_ACK"
-    }
-
-    $ackFrame = $frames[0]
-    if ($ackFrame.PayloadLength -ne 8) {
-        throw ("HOST_ACK payload length must be 8, got {0}" -f $ackFrame.PayloadLength)
-    }
-    $ackPayload = $ackFrame.Payload
-    if ($ackPayload[0] -notin @(0, 1)) {
-        throw "HOST_ACK ok must be 0 or 1"
-    }
-    $ackOk = $ackPayload[0] -eq 1
-    $ackCommand = [int]$ackPayload[1]
-    if ($ackCommand -ne $requestOpcode) {
-        throw ("ACK command mismatch: requested 0x{0:X2}, received 0x{1:X2}" -f $requestOpcode, $ackCommand)
-    }
-    $statusValue = [int]$ackPayload[2]
-    $statusName = Get-StatusName -Status $statusValue
-    $acceptedStatus = $statusValue -in @(0x00, 0x16)
-    if ($ackOk -ne $acceptedStatus) {
-        throw ("ACK ok/status mismatch: ok={0}, status={1}" -f ([int]$ackOk), $statusName)
-    }
-    if (-not $ackOk) {
-        throw ("Device rejected command 0x{0:X2}: {1} (0x{2:X2})" -f $requestOpcode, $statusName, $statusValue)
-    }
-
-    $responseType = [int]$ackPayload[6]
-    $resultFlags = [int]$ackPayload[7]
-    if ($requestOpcode -eq 0x37) {
-        if ($frames.Count -ne 2 -or $frames[1].Type -ne 0x12) {
-            throw "GET_MOTOR_STATUS must receive exactly HOST_ACK then MOTION_STATUS"
-        }
-        if ($responseType -ne 0x12) {
-            throw "GET_MOTOR_STATUS ACK response type mismatch"
-        }
-        if ($resultFlags -ne 0x08) {
-            throw "GET_MOTOR_STATUS ACK result flags mismatch"
-        }
-        if ($frames[1].PayloadLength -ne 10) {
-            throw ("MOTION_STATUS payload length must be 10, got {0}" -f $frames[1].PayloadLength)
-        }
-    } else {
-        if ($frames.Count -ne 1) {
-            throw "Ordinary command must receive exactly one HOST_ACK"
-        }
-        if ($responseType -ne 0) {
-            throw "Ordinary HOST_ACK response type must be zero"
-        }
-    }
-
-    $frameResults = @(
-        foreach ($frame in $frames) {
-            [ordered]@{
-                type = ("0x{0:X2}" -f $frame.Type)
-                payload_length = $frame.PayloadLength
-                hex = Convert-BytesToHex $frame.Raw
-            }
-        }
-    )
-    return [ordered]@{
-        status = "pass"
-        request_opcode = ("0x{0:X2}" -f $requestOpcode)
-        ack = [ordered]@{
-            ok = $ackOk
-            command = ("0x{0:X2}" -f $ackCommand)
-            status = $statusName
-            status_code = ("0x{0:X2}" -f $statusValue)
-            detail = ("0x{0:X2}" -f [int]$ackPayload[3])
-            state_hash16 = ("0x{0:X4}" -f ([uint16]([uint32]$ackPayload[4] -bor ([uint32]$ackPayload[5] -shl 8))))
-            response_type = ("0x{0:X2}" -f $responseType)
-            result_flags = ("0x{0:X2}" -f $resultFlags)
-        }
-        frames = $frameResults
-    }
-}
-
-# SEND_HEX_RUNTIME_START
-
-$request = Convert-HexToBytes $Hex
-$effectiveTimeoutMs = Get-ResponseTimeoutMs `
-    -Request $request `
-    -RequestedTimeoutMs $TimeoutMs
-
-$serial = [System.IO.Ports.SerialPort]::new($Port, $Baud, "None", 8, "One")
-$serial.Handshake = "None"
-$serial.DtrEnable = $false
-$serial.RtsEnable = $false
-$serial.ReadTimeout = 25
-$serial.WriteTimeout = 250
-$buffer = [System.Collections.Generic.List[byte]]::new()
-$deadline = [DateTime]::UtcNow.AddMilliseconds($effectiveTimeoutMs)
-$quietDeadline = $null
-
-try {
-    $serial.Open()
-    $serial.DiscardInBuffer()
-    $serial.DiscardOutBuffer()
-    $serial.Write($request, 0, $request.Length)
-
-    while ([DateTime]::UtcNow -lt $deadline) {
-        $available = $serial.BytesToRead
-        if ($available -gt 0) {
-            $chunk = [byte[]]::new($available)
-            $read = $serial.Read($chunk, 0, $chunk.Length)
-            for ($index = 0; $index -lt $read; $index++) {
-                $buffer.Add($chunk[$index])
-            }
-            $quietDeadline = [DateTime]::UtcNow.AddMilliseconds(30)
-        } elseif ($null -ne $quietDeadline -and [DateTime]::UtcNow -ge $quietDeadline) {
-            break
-        } else {
-            Start-Sleep -Milliseconds 1
-        }
-    }
-} finally {
-    if ($serial.IsOpen) {
-        $serial.Close()
-    }
-    $serial.Dispose()
-}
-
-if ($buffer.Count -eq 0) {
-    throw "HOST_ACK timeout"
-}
-$response = $buffer.ToArray()
-$result = Assert-ResponseContract -Request $request -ResponseBytes $response
-[ordered]@{
-    status = $result.status
-    port = $Port
-    baud = $Baud
-    effective_timeout_ms = $effectiveTimeoutMs
-    request_hex = Convert-BytesToHex $request
-    request_opcode = $result.request_opcode
-    ack = $result.ack
-    frames = $result.frames
-} | ConvertTo-Json -Depth 6

+ 0 - 9
tools/package_templates/bootstrap.ps1

@@ -1,9 +0,0 @@
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-
-[ordered]@{
-    schema = "prod2u-p4-normal-v3-bootstrap-v2"
-    status = "pass"
-    powershell = $PSVersionTable.PSVersion.ToString()
-    dependencies = "inbox_only"
-} | ConvertTo-Json -Compress

+ 0 - 18
tools/package_templates/run.ps1

@@ -1,18 +0,0 @@
-param(
-    [Parameter(Mandatory = $true)]
-    [ValidateSet("selftest", "send-hex", "initialize-disable", "program-sram")]
-    [string]$Command,
-    [Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments
-)
-
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-$root = Split-Path -Parent $MyInvocation.MyCommand.Path
-$script = switch ($Command) {
-    "selftest" { "selftest.ps1" }
-    "send-hex" { "SEND_HEX.ps1" }
-    "initialize-disable" { "INITIALIZE_DISABLE.ps1" }
-    "program-sram" { "PROGRAM_SRAM.ps1" }
-}
-& powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $root $script) @Arguments
-exit $LASTEXITCODE

+ 0 - 294
tools/package_templates/selftest.ps1

@@ -1,294 +0,0 @@
-Set-StrictMode -Version Latest
-$ErrorActionPreference = "Stop"
-$root = Split-Path -Parent $MyInvocation.MyCommand.Path
-$expectedLayerNames = @(
-    "python", "icarus", "verilator", "cocotb", "formal",
-    "td_primary", "td_confirmation", "td_primary_artifacts",
-    "td_confirmation_artifacts", "td_confirmation_bitstream",
-    "td_confirmation_synthesis", "td_confirmation_manifest",
-    "resource_primary", "resource_confirmation", "package_selftest"
-)
-$verificationEvidenceLayers = @(
-    "python", "icarus", "verilator", "cocotb", "formal",
-    "td_primary", "td_confirmation", "td_primary_artifacts",
-    "td_confirmation_artifacts", "td_confirmation_bitstream",
-    "td_confirmation_synthesis", "td_confirmation_manifest",
-    "resource_primary", "resource_confirmation"
-)
-$required = @(
-    "fw.bit",
-    "package-info.json",
-    "evidence\td-primary-receipt.json",
-    "evidence\validation-summary.json",
-    "evidence\package-selftest-result.json",
-    "config\host-contract.json",
-    "config\prod2u_p4_normal_v3_hw_binding.json",
-    "config\prod2u_p4_verification_targets_v1.json",
-    "schemas\host-contract.schema.json",
-    "SEND_HEX.ps1",
-    "INITIALIZE_DISABLE.ps1",
-    "PROGRAM_SRAM.ps1",
-    "run.ps1",
-    "bootstrap.ps1",
-    "README.zh-CN.md"
-)
-foreach ($relative in $required) {
-    if (-not (Test-Path -LiteralPath (Join-Path $root $relative) -PathType Leaf)) {
-        throw "required file missing: $relative"
-    }
-}
-
-function Get-BoundSha256([string]$Path) {
-    return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant()
-}
-
-function Assert-ValidJson([string]$Relative) {
-    try {
-        Get-Content -LiteralPath (Join-Path $root $Relative) -Raw -Encoding UTF8 |
-            ConvertFrom-Json | Out-Null
-    } catch {
-        throw "$Relative is not valid JSON"
-    }
-}
-
-function Get-ValidationSummaryStatus([object]$Layers) {
-    $statuses = @($Layers.PSObject.Properties | ForEach-Object { [string]$_.Value.status })
-    if ($statuses -contains "fail") { return "fail" }
-    if ($statuses -contains "running") { return "running" }
-    if ($statuses -contains "not_run") { return "not_run" }
-    return "pass"
-}
-
-foreach ($relative in @(
-    "config\prod2u_p4_normal_v3_hw_binding.json",
-    "config\prod2u_p4_verification_targets_v1.json"
-)) {
-    Assert-ValidJson $relative
-}
-
-$info = Get-Content -LiteralPath (Join-Path $root "package-info.json") -Raw -Encoding UTF8 | ConvertFrom-Json
-if ([string]$info.schema -ne "prod2u-p4-normal-v3-folder-package-info-v3") {
-    throw "package-info schema mismatch"
-}
-$verificationRunId = [string]$info.verification_run_id
-if ($verificationRunId -notmatch '^[0-9a-f]{32}$') {
-    throw "package verification_run_id is invalid"
-}
-if ([string]$info.profile -ne "prod2u-p4-normal-actuator-binary921-v3") {
-    throw "package profile mismatch"
-}
-$deliveryMode = [string]$info.delivery_mode
-if (-not ($info.verification_complete -is [bool])) {
-    throw "package verification_complete must be boolean"
-}
-if (-not ($info.confirmation_td_present -is [bool])) {
-    throw "package confirmation_td_present must be boolean"
-}
-$verificationComplete = $info.verification_complete
-$confirmationTdPresent = $info.confirmation_td_present
-if ($deliveryMode -notin @("normal_dual_td", "urgent_single_td")) {
-    throw "package delivery mode is invalid"
-}
-if ($deliveryMode -eq "normal_dual_td") {
-    if (-not $confirmationTdPresent) {
-        throw "normal dual-TD package must contain a confirmation receipt"
-    }
-} else {
-    if ($verificationComplete -or $confirmationTdPresent) {
-        throw "urgent single-TD package completeness fields disagree"
-    }
-}
-$commit = [string]$info.commit
-if ($commit -cnotmatch '^[0-9a-f]{8}$') { throw "package commit is invalid" }
-$firmware = Join-Path $root "fw.bit"
-$bitstreamSha256 = Get-BoundSha256 $firmware
-if ([string]$info.bitstream_sha256 -ne $bitstreamSha256) {
-    throw "bitstream hash mismatch"
-}
-$expectedName = "prod2u-p4-normal-$commit-$($bitstreamSha256.Substring(0, 16))"
-$currentName = Split-Path -Leaf $root
-if ($currentName -ne $expectedName -and -not $currentName.StartsWith(".prod2u-p4-normal-stage-")) {
-    throw "package folder name mismatch"
-}
-if ((Split-Path -Leaf (Split-Path -Parent $root)) -ne $commit) {
-    throw "package commit parent folder mismatch"
-}
-
-$primaryReceipt = Join-Path $root "evidence\td-primary-receipt.json"
-$confirmationReceipt = Join-Path $root "evidence\td-confirmation-receipt.json"
-$validationSummary = Join-Path $root "evidence\validation-summary.json"
-$selftestResult = Join-Path $root "evidence\package-selftest-result.json"
-if ([string]$info.td_receipt_sha256 -ne (Get-BoundSha256 $primaryReceipt)) {
-    throw "primary TD receipt hash mismatch"
-}
-if ($confirmationTdPresent) {
-    if (-not (Test-Path -LiteralPath $confirmationReceipt -PathType Leaf)) {
-        throw "confirmation TD receipt is missing"
-    }
-    if ([string]$info.confirmation_td_receipt_sha256 -ne (Get-BoundSha256 $confirmationReceipt)) {
-        throw "confirmation TD receipt hash mismatch"
-    }
-} else {
-    if (Test-Path -LiteralPath $confirmationReceipt -PathType Leaf) {
-        throw "urgent single-TD package unexpectedly contains a confirmation receipt"
-    }
-    if ($null -ne $info.confirmation_td_receipt_sha256) {
-        throw "urgent single-TD confirmation receipt hash must be null"
-    }
-}
-if ([string]$info.validation_summary_sha256 -ne (Get-BoundSha256 $validationSummary)) {
-    throw "validation summary hash mismatch"
-}
-if ([string]$info.package_selftest_result_sha256 -ne (Get-BoundSha256 $selftestResult)) {
-    throw "package selftest result hash mismatch"
-}
-
-$primary = Get-Content -LiteralPath $primaryReceipt -Raw -Encoding UTF8 | ConvertFrom-Json
-if ([string]$primary.commit -ne $commit) { throw "primary TD receipt commit mismatch" }
-if ([string]$primary.verification_run_id -ne $verificationRunId) {
-    throw "primary TD receipt verification_run_id mismatch"
-}
-if ([string]$primary.bitstream_sha256 -ne $bitstreamSha256) {
-    throw "primary TD receipt bitstream mismatch"
-}
-if ([string]$info.synthesis_input_hash -ne [string]$primary.synthesis_input_hash) {
-    throw "primary synthesis input hash mismatch"
-}
-if ($confirmationTdPresent) {
-    $confirmation = Get-Content -LiteralPath $confirmationReceipt -Raw -Encoding UTF8 | ConvertFrom-Json
-    if ([string]$confirmation.commit -ne $commit) {
-        throw "confirmation TD receipt commit mismatch"
-    }
-    if ([string]$confirmation.verification_run_id -ne $verificationRunId) {
-        throw "confirmation TD receipt verification_run_id mismatch"
-    }
-    if ($null -ne $confirmation.bitstream_sha256 -and
-        [string]$confirmation.bitstream_sha256 -ne $bitstreamSha256) {
-        throw "confirmation TD receipt bitstream mismatch"
-    }
-    if ([string]$info.confirmation_synthesis_input_hash -ne [string]$confirmation.synthesis_input_hash) {
-        throw "confirmation synthesis input hash mismatch"
-    }
-    if ([string]$info.confirmation_bitstream_sha256 -ne [string]$confirmation.bitstream_sha256) {
-        throw "confirmation bitstream hash binding mismatch"
-    }
-    if ([string]$primary.run_id -cnotmatch '^[0-9a-f]{32}$' -or
-        [string]$confirmation.run_id -cnotmatch '^[0-9a-f]{32}$' -or
-        [string]$primary.run_id -eq [string]$confirmation.run_id) {
-        throw "Primary and confirmation TD run_id must differ"
-    }
-    if ([string]::IsNullOrWhiteSpace([string]$primary.work_root) -or
-        [string]::IsNullOrWhiteSpace([string]$confirmation.work_root) -or
-        [string]$primary.work_root -cnotmatch '^[A-Za-z]:[\\/]' -or
-        [string]$confirmation.work_root -cnotmatch '^[A-Za-z]:[\\/]' -or
-        [string]::Equals(
-            [System.IO.Path]::GetFullPath([string]$primary.work_root).TrimEnd('\'),
-            [System.IO.Path]::GetFullPath([string]$confirmation.work_root).TrimEnd('\'),
-            [System.StringComparison]::OrdinalIgnoreCase
-        )) {
-        throw "Primary and confirmation TD work_root must differ"
-    }
-} else {
-    if ($null -ne $info.confirmation_synthesis_input_hash -or
-        $null -ne $info.confirmation_bitstream_sha256) {
-        throw "urgent single-TD confirmation bindings must be null"
-    }
-}
-$validation = Get-Content -LiteralPath $validationSummary -Raw -Encoding UTF8 | ConvertFrom-Json
-if ([string]$validation.schema -ne "prod2u-p4-normal-v3-validation-summary-v1") {
-    throw "validation summary schema mismatch"
-}
-if ([string]$validation.verification_run_id -ne $verificationRunId) {
-    throw "validation summary verification_run_id mismatch"
-}
-if ([string]$validation.commit -ne $commit -or [string]$validation.bitstream_sha256 -ne $bitstreamSha256) {
-    throw "validation summary binding mismatch"
-}
-if ([string]$validation.delivery_mode -ne $deliveryMode -or
-    -not ($validation.verification_complete -is [bool]) -or
-    -not ($validation.confirmation_td_present -is [bool]) -or
-    $validation.verification_complete -ne $verificationComplete -or
-    $validation.confirmation_td_present -ne $confirmationTdPresent) {
-    throw "validation summary delivery fields mismatch"
-}
-$observedLayerNames = @($validation.layers.PSObject.Properties.Name | Sort-Object)
-$expectedSortedLayerNames = @($expectedLayerNames | Sort-Object)
-if (@(Compare-Object $expectedSortedLayerNames $observedLayerNames).Count -ne 0) {
-    throw "validation layer set mismatch"
-}
-foreach ($property in @($validation.layers.PSObject.Properties)) {
-    if ([string]$property.Value.status -notin @("pass", "fail", "running", "not_run")) {
-        throw "validation layer status is invalid: $($property.Name)"
-    }
-}
-if ($deliveryMode -eq "urgent_single_td") {
-    if ([string]$validation.layers.td_confirmation.status -notin @("not_run", "running")) {
-        throw "urgent td_confirmation must be not_run or running"
-    }
-    foreach ($name in @(
-        "td_confirmation_artifacts", "td_confirmation_bitstream",
-        "td_confirmation_synthesis", "td_confirmation_manifest",
-        "resource_confirmation"
-    )) {
-        if ([string]$validation.layers.$name.status -ne "not_run") {
-            throw "urgent confirmation layer must be not_run: $name"
-        }
-    }
-}
-$expectedVerificationComplete = $deliveryMode -eq "normal_dual_td"
-foreach ($name in $verificationEvidenceLayers) {
-    if ([string]$validation.layers.$name.status -ne "pass") {
-        $expectedVerificationComplete = $false
-    }
-}
-if ($verificationComplete -ne $expectedVerificationComplete) {
-    throw "verification_complete does not match validation evidence"
-}
-foreach ($source in @($validation.sources)) {
-    $relative = [string]$source.path
-    $sourcePath = Join-Path $root $relative
-    if (-not (Test-Path -LiteralPath $sourcePath -PathType Leaf)) {
-        throw "validation receipt is missing: $relative"
-    }
-    if ([string]$source.sha256 -ne (Get-BoundSha256 $sourcePath)) {
-        throw "validation receipt hash mismatch: $relative"
-    }
-    if ([string]$source.verification_run_id -ne $verificationRunId) {
-        throw "validation source verification_run_id mismatch: $relative"
-    }
-    $sourceReceipt = Get-Content -LiteralPath $sourcePath -Raw -Encoding UTF8 | ConvertFrom-Json
-    if ([string]$sourceReceipt.verification_run_id -ne $verificationRunId) {
-        throw "validation receipt verification_run_id mismatch: $relative"
-    }
-}
-
-$expectedFiles = @{}
-foreach ($property in @($info.file_sha256.PSObject.Properties)) {
-    $expectedFiles[[string]$property.Name] = [string]$property.Value
-}
-$observedFiles = @{}
-Get-ChildItem -LiteralPath $root -Recurse -File | ForEach-Object {
-    $relative = $_.FullName.Substring($root.Length).TrimStart('\').Replace('\', '/')
-    if ($relative -notin @("package-info.json", "evidence/package-selftest-result.json")) {
-        $observedFiles[$relative] = Get-BoundSha256 $_.FullName
-    }
-}
-if ($expectedFiles.Count -ne $observedFiles.Count) { throw "package file hash map is not closed" }
-foreach ($relative in $observedFiles.Keys) {
-    if (-not $expectedFiles.ContainsKey($relative)) { throw "package file is not bound: $relative" }
-    if ($expectedFiles[$relative] -ne $observedFiles[$relative]) {
-        throw "package file hash mismatch: $relative"
-    }
-}
-
-[ordered]@{
-    schema = "prod2u-p4-normal-v3-folder-selftest-v3"
-    status = "pass"
-    verification_run_id = $verificationRunId
-    commit = $commit
-    bitstream_sha256 = $bitstreamSha256
-    delivery_mode = $deliveryMode
-    verification_complete = $verificationComplete
-    confirmation_td_present = $confirmationTdPresent
-    validation_status = Get-ValidationSummaryStatus $validation.layers
-} | ConvertTo-Json -Compress

+ 13 - 20
tools/prod2u_p4_harness.py

@@ -3027,27 +3027,20 @@ def _emit(payload: Mapping[str, Any], args: argparse.Namespace, label: str) -> i
 
 
 def package_required_files(*, confirmation_td_present: bool = True) -> tuple[str, ...]:
-    required = (
-        "fw.bit",
-        "package-info.json",
-        "evidence/td-primary-receipt.json",
-        "evidence/validation-summary.json",
-        "evidence/package-selftest-result.json",
-        "config/host-contract.json",
-        "config/prod2u_p4_normal_v3_hw_binding.json",
-        "config/prod2u_p4_verification_targets_v1.json",
-        "schemas/host-contract.schema.json",
-        "bootstrap.ps1",
-        "selftest.ps1",
-        "run.ps1",
-        "SEND_HEX.ps1",
-        "INITIALIZE_DISABLE.ps1",
-        "PROGRAM_SRAM.ps1",
-        "README.zh-CN.md",
+    del confirmation_td_present
+    return (
+        "prod2u_p4_normal_v3.bit",
+        "project.json",
+        "package_manifest.json",
+        "project_config_sha256.txt",
+        "bitstream_sha256.txt",
+        "protocol.md",
+        "requirements.zh-CN.md",
+        "source_manifest.json",
+        "verification_targets.json",
+        "td_receipt.json",
+        "verification_summary.json",
     )
-    if confirmation_td_present:
-        return required + ("evidence/td-confirmation-receipt.json",)
-    return required
 
 
 def package_selftest_payload(