瀏覽代碼

fix(prod2u): unlock public polarity config path and package provenance

Remove production-only polarity locks so project.json → generate_project can
emit alternate per-axis masks; add real-top startup 5000+500 matrix via the
public path; replace hardcoded dual-closure booleans and inventory-as-reference
pointer with commit-compare receipts and raw reference ZIP identity.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 月之前
父節點
當前提交
5603bb2c37

+ 117 - 13
.cursor/skills/chatgpt-56pro-auto-loop/SKILL.md

@@ -101,31 +101,132 @@ Playwright → 固定 ChatGPT 会话(Sol + Pro)
   `https://chatgpt.com/g/g-p-6a16aa59456c8191a9df2af8ba070da8/c/6a7312ac-2364-83e8-abb3-e3575bef6b1f`
 - 模型:GPT-5.6 Sol + Pro  
 - 单标签复用;禁循环新开页;禁点历史 Download 下错旧文件  
-- 上传用已验证 Windows 路径:  
+
+### 会话节流(强制,避免 “Something went wrong”)
+
+本固定会话被自动化盯得过紧时,ChatGPT 易出现网络/会话错误,而用户其它会话正常。必须:
+
+1. **Worker 每次探针最多 1 次**打开/刷新会话做只读探针;禁止同一探针周期内反复 navigate;主会话在 Worker 存活时不要自己探针  
+2. **Pro 正在 thinking / Stop answering 时:只读,禁止 Send、禁止补挂、禁止点 Retry 连点**  
+3. **发送消息:每轮任务最多 1 条**(含附件);同一轮不得因探针抖动反复重发  
+4. **附件**:确认 `ATTACHED_IN_THREAD` 后 30 分钟内默认不再重传;DOM 偶发找不到先滚动/等渲染,勿立刻再发  
+5. **Retry**:仅当错误条稳定可见且 Pro 未在回答时点 **一次**;点后至少等 10 分钟  
+6. **Worker 探针间隔 ≥ 5 分钟**(默认 300s);主会话稀心跳 **30 分钟**;4h 窗口靠 Worker 长等,不靠狂刷主会话  
+7. MCP 断连时先修好再动会话,禁止短时间密集重试点击  
+
+- **推荐上传法(绕过 Playwright 路径沙箱 ENOENT)**:  
+  1. 在 WSL 对 `.chatgpt-handoff/` 起 `python3 -m http.server <port> --bind 0.0.0.0`  
+  2. Playwright:`page.context().request.get('http://<WSL_IP>:<port>/<zip>')` 取 buffer  
+  3. `page.locator('#upload-files').setInputFiles({ name, mimeType:'application/zip', buffer })`  
+  4. 确认 composer 出现 `Remove file …` / `Zip Archive` 后再发送  
+  5. 发送后按「多重多次严格校验」探针,必须 `ATTACHED_IN_THREAD`  
+- 备选:Windows 路径  
   `C:\Users\Administrator\Agentworkspace\.playwright-upload-cache\<包名>.zip`  
-  经 `browser_run_code_unsafe` 对 composer `drop`(长对话可先藏历史 turn)  
-- 勿用 Linux `/root/...` 路径直接丢给 Edge  
+  (直接 setInputFiles/drop 常被沙箱 ENOENT;勿把 Linux `/root/...` 伪造成 `C:\root\...`)  
+
 - reference:按当轮 Pro 意见;未要求则默认不传  
 - Pro 可能很慢:本地等待,勿因超时放弃环路  
 
-## 发后强制长轮询(全自动)
+## 附件上传:多重多次严格校验(强制)
+
+**正文里写了路径/文件名 ≠ 上传成功。** 未通过本门禁前,禁止向用户或 Pro 声称“已上传/已挂载附件”。
+
+### 通过标准(全部满足才算 ATTACHED)
+
+1. **本地实体**:目标 zip 存在;`sha256sum` 与声明一致(可用  
+   `bash .chatgpt-handoff/verify-chatgpt-upload.sh <zip> [sha256]`)。  
+2. **会话附件芯片**:页面出现含该 **basename** 的 `Zip Archive` 卡片(或等价附件 UI),  
+   不是仅出现在消息纯文本里。  
+3. **非旧包冒充**:芯片 basename 必须是本轮文件;禁止把历史 `Download file` 当成新上传。  
+4. **发送后复检**:点发送后再次探针;发送前 composer 里有文件 ≠ 发送后已入线程。
+
+探针脚本:`.chatgpt-handoff/chatgpt-upload-probe.js`  
+(`verdict=ATTACHED_IN_THREAD` 且 `uploadSucceeded=true` 才算过;  
+`TEXT_PATH_ONLY_NOT_ATTACHED` / `NOT_FOUND` = 失败。)
+
+### 每次回传必须跑的次数与时机
+
+| 时机 | 动作 |
+|---|---|
+| 上传前 | 本地 SHA/size 校验 |
+| 选入 composer 后 | 探针 #1:应为 `PENDING_IN_COMPOSER` 或已见芯片 |
+| 发送后立即 | 探针 #2:必须 `ATTACHED_IN_THREAD` |
+| 发送后 +10~30s | 探针 #3:复检芯片仍在(防闪失) |
+| Worker 首次探针 | 探针 #4:再确认本轮包仍挂在线程 |
+
+任一次失败 → 标记 `UPLOAD_SUCCESS=false`,落盘  
+`.chatgpt-handoff/round-N/UPLOAD-AUDIT.md`,**自动重试上传(最多 3 次)**;  
+仍失败则明确请用户手动附文件,不得用“路径已写入正文”搪塞。
+
+### 禁止口径
+
+- 禁止:`已上传` / `已挂载` / `upload sent`(若仅有文本路径)  
+- 允许:`文本已发送;附件校验失败(TEXT_PATH_ONLY)` + 真实路径与 SHA  
+
+
+## 发后持续等待(Pro-Wait:全自动)
+
+发给 Pro 且上传门禁通过之后,**必须**进入持续等待(默认覆盖 ≥4h thinking)。架构:
+
+```
+主 Agent 一次启动
+  → 写 PRO-WAIT.json(phase=waiting, deadline≈now+4.5h)
+  → 后台 Pro-Wait Worker(唯一 Playwright 探针者)
+  → pro-wait-supervisor.sh(看门狗;稀唤醒)
+  → 主会话确认“已进入持续等待”后不再每 5 分钟刷屏
+```
+
+### 时序(勿混淆)
+
+| 角色 | 间隔 | 做什么 |
+|---|---|---|
+| **Pro-Wait Worker** | **5 分钟** | 只读 Playwright 探针;thinking 则 sleep 继续,**不结束** |
+| **supervisor** | 60s 自检 | 检查 Worker 心跳;**不**探针 ChatGPT |
+| **主会话心跳** | **30 分钟** | `AGENT_LOOP_WAKE_pro_wait_heartbeat` 最多一句状态 |
+| **看门狗** | 心跳缺 **15 分钟** | `AGENT_LOOP_WAKE_pro_wait_watchdog` → 主 Agent 重启 Worker |
+
+入口:
+
+- Worker 提示词:`.chatgpt-handoff/pro-wait-worker-prompt.md`
+- 状态机:`.chatgpt-handoff/PRO-WAIT.json`
+- 看门狗:`.chatgpt-handoff/pro-wait-supervisor.sh`(`pro-poll-loop.sh` 为兼容转调)
+- 时长默认 4.5h / 16200s(`PRODU2_PRO_POLL_DURATION_S`);可沿用已有 `pro-poll-deadline.epoch`
+
+### 主会话 notify 只听这些
+
+- `AGENT_LOOP_WAKE_pro_done` — 执行 `NEXT-TASK-PROMPT.md`
+- `AGENT_LOOP_WAKE_pro_wait_watchdog` — 重启 Worker;禁止借机狂点 ChatGPT
+- `AGENT_LOOP_WAKE_pro_wait_heartbeat` — 一句状态;Worker 活着则不要自己探针
+- `AGENT_LOOP_DONE_chatgpt_pro_poll` — 总结 / deadline blocker;不编造合同
+
+**禁止**再启动会每 5 分钟对主会话发 `AGENT_LOOP_TICK_chatgpt_pro_poll` 的旧循环。
+
+### Worker 规则(摘要)
+
+- 循环直到 `pro_done` / `disarmed` / 超过 deadline
+- thinking / idle 无新答复:**不 return**,sleep 后继续
+- 完整新答复:落盘 `REPLY-from-pro.md` + `NEXT-TASK-PROMPT.md`(含 md 下载门禁)→ `phase=pro_done` → 才退出
+- 对用户/主会话零刷屏;完成摘要只在 Worker 结束时一次
+- **禁止**因单次超时、短暂断连、“看起来很慢”、或 Case 审计已本地 PASS 而停止等 Pro
+- 用户要求“持续优化 / 自动环”时,本等待为默认行为,不需每轮再确认
+
+## Pro 附件提示词:下载与读取门禁
 
-发给 Pro 之后,**必须**启动持续轮询,默认:
+Pro 常把下一合同放在可下载 `.md` 附件里(官方 Preview 可能失败)。必须:
 
-- 时长 **≥ 2 小时**(推荐 2.5h / 9000s)
-- 间隔 **约 3 分钟**(180s)
-- 入口:`.chatgpt-handoff/pro-poll-loop.sh`(只发 `AGENT_LOOP_TICK_chatgpt_pro_poll` 唤醒主 Agent)
-- 主 Agent 每次 tick:Playwright 打开固定会话 → 判断 thinking / 完整答复 → 若完成则落盘 `REPLY-from-pro.md` + `NEXT-TASK-PROMPT.md` 并**立即执行**,然后停止轮询
-- 未完成:只更新 `LOOP-STATE.md` 时间戳,继续等下一 tick
-- **禁止**因单次超时、短暂断连或“看起来很慢”而停止环路;窗口结束仍无答复再记 blocker
-- 用户要求“持续优化 / 自动环”时,本长轮询为默认行为,不需每轮再确认
+1. 在消息内找 `Download` / 文件芯片 / `file-service` 链接,点下载到  
+   Playwright 可写目录或 `.chatgpt-handoff/round-N/`  
+2. 计算 SHA-256,与 Pro 声明(若有)比对;落盘  
+   `REPLY-from-pro.md` + 官方原文 + `NEXT-TASK-PROMPT.md`(可从官方 md 复制正文)  
+3. Preview unavailable 时:用 Download / `browser_network_request` / 页面内全文粘贴兜底,**不得**凭摘要发明合同  
+4. 若仅有会话正文无附件:以正文完整拷贝为合同,并在 LOOP-STATE 注明 `prompt_source=thread_text`
 
 ## 本地执行与回传
 
 - 按 Pro 当轮详设执行;优先级:功能简单可靠 → 再抠 LUT/Slice(其他资源可换)→ 最后性能  
 - 可按详设并行;执行期撞文件/worktree 问题时现场微调即可  
 - 回传:自然语言短分析 +「改了什么/测了什么」清单 + 分析包(默认无 reference)  
-- 发 Pro 后的等待用 `pro-poll-loop.sh` + Agent tick;`/loop` 也可臂装同一轮询  
+- 发 Pro 后的等待:写 `PRO-WAIT.json` + 启动 Pro-Wait Worker + `pro-wait-supervisor.sh`(`pro-poll-loop.sh` 兼容转调)  
 - `/run-everything`、`/in-cloud` 默认不用  
 - 不 force-push;不擅自 Hardware;不擅自 commit/push(除非当轮任务合同明确要求)  
 
@@ -134,6 +235,9 @@ Playwright → 固定 ChatGPT 会话(Sol + Pro)
 `.chatgpt-handoff/`:
 
 - `LOOP-STATE.md` — 轮次与是否继续  
+- `PRO-WAIT.json` — 持续等待状态机(phase / deadline / heartbeat)  
+- `pro-wait-worker-prompt.md` — 后台 Worker 合同  
+- `pro-wait-supervisor.sh` — 看门狗(稀唤醒)  
 - `round-N/upload.zip` + `.sha256`  
 - `round-N/PROMPT-to-pro.txt`  
 - `round-N/REPLY-from-pro.md`  

+ 20 - 7
docs/prod2u-door-temp-protocol.zh-CN.md

@@ -26,11 +26,24 @@
 | 值 | 含义 |
 |----|------|
 | 00 | 不启动新 jog(已在运动则忽略;不改变 EN) |
-| 01 | 打开方向(DIR=0,目标 HS),最多 450 STEP 上升沿 |
-| 02 | 关闭方向(DIR=1,目标 LS),最多 450 STEP 上升沿 |
+| 01 | 逻辑打开(向 open_limit),最多 450 STEP 上升沿 |
+| 02 | 逻辑关闭(向 close_limit),最多 450 STEP 上升沿 |
 
 busy 期间新的门命令全部忽略(无 latest-wins)。看门狗超时:停止 STEP,PTC=0、FAN=20;EN 仍永久有效。
 
+## 编译期每轴极性 / 端点角色(唯一权威入口)
+
+用户只改 `project.json` 中下列三组数组(下标 0=X,1=Y,2=Z),经正式 `tools/generate_project.py` 即可生成对应 mask;默认值全部为 1/true,等价当前生产镜像:
+
+| 字段 | 含义 |
+|------|------|
+| `motors.dir_close_level[i]` | 1:physical DIR=1 表示逻辑关闭;0:DIR=0 表示逻辑关闭 |
+| `limits.limit_active_high[i]` | true:该轴 LS/HS raw 高=到达;false:raw 低=到达 |
+| `limits.close_limit_is_ls[i]` | true:LS=逻辑关闭端、HS=打开端;false:角色对调 |
+
+生成参数:`P4_DIR_CLOSE_LEVEL_MASK` / `P4_LIMIT_ACTIVE_HIGH_MASK` / `P4_CLOSE_LIMIT_IS_LS_MASK`(bit0=X)。  
+`limits.active_level` 为 **legacy summary / deprecated / non-authoritative**,不控制 RTL mask,也不强制与 `all(limit_active_high)` 一致;保留仅为旧配置兼容。
+
 ## 物理映射(V1.2 BRD)
 
 | 角色 | 连接器 | FPGA |
@@ -43,15 +56,15 @@ busy 期间新的门命令全部忽略(无 latest-wins)。看门狗超时:
 | LS3/HS3 | CON129.1/2 | K16/J15 |
 | LS4/HS4 | CON129.3/4 | H15/H16(仅 inventory) |
 
-限位高有效。运行期与 startup 均硬停:DIR=1 看 LS,DIR=0 看 HS。  
+默认生产配置下限位高有效、LS=关闭端。运行期与 startup 均对**规范化后的逻辑端点**硬停。  
 `stop_semantics`:`truncate_current_high_pulse_immediately_after_synchronized_limit`(同步限位后立即截断当前 STEP 高脉冲,不再产生新上升沿)。
 
 ## Startup(上电一拍)
 
-1. 六路限位 2FF 同步后:已在 LS 的轴不运动。
-2. 其余轴 DIR=1 关向搜索,最多 **5000** 个 STEP 上升沿;命中 LS 的轴按截断语义立即停。
-3. 仅对仍未命中 LS 的轴做 DIR=0 回退最多 **500** 步(途中 HS 可提前停)。
-4. `startup_done` 粘性置位后才接受主机命令;运行期仍按方向选择限位硬截断(非惰性)。
+1. 六路限位 2FF 同步后:已在逻辑 close_limit 的轴不运动。
+2. 其余轴按逻辑关闭方向搜索,最多 **5000** 个 STEP 上升沿;命中 configured close endpoint 的轴立即停且不回退(`found_close` 锁存)。
+3. 仅对始终未命中 close_limit 的轴按逻辑打开方向回退最多 **500** 步(途中 open_limit 可提前停)。
+4. `startup_done` 粘性置位后才接受主机命令;运行期仍按逻辑方向选择限位硬截断(非惰性)。
 
 普通命令 jog = **450** 步 @ 1000 step/s。无电磁铁、无 motor-compat 双 profile。
 

+ 98 - 7
package_for_agent_analysis.py

@@ -18,7 +18,7 @@ import uuid
 import zipfile
 from datetime import datetime, timezone
 from pathlib import Path
-from typing import NamedTuple
+from typing import Any, NamedTuple
 
 
 ROOT = Path(__file__).resolve().parent
@@ -491,6 +491,8 @@ def analysis_exclusion_reason(
         ".hypothesis": "hypothesis_cache",
         ".ruff_cache": "ruff_cache",
         ".pytest_cache": "pytest_cache",
+        ".chatgpt-handoff": "chatgpt_handoff_runtime_not_in_compact",
+        ".playwright-upload-cache": "playwright_upload_cache",
         "dist": "generated_delivery_output",
         "log": "runtime_log_directory",
         "runs": "run_state_directory",
@@ -1184,13 +1186,102 @@ def collect_analysis_inputs(
                 td_run_id=td_run,
                 reference_set_fingerprint_sha256=ref_fp["sha256"],
             )
-            relations = pkg_prov.build_source_closure_relations(
-                old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
+            # Real dual-edge source-closure compare (same authority as firmware packager).
+            from build_firmware_package import (  # noqa: WPS433
+                OLD_BASELINE_COMMIT_DEFAULT,
+                generate_source_closure_comparison,
+            )
+
+            td_report_payload: dict[str, Any] | None = None
+            for report_meta in binding.get("td_reports") or []:
+                if not isinstance(report_meta, dict):
+                    continue
+                report_path = Path(str(report_meta.get("path") or ""))
+                if report_path.is_file():
+                    try:
+                        td_report_payload = json.loads(
+                            report_path.read_text(encoding="utf-8-sig")
+                        )
+                    except (OSError, json.JSONDecodeError):
+                        continue
+                    if td_report_payload.get("synthesis_input_manifest", {}).get("inputs"):
+                        break
+                    td_report_payload = None
+            if td_report_payload is None:
+                for candidate in td_report_paths or []:
+                    cpath = Path(str(candidate))
+                    if cpath.is_file():
+                        try:
+                            td_report_payload = json.loads(
+                                cpath.read_text(encoding="utf-8-sig")
+                            )
+                        except (OSError, json.JSONDecodeError):
+                            continue
+                        if td_report_payload.get("synthesis_input_manifest", {}).get(
+                            "inputs"
+                        ):
+                            break
+                        td_report_payload = None
+            if td_report_payload is None:
+                raise PackagingError(
+                    "source-closure relations require a TD report with "
+                    "synthesis_input_manifest.inputs (pass --td-report)"
+                )
+            art_to_del = generate_source_closure_comparison(
+                td_report=td_report_payload,
                 artifact_commit=artifact,
-                delivery_commit=delivery,
-                old_to_artifact_unchanged=False,
-                # Delivery may tip ahead of ARTIFACT when production inputs are unchanged.
-                artifact_to_delivery_unchanged=True,
+                matrix_commit=artifact,
+                final_dev_commit=delivery,
+                repo_root=root,
+            )
+            old_to_art = generate_source_closure_comparison(
+                td_report=td_report_payload,
+                artifact_commit=OLD_BASELINE_COMMIT_DEFAULT,
+                matrix_commit=OLD_BASELINE_COMMIT_DEFAULT,
+                final_dev_commit=artifact,
+                repo_root=root,
+            )
+            comparison_mode = str(art_to_del.get("mode") or "commit_compare")
+            if comparison_mode == "comparison_unavailable_without_git":
+                relations = pkg_prov.build_source_closure_relations(
+                    old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
+                    artifact_commit=artifact,
+                    delivery_commit=delivery,
+                    old_to_artifact_unchanged=None,
+                    artifact_to_delivery_unchanged=None,
+                    old_to_artifact_changed_paths=[],
+                    artifact_to_delivery_changed_paths=[],
+                    comparison_mode="comparison_unavailable",
+                )
+            else:
+                relations = pkg_prov.build_source_closure_relations(
+                    old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
+                    artifact_commit=artifact,
+                    delivery_commit=delivery,
+                    old_to_artifact_unchanged=bool(
+                        old_to_art.get("source_closure_equal")
+                    ),
+                    artifact_to_delivery_unchanged=bool(
+                        art_to_del.get("source_closure_equal")
+                    ),
+                    old_to_artifact_changed_paths=list(
+                        old_to_art.get("production_changed_paths") or []
+                    ),
+                    artifact_to_delivery_changed_paths=list(
+                        art_to_del.get("production_changed_paths") or []
+                    ),
+                    comparison_mode=comparison_mode,
+                )
+            rel_check = pkg_prov.validate_source_closure_relations(relations)
+            if rel_check["status"] != "pass":
+                raise PackagingError(
+                    f"source-closure relations inconsistent: {rel_check['failures']}"
+                )
+            provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-ART-TO-DEL.json"] = (
+                handoff.json_bytes(art_to_del)
+            )
+            provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-OLD-TO-ART.json"] = (
+                handoff.json_bytes(old_to_art)
             )
             sibling = pkg_prov.sibling_role_stub(
                 role="review-compact",

+ 5 - 4
projects/prod2u-door-temp/requirements.zh-CN.md

@@ -32,14 +32,15 @@ CRC 为 CRC-16/CCITT-FALSE。正式类型只有 `0x01`、`0x02` 和 `0x82`。
 
 ## 风门与马达
 
-- 三轴编码均为 `00/01/02`:`00` = 不启动新 jog(轴已 busy 时忽略该字节,不停止、不覆盖当前动作);`01` 开门 DIR=0;`02` 关门 DIR=1。
+- 三轴编码均为 `00/01/02`:`00` = 不启动新 jog(轴已 busy 时忽略该字节,不停止、不覆盖当前动作);`01` 逻辑打开(向 open_limit);`02` 逻辑关闭(向 close_limit)。
 - 普通 jog:450 步、1000 step/s,X/Y/Z 可并行。
 - 电机 EN:CON120.2 → C11,板级 NPN 反相;FPGA 恒 1(`permanent_high`),座端 EN 永久有效。
 - 步进/方向球位:X CON104.2/3 → C12/B12;Y CON105.2/3 → L12/J11;Z CON106.2/3 → L14/K14。
+- **编译期唯一权威配置**(下标 X/Y/Z):`motors.dir_close_level`、`limits.limit_active_high`、`limits.close_limit_is_ls`。默认全 1/true。经正式 `generate_project` 生成 `P4_*_MASK`;`limits.active_level` 为 legacy/deprecated/non-authoritative,不控制 mask。
 
 ## 六限位与运行期硬停
 
-每轴高低侧各一限位,FPGA 端 active high,`runtime_use=true`:
+每轴高低侧各一限位,`runtime_use=true`;默认生产极性为 FPGA 端 active high、LS=逻辑关闭端:
 
 | 轴 | LS | HS |
 | --- | --- | --- |
@@ -47,8 +48,8 @@ CRC 为 CRC-16/CCITT-FALSE。正式类型只有 `0x01`、`0x02` 和 `0x82`。
 | Y | CON12.3 C8 | CON12.4 A8 |
 | Z | CON129.1 K16 | CON129.2 J15 |
 
-- **Startup**:PTC=0、FAN=10;三轴 DIR=1 关门寻限;每轴最多 5000 步 @ 1000 step/s;未触发则回退 500 步后标记 missed;`startup_done` 粘滞。
-- **运行期**:按运动方向选择对应限位;限位有效时该轴硬停(同步限位后立即截断当前 STEP 高脉冲,`stop_semantics=truncate_current_high_pulse_immediately_after_synchronized_limit`);busy 期间忽略新 start。
+- **Startup**:PTC=0、FAN=10;三轴逻辑关闭寻限;每轴最多 5000 步 @ 1000 step/s;曾命中 close_limit 则锁存且不回退;始终未命中则逻辑打开回退最多 500 步;`startup_done` 粘滞。
+- **运行期**:按逻辑运动方向选择对应逻辑限位;限位有效时该轴硬停(同步限位后立即截断当前 STEP 高脉冲,`stop_semantics=truncate_current_high_pulse_immediately_after_synchronized_limit`);busy 期间忽略新 start。
 - Startup 完成前:SET_ALL / GET_TEMPERATURE 丢弃,看门狗不喂,帧解析器保持 flush。
 
 ## 输出与看门狗

+ 6 - 4
schemas/project.schema.json

@@ -331,7 +331,7 @@
                                                                                                "type":  "integer",
                                                                                                "enum":  [0, 1]
                                                                                            },
-                                                                                 "description":  "Per-axis physical DIR level for logical close; index0=X,1=Y,2=Z (bit0=X)."
+                                                                                 "description":  "AUTHORITATIVE per-axis physical DIR level for logical close (1 or 0); index0=X,1=Y,2=Z (bit0=X). Must be integer 0/1, not boolean."
                                                                              },
                                                          "mapping":  {
                                                                          "type":  "object",
@@ -406,7 +406,9 @@
                                                                              "type":  "integer"
                                                                          },
                                                          "active_level":  {
-                                                                              "type":  "string"
+                                                                              "type":  "string",
+                                                                              "enum":  ["high", "low"],
+                                                                              "description":  "LEGACY SUMMARY / DEPRECATED / NON-AUTHORITATIVE. Kept for old configs only. Does not control RTL masks or reject mixed-axis polarity. Authority is limits.limit_active_high[] alone."
                                                                           },
                                                          "limit_active_high":  {
                                                                                    "type":  "array",
@@ -415,7 +417,7 @@
                                                                                    "items":  {
                                                                                                  "type":  "boolean"
                                                                                              },
-                                                                                   "description":  "Per-axis limit active-high; index0=X,1=Y,2=Z (bit0=X)."
+                                                                                   "description":  "AUTHORITATIVE per-axis limit active-high; index0=X,1=Y,2=Z (bit0=X). Sole polarity authority with motors.dir_close_level and limits.close_limit_is_ls."
                                                                                },
                                                          "close_limit_is_ls":  {
                                                                                    "type":  "array",
@@ -424,7 +426,7 @@
                                                                                    "items":  {
                                                                                                  "type":  "boolean"
                                                                                              },
-                                                                                   "description":  "Per-axis: true means logical close limit is LS (else HS); index0=X,1=Y,2=Z."
+                                                                                   "description":  "AUTHORITATIVE per-axis: true means logical close limit is LS (else HS); index0=X,1=Y,2=Z."
                                                                                },
                                                          "functional_use":  {
                                                                                 "type":  "boolean"

+ 20 - 3
tests/board_viewer/board-logic.test.mjs

@@ -1,7 +1,8 @@
 import test from "node:test";
 import assert from "node:assert/strict";
 import {createHash} from "node:crypto";
-import {readFileSync} from "node:fs";
+import {existsSync, readFileSync} from "node:fs";
+import {fileURLToPath} from "node:url";
 
 import {
   connectorPinGroups,
@@ -12,6 +13,22 @@ import {
   searchBoard,
 } from "../../tools/board-viewer/web/board-logic.mjs";
 
+function resolveGeneratedAsset(name) {
+  // Live repo: tools/board-viewer/generated; compact package: evidence/board-viewer.
+  const candidates = [
+    new URL(`../../tools/board-viewer/generated/${name}`, import.meta.url),
+    new URL(`../../evidence/board-viewer/${name}`, import.meta.url),
+    new URL(`../evidence/board-viewer/${name}`, import.meta.url),
+  ];
+  for (const url of candidates) {
+    const path = fileURLToPath(url);
+    if (existsSync(path)) {
+      return url;
+    }
+  }
+  return candidates[0];
+}
+
 
 function pin(overrides = {}) {
   return {
@@ -309,8 +326,8 @@ test("candidate reason exposes the pin purpose and non-default polarity", () =>
 
 
 test("product candidate filters keep dedicated functions out of generic GPIO", () => {
-  const boardDataPath = new URL("../../tools/board-viewer/generated/board-data.json", import.meta.url);
-  const buildInfoPath = new URL("../../tools/board-viewer/generated/build-info.json", import.meta.url);
+  const boardDataPath = resolveGeneratedAsset("board-data.json");
+  const buildInfoPath = resolveGeneratedAsset("build-info.json");
   const expectationPath = new URL("./fixtures/candidate_count_expectation.json", import.meta.url);
   const boardDataBytes = readFileSync(boardDataPath);
   const buildInfoBytes = readFileSync(buildInfoPath);

+ 443 - 0
tests/sim/prod2u_p4_alt_config_startup_tb.v

@@ -0,0 +1,443 @@
+`timescale 1ns/1ps
+
+// Alternate-config STARTUP behavior TB against REAL top.
+// Self-configures from dut.LIMIT_ACTIVE_HIGH / DIR_CLOSE_LEVEL / CLOSE_LIMIT_IS_LS.
+// Counts external STEP ball rising edges (not internal start/done alone).
+// Covers configured close already-hit, mid-search hit, found_close latch,
+// 5000 miss + 500 backoff, open-limit early stop, and per-axis independence.
+module prod2u_p4_alt_config_startup_tb;
+    reg sys_clk = 1'b0;
+    reg host_uart_rx = 1'b1;
+    wire host_uart_tx;
+    wire [7:0] ptc_pwm_out;
+    wire [3:0] fan_pwm_out;
+    wire motor_en_n;
+    wire x_step, x_dir, y_step, y_dir, z_step, z_dir;
+    reg x_limit_ls = 1'b0;
+    reg x_limit_hs = 1'b0;
+    reg y_limit_ls = 1'b0;
+    reg y_limit_hs = 1'b0;
+    reg z_limit_ls = 1'b0;
+    reg z_limit_hs = 1'b0;
+    tri temp_scl;
+    tri temp_sda;
+
+    localparam integer FAST_TICK_DIV = 10;
+    localparam integer CLOSE_STEPS = 5000;
+    localparam integer BACKOFF_STEPS = 500;
+    localparam integer HOST_STEPS = 450;
+    reg [31:0] fast_tick_div;
+    reg fast_tick;
+
+    integer x_steps, y_steps, z_steps;
+    integer x_close_dir_steps, x_open_dir_steps;
+    reg prev_x_step, prev_y_step, prev_z_step;
+    reg counting;
+
+    wire [2:0] AH  = dut.LIMIT_ACTIVE_HIGH;
+    wire [2:0] DCL = dut.DIR_CLOSE_LEVEL;
+    wire [2:0] CLS = dut.CLOSE_LIMIT_IS_LS;
+
+    always #1 sys_clk = ~sys_clk;
+
+    prod2u_p4_normal_v3_top dut (
+        .sys_clk(sys_clk), .host_uart_rx(host_uart_rx), .host_uart_tx(host_uart_tx),
+        .ptc_pwm_out(ptc_pwm_out), .fan_pwm_out(fan_pwm_out),
+        .motor_en_n(motor_en_n),
+        .x_step(x_step), .x_dir(x_dir), .y_step(y_step), .y_dir(y_dir),
+        .z_step(z_step), .z_dir(z_dir),
+        .x_limit_ls(x_limit_ls), .x_limit_hs(x_limit_hs),
+        .y_limit_ls(y_limit_ls), .y_limit_hs(y_limit_hs),
+        .z_limit_ls(z_limit_ls), .z_limit_hs(z_limit_hs),
+        .temp_scl(temp_scl), .temp_sda(temp_sda)
+    );
+
+    initial begin
+        fast_tick = 1'b0;
+        fast_tick_div = 0;
+        force dut.tick_500us = fast_tick;
+        force dut.watchdog_timeout_event = 1'b0;
+    end
+
+    always @(posedge sys_clk) begin
+        if (fast_tick_div + 1 >= FAST_TICK_DIV) begin
+            fast_tick_div <= 0;
+            fast_tick <= 1'b1;
+        end else begin
+            fast_tick_div <= fast_tick_div + 1'b1;
+            fast_tick <= 1'b0;
+        end
+    end
+
+    always @(posedge sys_clk) begin
+        prev_x_step <= x_step;
+        prev_y_step <= y_step;
+        prev_z_step <= z_step;
+        if (counting) begin
+            if (!prev_x_step && x_step) begin
+                x_steps <= x_steps + 1;
+                if (x_dir === DCL[0])
+                    x_close_dir_steps <= x_close_dir_steps + 1;
+                else if (x_dir === ~DCL[0])
+                    x_open_dir_steps <= x_open_dir_steps + 1;
+            end
+            if (!prev_y_step && y_step)
+                y_steps <= y_steps + 1;
+            if (!prev_z_step && z_step)
+                z_steps <= z_steps + 1;
+        end
+    end
+
+    function automatic phys_inactive;
+        input ah_bit;
+        begin
+            phys_inactive = ~ah_bit;
+        end
+    endfunction
+
+    function automatic phys_active;
+        input ah_bit;
+        begin
+            phys_active = ah_bit;
+        end
+    endfunction
+
+    task drive_inactive_all;
+        begin
+            x_limit_ls = phys_inactive(AH[0]);
+            x_limit_hs = phys_inactive(AH[0]);
+            y_limit_ls = phys_inactive(AH[1]);
+            y_limit_hs = phys_inactive(AH[1]);
+            z_limit_ls = phys_inactive(AH[2]);
+            z_limit_hs = phys_inactive(AH[2]);
+        end
+    endtask
+
+    task set_close_phys;
+        input [1:0] axis;
+        input active;
+        reg level;
+        begin
+            level = active ? phys_active(AH[axis]) : phys_inactive(AH[axis]);
+            if (CLS[axis]) begin
+                if (axis == 2'd0) x_limit_ls = level;
+                else if (axis == 2'd1) y_limit_ls = level;
+                else z_limit_ls = level;
+            end else begin
+                if (axis == 2'd0) x_limit_hs = level;
+                else if (axis == 2'd1) y_limit_hs = level;
+                else z_limit_hs = level;
+            end
+        end
+    endtask
+
+    task set_open_phys;
+        input [1:0] axis;
+        input active;
+        reg level;
+        begin
+            level = active ? phys_active(AH[axis]) : phys_inactive(AH[axis]);
+            if (CLS[axis]) begin
+                if (axis == 2'd0) x_limit_hs = level;
+                else if (axis == 2'd1) y_limit_hs = level;
+                else z_limit_hs = level;
+            end else begin
+                if (axis == 2'd0) x_limit_ls = level;
+                else if (axis == 2'd1) y_limit_ls = level;
+                else z_limit_ls = level;
+            end
+        end
+    endtask
+
+    task drain_limit_sync;
+        begin
+            repeat (4) @(posedge sys_clk);
+        end
+    endtask
+
+    task clear_step_counters;
+        begin
+            x_steps = 0;
+            y_steps = 0;
+            z_steps = 0;
+            x_close_dir_steps = 0;
+            x_open_dir_steps = 0;
+            prev_x_step = 1'b0;
+            prev_y_step = 1'b0;
+            prev_z_step = 1'b0;
+        end
+    endtask
+
+    task wait_startup_done;
+        integer guard;
+        begin
+            guard = 0;
+            while (!dut.startup_done) begin
+                @(posedge sys_clk);
+                guard = guard + 1;
+                if (guard > 20000000)
+                    $fatal(1, "timeout waiting startup_done");
+            end
+        end
+    endtask
+
+    task pulse_por;
+        begin
+            // Cold start: release forces that might linger; rely on simulator POR.
+            counting = 1'b0;
+            clear_step_counters();
+            // Force async reset via internal rst_n if present after sync window.
+            // Top uses power-on reset counter; wait it out with inactive limits.
+            drain_limit_sync();
+        end
+    endtask
+
+    // ---- Scenario helpers that re-elaborate via $finish/$stop not available;
+    // instead we use force on u_startup_close_seek.rst path by re-running from
+    // a single initial with staged cases that each begin after POR settles,
+    // then force found_close/state only when needed. Prefer limit pin control. ----
+
+    task force_soft_restart;
+        begin
+            // Restart POR + startup FSM via the POR flop (drives sys_rst_n).
+            // Caller owns limit pins BEFORE calling this; pins are not cleared here.
+            counting = 1'b0;
+            force dut.u_por.por_reset_n = 1'b0;
+            force dut.u_por.por_count = 0;
+            repeat (8) @(posedge sys_clk);
+            clear_step_counters();
+            // Count from the first post-reset STEP edge so 5000/500 totals stay exact.
+            counting = 1'b1;
+            release dut.u_por.por_count;
+            release dut.u_por.por_reset_n;
+            while (!dut.sys_rst_n) @(posedge sys_clk);
+            while (!dut.limit_sync_valid) @(posedge sys_clk);
+        end
+    endtask
+
+    task start_host_motor;
+        input [2:0] mask;
+        input [2:0] dir_mask;
+        begin
+            @(negedge sys_clk);
+            force dut.host_motor_active_mask = mask;
+            force dut.host_motor_dir_mask = dir_mask;
+            force dut.host_motor_start = 1'b1;
+            @(posedge sys_clk);
+            @(negedge sys_clk);
+            force dut.host_motor_start = 1'b0;
+        end
+    endtask
+
+    task release_host_motor;
+        begin
+            release dut.host_motor_start;
+            release dut.host_motor_active_mask;
+            release dut.host_motor_dir_mask;
+        end
+    endtask
+
+    task case_already_on_close;
+        begin
+            $display("CASE already_on_close");
+            drive_inactive_all();
+            set_close_phys(2'd0, 1'b1);
+            set_close_phys(2'd1, 1'b1);
+            set_close_phys(2'd2, 1'b1);
+            force_soft_restart();
+            wait_startup_done();
+            counting = 1'b0;
+            if (x_steps !== 0 || y_steps !== 0 || z_steps !== 0)
+                $fatal(1, "already-on-close should be 0 steps, got x=%0d y=%0d z=%0d",
+                       x_steps, y_steps, z_steps);
+            if (motor_en_n !== 1'b1)
+                $fatal(1, "EN must stay permanent_high");
+            $display("PASS_SECTION_ALREADY_ON_CLOSE");
+        end
+    endtask
+
+    task case_mid_search_hit_no_backoff;
+        integer hit_at;
+        begin
+            $display("CASE mid_search_hit_no_backoff");
+            drive_inactive_all();
+            force_soft_restart();
+            hit_at = 40;
+            while (x_close_dir_steps < hit_at) @(posedge sys_clk);
+            if (x_dir !== DCL[0])
+                $fatal(1, "close search DIR mismatch: got %b expect %b", x_dir, DCL[0]);
+            set_close_phys(2'd0, 1'b1);
+            set_close_phys(2'd1, 1'b1);
+            set_close_phys(2'd2, 1'b1);
+            drain_limit_sync();
+            wait_startup_done();
+            counting = 1'b0;
+            if (x_open_dir_steps !== 0)
+                $fatal(1, "mid-hit must not backoff, open_dir_steps=%0d", x_open_dir_steps);
+            if (x_close_dir_steps >= CLOSE_STEPS)
+                $fatal(1, "mid-hit should stop before 5000, got %0d", x_close_dir_steps);
+            if (x_close_dir_steps < hit_at)
+                $fatal(1, "mid-hit never reached hit_at, got %0d", x_close_dir_steps);
+            $display("PASS_SECTION_MID_HIT steps=%0d", x_close_dir_steps);
+        end
+    endtask
+
+    task case_brief_hit_latches_found_close;
+        integer hit_at;
+        begin
+            $display("CASE brief_hit_latches_found_close");
+            drive_inactive_all();
+            force_soft_restart();
+            hit_at = 25;
+            while (x_close_dir_steps < hit_at) @(posedge sys_clk);
+            set_close_phys(2'd0, 1'b1);
+            set_close_phys(2'd1, 1'b1);
+            set_close_phys(2'd2, 1'b1);
+            drain_limit_sync();
+            // Release immediately after sync — found_close must stay latched.
+            drive_inactive_all();
+            drain_limit_sync();
+            wait_startup_done();
+            counting = 1'b0;
+            if (x_open_dir_steps !== 0)
+                $fatal(1, "brief hit released but backoff ran: open=%0d", x_open_dir_steps);
+            if (dut.u_startup_close_seek.found_close !== 3'b111)
+                $fatal(1, "found_close not latched after brief hit: %b",
+                       dut.u_startup_close_seek.found_close);
+            $display("PASS_SECTION_BRIEF_HIT_LATCH");
+        end
+    endtask
+
+    task case_full_miss_then_backoff;
+        begin
+            $display("CASE full_miss_then_backoff");
+            drive_inactive_all();
+            force_soft_restart();
+            // Stay inactive through entire close search + backoff.
+            wait_startup_done();
+            counting = 1'b0;
+            if (x_close_dir_steps !== CLOSE_STEPS)
+                $fatal(1, "expected exactly 5000 close steps, got %0d", x_close_dir_steps);
+            if (x_open_dir_steps !== BACKOFF_STEPS)
+                $fatal(1, "expected exactly 500 open backoff steps, got %0d", x_open_dir_steps);
+            $display("PASS_SECTION_FULL_MISS_BACKOFF close=%0d open=%0d",
+                     x_close_dir_steps, x_open_dir_steps);
+        end
+    endtask
+
+    task case_backoff_open_limit_early_stop;
+        integer seen_open_dir;
+        begin
+            $display("CASE backoff_open_limit_early_stop");
+            drive_inactive_all();
+            force_soft_restart();
+            // Wait until close search finishes (5000) and backoff begins.
+            while (x_close_dir_steps < CLOSE_STEPS) @(posedge sys_clk);
+            // Wait for DIR to switch to logical open.
+            seen_open_dir = 0;
+            while (seen_open_dir == 0) begin
+                @(posedge sys_clk);
+                if (x_dir === ~DCL[0] && x_step)
+                    seen_open_dir = 1;
+                if (dut.startup_done)
+                    $fatal(1, "startup finished before backoff open DIR observed");
+            end
+            while (x_open_dir_steps < 30) @(posedge sys_clk);
+            set_open_phys(2'd0, 1'b1);
+            set_open_phys(2'd1, 1'b1);
+            set_open_phys(2'd2, 1'b1);
+            drain_limit_sync();
+            wait_startup_done();
+            counting = 1'b0;
+            if (x_close_dir_steps !== CLOSE_STEPS)
+                $fatal(1, "close search not 5000 before early open stop: %0d", x_close_dir_steps);
+            if (x_open_dir_steps >= BACKOFF_STEPS)
+                $fatal(1, "open limit did not early-stop backoff: %0d", x_open_dir_steps);
+            if (x_open_dir_steps < 30)
+                $fatal(1, "backoff never reached sample point: %0d", x_open_dir_steps);
+            $display("PASS_SECTION_BACKOFF_EARLY_OPEN open_steps=%0d", x_open_dir_steps);
+        end
+    endtask
+
+    task case_axis_independent_profiles;
+        begin
+            $display("CASE axis_independent_profiles");
+            // X: already on close (0 steps)
+            // Y: mid-hit during close search
+            // Z: full miss → 5000+500
+            drive_inactive_all();
+            set_close_phys(2'd0, 1'b1);
+            force_soft_restart();
+            // Y hits after some steps; Z never; X stays on close.
+            while (y_steps < 35) @(posedge sys_clk);
+            set_close_phys(2'd1, 1'b1);
+            drain_limit_sync();
+            wait_startup_done();
+            counting = 1'b0;
+            if (x_steps !== 0)
+                $fatal(1, "X should be 0 steps (pre-hit), got %0d", x_steps);
+            if (y_steps >= CLOSE_STEPS)
+                $fatal(1, "Y should mid-stop, got %0d", y_steps);
+            if (y_steps < 35)
+                $fatal(1, "Y never reached mid-hit, got %0d", y_steps);
+            if (z_steps !== (CLOSE_STEPS + BACKOFF_STEPS))
+                $fatal(1, "Z should be 5000+500, got %0d", z_steps);
+            $display("PASS_SECTION_AXIS_INDEPENDENT x=%0d y=%0d z=%0d",
+                     x_steps, y_steps, z_steps);
+        end
+    endtask
+
+    task case_host_jog_after_startup;
+        begin
+            $display("CASE host_jog_after_startup");
+            drive_inactive_all();
+            set_close_phys(2'd0, 1'b1);
+            set_close_phys(2'd1, 1'b1);
+            set_close_phys(2'd2, 1'b1);
+            force_soft_restart();
+            wait_startup_done();
+            drive_inactive_all();
+            drain_limit_sync();
+            clear_step_counters();
+            counting = 1'b1;
+            start_host_motor(3'b001, 3'b001);
+            while (!dut.u_motor_engine.done) @(posedge sys_clk);
+            release_host_motor();
+            counting = 1'b0;
+            if (x_steps !== HOST_STEPS)
+                $fatal(1, "post-startup host jog expected 450, got %0d", x_steps);
+            if (motor_en_n !== 1'b1)
+                $fatal(1, "EN disturbed after startup");
+            $display("PASS_SECTION_HOST_JOG_AFTER_STARTUP");
+        end
+    endtask
+
+    initial begin
+        counting = 1'b0;
+        clear_step_counters();
+        drive_inactive_all();
+
+        $display("ALT_STARTUP_MASKS AH=%b DCL=%b CLS=%b", AH, DCL, CLS);
+        if (`P4_STARTUP_CLOSE_STEPS !== CLOSE_STEPS)
+            $fatal(1, "P4_STARTUP_CLOSE_STEPS drift");
+        if (`P4_STARTUP_BACKOFF_STEPS !== BACKOFF_STEPS)
+            $fatal(1, "P4_STARTUP_BACKOFF_STEPS drift");
+
+        // Let initial POR complete once with inactive limits, then drive cases
+        // via soft restart (force rst_n).
+        counting = 1'b1;
+        repeat (2000) @(posedge sys_clk);
+        counting = 1'b0;
+
+        case_already_on_close();
+        case_mid_search_hit_no_backoff();
+        case_brief_hit_latches_found_close();
+        case_full_miss_then_backoff();
+        case_backoff_open_limit_early_stop();
+        case_axis_independent_profiles();
+        case_host_jog_after_startup();
+
+        $display("PASS prod2u_p4_alt_config_startup_tb AH=%b DCL=%b CLS=%b", AH, DCL, CLS);
+        $finish;
+    end
+endmodule

+ 2 - 0
tests/unit/package_review_compact_contract.py

@@ -31,6 +31,8 @@ REVIEW_COMPACT_EXCLUDED_PREFIXES: tuple[tuple[str, str], ...] = (
     ("node_modules", "node_modules_runtime"),
     (".venv", "virtual_environment"),
     ("venv", "virtual_environment"),
+    (".chatgpt-handoff", "chatgpt_handoff_runtime_not_in_compact"),
+    (".playwright-upload-cache", "playwright_upload_cache"),
 )
 
 REVIEW_COMPACT_EXCLUDED_BASENAMES: tuple[tuple[str, str], ...] = (

+ 177 - 44
tests/unit/test_alt_config_rtl_matrix.py

@@ -1,34 +1,47 @@
 """Real RTL Icarus matrix for compile-time motor polarity / endpoint masks.
 
-Does NOT rewrite production project.json. Each case renders a temporary
-params.vh via _render_params and compiles the real top + alt-config TB with
-``-I <tmpdir>`` ahead of the repo root so the alt defines win.
+Authority path (feature acceptance):
+  temp project.json → public generate_project / CLI → temp generated params
+  → compile real production RTL + real top + TB
+
+``_render_params`` is not used here.
 """
 
 from __future__ import annotations
 
 import copy
 import itertools
+import json
 import os
-import shutil
 import subprocess
 import tempfile
 import unittest
 from pathlib import Path
 
-from tools.generate_project import _render_params, load_project
+from tools.generate_project import generate_project, load_project
 from tools.prod2u_p4_harness import PRODUCTION_RTL_SOURCES, ROOT, resolve_tool
 
-TB_NAME = "prod2u_p4_alt_config_polarity_tb"
-TB_REL = f"tests/sim/{TB_NAME}.v"
-
-
-def _axis_bools(bit: int) -> list[bool]:
-    return [bool((bit >> i) & 1) for i in range(3)]
+POLARITY_TB = "prod2u_p4_alt_config_polarity_tb"
+STARTUP_TB = "prod2u_p4_alt_config_startup_tb"
+PROJECT_PATH = ROOT / "projects" / "prod2u-door-temp" / "project.json"
 
 
-def _axis_levels(bit: int) -> list[int]:
-    return [(bit >> i) & 1 for i in range(3)]
+def _write_alt_project(
+    directory: Path,
+    *,
+    limit_active_high: list[bool],
+    dir_close_level: list[int],
+    close_limit_is_ls: list[bool],
+) -> Path:
+    """Deep-copy canonical project.json and mutate only the three public arrays."""
+    project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+    project["limits"]["limit_active_high"] = list(limit_active_high)
+    project["motors"]["dir_close_level"] = list(dir_close_level)
+    project["limits"]["close_limit_is_ls"] = list(close_limit_is_ls)
+    # Leave legacy limits.active_level untouched (non-authoritative).
+    path = directory / "project.json"
+    path.write_text(json.dumps(project, indent=2) + "\n", encoding="utf-8")
+    return path
 
 
 class AltConfigRtlMatrixTests(unittest.TestCase):
@@ -38,34 +51,54 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
         cls.vvp = resolve_tool("vvp")
         if not cls.iverilog or not cls.vvp:
             raise unittest.SkipTest("iverilog/vvp unavailable")
-        cls.base_project = load_project(ROOT / "projects" / "prod2u-door-temp" / "project.json")
+        # Confirm canonical load still works (defaults).
+        cls.base_project = load_project(PROJECT_PATH)
 
-    def _run_case(
+    def _run_public_case(
         self,
         name: str,
         *,
+        tb_name: str,
         limit_active_high: list[bool],
         dir_close_level: list[int],
         close_limit_is_ls: list[bool],
+        timeout_s: int = 180,
     ) -> None:
-        alt = copy.deepcopy(self.base_project)
-        alt["limits"]["limit_active_high"] = list(limit_active_high)
-        alt["motors"]["dir_close_level"] = list(dir_close_level)
-        alt["limits"]["close_limit_is_ls"] = list(close_limit_is_ls)
-        params_text = _render_params(alt)
-
         with tempfile.TemporaryDirectory(prefix=f"alt-rtl-{name}-") as tmp:
             tmp_path = Path(tmp)
+            pj = _write_alt_project(
+                tmp_path,
+                limit_active_high=limit_active_high,
+                dir_close_level=dir_close_level,
+                close_limit_is_ls=close_limit_is_ls,
+            )
+            gen_out = tmp_path / "generated-out"
+            # Public API path (not _render_params).
+            generate_project(pj, gen_out)
+
+            # Include layout: generated-out/generated/params.vh must win via
+            # -I <include_root> where include_root/src/generated/... exists.
             include_root = tmp_path / "include"
             gen_dir = include_root / "src" / "generated"
             gen_dir.mkdir(parents=True)
-            (gen_dir / "prod2u_door_temp_params.vh").write_text(params_text, encoding="ascii")
+            params_src = gen_out / "generated" / "prod2u_door_temp_params.vh"
+            self.assertTrue(params_src.is_file(), params_src)
+            (gen_dir / "prod2u_door_temp_params.vh").write_text(
+                params_src.read_text(encoding="ascii"),
+                encoding="ascii",
+            )
 
             work = tmp_path / "work"
             work.mkdir()
-            vvp_out = work / f"{TB_NAME}.vvp"
-            sources = [str(ROOT / rel) for rel in PRODUCTION_RTL_SOURCES]
-            sources.append(str(ROOT / TB_REL))
+            vvp_out = work / f"{tb_name}.vvp"
+            # Omit checked-in params.vh so public-generate include_root is sole
+            # authority (cwd=work → `include "src/generated/..."` hits -I first).
+            sources = [
+                str(ROOT / rel)
+                for rel in PRODUCTION_RTL_SOURCES
+                if Path(rel).name != "prod2u_door_temp_params.vh"
+            ]
+            sources.append(str(ROOT / "tests" / "sim" / f"{tb_name}.v"))
             compile_cmd = [
                 str(self.iverilog),
                 "-g2005-sv",
@@ -74,7 +107,7 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
                 "-I",
                 str(ROOT),
                 "-s",
-                TB_NAME,
+                tb_name,
                 "-o",
                 str(vvp_out),
                 *sources,
@@ -91,7 +124,7 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
             self.assertEqual(
                 compiled.returncode,
                 0,
-                f"{name} iverilog failed:\n{compiled.stdout}\n{compiled.stderr}",
+                f"{name}/{tb_name} iverilog failed:\n{compiled.stdout}\n{compiled.stderr}",
             )
             ran = subprocess.run(
                 [str(self.vvp), str(vvp_out)],
@@ -100,17 +133,24 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE,
                 check=False,
-                timeout=180,
+                timeout=timeout_s,
             )
             self.assertEqual(
                 ran.returncode,
                 0,
-                f"{name} vvp failed:\n{ran.stdout}\n{ran.stderr}",
+                f"{name}/{tb_name} vvp failed:\n{ran.stdout}\n{ran.stderr}",
             )
-            self.assertIn("PASS prod2u_p4_alt_config_polarity_tb", ran.stdout, ran.stdout)
+            self.assertIn(f"PASS {tb_name}", ran.stdout, ran.stdout)
+
+    def _run_polarity(self, name: str, **kwargs) -> None:
+        self._run_public_case(name, tb_name=POLARITY_TB, timeout_s=180, **kwargs)
+
+    def _run_startup(self, name: str, **kwargs) -> None:
+        # 5000+500 with force tick is heavier.
+        self._run_public_case(name, tb_name=STARTUP_TB, timeout_s=600, **kwargs)
 
     def test_default_production_masks_rtl(self) -> None:
-        self._run_case(
+        self._run_polarity(
             "all_default",
             limit_active_high=[True, True, True],
             dir_close_level=[1, 1, 1],
@@ -122,7 +162,7 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
         for ah, dcl, cls in itertools.product((False, True), (0, 1), (False, True)):
             name = f"x_ah{int(ah)}_dcl{dcl}_cls{int(cls)}"
             with self.subTest(name=name):
-                self._run_case(
+                self._run_polarity(
                     name,
                     limit_active_high=[ah, True, True],
                     dir_close_level=[dcl, 1, 1],
@@ -130,7 +170,7 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
                 )
 
     def test_all_active_low(self) -> None:
-        self._run_case(
+        self._run_polarity(
             "all_active_low",
             limit_active_high=[False, False, False],
             dir_close_level=[1, 1, 1],
@@ -138,7 +178,7 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
         )
 
     def test_dir_all_invert(self) -> None:
-        self._run_case(
+        self._run_polarity(
             "dir_all_invert",
             limit_active_high=[True, True, True],
             dir_close_level=[0, 0, 0],
@@ -146,7 +186,7 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
         )
 
     def test_ls_hs_all_swap(self) -> None:
-        self._run_case(
+        self._run_polarity(
             "ls_hs_all_swap",
             limit_active_high=[True, True, True],
             dir_close_level=[1, 1, 1],
@@ -154,7 +194,7 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
         )
 
     def test_all_three_inverted(self) -> None:
-        self._run_case(
+        self._run_polarity(
             "all_three_inverted",
             limit_active_high=[False, False, False],
             dir_close_level=[0, 0, 0],
@@ -163,13 +203,78 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
 
     def test_mixed_xyz_asymmetric(self) -> None:
         """X default / Y active-low+DIR invert / Z LS-HS swap (bit order check)."""
-        self._run_case(
+        self._run_polarity(
             "mixed_xyz",
             limit_active_high=[True, False, True],
             dir_close_level=[1, 0, 1],
             close_limit_is_ls=[True, True, False],
         )
 
+    def test_public_cli_generates_alt_params_for_rtl(self) -> None:
+        """CLI path (not only Python API) must feed the same include layout."""
+        import sys
+
+        with tempfile.TemporaryDirectory(prefix="alt-cli-") as tmp:
+            tmp_path = Path(tmp)
+            pj = _write_alt_project(
+                tmp_path,
+                limit_active_high=[False, True, True],
+                dir_close_level=[1, 1, 1],
+                close_limit_is_ls=[True, True, True],
+            )
+            out = tmp_path / "out"
+            proc = subprocess.run(
+                [sys.executable, str(ROOT / "tools" / "generate_project.py"), str(pj), str(out)],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout)
+            params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
+            self.assertIn("`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b110", params)
+
+    # --- Startup 5000+500 behavioral matrix (public generate path) ---
+
+    def test_startup_default(self) -> None:
+        self._run_startup(
+            "startup_default",
+            limit_active_high=[True, True, True],
+            dir_close_level=[1, 1, 1],
+            close_limit_is_ls=[True, True, True],
+        )
+
+    def test_startup_all_active_low(self) -> None:
+        self._run_startup(
+            "startup_all_active_low",
+            limit_active_high=[False, False, False],
+            dir_close_level=[1, 1, 1],
+            close_limit_is_ls=[True, True, True],
+        )
+
+    def test_startup_ls_hs_swap(self) -> None:
+        self._run_startup(
+            "startup_ls_hs_swap",
+            limit_active_high=[True, True, True],
+            dir_close_level=[1, 1, 1],
+            close_limit_is_ls=[False, False, False],
+        )
+
+    def test_startup_dir_invert(self) -> None:
+        self._run_startup(
+            "startup_dir_invert",
+            limit_active_high=[True, True, True],
+            dir_close_level=[0, 0, 0],
+            close_limit_is_ls=[True, True, True],
+        )
+
+    def test_startup_mixed_xyz(self) -> None:
+        self._run_startup(
+            "startup_mixed_xyz",
+            limit_active_high=[True, False, True],
+            dir_close_level=[1, 0, 1],
+            close_limit_is_ls=[True, True, False],
+        )
+
 
 class AltConfigFormalNormalizeTests(unittest.TestCase):
     """BMC/cover only — never claim infinite prove for alt-config normalize."""
@@ -188,20 +293,17 @@ class AltConfigFormalNormalizeTests(unittest.TestCase):
         env = os.environ.copy()
         oss_bin = str(Path(sby).resolve().parent)
         env["PATH"] = oss_bin + os.pathsep + env.get("PATH", "")
-        # Do NOT export OSS CAD LD_LIBRARY_PATH into the parent shell; sby's
-        # own wrapper sets what it needs. Stripping avoids apt/tool breakage.
         env.pop("LD_LIBRARY_PATH", None)
         env.pop("LD_PRELOAD", None)
         env.pop("QT_PLUGIN_PATH", None)
         for task in ("bmc", "cover"):
             with self.subTest(task=task):
-                # Paths in the .sby are relative to tests/formal.
                 completed = subprocess.run(
                     [sby, "-f", sby_path.name, task],
                     cwd=formal_dir,
                     text=True,
                     stdout=subprocess.PIPE,
-                    stderr=subprocess.PIPE,
+                    stderr=subprocess.STDOUT,
                     check=False,
                     timeout=300,
                     env=env,
@@ -209,11 +311,42 @@ class AltConfigFormalNormalizeTests(unittest.TestCase):
                 self.assertEqual(
                     completed.returncode,
                     0,
-                    f"sby {task} failed:\n{completed.stdout}\n{completed.stderr}",
+                    f"sby {task} failed:\n{completed.stdout}",
                 )
-                # Explicitly reject mislabeling: depth-bounded BMC is not prove.
+                # Honesty: this is BMC/cover, not unbounded proof.
+                self.assertNotIn("UNBOUNDED PROOF", completed.stdout.upper())
                 self.assertNotIn("prove", task)
-                self.assertIn("DONE (PASS", completed.stdout)
+
+    def test_formal_model_structurally_tracks_top(self) -> None:
+        """Helper BMC model must keep the same normalize identifiers as real top.
+
+        Formal evidence type remains BMC/cover only — not unbounded proof and not
+        a substitute for the real-top Icarus matrix above.
+        """
+        top = (ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v").read_text(
+            encoding="utf-8"
+        )
+        formal = (
+            ROOT / "tests" / "formal" / "alt_config_limit_normalize_formal.v"
+        ).read_text(encoding="utf-8")
+        # Top uses localparam names; formal shell uses lowercase ports that
+        # mirror the same normalize / selected_limit / DIR edge equations.
+        for needle in (
+            "selected_limit",
+            "close_limit",
+            "open_limit",
+            "ls_reached",
+            "hs_reached",
+        ):
+            self.assertIn(needle, top)
+            self.assertIn(needle, formal)
+        self.assertIn("LIMIT_ACTIVE_HIGH", top)
+        self.assertIn("limit_active_high", formal)
+        self.assertIn("DIR_CLOSE_LEVEL", top)
+        self.assertIn("dir_close_level", formal)
+        self.assertIn("CLOSE_LIMIT_IS_LS", top)
+        self.assertIn("close_limit_is_ls", formal)
+        self.assertIn("BMC/cover only", formal)
 
 
 if __name__ == "__main__":

+ 162 - 3
tests/unit/test_motor_polarity_config.py

@@ -69,7 +69,7 @@ class MotorPolarityConfigTests(unittest.TestCase):
     def test_render_params_respects_alternate_masks(self):
         project = load_project(PROJECT_PATH)
         alt = copy.deepcopy(project)
-        # Bypass production lock by rendering from a mutated copy directly.
+        # Unit-level renderer check (not feature acceptance).
         alt["limits"]["limit_active_high"] = [False, False, False]
         alt["motors"]["dir_close_level"] = [0, 0, 0]
         alt["limits"]["close_limit_is_ls"] = [False, False, False]
@@ -78,6 +78,49 @@ class MotorPolarityConfigTests(unittest.TestCase):
         self.assertIn("`define P4_DIR_CLOSE_LEVEL_MASK 3'b000", params)
         self.assertIn("`define P4_CLOSE_LIMIT_IS_LS_MASK 3'b000", params)
 
+    def test_public_load_generate_accepts_mixed_axis_config(self):
+        """Feature acceptance: public load_project/generate_project path."""
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        # X default, Y active-low + DIR invert, Z LS/HS swap.
+        # Leave legacy limits.active_level untouched (non-authoritative).
+        project["limits"]["limit_active_high"] = [True, False, True]
+        project["motors"]["dir_close_level"] = [1, 0, 1]
+        project["limits"]["close_limit_is_ls"] = [True, True, False]
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            pj = root / "project.json"
+            out = root / "generated-out"
+            pj.write_text(json.dumps(project, indent=2), encoding="utf-8")
+            loaded = load_project(pj)
+            self.assertEqual(loaded["limits"]["limit_active_high"], [True, False, True])
+            generate_project(pj, out)
+            params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
+            self.assertEqual(_mask_define(params, "P4_LIMIT_ACTIVE_HIGH_MASK"), "3'b101")
+            self.assertEqual(_mask_define(params, "P4_DIR_CLOSE_LEVEL_MASK"), "3'b101")
+            self.assertEqual(_mask_define(params, "P4_CLOSE_LIMIT_IS_LS_MASK"), "3'b011")
+
+    def test_public_cli_accepts_x_active_low(self):
+        import subprocess
+        import sys
+
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        project["limits"]["limit_active_high"] = [False, True, True]
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            pj = root / "project.json"
+            out = root / "out"
+            pj.write_text(json.dumps(project, indent=2), encoding="utf-8")
+            script = ROOT / "tools" / "generate_project.py"
+            proc = subprocess.run(
+                [sys.executable, str(script), str(pj), str(out)],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout)
+            params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
+            self.assertEqual(_mask_define(params, "P4_LIMIT_ACTIVE_HIGH_MASK"), "3'b110")
+
     def test_mixed_axis_mask_order(self):
         project = load_project(PROJECT_PATH)
         alt = copy.deepcopy(project)
@@ -90,6 +133,42 @@ class MotorPolarityConfigTests(unittest.TestCase):
         self.assertIn("`define P4_DIR_CLOSE_LEVEL_MASK 3'b101", params)
         self.assertIn("`define P4_CLOSE_LIMIT_IS_LS_MASK 3'b011", params)
 
+    def test_canonical_fresh_generation_byte_identical(self):
+        """Default project regenerate must match tracked production outputs."""
+        tracked = ROOT / "src" / "generated"
+        with tempfile.TemporaryDirectory() as directory:
+            out = Path(directory) / "out"
+            generate_project(PROJECT_PATH, out)
+            generated = out / "generated"
+            for name in (
+                "prod2u_door_temp_params.vh",
+                "host-contract.json",
+                "project-summary.json",
+                "td-source-manifest.json",
+                "prod2u_door_temp.adc",
+                "golden-vectors.json",
+            ):
+                left = (generated / name).read_bytes()
+                right = (tracked / name).read_bytes()
+                self.assertEqual(left, right, f"byte drift in {name}")
+
+    def test_public_path_leaves_legacy_active_level_untouched(self):
+        """Changing per-axis arrays must not require syncing limits.active_level."""
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        project["limits"]["limit_active_high"] = [False, False, False]
+        # Leave legacy active_level as production "high" (non-authoritative).
+        self.assertEqual(project["limits"]["active_level"], "high")
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            pj = root / "project.json"
+            out = root / "out"
+            pj.write_text(json.dumps(project, indent=2), encoding="utf-8")
+            generate_project(pj, out)
+            params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(
+                encoding="ascii"
+            )
+            self.assertEqual(_mask_define(params, "P4_LIMIT_ACTIVE_HIGH_MASK"), "3'b000")
+
     def test_rejects_wrong_length_dir_close_level(self):
         project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
         project["motors"]["dir_close_level"] = [1, 1]
@@ -108,6 +187,85 @@ class MotorPolarityConfigTests(unittest.TestCase):
             with self.assertRaises(Exception):
                 load_project(bad)
 
+    def test_rejects_bool_dir_close_level(self):
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        project["motors"]["dir_close_level"] = [True, True, True]
+        with tempfile.TemporaryDirectory() as directory:
+            bad = Path(directory) / "project.json"
+            bad.write_text(json.dumps(project), encoding="utf-8")
+            with self.assertRaises(Exception):
+                load_project(bad)
+
+    def test_rejects_out_of_range_dir_close_level(self):
+        for bad_val in (2, -1):
+            with self.subTest(val=bad_val):
+                project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+                project["motors"]["dir_close_level"] = [bad_val, 1, 1]
+                with tempfile.TemporaryDirectory() as directory:
+                    bad = Path(directory) / "project.json"
+                    bad.write_text(json.dumps(project), encoding="utf-8")
+                    with self.assertRaises(Exception):
+                        load_project(bad)
+
+    def test_rejects_null_and_string_polarity_fields(self):
+        cases = (
+            ("limits", "limit_active_high", [None, True, True]),
+            ("limits", "limit_active_high", ["false", True, True]),
+            ("limits", "close_limit_is_ls", [True, "true", True]),
+            ("limits", "close_limit_is_ls", ["true", True, True]),
+            ("motors", "dir_close_level", [1, "1", 1]),
+            ("motors", "dir_close_level", [1, None, 1]),
+        )
+        for section, key, value in cases:
+            with self.subTest(field=f"{section}.{key}", value=value):
+                project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+                project[section][key] = value
+                with tempfile.TemporaryDirectory() as directory:
+                    bad = Path(directory) / "project.json"
+                    bad.write_text(json.dumps(project), encoding="utf-8")
+                    with self.assertRaises(Exception):
+                        load_project(bad)
+
+    def test_rejects_missing_polarity_fields(self):
+        for section, key in (
+            ("limits", "limit_active_high"),
+            ("limits", "close_limit_is_ls"),
+            ("motors", "dir_close_level"),
+        ):
+            with self.subTest(field=f"{section}.{key}"):
+                project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+                del project[section][key]
+                with tempfile.TemporaryDirectory() as directory:
+                    bad = Path(directory) / "project.json"
+                    bad.write_text(json.dumps(project), encoding="utf-8")
+                    with self.assertRaises(Exception):
+                        load_project(bad)
+
+    def test_active_level_need_not_match_mixed_arrays(self):
+        """Legacy active_level must not block mixed-axis public generate."""
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        project["limits"]["limit_active_high"] = [True, False, True]
+        project["limits"]["active_level"] = "high"  # not equal to all(...)
+        with tempfile.TemporaryDirectory() as directory:
+            root = Path(directory)
+            pj = root / "project.json"
+            out = root / "out"
+            pj.write_text(json.dumps(project, indent=2), encoding="utf-8")
+            generate_project(pj, out)
+            params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(
+                encoding="ascii"
+            )
+            self.assertEqual(_mask_define(params, "P4_LIMIT_ACTIVE_HIGH_MASK"), "3'b101")
+
+    def test_rejects_wrong_length_close_limit_is_ls(self):
+        project = json.loads(PROJECT_PATH.read_text(encoding="utf-8"))
+        project["limits"]["close_limit_is_ls"] = [True, True, True, True]
+        with tempfile.TemporaryDirectory() as directory:
+            bad = Path(directory) / "project.json"
+            bad.write_text(json.dumps(project), encoding="utf-8")
+            with self.assertRaises(Exception):
+                load_project(bad)
+
 
 def _mask_define(params: str, name: str) -> str:
     needle = f"`define {name} "
@@ -120,8 +278,9 @@ def _mask_define(params: str, name: str) -> str:
 class AlternateConfigMaskMatrixTests(unittest.TestCase):
     """Thin generator matrix: prove representative alt configs emit correct masks.
 
-    Production load_project locks defaults; these cases mutate a deep copy and
-    call _render_params only (no second firmware / no project.json rewrite).
+    Unit-level: mutate a deep copy and call _render_params. Feature acceptance
+    for the public project.json → load/generate/CLI path lives in
+    MotorPolarityConfigTests.test_public_*.
     """
 
     # name -> (limit_active_high, dir_close_level, close_limit_is_ls,

+ 79 - 0
tests/unit/test_release_set_provenance.py

@@ -47,6 +47,85 @@ class ReleaseSetProvenanceTests(unittest.TestCase):
         self.assertFalse(pointer["raw_brd_pdf_dsn_in_default_compact"])
         self.assertEqual(len(pointer["content_fingerprint"]), 64)
         self.assertEqual(len(pointer["brd_sha256"]), 64)
+        # Must point at raw reference ZIP identity, not inventory.
+        self.assertEqual(pointer["filename"], pkg_prov.REFERENCE_PACKAGE_FILENAME)
+        self.assertEqual(pointer["sha256"], pkg_prov.REFERENCE_PACKAGE_SHA256)
+        self.assertEqual(pointer["size"], pkg_prov.REFERENCE_PACKAGE_SIZE)
+        self.assertEqual(pointer["brd_sha256"], pkg_prov.REFERENCE_CANONICAL_BRD_SHA256)
+        self.assertIn("derived_board_viewer", pointer)
+        self.assertNotEqual(pointer["filename"], "REFERENCE-INVENTORY.json")
+
+    def test_reference_fingerprint_excludes_generated_at(self) -> None:
+        fp = pkg_prov.reference_set_fingerprint(ROOT)
+        dumped = json.dumps(fp["parts"], sort_keys=True)
+        self.assertNotIn("generated_at", dumped)
+        self.assertEqual(fp["parts"]["reference_package_sha256"], pkg_prov.REFERENCE_PACKAGE_SHA256)
+
+    def test_relations_consistency_negatives(self) -> None:
+        # unchanged=false + empty paths + commit_compare → FAIL
+        bad_empty = pkg_prov.build_source_closure_relations(
+            old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
+            artifact_commit=pkg_prov.ARTIFACT_DEFAULT,
+            delivery_commit="a" * 40,
+            old_to_artifact_unchanged=False,
+            artifact_to_delivery_unchanged=True,
+            old_to_artifact_changed_paths=[],
+            artifact_to_delivery_changed_paths=[],
+            comparison_mode="commit_compare",
+        )
+        check = pkg_prov.validate_source_closure_relations(bad_empty)
+        self.assertEqual(check["status"], "fail")
+        self.assertTrue(
+            any("unchanged_false_empty_paths" in f for f in check["failures"]),
+            check["failures"],
+        )
+
+        # unchanged=true + non-empty paths → FAIL
+        bad_true = pkg_prov.build_source_closure_relations(
+            old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
+            artifact_commit=pkg_prov.ARTIFACT_DEFAULT,
+            delivery_commit="a" * 40,
+            old_to_artifact_unchanged=True,
+            artifact_to_delivery_unchanged=True,
+            old_to_artifact_changed_paths=["projects/prod2u-door-temp/project.json"],
+            artifact_to_delivery_changed_paths=[],
+            comparison_mode="commit_compare",
+        )
+        check2 = pkg_prov.validate_source_closure_relations(bad_true)
+        self.assertEqual(check2["status"], "fail")
+        self.assertTrue(
+            any("unchanged_true_with_changed_paths" in f for f in check2["failures"]),
+            check2["failures"],
+        )
+
+        # ARTIFACT identity mismatch across edges → FAIL
+        mismatch = pkg_prov.build_source_closure_relations(
+            old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
+            artifact_commit=pkg_prov.ARTIFACT_DEFAULT,
+            delivery_commit="a" * 40,
+            old_to_artifact_unchanged=False,
+            artifact_to_delivery_unchanged=True,
+            old_to_artifact_changed_paths=["projects/prod2u-door-temp/project.json"],
+            artifact_to_delivery_changed_paths=[],
+            comparison_mode="commit_compare",
+        )
+        mismatch["artifact_to_delivery"]["from_commit"] = "b" * 40
+        check3 = pkg_prov.validate_source_closure_relations(mismatch)
+        self.assertEqual(check3["status"], "fail")
+        self.assertIn("artifact_identity_mismatch_across_edges", check3["failures"])
+
+        # Valid dual edge → PASS
+        good = pkg_prov.build_source_closure_relations(
+            old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
+            artifact_commit=pkg_prov.ARTIFACT_DEFAULT,
+            delivery_commit="a" * 40,
+            old_to_artifact_unchanged=False,
+            artifact_to_delivery_unchanged=True,
+            old_to_artifact_changed_paths=["projects/prod2u-door-temp/project.json"],
+            artifact_to_delivery_changed_paths=[],
+            comparison_mode="commit_compare",
+        )
+        self.assertEqual(pkg_prov.validate_source_closure_relations(good)["status"], "pass")
 
     def test_release_set_id_stable_and_independent_of_zip_sha(self) -> None:
         kwargs = dict(

+ 25 - 0
tools/board-viewer/board_viewer/detached.py

@@ -45,7 +45,32 @@ SVG_NAMES: tuple[str, ...] = (
     "board-mask-edge.svg",
 )
 CANONICAL_GENERATED_DIR = "tools/board-viewer/generated"
+# Compact packages relocate the six derived assets under evidence/.
+COMPACT_EVIDENCE_GENERATED_DIRS = (
+    "evidence/board-viewer",
+    "evidence/board-viewer/generated",
+    "CPLD/evidence/board-viewer",
+    "CPLD/evidence/board-viewer/generated",
+)
 EVIDENCE_CLASS = "derived_evidence"
+
+
+def resolve_generated_dir(root: Path | str) -> Path:
+    """Resolve board-viewer derived assets for live repo or compact extract."""
+    base = Path(root)
+    candidates = [
+        base / CANONICAL_GENERATED_DIR,
+        *[base / rel for rel in COMPACT_EVIDENCE_GENERATED_DIRS],
+        # Some extracts nest under source/
+        base / "source" / CANONICAL_GENERATED_DIR,
+        base / "CPLD" / "source" / CANONICAL_GENERATED_DIR,
+    ]
+    for candidate in candidates:
+        if (candidate / "board-data.json").is_file() and (
+            candidate / "build-info.json"
+        ).is_file():
+            return candidate
+    return base / CANONICAL_GENERATED_DIR
 AUTHORITY = "analysis_evidence_not_source_closure"
 REGENERATION_STATUS = "not_packaged_by_policy"
 VIEWBOX_TOLERANCE_MM = 0.1

+ 11 - 4
tools/board-viewer/validate_detached_derived.py

@@ -16,17 +16,23 @@ from board_viewer.detached import (
     describe_derived_assets,
     packaging_policy,
     report_to_dict,
+    resolve_generated_dir,
     validate_detached_derived,
 )
 
 
 ROOT = Path(__file__).resolve().parents[2]
-DEFAULT_GENERATED = ROOT / "tools" / "board-viewer" / "generated"
+DEFAULT_GENERATED = resolve_generated_dir(ROOT)
 
 
 def main(argv: list[str] | None = None) -> int:
     parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("--generated", type=Path, default=DEFAULT_GENERATED)
+    parser.add_argument(
+        "--generated",
+        type=Path,
+        default=None,
+        help="Derived asset directory (auto-resolves live or compact evidence path)",
+    )
     parser.add_argument("--repository-root", type=Path, default=ROOT)
     parser.add_argument(
         "--require-brd",
@@ -46,17 +52,18 @@ def main(argv: list[str] | None = None) -> int:
         help="Print derived-asset provenance rows and exit based on presence",
     )
     args = parser.parse_args(argv)
+    generated = args.generated or resolve_generated_dir(args.repository_root)
 
     if args.print_policy:
         print(json.dumps(packaging_policy(), indent=2, ensure_ascii=False))
         return 0
     if args.print_asset_rows:
-        rows = describe_derived_assets(args.generated)
+        rows = describe_derived_assets(generated)
         print(json.dumps(rows, indent=2, ensure_ascii=False))
         return 0 if all(row.get("exists") for row in rows) else 1
 
     report = validate_detached_derived(
-        args.generated,
+        generated,
         repository_root=args.repository_root,
         require_brd_present=args.require_brd,
     )

+ 5 - 0
tools/build_firmware_package.py

@@ -536,6 +536,11 @@ def build_firmware_package(
         artifact_to_delivery_changed_paths=list(comparison.get("production_changed_paths") or []),
         comparison_mode=str(comparison.get("mode") or "commit_compare"),
     )
+    rel_check = pkg_prov.validate_source_closure_relations(relations)
+    if rel_check["status"] != "pass":
+        raise PackagingError(
+            f"source-closure relations inconsistent: {rel_check['failures']}"
+        )
     reference_pointer = pkg_prov.build_reference_pointer(
         artifact_commit=artifact_commit,
         delivery_commit=final_dev_commit,

+ 9 - 8
tools/generate_project.py

@@ -243,7 +243,7 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
     for index, level in enumerate(dir_close_level):
         _require(isinstance(level, int) and not isinstance(level, bool) and level in (0, 1),
                  f"motors.dir_close_level[{index}] must be 0 or 1")
-    _require(dir_close_level == [1, 1, 1], "production dir_close_level must be [1,1,1]")
+    # Per-axis dir_close_level is the sole authority; mixed 0/1 configs are allowed.
     mapping = _object(motors["mapping"], "motors.mapping")
     _require(motors["count"] == 3 and motors["order"] == ["x", "y", "z"], "production motor count/order must be x,y,z")
     _keys(mapping, {"x", "y", "z"}, "motors.mapping")
@@ -274,20 +274,21 @@ def _validate_project(payload: Mapping[str, Any]) -> None:
         "limits",
     )
     _require(limits["limit_count"] == len(limits["channels"]) == 6, "limit count/list mismatch")
-    _require(limits["active_level"] == "high" and limits["functional_use"] is True, "limit policy mismatch")
+    # limits.active_level is legacy / deprecated / non-authoritative. Accept the
+    # historical string enum only; do not bind it to per-axis arrays or RTL masks.
+    _require(
+        limits["active_level"] in ("high", "low") and limits["functional_use"] is True,
+        "limits.active_level must be legacy enum high|low and functional_use true",
+    )
     _require(limits["runtime_use"] is True, "runtime limit use must be true")
     limit_active_high = _list(limits["limit_active_high"], "limits.limit_active_high", length=motors["count"])
     for index, active_high in enumerate(limit_active_high):
         _require(isinstance(active_high, bool), f"limits.limit_active_high[{index}] must be a boolean")
-    _require(limit_active_high == [True, True, True], "production limit_active_high must be [true,true,true]")
     close_limit_is_ls = _list(limits["close_limit_is_ls"], "limits.close_limit_is_ls", length=motors["count"])
     for index, close_is_ls in enumerate(close_limit_is_ls):
         _require(isinstance(close_is_ls, bool), f"limits.close_limit_is_ls[{index}] must be a boolean")
-    _require(close_limit_is_ls == [True, True, True], "production close_limit_is_ls must be [true,true,true]")
-    _require(
-        all(limit_active_high) == (limits["active_level"] == "high"),
-        "limits.active_level must match limit_active_high aggregate",
-    )
+    # Per-axis limit_active_high / close_limit_is_ls / dir_close_level alone decide
+    # generated masks. Mixed-axis configs must not force active_level sync.
     startup = _object(limits["startup"], "limits.startup")
     _keys(
         startup,

+ 5 - 0
tools/package_agent_handoff.py

@@ -336,12 +336,15 @@ def common_file_exclusion_reason(relative: str) -> str | None:
         ".bid",
         ".data",
         ".db",
+        ".sqlite",
         ".timing",
         ".rpt",
         ".area",
         ".qor",
         ".vvp",
     }
+    if name in {"status.sqlite", "logfile.txt"} and "/tests/formal/" in f"/{lower}/":
+        return "formal_workdir_artifact"
     if suffix in generated_binary_suffixes:
         return "generated_binary_artifact"
     if suffix == ".exe":
@@ -379,6 +382,8 @@ def exclusion_reason(relative: str, *, is_dir: bool, context: ScanContext) -> st
         ".omo": "agent_session_runtime",
         ".hypothesis": "hypothesis_cache",
         ".pytest_cache": "pytest_cache",
+        ".chatgpt-handoff": "chatgpt_handoff_runtime_not_in_compact",
+        ".playwright-upload-cache": "playwright_upload_cache",
         "workspace": "deprecated_workspace",
         "_archive": "deprecated_archive",
         "unused": "unused_workspace_area",

+ 179 - 45
tools/package_provenance.py

@@ -21,6 +21,17 @@ ROOT = Path(__file__).resolve().parents[1]
 OLD_BASELINE_DEFAULT = "0de9f93988344e3c11931482902196b02ac7a713"
 ARTIFACT_DEFAULT = "f23d6d4c57959071cd3886ea5503fbe903aee547"
 
+# Standalone raw reference package identity (receipt-backed; ZIP not in default compact).
+REFERENCE_PACKAGE_FILENAME = "prod2u-reference-v1_2-3axis-20260805T171312Z.zip"
+REFERENCE_PACKAGE_SHA256 = (
+    "b8a1dd092f453b1b25a4faf4734e8c5a404bfa38752f19fb67cf842d228ec2b1"
+)
+REFERENCE_PACKAGE_SIZE = 4446292
+REFERENCE_CANONICAL_BRD_SHA256 = (
+    "269b5bab2f2e1215b9392079a003badc34238ae3cbe8e5094c9a11bba8b84ebb"
+)
+REFERENCE_RECEIPT_REL = "receipts/reference-package-20260805T171312Z.json"
+
 
 def _sha256_bytes(data: bytes) -> str:
     return hashlib.sha256(data).hexdigest()
@@ -47,8 +58,8 @@ def build_source_closure_relations(
     old_baseline_commit: str,
     artifact_commit: str,
     delivery_commit: str,
-    old_to_artifact_unchanged: bool,
-    artifact_to_delivery_unchanged: bool,
+    old_to_artifact_unchanged: bool | None,
+    artifact_to_delivery_unchanged: bool | None,
     old_to_artifact_changed_paths: list[str] | None = None,
     artifact_to_delivery_changed_paths: list[str] | None = None,
     comparison_mode: str = "commit_compare",
@@ -65,7 +76,7 @@ def build_source_closure_relations(
             "to_commit": artifact_commit,
             "from_short": _short(old_baseline_commit),
             "to_short": _short(artifact_commit),
-            "unchanged": bool(old_to_artifact_unchanged),
+            "unchanged": old_to_artifact_unchanged,
             "production_changed_paths": old_paths,
         },
         "artifact_to_delivery": {
@@ -73,38 +84,152 @@ def build_source_closure_relations(
             "to_commit": delivery_commit,
             "from_short": _short(artifact_commit),
             "to_short": _short(delivery_commit),
-            "unchanged": bool(artifact_to_delivery_unchanged),
+            "unchanged": artifact_to_delivery_unchanged,
             "production_changed_paths": del_paths,
         },
         # Human-readable aliases (same authority, not a second truth).
-        "OLD_TO_NEW_SOURCE_CLOSURE_UNCHANGED": bool(old_to_artifact_unchanged),
-        "NEW_ARTIFACT_TO_DELIVERY_SOURCE_CLOSURE_UNCHANGED": bool(artifact_to_delivery_unchanged),
+        "OLD_TO_NEW_SOURCE_CLOSURE_UNCHANGED": old_to_artifact_unchanged,
+        "NEW_ARTIFACT_TO_DELIVERY_SOURCE_CLOSURE_UNCHANGED": artifact_to_delivery_unchanged,
     }
     return payload
 
 
-def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
-    """Stable reference-set fingerprint from inventory + board-viewer build-info."""
+def validate_source_closure_relations(relations: dict[str, Any] | Any) -> dict[str, Any]:
+    """Fail-closed consistency checks for dual-edge relations.
+
+    Negatives required by contract:
+    - unchanged=false + empty changed_paths + mode=commit_compare → FAIL
+    - unchanged=true + non-empty changed_paths → FAIL
+    - comparison_mode=commit_compare with unknown booleans → FAIL
+    """
+    failures: list[str] = []
+    if not isinstance(relations, dict):
+        return {"status": "fail", "failures": ["relations_not_object"]}
+
+    mode = relations.get("comparison_mode")
+    if mode not in {"commit_compare", "snapshot_hash", "comparison_unavailable"}:
+        failures.append(f"bad_comparison_mode:{mode}")
+
+    for edge_key in ("old_baseline_to_artifact", "artifact_to_delivery"):
+        edge = relations.get(edge_key) or {}
+        if not isinstance(edge, dict):
+            failures.append(f"{edge_key}_not_object")
+            continue
+        unchanged = edge.get("unchanged")
+        paths = edge.get("production_changed_paths") or []
+        if not isinstance(paths, list):
+            failures.append(f"{edge_key}_paths_not_list")
+            paths = []
+        if mode == "commit_compare":
+            if unchanged is True and paths:
+                failures.append(f"{edge_key}_unchanged_true_with_changed_paths")
+            if unchanged is False and not paths:
+                failures.append(f"{edge_key}_unchanged_false_empty_paths")
+            if unchanged not in (True, False):
+                failures.append(f"{edge_key}_unchanged_not_bool_under_commit_compare")
+        if mode == "comparison_unavailable":
+            if unchanged is not None:
+                failures.append(f"{edge_key}_guessed_bool_when_unavailable")
+
+    # Identity presence
+    old_edge = relations.get("old_baseline_to_artifact") or {}
+    art_edge = relations.get("artifact_to_delivery") or {}
+    if not old_edge.get("from_commit") or not old_edge.get("to_commit"):
+        failures.append("old_edge_missing_commits")
+    if not art_edge.get("from_commit") or not art_edge.get("to_commit"):
+        failures.append("art_edge_missing_commits")
+    if (
+        old_edge.get("to_commit")
+        and art_edge.get("from_commit")
+        and old_edge.get("to_commit") != art_edge.get("from_commit")
+    ):
+        failures.append("artifact_identity_mismatch_across_edges")
+
+    return {"status": "fail" if failures else "pass", "failures": failures}
+
+
+def load_reference_package_identity(repo_root: Path | None = None) -> dict[str, Any]:
+    """Raw reference package identity from canonical receipt (stable; no timestamps)."""
     root = repo_root or ROOT
-    inventory_path = root / "docs" / "REFERENCE-INVENTORY.json"
-    build_info_path = root / "tools" / "board-viewer" / "generated" / "build-info.json"
-    brd_rel = (
-        "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/"
-        "FCB_FPGA+MCU_V1.2_20260717.brd"
+    receipt_path = root / REFERENCE_RECEIPT_REL
+    identity = {
+        "filename": REFERENCE_PACKAGE_FILENAME,
+        "size": REFERENCE_PACKAGE_SIZE,
+        "sha256": REFERENCE_PACKAGE_SHA256,
+        "canonical_brd_sha256": REFERENCE_CANONICAL_BRD_SHA256,
+        "receipt_path": REFERENCE_RECEIPT_REL,
+    }
+    if receipt_path.is_file():
+        receipt = _read_json(receipt_path)
+        zip_sha = receipt.get("zip_sha256")
+        zip_bytes = receipt.get("zip_bytes")
+        brd_sha = receipt.get("brd_sha256")
+        pkg_name = receipt.get("package_name")
+        if zip_sha and zip_sha != REFERENCE_PACKAGE_SHA256:
+            raise ValueError(
+                f"reference receipt zip sha mismatch: {zip_sha} != {REFERENCE_PACKAGE_SHA256}"
+            )
+        if brd_sha and brd_sha != REFERENCE_CANONICAL_BRD_SHA256:
+            raise ValueError(
+                f"reference receipt BRD sha mismatch: {brd_sha} != {REFERENCE_CANONICAL_BRD_SHA256}"
+            )
+        if zip_bytes and int(zip_bytes) != REFERENCE_PACKAGE_SIZE:
+            raise ValueError(
+                f"reference receipt size mismatch: {zip_bytes} != {REFERENCE_PACKAGE_SIZE}"
+            )
+        if pkg_name and f"{pkg_name}.zip" != REFERENCE_PACKAGE_FILENAME:
+            # Allow receipt package_name without .zip suffix.
+            if pkg_name != REFERENCE_PACKAGE_FILENAME.removesuffix(".zip"):
+                raise ValueError(f"reference receipt name mismatch: {pkg_name}")
+        identity["receipt_status"] = receipt.get("status")
+    return identity
+
+
+def derived_board_viewer_identity(repo_root: Path | None = None) -> dict[str, Any]:
+    """Derived board-viewer evidence identity (separate from raw reference package)."""
+    root = repo_root or ROOT
+    generated = root / "tools" / "board-viewer" / "generated"
+    names = (
+        "board-data.json",
+        "build-info.json",
+        "import-report.json",
+        "board-copper.svg",
+        "board-silkscreen.svg",
+        "board-mask-edge.svg",
     )
-    brd_path = root / brd_rel
+    assets: dict[str, str | None] = {}
+    for name in names:
+        path = generated / name
+        assets[name] = _sha256_file(path) if path.is_file() else None
+    build_info = _read_json(generated / "build-info.json") if (generated / "build-info.json").is_file() else {}
+    input_brd = None
+    sources = build_info.get("sources") if isinstance(build_info, dict) else None
+    if isinstance(sources, dict):
+        brd = sources.get("brd")
+        if isinstance(brd, dict):
+            input_brd = brd.get("sha256")
+    # Stable fingerprint MUST NOT include generated_at or absolute paths.
+    parts = {
+        "assets": assets,
+        "board_viewer_generator_version": build_info.get("generator_version"),
+        "input_brd_sha256": input_brd,
+    }
+    fp = _sha256_bytes(json.dumps(parts, sort_keys=True, separators=(",", ":")).encode("utf-8"))
+    return {
+        "schema": "prod2u-derived-board-viewer-identity-v1",
+        "sha256": fp,
+        "parts": parts,
+        # Informational only — not mixed into raw reference fingerprint.
+        "generated_at_informational": build_info.get("generated_at"),
+    }
 
-    inventory = _read_json(inventory_path) if inventory_path.is_file() else {}
-    build_info = _read_json(build_info_path) if build_info_path.is_file() else {}
-    expected_brd = (
-        inventory.get("evidence_boundaries", {}).get("expected_brd_sha256")
-        if isinstance(inventory, dict)
-        else None
-    )
-    brd_sha = _sha256_file(brd_path) if brd_path.is_file() else None
-    if expected_brd and brd_sha and expected_brd != brd_sha:
-        raise ValueError(f"BRD sha mismatch: expected {expected_brd} got {brd_sha}")
 
+def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
+    """Stable raw reference-set fingerprint (no generated_at / temp paths)."""
+    root = repo_root or ROOT
+    inventory_path = root / "docs" / "REFERENCE-INVENTORY.json"
+    raw = load_reference_package_identity(root)
+    inventory = _read_json(inventory_path) if inventory_path.is_file() else {}
     schematic_identity = {
         "v1_2_schematic_pdf_status": inventory.get("evidence_boundaries", {})
         .get("v1_2_schematic_pdf", {})
@@ -114,12 +239,12 @@ def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
         ),
     }
     content_parts = {
-        "inventory_sha256": _sha256_file(inventory_path) if inventory_path.is_file() else None,
-        "build_info_sha256": _sha256_file(build_info_path) if build_info_path.is_file() else None,
-        "brd_sha256": brd_sha or expected_brd,
+        "reference_package_filename": raw["filename"],
+        "reference_package_sha256": raw["sha256"],
+        "reference_package_size": raw["size"],
+        "canonical_brd_sha256": raw["canonical_brd_sha256"],
         "schematic_identity": schematic_identity,
-        "board_viewer_generator_version": build_info.get("generator_version"),
-        "board_viewer_generated_at": build_info.get("generated_at"),
+        "inventory_sha256": _sha256_file(inventory_path) if inventory_path.is_file() else None,
     }
     fp = _sha256_bytes(
         json.dumps(content_parts, sort_keys=True, separators=(",", ":")).encode("utf-8")
@@ -128,7 +253,10 @@ def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
         "schema": "prod2u-reference-set-fingerprint-v1",
         "sha256": fp,
         "parts": content_parts,
-        "canonical_brd_path": brd_rel,
+        "canonical_brd_path": (
+            "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/"
+            "FCB_FPGA+MCU_V1.2_20260717.brd"
+        ),
         "raw_brd_pdf_dsn_in_default_compact": False,
     }
 
@@ -144,27 +272,33 @@ def build_reference_pointer(
 ) -> dict[str, Any]:
     """Build REFERENCE-POINTER.json (full for review-compact; summary for firmware)."""
     root = repo_root or ROOT
+    raw = load_reference_package_identity(root)
     ref_fp = reference_set_fingerprint(root)
-    inventory_path = root / "docs" / "REFERENCE-INVENTORY.json"
-    inventory_name = inventory_path.name if inventory_path.is_file() else "REFERENCE-INVENTORY.json"
-    inventory_sha = (
-        _sha256_file(inventory_path) if inventory_path.is_file() else ref_fp["parts"].get("inventory_sha256")
-    )
+    derived = derived_board_viewer_identity(root)
     pointer = {
         "schema": "prod2u-reference-pointer-v1",
         "generated_at_utc": datetime.now(timezone.utc).isoformat(),
         "reference_changed": bool(reference_changed),
         "reference_reused": bool(reference_reused),
-        "filename": inventory_name,
-        "sha256": inventory_sha,
+        # Raw reference package identity (NOT inventory filename/hash).
+        "filename": raw["filename"],
+        "size": raw["size"],
+        "sha256": raw["sha256"],
         "content_fingerprint": ref_fp["sha256"],
-        "brd_sha256": ref_fp["parts"].get("brd_sha256"),
+        "brd_sha256": raw["canonical_brd_sha256"],
         "schematic_identity": ref_fp["parts"].get("schematic_identity"),
-        "board_viewer_build_info": {
-            "path": "tools/board-viewer/generated/build-info.json",
-            "sha256": ref_fp["parts"].get("build_info_sha256"),
-            "generator_version": ref_fp["parts"].get("board_viewer_generator_version"),
-            "generated_at": ref_fp["parts"].get("board_viewer_generated_at"),
+        "raw_reference_package": {
+            "filename": raw["filename"],
+            "size": raw["size"],
+            "sha256": raw["sha256"],
+            "canonical_brd_sha256": raw["canonical_brd_sha256"],
+            "receipt_path": raw.get("receipt_path"),
+        },
+        "derived_board_viewer": {
+            "fingerprint_sha256": derived["sha256"],
+            "assets": derived["parts"]["assets"],
+            "board_viewer_generator_version": derived["parts"]["board_viewer_generator_version"],
+            "input_brd_sha256": derived["parts"]["input_brd_sha256"],
         },
         "artifact_source_commit": artifact_commit,
         "delivery_commit": delivery_commit,
@@ -175,6 +309,8 @@ def build_reference_pointer(
             "schema": pointer["schema"],
             "reference_changed": pointer["reference_changed"],
             "reference_reused": pointer["reference_reused"],
+            "filename": pointer["filename"],
+            "sha256": pointer["sha256"],
             "content_fingerprint": pointer["content_fingerprint"],
             "brd_sha256": pointer["brd_sha256"],
             "artifact_source_commit": artifact_commit,
@@ -244,7 +380,6 @@ def build_release_set_document(
     hardware_validation: str = "not_run",
 ) -> dict[str, Any]:
     """External release-set JSON written AFTER both packages exist."""
-    # Fail closed on accidental cyclic fields.
     for name, sha in (
         (firmware_filename, firmware_sha256),
         (review_compact_filename, review_compact_sha256),
@@ -352,7 +487,6 @@ def validate_release_set_selftest(
                 if sib_name != expected_sibling_filename_in_compact:
                     failures.append("compact_sibling_filename_mismatch")
 
-    # Tamper vectors the caller can inject by mutating document before call.
     identity = document.get("identity") or {}
     if not identity.get("bitstream_sha256"):
         failures.append("missing_bitstream_identity")