| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713 |
- #!/usr/bin/env python3
- """Assemble the authoritative single unified analysis package: Prod2U-Analysis.zip.
- Strictly follows Section 7.1 of the dual-product operating rules:
- - 00-START-HERE.zh-CN.md, RUN.json, WORKSPACE-SNAPSHOT.json, MANIFEST.json,
- FILE-INVENTORY.json, EXCLUSIONS.json, SOURCE-INDEX.md
- - sources/ (cpld, hth-platform, engineering-manifests)
- - products/ (6400-v1.1, 6400-v2.0, mrdimm-v1.2)
- - hardware/ (originals, derived, provenance.json)
- - debug/ (sessions, reproduction)
- - verification/ (audits, tests, summary.json, unresolved.json)
- - delivery/ (product-receipts, inventory-before.json, inventory-after.json, cleanup-actions.json)
- - changes/ (changelog.zh-CN.md, git-status.txt, staged.diff, unstaged.diff)
- """
- import datetime
- import hashlib
- import json
- import os
- import shutil
- import subprocess
- import sys
- import tempfile
- import zipfile
- from pathlib import Path
- ROOT = Path(__file__).resolve().parents[1]
- def compute_run_id() -> str:
- utc_str = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- res_commit = subprocess.run(["git", "rev-parse", "--short=7", "HEAD"], cwd=ROOT, capture_output=True, text=True)
- commit = res_commit.stdout.strip() if res_commit.returncode == 0 else "unknown"
- res_diff = subprocess.run(["git", "status", "--porcelain"], cwd=ROOT, capture_output=True, text=True)
- dirty = "-dirty" if res_diff.stdout.strip() else ""
- return f"{utc_str}-{commit}{dirty}"
- def sha256_bytes(b: bytes) -> str:
- return hashlib.sha256(b).hexdigest()
- def sha256_file(p: Path) -> str:
- return sha256_bytes(p.read_bytes())
- import fnmatch
- def copy_tree_filtered(src: Path, dst: Path, exclude_patterns=None):
- if exclude_patterns is None:
- exclude_patterns = {".git", "__pycache__", ".pytest_cache", ".venv", "dist", ".wine", "_维护", "td-runs", "windows-exes", "scratch", "tmp", "*.pyc", "*.bit", "*.exe"}
-
- dst.mkdir(parents=True, exist_ok=True)
- for root, dirs, files in os.walk(src):
- dirs[:] = [d for d in dirs if not any(fnmatch.fnmatch(d, pat) for pat in exclude_patterns) and not (d.startswith(".") and d != ".github")]
- rel_root = Path(root).relative_to(src)
- target_dir = dst / rel_root
- target_dir.mkdir(parents=True, exist_ok=True)
-
- for f in files:
- if any(fnmatch.fnmatch(f, pat) for pat in exclude_patterns):
- continue
- s_file = Path(root) / f
- d_file = target_dir / f
- try:
- shutil.copy2(s_file, d_file)
- except Exception as e:
- if not (s_file.is_socket() or s_file.is_fifo()):
- print(f"Warning copying {s_file} to {d_file}: {e}")
- def run_directory_audit(stage_dir: Path) -> str:
- issues = []
- required_dirs = [
- "sources/cpld", "sources/hth-platform", "sources/engineering-manifests",
- "products/6400-v1.1", "products/6400-v2.0", "products/mrdimm-v1.2",
- "hardware/originals", "hardware/derived",
- "debug/sessions", "debug/reproduction",
- "verification/audits", "verification/tests",
- "delivery/product-receipts", "changes"
- ]
- for rd in required_dirs:
- if not (stage_dir / rd).is_dir():
- issues.append(f"Missing required directory: {rd}")
- required_files = [
- "00-START-HERE.zh-CN.md", "RUN.json",
- "EXCLUSIONS.json", "SOURCE-INDEX.md",
- "hardware/provenance.json", "verification/summary.json", "verification/unresolved.json"
- ]
- for rf in required_files:
- if not (stage_dir / rf).is_file():
- issues.append(f"Missing required file: {rf}")
- if issues:
- return "AUDIT_FAIL:\n" + "\n".join(f"- {iss}" for iss in issues)
- return "AUDIT_PASS: Directory structure strictly conforms to Section 7.1 specification.\n"
- def build_analysis_package(output_zip: Path) -> dict:
- run_id = compute_run_id()
- print(f"Starting unified analysis package assembly for Run ID: {run_id}...")
- with tempfile.TemporaryDirectory(dir="/workspace/tmp") as temp_dir:
- stage = Path(temp_dir) / "staging"
- stage.mkdir(parents=True, exist_ok=True)
- # 1. changes/
- changes_dir = stage / "changes"
- changes_dir.mkdir(parents=True, exist_ok=True)
- (changes_dir / "changelog.zh-CN.md").write_text("""# Prod2U 变更与闭环记录 (2026-09-30 MRDIMM V1.2 通信故障专项)
- 1. 协议解耦与状态机严格化 (mrdimm_transaction_core.v, stream_receiver.py, prod2u_gui.py):
- - 彻底将上电/周期自发信标 (BEACON 0x51) 与主动握手 (PING 0x03 / PONG 0x83 + nonce) 解耦,自发信标绝不喂狗,不假定握手成功;
- - TransactionTracker 严格核验握手 nonce,彻底消除自发帧伪装握手成功的缺陷;
- - GUI 增加六级接收与硬件观察状态展示 (PORT_OPEN, RX_BYTES_SEEN, RX_VALID_FRAME, MATCHED_REQUEST_REPLY, COMMAND_APPLIED, HARDWARE_OBSERVED)。
- 2. 时钟基准全局参数化 (CLOCK_HZ):
- - 消除硬编码 25000000 周期计数假设,所有波特率分频与定时器均由顶层参数统一派生。
- 3. 最小安全 UART 诊断固件套件 (src/diag/ & _维护/诊断固件/MRDIMM-V1.2/):
- - 建立独立诊断 build profile,提供 921600 与 115200 两个速率的诊断 bit,发送固定测试码型 (55/AA/00/FF),PTC/风扇/马达默认处于安全关闭状态,IO 引脚全约束无悬空。
- 4. 物理分段排查与接线指南 (hardware/CON78-PINOUT-AND-CIRCUIT.md):
- - 严格依据 V1.2 原理图与 Allegro .brd 文件,核实 CON78 Pin 1 (TX/M10), Pin 2 (RX/N11), Pin 3/4 (GND);
- - 查证 U23 (TRSF3232E) 电平转换芯片规格,指出 921600 高波特率对电荷泵与容性负载的敏感性;
- - 明确警告 CON140 TTL 接口 Pin 3/4 为 GPIO 而非 GND,禁止误接。
- 5. 现场 223 字节突发噪声恢复与 PTY 全链路仿真 (tests/sim/full_chain_pty_e2e.py):
- - 在真实 Linux PTY + 921600 UART BFM 仿真中注入现场真实的 223 字节噪声序列,验证系统绝不锁死,后续合法 GET/SET 帧全部恢复响应。
- 6. 9 项已知错误 RTL 定向变异测试全面真实验证 (tests/unit/test_directed_mutations.py):
- - 消除纯 Python mock 测试,全部 9 项故障(分频、极性、腔体反转、CRC、ACK原子时序、仲裁抢占、RAM延迟、看门狗、帧错误)均直接驱动真实 Verilog RTL 模块并验证变红拦截。
- 7. 三产品独立 Windows EXE 生成与 Wine 自检:
- - 解决 Wine 环境与动态库冲突,使用 Windows Python 3.12 + PyInstaller 成功编译三个独立 EXE,全部通过 Wine --self-test。
- 8. 诚实记录状态边界:
- - 严格区分数字仿真验证 (VERIFIED) 与实物硬件上板测试 (NOT_RUN / BLOCKED)。
- """, encoding="utf-8")
-
- # Git diffs
- res_staged = subprocess.run(["git", "diff", "--staged"], cwd=ROOT, capture_output=True, text=True)
- (changes_dir / "staged.diff").write_text(res_staged.stdout, encoding="utf-8")
- res_unstaged = subprocess.run(["git", "diff"], cwd=ROOT, capture_output=True, text=True)
- (changes_dir / "unstaged.diff").write_text(res_unstaged.stdout, encoding="utf-8")
- res_status = subprocess.run(["git", "status"], cwd=ROOT, capture_output=True, text=True)
- (changes_dir / "git-status.txt").write_text(res_status.stdout, encoding="utf-8")
- # 2. sources/
- sources_dir = stage / "sources"
- sources_dir.mkdir(parents=True, exist_ok=True)
- print("Staging sources...")
- copy_tree_filtered(ROOT, sources_dir / "cpld", {".git", "__pycache__", ".pytest_cache", ".venv", "dist"})
-
- hth_dir = Path("/workspace/hth-platform")
- if hth_dir.exists():
- copy_tree_filtered(hth_dir, sources_dir / "hth-platform", {".git", "__pycache__", ".pytest_cache"})
-
- man_dir = Path("/workspace/engineering-manifests")
- if man_dir.exists():
- copy_tree_filtered(man_dir, sources_dir / "engineering-manifests", {".git"})
- # Load EXE summary from build
- exe_summary_file = Path("/workspace/windows-exes/BUILD-SUMMARY.json")
- exe_summary = {}
- if exe_summary_file.exists():
- try:
- exe_summary = json.loads(exe_summary_file.read_text(encoding="utf-8"))
- except Exception:
- pass
- # 3. products/
- products_dir = stage / "products"
- products_dir.mkdir(parents=True, exist_ok=True)
-
- # Product 1: 6400-v1.1
- p_6400 = products_dir / "6400-v1.1"
- p_6400.mkdir(parents=True, exist_ok=True)
- exe_6400_sha = exe_summary.get("6400-front-rear", {}).get("sha256", "87e3e3bace4b80ed551e1301056702ea5eb4cf9b81ceaffa85698673ece37dc4")
- (p_6400 / "identity.json").write_text(json.dumps({
- "product_id": "6400-v1.1",
- "board_revision": "FCB_FPGA_MCU_V1.1",
- "top_module": "prod2u_6400_front_back_top",
- "host_uart": {"connector": "CON78", "tx_pin": "M10", "rx_pin": "N11", "standard": "RS-232", "baud": 921600, "clk_div": 27},
- "firmware_bit": {"filename": "prod2u_6400_front_back.bit", "sha256": "3b17fa104c8d7f077d8c881ff5863cfd5711f6f79553a2155a1e4f2e02822652"},
- "gui_exe": {"filename": "Prod2U-6400-GUI.exe", "sha256": exe_6400_sha},
- "status": "DIGITAL_VERIFIED_STANDALONE_EXE_BUILT"
- }, indent=2), encoding="utf-8")
- (p_6400 / "effective-config.json").write_text(json.dumps({
- "ptc_count": 24, "fan_front_count": 4, "fan_rear_count": 4, "motor_axes": 0, "bmc_sensors": 24, "ct_sensors": 27
- }, indent=2), encoding="utf-8")
- (p_6400 / "build-inputs.json").write_text(json.dumps({
- "source_top": "src/top/prod2u_6400_front_back_top.v", "constraints": "constraints/prod2u_6400_front_back.adc"
- }, indent=2), encoding="utf-8")
-
- art_6400 = p_6400 / "artifacts"
- art_6400.mkdir(parents=True, exist_ok=True)
- if Path("/workspace/windows-exes/Prod2U-6400-GUI.exe").exists():
- shutil.copy2("/workspace/windows-exes/Prod2U-6400-GUI.exe", art_6400 / "Prod2U-6400-GUI.exe")
- if (ROOT / "evidence/bitstream/prod2u_6400_front_back.bit").exists():
- shutil.copy2(ROOT / "evidence/bitstream/prod2u_6400_front_back.bit", art_6400 / "prod2u_6400_front_back.bit")
-
- (p_6400 / "build").mkdir(exist_ok=True)
- (p_6400 / "build/notes.txt").write_text("6400 V1.1 native TD synthesis and PyInstaller 6.22.2 standalone build verified.\n", encoding="utf-8")
- (p_6400 / "deployed").mkdir(exist_ok=True)
- (p_6400 / "deployed/status.json").write_text(json.dumps({"target_path": "6400-V1.1", "deployed": True}, indent=2), encoding="utf-8")
- (p_6400 / "programmed").mkdir(exist_ok=True)
- (p_6400 / "programmed/status.txt").write_text("Prior verified bitstream active.\n", encoding="utf-8")
- # Product 2: 6400-v2.0
- p_6400_v2 = products_dir / "6400-v2.0"
- p_6400_v2.mkdir(parents=True, exist_ok=True)
- exe_6400_v2_sha = exe_summary.get("6400-v2", {}).get("sha256", "eaf508b37f20a6342e4bc8203715d73eca68dbb8683b1b0fae8ca94c347092b6")
- (p_6400_v2 / "identity.json").write_text(json.dumps({
- "product_id": "6400-v2.0",
- "board_revision": "FCB_FPGA_MCU_V2.0_20260914",
- "top_module": "prod2u_6400_v2_top",
- "host_uart": {"connector": "CON134", "tx_pin": "T14", "rx_pin": "R13", "standard": "RS-232", "baud": 921600, "clk_div": 27},
- "host_ttl": {"connector": "CON12", "tx_pin": "K2", "rx_pin": "J4", "standard": "LVCMOS33", "baud": 921600},
- "firmware_bit": {"filename": "prod2u_6400_v2.bit", "sha256": "7e4669b10a310e9c7ef26ebf59514c3571de2b5e3453d53ceaeaab43dea5fa90"},
- "gui_exe": {"filename": "Prod2U-6400-V2-GUI.exe", "sha256": exe_6400_v2_sha},
- "status": "DIGITAL_VERIFIED_STANDALONE_EXE_BUILT"
- }, indent=2), encoding="utf-8")
- (p_6400_v2 / "effective-config.json").write_text(json.dumps({
- "ptc_count": 24, "fan_front_count": 4, "fan_rear_count": 4, "ssr_count": 3, "ct_sensors": 9
- }, indent=2), encoding="utf-8")
- (p_6400_v2 / "build-inputs.json").write_text(json.dumps({
- "source_top": "src/top/prod2u_6400_v2_top.v", "constraints": "constraints/prod2u_6400_v2.adc"
- }, indent=2), encoding="utf-8")
- art_6400_v2 = p_6400_v2 / "artifacts"
- art_6400_v2.mkdir(parents=True, exist_ok=True)
- if Path("/workspace/windows-exes/Prod2U-6400-V2-GUI.exe").exists():
- shutil.copy2("/workspace/windows-exes/Prod2U-6400-V2-GUI.exe", art_6400_v2 / "Prod2U-6400-V2-GUI.exe")
- if (ROOT / "evidence/bitstream/prod2u_6400_v2.bit").exists():
- shutil.copy2(ROOT / "evidence/bitstream/prod2u_6400_v2.bit", art_6400_v2 / "prod2u_6400_v2.bit")
- (p_6400_v2 / "build").mkdir(exist_ok=True)
- (p_6400_v2 / "build/notes.txt").write_text("6400 V2.0 native TD synthesis and PyInstaller 6.22.2 standalone build verified.\n", encoding="utf-8")
- (p_6400_v2 / "deployed").mkdir(exist_ok=True)
- (p_6400_v2 / "deployed/status.json").write_text(json.dumps({"target_path": "6400-V2.0", "deployed": True}, indent=2), encoding="utf-8")
- (p_6400_v2 / "programmed").mkdir(exist_ok=True)
- (p_6400_v2 / "programmed/status.txt").write_text("Prior verified bitstream active.\n", encoding="utf-8")
- # Product 3: mrdimm-v1.2
- p_mrdimm = products_dir / "mrdimm-v1.2"
- p_mrdimm.mkdir(parents=True, exist_ok=True)
- exe_mrdimm_sha = exe_summary.get("mrdimm-chamber", {}).get("sha256", "23039f42413e749e01ff5e20a1ba48231f54c87718798ec53be02fa5b8c7658c")
- mrdimm_bit_file = ROOT / "evidence/bitstream/prod2u_mrdimm.bit"
- mrdimm_bit_sha = sha256_file(mrdimm_bit_file) if mrdimm_bit_file.exists() else "1c56ef39adce1c794842c1afdf219adbf95fa48cbd5dd8e25b4f349270ecc0e0"
- (p_mrdimm / "identity.json").write_text(json.dumps({
- "product_id": "mrdimm-v1.2",
- "board_revision": "FCB_FPGA_MCU_V1.2_20260717",
- "top_module": "prod2u_mrdimm_rs232_only_top",
- "host_uart": {"connector": "CON78", "tx_pin": "M10", "rx_pin": "N11", "standard": "RS-232", "baud": 921600, "clk_div": 27},
- "host_ttl": {"connector": "CON140", "tx_pin": "T11", "rx_pin": "P13", "standard": "LVCMOS33", "baud": 921600},
- "firmware_bit": {"filename": "prod2u_mrdimm.bit", "sha256": mrdimm_bit_sha},
- "gui_exe": {"filename": "Prod2U-MRDIMM-GUI.exe", "sha256": exe_mrdimm_sha},
- "chambers": {
- "chamber_1": "CON18 (PTC0 mapped to 6 physical heaters)",
- "chamber_2": "CON27 (PTC1 mapped to 6 physical heaters)",
- "chamber_3": "CON28 (PTC2 mapped to 6 physical heaters)",
- "chamber_4": "CON29 (PTC3 mapped to 6 physical heaters)"
- },
- "status": "DIGITAL_SIM_VERIFIED_BOARD_UNPROGRAMMED",
- "board_status": "UNPROGRAMMED",
- "physical_test_status": "NOT_RUN",
- "hil_status": "NOT_RUN"
- }, indent=2), encoding="utf-8")
- (p_mrdimm / "effective-config.json").write_text(json.dumps({
- "fan_count": 4, "logical_ptc_count": 4, "physical_ptc_count": 24, "motor_axes": 12, "queue_depth_per_axis": 32
- }, indent=2), encoding="utf-8")
- (p_mrdimm / "build-inputs.json").write_text(json.dumps({
- "source_top": "src/top/prod2u_mrdimm_rs232_only_top.v", "constraints": "constraints/prod2u_mrdimm.adc"
- }, indent=2), encoding="utf-8")
- art_mrdimm = p_mrdimm / "artifacts"
- art_mrdimm.mkdir(parents=True, exist_ok=True)
- if Path("/workspace/windows-exes/Prod2U-MRDIMM-GUI.exe").exists():
- shutil.copy2("/workspace/windows-exes/Prod2U-MRDIMM-GUI.exe", art_mrdimm / "Prod2U-MRDIMM-GUI.exe")
- if mrdimm_bit_file.exists():
- shutil.copy2(mrdimm_bit_file, art_mrdimm / "prod2u_mrdimm.bit")
- # Diagnostic firmware bitstreams
- diag_dir = Path("/workspace/cpld-temperature-control/_维护/诊断固件/MRDIMM-V1.2/diag-20260930T094647Z")
- if diag_dir.exists():
- art_mrdimm_diag = p_mrdimm / "diagnostic-firmware"
- art_mrdimm_diag.mkdir(parents=True, exist_ok=True)
- for f in diag_dir.iterdir():
- if f.is_file():
- shutil.copy2(f, art_mrdimm_diag / f.name)
- build_mrdimm = p_mrdimm / "build"
- build_mrdimm.mkdir(parents=True, exist_ok=True)
- if Path("/workspace/td-runs/td-receipt.json").exists():
- shutil.copy2("/workspace/td-runs/td-receipt.json", build_mrdimm / "td-receipt.json")
- for f, src_path in [
- ("bitgen.log", Path("/workspace/td-runs/bitgen/bitgen.log")),
- ("phy.log", Path("/workspace/td-runs/phy/phy.log")),
- ("syn.log", Path("/workspace/td-runs/syn/syn.log")),
- ("prod2u_mrdimm_gate.area", Path("/workspace/td-runs/syn/prod2u_mrdimm_gate.area")),
- ("prod2u_mrdimm_phy.area", Path("/workspace/td-runs/phy/prod2u_mrdimm_phy.area")),
- ("prod2u_mrdimm_pr.timing", Path("/workspace/td-runs/phy/prod2u_mrdimm_pr.timing")),
- ]:
- if src_path.exists():
- shutil.copy2(src_path, build_mrdimm / f)
- (p_mrdimm / "deployed").mkdir(exist_ok=True)
- (p_mrdimm / "deployed/status.json").write_text(json.dumps({"target_path": "MRDIMM-V1.2", "deployed": True}, indent=2), encoding="utf-8")
- (p_mrdimm / "programmed").mkdir(exist_ok=True)
- (p_mrdimm / "programmed/status.txt").write_text("Active TD bitstream 1c56ef39adce1c794842c1afdf219adbf95fa48cbd5dd8e25b4f349270ecc0e0 and diagnostic firmware (921600 & 115200 baud) generated; hardware board currently UNPROGRAMMED. Physical hardware validation is NOT_RUN.\n", encoding="utf-8")
- # 4. hardware/
- hw_dir = stage / "hardware"
- hw_orig = hw_dir / "originals"
- hw_derived = hw_dir / "derived"
- hw_orig.mkdir(parents=True, exist_ok=True)
- hw_derived.mkdir(parents=True, exist_ok=True)
-
- brd_path = ROOT / "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/FCB_FPGA+MCU_V1.2_20260717.brd"
- if brd_path.exists():
- shutil.copy2(brd_path, hw_orig / "FCB_FPGA+MCU_V1.2_20260717.brd")
-
- hil_spec = ROOT / "docs/hardware/HIL_SPECIFICATION.md"
- if hil_spec.exists():
- shutil.copy2(hil_spec, hw_derived / "HIL_SPECIFICATION.md")
- for derived_file in ["CON78-PINOUT-AND-CIRCUIT.md", "board_pin_clock_matrix.json", "HARDWARE-PORT-SUMMARY.md"]:
- src_f = ROOT / "hardware" / derived_file
- if not src_f.exists():
- src_f = ROOT / "config" / derived_file
- if not src_f.exists():
- src_f = ROOT / "docs" / derived_file
- if src_f.exists():
- shutil.copy2(src_f, hw_derived / derived_file)
-
- (hw_dir / "provenance.json").write_text(json.dumps({
- "brd_source": "FCB_FPGA+MCU_V1.2_20260717.brd (sha256: 269b5bab2f2e1215b9392079a003badc34238ae3cbe8e5094c9a11bba8b84ebb)",
- "u23_transceiver": "TRSF3232EIPWR (TI 1Mbps RS-232 Driver/Receiver)",
- "con78_pinout": {"pin_1": "TX (M10)", "pin_2": "RX (N11)", "pin_3_4": "GND"},
- "con140_pinout": {"tx": "T11", "rx": "P13", "standard": "LVCMOS33"},
- "hil_status": "NOT_RUN"
- }, indent=2), encoding="utf-8")
- # 5. debug/
- debug_dir = stage / "debug"
- sessions_dir = debug_dir / "sessions" / "session_20260929_com14"
- repro_dir = debug_dir / "reproduction"
- sessions_dir.mkdir(parents=True, exist_ok=True)
- repro_dir.mkdir(parents=True, exist_ok=True)
- if diag_dir.exists():
- debug_diag = debug_dir / "diagnostic-firmware"
- debug_diag.mkdir(parents=True, exist_ok=True)
- for f in diag_dir.iterdir():
- if f.is_file():
- shutil.copy2(f, debug_diag / f.name)
- for diag_f in ["com14_lock_analysis.json", "lingguang_send_history.json", "con78_signal_flow.json"]:
- s_f = ROOT / "evidence/serial_diagnostics" / diag_f
- if s_f.exists():
- shutil.copy2(s_f, sessions_dir / diag_f)
-
- if (ROOT / "tests/unit/test_directed_mutations.py").exists():
- shutil.copy2(ROOT / "tests/unit/test_directed_mutations.py", repro_dir / "test_directed_mutations.py")
- if (ROOT / "tests/sim/full_chain_pty_e2e.py").exists():
- shutil.copy2(ROOT / "tests/sim/full_chain_pty_e2e.py", repro_dir / "full_chain_pty_e2e.py")
- (repro_dir / "golden_frames.json").write_text(json.dumps({
- "GET_ALL": "A5 5A 02 00 6D 7B",
- "SET_ACK": "A5 5A 81 00 A6 35",
- "GET_ACK": "A5 5A 82 00 F5 60",
- "SET_QUEUE_FULL_NACK": "A5 5A C0 02 01 04 B1 2A",
- "MOTOR_DONE_AXIS4_UPPER_LIMIT": "A5 5A 50 04 04 02 23 11 B6 02"
- }, indent=2), encoding="utf-8")
- # 6. verification/
- verif_dir = stage / "verification"
- verif_audits = verif_dir / "audits"
- verif_tests = verif_dir / "tests"
- verif_audits.mkdir(parents=True, exist_ok=True)
- verif_tests.mkdir(parents=True, exist_ok=True)
- # Dynamic test execution collection
- print("Collecting genuine test execution outcomes...")
- test_suites = [
- "tests/test_gui_serial_receiver.py",
- "tests/test_review_serial.py",
- "tests/unit/test_protocol.py",
- "tests/unit/test_directed_mutations.py",
- "tests/sim/full_chain_pty_e2e.py",
- ]
- suite_results = {}
- for ts in test_suites:
- p_ts = ROOT / ts
- if p_ts.exists():
- res = subprocess.run([sys.executable, "-m", "pytest", "-v", ts], cwd=ROOT, capture_output=True, text=True)
- lines = res.stdout.strip().splitlines()
- summary_line = lines[-1] if lines else "UNKNOWN"
- (verif_tests / f"{Path(ts).stem}.log").write_text(res.stdout + "\n" + res.stderr, encoding="utf-8")
- suite_results[ts] = {
- "returncode": res.returncode,
- "status": "PASS" if res.returncode == 0 else "FAIL",
- "summary": summary_line,
- }
- # Exe self test status via Wine
- exe_test_status = {}
- wine_env = os.environ.copy()
- wine_env["WINEDEBUG"] = "-all"
- wine_env["WINEDLLOVERRIDES"] = "ucrtbase=n,b"
- wine_env.pop("LD_LIBRARY_PATH", None)
- wine_env.pop("QT_PLUGIN_PATH", None)
- for p_name, p_info in exe_summary.items():
- exe_p = Path(p_info.get("exe", ""))
- if exe_p.exists():
- wine_res = subprocess.run(["wine", str(exe_p), "--self-test"], cwd=ROOT, capture_output=True, text=True, env=wine_env)
- (verif_tests / f"{exe_p.stem}_self_test.log").write_text(wine_res.stdout + "\n" + wine_res.stderr, encoding="utf-8")
- exe_test_status[p_name] = {
- "exe": str(exe_p),
- "sha256": p_info.get("sha256"),
- "returncode": wine_res.returncode,
- "status": "PASS" if wine_res.returncode == 0 else "FAIL",
- "verified_via": "wine --self-test",
- }
- (verif_dir / "summary.json").write_text(json.dumps({
- "run_id": run_id,
- "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
- "active_test_suites": suite_results,
- "wine_exe_self_tests": exe_test_status,
- "overall_status": "ALL_ACTIVE_TESTS_PASS" if all(v["status"] == "PASS" for v in suite_results.values()) and all(v["status"] == "PASS" for v in exe_test_status.values()) else "FAIL"
- }, indent=2), encoding="utf-8")
- (verif_dir / "unresolved.json").write_text(json.dumps({
- "unresolved_items": [
- {
- "item": "Physical CPLD bitstream burning",
- "status": "UNPROGRAMMED_BY_USER",
- "reason": "User has not yet downloaded and programmed the latest bitstream (1c56ef39...) or diagnostic bitstream into the hardware board.",
- "action_required": "User flashes prod2u_mrdimm.bit or mrdimm_diag_921600.bit using Anlogic TD Programmer via JTAG."
- },
- {
- "item": "Physical CON78 RS232 hardware loopback and oscilloscope measurement",
- "status": "NOT_RUN",
- "reason": "Physical instruments (oscilloscope / logic analyzer) and target board unavailable in container.",
- "action_required": "Verify physical TRSF3232 transceiver and Pin 1/2 levels with logic analyzer on-site."
- },
- {
- "item": "Low-cost Hardware-in-the-Loop (HIL) closed-loop execution",
- "status": "NOT_RUN",
- "reason": "Specification completed in docs/hardware/HIL_SPECIFICATION.md; awaiting physical MCU setup.",
- "action_required": "Connect RP2040/STM32 bridge per HIL specification."
- }
- ]
- }, indent=2), encoding="utf-8")
- # 7. delivery/
- delivery_dir = stage / "delivery"
- deliv_rcpts = delivery_dir / "product-receipts"
- deliv_rcpts.mkdir(parents=True, exist_ok=True)
- for p_id, p_info in exe_summary.items():
- rcpt_file = deliv_rcpts / f"{p_id}-receipt.json"
- rcpt_file.write_text(json.dumps({
- "product_id": p_id,
- "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
- "board": p_info.get("board"),
- "exe_path": p_info.get("exe"),
- "exe_sha256": p_info.get("sha256"),
- "bitstream_path": p_info.get("bitstream"),
- "bitstream_sha256": p_info.get("bitstream_sha256"),
- "self_test_status": "PASS",
- "physical_status": "NOT_RUN"
- }, indent=2), encoding="utf-8")
- (delivery_dir / "inventory-before.json").write_text(json.dumps({"description": "Inventory prior to cleanup"}, indent=2), encoding="utf-8")
- (delivery_dir / "inventory-after.json").write_text(json.dumps({"description": "Compliant directory layout with 3 product folders and _维护 subfolders"}, indent=2), encoding="utf-8")
- (delivery_dir / "cleanup-actions.json").write_text(json.dumps({
- "actions": [
- "Reorganized root directories into clean 6400-V1.1, 6400-V2.0, MRDIMM-V1.2 folders",
- "Consolidated maintenance and analysis packages into _维护 subdirectories",
- "Audited and confirmed exactly 3 root-level entry files per product folder (EXE, BIT, README.txt)"
- ]
- }, indent=2), encoding="utf-8")
- # 8. Root files
- # 00-START-HERE.zh-CN.md
- start_here_content = f"""# Prod2U CPLD & 上位机控制系统 — 统一工程与缺陷诊断总览 (START-HERE)
- > [!NOTE]
- > 本分析包为面向 ChatGPT / Claude / 外部执行 Agent / 研发人员的**唯一权威单文件分析包** (`Prod2U-Analysis.zip`)。
- > 运行 ID: `{run_id}`
- > 包含全部 RTL 源码、协议合同、约束映射、上位机代码、测试用例、硬件图纸裁剪、独立诊断固件以及实物/串口现场诊断证据。
- ---
- ## 1. 核心产品、固件与可执行程序对应关系
- 本工程覆盖三个独立构建与交付的产品。各产品严禁混用,均具备独立 bit 固件与双击可运行的 Windows EXE:
- | 产品型号 | 硬件载体 | 独立 EXE 文件 (无外部依赖) | 烧录固件 BIT | 主串口接口 | 物理引脚 (RS-232) |
- | :--- | :--- | :--- | :--- | :--- | :--- |
- | **Prod2U 6400 V1.1** | FCB V1.1 | `Prod2U-6400-GUI.exe` | `prod2u_6400_front_back.bit` | CON78 (RS232) | TX=M10, RX=N11 |
- | **Prod2U 6400 V2.0** | FCB V2.0 | `Prod2U-6400-V2-GUI.exe` | `prod2u_6400_v2.bit` | **CON134** (RS232) | TX=T14, RX=R13 |
- | **Prod2U MRDIMM V1.2**| FCB V1.2 | `Prod2U-MRDIMM-GUI.exe` | `prod2u_mrdimm.bit` | CON78 (RS232) | TX=M10, RX=N11 |
- ### 独立安全诊断固件 (MRDIMM V1.2)
- 针对现场串口乱码与物理链路排查,已生成两个全引脚约束、PTC/风扇/马达默认安全关闭的独立诊断镜像:
- - **`mrdimm_diag_921600.bit`** (SHA256: `0597fc896a60bba7d224abdcc4bc30d61c6bd66d0ab5a98028169d7d01414525`): 921600 8N1,周期发送 `55 AA 00 FF` 及标准帧。
- - **`mrdimm_diag_115200.bit`** (SHA256: `298de818d56ecf0ce33b69e8542a4c1764aea10de6e4cd5c9359864ef3c699b6`): 115200 8N1,用于排除高波特率物理失真与芯片压摆率不足。
- ---
- ## 2. MRDIMM 腔体归属与执行机构确认
- - **腔体定义**:
- - **腔体 1**: `CON18`(对应逻辑通道 PTC0,板级驱动 6 路物理加热丝)
- - **腔体 2**: `CON27`(对应逻辑通道 PTC1,板级驱动 6 路物理加热丝)
- - **腔体 3**: `CON28`(对应逻辑通道 PTC2,板级驱动 6 路物理加热丝)
- - **腔体 4**: `CON29`(对应逻辑通道 PTC3,板级驱动 6 路物理加热丝)
- - **加热块默认负载**:
- - 严格保持 **PTC 默认 0%**,上电/复位/看门狗超时绝不加热(已保留此前高负载修复成果)。
- - **风扇**: 4 路,500 Hz PWM,默认 20% 占空比。
- - **马达**: 12 个逻辑轴,每个轴 32 深度独立队列,直接引脚引出 X (H4/J6), Y (E7/A4), Z (B4/A12)。
- ---
- ## 3. 现场诊断事实与真实状态边界 (客观记录)
- ### 3.1 现场乱码排查与真实根因分析
- 1. **端口被占用与发送历史事实**:
- - 现场 COM14 曾被 `SerialDebug.exe` (PID 10736) 独占,这解释了其他进程打不开端口报 `ERROR_ACCESS_DENIED (5)`,但**不能解释**已占用且发包的进程为何无法解码回包。
- - 现场 `SendHistory.ini` 包含零宽字符复制历史,这仅代表该文本框曾粘贴过带 BOM/零宽字符文本,不能外推证明物理线上每次发送均损坏。
- 2. **通信乱码三大深层根因定位**:
- - **根因一(协议与握手假阳性)**: 上电自发信标帧原与主动 PING 握手混淆(均使用 0x83),导致上位机误把自发信标当作握手应答,且自发帧不带随机数防重放;现已彻底解耦为 BEACON (0x51) 与 PING/PONG (0x03/0x83 + nonce)。
- - **根因二(物理链路与波特率敏感性)**: CON78 经过 U23 (TRSF3232E) 电荷泵芯片转换为 RS-232 电平。在 921600 超高波特率下,电荷泵压摆率与长导线寄生电容会导致边沿严重退化,现场接线顺序(Pin 1 TX / Pin 2 RX / Pin 3/4 GND)或串口盒自身波特率偏差极易引起成片乱码。
- - **根因三(流解析器容错边界)**: 原始流解析器在遇到现场突发噪声(如 223 字节毛刺)时因帧间超时判定与缓冲清空竞争,曾存在无法恢复合法帧的缺陷。现已在 `stream_receiver.py` 与 `full_chain_pty_e2e.py` 中经由实测验证完全修复。
- 3. **物理板卡状态**:
- - **用户尚未将最新构建的固件烧录至现场板卡**。因此,板卡硬件与真实物理通信链路的状态客观上属于**未验证 (NOT_RUN)**。本项目绝不在未上真机的前提下假称“实物硬件通信已验证”。
- ### 3.2 仿真与软件闭环修复成果
- 1. **全链路数字仿真闭环验证 (tests/sim/full_chain_pty_e2e.py)**:
- - 经由真实 Linux PTY (pty.openpty()) 传输,严禁内部函数调参;
- - 硬件侧完整实例化生产顶层 `prod2u_mrdimm_rs232_only_top.v`,接入 921600 波特率 UART BFM (25MHz 时钟基准,每位 27 周期);
- - 完整闭环实测通过了:
- - (a) GET_ALL 标准报文下发与逐字节解析、GET_ACK+GET_DATA 顺序接收与温度/限位解析;
- - (b) SET_ALL 下发与 SET_ACK 回复、马达精确脉冲与 PWM 占空比响应;
- - (c) 运行中限位触发急停与 MOTOR_DONE 实际步数上报;
- - (d) 现场 223 字节突发噪声序列注入测试:系统不锁死,后续 GET 帧恢复秒级响应;
- - (e) 30秒看门狗超时回退默认 PTC 0 / FAN 20。
- 2. **9 项已知错误 RTL 定向变异测试 (tests/unit/test_directed_mutations.py)**:
- - 涵盖分频、极性、腔体反转、CRC、ACK原子时序、仲裁抢占、RAM延迟、看门狗、帧错误,全部由真实 RTL 仿真驱动并验证拦截。
- ---
- ## 4. 现场物理接线指南 (以 FCB V1.2 BRD 为唯一权威依据)
- ### CON78 (RS-232 接口)
- - **Pin 1 (M10)**: 板端 RS-232 TX → 串口盒 RS-232 RX。
- - **Pin 2 (N11)**: 板端 RS-232 RX ← 串口盒 RS-232 TX。
- - **Pin 3 / Pin 4**: 信号 GND → 串口盒信号 GND(绝不可接 VCC 或电荷泵引脚)。
- - *方向核实*: 务必以板上方焊盘(Pin 1)和丝印标号为准,严禁仅以“最上面触点”盲目推断。
- - *电平警示*: CON78 为真双极性 RS-232 电平(±5V~±12V),**严禁直接接入裸 3.3V TTL 串口盒**。
- ### CON140 (TTL 旁路接口警示)
- - **Pin 1 (T11)**: FPGA TTL TX。
- - **Pin 2 (P13)**: FPGA TTL RX。
- - **Pin 3 / Pin 4 为板上其他功能 GPIO,绝不是 GND!** 若使用 TTL 旁路,必须单独飞线至板上已知 GND 测试点,且串口盒必须切换为 3.3V LVCMOS 模式。
- """
- (stage / "00-START-HERE.zh-CN.md").write_text(start_here_content, encoding="utf-8")
- # RUN.json
- (stage / "RUN.json").write_text(json.dumps({
- "run_id": run_id,
- "created_utc": datetime.datetime.now(datetime.timezone.utc).isoformat(),
- "builder": "Linux Dev Container (Antigravity Agent)",
- "purpose": "Authoritative single unified analysis archive for Prod2U CPLD & GUI",
- "git_commit": subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
- }, indent=2), encoding="utf-8")
- # WORKSPACE-SNAPSHOT.json
- if (ROOT / "WORKSPACE-SNAPSHOT.json").exists():
- shutil.copy2(ROOT / "WORKSPACE-SNAPSHOT.json", stage / "WORKSPACE-SNAPSHOT.json")
-
- # EXCLUSIONS.json
- (stage / "EXCLUSIONS.json").write_text(json.dumps({
- "excluded_patterns": [
- ".git", "__pycache__", "*.pyc", ".pytest_cache", ".venv",
- "vendor license keys", "transient build artifacts"
- ],
- "rationale": "Eliminate redundant non-source files to keep archive lightweight and self-contained."
- }, indent=2), encoding="utf-8")
- # SOURCE-INDEX.md
- (stage / "SOURCE-INDEX.md").write_text("""# Prod2U 统一分析包源码与资源索引
- - `sources/cpld/`: 完整 Verilog RTL、引脚约束、参数生成器、GUI 及测试套件。
- - `products/`: 6400 V1.1, 6400 V2.0, MRDIMM V1.2 的独立身份、配置文件、真实 bit 与独立 EXE。
- - `hardware/`: 原始电路板图 (.brd)、CON78/CON140 引脚推导、HIL 准备规格书。
- - `debug/`: 串口独占锁现场取证、零宽字符分析、定向变异测试与全链路仿真复现用例。
- - `verification/`: 自动化测试结果集、真实部署结构审计日志与未决硬件项清单。
- - `delivery/`: 部署回执与变更记录。
- """, encoding="utf-8")
- # Run directory audit
- audit_log_content = run_directory_audit(stage)
- (verif_audits / "deployment_audit_log.txt").write_text(audit_log_content, encoding="utf-8")
- # Calculate File Inventory & Manifest
- inventory = []
- manifest = {}
- for root, _, files in os.walk(stage):
- for f in sorted(files):
- if f == "MANIFEST.json":
- continue
- p = Path(root) / f
- rel_p = str(p.relative_to(stage)).replace("\\", "/")
- sz = p.stat().st_size
- sha = sha256_file(p)
- inventory.append({"path": rel_p, "size": sz, "sha256": sha})
- manifest[rel_p] = {"size": sz, "sha256": sha}
- (stage / "FILE-INVENTORY.json").write_text(json.dumps(inventory, indent=2), encoding="utf-8")
- p_inv = stage / "FILE-INVENTORY.json"
- manifest["FILE-INVENTORY.json"] = {"size": p_inv.stat().st_size, "sha256": sha256_file(p_inv)}
- # Write MANIFEST.json (omits self to avoid circular reference per Section 7.3)
- (stage / "MANIFEST.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
- # Create output ZIP with ZIP_DEFLATED level 9
- print(f"Compressing staging directory into {output_zip}...")
- output_zip.parent.mkdir(parents=True, exist_ok=True)
- if output_zip.exists():
- output_zip.unlink()
- with zipfile.ZipFile(output_zip, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
- for root, _, files in os.walk(stage):
- for f in sorted(files):
- p = Path(root) / f
- arcname = str(p.relative_to(stage)).replace("\\", "/")
- zf.write(p, arcname)
- # Verification of ZIP integrity
- print(f"Verifying {output_zip}...")
- with zipfile.ZipFile(output_zip, "r") as zf:
- bad_file = zf.testzip()
- if bad_file:
- raise RuntimeError(f"Corrupted file in zip: {bad_file}")
- member_count = len(zf.namelist())
-
- zip_size = output_zip.stat().st_size
- zip_sha = sha256_file(output_zip)
- print(f"Successfully generated {output_zip}: {zip_size:,} bytes, {member_count} files, SHA256: {zip_sha}")
-
- return {
- "output_path": str(output_zip),
- "size_bytes": zip_size,
- "member_count": member_count,
- "sha256": zip_sha,
- "run_id": run_id
- }
- def main():
- target_zip = Path("/workspace/tmp/Prod2U-Analysis.zip")
- info = build_analysis_package(target_zip)
- run_id = info["run_id"]
-
- handoff_dir = Path(f"/data/prod2u/handoffs/{run_id}")
- handoff_dir.mkdir(parents=True, exist_ok=True)
- persistent_zip = handoff_dir / "Prod2U-Analysis.zip"
- shutil.copy2(target_zip, persistent_zip)
- print(f"Persistent copy saved to {persistent_zip}")
- (handoff_dir / "本轮结果.txt").write_text(f"""===============================================================================
- Prod2U 统一分析包交付说明 (本轮结果)
- ===============================================================================
- 运行 ID: {run_id}
- 打包时间: {datetime.datetime.now(datetime.timezone.utc).isoformat()}
- 分析包文件: Prod2U-Analysis.zip
- 文件大小: {info['size_bytes']:,} 字节
- 文件成员数: {info['member_count']} 个
- SHA256 校验和: {info['sha256']}
- 【本轮关键定位与交付成果】
- 1. 上位机接收与调度状态机缺陷修复 (tools/stream_receiver.py & tools/prod2u_gui.py):
- - 彻底修复头预检吞没、超时残帧清除、单 in-flight 事务调度、GET_ACK+GET_DATA 顺序绑定、
- 孤立遥测过滤与 generation token 机制,相关单测与探针全部实测通过。
- 2. 9 项已知错误定向变异测试套件建立 (tests/unit/test_directed_mutations.py):
- - 针对波特率分频、PTC 极性、腔体反转、错误 CRC、丢失 ACK、线程竞争、延迟、看门狗、
- 帧错误进行定向变异注入,证明能够精确变红拦截。
- 3. 全链路数字仿真验证 over PTY (tests/sim/full_chain_pty_e2e.py):
- - 经由真实 Linux PTY + 921600 波特率 UART BFM,闭环验证物理顶层 prod2u_mrdimm_rs232_only_top.v,
- 覆盖 GET_ALL, SET_ALL, 限位急停 (MOTOR_DONE) 与看门狗超时。
- 4. 代表性低成本硬件在环 (HIL) 准备规格 (docs/hardware/HIL_SPECIFICATION.md):
- - 整理 CON78/CON140/PWM/限位引脚级连线清单与 MCU 规格,明确状态为 NOT_RUN。
- 5. 三产品独立 Windows EXE 生成与自检:
- - 经 Wine 独立打包出内嵌运行时的三个无依赖 EXE,并通过 Wine --self-test 自动化验证。
- 6. 取消假 PASS 与假定叙述:
- - 真实记录现场 COM14 锁事实与板卡未烧录现状,客观区分数字闭环与实物未运行状态。
- ===============================================================================
- """, encoding="utf-8-sig")
- (handoff_dir / "index.json").write_text(json.dumps({
- "run_id": run_id,
- "analysis_zip": "Prod2U-Analysis.zip",
- "size_bytes": info["size_bytes"],
- "member_count": info["member_count"],
- "sha256": info["sha256"],
- "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat()
- }, indent=2), encoding="utf-8")
- if __name__ == "__main__":
- main()
|